use*_*470 3 c buffer serial-port
我正在尝试找出一个读取串行数据的好解决方案,以及当 aread()完成但它包含不完整的消息时该怎么办。
设备之间的预期消息具有定义的开始和结束字节,因此很容易看到消息何时开始和结束。
我可以很好地打开串行端口并从串行端口读取。但我遇到计算机读取速度快于数据传输速度的情况,并且我收到一条不完整的消息。
对于这个例子,假设预期的消息是
0x10 0xFF 0xFF 0xFF 0xFF 0x11
Run Code Online (Sandbox Code Playgroud)
以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();
Run Code Online (Sandbox Code Playgroud)
为了最大限度地减少对小字节数进行多次read()系统调用的开销(例如一次读取一个字节的错误解决方案),请在代码中使用中间缓冲区。
串行终端的read ()应处于阻塞模式,以避免返回零字节的代码。
#define BLEN 1024
unsigned char rbuf[BLEN];
unsigned char *rp = &rbuf[BLEN];
int bufcnt = 0;
/* get a byte from intermediate buffer of serial terminal */
static unsigned char getbyte(void)
{
if ((rp - rbuf) >= bufcnt) {
/* buffer needs refill */
bufcnt = read(fd, rbuf, BLEN);
if (bufcnt <= 0) {
/* report error, then abort */
}
rp = rbuf;
}
return *rp++;
}
Run Code Online (Sandbox Code Playgroud)
有关串行终端的正确termios初始化代码,请参阅此答案。您应该将 VMIN 参数增加到更接近 BLEN 值或至少是最长预期消息的长度,并且 VTIME 为 1。
现在,您可以方便地一次访问接收到的数据一个字节,同时将性能损失降至最低。
#define MLEN 1024 /* choose appropriate value for message protocol */
int main()
{
unsigned char mesg[MLEN];
...
while (1) {
while (getbyte() != 0x10)
/* discard data until start found */ ;
length = 0;
while ((mesg[length] = getbyte()) != 0x11) {
/* accumulate data until end found */
length++;
}
/* process the message */
...
} /* loop for next message */
...
}
Run Code Online (Sandbox Code Playgroud)
请注意,您对消息帧的检测并不可靠。
如果数据是二进制的,因此可以使用与这些开始和结束字节相同的值,那么对接收到的数据的这种解析很容易出现未对齐的消息帧。有关正确算法的描述,
请参阅此答案。