Simvik

Read several data identifiers in one request

ReadDataByIdentifier with a DID table: skip unknown identifiers, and pick the right negative response. A medium embedded C problem (UDS: data identifiers and…

medium · UDS: data identifiers and the fault memory · uds · automotive · diagnostics · table-driven · negative-response

Write read_dids(table, entries, req, len, resp, resp_max), the handler for UDS service 0x22 ReadDataByIdentifier. The request is 22 followed by one or more 2-byte identifiers (high byte first). table describes the entries identifiers this ECU has.

Write the response to resp and return its length.

  1. A request that is not 22 plus a whole number of identifiers (at least one, at most MAX_DIDS): 7F 22 13.
  2. Otherwise go through the identifiers in the order requested. For each one in the table, append the identifier and its data. Identifiers that are not in the table are skipped.
  3. If none of them was in the table: 7F 22 31.
  4. If the response would be longer than resp_max bytes: 7F 22 14 responseTooLong. Never write past resp_max (a negative response always fits: resp_max is at least 3).

The positive response starts with 62.

Starter code

uint16_t read_dids(const did_entry_t *table, size_t entries, const uint8_t *req, uint16_t len, uint8_t *resp, uint16_t resp_max) {
  (void)resp_max;
  uint16_t did = (uint16_t)((req[1] << 8) | req[2]);
  for (size_t k = 0; k < entries; k++) {
    if (table[k].did == did) {
      resp[0] = 0x62;
      resp[1] = req[1];
      resp[2] = req[2];
      memcpy(&resp[3], table[k].data, table[k].len);
      return (uint16_t)(3 + table[k].len);
    }
  }
  (void)len;
  resp[0] = 0x7F; resp[1] = 0x22; resp[2] = 0x31;
  return 3;
}

Example tests

One identifier

const uint8_t req[] = { 0x22, 0x01, 0x01 };
ask(req, sizeof req, 40);

Expected output:

62 01 01 2E E8

Two identifiers, in the order asked

const uint8_t req[] = { 0x22, 0xF1, 0x8C, 0xF1, 0x86 };
ask(req, sizeof req, 40);

Expected output:

62 F1 8C 54 45 30 30 34 32 F1 86 03

Learn it first

More UDS: data identifiers and the fault memory problems