Simvik

Byte-stream frame parser

Reassemble frames from a byte stream one byte at a time. A hard embedded C problem (Protocols, framing and checksums), run and graded in the browser.

hard · Protocols, framing and checksums · state-machine · framing · uart

Bytes arrive one at a time from a UART interrupt, so the receiver must remember where it is in a frame. Frames are 0x7E, a length, the payload, and a checksum equal to the XOR of the length and payload bytes. A zero-initialised parser_t is waiting for a start byte.

Process one received byte and return true only when it completes a frame with a correct checksum; the payload and its length are then in p->payload and p->len.

  • WAIT_START: ignore everything except FRAME_START.
  • WAIT_LEN: a length above MAX_PAYLOAD is invalid; go back to WAIT_START. A length of 0 goes straight to WAIT_CHECKSUM.
  • READ_PAYLOAD: store bytes until len have arrived.
  • WAIT_CHECKSUM: compare, then return to WAIT_START whatever the result.

Starter code

bool parser_feed(parser_t *p, uint8_t byte) {
  switch (p->state) {
    case WAIT_START:
      break;
    case WAIT_LEN:
      break;
    case READ_PAYLOAD:
      break;
    case WAIT_CHECKSUM:
      break;
  }
  return false;
}

Example tests

One complete frame

parser_t p = { 0 };
const uint8_t rx[] = { 0x7E, 0x02, 0xAA, 0xBB, 0x13 };
printf("%d\n", feed_all(&p, rx, sizeof rx));

Expected output:

frame 2: AA BB
1

Noise before the start byte

parser_t p = { 0 };
const uint8_t rx[] = { 0x00, 0xFF, 0x7E, 0x01, 0x55, 0x54 };
printf("%d\n", feed_all(&p, rx, sizeof rx));

Expected output:

frame 1: 55
1

Learn it first

More Protocols, framing and checksums problems