无网不进  
软硬件开发

详解Android USB转串口通信开发基本流程

我们开发使用的是usb主机模式,即:安卓平板作为主机,usb外设作为从机进行数据通信。整个开发流程可以总结为以下几点:

1.发现设备

1
2
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
Map<String, UsbDevice> usbList = usbManager.getDeviceList();

通过UsbManager这个系统提供的类,我们可以枚举出当前连接的所有usb设备,我们主要需要的是UsbDevice对象,关于UsbDevice这个类,官方是这样注释的:

This class represents a USB device attached to the android device with the android device
acting as the USB host.

是的,这个类就代表了Android所连接的usb设备。

2.打开设备

接下来,我们需要打开刚刚搜索到的usb设备,我们可以将平板与usb外设之间的连接想象成一个通道,只有把通道的门打开后,两边才能进行通信。

一般来说,在没有定制的android设备上首次访问usb设备的时候,默认我们是没有访问权限的,因此我们首先要判断对当前要打开的usbDevice是否有访问权限:

1
2
3
4
5
6
7
8
9
if (!usbManager.hasPermission(usbDevice)) {
    usbPermissionReceiver = new UsbPermissionReceiver();
    //申请权限
    Intent intent = new Intent(ACTION_DEVICE_PERMISSION);
    PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    IntentFilter permissionFilter = new IntentFilter(ACTION_DEVICE_PERMISSION);
    context.registerReceiver(usbPermissionReceiver, permissionFilter);
    usbManager.requestPermission(usbDevice, mPermissionIntent);
    }

这里我们声明一个广播UsbPermissionReceiver,当接受到授权成功的广播后做一些其他处理: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private class UsbPermissionReceiver extends BroadcastReceiver {
   public void onReceive(Context context, Intent intent) {
     String action = intent.getAction();
     if (ACTION_DEVICE_PERMISSION.equals(action)) {
       synchronized (this) {
         UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
         if (device.getDeviceName().equals(usbDevice.getDeviceName()) {
           if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
            //授权成功,在这里进行打开设备操作
           } else {
            //授权失败
           }
         }
       }
     }
   }
 }

接下来,我们要找到具有数据传输功能的接口UsbInterface,从它里边儿找到数据输入和输出端口UsbEndpoint,一般情况下,一个usbDevice有多个UsbInterface,我们需要的一般是第一个,所以:

1
usbInterface=usbDevice.getInterface(0);

同样的,一个usbInterface有多个UsbEndpoint,有控制端口和数据端口等,因此我们需要根据类型和数据流向来找到我们需要的数据输入和输出两个端口:

1
2
3
4
5
6
7
8
9
10
for (int index = 0; index < usbInterface.getEndpointCount(); index++) {
        UsbEndpoint point = usbInterface.getEndpoint(index);
        if (point.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
          if (point.getDirection() == UsbConstants.USB_DIR_IN) {
            usbEndpointIn = point;
          } else if (point.getDirection() == UsbConstants.USB_DIR_OUT) {
            usbEndpointOut = point;
          }
        }
      }

最后,才是真正的打开usb设备,我们需要和usb外设建立一个UsbDeviceConnection,它的注释很简介的说明了它的用途:

This class is used for sending and receiving data and control messages to a USB device.

它的获取也很简单,就一句代码:

1
usbDeviceConnection = usbManager.openDevice(usbDevice);

到这里,理论上平板和usb外设之间的连接已经建立了,也可以首发数据了,但是,我们大部分情况下还需要对usb串口进行一些配置,比如波特率,停止位,数据控制等,不然两边配置不同,收到的数据会乱码。具体怎么配置,就看你使用的串口芯片是什么了,目前流行的有pl2303,ch340等,由于篇幅问题,需要具体配置串口代码的朋友请自行查阅。

3.数据传输

到这里,我们已经可以与usb外设进行数据传输了,首先来看怎么向usb设备发送数据。

 1.向usb外设发送数据

在第二步中,我们已经获取了数据的输出端口usbEndpointIn,我们向外设发送数据就是通过这个端口来实现的。来看怎么用:

 

复制代码代码如下:

int ret = usbDeviceConnection.bulkTransfer(usbEndpointOut, data, data.length, DEFAULT_TIMEOUT);

 

 

bulkTransfer这个函数用于在给定的端口进行数据传输,第一个参数就是此次传输的端口,这里我们用的输出端口,第二个参数是要发送的数据,类型为字节数组,第三个参数代表要发送的数据长度,最后一个参数是超时,返回值代表发送成功的字节数,如果返回-1,那就是发送失败了。

2.接受usb外设发送来的数据

同理,我们已经找到了数据输入端口usbEndpointIn,因为数据的输入是不定时的,因此我们可以另开一个线程,来专门接受数据,接受数据的代码如下:

1
2
3
4
5
6
7
8
9
10
11
int inMax = inEndpoint.getMaxPacketSize();
ByteBuffer byteBuffer = ByteBuffer.allocate(inMax);
UsbRequest usbRequest = new UsbRequest();
usbRequest.initialize(connection, inEndpoint);
usbRequest.queue(byteBuffer, inMax);
if(connection.requestWait() == usbRequest){
  byte[] retData = byteBuffer.array();
  for(Byte byte1 : retData){
    System.err.println(byte1);
  }
}

以上,就是usb转串口通信的基本流程,有些地方写的不是很全面,比如接收usb外设数据的方法应该还有别的,不足之处欢迎指正。也希望大家多多支持脚本之家。

原文链接:http://blog.csdn.net/weixin_38251977/article/details/69944095

posted on 2017-12-28 13:02  无网不进  阅读(1942)  评论(0编辑  收藏  举报