flutter_libserialport写入正常但读取未处理异常

niwlg2el  于 2023-03-31  发布在  Flutter
关注(0)|答案(2)|浏览(531)

我正在尝试实现一个简单的at cmd应用程序。我修改了flutter_libserialport示例。https://pub.dev/packages/flutter_libserialport
简单地说,
1.将floatButton操作替换为我自己的reTest()函数

floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        // onPressed: initPorts,
        onPressed: rwTest,
    ),

1.下面是我的rwTest

Future<void> rwTest() async {
        for (var p in availablePorts) {
          if (p == 'COM115') {
            print(p);
            List<int> d = [65, 84, 13];
            Uint8List bytes = Uint8List.fromList(d);
            SerialPort port = SerialPort(p);
            SerialPortReader reader = SerialPortReader(port, timeout: 10000);
            try {
              port.openReadWrite();
              print(port.write(bytes));
              await reader.stream.listen((data) {
                print('received : $data');
              });
              port.close();
            } on SerialPortError catch (_, err) {
              if (port.isOpen) {
                port.close();
                print('serial port error');
              }
            }
          }
        }
      }

我的设备显示为COM 115,所以我把固定值。和“写”操作是成功的,但当我使用“reader.stream.listen()”
SerialPortError发生如下抖动:COM 115Flutter:3 [错误:flutter/lib/ui/ui_dart_state.cc(209)]未处理的异常:SerialPortError:There is no need to be a reference to the following parameters:
我猜“听”的用法是错误的,但我不知道如何修复它。有人可以帮助我修复它吗?

2w3kk1z5

2w3kk1z51#

你只需要删除try{}中的port.close() ...我认为你还应该设置timeout = 1,
此外,最好在使用端口之前设置一个配置
注意:你可以只通过name访问端口,而不用遍历所有可用的端口。

Future<void> rwTest() async {
    List<int> d = [65, 84, 13];
    Uint8List bytes = Uint8List.fromList(d);
    SerialPort port = SerialPort('COM115');
    // configuration 
    final configu = SerialPortConfig();
    configu.baudRate = 9600;
    configu.bits = 8;
    configu.parity = 0;
    port.config = configu;
    SerialPortReader reader = SerialPortReader(port, timeout: 10);
    try {
      port.openReadWrite();
      print(port.write(bytes));
      await reader.stream.listen((data) {
        print('received : $data');
      });
    } on SerialPortError catch (_, err) {
      if (port.isOpen) {
        port.close();
        print('serial port error');
      }
    }
  }
omhiaaxx

omhiaaxx2#

只要通信处于活动状态,串行端口就需要打开以发送和接收数据
删除端口关闭方法调用

try {
    port.openReadWrite();
    print(port.write(bytes));
    await reader.stream.listen((data) {
        print('received : $data');
    });
    //port.close(); --> remove this line
}

退出时关闭读取器流,然后关闭端口

相关问题