usb-host与外设通信(三)

4.与设备之间的通信

和USB设备通信可以是同步的或者是异步的,无论是哪一种情况,你都应该创建一个新的线程来处理数据传输,这样才不会使UI线程出现阻塞。与设备建立适宜的通信,你需要获得该设备一个合适的UsbInterfaceUsbEndpoint(想要通信)并且用 UsbDeviceConnection在终结点上发送请求。(原文:you need to obtain the appropriateUsbInterface and UsbEndpoint of the device that you want to communicate on and send requests on this endpoint with a UsbDeviceConnection.)总之,你写的代码应该这样:

4.1检查设备对象的属性,比如PID,VID或者设备单元来确定你是否想要与该设备进行通信

4.2当你确定该设备就是你想通信的对象,找到合适的UsbInterface(你想要用该接口在合适的UsbEndpoint下进行通信),接口可以有一个或者多个终结点,并且一般含有一个输入、输出端点来进行双向通信。

4.3当发现合适的endpoint时,在该endpoint处打开一个UsbDeviceConnection

4.4终结点处, bulkTransfer() controlTransfer() 方法提供传送数据。你应该在另外一个线程中去实行这一步骤以防UI线程被阻塞。

下面代码一个琐碎方式同步数据传输,你代码应该更多逻辑性以便正确地找到正确接口终结点进行通信同时也不要再UI线程中做任何的数据传输

private Byte[] bytes
private static int TIMEOUT = 0;
private boolean forceClaim = true;

...

UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
UsbDeviceConnection connection = mUsbManager.openDevice(device); 
connection.claimInterface(intf, forceClaim);
connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //写在另一个线程中
异步发送数据,需要使用 UsbRequest类去初始化队列异步请求,然后用requestWait()等待结果

5.终止设备通信

当通信完成或者设备拔出,通过请求releaseInterface()  close()来关闭 UsbInterfaceUsbDeviceConnection监听设备拔出事件,需要创建一个如下的广播接收器:

BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction(); 

      if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                // call your method that cleans up and closes communication with the device
            }
        }
    }
};
在程序中而不是在Manifest中创建一个广播接收器可以让你的程序在运行时处理拔出事件。这样拔出事件仅仅被发送到当前运行的程序而不是广播到所有的应用程序中


原文地址:https://www.cnblogs.com/sowhat4999/p/4439875.html