felHR85 / UsbSerial

Usb serial controller for Android
MIT License
1.78k stars 582 forks source link

Strange issue when calling readBytes() byte per byte #323

Open afalkenhahn opened 3 years ago

afalkenhahn commented 3 years ago

I'm having a strange issue when using readBytes() to read just a single byte. When I send 7 bytes from a PC to an Android device, and try to read them using something like this, it works fine:

byte[] data = new byte[7];
int k = 0;
while(k != 7) {
    int len = readBytes(data, 0);    
    if(len > 0) k += len;
}

But when I send 7 bytes from a PC to an Android device and I use a buffer that is only a single byte, it doesn't work. This is the code:

byte[] data = new byte[1];
int k = 0;
while(k != 7) {
    int len = readBytes(data, 0);    
    if(len > 0) k += len;
}

The code above will loop forever because k will never be more than 0.

I've debugged it and found out that bulkTransfer always returns -1 so I suspect it does so because the buffer is too small (just 1 byte) for bulkTransfer to copy all data it has. Could this be the reason?

If it is, shouldn't UsbSerial be fixed to work around this so that readBytes can be used with arbitrary buffer sizes? E.g. readBytes could call syncRead in buffers of 8kb or so internally so that bulkTransfer will never fail because of a buffer being too small...

Any ideas/thoughts on this?