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

好久没有写文章了,年前公司新开了一个项目,是和usb转串口通信相关的,需求是用安卓平板通过usb转接后与好几个外设进行通信,一直忙到最近,才慢慢闲下来,趁着这个周末不忙,记录下usb转串口通信开发的基本流程。

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

1.发现设备

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是否有访问权限:

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,当接受到授权成功的广播后做一些其他处理:

  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,我们需要的一般是第一个,所以:

usbInterface=usbDevice.getInterface(0);

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

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.

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

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,因为数据的输入是不定时的,因此我们可以另开一个线程,来专门接受数据,接受数据的代码如下:

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外设数据的方法应该还有别的,不足之处欢迎指正。

Android 实现 USB 串口通信的具体步骤如下: 1. 获取 USB 设备的权限:在 AndroidManifest.xml 文件中添加一个 USB 设备的 intent-filter,并在应用程序中注册一个 BroadcastReceiver 来接收 USB 设备的插入和移除事件。 2. 扫描 USB 设备:使用 UsbManager 类扫描 USB 设备并获取其接口和端点信息。 3. 打开 USB 连接:使用 UsbDeviceConnection 类打开 USB 连接。 4. 配置串口参数:使用 UsbDeviceConnection 类设置串口参数,例如波特率、数据位、停止位和校验位等。 5. 发送和接收数据:使用 UsbDeviceConnection 类向 USB 设备发送数据并从 USB 设备接收数据。 下面是一个基本的示例代码,演示如何实现 Android USB 串口通信: ```java public class MainActivity extends Activity { private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private UsbManager mUsbManager; private UsbDevice mDevice; private UsbDeviceConnection mConnection; private UsbEndpoint mEndpointIn; private UsbEndpoint mEndpointOut; private BroadcastReceiver mUsbReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); // 注册 USB 设备插入和移除的 Broadcast Receiver mUsbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if (device != null) { // 权限已授予,打开 USB 连接 openUsbDevice(device); } } else { // 权限未授予 Log.d("USB", "permission denied for device " + device); } } } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { // USB 设备已插入,请求权限 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); requestUsbPermission(device); } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { // USB 设备已移除,关闭连接 closeUsbDevice(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_USB_PERMISSION); filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbReceiver, filter); // 扫描 USB 设备并请求权限 UsbDevice device = findUsbDevice(); if (device != null) { requestUsbPermission(device); } } @Override protected void onDestroy() { super.onDestroy(); // 关闭连接和释放资源 unregisterReceiver(mUsbReceiver); closeUsbDevice(); } private UsbDevice findUsbDevice() { // 扫描 USB 设备并返回第一个串口设备 for (UsbDevice device : mUsbManager.getDeviceList().values()) { int interfaceCount = device.getInterfaceCount(); for (int i = 0; i < interfaceCount; i++) { UsbInterface usbInterface = device.getInterface(i); if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM) { return device; } } } return null; } private void requestUsbPermission(UsbDevice device) { // 请求 USB 设备权限 PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); mUsbManager.requestPermission(device, permissionIntent); } private void openUsbDevice(UsbDevice device) { // 打开 USB 连接并设置端点信息 mDevice = device; mConnection = mUsbManager.openDevice(device); if (mConnection != null) { UsbInterface usbInterface = device.getInterface(0); for (int i = 0; i < usbInterface.getEndpointCount(); i++) { UsbEndpoint endpoint = usbInterface.getEndpoint(i); if (endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) { mEndpointIn = endpoint; } else if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) { mEndpointOut = endpoint; } } } } } private void closeUsbDevice() { // 关闭 USB 连接和释放资源 mDevice = null; if (mConnection != null) { mConnection.close(); mConnection = null; } mEndpointIn = null; mEndpointOut = null; } private void sendData(byte[] data) { // 发送数据到 USB 设备 if (mConnection != null && mEndpointOut != null) { mConnection.bulkTransfer(mEndpointOut, data, data.length, 0); } } private byte[] receiveData() { // 接收数据从 USB 设备 if (mConnection != null && mEndpointIn != null) { byte[] buffer = new byte[1024]; int count = mConnection.bulkTransfer(mEndpointIn, buffer, buffer.length, 0); if (count > 0) { byte[] data = new byte[count]; System.arraycopy(buffer, 0, data, 0, count); return data; } } return null; } } ``` 在上述示例代码中,我们使用 UsbManager 类扫描 USB 设备并获取其接口和端点信息。然后,我们使用 UsbDeviceConnection 类打开 USB 连接,并设置串口参数。最后,我们使用 UsbDeviceConnection 类向 USB 设备发送数据并从 USB 设备接收数据。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值