A classic problem in embedded systems programming! You're dealing with a framing problem in serial communication, where your message (packet) might be split across multiple receive events. I'll guide you through a robust solution using C (since you're working with embedded systems, we'll stick to C features; C++ is not commonly used in microcontrollers due to its overhead). We'll leverage FreeRTOS features to handle the reassembly process efficiently.
The Strategy:
- Buffering: Store incoming data in a circular buffer (also known as a ring buffer). This data structure is perfect for handling continuous streams of data where you need to append and process chunks.
- State Machine: Implement a simple finite state machine (FSM) to track the packet framing status: waiting for STX, receiving packet data, and waiting for ETX.
- Timers: Use a software timer (provided by FreeRTOS) to detect timeout conditions, ensuring you don't wait indefinitely for an ETX after receiving an STX.
- Parser: Once you detect a complete packet (STX + data + ETX), validate and process it.
Step 1: Circular Buffer Implementation
First, create a simple circular buffer. This will hold the incoming UART data.
#include <stdint.h>
#include <stdbool.h>
#include <string.h> // for memcpy
#define CIRC_BUFFER_SIZE 128 // Adjust size based on your max packet size and latency expectations
typedef struct {
uint8_t buffer[CIRC_BUFFER_SIZE];
uint16_t head; // Where we write new data
uint16_t tail; // Where we read data for processing
uint16_t count; // Number of bytes currently in the buffer
} CircularBuffer_t;
void circBufferInit(CircularBuffer_t *cb) {
cb->head = 0;
cb->tail = 0;
cb->count = 0;
}
bool circBufferIsFull(CircularBuffer_t *cb) {
return cb->count >= CIRC_BUFFER_SIZE;
}
bool circBufferIsEmpty(CircularBuffer_t *cb) {
return cb->count == 0;
}
void circBufferPush(CircularBuffer_t *cb, uint8_t *data, uint16_t len) {
if (len > (CIRC_BUFFER_SIZE - cb->count)) {
// Handle buffer overflow error, e.g., reset or log error
return;
}
for (uint16_t i = 0; i < len; i++) {
cb->buffer[cb->head] = data[i];
cb->head = (cb->head + 1) % CIRC_BUFFER_SIZE;
}
cb->count += len;
}
uint8_t circBufferPop(CircularBuffer_t *cb) {
if (circBufferIsEmpty(cb)) {
// Handle underflow, should not happen if used correctly
return 0;
}
uint8_t data = cb->buffer[cb->tail];
cb->tail = (cb->tail + 1) % CIRC_BUFFER_SIZE;
cb->count--;
return data;
}
Step 2: Finite State Machine (FSM) for Packet Parsing
Now, define your FSM states and the parser logic.
typedef enum {
WAIT_FOR_STX,
RECEIVING_PACKET,
WAIT_FOR_ETX
} PacketState_t;
typedef struct {
PacketState_t state;
uint16_t packetLen; // Length of the current packet being received
TickType_t stxReceivedTick; // Timestamp when STX was received
} PacketParser_t;
#define PACKET_TIMEOUT_MS 50 // Adjust based on your protocol's max inter-byte delay
#define STX 0x02 // Your Start of Text character
#define ETX 0x03 // Your End of Text character
void packetParserInit(PacketParser_t *parser) {
parser->state = WAIT_FOR_STX;
parser->packetLen = 0;
}
void processIncomingData(CircularBuffer_t *cb, PacketParser_t *parser) {
while (!circBufferIsEmpty(cb)) {
uint8_t byte = circBufferPop(cb);
switch (parser->state) {
case WAIT_FOR_STX:
if (byte == STX) {
parser->state = RECEIVING_PACKET;
parser->packetLen = 0;
parser->stxReceivedTick = xTaskGetTickCount(); // Get current tick
}
break;
case RECEIVING_PACKET:
if (byte == ETX) {
parser->state = WAIT_FOR_STX;
// **Packet complete**, process it
processPacket(cb->buffer + ((cb->tail - parser->packetLen - 1) % CIRC_BUFFER_SIZE), parser->packetLen);
} else {
parser->packetLen++;
// Check for timeout
if ((xTaskGetTickCount() - parser->stxReceivedTick) > pdMS_TO_TICKS(PACKET_TIMEOUT_MS)) {
// **Timeout error**: STX received but no ETX within time limit. Reset state.
parser->state = WAIT_FOR_STX;
// Optionally, log error or flush partial packet data
}
// Also check if packet length exceeds your max allowed size
if (parser->packetLen > MAX_PACKET_SIZE) {
// **Packet too long error**: Handle accordingly
parser->state = WAIT_FOR_STX;
}
}
break;
case WAIT_FOR_ETX: // This state is redundant; kept for clarity in more complex protocols
parser->state = WAIT_FOR_STX; // Fall back, treat as garbage
break;
}
}
}
void processPacket(uint8_t *data, uint16_t len) {
// **Your code here**: Validate and act on the packet data
// This is where you handle the fully received packet, e.g., checksum validation, command processing, etc.
}
Step 3: UART DataReceived Event Hookup
In your UART DataReceived event (interrupt or callback), simply push the data to the circular buffer:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart, uint16_t size) {
circBufferPush(&myCircBuffer, rxBuffer, size); // rxBuffer is where HAL stores received data
// Optionally, notify a task to run `processIncomingData` via a semaphore or task notification
xTaskNotifyGive(parserTaskHandle); // Assuming parserTaskHandle is your processing task handle
}
Step 4: Processing Task (FreeRTOS)
Create a task that waits for notifications (e.g., from HAL_UART_RxCpltCallback) and runs processIncomingData:
void packetParserTask(void *argument) {
CircularBuffer_t myCircBuffer;
PacketParser_t myParser;
circBufferInit(&myCircBuffer);
packetParserInit(&myParser);
while (1) {
// Wait for UART data notification
xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
// Process any pending data
processIncomingData(&myCircBuffer, &myParser);
}
}
Key Points & FreeRTOS Features Used:
- Circular Buffer: Efficiently handles streaming data, allowing non-blocking UART receive and packet reassembly.
- Software Timer (Ticks):
xTaskGetTickCount() and pdMS_TO_TICKS() ensure timeout detection without blocking.
- Task Notifications: Lightweight mechanism (
xTaskNotifyGive / xTaskNotifyWait) to signal the parser task when new UART data arrives, avoiding polling.
- Finite State Machine: Simplifies packet parsing logic, making the code readable and maintainable.
Benefits:
- Handles split packets seamlessly.
- Detects transmission errors (timeouts, packet too long).
- Non-blocking: UART reception and packet processing are decoupled.
- Memory-safe: Circular buffer prevents overflow (if sized correctly).
Adjust buffer sizes (CIRC_BUFFER_SIZE, MAX_PACKET_SIZE) and PACKET_TIMEOUT_MS based on your protocol specs and performance requirements. This design is robust, scalable, and suitable for most binary protocols over UART in FreeRTOS-based systems. Happy coding!