I'm reading on a stream connected on a UART serial port via half-duplex RS-485 protocol at 9600bps, Data : 8 bits, Stop 1 bit no parity with an embedded device.
I know that the system which I'm connected to sends binary commands between 2 byte and 10 bytes long at an interval of 20ms.
I access the stream with the following flags:
uart0_filestream = open(COM_UART_DEV, O_RDWR | O_NOCTTY | O_NDELAY);
However, it happens frequently that the 10 bytes long commands will be chunked in half causing a checksum error in my application. I need to poll every 20 ms and the only solution I found for this is to inscrease the sleep time between polls, which I don't want.
Is there a flag or a smart method that I can use to make sure the transmission is complete before reading the content of the stream buffer?
Okay, I found a solution that's ok for my needs. Since I can't know for sure that when I will read the content of the stream all the data will be there and I don't want to increase my poll interval, as @sawdust suggested, I increased the poll rate:
unsigned char *pStartBuffer = pRxBuffer;
if(uart0_filestream != -1)
{
int rx_length = 0, rx = 0, elapsed = 0;
bool bCommand = false;
while(rx_length <= 10)//&& elapsed <= 10)
{
rx = read(uart0_filestream, (void*)pRxBuffer, length);
if(rx > 0)
{
rx_length += rx;
pRxBuffer += rx;
if(checksum(pStartBuffer, rx_length) == true)
{
bCommand = true;
break;
}
}
nanosleep(&sleep_rx, NULL);
//elapsed+=2;
}
I increased the poll rate to 8ms at first. Since I know that the longest command I can receive is 10 bytes long, I read until the checksum is valid or that the content read is 10 bytes long and sleep an extra 2ms between polls. This performs very well for now.