Simvik

Reassemble a segmented message

An ISO-TP receiver: first and consecutive frames in, a complete message or nothing out. A hard embedded C problem (ISO-TP: flow control and timing), run and…

hard · ISO-TP: flow control and timing · isotp · can · automotive · state-machine · robustness

Write isotp_rx(r, d, dlc): the receiving half of ISO-TP for one connection. It is given each CAN frame that arrives (dlc bytes in d) and returns what the caller must do. r starts zeroed.

FrameDo
Single frame 0LIf L is 1 to 7 and fits in the frame: end any reception in progress, copy the message to buf, set len, return RX_MESSAGE. Otherwise ignore the frame.
First frame 1L LLIgnore it unless dlc is 8 and the 12-bit length is at least 8. Otherwise end any reception in progress; if the length is more than RX_BUF return RX_FC_OVERFLOW; else store its 6 bytes, expect sequence number 1, and return RX_FC_CONTINUE.
Consecutive frame 2NIgnore it when no reception is in progress. A wrong N ends the reception (the message is lost). Otherwise take up to 7 bytes, as many as the message still needs (ignore the frame if it holds fewer than that), and count N on, 15 wrapping to 0. When the message is complete, return RX_MESSAGE.
anything else, or dlc 0Ignore.

"Ignore" means return RX_NOTHING and change nothing. Never write past buf.

Starter code

rx_result_t isotp_rx(isotp_rx_t *r, const uint8_t *d, uint8_t dlc) {
  uint8_t type = d[0] >> 4, low = d[0] & 0x0F;
  (void)dlc;
  if (type == 0) {
    memcpy(r->buf, &d[1], low);
    r->len = low;
    return RX_MESSAGE;
  }
  if (type == 1) {
    r->len = (uint16_t)((low << 8) | d[1]);
    memcpy(r->buf, &d[2], 6);
    r->got = 6;
    r->active = true;
    return RX_FC_CONTINUE;
  }
  if (type == 2) {
    memcpy(&r->buf[r->got], &d[1], 7);
    r->got += 7;
    if (r->got >= r->len) return RX_MESSAGE;
  }
  return RX_NOTHING;
}

Example tests

A single frame

const uint8_t sf[8] = { 0x03, 0x22, 0xF1, 0x90, 0xCC, 0xCC, 0xCC, 0xCC };
feed(sf, 8);

Expected output:

03.. -> message of 3: 22 F1 90

Ten bytes in two frames

const uint8_t ff[8] = { 0x10, 0x0A, 1, 2, 3, 4, 5, 6 };
const uint8_t cf[8] = { 0x21, 7, 8, 9, 10, 0xCC, 0xCC, 0xCC };
feed(ff, 8);
feed(cf, 8);

Expected output:

10.. -> flow control: continue
21.. -> message of 10: 01 02 03 04 05 06 07 08 09 0A

Learn it first

More ISO-TP: flow control and timing problems

  • Decode STmin · Turn the STmin byte of a flow control frame into microseconds, reserved values included.