我需要通过串口写入120字节的数据,但是我发现使用flutter_libserialport库的写接口只能成功写入60字节。有什么办法可以解决这个问题吗? 以下是我的代码
debugPrint(
"Send command: ${request.map((e) => e.toRadixString(16).padLeft(2, '0').toUpperCase()).join(' ')}");
debugPrint("length: ${_portManager.write(request)}");
class SerialPortManager {
final String portName;
late SerialPort _serialPort;
final LogManager logManager; // 添加 LogManager 成员
SerialPortManager(this.portName, this.logManager) {
_serialPort = SerialPort(portName);
_serialPort.config = SerialPortConfig()
..baudRate = 115200
..setFlowControl(SerialPortFlowControl.none);
}
bool open() {
if (!_serialPort.openReadWrite()) {
try {
_serialPort.open(mode: SerialPortMode.readWrite);
return true;
} catch (e) {
debugPrint("Error opening port $portName: $e");
logManager.addLog("Error opening port $portName: $e");
return false;
}
}
return true;
}
void close() {
if (_serialPort.isOpen) {
_serialPort.close();
}
}
int write(Uint8List data) {
try {
if (!_serialPort.isOpen) {
if (!open()) {
return -1;
}
}
return _serialPort.write(data);
} catch (e) {
debugPrint("Error writing to port $portName: $e");
logManager.addLog("Error writing to port $portName: $e");
return -1;
}
}
Stream<Uint8List>? listen() {
try {
return SerialPortReader(_serialPort).stream;
} catch (e) {
debugPrint("Error setting up listener for port $portName: $e");
logManager.addLog("Error setting up listener for port $portName: $e");
return null;
}
}
}
打印的是:
颤动:发送命令:4C 4B 00 7C 2F 40 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 12 颤动:长度:60
我想在Flutter中使用串口写入60多个字节
int write(Uint8List data) {
try {
if (!_serialPort.isOpen) {
if (!open()) {
return -1;
}
}
return _serialPort.write(data,timeout: 500);
} catch (e) {
debugPrint("Error writing to port $portName: $e");
logManager.addLog("Error writing to port $portName: $e");
return -1;
}
}
/// Write data to the serial port.
///
/// If `timeout` is 0 or greater, the write operation is blocking.
/// The timeout is specified in milliseconds. Pass 0 to wait infinitely.
///
/// Returns the amount of bytes written.
int write(Uint8List bytes, {int timeout = -1});
所以我可以将超时更改为0或>0,现在效果很好~