/* * Diagnostic Probe Module Implementation * * See diag_probe.h. Threading: onFrame() runs in the CAN task, everything else * in loop(); g_mutex guards the shared state. Transmission goes through * CANDriver::transmit() and nowhere else. */ #include "diag_probe.h" #include "serial_lock.h" #include "drivers/can_driver.h" #include #include #include namespace DiagProbe { // ============================================================================ // CONSTANTS // ============================================================================ static const uint32_t OBD_FUNCTIONAL_ID = 0x7DF; // "any emissions ECU" static const uint32_t OBD_RESP_FIRST = 0x7E8; // responders 0x7E8..0x7EF static const uint32_t OBD_RESP_LAST = 0x7EF; // physical request = response - 8 static const uint32_t OBD_REQ_FIRST = 0x7E0; static const uint32_t OBD_REQ_LAST = 0x7E7; static const uint32_t BMW_TESTER_ID = 0x6F1; // BMW KWP/UDS tester (Launch, INPA) static const uint32_t BMW_RX_BASE = 0x600; // an ECU replies on 0x600 + its address static const uint8_t BMW_ADDR_DDE = 0x12; // engine ECU address (reply on 0x612) static const uint32_t REPLY_TIMEOUT_MS = 500; // P2 is 50 ms; be generous static const uint32_t LINGER_MS = 150; // after the first reply, wait for other ECUs static const uint32_t PENDING_EXTRA_MS = 2000; // NRC 0x78 "response pending" static const uint32_t TESTER_GUARD_MS = 3000; // refuse to send this soon after a foreign tester static const uint8_t PAD_BYTE = 0x00; static const size_t MAX_PAYLOAD = 384; // KWP ident replies can be long static const int MAX_RESPONDERS = 4; static const int SCAN_BLOCKS = 8; // 0x00, 0x20, ... 0xE0 // ============================================================================ // STATE // ============================================================================ enum state_t { ST_IDLE, ST_WAITING }; struct responder_t { uint32_t id; uint32_t bitmap[SCAN_BLOCKS]; bool have[SCAN_BLOCKS]; }; static SemaphoreHandle_t g_mutex = NULL; static state_t g_state = ST_IDLE; static uint8_t g_req_mode = 0; static int g_req_pid = 0; // -1 = request had no PID/sub byte (e.g. mode 03) static bool g_bmw = false; // current request is BMW-addressed on 0x6F1 static uint8_t g_bmw_target = 0; // its target ECU address (reply on 0x600+addr) static uint32_t g_deadline_ms = 0; static uint8_t g_replies_this_req = 0; // ISO-TP reassembly (one multi-frame reply at a time; other ECUs' single frames // still get through while it is in progress) static uint32_t g_rx_id = 0; static uint8_t g_rx_buf[MAX_PAYLOAD]; static size_t g_rx_len = 0, g_rx_expected = 0; static uint8_t g_rx_seq = 0; static bool g_rx_active = false; // supported-PID scan static bool g_scan_active = false; static int g_scan_block = 0; static responder_t g_resp[MAX_RESPONDERS]; static int g_resp_count = 0; // foreign tester guard + counters static uint32_t g_last_tester_ms = 0; static uint32_t g_last_tester_id = 0; static uint32_t g_requests = 0, g_replies = 0, g_timeouts = 0, g_negatives = 0; static uint32_t g_tx_fail_at_send = 0; // CANDriver tx_failures when the request went out static bool g_last_req_unacked = false; // ============================================================================ // HELPERS // ============================================================================ static void lock() { if (g_mutex) xSemaphoreTake(g_mutex, portMAX_DELAY); } static void unlock() { if (g_mutex) xSemaphoreGive(g_mutex); } static void print(const char* fmt, ...) { char buf[220]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); SerialLock::lock(); Serial.println(buf); SerialLock::unlock(); } static void hexdump(char* out, size_t out_sz, const uint8_t* p, size_t n) { size_t w = 0; for (size_t i = 0; i < n && w + 3 < out_sz; i++) { w += snprintf(out + w, out_sz - w, "%02X ", p[i]); } if (w > 0) out[w - 1] = 0; else out[0] = 0; } /** Names for the mode-01 PIDs worth recognising in a scan summary. */ static const char* pidName(uint8_t pid) { switch (pid) { case 0x01: return "monitor status"; case 0x04: return "engine load"; case 0x05: return "coolant temp"; case 0x0B: return "MAP (1 byte, caps 255 kPa)"; case 0x0C: return "rpm"; case 0x0D: return "vehicle speed"; case 0x0F: return "intake air temp"; case 0x10: return "MAF"; case 0x11: return "throttle"; case 0x1F: return "run time"; case 0x21: return "distance with MIL"; case 0x23: return "fuel rail pressure"; case 0x2C: return "EGR commanded"; case 0x33: return "barometric"; case 0x42: return "module voltage"; case 0x46: return "ambient air temp"; case 0x4C: return "throttle commanded"; case 0x5C: return "oil temp"; case 0x5E: return "fuel rate"; case 0x62: return "actual torque %"; case 0x63: return "reference torque"; case 0x70: return "boost pressure control"; case 0x73: return "exhaust pressure"; case 0x78: return "EGT bank 1"; case 0x7A: return "DPF differential pressure"; case 0x83: return "NOx sensor"; default: return NULL; } } /** Human decode of a mode-01 reply payload p = [pid, A, B, ...], n bytes. */ static void decodePid(uint8_t pid, const uint8_t* d, size_t n) { // d points at A; n = number of data bytes after the PID echo #define NEED(k) if (n < (k)) return #define U16(i) ((uint16_t)((d[i] << 8) | d[(i) + 1])) switch (pid) { case 0x05: NEED(1); print("[diag] coolant = %d C", (int)d[0] - 40); break; case 0x0B: NEED(1); print("[diag] MAP = %u kPa abs%s", d[0], d[0] == 255 ? " (clipped)" : ""); break; case 0x0C: NEED(2); print("[diag] rpm = %u", U16(0) / 4); break; case 0x0D: NEED(1); print("[diag] speed = %u km/h", d[0]); break; case 0x0F: NEED(1); print("[diag] intake air = %d C", (int)d[0] - 40); break; case 0x10: NEED(2); print("[diag] MAF = %u.%02u g/s", U16(0) / 100, U16(0) % 100); break; case 0x11: NEED(1); print("[diag] throttle = %u %%", (unsigned)d[0] * 100 / 255); break; case 0x23: NEED(2); print("[diag] rail pressure = %lu kPa", (unsigned long)U16(0) * 10); break; case 0x33: NEED(1); print("[diag] baro = %u kPa", d[0]); break; case 0x42: NEED(2); print("[diag] module voltage = %u.%03u V", U16(0) / 1000, U16(0) % 1000); break; case 0x46: NEED(1); print("[diag] ambient = %d C", (int)d[0] - 40); break; case 0x5C: NEED(1); print("[diag] oil temp = %d C", (int)d[0] - 40); break; case 0x5E: NEED(2); print("[diag] fuel rate = %u.%02u L/h", U16(0) / 20, (U16(0) % 20) * 5); break; case 0x62: NEED(1); print("[diag] actual torque = %d %%", (int)d[0] - 125); break; case 0x63: NEED(2); print("[diag] reference torque = %u Nm", U16(0)); break; case 0x70: NEED(5); // A = support bits; B,C commanded; D,E actual; x0.03125 kPa print("[diag] boost commanded = %lu hPa abs, actual = %lu hPa abs (J1979 PID 70)", (unsigned long)U16(1) * 3125 / 10000, (unsigned long)U16(3) * 3125 / 10000); break; case 0x73: NEED(3); print("[diag] exhaust pressure bank1 = %lu hPa", (unsigned long)U16(1) / 10); break; case 0x78: NEED(3); { for (size_t s = 0; s < 4 && (size_t)(2 + 2 * s) < n; s++) { uint16_t raw = U16(1 + 2 * s); print("[diag] EGT sensor %u = %d.%u C", (unsigned)s + 1, (int)raw / 10 - 40, raw % 10); } break; } case 0x7A: NEED(3); print("[diag] DPF dP = %lu Pa", (unsigned long)U16(1) * 10); break; default: break; } #undef NEED #undef U16 } static responder_t* findResponder(uint32_t id, bool create) { for (int i = 0; i < g_resp_count; i++) { if (g_resp[i].id == id) return &g_resp[i]; } if (!create || g_resp_count >= MAX_RESPONDERS) return NULL; responder_t* r = &g_resp[g_resp_count++]; memset(r, 0, sizeof(*r)); r->id = id; return r; } // ---------------------------------------------------------------------------- // Transmit // ---------------------------------------------------------------------------- /** Common preconditions for any transmit; prints the refusal reason. */ static bool clearToSend() { if (!CANDriver::isActive()) { print("[diag] refused: CAN is not running"); return false; } uint32_t now = millis(); lock(); bool busy = (g_state != ST_IDLE); uint32_t since_tester = now - g_last_tester_ms; bool tester = (g_last_tester_ms != 0) && (since_tester < TESTER_GUARD_MS); uint32_t tester_id = g_last_tester_id; unlock(); if (busy) { print("[diag] refused: a request is already in flight"); return false; } if (tester) { print("[diag] refused: another tester is polling (0x%03lX seen %lu ms ago) - unplug the scan tool", (unsigned long)tester_id, (unsigned long)since_tester); return false; } return true; } /** Arm the waiting state. Caller sends the frame right after. */ static void armRequest(uint8_t mode, int pid, bool bmw, uint8_t target) { lock(); g_state = ST_WAITING; g_bmw = bmw; g_bmw_target = target; g_req_mode = mode; g_req_pid = pid; g_deadline_ms = millis() + REPLY_TIMEOUT_MS; g_replies_this_req = 0; g_rx_active = false; g_requests++; g_tx_fail_at_send = CANDriver::getStats().tx_failures; unlock(); } /** Build and send one single-frame OBD request on 0x7DF. pid < 0 = mode only. */ static bool sendRequest(uint8_t mode, int pid) { if (!clearToSend()) return false; uint8_t f[8]; memset(f, PAD_BYTE, sizeof(f)); if (pid < 0) { f[0] = 0x01; // ISO-TP single frame, 1 byte (e.g. mode 03) f[1] = mode; } else { f[0] = 0x02; // ISO-TP single frame, 2 bytes f[1] = mode; f[2] = (uint8_t)pid; } armRequest(mode, pid, false, 0); if (!CANDriver::transmit(OBD_FUNCTIONAL_ID, f, sizeof(f))) { lock(); g_state = ST_IDLE; unlock(); print("[diag] transmit failed (TWAI queue)"); return false; } if (pid < 0) print("[diag] -> 0x7DF %02X", mode); else print("[diag] -> 0x7DF %02X %02X", mode, pid); return true; } /** * One single-frame BMW-addressed request on 0x6F1 (ISO 15765 extended * addressing: byte 0 = target ECU address, then normal ISO-TP). Read-only * services only - enforced here, not just at the console. */ static bool sendBmwRequest(uint8_t target, const uint8_t* req, size_t n) { static const uint8_t OK_SERVICES[] = {0x1A, 0x18, 0x21, 0x22}; if (n < 1 || n > 6) { print("[diag] BMW request must be 1..6 bytes (single frame)"); return false; } bool allowed = false; for (size_t i = 0; i < sizeof(OK_SERVICES); i++) { if (req[0] == OK_SERVICES[i]) allowed = true; } if (!allowed) { print("[diag] service 0x%02X refused - read-only services only (1A ident, 18 DTCs, 21/22 read data)", req[0]); return false; } if (!clearToSend()) return false; uint8_t f[8]; memset(f, PAD_BYTE, sizeof(f)); f[0] = target; f[1] = (uint8_t)n; memcpy(f + 2, req, n); armRequest(req[0], (n >= 2) ? (int)req[1] : -1, true, target); if (!CANDriver::transmit(BMW_TESTER_ID, f, sizeof(f))) { lock(); g_state = ST_IDLE; unlock(); print("[diag] transmit failed (TWAI queue)"); return false; } char hex[3 * 6 + 1]; hexdump(hex, sizeof(hex), req, n); print("[diag] -> 0x6F1 [%02X] %s (reply expected on 0x%03lX)", target, hex, (unsigned long)(BMW_RX_BASE + target)); return true; } /** Flow control for a multi-frame reply: "send everything, no gaps". */ static void sendFlowControl(uint32_t responder_id) { uint8_t f[8]; memset(f, PAD_BYTE, sizeof(f)); if (g_bmw) { f[0] = g_bmw_target; // extended addressing: target first, then the FC f[1] = 0x30; // FC, ContinueToSend f[2] = 0x00; // block size: all f[3] = 0x00; // STmin: 0 ms CANDriver::transmit(BMW_TESTER_ID, f, sizeof(f)); return; } f[0] = 0x30; f[1] = 0x00; f[2] = 0x00; CANDriver::transmit(responder_id - 8, f, sizeof(f)); } // ---------------------------------------------------------------------------- // Reply handling (CAN task context) // ---------------------------------------------------------------------------- static void finishScanBlockIfPrimary(uint32_t id, const uint8_t* p, size_t n); /** A complete ISO-TP payload from `id`. Caller holds g_mutex. */ static void handleReply(uint32_t id, const uint8_t* p, size_t n) { char hex[3 * 48 + 1]; hexdump(hex, sizeof(hex), p, n > 48 ? 48 : n); g_replies++; if (n >= 3 && p[0] == 0x7F) { // negative response: 7F if (p[2] == 0x78) { print("[diag] <- 0x%03lX %s (response pending, waiting)", (unsigned long)id, hex); g_deadline_ms = millis() + PENDING_EXTRA_MS; return; } g_negatives++; const char* why = (p[2] == 0x11) ? "service not supported" : (p[2] == 0x12) ? "sub-function / PID not supported" : (p[2] == 0x31) ? "request out of range" : (p[2] == 0x22) ? "conditions not correct" : "negative response"; print("[diag] <- 0x%03lX %s (%s, NRC 0x%02X)", (unsigned long)id, hex, why, p[2]); g_replies_this_req++; if (g_deadline_ms > millis() + LINGER_MS) g_deadline_ms = millis() + LINGER_MS; return; } g_replies_this_req++; if (g_deadline_ms > millis() + LINGER_MS) g_deadline_ms = millis() + LINGER_MS; print("[diag] <- 0x%03lX %s%s", (unsigned long)id, hex, n > 48 ? " ..." : ""); if (n < 1 || p[0] != (uint8_t)(g_req_mode + 0x40) || (!g_bmw && g_req_pid >= 0 && (n < 2 || p[1] != (uint8_t)g_req_pid))) { print("[diag] (unexpected payload for request %02X)", g_req_mode); return; } if (g_bmw) { // KWP ident replies are long and the header line clips at 48 bytes: // dump the whole payload, 16 bytes per line, hex + ascii. for (size_t i = 1; i < n; i += 16) { size_t k = (n - i < 16) ? (n - i) : 16; char hx[3 * 16 + 1]; hexdump(hx, sizeof(hx), p + i, k); char as[17]; for (size_t j = 0; j < k; j++) { as[j] = (p[i + j] >= 0x20 && p[i + j] < 0x7F) ? (char)p[i + j] : '.'; } as[k] = 0; print("[diag] +%03u %-48s |%s|", (unsigned)(i - 1), hx, as); } return; } if (g_req_mode == 0x03) { // 43 <2 bytes per DTC> uint8_t cnt = (n >= 2) ? p[1] : 0; print("[diag] %u stored DTC(s):", cnt); for (size_t i = 2; i + 1 < n; i += 2) { uint8_t a = p[i], b = p[i + 1]; if (a == 0 && b == 0) continue; print("[diag] %c%u%X%02X", "PCBU"[a >> 6], (a >> 4) & 3, a & 0x0F, b); } return; } if (g_req_mode == 0x01 && (g_req_pid & 0x1F) == 0 && n >= 6) { // supported-PID bitmap: 41 A B C D uint32_t bits = ((uint32_t)p[2] << 24) | ((uint32_t)p[3] << 16) | ((uint32_t)p[4] << 8) | p[5]; responder_t* r = findResponder(id, true); int blk = g_req_pid / 0x20; if (r && blk < SCAN_BLOCKS) { r->bitmap[blk] = bits; r->have[blk] = true; } char list[3 * 32 + 1]; size_t w = 0; for (int b = 31; b >= 0; b--) { if (bits & (1UL << b)) { w += snprintf(list + w, sizeof(list) - w, "%02X ", g_req_pid + (32 - b)); } } if (w) list[w - 1] = 0; else strcpy(list, "(none)"); print("[diag] PIDs %02X-%02X supported: %s", g_req_pid + 1, g_req_pid + 0x20, list); return; } if (g_req_mode == 0x01) { decodePid(g_req_pid, p + 2, n - 2); } else if (g_req_mode == 0x09 && n >= 3) { // 49 char s[MAX_PAYLOAD + 1]; size_t k = 0; for (size_t i = 3; i < n && k < MAX_PAYLOAD; i++) { s[k++] = (p[i] >= 0x20 && p[i] < 0x7F) ? (char)p[i] : '.'; } s[k] = 0; print("[diag] %s: \"%s\"", g_req_pid == 0x02 ? "VIN" : g_req_pid == 0x0A ? "ECU name" : "text", s); } } void onFrame(const twai_message_t& m) { if (m.extd) return; uint32_t id = m.identifier; // Foreign tester activity: our own frames are not looped back in NORMAL mode, // so anything on these IDs is somebody else's request. if (id == OBD_FUNCTIONAL_ID || (id >= OBD_REQ_FIRST && id <= OBD_REQ_LAST) || id == BMW_TESTER_ID) { lock(); g_last_tester_ms = millis(); g_last_tester_id = id; unlock(); return; } if (m.data_length_code == 0) return; bool maybe_obd = (id >= OBD_RESP_FIRST && id <= OBD_RESP_LAST); bool maybe_bmw = (id >= BMW_RX_BASE && id < BMW_RX_BASE + 0x100); if (!maybe_obd && !maybe_bmw) return; lock(); if (g_state != ST_WAITING) { unlock(); return; } const uint8_t* d = m.data; uint8_t dlc = m.data_length_code; uint8_t off = 0; // index of the ISO-TP PCI byte if (g_bmw) { // extended addressing: reply on 0x600+target, byte 0 = tester addr 0xF1 if (id != BMW_RX_BASE + g_bmw_target || dlc < 2 || d[0] != 0xF1) { unlock(); return; } off = 1; } else if (!maybe_obd) { unlock(); return; } uint8_t pci = d[off] >> 4; if (pci == 0x0) { // single frame size_t len = d[off] & 0x0F; if (len > 0 && off + 1 + len <= dlc) handleReply(id, d + off + 1, len); } else if (pci == 0x1) { // first frame: 1L LL data[...] if (!g_rx_active && dlc >= (uint8_t)(off + 2)) { g_rx_expected = ((size_t)(d[off] & 0x0F) << 8) | d[off + 1]; if (g_rx_expected > MAX_PAYLOAD) g_rx_expected = MAX_PAYLOAD; g_rx_len = 0; for (uint8_t i = off + 2; i < dlc && g_rx_len < g_rx_expected; i++) g_rx_buf[g_rx_len++] = d[i]; g_rx_id = id; g_rx_seq = 1; g_rx_active = true; g_deadline_ms = millis() + REPLY_TIMEOUT_MS; unlock(); sendFlowControl(id); // outside the lock: transmit() may block briefly return; } } else if (pci == 0x2) { // consecutive frame: 2N data[...] if (g_rx_active && id == g_rx_id && (d[off] & 0x0F) == (g_rx_seq & 0x0F)) { for (uint8_t i = off + 1; i < dlc && g_rx_len < g_rx_expected; i++) g_rx_buf[g_rx_len++] = d[i]; g_rx_seq++; g_deadline_ms = millis() + REPLY_TIMEOUT_MS; if (g_rx_len >= g_rx_expected) { g_rx_active = false; handleReply(id, g_rx_buf, g_rx_len); } } } unlock(); } // ---------------------------------------------------------------------------- // Sequencing (loop context) // ---------------------------------------------------------------------------- static void printScanSummary() { if (g_resp_count == 0) { if (g_last_req_unacked) { print("[diag] scan result: the request was NOT ACKED - no other node saw it."); print("[diag] Bench with no bus, wiring, or a bus fault. Says nothing about the ECU yet."); } else { print("[diag] scan result: frame ACKED but NO REPLY on 0x7E8-0x7EF. This ECU does not"); print("[diag] answer generic OBD-II on this bus (EOBD on K-line, or not at all) - Route B only."); } return; } for (int i = 0; i < g_resp_count; i++) { responder_t* r = &g_resp[i]; int total = 0; for (int b = 0; b < SCAN_BLOCKS; b++) { if (!r->have[b]) continue; for (int bit = 31; bit >= 0; bit--) if (r->bitmap[b] & (1UL << bit)) total++; } print("[diag] responder 0x%03lX (%s): %d mode-01 PIDs", (unsigned long)r->id, r->id == 0x7E8 ? "engine ECU" : r->id == 0x7E9 ? "usually transmission" : "other", total); for (int b = 0; b < SCAN_BLOCKS; b++) { if (!r->have[b]) continue; for (int bit = 31; bit >= 0; bit--) { if (!(r->bitmap[b] & (1UL << bit))) continue; uint8_t pid = (uint8_t)(b * 0x20 + (32 - bit)); const char* name = pidName(pid); if (name) print("[diag] %02X %s", pid, name); } } } print("[diag] next: `diag pid 0C` (rpm) to prove a data read, `diag vin` for the donor"); } void tick() { if (g_state == ST_IDLE) return; uint32_t now = millis(); lock(); if ((int32_t)(now - g_deadline_ms) < 0) { unlock(); return; } // request over bool got_reply = g_replies_this_req > 0; bool scan = g_scan_active; int block = g_scan_block; g_state = ST_IDLE; g_rx_active = false; if (!got_reply) g_timeouts++; // Did the TWAI controller report that nobody ACKed our single-shot frame? g_last_req_unacked = (CANDriver::getStats().tx_failures != g_tx_fail_at_send); bool unacked = g_last_req_unacked; bool send_next = false; if (scan) { // continue while the primary responder advertised the next block responder_t* primary = (g_resp_count > 0) ? &g_resp[0] : NULL; bool next_supported = primary && block < SCAN_BLOCKS && primary->have[block] && (primary->bitmap[block] & 1UL); if (got_reply && next_supported && block + 1 < SCAN_BLOCKS) { g_scan_block = block + 1; send_next = true; } else { g_scan_active = false; } } unlock(); if (!got_reply) { if (g_req_pid < 0) { print("[diag] no reply within %lu ms (request %02X)%s", (unsigned long)REPLY_TIMEOUT_MS, g_req_mode, unacked ? " - frame was not ACKed by any node" : " - frame was ACKed, ECU stayed silent"); } else { print("[diag] no reply within %lu ms (request %02X %02X)%s", (unsigned long)REPLY_TIMEOUT_MS, g_req_mode, g_req_pid, unacked ? " - frame was not ACKed by any node" : " - frame was ACKed, ECU stayed silent"); } } if (scan) { if (send_next) { sendRequest(0x01, (uint8_t)(g_scan_block * 0x20)); } else { printScanSummary(); } } } // ---------------------------------------------------------------------------- // Console // ---------------------------------------------------------------------------- static void help() { print("diag pids scan mode-01 supported-PID bitmaps (the Route A probe)"); print("diag pid one mode-01 request, e.g. `diag pid 0C` (rpm), `diag pid 70` (boost)"); print("diag dtc mode 03 - read stored generic DTCs"); print("diag vin mode 09 PID 02 - VIN"); print("diag ecu mode 09 PID 0A - ECU name"); print("diag ident [addr] BMW KWP `1A 80` ECU identification (default addr 12 = DDE, reply 0x612)"); print("diag bmw raw BMW request on 0x6F1, read-only services only (1A/18/21/22)"); print("diag raw on|off CANRAW frame logging (off = clean console during scans)"); print("diag status counters, responders, tester guard"); print("Sends on 0x7DF / 0x6F1 only, one request at a time; refused while a scan tool is polling."); } static void status() { lock(); uint32_t req = g_requests, rep = g_replies, to = g_timeouts, neg = g_negatives; uint32_t tms = g_last_tester_ms, tid = g_last_tester_id; state_t st = g_state; int nresp = g_resp_count; unlock(); can_stats_t cs = CANDriver::getStats(); print("[diag] state=%s requests=%lu replies=%lu timeouts=%lu negative=%lu | CAN tx=%lu tx_failed=%lu", st == ST_IDLE ? "idle" : "waiting", (unsigned long)req, (unsigned long)rep, (unsigned long)to, (unsigned long)neg, (unsigned long)cs.messages_transmitted, (unsigned long)cs.tx_failures); if (tms) { print("[diag] foreign tester 0x%03lX last seen %lu ms ago", (unsigned long)tid, (unsigned long)(millis() - tms)); } else { print("[diag] no foreign tester seen since boot"); } for (int i = 0; i < nresp; i++) { print("[diag] responder %d: 0x%03lX", i, (unsigned long)g_resp[i].id); } } bool handleCommand(const char* line) { char buf[64]; strncpy(buf, line, sizeof(buf) - 1); buf[sizeof(buf) - 1] = 0; char* argv[10] = {0}; int argc = 0; for (char* tok = strtok(buf, " \t"); tok && argc < 10; tok = strtok(NULL, " \t")) { argv[argc++] = tok; } if (argc == 0 || strcmp(argv[0], "diag") != 0) return false; if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; } if (!strcmp(argv[1], "status")) { status(); return true; } if (!strcmp(argv[1], "pids")) { lock(); bool busy = (g_state != ST_IDLE); if (!busy) { g_scan_active = true; g_scan_block = 0; g_resp_count = 0; memset(g_resp, 0, sizeof(g_resp)); } unlock(); if (busy) { print("[diag] refused: a request is already in flight"); return true; } print("[diag] scanning supported PIDs (mode 01, blocks 00/20/40/...)"); if (!sendRequest(0x01, 0x00)) { lock(); g_scan_active = false; unlock(); } return true; } if (!strcmp(argv[1], "pid") && argc == 3) { long v = strtol(argv[2], NULL, 16); if (v < 0 || v > 0xFF) { print("[diag] pid must be 00..FF (hex)"); return true; } sendRequest(0x01, (uint8_t)v); return true; } if (!strcmp(argv[1], "vin")) { sendRequest(0x09, 0x02); return true; } if (!strcmp(argv[1], "ecu")) { sendRequest(0x09, 0x0A); return true; } if (!strcmp(argv[1], "dtc")) { sendRequest(0x03, -1); return true; } if (!strcmp(argv[1], "raw") && argc == 3) { bool on = !strcmp(argv[2], "on"); CANDriver::setRawLogging(on); print("[diag] CANRAW logging %s", on ? "on" : "off"); return true; } if (!strcmp(argv[1], "ident")) { uint8_t target = BMW_ADDR_DDE; if (argc >= 3) target = (uint8_t)strtol(argv[2], NULL, 16); uint8_t req[2] = {0x1A, 0x80}; sendBmwRequest(target, req, sizeof(req)); return true; } if (!strcmp(argv[1], "bmw") && argc >= 4) { uint8_t target = (uint8_t)strtol(argv[2], NULL, 16); char hexs[13] = {0}; // up to 6 bytes = 12 hex chars size_t hl = 0; for (int i = 3; i < argc; i++) { for (const char* c = argv[i]; *c; c++) { if (hl >= sizeof(hexs) - 1) { print("[diag] too many bytes (max 6)"); return true; } hexs[hl++] = *c; } } if (hl == 0 || (hl % 2) != 0) { print("[diag] give whole hex bytes, e.g. `diag bmw 12 1A 80`"); return true; } uint8_t req[6]; size_t n = 0; for (size_t i = 0; i < hl; i += 2) { char b[3] = {hexs[i], hexs[i + 1], 0}; req[n++] = (uint8_t)strtol(b, NULL, 16); } sendBmwRequest(target, req, n); return true; } help(); return true; } void init() { if (!g_mutex) g_mutex = xSemaphoreCreateMutex(); } } // namespace DiagProbe