I am reading data frames from a device using a software UART driver. It's written as a tty module so reading from is is pretty standard:
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);
}
It works most of the time, but sometimes I miss some bytes due to limitations in the reliability of the UART.
My problem is that when I miss bytes the code reads the initial bytes of the next frame as the final bytes of the previous frame. This causes random, unpredictable behavior.
I am wondering if there is a good way to read based on time, instead of data size. Something like this:
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
}
I could probably hack together something that does this eventually but I imagine there is a good chance this has already been figured out, and I am just failing to find the info on the internet.