2016-06-08 742 views
1

我正在使用Android USB Host API使用FT232发送和接收数据。我使用两个线程发送部分和阅读部分。我可以发送和接收数据,但读取的数据与数据发送的数据不相等。例如,当我发送字节[1,2,3,4,5]。读取的数据有时是字节[1,2,5]。有时可以读取5个字节,但有时会丢失一些字节。附件是我正在使用的代码。Android USB无法通过bulkTransfer读取完整数据

设置部分:

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); 
       } 
      } 
          } 
        } 
       } 
      } 
     } 

发送部分:

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(); 
} 

阅读部分:

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); 
} 

回答

0

我已经找到了Android的一个库,它解决了这个问题。希望它能帮助有同样问题的人。

UsbSerial