Enhancing Serial Port Data Reception with Frame-Based Buffering

The CustomSerialPort library captures serial data within a specified time window (default 128ms) to facilitate response-based communication. While effective for intermittent data transmission, this approach may fail to capture complete frames when dealing with continuous data streams, such as those from certain weighing scales operating in periodic reporting modes.

To address this limitation, an enhanced version introduces frame-aware buffering capabilities. By defining a minimum frame length, the system can determine when sufficient data has been received to constitute at least one complete message. When the accumulated bytes exceed this threshold, the buffered data is dispatched via event notification to registered observers, who can then apply framing protocols including header/trailer detection and checksum validation.

Implementation Details

Constructor Configuration

public SerialPortFrameHandler(
    IDataProcessor processor,
    int frameThreshold)
    : this()
{
    _processor = processor;
    int capacity = frameThreshold < 4096 ? 4096 : frameThreshold * 2;
    _receiveBuffer = new byte[capacity];
    _frameSize = frameThreshold;
}

Message Processing Logic

#region DataHandling

private void ProcessIncoming(byte[] incoming)
{
    if (_position + incoming.Length > _receiveBuffer.Length)
    {
        ClearBuffer();
        return;
    }

    Array.Copy(incoming, 0, _receiveBuffer, _position, incoming.Length);
    _position += incoming.Length;
}

private void EvaluateAndDispatch()
{
    bool sizeCondition = _frameSize > 0 && _position >= _frameSize;
    bool timerCondition = _frameSize == 0 && (Environment.TickCount - _latestTick) >= _interval;
    
    if (sizeCondition || timerCondition)
    {
        byte[] payload = new byte[_position];
        Array.Copy(_receiveBuffer, 0, payload, 0, _position);
        _processor?.OnDataReceived(payload);
        ClearBuffer();
    }

    if (timerCondition)
    {
        _latestTick = Environment.TickCount;
    }
}

private void ClearBuffer()
{
    _position = 0;
}

#endregion

Tags: serial-port data-buffering frame-processing embedded-systems communication-protocols

Posted on Wed, 14 Oct 2026 16:33:42 +0000 by rabab.orthalis