Android - Losing incoming (hi-speed) USB data Android - Losing incoming (hi-speed) USB data android android

Android - Losing incoming (hi-speed) USB data


I've encountered this kind of problem before. Forget using Java, in the background it's doing untold number of things that prevent realtime access, e.g. garbage collection, thread processing. Also forget using event-driven programming, even in high priority threads, it can take a long time before the event is processed and you can lose data.

The way I fixed it was to write "unfriendly" code! Used C or assembly, and wrote a polling function like this (in C-like pseudo-code):

#define PAUSE 2 /* Check twice as often as the packet rate */#define TIMEOUT (500 / PAUSE) /* Abort if half a second of no data *//* Provide handle, data buffer and size of buffer   Returns TRUE if full buffer read, FALSE if not, data unread in size*/ BOOL real_time_read(HANDLE handle, BYTE *data, size_t *size){    BOOL result = FALSE;    int timeout = TIMEOUT;    set_thread_priority(REALTIME);    while (is_handle_valid(handle))    {        if (is_data_pending(handle))        {            size_t count = get_data(handle, data, size);            data += count;            *size -= count;            if (!*size)            {                result = TRUE;                break;            }        }        else if (!--timeout)            break;        /* Give a tiny time slice to other processes */        usleep(PAUSE);    }    return result;}

You mentioned you tried C, so it should be straightforward to convert this to real functions. Avoid the temptation to use convenience functions, you want as close to the metal as possible. E.g. if an O/S function Read() in turn calls read() which in turn calls _read(), you want to be using _read().The device will be noticeably slower while this is going on, but that's the tradeoff of real-time access.