PacketIO

PacketIO is a C++ library for framing packets sent or received over an Arduino Stream, such as Serial. It is distributed as a PlatformIO library.

The key feature of this library over other framing implementations, such as PacketSerial, it that it operates on streams. This means that if your application layer is able to produce or consume streams, you can push these streams right the way through your program. Put simply, this means you can send arbitrarily large packets, without having to worry about allocating buffers.

The example below shows a contrived case when streams are needed - it duplicates whatever packets come in, but it works no matter how large the incoming packet is:

#include <Arduino.h>
#include <cobs/Stream.h>
#include <cobs/Print.h>
using namespace packetio;

COBSPrint cobs_out(Serial);
COBSStream cobs_in(Serial);

void setup() {
    Serial.begin();
}

void loop() {
    // send a packet
    cobs_out.print("Starting packet duplicator");
    cobs_out.end();

    // duplicate bytes of every packet read
    while(true) {
        int c = cobs_in.read();
        if(c == COBSStream::EOP) {
            // incoming packet ended - end ours too
            cobs_out.end();
            cobs_in.next();
        }
        else if(c != COBSStream::EOF) {
            // got a byte - duplicate it
            cobs_out.write(c);
            cobs_out.write(c);
        }
    }
}