Android USB设备通信--读写操作

进行读写操作的前提:

  • 获取UsbDeviceConnection对象,即建立连接;

  • 正确获取到所需要的UsbInterface对象,并占用这个通信接口;

  • 正确获取到所需要的Endpoint,包括读Endpoint和写Endpoint;

  • 创建相应的数据缓存区,包括读写数据缓存区。

protected byte[] mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
protected byte[] mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];

//dest是读数据缓存,会将数据读入到这个字节数组中
//timeoutMillis 是超时时间
//方法返回读入的数据长度
public int read(byte[] dest, int timeoutMillis) throws IOException {
      final int numBytesRead;
      //多线程处理
      synchronized (mReadBufferLock) {
          int readAmt = Math.min(dest.length, mReadBuffer.length);
          /**     
            * Performs a bulk transaction on the given endpoint.     
            * The direction of the transfer is determined by the direction of the endpoint.     
            * 

* This method transfers data starting from index 0 in the buffer. * To specify a different offset, use * {@link #bulkTransfer(UsbEndpoint, byte[], int, int, int)}. *

* * @param endpoint the endpoint for this transaction * @param buffer buffer for data to send or receive * @param length the length of the data to send or receive * @param timeout in milliseconds * @return length of data transferred (or zero) for success, * or negative value for failure */
numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt, timeoutMillis); if (numBytesRead < 0) { // This sucks: we get -1 on timeout, not 0 as preferred. // We *should* use UsbRequest, except it has a bug/api oversight // where there is no way to determine the number of bytes read // in response :\ -- http://b.android.com/28023 return 0; } //将读到的数据复制到dest数组中 System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead); } return numBytesRead; } //src表示需要写出的数据字节数组 //timeoutMillis超时时间 public int write(byte[] src, int timeoutMillis) throws IOException { int offset = 0;//记录已发送的长度 while (offset < src.length) { final int writeLength; final int amtWritten; synchronized (mWriteBufferLock) { final byte[] writeBuffer; //已经发送的长度 writeLength = Math.min(src.length - offset, mWriteBuffer.length); if (offset == 0) { writeBuffer = src; } else { // bulkTransfer does not support offsets, make a copy. //将src中的数据复制到mWriteBuffer中 System.arraycopy(src, offset, mWriteBuffer, 0, writeLength); writeBuffer = mWriteBuffer; } //发送出去,返回发送长度 amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength, timeoutMillis); } if (amtWritten <= 0) { throw new IOException("Error writing " + writeLength + " bytes at offset " + offset + " length=" + src.length); } offset += amtWritten; } return offset; }

上述读写过程,流程如下:

Android USB设备通信--读写操作_第1张图片

你可能感兴趣的:(Android,USB)