本文介绍如何通过flutter_usb_serial插件在Flutter中实现USB转串口通信调试。
1、引入依赖
在flutter工程的pubspec.yaml文件中引入flutter_usb_serial依赖:
dependencies:
  flutter_usb_serial: ^0.0.22、导入import依赖包
在dart代码中import导入usb_serial/usb_serial.dart就可以使用了。
import 'package:usb_serial/usb_serial.dart';3、读取所有USB口设备
通过UsbSerial.listDevices方法可以获取当前的所有USB口。以下代码用于打印所有的USB口名称。
// USB测试
void serialTest() {
    List<UsbDevice> devices = await UsbSerial.listDevices();
    print("USB: ${devices}");
    UsbDevice? device = null;
    var i = 0;
    for (final item in devices) {
      print('${++i}) ${item}');  
      print('\t deviceId: ${item.deviceId}');
      print('\t productName: ${item.productName}');
      if(item.productName == 'USB Single Serial') {
        device = item;
      }
    }
}4、打开USB设备并设置通信参数
通过create方法创建设备对象,并通过open方法打开USB设备,可以通过setPortParameters设置通信参数。
UsbPort? port;
if (device == null) {
  return;
}
port = await device.create();
if(port == null) {
  print("创建设备对象失败");
  return;
}
bool openResult = await port.open();
if ( !openResult ) {
  print("Failed to open");
  return;
}
await port.setDTR(true);
await port.setRTS(true);
port.setPortParameters(115200, UsbPort.DATABITS_8,
  UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);5、监听并接收数据
通过调用设备对象的inputStream流的listen方法可以进行监听SUB端口的收到的所有数据。
// 监听消息
String message = '';
port.inputStream?.listen((data) {
  // print('received: $data');
  String hexString = data.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(); // 转换为16进制
  // print('receivedHex: ${hexString.toUpperCase()}'); 
  message += hexString.toUpperCase();
  if(message.length >= 6) {
    String content = message;
    print('received message: $content');
    // 处理握手消息
    handshakeMessage(content, port!);
    // 处理唤醒消息
    handleWakeup(content, port);
    message = '';
  }      
});6、通过USB串口发送消息
通过调用usb设备对象的write方法可以直接向USB串口发送数据,需要注意的是数据类型是Uint8List。
// 发送消息
void handshakeMessage(String data, UsbPort port) {
  List<String> list = strToList(data);
  if(list[0] == 'A5' && list[1] == '01' && list[2] == '01') {
    var bytes = Uint8List.fromList([0xA5, 0x01, 0xFF, 0x04, 0x00, 0x00, 0x00, 0xA5, 0x00, 0x00, 0x00, 0xB2]);  
    port.write(bytes);
  }
}7、代码示例
在flutter中实现USB转串口通信的完整代码示例如下:
// USB转串口测试
Future<void> test() async {
  List<UsbDevice> devices = await UsbSerial.listDevices();
  print("USB: ${devices}");
  UsbDevice? device = null;
  var i = 0;
  for (final item in devices) {
    print('${++i}) ${item}');  
    print('\t deviceId: ${item.deviceId}');
    print('\t productName: ${item.productName}');
    if(item.productName == 'USB Single Serial') {
      device = item;
    }
  }
  UsbPort? port;
  if (device == null) {
    return;
  }
  port = await device.create();
  if(port == null) {
    print("创建设备对象失败");
    return;
  }
  bool openResult = await port.open();
  if ( !openResult ) {
    print("Failed to open");
    return;
  }
  
  await port.setDTR(true);
  await port.setRTS(true);
  port.setPortParameters(115200, UsbPort.DATABITS_8,
    UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);
  // 监听消息
  String message = '';
  port.inputStream?.listen((data) {
    // print('received: $data');
    String hexString = data.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(); // 转换为16进制
    // print('receivedHex: ${hexString.toUpperCase()}'); 
    message += hexString.toUpperCase();
    if(message.length >= 6) {
      String content = message;
      print('received message: $content');
      // 处理握手消息
      handshakeMessage(content, port!);
      // 处理唤醒消息
      handleWakeup(content, port);
      message = '';
    }      
  });
}新时代农民工










