超时从串口读取可变长度数据
Reading variable length data from serial with timeout
我正在使用软件 UART 驱动程序从设备读取数据帧。它被写成一个 tty 模块,所以从 is 中读取是非常标准的:
struct termios options;
int tty = open(path, O_RDWR | O_NOCTTY | O_SYNC);
tcgetattr(tty, &options);
options.c_cflag = B4800 | CS8 | CLOCAL | CREAD | PARENB;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcsetattr(tty, TCSANOW, &options);
while (running)
{
int rx_count = read(tty_device, (void*)header, header_size);
// parse the header to figure out the total frame size
rx_count = read(tty_device, (void*)frame_data, frame_size);
}
大部分时间都可以,但有时由于 UART 可靠性的限制,我会漏掉一些字节。
我的问题是,当我遗漏字节时,代码会将下一帧的初始字节读取为上一帧的最后字节。这会导致随机的、不可预测的行为。
我想知道是否有一种基于时间而不是数据大小读取的好方法。像这样:
while (running)
{
// read bytes continuously from the tty device
// if 1 second passes with no further bytes coming, stop reading
// process whatever data was read
}
我可能会拼凑一些东西最终做到这一点,但我想这很有可能已经被弄清楚了,我只是没能在互联网上找到这些信息。
我能够使用 VMIN 和 VTIME 完成我需要的工作,如 link 中 sawdust 的评论所示:
Linux Blocking vs. non Blocking Serial Read
这也与我的问题有关。不知何故,我之前无法找出正确的搜索词来找到它:
VMIN and VTIME Terminal Settings for variable sized messages
我正在使用软件 UART 驱动程序从设备读取数据帧。它被写成一个 tty 模块,所以从 is 中读取是非常标准的:
struct termios options;
int tty = open(path, O_RDWR | O_NOCTTY | O_SYNC);
tcgetattr(tty, &options);
options.c_cflag = B4800 | CS8 | CLOCAL | CREAD | PARENB;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcsetattr(tty, TCSANOW, &options);
while (running)
{
int rx_count = read(tty_device, (void*)header, header_size);
// parse the header to figure out the total frame size
rx_count = read(tty_device, (void*)frame_data, frame_size);
}
大部分时间都可以,但有时由于 UART 可靠性的限制,我会漏掉一些字节。
我的问题是,当我遗漏字节时,代码会将下一帧的初始字节读取为上一帧的最后字节。这会导致随机的、不可预测的行为。
我想知道是否有一种基于时间而不是数据大小读取的好方法。像这样:
while (running)
{
// read bytes continuously from the tty device
// if 1 second passes with no further bytes coming, stop reading
// process whatever data was read
}
我可能会拼凑一些东西最终做到这一点,但我想这很有可能已经被弄清楚了,我只是没能在互联网上找到这些信息。
我能够使用 VMIN 和 VTIME 完成我需要的工作,如 link 中 sawdust 的评论所示: Linux Blocking vs. non Blocking Serial Read
这也与我的问题有关。不知何故,我之前无法找出正确的搜索词来找到它: VMIN and VTIME Terminal Settings for variable sized messages