USB通信使用系统api,USB转串口通信使用第三方库usb-serial-for-android,串口通信使用Google官方库android-serialport-api。
一、USB通信
1.1 查找USB设备(2选1)
1.1.1 获取已连接USB设备
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
1.1.2 监听USB设备插拔
https://blog.csdn.net/u011630465/article/details/86525857?spm=1001.2014.3001.5501
1.2 USB设备授权
usb设备必须授权成功才能进行通信,否则会报设备没有权限错误。
// 判断usb设备是否有权限
manager.hasPermission(mUsbDevice)
// 为usb设备申请权限
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_DEVICE_PERMISSION), 0);
manager.requestPermission(mUsbDevice, pendingIntent)
1.3 打开USB设备
UsbDeviceConnection mConnection= manager.openDevice(mUsbDevice);
1.4 找到通信接口和节点
一般只有一个UsbInterface(也可能存在多个),每个UsbInterface下又有多个UsbEndpoint,找到对应的读写数据节点。
UsbInterface dataIface = mDevice.getInterface(0);
for (int i = 0; i < dataIface.getEndpointCount(); i++) {
UsbEndpoint endpoint = dataIface.getEndpoint(i);
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
mReadEndpoint = endpoint;
}
if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
mWriteEndpoint = endpoint;
}
}
1.5 开始通信
1.5.1 写数据
mConnection.bulkTransfer(mWriteEndpoint, bytes, bytes.length, timeout);
1.5.2 读数据
mConnection.bulkTransfer(mReadEndpoint, bytes, bytes.length, timeout);
二、USB转串口通信
USB转串口通信使用第三方库https://github.com/mik3y/usb-serial-for-android,底层实际也是使用系统USB通信api,在系统api的基础上增加串口驱动封装。
1.1-1.3(与USB通信流程一致)
1.4 检查驱动
驱动类型由串口芯片决定,驱动本质也只是调用系统usb写数据api完成一系列初始化操作。
UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(usbDevice);
1.5 打开串口,设置相关参数
UsbSerialPort mUsbSerialPort = driver.getPorts().get(mPort);
mUsbSerialPort.open(mConnection);
mUsbSerialPort.setParameters(mBaudRate, mDataBits, mStopBits, mParity);
1.6 开始通信
1.6.1 写数据
mUsbSerialPort.write(bytes, TIMEOUT);
1.6.2 读数据
mUsbSerialPort.read(bytes, TIMEOUT);
三、串口通信
串口通信使用google官方sdk:https://github.com/cepr/android-serialport-api
SerialPort mSerialPort = new SerialPort(new File("/dev/ttyUSB0"), 9600, 0);
// 读
InputStream inputStream = mSerialPort.getInputStream();
inputStream.read(buffer);
// 写
OutputStream outputStream = mSerialPort.getOutputStream();
out.write(bytes);