Flutter 新手,但拥有多年为嵌入式设备编写 C 代码的经验。尝试了解数据流如何与 Dart 以及这个特定的库一起工作。我正在寻找如何使用 Arduino 来回发送几个字节以执行一些简单操作的示例,但我没有找到任何显示通过串行链路进行结构化数据包交换(例如 XModem)的内容。您接收固定大小的数据包(128 字节)并在接收器处重新组装它们。
我已经设法获得一些代码,这些代码将等到至少收到 5 个字节后才对其进行任何操作,并且如果我一次发送一个字节,它就可以工作。但是如果我发送一堆字节,它就会打印所有字节。它们的分割方式也不一致( data.length 与 upcommingData.listen(data) 不一致)。尝试制作缓冲区 Uint8List,但使用 .add 或 .addAll 向其附加数据似乎不起作用。
我知道这段代码不是最好的方法,但它是我能够工作的全部。还没有弄清楚 SerialPortBuffer() 并且找不到任何示例。也尝试过使用 ChunkedStreamReader 但没有成功(也没有超出 API 文档中的示例)
如有任何帮助,我们将不胜感激。
`
List<String> availablePort = SerialPort.availablePorts;
SerialPort port = SerialPort('COM8');
SerialPortReader reader = SerialPortReader(port);
List<Uint8List> buffer = []; // Doesn't work with just Uint8List
int bufferIndex = 0;
debugPrint('Available Ports: $availablePort');
// Incoming serial port stream
Stream<Uint8List> upcommingData = reader.stream.map((data) {
return data;
});
try {
port.openReadWrite();
initSerial(port);
// Send data to serial port
serialSend(port, 'Testing');
upcommingData.listen((data) {
buffer.add(data);
bufferIndex += data.length;
if (bufferIndex >= 5) {
String strBuffer = '';
for (var letter in buffer) {
strBuffer += String.fromCharCodes(letter);
}
debugPrint('Buffer: $strBuffer');
bufferIndex = 0;
buffer = [];
strBuffer = '';
}
});
} on SerialPortError catch (err, _) {
if (kDebugMode) {
print(SerialPort.lastError);
}
port.close();
} finally {
// Catch anything not caught
}
L
编辑(一些进展)
因此,在尝试使用 ChunkedStreamReader 并找出 SerialPortBuffer 失败后,我发现 Uint8List 无法像 Flutter 中的其他 List 一样进行操作。将缓冲区设置为 List 似乎更容易,然后根据需要使用
String.fromCharCodes()
将其更改回 Uint8List。对 Uint8 数据使用 int 似乎很浪费,但我想不出更好的方法。
`
List<String> availablePort = SerialPort.availablePorts;
SerialPort port = SerialPort('COM8');
SerialPortReader reader = SerialPortReader(port);
List<int> buffer = [];
int bufferIndex = 0;
debugPrint('Available Ports: $availablePort');
// Incoming serial port stream
Stream<Uint8List> upcommingData = reader.stream.map((data) {
return data;
});
try {
port.openReadWrite();
initSerial(port);
// Send data to serial port
serialSend(port, 'Testing');
upcommingData.listen((data) {
buffer += data;
bufferIndex += data.length;
if (bufferIndex >= 5) {
String strBuffer = String.fromCharCodes(buffer);
debugPrint('Buffer: $strBuffer');
bufferIndex = 0;
buffer = [];
}
});
} on SerialPortError catch (err, _) {
if (kDebugMode) {
print(SerialPort.lastError);
}
port.close();
} finally {
// Catch anything not caught
}
L