Simvik

Split a message into ISO-TP frames

Produce the single frame, or the first frame and consecutive frames, that carry a message. A medium embedded C problem (ISO-TP: frames and segmentation), run…

medium · ISO-TP: frames and segmentation · isotp · can · automotive · segmentation

Write isotp_segment(msg, len, frames), which fills frames with the 8-byte CAN frames that carry msg[0..len) and returns how many there are.

  • 7 bytes or fewer: one single frame. Byte 0 is the length; the message follows.
  • 8 to 4095 bytes: a first frame, 1L LL (the 12-bit length, high nibble first) and the first 6 bytes; then consecutive frames, 2N and up to 7 bytes each. N is 1 for the first consecutive frame and counts up, wrapping from 15 to 0.
  • Unused bytes of any frame are the padding byte 0xCC.
  • A length of 0, or more than 4095, cannot be sent: return 0.

(The flow control frame that a real sender waits for after the first frame is the receiver's to send: it is not part of this problem.)

Starter code

int isotp_segment(const uint8_t *msg, uint16_t len, uint8_t frames[][8]) {
  int count = 0;
  for (uint16_t sent = 0; sent < len; sent += 7) {
    uint16_t n = len - sent > 7 ? 7 : len - sent;
    frames[count][0] = (uint8_t)n;
    memcpy(&frames[count][1], &msg[sent], n);
    count++;
  }
  return count;
}

Example tests

A short message is one padded frame

const uint8_t m[2] = { 0x3E, 0x00 };
int n = isotp_segment(m, 2, frames);
printf("%d frame(s)\n", n);
for (int i = 0; i < n; i++) row(i);

Expected output:

1 frame(s)
  0: 02 3E 00 CC CC CC CC CC

A 20-byte response

uint8_t m[20];
fill(m, 20);
int n = isotp_segment(m, 20, frames);
printf("%d frame(s)\n", n);
for (int i = 0; i < n; i++) row(i);

Expected output:

3 frame(s)
  0: 10 14 01 02 03 04 05 06
  1: 21 07 08 09 0A 0B 0C 0D
  2: 22 0E 0F 10 11 12 13 14

Learn it first

More ISO-TP: frames and segmentation problems