Search code examples
androidusbusbserialftdi

Android USB cannot read complete data through bulkTransfer


I am using Android USB Host API to send and receive data using FT232. I am using two threads for the sending part and the reading part. I can send and receive data but the data read is not equal to what the data sent. For example, when I send byte[1, 2, 3, 4, 5]. The data read is sometimes byte[1, 2, 5]. Sometimes the 5 bytes can be read but sometimes some bytes are lost. Attached is the code I'm using.

Setup part:

HashMap<String, UsbDevice> list = mUsbManager.getDeviceList();
Iterator<UsbDevice> iterator = list.values().iterator();
while(iterator.hasNext()) {
    UsbDevice device = iterator.next();
    if (device.getInterfaceCount() == 1) {
        mInterface = device.getInterface(0);
        for (int i = 0; i < mInterface.getEndpointCount(); i++) {
            if (mInterface.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                if (mInterface.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN) {
                    mEndpointIn = mInterface.getEndpoint(i);
                } else {
                    mEndpointOut = mInterface.getEndpoint(i);
                }
             }
                            }
                    }
                }
            }
        }

Send part:

UsbDeviceConnection connection = mUsbManager.openDevice(device);
if (connection == null) {
    Log.e(TAG, "Connection terminated");
    return;
}
byte[] bytes = new byte[1, 2, 3, 4, 5];
boolean claimed = connection.claimInterface(mInterface, true);
if (claimed) {
    connection.controlTransfer(0x40, 0x03, 0x0034, 0, null, 0, 0); // baud rate 57600
    connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0); // 8-N-1
    int sentLength = connection.bulkTransfer(mEndpointOut, bytes, bytes.length, 100);
    connection.releaseInterface(mInterface);
    connection.close();
}

Read part:

UsbDeviceConnection connection = mUsbManager.openDevice(device);
if (connection == null) {
    Log.e(TAG, "Connection terminated");
    return;
}
byte[] inData = new byte[64];
boolean claimed = connection.claimInterface(mInterface, true);
if (claimed) {
    connection.controlTransfer(0x40, 0x03, 0x0034, 0, null, 0, 0); // baud rate 57600
    connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0); // 8-N-1
    int readLength = connection.bulkTransfer(mEndpointIn, inData, inData.length, 100);
    connection.releaseInterface(mInterface);
    connection.close();
    // 'result' is the data I want, the first 2 bytes are status bytes so being removed
    byte[] result = new byte[inData.length - 2];
    System.arrayCopy(inData, 2, result, 0, inData.length - 2);
}

Solution

  • I have found a library for Android which solved this problem. Hope it will help anyone having the same issue.

    UsbSerial