I am currently writing code for a UART communication in my firmware. I am getting an interrupt every byte received (meaning I don't get a chunk of data, 1 byte at a time but, in the sample below I store them into a chunk of data for simulating my data parsing only).
I have a dynamic message length format, as shown in the code below. May I know what is the most efficient and elegant way to parse this message? I believe my current code could be further improved.
#include <stdint.h>
typedef struct {
uint8_t header_DLE;
uint16_t id;
uint8_t msg_command;
uint16_t msg_length;
uint8_t data[400];
uint8_t footer_DLE;
uint8_t footer_BCC;
} Serial_Rx_Data;
Serial_Rx_Data _rx_data;
static int _rx_index;
static uint8_t _rawData[512];
int main()
{
uint8_t data[18];
//Message format
data[0] = 0x10; //DLE
data[1] = 0x03; //ID
data[2] = 0; //ID
data[3] = 0x03; //Command
data[4] = 0x03; //Length - determines the data length
data[5] = 0; //Length
data[6] = 0x41; //Data
data[7] = 0x42; //Data
data[8] = 0x43; //Data
data[9] = 0x03; //DLE
data[10] = 0xfa; //BCC
//Simulate getting data every byte
for (int i = 0; i <= 10; i++) {
_rawData[_rx_index] = data[i];
if (_rx_index == 5) {
_rx_data.header_DLE = _rawData[0];
_rx_data.id = _rawData[2] << 8 | _rawData[1];
_rx_data.msg_command = _rawData[3];
_rx_data.msg_length = _rawData[5] << 8 | _rawData[4];
}
//Get the length of data
if ((_rx_index == 6) && (_rx_data.msg_length > 0)) {
for (int j = 0; j < _rx_data.msg_length; j++) {
_rx_data.data[j] = _rawData[6 + j];
}
}
//Get the last 2 byte
if (_rx_index == (_rx_data.msg_length + 6 + 1)) {
_rx_data.footer_DLE = _rawData[6 + _rx_data.msg_length];
_rx_data.footer_BCC = _rawData[6 + _rx_data.msg_length + 1];
//Complete parsing
//Callback to other function
}
_rx_index++;
}
return 0;
}