我正在努力寻找一种优雅的解决方案来读取串行数据,以及在
设备之间的预期消息具有定义的起始和结束字节,因此很容易看到消息的起始和结束。
我可以正常打开串行端口并从中读取数据。但是我遇到了电脑读取速度比数据传输速度更快的情况,导致我收到了不完整的消息。
针对本例,假设期望的消息是:
read()
完成但包含不完整消息时该怎么做。设备之间的预期消息具有定义的起始和结束字节,因此很容易看到消息的起始和结束。
我可以正常打开串行端口并从中读取数据。但是我遇到了电脑读取速度比数据传输速度更快的情况,导致我收到了不完整的消息。
针对本例,假设期望的消息是:
0x10 0xFF 0xFF 0xFF 0xFF 0x11
0x10是起始,0x11是结束,0xFF是数据字节。
我是C语言新手,可能会忽略一些显而易见的东西, 我的当前解决方案
int main() {
/* Ommited serial port opening and checking*/
char read_buffer[80];
char message_buffer[80];
int message_buffer_index = 0;
int start_index = -1;
int end_index = -1;
int read_bytes;
read_bytes = read(serial_port, read_buffer, sizeof(read_buffer) - 1);
/* Now lets say read_bytes returns 3 and read buffer is {0x10, 0xFF, 0xFF} */
/* What should I do with the read_buffer? Currently appending to message buffer*/
memcpy(&message_buffer[message_buffer_index], &read_buffer[0], read_bytes);
/* Now check the message buffer for a full message */
for (int i = 0; i < 80; i++) {
if (message_buffer[i] = 0x10) {
start_index = i;
continue;
}
if (message_buffer[i] = 0x11) {
end_index = i;
}
if (start_index != -1 && end_index != -1) {
/* Found a message, do something with it, not super important here */
process_message();
/* Now how to erase the full message from the
buffer and push any non processed data to the
front? */
remove_message();
}
}
}
int process_message();
int remove_message();
#include
2)子函数的原型。请发布一个[mcve]。 - user3629249read_bytes = read(serial_port, read_buffer, sizeof(read_buffer)
,建议(虽然效率较低)在循环中一次读取一个字节,同时检查“开始”和“结束”字节。只有在读取到“开始”字节后才开始累积数据。当读取到“结束”字节时停止累积数据。 - user3629249#define
值,以便子函数知道要处理的最大数据量。建议将消息的实际长度传递给子函数。 - user3629249