Yes, FreeRTOS Stream Buffers are an excellent choice for handling fragmented data reception and reassembly in your scenario. Stream buffers are designed to efficiently manage streams of data, making them ideal for UART communication where data arrives in chunks. Below is how you can utilize FreeRTOS Stream Buffers to solve your problem.
Why Use Stream Buffers?
- Efficient Data Handling: Stream buffers automatically handle data storage and retrieval, simplifying buffer management.
- Thread-Safe: They are designed to be used in both ISRs and tasks, ensuring safe access without additional synchronization.
- Dynamic Sizing: They can grow dynamically (if configured as a message buffer) or wrap around (if configured as a circular buffer).
Implementation Steps
1. Create a Stream Buffer
Initialize a stream buffer to store incoming UART data.
#define STREAM_BUFFER_SIZE 256
StaticStreamBuffer_t xStaticStreamBufferStruct;
uint8_t ucStaticStreamBufferStorage[STREAM_BUFFER_SIZE];
StreamBufferHandle_t xStreamBuffer = xStreamBufferCreateStatic(
STREAM_BUFFER_SIZE, // Total bytes in the buffer
1, // Trigger level (not used here)
ucStaticStreamBufferStorage,
&xStaticStreamBufferStruct);
2. UART Data Reception (ISR or Callback)
In the DataReceived event, send the received data directly to the stream buffer.
void DataReceived(uint8_t *data, uint16_t length) {
size_t bytesSent = xStreamBufferSendFromISR(xStreamBuffer, data, length, NULL);
if (bytesSent != length) {
// Handle buffer overflow (optional)
}
}
3. Packet Reassembly Task
Create a task that reads data from the stream buffer, looks for STX and ETX, and reassembles packets.
void PacketReassemblyTask(void *pvParameters) {
uint8_t byte;
PacketState currentState = WAITING_FOR_STX;
uint8_t packet[MAX_PACKET_SIZE];
uint16_t packetIndex = 0;
TickType_t lastStxTime = xTaskGetTickCount();
while (1) {
// Receive a byte from the stream buffer with a timeout
if (xStreamBufferReceive(xStreamBuffer, &byte, sizeof(byte), pdMS_TO_TICKS(1000))) {
switch (currentState) {
case WAITING_FOR_STX:
if (byte == STX) {
currentState = COLLECTING_PACKET;
packetIndex = 0;
lastStxTime = xTaskGetTickCount();
}
break;
case COLLECTING_PACKET:
packet[packetIndex++] = byte;
if (byte == ETX) {
HandleCompletePacket(packet, packetIndex);
currentState = WAITING_FOR_STX;
}
break;
}
} else {
// Timeout: Check if waiting for ETX and discard incomplete packet
if (currentState == COLLECTING_PACKET && (xTaskGetTickCount() - lastStxTime > pdMS_TO_TICKS(1000))) {
currentState = WAITING_FOR_STX;
// Optionally, log or handle the discarded packet
}
}
}
}
4. Error Handling and Timeout
- Timeout: Use the receive timeout to detect if no data is arriving after
STX.
- Buffer Overflow: Monitor the return value of
xStreamBufferSendFromISR to detect if data is lost due to buffer overflow.
5. Handling Large Packets
If packets can be larger than the stream buffer size, configure the stream buffer as a message buffer (non-circular) and handle multi-part messages.
Advantages of Stream Buffers
- Simplified Buffer Management: No need to manually implement a circular buffer or handle buffer indices.
- ISR-Friendly: Optimized for use in both ISRs and tasks.
- Flexible: Can be configured as a circular buffer or a message buffer depending on needs.
Example with Message Buffer (Non-Circular)
If you expect packets to be larger than the buffer size, use a message buffer to store entire packets.
#define STREAM_BUFFER_SIZE 256
StreamBufferHandle_t xStreamBuffer = xStreamBufferCreate(
STREAM_BUFFER_SIZE, // Total bytes in the buffer
1); // Trigger level (not used here)
In this case, you would read data in chunks and reassemble packets based on STX and ETX.
Key Points
- Stream Buffer Type: Choose between a circular buffer (default) or a message buffer based on packet size and behavior.
- Timeout Handling: Use the receive timeout to implement a timeout mechanism for incomplete packets.
- Error Handling: Monitor buffer overflows and timeouts to ensure robustness.
By leveraging FreeRTOS Stream Buffers, you can significantly simplify the implementation while ensuring efficient and thread-safe data handling.