Add diag console probe (OBD-II mode 01/09 on 0x7DF); wiki: diagnostic polling, two sources
Firmware: - CANDriver::transmit(): the single sanctioned transmit path (single-shot, echoed as CANTX lines, TX_FAILED alert counted); CAN-task warnings now take the serial lock - DiagProbe module: `diag pids` supported-PID bitmap scan, `diag pid <hex>`, `diag vin`, `diag ecu`, `diag status`; ISO-TP reassembly with flow control; one request in flight, refused for 3 s after any foreign tester frame - Console dispatch chained via Tunables::setExtraCommandHandler() - CLAUDE.md and docs/UART_PROTOCOL.md updated Wiki: - New page obd-diagnostic-polling (broadcast vs polled, 0x6F1->0x612 addressing, Route A generic OBD PID table, Route B, test-day procedure, firmware probe) - New sources: google-ai-dde7m57-pids (clipping, unverified, 0x612 direction contradicted), dwr-335d-torque-pids (thread + raw/BMW 335d.csv decoded) - Clippings/ folder added to the schema (Obsidian Web Clipper, treated as raw/) - bmw-m57n-engine, can-bus-integration, open-questions, index, log updated
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
#include "modules/settings_manager.h"
|
||||
#include "modules/serial_lock.h"
|
||||
#include "modules/tunables.h"
|
||||
#include "modules/diag_probe.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
// Import shared data from UARTManager namespace
|
||||
@@ -339,9 +340,10 @@ static bool parseCANMessage(const twai_message_t& message) {
|
||||
*
|
||||
* @param message Received TWAI message
|
||||
*/
|
||||
static void emitRawFrame(const twai_message_t& message) {
|
||||
static void emitFrameLine(const char* prefix, const twai_message_t& message) {
|
||||
char buf[72];
|
||||
int n = snprintf(buf, sizeof(buf), "CANRAW,%lu,%03lX,%u,%u,",
|
||||
int n = snprintf(buf, sizeof(buf), "%s,%lu,%03lX,%u,%u,",
|
||||
prefix,
|
||||
(unsigned long)millis(),
|
||||
(unsigned long)message.identifier,
|
||||
(unsigned)(message.extd ? 1 : 0),
|
||||
@@ -370,9 +372,12 @@ static void handleRxMessage(twai_message_t& message) {
|
||||
|
||||
// Raw capture FIRST, before parse — logs every frame including unknown IDs
|
||||
if (g_raw_logging) {
|
||||
emitRawFrame(message);
|
||||
emitFrameLine("CANRAW", message);
|
||||
}
|
||||
|
||||
// Diagnostic replies (0x7E8..) and foreign-tester detection
|
||||
DiagProbe::onFrame(message);
|
||||
|
||||
// Auto-restart UART if it was stopped due to CAN timeout
|
||||
if (g_uart_auto_stopped) {
|
||||
ESP_LOGI("CANDrv", "✓ CAN messages resumed, auto-restarting UART");
|
||||
@@ -453,7 +458,8 @@ static bool initTWAI() {
|
||||
uint32_t alerts_to_enable = TWAI_ALERT_RX_DATA |
|
||||
TWAI_ALERT_ERR_PASS |
|
||||
TWAI_ALERT_BUS_ERROR |
|
||||
TWAI_ALERT_RX_QUEUE_FULL;
|
||||
TWAI_ALERT_RX_QUEUE_FULL |
|
||||
TWAI_ALERT_TX_FAILED;
|
||||
|
||||
if (twai_reconfigure_alerts(alerts_to_enable, NULL) != ESP_OK) {
|
||||
ESP_LOGE("CANDrv", "Failed to reconfigure alerts");
|
||||
@@ -537,14 +543,27 @@ static void canTask(void* parameter) {
|
||||
|
||||
// Handle error alerts
|
||||
if (alerts_triggered & TWAI_ALERT_ERR_PASS) {
|
||||
SerialLock::lock();
|
||||
ESP_LOGW("CANTask", "TWAI controller has become error passive");
|
||||
SerialLock::unlock();
|
||||
}
|
||||
if (alerts_triggered & TWAI_ALERT_BUS_ERROR) {
|
||||
twai_status_info_t status;
|
||||
twai_get_status_info(&status);
|
||||
SerialLock::lock();
|
||||
ESP_LOGW("CANTask", "Bus error detected (count: %d)", status.bus_error_count);
|
||||
SerialLock::unlock();
|
||||
g_can_stats.parse_errors++;
|
||||
}
|
||||
if (alerts_triggered & TWAI_ALERT_TX_FAILED) {
|
||||
// Single-shot frame got no ACK or hit a bus error: nobody is
|
||||
// listening on that ID, or the bus is unhappy. Not retried.
|
||||
g_can_stats.tx_failures++;
|
||||
SerialLock::lock();
|
||||
ESP_LOGW("CANTask", "TX failed (no ACK / bus error) - %lu so far",
|
||||
(unsigned long)g_can_stats.tx_failures);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
if (alerts_triggered & TWAI_ALERT_RX_QUEUE_FULL) {
|
||||
twai_status_info_t status;
|
||||
twai_get_status_info(&status);
|
||||
@@ -661,6 +680,30 @@ bool isActive() {
|
||||
return g_can_active;
|
||||
}
|
||||
|
||||
bool transmit(uint32_t id, const uint8_t* data, uint8_t len) {
|
||||
if (!g_can_active || data == NULL || len > 8 || id > 0x7FF) {
|
||||
g_can_stats.tx_failures++;
|
||||
return false;
|
||||
}
|
||||
twai_message_t m;
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.identifier = id;
|
||||
m.extd = 0;
|
||||
m.ss = 1; // single shot: never retransmit on error
|
||||
m.data_length_code = len;
|
||||
memcpy(m.data, data, len);
|
||||
|
||||
esp_err_t r = twai_transmit(&m, pdMS_TO_TICKS(20));
|
||||
if (r != ESP_OK) {
|
||||
g_can_stats.tx_failures++;
|
||||
ESP_LOGW("CANDrv", "twai_transmit(0x%03lX) failed: %s", (unsigned long)id, esp_err_to_name(r));
|
||||
return false;
|
||||
}
|
||||
g_can_stats.messages_transmitted++;
|
||||
emitFrameLine("CANTX", m);
|
||||
return true;
|
||||
}
|
||||
|
||||
void setRawLogging(bool enabled) {
|
||||
g_raw_logging = enabled;
|
||||
ESP_LOGI("CANDrv", "Raw frame logging %s", enabled ? "ENABLED" : "disabled");
|
||||
|
||||
+5
-1
@@ -12,6 +12,7 @@
|
||||
#include "modules/serial_lock.h" // Global serial write mutex
|
||||
#include "modules/tunables.h" // Gauge calibration + alert thresholds (NVS, serial console)
|
||||
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B
|
||||
#include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter
|
||||
|
||||
// ============================================================================
|
||||
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
|
||||
@@ -142,6 +143,8 @@ void setup()
|
||||
|
||||
// Tunables (gauge calibration, alert thresholds) - before CAN/UART start
|
||||
Tunables::init();
|
||||
DiagProbe::init();
|
||||
Tunables::setExtraCommandHandler(DiagProbe::handleCommand);
|
||||
|
||||
// Load saved switch states from NVS
|
||||
ESP_LOGI("MAIN", "Loading saved switch states from NVS...");
|
||||
@@ -207,8 +210,9 @@ void loop()
|
||||
// (Settings screen gets destroyed/recreated when swiping)
|
||||
UIStateManager::applySavedStatesToUI();
|
||||
|
||||
// Serial console for the gauge tunables (cfg ...)
|
||||
// Serial console: gauge tunables (cfg ...) and the diagnostic probe (diag ...)
|
||||
Tunables::pollSerial();
|
||||
DiagProbe::tick();
|
||||
|
||||
DrivelineScreen::tick();
|
||||
TuningScreen::tick();
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
/*
|
||||
* 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 <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <string.h>
|
||||
|
||||
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 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 = 64;
|
||||
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, g_req_pid = 0;
|
||||
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
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/** Build and send one single-frame request. Caller holds no lock. */
|
||||
static bool sendRequest(uint8_t mode, uint8_t pid) {
|
||||
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;
|
||||
}
|
||||
|
||||
uint8_t f[8];
|
||||
memset(f, PAD_BYTE, sizeof(f));
|
||||
f[0] = 0x02; // ISO-TP single frame, 2 bytes
|
||||
f[1] = mode;
|
||||
f[2] = pid;
|
||||
|
||||
lock();
|
||||
g_state = ST_WAITING;
|
||||
g_req_mode = mode;
|
||||
g_req_pid = pid;
|
||||
g_deadline_ms = now + REPLY_TIMEOUT_MS;
|
||||
g_replies_this_req = 0;
|
||||
g_rx_active = false;
|
||||
g_requests++;
|
||||
g_tx_fail_at_send = CANDriver::getStats().tx_failures;
|
||||
unlock();
|
||||
|
||||
if (!CANDriver::transmit(OBD_FUNCTIONAL_ID, f, sizeof(f))) {
|
||||
lock();
|
||||
g_state = ST_IDLE;
|
||||
unlock();
|
||||
print("[diag] transmit failed (TWAI queue)");
|
||||
return false;
|
||||
}
|
||||
print("[diag] -> 0x7DF %02X %02X", mode, pid);
|
||||
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));
|
||||
f[0] = 0x30; // FC, ContinueToSend
|
||||
f[1] = 0x00; // block size: all
|
||||
f[2] = 0x00; // STmin: 0 ms
|
||||
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 * 24 + 1];
|
||||
hexdump(hex, sizeof(hex), p, n > 24 ? 24 : n);
|
||||
g_replies++;
|
||||
|
||||
if (n >= 3 && p[0] == 0x7F) {
|
||||
// negative response: 7F <mode> <NRC>
|
||||
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 > 24 ? " ..." : "");
|
||||
|
||||
if (n < 2 || p[0] != (uint8_t)(g_req_mode + 0x40) || p[1] != g_req_pid) {
|
||||
print("[diag] (unexpected payload for request %02X %02X)", g_req_mode, g_req_pid);
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_req_mode == 0x01 && (g_req_pid & 0x1F) == 0 && n >= 6) {
|
||||
// supported-PID bitmap: 41 <block> 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 <pid> <count> <ascii...>
|
||||
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 (id < OBD_RESP_FIRST || id > OBD_RESP_LAST) return;
|
||||
if (m.data_length_code == 0) return;
|
||||
|
||||
lock();
|
||||
if (g_state != ST_WAITING) { unlock(); return; }
|
||||
|
||||
uint8_t pci = m.data[0] >> 4;
|
||||
const uint8_t* d = m.data;
|
||||
uint8_t dlc = m.data_length_code;
|
||||
|
||||
if (pci == 0x0) {
|
||||
// single frame
|
||||
size_t len = d[0] & 0x0F;
|
||||
if (len > 0 && len + 1 <= dlc) handleReply(id, d + 1, len);
|
||||
} else if (pci == 0x1) {
|
||||
// first frame: 1L LL data[6]
|
||||
if (!g_rx_active && dlc >= 2) {
|
||||
g_rx_expected = ((size_t)(d[0] & 0x0F) << 8) | d[1];
|
||||
if (g_rx_expected > MAX_PAYLOAD) g_rx_expected = MAX_PAYLOAD;
|
||||
g_rx_len = 0;
|
||||
for (uint8_t i = 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[7]
|
||||
if (g_rx_active && id == g_rx_id && (d[0] & 0x0F) == (g_rx_seq & 0x0F)) {
|
||||
for (uint8_t i = 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) {
|
||||
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 <hex> one mode-01 request, e.g. `diag pid 0C` (rpm), `diag pid 70` (boost)");
|
||||
print("diag vin mode 09 PID 02 - VIN");
|
||||
print("diag ecu mode 09 PID 0A - ECU name");
|
||||
print("diag status counters, responders, tester guard");
|
||||
print("Sends on 0x7DF 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[4] = {0};
|
||||
int argc = 0;
|
||||
for (char* tok = strtok(buf, " \t"); tok && argc < 4; 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; }
|
||||
|
||||
help();
|
||||
return true;
|
||||
}
|
||||
|
||||
void init() {
|
||||
if (!g_mutex) g_mutex = xSemaphoreCreateMutex();
|
||||
}
|
||||
|
||||
} // namespace DiagProbe
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Diagnostic Probe Module
|
||||
*
|
||||
* The ONLY place this firmware transmits on the PT-CAN. Sends single OBD-II
|
||||
* (SAE J1979 / ISO 15031-5) requests on the functional address 0x7DF and
|
||||
* reassembles the ISO 15765-2 replies from 0x7E8..0x7EF, to find out whether
|
||||
* the DDE answers generic OBD on this bus and which PIDs it offers — the first
|
||||
* step of wiki/pages/obd-diagnostic-polling.md ("Route A").
|
||||
*
|
||||
* Strictly on demand: nothing is sent unless a `diag ...` console command asks
|
||||
* for it, one request is in flight at a time, frames go out single-shot (no
|
||||
* retransmit storms if nobody ACKs), and requests are refused while another
|
||||
* tester (a scan tool on 0x7DF / 0x7E0..7 / 0x6F1) has been seen recently.
|
||||
*
|
||||
* Console (USB serial, same line reader as `cfg`):
|
||||
* diag pids scan the mode-01 supported-PID bitmaps (00, 20, 40, ...)
|
||||
* diag pid <hex> one mode-01 request, e.g. `diag pid 0C` (rpm)
|
||||
* diag vin mode 09 PID 02 — VIN (identifies the donor)
|
||||
* diag ecu mode 09 PID 0A — ECU name string
|
||||
* diag status counters, responders seen, tester-guard timer
|
||||
* diag help
|
||||
*
|
||||
* Every frame we send is echoed on the console as
|
||||
* CANTX,<ts_ms>,<id_hex>,0,<dlc>,<data_hex>
|
||||
* — the same shape as CANRAW — so a capture holds both halves of every exchange.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "driver/twai.h"
|
||||
|
||||
namespace DiagProbe {
|
||||
|
||||
/** Create the state mutex. Call once in setup(), before the CAN task starts. */
|
||||
void init();
|
||||
|
||||
/**
|
||||
* Execute one console line beginning with "diag".
|
||||
* @return true if the line was a diag command (even if it was rejected)
|
||||
*/
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
/** Timeouts and scan sequencing. Call from loop(). */
|
||||
void tick();
|
||||
|
||||
/**
|
||||
* Feed every received CAN frame here (called from the CAN task). Cheap for
|
||||
* IDs outside the diagnostic range.
|
||||
*/
|
||||
void onFrame(const twai_message_t& m);
|
||||
|
||||
} // namespace DiagProbe
|
||||
@@ -22,6 +22,7 @@ static SemaphoreHandle_t g_mutex = NULL;
|
||||
|
||||
static char g_line[96];
|
||||
static size_t g_line_len = 0;
|
||||
static bool (*g_extra_handler)(const char*) = NULL;
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPERS
|
||||
@@ -88,6 +89,7 @@ static void help() {
|
||||
print(" tach_en temp_en coolant_hot gearbox_hot batt_low(x100)");
|
||||
print("cfg override off | rpm <n> | duty <n> | both <rpm> <duty>");
|
||||
print("cfg reset back to defaults");
|
||||
print("diag help OBD-II diagnostic probe (transmits on the bus)");
|
||||
}
|
||||
|
||||
static bool setField(const char* name, long v) {
|
||||
@@ -241,14 +243,18 @@ bool handleCommand(const char* line) {
|
||||
return true;
|
||||
}
|
||||
|
||||
void setExtraCommandHandler(bool (*handler)(const char* line)) {
|
||||
g_extra_handler = handler;
|
||||
}
|
||||
|
||||
void pollSerial() {
|
||||
while (Serial.available()) {
|
||||
char c = (char)Serial.read();
|
||||
if (c == '\r' || c == '\n') {
|
||||
if (g_line_len > 0) {
|
||||
g_line[g_line_len] = 0;
|
||||
if (!handleCommand(g_line)) {
|
||||
print("[console] unknown command '%s' (try 'cfg help')", g_line);
|
||||
if (!handleCommand(g_line) && !(g_extra_handler && g_extra_handler(g_line))) {
|
||||
print("[console] unknown command '%s' (try 'cfg help' or 'diag help')", g_line);
|
||||
}
|
||||
g_line_len = 0;
|
||||
}
|
||||
|
||||
@@ -54,8 +54,14 @@ bool handleCommand(const char* line);
|
||||
|
||||
/**
|
||||
* Non-blocking: read pending bytes from Serial, dispatch complete lines to
|
||||
* handleCommand(). Call from loop().
|
||||
* handleCommand(), then to the extra handler (if registered). Call from loop().
|
||||
*/
|
||||
void pollSerial();
|
||||
|
||||
/**
|
||||
* Register a second console command handler (e.g. DiagProbe::handleCommand)
|
||||
* that gets lines `cfg` does not recognise. Returns true if it consumed the line.
|
||||
*/
|
||||
void setExtraCommandHandler(bool (*handler)(const char* line));
|
||||
|
||||
} // namespace Tunables
|
||||
|
||||
Reference in New Issue
Block a user