I am trying to read messages sent to my application via serial port. I am doing this successfully for the most part. My function assumes that there will be characters being read from the serial port which is where my concern comes in. Sometimes there is unknown characters or raw data being read into a character array. Before moving forward with the serial port message, I wanted to check the array to make sure there isn’t raw data or unknown characters. I have added the below check but was wondering if there was a better way to check:
/// \return -1 for success or returns index of failed check
int serial_error_check (char *buffer, int bufLen)
{
for (int i = 0; i < bufLen; i++)
{
// 10 is LF, 13 is CR, all other characters fall between 32 and 126
if (buffer[i] != 10 && buffer[i] != 13)
{
if (buffer[i] < 32 || buffer[i] > 126)
{
return i;
}
}
}
return -1;
}
C code on Linux OS.
EDIT: I tested this code by changing the baud rate on the serial port so that it didn't match with the receive end. I sent data across which caused for unknown characters to enter the buffer. The function returned but caused one of my processes to crash. So to refocus my question: how should I check each character index to make sure the buffer isn't corrupted? side notes: The connection is to a piece of hardware that the firmware has already been written so handshaking or checksum probably won't work. the buffer size is char[128] and I get the size of the message sent but that number is size of 1 character.