7 Commits

Author SHA1 Message Date
julian 8ded9c2a08 Merge origin/main (27 commits from the other machine) with the Engine data screen
Firmware / build (push) Successful in 7m2s
All incoming changes kept as they were. Conflicts resolved by adding the
Engine-data pieces next to them:
- main.cpp: StatusOverlay::tick() and EngineScreen::tick()
- driveline_screen.cpp: both include sets; the old mismatch label stays
  removed (overlay owns it); the Engine data button moves to y 60, left of
  the diff-lock drawing, clear of the overlay band
- CLAUDE.md: Engine data bullet added; DiagProbe paragraph keeps its text
  plus the live-mode sentence
- wiki: all incoming log entries kept, the 2026-10-07 entry appended;
  open-questions #12 keeps the renamed line plus the 2026-10-07 update

Built clean locally (custom_sdkconfig core rebuild).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:51:53 +02:00
julian a28cbada59 Engine data screen: live rail, boost, charge-air temp, battery from the DDE
New screen (Engine data button on Driveline) polls the DDE with the
Launch's KWP `2C 10 <id>` reads: 00DF rail (bar = raw x 0.03, verified),
0091 boost (mbar = raw / 8), 16A8 charge-air temp, 0093 battery - the last
three provisional (one engine-off point each), tagged on screen with the
raw value shown for calibration.

DiagProbe live mode: `2C 10 15 E0` once, then the four reads in turn, one
in flight, ~100 ms apart, quiet on the console, paused by the foreign-tester
guard, stops 1.5 s after the screen stops asking. 2C stays forbidden from
the console. CANDriver::transmit gains an echo flag (live frames echoed only
with CANRAW on). Wiki: the three CANNY captures ingested, identifier table
and the no-password decision recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 19:48:00 +02:00
julian 9bfcd99dee Settings: diff-lock row's switch box aligned START - END collapsed its content width and clipped the Inverted switch
Firmware / build (push) Successful in 6m49s
2026-09-29 15:41:19 +02:00
julian b431cdfa16 Diff locks: per-board polarity ('Inverted' switch in the Settings row, 'difflock invert on|off', NVS difflock_inv) - in the car the lock wires carry 12 V while unlocked
Firmware / build (push) Successful in 7m6s
2026-09-29 15:18:23 +02:00
julian 0254bf19e9 Diff-lock drawing: wheelbase -20 %, same square tyres all round, locked axle's tyres filled, no caption text
Firmware / build (push) Successful in 7m5s
2026-09-29 10:53:48 +02:00
julian 01f7501ae7 Diff locks on the Driveline: chassis top view after the user's sketch (steered front wheels, prop shaft, rear axle); locked axle amber with an X on its diff, front-only red, caption
Firmware / build (push) Successful in 6m59s
2026-09-29 10:30:46 +02:00
julian 31ca44187e Diff-lock inputs: DI0 rear / DI1 front via CH422G EXIO0/EXIO5 (bank flipped to input per read), Settings > System switch default OFF, DIFF LOCK pills on the Driveline, 'difflock' console; wiki diff-lock-inputs
Firmware / build (push) Successful in 7m26s
2026-09-29 09:48:57 +02:00
25 changed files with 41474 additions and 22 deletions
+11 -4
View File
@@ -88,10 +88,12 @@ src/
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
link_peer.cpp # Inst. Cluster over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' console)
status_overlay.cpp # lv_layer_top() on EVERY screen: Wi-Fi chip top-right, blinking red / steady amber alert banner top-centre
diff_locks.cpp # Diff-lock inputs DI0 rear / DI1 front via CH422G EXIO0/EXIO5 ('difflock' console, Settings switch, default OFF)
settings_manager.cpp # NVS persistent storage
ui_state_manager.cpp # Debug flag (performance overlay, sent to B)
display_init.cpp # Display initialization; boots into DrivelineScreen
driveline_screen.cpp # Hand-coded LVGL boot screen (gear, temps, rpm, status)
engine_screen.cpp # Live DDE values: rail, boost, charge-air temp, battery (Engine data button)
drivers/
can_driver.cpp # CAN Bus driver (TWAI)
@@ -143,7 +145,7 @@ include/
Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Namespace: "settings"
- Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en` (boolean values)
- Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en`, `difflock_en`, `difflock_inv` (boolean values)
- Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()`
- Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed
@@ -213,7 +215,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
### Diagnostic probe (`diag` console)
`src/modules/diag_probe.cpp` is the only code allowed to call `CANDriver::transmit()`. It sends single diagnostic requests and reassembles the ISO-TP replies, on two routes: generic OBD-II on `0x7DF` (replies `0x7E8..0x7EF`) and BMW-addressed KWP2000 on `0x6F1` with target byte (replies `0x600`+addr, extended addressing). Commands: `diag pids` (supported-PID bitmap scan), `diag pid <hex>`, `diag dtc` (mode 03), `diag vin`, `diag ecu`, `diag ident [addr]` (KWP `1A 80`), `diag bmw <addr> <hex...>` (raw, whitelisted), `diag raw on|off` (CANRAW mute for scans), `diag status`. One request in flight, single-shot frames, refused for 3 s after any foreign tester frame (`0x7DF`, `0x7E0-7`, `0x6F1`); read-only services only — generic 01/03/09, BMW `1A`/`18`/`21`/`22` (whitelist enforced in `sendBmwRequest()`), never session control or writes. Transmitted frames are echoed as `CANTX,` lines in the same format as `CANRAW,`. Console lines that `cfg` does not recognise are passed to it via `Tunables::setExtraCommandHandler()`. Background and test procedure: `wiki/pages/obd-diagnostic-polling.md`.
`src/modules/diag_probe.cpp` is the only code allowed to call `CANDriver::transmit()`. It sends single diagnostic requests and reassembles the ISO-TP replies, on two routes: generic OBD-II on `0x7DF` (replies `0x7E8..0x7EF`) and BMW-addressed KWP2000 on `0x6F1` with target byte (replies `0x600`+addr, extended addressing). Commands: `diag pids` (supported-PID bitmap scan), `diag pid <hex>`, `diag dtc` (mode 03), `diag vin`, `diag ecu`, `diag ident [addr]` (KWP `1A 80`), `diag bmw <addr> <hex...>` (raw, whitelisted), `diag raw on|off` (CANRAW mute for scans), `diag status`. **Live mode** (`liveKeepAlive()` / `liveStop()` / `liveValue()`, used by the Engine data screen): the Launch's `2C 10 15 E0` once, then `2C 10 00DF/0091/16A8/0093` in turn to the DDE, one in flight, ~100 ms apart, quiet on the console (CANTX echoed only with CANRAW on), paused by the tester guard; `2C` is never allowed from the console. One request in flight, single-shot frames, refused for 3 s after any foreign tester frame (`0x7DF`, `0x7E0-7`, `0x6F1`); read-only services only — generic 01/03/09, BMW `1A`/`18`/`21`/`22` (whitelist enforced in `sendBmwRequest()`), never session control or writes. Transmitted frames are echoed as `CANTX,` lines in the same format as `CANRAW,`. Console lines that `cfg` does not recognise are passed to it via `Tunables::setExtraCommandHandler()`. Background and test procedure: `wiki/pages/obd-diagnostic-polling.md`.
### OTA updates (`ota` console)
@@ -231,12 +233,17 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
`src/modules/link_peer.cpp` keeps B's last `STATUS` frame (version, update phase, progress, flags; "not heard" after 15 s), owns the pairing key (NVS `linkpeer`) and drives B's updater. `link pair` generates a 32-byte key and sends it **three times over UART1 only** (`UARTManager::sendWire()`, never ESP-NOW - both repos are public, this is the one secret); B confirms with `key_fp` in its next STATUS. `tick()` pushes the remembered Wi-Fi network to B in an encrypted `SECURE` frame whenever B lacks it or it changed (hash-compared, ≥ 15 s apart; `WiFiManager::getSavedCredentials()` exists for this alone - never print the password), and a FORGET when A forgets its network. `requestCheck()` / `requestInstall()` (Settings → Updates, Inst. Cluster card) require: B heard, paired with *this* key, B has credentials, B not busy, A on Wi-Fi (same AP as B ⇒ same channel ⇒ progress frames arrive), and for install `Ota::isParked()`. Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. Design + procedure: B's wiki `controller-b-ota`.
### Diff-lock inputs (`difflock` console)
`src/modules/diff_locks.cpp` reads the Patrol's two diff-lock signals (+12 V = locked) on the isolated inputs: DI0 = rear, DI1 = front, `DI_COM` to vehicle ground. The PC814 outputs reach the ESP32 only through the CH422G (DI0 = EXIO0, DI1 = EXIO5, active LOW), and the CH422G's IO0-7 are one bank, all in or all out - the same bank drives touch reset (EXIO1), backlight (EXIO2) and LCD reset (EXIO3). Each poll (4 Hz, under the LVGL lock so no touch read shares the bus) writes WR_SET input (0x24 <- 0x00), reads 0x26, and writes output back (0x01), restore retried; the chip keeps its output latch. Raw I2C on host 0 (legacy driver, as the panel library), never the library's `enableAllIO_Input()` (it sleeps 2 ms with the bank floating). A state counts after two equal reads. Polarity is a per-board setting (`difflock_inv`, the "Inverted" switch in the same Settings row, `difflock invert on|off`): in the car the lock wires carry 12 V while UNLOCKED, so the car board needs it on, the bench (12 V = locked) needs it off. Behind the Settings → System switch, default OFF, so a board without the wiring never flips the bank. The Driveline shows a top view of the chassis in the top-right corner, drawn from the user's sketch with `lv_line` objects and two border boxes, geometry in sketch pixels scaled by `DL_S`. All four tyres are the same square-cornered rectangle, and the wheelbase is the sketch's shortened by 20 %. A locked axle turns amber: axle, tyres filled solid, and an X on its diff. A filled tyre is one `lv_line` as wide as the tyre with square ends, because LVGL 8 cannot rotate a box. The front axle turns red if it reads locked without the rear. There is no text caption (user). The whole drawing is hidden when the switch is off; the System row's sub-line shows the live state for testing. Wiring and evidence: wiki `diff-lock-inputs`.
### Screens
All hand-coded in `src/modules`, built once and kept (never deleted - the old generated screens were deleted on leave, which left dangling pointers and caused the 2026-09-27 freezes). Shared look in `ui_kit.cpp` (20/24 px text, >= 56 px touch targets, no shadows/animations, `UiKit::confirm()` modal dialog). Each screen has a `tick()` called from `loop()` that refreshes values under the LVGL lock, only while it is shown, and only re-sets label text that changed.
- **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Main CTRL -> `Ota::requestCheck/requestInstall`, Inst. Cluster -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay switches, live ESP-NOW, CAN, memory, uptime). Swipe right or the Driveline button goes back
- **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning, **Engine data** button (y 60, left of the diff-lock drawing)
- **Engine data** (`engine_screen.cpp`) - rail pressure, boost, charge-air temp, battery from the DDE via `DiagProbe`'s live poll (runs only while the screen is shown, ~1.5 s keep-alive; pauses while another tester is on the bus). Scalings live in the screen's `CHANNELS[]` table; provisional ones are tagged and every value shows its raw number. Swipe right or the Driveline button goes back
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Main CTRL -> `Ota::requestCheck/requestInstall`, Inst. Cluster -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay / diff-lock input switches, live ESP-NOW, CAN, memory, uptime on the firmware line - the page is full at four rows). Swipe right or the Driveline button goes back
- **Gauge Tuning** (`tuning_screen.cpp`) - tabs Tachometer / Coolant gauge / Alerts / Simulation; -/+ rows with hints (hold to repeat, speeds up), per-tab Reset with confirm, "Saving... / All changes saved" footer, SIMULATION ON chip while an override is active. Swipe left or the Driveline button goes back
- Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`): full-screen fades are software-blended every frame and stutter at 1024x600. The firmware version is a label on `lv_layer_top()` (bottom-right, every screen, `DisplayInit`)
- **StatusOverlay** (2026-09-27, `status_overlay.cpp`, also on `lv_layer_top()`): a 150 px Wi-Fi chip top-right (off / not connected / joining / network name) and an alert banner top-centre that blinks red at 2 Hz while any red alert bit is set (coolant hot, gearbox oil hot, gear mismatch, battery low - text names the value) and is steady amber for gearbox cooling; hidden with CAN or ignition off. The top ~56 px of every screen belong to it: `UiKit::header()` puts the back button at x -176, the Driveline chips start at y 60. On the Driveline the crossed value AND its title go red (amber for cooling) and a gear mismatch turns the hero ring + letter red (the old top-right mismatch label is gone). Blinking is a colour toggle from `tick()` every 500 ms, not an lv_anim (a 1024-wide banner animated per frame would cost real render time)
+8
View File
@@ -132,6 +132,14 @@ diag raw on | off CANRAW frame logging
diag status
```
### `difflock` — diff-lock inputs (DI0 = rear, DI1 = front; Settings → System switch, default OFF)
```
difflock status rear / front LOCKED or open, raw CH422G IO byte, read counters
difflock on | off same as the switch (saved)
difflock invert on | off polarity, same as the "Inverted" switch (saved): on = NO current means locked
```
Wiring: lock wire → DI0 / DI1, `DI_COM` → vehicle ground. If the screen shows locked when unlocked (the Patrol's ground-switched lamp wires do this), turn **Inverted** on. Details: wiki `diff-lock-inputs`.
### Diagnostics
```
mem internal heap, PSRAM, LVGL pool
+5 -4
View File
@@ -147,12 +147,13 @@ namespace CANDriver {
/**
* Transmit ONE standard (11-bit) frame, single-shot (no automatic
* retransmission if nobody ACKs). The only write path onto the vehicle
* bus; reserved for DiagProbe's on-demand diagnostic requests. Echoes the
* frame on the console as a "CANTX," line (same shape as CANRAW) so
* captures hold both halves of an exchange.
* bus; reserved for DiagProbe (console requests + the Engine data screen's
* live poll). Echoes the frame on the console as a "CANTX," line (same
* shape as CANRAW) so captures hold both halves of an exchange; the live
* poll passes echo=false unless CANRAW logging is on (10 frames/s).
* @return true if the frame was queued (delivery is reported via stats)
*/
bool transmit(uint32_t id, const uint8_t* data, uint8_t len);
bool transmit(uint32_t id, const uint8_t* data, uint8_t len, bool echo = true);
/**
* Enable/disable raw frame logging (candump-style capture of EVERY frame).
+2 -2
View File
@@ -699,7 +699,7 @@ bool isActive() {
return g_can_active;
}
bool transmit(uint32_t id, const uint8_t* data, uint8_t len) {
bool transmit(uint32_t id, const uint8_t* data, uint8_t len, bool echo) {
if (!g_can_active || data == NULL || len > 8 || id > 0x7FF) {
g_can_stats.tx_failures++;
return false;
@@ -719,7 +719,7 @@ bool transmit(uint32_t id, const uint8_t* data, uint8_t len) {
return false;
}
g_can_stats.messages_transmitted++;
emitFrameLine("CANTX", m);
if (echo) emitFrameLine("CANTX", m);
return true;
}
+8 -2
View File
@@ -11,6 +11,7 @@
#include "modules/driveline_screen.h" // Hand-coded driveline screen (boot screen)
#include "modules/tuning_screen.h" // Hand-coded gauge tuning screen (swipe right from Driveline)
#include "modules/settings_screen.h" // Hand-coded settings screen (swipe left from Driveline)
#include "modules/engine_screen.h" // Live DDE values (Engine data button on Driveline)
#include "modules/serial_lock.h" // Global serial write mutex
#include "modules/tunables.h" // Gauge calibration + alert thresholds (NVS, serial console)
#include "modules/perf_monitor.h" // `perf` console: render fps, flush cost, CPU idle, heap
@@ -19,6 +20,7 @@
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
#include "modules/link_peer.h" // Inst. Cluster status, pairing, credential handoff, B updates (`link` console)
#include "modules/status_overlay.h" // Every screen: Wi-Fi chip top-right, blinking alert banner top-centre
#include "modules/diff_locks.h" // Diff-lock inputs DI0 rear / DI1 front via the CH422G (`difflock` console)
// ============================================================================
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
@@ -57,11 +59,12 @@ static bool memCommand(const char* line) {
return true;
}
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem.
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem, link, difflock.
static bool consoleExtraCommand(const char* line) {
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
WiFiManager::handleCommand(line) || memCommand(line) ||
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line);
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
DiffLocks::handleCommand(line);
}
// ============================================================================
@@ -107,6 +110,7 @@ void setup()
bool saved_uart_state = SettingsManager::loadUARTState();
bool saved_can_state = SettingsManager::loadCANState();
bool saved_debug_state = SettingsManager::loadDebugState();
DiffLocks::init(SettingsManager::loadDiffLockState(), SettingsManager::loadDiffLockInvert()); // CH422G bus is up since DisplayInit
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
// Initialize UI State Manager
@@ -165,11 +169,13 @@ void loop()
DiagProbe::tick();
Ota::tick(); // confirms a freshly installed image after healthy uptime
LinkPeer::tick(); // Inst. Cluster heard/lost, credential sync
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
DrivelineScreen::tick();
TuningScreen::tick();
SettingsScreen::tick();
StatusOverlay::tick();
EngineScreen::tick();
delay(100); // Check frequently to catch screen changes quickly
}
+147 -1
View File
@@ -80,6 +80,23 @@ 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;
// live engine data (Engine data screen) - liveStop() is public, declared in the header
static const uint16_t LIVE_IDS[LIVE_COUNT] = {0x00DF, 0x0091, 0x16A8, 0x0093};
static const uint16_t LIVE_DEFINE_ID = 0x15E0; // the Launch sends `2C 10 15 E0` once on connect
static const uint32_t LIVE_GAP_MS = 80; // between requests (plus the loop's 100 ms tick)
static const uint32_t LIVE_KEEPALIVE_MS = 1500; // stop this long after the screen stops asking
static const uint8_t LIVE_NO_ANSWER_AFTER = 4; // consecutive timeouts
static bool g_live = false;
static bool g_live_defined = false;
static uint8_t g_live_next = 0;
static uint32_t g_live_keep_ms = 0, g_live_last_tx = 0;
static live_state_t g_live_state = LIVE_OFF;
static uint8_t g_live_misses = 0;
static bool g_live_req = false; // the request in flight is a live one (quiet)
static int8_t g_live_req_index = -1; // -1 = the define request
static struct { bool valid; uint16_t raw; uint32_t at_ms; uint8_t nrc; } g_live_vals[LIVE_COUNT];
// ============================================================================
// HELPERS
// ============================================================================
@@ -335,6 +352,28 @@ 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) {
if (g_live_req) {
// quiet: store and finish at once (no linger - only the DDE answers 0x612)
if (n >= 3 && p[0] == 0x7F && p[2] == 0x78) { g_deadline_ms = millis() + PENDING_EXTRA_MS; return; }
g_replies++;
g_replies_this_req++;
g_live_misses = 0;
if (g_live_req_index >= 0) {
auto& v = g_live_vals[g_live_req_index];
if (n >= 4 && p[0] == 0x6C && p[1] == 0x10) {
v.raw = (uint16_t)((p[2] << 8) | p[3]);
v.valid = true;
v.at_ms = millis();
v.nrc = 0;
} else if (n >= 3 && p[0] == 0x7F) {
v.nrc = p[2];
g_negatives++;
}
}
g_state = ST_IDLE;
g_live_req = false;
return;
}
char hex[3 * 48 + 1];
hexdump(hex, sizeof(hex), p, n > 48 ? 48 : n);
g_replies++;
@@ -540,13 +579,78 @@ static void printScanSummary() {
print("[diag] next: `diag pid 0C` (rpm) to prove a data read, `diag vin` for the donor");
}
/** One fixed `2C 10 <id>` request to the DDE for the live poll. Caller checked the guards. */
static void sendLive(int8_t index) {
uint16_t vid = index < 0 ? LIVE_DEFINE_ID : LIVE_IDS[index];
uint8_t f[8];
memset(f, PAD_BYTE, sizeof(f));
f[0] = BMW_ADDR_DDE;
f[1] = 0x04;
f[2] = 0x2C;
f[3] = 0x10;
f[4] = (uint8_t)(vid >> 8);
f[5] = (uint8_t)vid;
armRequest(0x2C, 0x10, true, BMW_ADDR_DDE);
lock();
g_live_req = true;
g_live_req_index = index;
unlock();
if (!CANDriver::transmit(BMW_TESTER_ID, f, sizeof(f), CANDriver::isRawLogging())) {
lock();
g_state = ST_IDLE;
g_live_req = false;
unlock();
}
}
static void liveTick() {
if (!g_live) return;
uint32_t now = millis();
if (now - g_live_keep_ms > LIVE_KEEPALIVE_MS) {
liveStop();
return;
}
if (!CANDriver::isActive()) { g_live_state = LIVE_CAN_OFF; return; }
lock();
bool busy = (g_state != ST_IDLE);
bool tester = (g_last_tester_ms != 0) && (now - g_last_tester_ms < TESTER_GUARD_MS);
unlock();
if (tester) {
g_live_state = LIVE_PAUSED_TESTER;
g_live_defined = false; // redo the define once the other tester is gone
return;
}
if (busy || now - g_live_last_tx < LIVE_GAP_MS) return;
g_live_state = (g_live_misses >= LIVE_NO_ANSWER_AFTER) ? LIVE_NO_ANSWER : LIVE_RUNNING;
g_live_last_tx = now;
if (!g_live_defined) {
g_live_defined = true;
sendLive(-1);
} else {
sendLive((int8_t)g_live_next);
g_live_next = (g_live_next + 1) % LIVE_COUNT;
}
}
void tick() {
if (g_state == ST_IDLE) return;
if (g_state == ST_IDLE) { liveTick(); return; }
uint32_t now = millis();
lock();
if ((int32_t)(now - g_deadline_ms) < 0) { unlock(); return; }
if (g_live_req) { // a live request timed out: count it quietly, carry on
g_state = ST_IDLE;
g_live_req = false;
g_timeouts++;
if (g_live_misses < 255) g_live_misses++;
unlock();
liveTick();
return;
}
// request over
bool got_reply = g_replies_this_req > 0;
bool scan = g_scan_active;
@@ -721,4 +825,46 @@ void init() {
if (!g_mutex) g_mutex = xSemaphoreCreateMutex();
}
// ----------------------------------------------------------------------------
// Live engine data
// ----------------------------------------------------------------------------
void liveKeepAlive() {
g_live_keep_ms = millis();
if (g_live) return;
lock();
memset(g_live_vals, 0, sizeof(g_live_vals));
unlock();
g_live = true;
g_live_defined = false;
g_live_next = 0;
g_live_misses = 0;
g_live_last_tx = 0;
g_live_state = LIVE_RUNNING;
print("[diag] live engine data ON: polling the DDE (2C 10 00DF/0091/16A8/0093)");
}
void liveStop() {
if (!g_live) return;
g_live = false;
g_live_state = LIVE_OFF;
print("[diag] live engine data OFF");
}
live_state_t liveState() {
return g_live ? g_live_state : LIVE_OFF;
}
live_value_t liveValue(live_id_t id) {
live_value_t out = {false, 0, 0, 0};
if (id >= LIVE_COUNT) return out;
lock();
out.valid = g_live_vals[id].valid;
out.raw = g_live_vals[id].raw;
out.nrc = g_live_vals[id].nrc;
out.age_ms = out.valid ? millis() - g_live_vals[id].at_ms : 0;
unlock();
return out;
}
} // namespace DiagProbe
+36
View File
@@ -28,6 +28,14 @@
* services are whitelisted in sendBmwRequest(): 1A (ident), 18 (DTCs),
* 21/22 (read data) — never session control, resets, or writes.
*
* Live engine data (Engine data screen, 2026-10-07): while the screen keeps
* calling liveKeepAlive(), the probe polls four DDE values with the same
* KWP `2C 10 <id>` requests the Launch uses (one-time `2C 10 15 E0`, then
* rail 00DF, boost 0091, charge-air temp 16A8, battery 0093 in turn, one
* request in flight, ~100 ms apart). Quiet on the console, pauses while
* another tester is on the bus, stops 1.5 s after the last keep-alive.
* `2C` is NOT allowed from the console - only these fixed frames.
*
* 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.
@@ -58,4 +66,32 @@ void tick();
*/
void onFrame(const twai_message_t& m);
// ---- Live engine data ------------------------------------------------------
typedef enum { LIVE_RAIL, LIVE_BOOST, LIVE_AIR_TEMP, LIVE_BATTERY, LIVE_COUNT } live_id_t;
typedef enum {
LIVE_OFF, // not polling
LIVE_RUNNING,
LIVE_PAUSED_TESTER, // another tester (e.g. the Launch) is polling - we stay quiet
LIVE_CAN_OFF, // CAN task stopped
LIVE_NO_ANSWER // requests go out but the DDE does not answer
} live_state_t;
typedef struct {
bool valid; // at least one reply since polling started
uint16_t raw; // last 2-byte value from `6C 10 HH LL`
uint32_t age_ms; // since that reply
uint8_t nrc; // last negative-response code (0 = none)
} live_value_t;
/** Keep the live poll running; starts it if needed. Call from loop() while the screen is shown. */
void liveKeepAlive();
/** Stop at once (leaving the screen). */
void liveStop();
live_state_t liveState();
live_value_t liveValue(live_id_t id);
} // namespace DiagProbe
+163
View File
@@ -0,0 +1,163 @@
/*
* Differential lock inputs - see diff_locks.h
*
* Schematic (V1.2, sheet 1): DINx -> PC814 LED -> 3.6 kOhm -> DI_COM. The
* optocoupler's transistor pulls DIx (4.7 kOhm to 3V3) LOW while current flows,
* so a LOCKED diff reads 0 on its EXIO bit. The PC814 LED is bidirectional:
* +12 V on DINx with DI_COM on ground is the "PNP / high-level" wiring.
*/
#include "diff_locks.h"
#include "settings_manager.h"
#include "serial_lock.h"
#include "display/lvgl_v8_port.h"
#include <driver/i2c.h>
#include <stdarg.h>
namespace DiffLocks {
// CH422G on the panel library's I2C host 0. Its "registers" are I2C addresses.
static const i2c_port_t CH422G_PORT = I2C_NUM_0;
static const uint8_t ADDR_WR_SET = 0x24; // system parameter byte
static const uint8_t ADDR_RD_IO = 0x26; // IO0-7 pin levels
// WR_SET as the board config leaves it (ESP_PANEL_BOARD_EXPANDER_POST_BEGIN_FUNCTION:
// enableAllIO_Output -> IO_OE only; OC push-pull, no sleep). Input = IO_OE cleared.
static const uint8_t WR_SET_OUTPUT = 0x01;
static const uint8_t WR_SET_INPUT = 0x00;
static const uint8_t BIT_REAR = 1 << 0; // DI0 = EXIO0
static const uint8_t BIT_FRONT = 1 << 5; // DI1 = EXIO5
static const uint32_t POLL_MS = 250;
static const uint8_t FAULT_AFTER = 3; // failed reads in a row
static bool g_enabled = false;
static bool g_inverted = false;
static bool g_rear = false, g_front = false; // debounced
static bool g_have_state = false;
static uint8_t g_last_raw = 0xFF;
static bool g_have_raw = false;
static uint8_t g_fail_run = 0;
static uint32_t g_reads = 0, g_fails = 0;
static uint32_t g_last_poll = 0;
static void print(const char* fmt, ...) {
char buf[160];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static esp_err_t writeSet(uint8_t v) {
return i2c_master_write_to_device(CH422G_PORT, ADDR_WR_SET, &v, 1, pdMS_TO_TICKS(10));
}
/**
* One raw read of IO0-7. The bank is an input only between the two WR_SET
* writes (three short I2C transactions); the output is restored even when the
* read fails, and retried, because touch reset, backlight and LCD reset live on
* the same bank. The caller holds the LVGL lock, so no touch read (same bus)
* can land in the middle.
*/
static bool readBank(uint8_t* out) {
if (writeSet(WR_SET_INPUT) != ESP_OK) {
writeSet(WR_SET_OUTPUT); // a half-done write: make sure we are back
return false;
}
esp_err_t r = i2c_master_read_from_device(CH422G_PORT, ADDR_RD_IO, out, 1, pdMS_TO_TICKS(10));
for (int i = 0; i < 3 && writeSet(WR_SET_OUTPUT) != ESP_OK; i++) {}
return r == ESP_OK;
}
void init(bool enabled, bool inverted) {
g_enabled = enabled;
g_inverted = inverted;
print("[difflock] %s (DI0 = rear, DI1 = front, %s)", enabled ? "ON" : "OFF - Settings > System to enable",
inverted ? "INVERTED: no current = locked" : "current = locked");
}
void setEnabled(bool enabled) {
if (enabled == g_enabled) return;
g_enabled = enabled;
g_have_state = g_have_raw = false;
g_rear = g_front = false;
g_fail_run = 0;
SettingsManager::saveDiffLockState(enabled);
}
void setInverted(bool inverted) {
if (inverted == g_inverted) return;
g_inverted = inverted;
g_have_state = g_have_raw = false; // re-evaluate from the next two reads
SettingsManager::saveDiffLockInvert(inverted);
}
bool isInverted() { return g_inverted; }
bool isEnabled() { return g_enabled; }
bool isValid() { return g_enabled && g_have_state && g_fail_run < FAULT_AFTER; }
bool rearLocked() { return isValid() && g_rear; }
bool frontLocked() { return isValid() && g_front; }
void tick() {
if (!g_enabled || millis() - g_last_poll < POLL_MS) return;
g_last_poll = millis();
if (!lvgl_port_lock(100)) return; // UI busy: try again next poll
uint8_t raw = 0xFF;
bool ok = readBank(&raw);
lvgl_port_unlock();
g_reads++;
if (!ok) {
g_fails++;
if (g_fail_run < 255) g_fail_run++;
if (g_fail_run == FAULT_AFTER) print("[difflock] CH422G read failing - lock states unknown");
return;
}
g_fail_run = 0;
// Accept a state only when two reads in a row agree (<= 0.5 s latency).
uint8_t bits = raw & (BIT_REAR | BIT_FRONT);
if (g_have_raw && bits == (g_last_raw & (BIT_REAR | BIT_FRONT))) {
// opto conducting = pin low; that is "locked" unless the polarity is inverted
bool rear = !(bits & BIT_REAR) != g_inverted;
bool front = !(bits & BIT_FRONT) != g_inverted;
if (!g_have_state || rear != g_rear || front != g_front) {
g_rear = rear;
g_front = front;
g_have_state = true;
print("[difflock] rear %s, front %s%s", rear ? "LOCKED" : "open", front ? "LOCKED" : "open",
(front && !rear) ? " (front without rear - check the DI0 wiring)" : "");
}
}
g_last_raw = raw;
g_have_raw = true;
}
bool handleCommand(const char* line) {
if (strncmp(line, "difflock", 8) != 0 || (line[8] != 0 && line[8] != ' ')) return false;
const char* a = line + 8;
while (*a == ' ') a++;
if (!strcmp(a, "on")) { setEnabled(true); print("[difflock] ON (saved)"); return true; }
if (!strcmp(a, "off")) { setEnabled(false); print("[difflock] OFF (saved)"); return true; }
if (!strcmp(a, "invert on")) { setInverted(true); print("[difflock] INVERTED: no current = locked (saved)"); return true; }
if (!strcmp(a, "invert off")) { setInverted(false); print("[difflock] normal: current (+12 V) = locked (saved)"); return true; }
if (!*a || !strcmp(a, "status")) {
if (!g_enabled) { print("[difflock] OFF - inputs not read ('difflock on' or Settings > System)"); return true; }
print("[difflock] rear %s, front %s | %s | raw IO0-7 0x%02X | %lu reads, %lu failed%s",
!isValid() ? "?" : g_rear ? "LOCKED" : "open",
!isValid() ? "?" : g_front ? "LOCKED" : "open",
g_inverted ? "inverted" : "normal", g_last_raw, (unsigned long)g_reads, (unsigned long)g_fails,
g_fail_run >= FAULT_AFTER ? " | READ FAULT" : "");
return true;
}
print("[difflock] usage: difflock status | on | off | invert on|off (DI0 = rear, DI1 = front)");
return true;
}
} // namespace DiffLocks
+47
View File
@@ -0,0 +1,47 @@
/*
* Differential lock inputs - DI0 = rear, DI1 = front
*
* The Patrol's lock switches put +12 V on a wire while a diff is locked. Those
* wires go to the board's isolated inputs (PC814 optocouplers, 5-36 V, DI_COM to
* vehicle ground). The inputs reach the ESP32 only through the CH422G expander
* (DI0 = EXIO0, DI1 = EXIO5), whose IO0-7 are all-in or all-out as ONE bank - and
* the same bank drives touch reset, backlight enable and LCD reset. So each read
* switches the bank to input for ~0.1 ms and straight back (output latches are
* kept by the chip). That is why the whole feature sits behind a Settings switch,
* default OFF: a board without diff-lock wiring never touches the bank.
*/
#pragma once
#include <Arduino.h>
namespace DiffLocks {
/** Call once after DisplayInit (the CH422G's I2C bus is installed by the panel library). */
void init(bool enabled, bool inverted);
/** Settings switch / `difflock on|off`. Saved to NVS (SettingsManager). */
void setEnabled(bool enabled);
bool isEnabled();
/**
* Polarity. Normal: current through the input (+12 V on DINx) = locked.
* Inverted: NO current = locked - the Patrol's ground-switched lock lamps give
* 12 V through the lamp while unlocked and 0 V once the diff switch closes
* (seen in the car, 2026-09-29). Saved to NVS.
*/
void setInverted(bool inverted);
bool isInverted();
/** Poll the inputs (4 Hz, debounced over two reads). Call from loop(). */
void tick();
/** Enabled AND the last reads succeeded - otherwise the lock states mean nothing. */
bool isValid();
bool rearLocked();
bool frontLocked();
/** `difflock status | on | off | invert on|off`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace DiffLocks
+187
View File
@@ -5,10 +5,14 @@
#include "driveline_screen.h"
#include "uart_manager.h"
#include <string.h>
#include <math.h>
#include "display/lvgl_v8_port.h"
#include "drivers/can_driver.h"
#include "tuning_screen.h"
#include "settings_screen.h"
#include "diff_locks.h"
#include "engine_screen.h"
#include "ui_kit.h"
#include "esp_log.h"
namespace DrivelineScreen {
@@ -49,6 +53,7 @@ static lv_obj_t* g_ign_chip = NULL;
static lv_obj_t* g_eng_chip = NULL;
static lv_obj_t* g_clutch_chip = NULL;
static lv_obj_t* g_cool_chip = NULL;
static lv_obj_t* g_diff_box = NULL; // top-right: chassis top view, locked axles lit
// ============================================================================
// PRIVATE HELPERS
@@ -111,6 +116,142 @@ static void setChip(lv_obj_t* chip, const char* text, lv_color_t colour) {
}
}
// ---- diff-lock drawing ------------------------------------------------------
// A top view of the chassis, after the user's sketch (front up): steered front
// tyres on the front axle, prop shaft, rear axle on straight tyres. All four
// tyres are the same square-cornered 24 x 76 rectangle. A locked axle lights up:
// axle, tyres filled, and an X on its diff. Geometry is in sketch pixels, scaled
// by DL_S. Wheelbase 151 = the sketch's 189 shortened by 20 % (user, 2026-09-29).
static const float DL_S = 0.46f; // sketch -> screen
static const lv_coord_t DL_BOX_W = 110; // hugs the drawing (dl(DL_W) = 98)
static const float DL_W = 212; // sketch width the drawing is centred in
static const float DL_SHAFT_X = 106;
static const float DL_FRONT_Y = 45;
static const float DL_REAR_Y = DL_FRONT_Y + 151;
static const float DL_TRACK_L = 45, DL_TRACK_R = 167; // tyre centres, symmetric about the shaft
static const float DL_TYRE_W = 24, DL_TYRE_L = 76;
static const float DL_STEER = 25; // front tyres, degrees, top leaning right
static lv_coord_t dl(float v) { return (lv_coord_t)lroundf(v * DL_S); }
/** Sketch point -> box point (drawing centred horizontally in the box). */
static lv_point_t dlPoint(float x, float y) {
lv_point_t pt;
pt.x = (DL_BOX_W - dl(DL_W)) / 2 + dl(x);
pt.y = dl(y) + 2;
return pt;
}
struct TyreView {
lv_obj_t* outline;
lv_obj_t* fill; // shown only while the axle is locked
};
struct AxleView {
lv_obj_t* axle;
TyreView tyre[2];
lv_obj_t* cross[2]; // the X on the diff, shown only while locked
};
static AxleView g_front_axle, g_rear_axle;
// lv_line keeps a pointer to its points: they must outlive the objects.
static lv_point_t g_pts_shaft[2];
static lv_point_t g_pts_axle[2][2]; // [front, rear][end]
static lv_point_t g_pts_tyre[2][2][5]; // [front, rear][left, right] closed outline
static lv_point_t g_pts_fill[2][2][2]; // [front, rear][left, right] centre line of the fill
static lv_point_t g_pts_cross[2][2][2]; // [front, rear][stroke][end]
static lv_obj_t* makeLine(lv_obj_t* parent, lv_point_t* pts, uint16_t n, lv_coord_t width, bool rounded) {
lv_obj_t* l = lv_line_create(parent);
lv_line_set_points(l, pts, n);
lv_obj_set_style_line_width(l, width, 0);
lv_obj_set_style_line_rounded(l, rounded, 0);
lv_obj_set_style_line_color(l, COL_MUTED, 0);
lv_obj_clear_flag(l, LV_OBJ_FLAG_CLICKABLE);
return l;
}
/**
* A tyre centred on (cx, cy), `steer` degrees from straight (top leaning right).
* The fill is ONE line as wide as the tyre with square ends, which is exactly
* the filled rectangle, rotated or not (LVGL 8 cannot rotate a plain box).
*/
static TyreView makeTyre(lv_obj_t* parent, lv_point_t* outline, lv_point_t* fill,
float cx, float cy, float steer) {
const float a = DL_TYRE_W / 2, b = DL_TYRE_L / 2, t = steer * (float)M_PI / 180.0f;
const float ux = sinf(t), uy = -cosf(t); // long axis, towards the top
const float vx = cosf(t), vy = sinf(t); // short axis
const float k[4][2] = {{b, a}, {b, -a}, {-b, -a}, {-b, a}};
for (int i = 0; i < 4; i++) {
outline[i] = dlPoint(cx + k[i][0] * ux + k[i][1] * vx, cy + k[i][0] * uy + k[i][1] * vy);
}
outline[4] = outline[0];
fill[0] = dlPoint(cx + b * ux, cy + b * uy);
fill[1] = dlPoint(cx - b * ux, cy - b * uy);
TyreView v;
v.fill = makeLine(parent, fill, 2, dl(DL_TYRE_W), false);
lv_obj_add_flag(v.fill, LV_OBJ_FLAG_HIDDEN);
v.outline = makeLine(parent, outline, 5, 2, true); // 2 px rounded joins read as square corners
return v;
}
/** The X on a diff at (cx, cy); idx 0 = front, 1 = rear. */
static void diffCross(lv_obj_t* parent, AxleView& a, int idx, float cx, float cy) {
const float r = 16;
g_pts_cross[idx][0][0] = dlPoint(cx - r, cy - r); g_pts_cross[idx][0][1] = dlPoint(cx + r, cy + r);
g_pts_cross[idx][1][0] = dlPoint(cx + r, cy - r); g_pts_cross[idx][1][1] = dlPoint(cx - r, cy + r);
for (int k = 0; k < 2; k++) {
a.cross[k] = makeLine(parent, g_pts_cross[idx][k], 2, 4, true);
lv_obj_add_flag(a.cross[k], LV_OBJ_FLAG_HIDDEN);
}
}
/** Line colour, written only on change. */
static void setPartColour(lv_obj_t* o, lv_color_t c) {
if (lv_color_to32(lv_obj_get_style_line_color(o, 0)) != lv_color_to32(c)) {
lv_obj_set_style_line_color(o, c, 0);
}
}
static void setHidden(lv_obj_t* o, bool hidden) {
if (lv_obj_has_flag(o, LV_OBJ_FLAG_HIDDEN) == hidden) return;
if (hidden) lv_obj_add_flag(o, LV_OBJ_FLAG_HIDDEN);
else lv_obj_clear_flag(o, LV_OBJ_FLAG_HIDDEN);
}
static void setAxle(AxleView& a, bool locked, lv_color_t colour) {
lv_color_t c = locked ? colour : COL_MUTED;
setPartColour(a.axle, c);
for (int i = 0; i < 2; i++) {
setPartColour(a.tyre[i].outline, c);
setPartColour(a.tyre[i].fill, c);
setHidden(a.tyre[i].fill, !locked);
setPartColour(a.cross[i], c);
setHidden(a.cross[i], !locked);
}
}
/**
* @brief Diff locks, from the isolated inputs (not CAN - shown with CAN off too).
* Locked axle = amber. The front can only lock after the rear, so FRONT
* without REAR is a wiring/switch fault and shows red.
*/
static void refreshDiffLocks() {
bool on = DiffLocks::isEnabled();
setHidden(g_diff_box, !on);
if (!on) return;
if (!DiffLocks::isValid()) {
setAxle(g_front_axle, false, COL_MUTED);
setAxle(g_rear_axle, false, COL_MUTED);
return;
}
bool rear = DiffLocks::rearLocked(), front = DiffLocks::frontLocked();
setAxle(g_rear_axle, rear, COL_AMBER);
setAxle(g_front_axle, front, rear ? COL_AMBER : COL_ALERT); // no caption: the drawing says it all (user)
}
/**
* @brief Compose the hero gear label from the 0x1D2 pieces.
*
@@ -185,6 +326,11 @@ static void onScreenGesture(lv_event_t* e) {
}
}
static void onEngineData(lv_event_t* e) {
(void)e;
EngineScreen::show();
}
/**
* @brief Build the screen. Idempotent — returns immediately if already built.
*/
@@ -212,6 +358,45 @@ static void build() {
g_cool_chip = makeChip(bar, "COOLING --");
// Gear mismatch: the ring and the gear letter turn red, and the overlay banner says so.
// ---- diff locks, top-right under the overlay's Wi-Fi chip (hidden until enabled).
// Box bottom stays above the GEARBOX OIL stat (its top is at y ~227).
g_diff_box = lv_obj_create(g_screen);
lv_obj_remove_style_all(g_diff_box);
lv_obj_set_size(g_diff_box, DL_BOX_W, dl(DL_REAR_Y + DL_TYRE_L / 2) + 6); // drawing only, no caption
lv_obj_align(g_diff_box, LV_ALIGN_TOP_RIGHT, -16, 60);
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_CLICKABLE); // swipes pass through to the screen
lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
g_pts_shaft[0] = dlPoint(DL_SHAFT_X, DL_FRONT_Y);
g_pts_shaft[1] = dlPoint(DL_SHAFT_X, DL_REAR_Y);
makeLine(g_diff_box, g_pts_shaft, 2, 3, true);
// axles run between the tyres' inner edges (a steered tyre's edge sits a little further out)
const float half = DL_TYRE_W / 2;
const float half_steered = half / cosf(DL_STEER * (float)M_PI / 180.0f);
g_pts_axle[0][0] = dlPoint(DL_TRACK_L + half_steered, DL_FRONT_Y);
g_pts_axle[0][1] = dlPoint(DL_TRACK_R - half_steered, DL_FRONT_Y);
g_pts_axle[1][0] = dlPoint(DL_TRACK_L + half, DL_REAR_Y);
g_pts_axle[1][1] = dlPoint(DL_TRACK_R - half, DL_REAR_Y);
g_front_axle.axle = makeLine(g_diff_box, g_pts_axle[0], 2, 3, true);
g_rear_axle.axle = makeLine(g_diff_box, g_pts_axle[1], 2, 3, true);
g_front_axle.tyre[0] = makeTyre(g_diff_box, g_pts_tyre[0][0], g_pts_fill[0][0], DL_TRACK_L, DL_FRONT_Y, DL_STEER);
g_front_axle.tyre[1] = makeTyre(g_diff_box, g_pts_tyre[0][1], g_pts_fill[0][1], DL_TRACK_R, DL_FRONT_Y, DL_STEER);
g_rear_axle.tyre[0] = makeTyre(g_diff_box, g_pts_tyre[1][0], g_pts_fill[1][0], DL_TRACK_L, DL_REAR_Y, 0);
g_rear_axle.tyre[1] = makeTyre(g_diff_box, g_pts_tyre[1][1], g_pts_fill[1][1], DL_TRACK_R, DL_REAR_Y, 0);
diffCross(g_diff_box, g_front_axle, 0, DL_SHAFT_X, DL_FRONT_Y);
diffCross(g_diff_box, g_rear_axle, 1, DL_SHAFT_X, DL_REAR_Y);
// Live DDE values (rail, boost, charge-air temp, battery). A button, not a
// swipe, so polling the engine ECU never starts by accident. Below the
// overlay band (y 60, like the chips), left of the diff-lock drawing.
lv_obj_t* eng = UiKit::button(g_screen, LV_SYMBOL_CHARGE " Engine data", 200, 56,
UiKit::BTN_SECONDARY, onEngineData, NULL);
lv_obj_align(eng, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16, 60);
// ---- gear hero -------------------------------------------------------
g_gear_ring = lv_obj_create(g_screen);
lv_obj_set_size(g_gear_ring, 220, 220);
@@ -322,6 +507,8 @@ void tick() {
(void)gear; // gear now comes from the driveline pieces, not the UART enum
lvgl_port_lock(-1);
refreshDiffLocks(); // hard-wired inputs: live even with CAN or the key off
// Blank every readout when there's nothing live to show: CAN off, or the key
// is off. The user asked for a full reset on ignition-off so the screen goes
// quiet with the car rather than freezing the last frame. 0x3B4 sends its
+169
View File
@@ -0,0 +1,169 @@
/*
* Engine Data Screen Module Implementation - see engine_screen.h
*/
#include "engine_screen.h"
#include "ui_kit.h"
#include "diag_probe.h"
#include "driveline_screen.h"
#include "display/lvgl_v8_port.h"
namespace EngineScreen {
using namespace UiKit;
// ============================================================================
// SCALINGS (raw = the 2-byte value of `6C 10 HH LL`)
// ============================================================================
typedef struct {
DiagProbe::live_id_t id;
const char* title;
const char* unit;
float factor;
float offset;
int decimals;
bool provisional; // fitted to a single Launch reading
} channel_t;
static const channel_t CHANNELS[DiagProbe::LIVE_COUNT] = {
// verified 2026-09-23 against the Launch at two operating points
{DiagProbe::LIVE_RAIL, "Rail pressure", "bar", 0.03f, 0.0f, 1, false},
// 8271 raw <-> ~1028-1034 mbar engine off (2026-10-07): 1/8 mbar per count
{DiagProbe::LIVE_BOOST, "Boost (absolute)", "mbar", 0.125f, 0.0f, 0, true},
// 5295..5301 raw <-> Launch 36-38 C engine off (2026-10-07)
{DiagProbe::LIVE_AIR_TEMP, "Charge-air temp", "\xC2\xB0" "C", 0.01f, -15.0f, 1, true},
// 4998 raw <-> 12.27 V engine off (2026-10-07, from the capture's file name)
{DiagProbe::LIVE_BATTERY, "Battery", "V", 0.002455f, 0.0f, 2, true},
};
static const uint32_t STALE_MS = 3000; // value older than this shows "--"
// ============================================================================
// STATE
// ============================================================================
static lv_obj_t* g_screen = NULL;
static lv_obj_t* g_status = NULL;
static lv_obj_t* g_value[DiagProbe::LIVE_COUNT];
static lv_obj_t* g_raw[DiagProbe::LIVE_COUNT];
static void onBack(lv_event_t* e) {
(void)e;
DiagProbe::liveStop();
DrivelineScreen::show();
}
static void onGesture(lv_event_t* e) {
(void)e;
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act());
DiagProbe::liveStop();
DrivelineScreen::show();
}
}
static void makeCard(lv_obj_t* parent, int i) {
const channel_t& ch = CHANNELS[i];
lv_obj_t* c = card(parent);
lv_obj_set_size(c, 476, 200);
lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(c, 20, 0);
lv_obj_set_style_pad_row(c, 8, 0);
lv_obj_t* top = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(top, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(top, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
label(top, ch.title, &lv_font_montserrat_24, UI_COL_MUTED);
if (ch.provisional) {
lv_obj_t* tag = label(top, "provisional", &lv_font_montserrat_14, UI_COL_AMBER);
lv_obj_set_style_border_color(tag, UI_COL_AMBER, 0);
lv_obj_set_style_border_width(tag, 1, 0);
lv_obj_set_style_radius(tag, 6, 0);
lv_obj_set_style_pad_hor(tag, 8, 0);
lv_obj_set_style_pad_ver(tag, 3, 0);
}
lv_obj_t* row = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(row, 12, 0);
g_value[i] = label(row, "--", &lv_font_montserrat_48, UI_COL_TEXT);
lv_obj_t* u = label(row, ch.unit, &lv_font_montserrat_24, UI_COL_MUTED);
lv_obj_set_style_pad_bottom(u, 6, 0);
g_raw[i] = label(c, "raw --", &lv_font_montserrat_20, UI_COL_MUTED);
}
static void build() {
if (g_screen) return;
g_screen = screen();
lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL);
header(g_screen, "ENGINE DATA", onBack);
g_status = label(g_screen, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_set_pos(g_status, 24, 84);
lv_obj_t* grid = box(g_screen, LV_FLEX_FLOW_ROW_WRAP);
lv_obj_set_size(grid, 1024 - 48, 200 * 2 + 24);
lv_obj_set_pos(grid, 24, 126);
lv_obj_set_style_pad_column(grid, 24, 0);
lv_obj_set_style_pad_row(grid, 24, 0);
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) makeCard(grid, i);
}
static void refresh() {
const char* st;
lv_color_t col = UI_COL_MUTED;
switch (DiagProbe::liveState()) {
case DiagProbe::LIVE_RUNNING:
st = LV_SYMBOL_OK " Live from the engine ECU (DDE)"; col = UI_COL_OK; break;
case DiagProbe::LIVE_PAUSED_TESTER:
st = LV_SYMBOL_PAUSE " Paused: another diagnostic tester is connected (e.g. the Launch)"; col = UI_COL_AMBER; break;
case DiagProbe::LIVE_CAN_OFF:
st = LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System"; col = UI_COL_WARN; break;
case DiagProbe::LIVE_NO_ANSWER:
st = LV_SYMBOL_WARNING " No answer from the engine ECU - is the ignition on?"; col = UI_COL_WARN; break;
default:
st = "Starting..."; break;
}
setText(g_status, st);
setTextColor(g_status, col);
char buf[48];
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
const channel_t& ch = CHANNELS[i];
DiagProbe::live_value_t v = DiagProbe::liveValue(ch.id);
if (v.valid && v.age_ms < STALE_MS) {
snprintf(buf, sizeof(buf), "%.*f", ch.decimals, v.raw * ch.factor + ch.offset);
setText(g_value[i], buf);
snprintf(buf, sizeof(buf), "raw %u (0x%04X)", v.raw, v.raw);
} else {
setText(g_value[i], "--");
if (v.nrc) snprintf(buf, sizeof(buf), "refused by the ECU (NRC 0x%02X)", v.nrc);
else if (v.valid) snprintf(buf, sizeof(buf), "raw %u (stale)", v.raw);
else snprintf(buf, sizeof(buf), "raw --");
}
setText(g_raw[i], buf);
}
}
void show() {
build();
DiagProbe::liveKeepAlive();
refresh();
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
}
void tick() {
if (g_screen == NULL || lv_scr_act() != g_screen) return;
DiagProbe::liveKeepAlive(); // polling stops ~1.5 s after the screen is left
static uint32_t last = 0;
if (millis() - last < 250) return;
last = millis();
lvgl_port_lock(-1);
refresh();
lvgl_port_unlock();
}
} // namespace EngineScreen
+31
View File
@@ -0,0 +1,31 @@
/*
* Engine Data Screen Module
*
* Four live values read from the DDE (engine ECU) with the same KWP `2C 10`
* requests the Launch scanner uses: rail pressure, boost (charge-air pressure,
* actual), charge-air temperature, battery voltage. Polling (DiagProbe's live
* mode) runs only while this screen is shown and pauses while another tester
* is on the bus.
*
* Scalings come from Launch captures (wiki/pages/obd-diagnostic-polling.md);
* the ones resting on a single reading are tagged "provisional" on screen, and
* every value shows its raw number so it can be compared with the Launch.
*
* Opened from the "Engine data" button on the Driveline screen; the Driveline
* button or a right swipe goes back.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
namespace EngineScreen {
/** Build (idempotent) and load. Caller holds the LVGL lock. */
void show();
/** Keep the poll alive and refresh values while shown. Call from loop(); takes its own lock. */
void tick();
} // namespace EngineScreen
+30
View File
@@ -19,6 +19,8 @@ static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
static const char* NVS_KEY_UART_ENABLED = "uart_en";
static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
static const char* NVS_KEY_CAN_ENABLED = "can_en";
static const char* NVS_KEY_DIFFLOCK_ENABLED = "difflock_en";
static const char* NVS_KEY_DIFFLOCK_INVERT = "difflock_inv";
// ============================================================================
// PUBLIC API IMPLEMENTATION
@@ -89,4 +91,32 @@ bool loadCANState() {
return enabled;
}
void saveDiffLockState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_DIFFLOCK_ENABLED, enabled);
preferences.end();
Serial.printf("[SettingsManager] Saved DiffLock state = %s\n", enabled ? "ON" : "OFF");
}
bool loadDiffLockState() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool enabled = preferences.getBool(NVS_KEY_DIFFLOCK_ENABLED, false); // default: OFF
preferences.end();
return enabled;
}
void saveDiffLockInvert(bool inverted) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_DIFFLOCK_INVERT, inverted);
preferences.end();
Serial.printf("[SettingsManager] Saved DiffLock polarity = %s\n", inverted ? "INVERTED" : "normal");
}
bool loadDiffLockInvert() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool inverted = preferences.getBool(NVS_KEY_DIFFLOCK_INVERT, false); // default: current = locked
preferences.end();
return inverted;
}
} // namespace SettingsManager
+8
View File
@@ -66,4 +66,12 @@ void saveCANState(bool enabled);
*/
bool loadCANState();
/** Diff-lock inputs DI0/DI1 read (DiffLocks). Default OFF. */
void saveDiffLockState(bool enabled);
bool loadDiffLockState();
/** Diff-lock polarity: true = no current means locked. Default false. */
void saveDiffLockInvert(bool inverted);
bool loadDiffLockInvert();
} // namespace SettingsManager
+45 -6
View File
@@ -8,6 +8,7 @@
#include "wifi_manager.h"
#include "ota_update.h"
#include "link_peer.h"
#include "diff_locks.h"
#include "uart_manager.h"
#include "espnow_link.h"
#include "settings_manager.h"
@@ -82,6 +83,9 @@ static Ota::phase_t g_upd_refusal_phase = Ota::PHASE_IDLE;
static lv_obj_t* g_sys_can = NULL;
static lv_obj_t* g_sys_link = NULL;
static lv_obj_t* g_sys_dbg = NULL;
static lv_obj_t* g_sys_diff = NULL;
static lv_obj_t* g_sys_diff_inv = NULL; // polarity: no current = locked
static lv_obj_t* g_sys_diff_sub = NULL; // sub-line of the diff-lock row: live state
static lv_obj_t* g_sys_info = NULL; // values column; keys are static
static void refresh(bool force);
@@ -768,10 +772,30 @@ static void onDebugSwitch(lv_event_t* e) {
UIStateManager::setDebugEnabled(on);
}
static void onDiffSwitch(lv_event_t* e) {
if (g_refreshing) return;
DiffLocks::setEnabled(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED));
}
static void onDiffInvertSwitch(lv_event_t* e) {
if (g_refreshing) return;
DiffLocks::setInverted(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED));
}
static void refreshSystem(bool force) {
setChecked(g_sys_can, CANDriver::isActive());
setChecked(g_sys_link, UARTManager::getState() != UARTManager::UART_STATE_OFF);
setChecked(g_sys_dbg, UIStateManager::isDebugEnabled());
setChecked(g_sys_diff, DiffLocks::isEnabled());
setChecked(g_sys_diff_inv, DiffLocks::isInverted());
// live state in the sub-line, so the wiring can be tested from this page
if (!DiffLocks::isEnabled()) setText(g_sys_diff_sub, DiffLocks::isInverted()
? "DI0 rear, DI1 front - 0 V = locked"
: "DI0 rear, DI1 front - 12 V = locked");
else if (!DiffLocks::isValid()) setText(g_sys_diff_sub, "Now: reading...");
else setText(g_sys_diff_sub, DiffLocks::frontLocked()
? (DiffLocks::rearLocked() ? "Now: rear LOCKED, front LOCKED" : "Now: FRONT only - check DI0 wiring")
: (DiffLocks::rearLocked() ? "Now: rear LOCKED, front open" : "Now: both open"));
static uint32_t last = 0; // the figures below change slowly; 1 Hz is plenty
if (!force && millis() - last < 1000) return;
@@ -782,18 +806,17 @@ static void refreshSystem(bool force) {
uint32_t up = millis() / 1000;
char buf[400];
snprintf(buf, sizeof(buf),
"%s (slot %s)\n"
"%s (slot %s), up %lu h %02lu min\n"
"ESP-NOW %s, %lu frames sent, %lu failed\n"
"%lu frames received\n"
"%u KB internal free, %u KB PSRAM free\n"
"%lu h %02lu min",
"%u KB internal free, %u KB PSRAM free",
FW_VERSION, run ? run->label : "?",
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60),
EspNowLink::isReady() ? "up" : "DOWN",
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount(),
(unsigned long)cs.messages_received,
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) / 1024),
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024),
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60));
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
setText(g_sys_info, buf);
}
@@ -810,13 +833,29 @@ static void buildSystemPage(lv_obj_t* page) {
g_sys_link = toggle(right, onLinkSwitch, NULL);
makeSettingRow(c, "Performance overlay", "Frame rate and CPU load in the corner", &right);
g_sys_dbg = toggle(right, onDebugSwitch, NULL);
lv_obj_t* diff_row = makeSettingRow(c, "Diff lock inputs", "DI0 rear, DI1 front - 12 V = locked", &right);
g_sys_diff_sub = lv_obj_get_child(lv_obj_get_child(diff_row, 0), 1);
// two switches on the right: polarity ("Inverted") and on/off; the page has no room for a fifth row
lv_obj_t* diff_right = box(right, LV_FLEX_FLOW_ROW);
lv_obj_set_size(diff_right, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
// START, not END: with END, LVGL 8's content-size pass measures only the last child
// (the earlier ones sit at negative x) and clips "Inverted" away - seen on the board.
// The row's SPACE_BETWEEN already pushes this box to the right edge.
lv_obj_set_flex_align(diff_right, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(diff_right, 12, 0);
label(diff_right, "Inverted", &lv_font_montserrat_20, UI_COL_MUTED);
g_sys_diff_inv = toggle(diff_right, onDiffInvertSwitch, NULL);
lv_obj_t* gap = box(diff_right, LV_FLEX_FLOW_ROW);
lv_obj_set_size(gap, 12, 1);
g_sys_diff = toggle(diff_right, onDiffSwitch, NULL);
// two labels side by side, same line spacing, so keys and values line up
lv_obj_t* info = card(page);
lv_obj_set_size(info, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(info, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(info, 24, 0);
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory\nUptime", &lv_font_montserrat_20, UI_COL_MUTED);
// Uptime shares the firmware line: a fourth switch row leaves no room for a fifth line (484 px page)
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_set_style_text_line_space(keys, 6, 0);
g_sys_info = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT);
lv_obj_set_style_text_line_space(g_sys_info, 6, 0);
+3 -1
View File
@@ -1,6 +1,6 @@
---
type: index
updated: 2026-09-27
updated: 2026-10-07
---
# Index
@@ -13,6 +13,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
- [[bmw-m57n-engine]] — the 3.0L BMW diesel whose CAN bus we read; E60/E65 donor (confirmed), DDE ECU, auto box with EGS on bus
- [[nissan-patrol-swap]] — the target vehicle: Patrol receiving the M57N + BMW auto; the tapped bus is a BMW island in a Nissan
- [[esp32-s3-touch-lcd-5b]] — Waveshare 5" display board (Main CTRL); onboard TJA1051 CAN transceiver, 7–36 V input, pinout, PSRAM/LCD gotchas — **flash writes flicker the RGB panel, full-screen fades stutter, internal RAM nearly full, opening the serial port resets the board unless DTR/RTS are low; Wi-Fi scans caused the flickering dots; all screens hand-coded since 2026-09-27**
- [[diff-lock-inputs]] — **2026-09-29**: Patrol diff locks (+12 V = locked) on DI0 rear / DI1 front, `DI_COM` to ground; PC814 → CH422G EXIO0/EXIO5 (active low); the bank flip per read is unverified for panel flicker, so it is behind a Settings switch, default OFF
## Concepts
@@ -45,5 +46,6 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
- [[google-ai-dde7m57-pids]] — Google AI Mode clipping on "dde7m57 pids" (ingested 2026-09-21, raw in `Clippings/`): uncited; its `0x612`-as-request claim is **contradicted**, its D1xx identifiers are `(unverified)`; kept for the Ediabas value names and the user's own observation that `0x612` appears with the Launch connected
- [[diag-route-a-2026-09-23]] — **first live Route A probe run (2026-09-23)**: DDE serves generic OBD mode 01 on `0x7E8` (verified: rpm + coolant cross-checked against the broadcast IDs); supported-PID list; MAF/IAT values implausible (explained by Route B session: sensor faults); mode 09 silent (no VIN); **5 stored DTCs, MIL off**; raw at `raw/diag-20260923-1117*.log`
- [[launch-capture-2026-09-23]] — **rail pressure decoded via Launch capture (2026-09-23)**: the DDE serves live data through service `2C` (`2C 10 00 DF` → `6C 10 HHLL`); **rail pressure bar = HHLL × 0.03**, verified two-point against the Launch (idle 305 / 2500 rpm 430); recipe generalises to any Launch-visible value; self-poll needs the session handshake (design decision); raw at `raw/serial-COM10-20260923-163511.log`
- [[launch-captures-2026-10-07]] — **boost, charge-air temp and battery identifiers** found with the CANNY logger while the Launch polled (engine off): `0091` boost (mbar ≈ raw ÷ 8), `16A8` charge-air temp, `0093` battery — scalings provisional (one point each); feeds the Engine data screen
- [[diag-route-b-2026-09-23]] — **Route B verified + DTCs read (same day)**: `0x6F1 [12]` → `0x612` confirmed live; `1A 86` ident = **VIN prefix WBANC92090 (E60 530d), DDE part numbers 7799764/7799765/7793887, 2006-03, KWP2000 not UDS**; `diag dtc` = P0101/P0113/P0500/P0545/P0030 (all disconnected-sensor swap leftovers); raw at `raw/diag-20260923-124*.log`
- [[dwr-335d-torque-pids]] — **DWR's "Extended BMW 335d PIDs for Torque"** (thread page 1 + `raw/BMW 335d.csv`, ingested 2026-09-21): a gauge-checked set of **generic J1979 mode-01 PIDs** from an M57 diesel (2009 335d, DDE7.3) — boost via PID 70, exhaust pressure, EGTs, MAF, fuel rate; nothing BMW-proprietary. Basis for the "try generic OBD first" route; the diesel-specific PIDs are probably absent on our EDC16
+12
View File
@@ -218,3 +218,15 @@ User renamed Controller A → **Main CTRL** and Controller B → **Inst. Cluster
## [2026-09-28] update | Deep-sleep feature REMOVED (user decision) - and the lesson it left
The "Sleep when the car is off" switch and both power managers are gone: code, Settings row, NVS key, the `CFG_SLEEP_WHEN_SILENT` bit in the shared header, the wiki page and the cheat-sheet entries. Reason: on the bench the Main CTRL's panel showed flickering white edges after a sleep, and it stayed that way through resets and even a USB flash of release v0.1.8. Cause, understood too late: `gpio_hold_en()` on the 20 RGB panel lines (added to blank the panel in sleep) lives in the RTC domain and **survives every reset except a power cycle** - no firmware without a matching `gpio_hold_dis()` at boot can drive the panel again. Only pulling the power clears it. **Rule for the future: never use GPIO hold / deep-sleep hold on this board's panel lines, and never send a board to deep sleep from the console without the user's go-ahead** (the USB port vanishes and only reset or power brings it back). The boards stay awake whenever powered; if power saving is ever wanted again, do it in hardware (ignition-switched supply).
## [2026-09-29] update | Diff-lock inputs on DI0 / DI1
The user wants the two Patrol diff locks (+12 V while locked; the front only locks after the rear) shown on the Main CTRL. From the schematic: DI0 = CH422G EXIO0, DI1 = EXIO5, active low behind PC814. The CH422G's IO0-7 are one all-in/all-out bank shared with touch reset, backlight and LCD reset, so the firmware flips the bank to input for about 0.1 ms per read, 4 Hz. It is behind a Settings switch, default OFF, until tried on the bench for flicker. New page [[diff-lock-inputs]]; the schematic source page now carries the input circuit and the EXIO net table.
## [2026-09-29] update | Diff-lock polarity is inverted in the car
In the car the Driveline showed locked while unlocked and open while locked; the bench (12 V = locked) had been right. The likely cause is the ground-switched dash lamps (unverified). Added a per-board polarity setting: the "Inverted" switch in the Settings diff-lock row and `difflock invert on|off`, NVS `difflock_inv`. [[diff-lock-inputs]] is corrected.
## [2026-10-07] ingest + build | Boost / charge-air temp / battery identifiers; Engine data screen
Ingested three CANNY-logger captures (`raw/airtemp38-63.txt`, `raw/boost.txt`, `raw/battery12-27.txt`) -> [[launch-captures-2026-10-07]]: the Launch reads `2C 10 16A8` (charge-air temp), `0091` (boost actual), `0093` (battery), each a 2-byte `6C 10` reply. Engine off throughout, so one calibration point each: boost mbar = raw / 8 fits 1028-1034 mbar; temp and battery fits are guesses. User decision: a no-password **Engine data screen** (button on Driveline) showing rail, boost, charge-air temp, battery - polled only while shown, paused while another tester is on the bus, provisional values tagged and raw shown. Updated [[obd-diagnostic-polling]] (identifier table, decision), index.
+51
View File
@@ -0,0 +1,51 @@
---
type: concept
tags: [hardware, patrol, inputs, ch422g, wiring]
updated: 2026-09-29
---
# Diff-lock inputs (DI0 rear, DI1 front)
The Patrol has two differential locks. The user first described the wires as carrying **+12 V while a diff is locked**. In the car, the screen then showed the opposite (verified by the user, 2026-09-29): the wires carry current while unlocked and none once locked.
> [!warning] Polarity in the car is inverted
> On the bench, 12 V on DI0 showed locked (verified). In the car, the same firmware showed locked while unlocked and open while locked (verified, 2026-09-29). The likely cause is the usual lamp wiring: the dash lamp is fed +12 V and the diff's position switch grounds it on lock. A wire tapped between the lamp and the switch then sits at about 12 V through the lamp filament while unlocked, and at 0 V once the switch closes `(unverified: wiring not traced)`. Fix: the per-board **Inverted** switch (Settings → System, diff-lock row) or `difflock invert on` `(repo)`. With it on, a broken wire reads as *locked*, which shows up as amber, not as a silent "open".
The front can only be locked after the rear, so the valid states are: none, rear only, rear + front (source: user). The Main CTRL shows them on the Driveline screen from its two isolated inputs.
## Wiring
| Terminal (16-way block) | Connect to |
|---|---|
| `DI0` | rear diff-lock wire (in the car: 12 V = UNlocked, so turn Inverted on) |
| `DI1` | front diff-lock wire (same) |
| `DI_COM` | vehicle ground (chassis, same ground as the board's `GND`) |
This is Waveshare's "PNP wet input / high-level trigger" wiring: `DI_COM` to the negative pole, 5–36 V DC on the input (source: [[esp32-s3-touch-lcd-5b-waveshare-wiki]]). Tap the wires in parallel with whatever the Patrol already drives with them (dash lamp); each input draws only ~3 mA.
## Circuit (source: [[esp32-s3-touch-lcd-5-schematic]], sheet 1, "DI/DO")
- `DINx` → PC814 LED (bidirectional, so polarity does not matter) → 3.6 kΩ (R78 / R73, 1206) → `DI_COM`. At 12 V: (12 − 1.2) / 3.6 k ≈ **3.0 mA**; at 14.4 V charging ≈ 3.7 mA.
- 100 nF across each input (C100 / C101) filters spikes.
- `DI_COM` is also fed from 5 V through D4 (1N5822) + R79 220 Ω. That is what makes the "dry contact" mode work (`DI_COM` left open, the input switched to ground). With `DI_COM` on ground, as here, that path draws ~20 mA from the board's 5 V rail `(unverified: read from the schematic, not measured)`.
- Output side: the phototransistor pulls `DI0` / `DI1` (4.7 kΩ to 3V3) **low** while current flows. `DI0` = CH422G **EXIO0**, `DI1` = **EXIO5** (net table on the same sheet). So **locked = bit reads 0**.
## How the firmware reads them `(repo)`
The CH422G's IO0–7 are **one bank, all inputs or all outputs**, and the same bank drives touch reset (EXIO1), backlight (EXIO2) and LCD reset (EXIO3). The firmware switches the bank to input for about 0.1 ms per read (three I2C transactions: WR_SET 0x00, read, WR_SET 0x01), 4 times a second, under the LVGL lock. The chip keeps its output latch, so the outputs return to their previous levels. Another project does the same on a running display (source: github.com/VaAndCob/waveshare-esp32-s3-5inch-ch422g-driver, `EX_Read()`).
> [!warning] Not yet verified on this board
> Whether the 0.1 ms float disturbs the panel (flicker) or touch is **unknown** until tried. That is why the feature sits behind **Settings → System → Diff lock inputs**, default OFF. A board without the wiring never flips the bank. If the panel flickers with the switch on, turn it off. The fallback is to move the inputs to spare GPIOs on the Inst. Cluster.
A state counts after two equal reads, so it can lag the real switch by up to 0.5 s. The Driveline draws a top view of the chassis, after the user's sketch. A locked axle turns amber: axle, tyres filled, and an X on the diff. There is no text; the drawing alone carries the state (user, 2026-09-29). Front locked without rear turns the front axle red, as a wiring or switch fault (verified on the bench by the user, 2026-09-29, with the earlier pill display: DI1 alone showed red, both inputs showed amber).
## Test on the bench
1. Settings → System → Diff lock inputs ON. The row's sub-line shows "Now: both open".
2. Put 12 V (the board's own VIN supply) on `DI0`, with `DI_COM` on `GND`. It should show "rear LOCKED", and the rear axle in the Driveline chassis drawing turns amber with an X on the diff. Then do the same on `DI1`.
3. Console: `difflock status` prints the raw IO byte: bit 0x01 (rear) and bit 0x20 (front) are SET while open, clear while locked.
4. Watch the panel for flicker while the switch is on (see the warning above).
## Related
[[esp32-s3-touch-lcd-5b]] · [[esp32-s3-touch-lcd-5-schematic]] · [[patrol-instrument-cluster]]
+16 -1
View File
@@ -1,7 +1,7 @@
---
type: concept
tags: [can-bus, dde, egs, diagnostics, kwp2000, uds, obd, design-decision, rail-pressure]
updated: 2026-09-23
updated: 2026-10-07
---
# OBD / Diagnostic Polling
@@ -123,6 +123,21 @@ Run via `tools/diag_session.py` (one serial session, logs straight into `wiki/ra
5. `diag status` once at the end (counters, tester guard), then stop the monitor.
6. Copy the log into `raw/`, write a `sources/` page with the supported-PID list and the VIN, update this page (Route A verified / refuted) and [[open-questions]] #2 and #7.
## Known live-data identifiers (`2C 10 <id>` → `6C 10 HH LL`)
| Value | ID | Scaling | Status |
|---|---|---|---|
| Rail pressure, actual | `00DF` | bar = raw × 0.03 | `(verified 2026-09-23)`, two points |
| Charge-air pressure, actual (boost, absolute) | `0091` | mbar = raw ÷ 8 | `(unverified)` one point, engine off |
| Charge-air temperature | `16A8` | °C = raw × 0.01 − 15 | `(unverified)` one point, engine off |
| Battery voltage | `0093` | V = raw × 0.002455 | `(unverified)` one point, engine off |
Evidence: [[launch-capture-2026-09-23]], [[launch-captures-2026-10-07]]. Each provisional scaling needs one more capture at a different operating point.
## Engine data screen `(repo, 2026-10-07)`
**Decision (user, 2026-10-07):** the four values above get their own screen on Controller A, opened by an **"Engine data" button on the Driveline screen**, **no password**. This replaces the 2026-09-23 plan of a password-protected Diagnostics screen for these reads. Guard rails kept: polling runs **only while the screen is shown** (stops ~1.5 s after it is left), one request in flight, ~100 ms apart (each value ~2.5 Hz), **pauses while another tester is on the bus** (3 s guard), only these fixed frames - `2C` stays forbidden from the `diag` console. Sends the Launch's `2C 10 15 E0` once per start, then the four reads in turn. Provisional scalings are tagged on screen and every value shows its raw number for calibration against the Launch. A password can still come with a future Diagnostics screen for anything beyond these reads.
## Beyond the probe `(repo)`
- **The decode recipe (proven 2026-09-23):** log `CANRAW` while the Launch shows a live value → find the `2C 10 <id>` / `6C 10 <data>` pair whose data tracks the reading → calibrate scale against the display at two operating points (idle + a blip). One session per parameter. Boost, MAF, injection quantity, EGTs all reachable this way. Worked example: [[launch-capture-2026-09-23]] (rail pressure).
+1 -1
View File
@@ -24,7 +24,7 @@ The research frontier. Answering any of these should trigger updates across the
## Design decisions (parked, not blocking)
12. **The "Diagnostics" screen (planned 2026-09-23).** Active diagnostic polling — replaying the `2C` live-data reads we decoded ([[launch-capture-2026-09-23]]) so values like rail pressure appear on Main CTRL without the Launch — is now technically unblocked (no session/security needed). Intended design when built: a **password-protected Diagnostics screen**, authorized-technician access only, manual trigger, refuses while a scan tool is connected, read-oriented services only. The same gate covers the general transmit-on-the-bus decision. This is deliberately deferred, but the capability, the byte sequences, and these guard rails are recorded so the work resumes from here, not from scratch. OTA check/install was meant to live here too (2026-09-26); **decided otherwise 2026-09-27**: it is on the Settings screen behind a confirm dialog ([[ota-updates]]). Whatever password this screen gets must be stored as a salted hash in NVS because the firmware is public. → [[obd-diagnostic-polling]], [[dual-controller-architecture]], [[ota-updates]]
12. **The "Diagnostics" screen (planned 2026-09-23).** Active diagnostic polling — replaying the `2C` live-data reads we decoded ([[launch-capture-2026-09-23]]) so values like rail pressure appear on Main CTRL without the Launch — is now technically unblocked (no session/security needed). Intended design when built: a **password-protected Diagnostics screen**, authorized-technician access only, manual trigger, refuses while a scan tool is connected, read-oriented services only. The same gate covers the general transmit-on-the-bus decision. This is deliberately deferred, but the capability, the byte sequences, and these guard rails are recorded so the work resumes from here, not from scratch. **Update 2026-10-07:** the first live reads (rail, boost, charge-air temp, battery) ship on a no-password **Engine data screen** instead (user decision; guard rails in [[obd-diagnostic-polling]]); this password-gated screen remains the plan for anything beyond those reads. OTA check/install was meant to live here too (2026-09-26); **decided otherwise 2026-09-27**: it is on the Settings screen behind a confirm dialog ([[ota-updates]]). Whatever password this screen gets must be stored as a salted hash in NVS because the firmware is public. → [[obd-diagnostic-polling]], [[dual-controller-architecture]], [[ota-updates]]
## Project context
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+8065
View File
File diff suppressed because it is too large Load Diff
@@ -28,6 +28,7 @@ Raw: `raw/ESP32-S3-Touch-LCD-5-Sch.pdf` (3 sheets, V1.2), re-downloaded 2026-09-
- CAN: `CANTX` = IO15, `CANRX` = IO16 (matches `(repo)`); RS485: `RS485_TXD` = IO44, `RS485_RXD` = IO43 (matches [[esp32-s3-touch-lcd-5-intro-photo]]).
- SD card on `MOSI` IO11 / `SCK` IO12 / `MISO` IO13, `SDCS` on CH422G `EXIO4` — the pin facts needed for the SD "black box" idea in [[obd-diagnostic-polling]].
- Isolated outputs `DO0`/`DO1` via PC817 optocouplers driven from `OD0`/`OD1` (CH422G), inputs `DI0`/`DI1` via PC814.
- Input detail (read 2026-09-29 for [[diff-lock-inputs]]): `DINx` → PC814 LED → 3.6 kΩ 1206 → `DI_COM`, 100 nF across. `DI_COM` is also fed from 5 V via D4 1N5822 + R79 220 Ω, for dry contacts. The phototransistor pulls `DI0`/`DI1` (4.7 kΩ to 3V3) low. The net table maps `DI0` = **EXIO0** and `DI1` = **EXIO5**. The rest of the bank: EXIO1 `CTP_RST`, EXIO2 `DISP`, EXIO3 `LCD_RST`, EXIO4 `SDCS`.
- Strapping pads `R87–R94` (IO0/IO3/IO45/IO46).
## Related
@@ -0,0 +1,42 @@
---
type: source
tags: [can-bus, obd, dde, kwp2000, launch, boost, charge-air, battery, live-data, capture]
updated: 2026-10-07
---
# Launch live-data captures — boost, charge-air temp, battery (2026-10-07)
Three short captures taken by the user with the **CANNY 5.3 Pico logger** (tab-separated `ID CAN DLC bytes… ascii timestamp RX0`) while the Launch scanner showed one parameter at a time. **Engine off, ignition on** in all three (rpm 0 on `0x0AA`, coolant 72–74 °C on `0x1D0`). Raw: `raw/airtemp38-63.txt` (12.9 s), `raw/boost.txt` (13.8 s), `raw/battery12-27.txt` (43.5 s).
## What the Launch sends
Same mechanism as [[launch-capture-2026-09-23]], one value per request, each cycle every ~210–240 ms:
1. `6F1: 12 02 1A 80` → multi-frame ident reply on `612` (the Launch re-reads the ECU ident every cycle; we don't need it)
2. `6F1: 12 04 2C 10 <id>` → `612: F1 04 6C 10 HH LL` — a 2-byte value
No define (`2C 10 15 E0`) appears in these logs - the Launch session was already open - so reads work at least after one define per session `(verified)`.
## Identifiers found
| Launch parameter | ID | Raw seen (engine off) | Launch showed | Scaling (best current) | Confidence |
|---|---|---|---|---|---|
| Charge-Air Temperature | `16A8` | 5295–5301 | 36–38 °C | °C = raw × 0.01 − 15 → 38.0 | `(unverified)` one point; the Launch's 2 °C spread doesn't fit a 6-count raw spread, so multiplier/offset are not separable yet |
| Charge-Air Pressure, Actual | `0091` | 8271 (flat) | 1028 mbar off (read later, separate session); first read as "1080 pascal" (misread) | mbar = raw ÷ 8 → 1034 | `(unverified)` one point, within 0.6% (weather drift between sessions plausible); 1/8 mbar per count is a typical ECU fixed-point unit |
| Battery Voltage | `0093` | 4990–5006 | 12.27 V (from the file name; not confirmed by the user) | V = raw × 0.002455 | `(unverified)` one point |
| Rail Pressure (start of the battery log) | `00DF` | 212 / 285 | — | bar = raw × 0.03 → 6.4 / 8.6 bar residual | `(verified 2026-09-23)` |
The user also read, without a log: idle ≈ 1033 mbar, free-rev to 4000 rpm ≈ 1300 mbar (normal: a diesel turbo barely spools without load). `0x3B4` broadcast only its invalid marker in these logs, so it could not cross-check the battery value.
## To close the scalings
One capture per parameter at two clearly different states, with the Launch value noted at each: battery engine off (~12.3 V) vs running (~14 V); boost engine off vs held ~2500–3000 rpm (and ideally under load); charge-air temp cold vs after a drive. If raw ÷ 8 is right, 1300 mbar reads ~10400 raw (`0x28A0`).
## Consequences
- **Boost is reachable** — the value the project wanted from the start and that the DDE never broadcasts ([[obd-diagnostic-polling]]).
- Built 2026-10-07 into Controller A's **Engine data screen** (rail, boost, charge-air temp, battery), polled only while the screen is shown, pausing while another tester is on the bus; provisional scalings are tagged on screen and raw values shown for calibration `(repo)`.
## Related
[[obd-diagnostic-polling]] · [[launch-capture-2026-09-23]] · [[bmw-m57n-engine]] · [[open-questions]]