13 Commits

Author SHA1 Message Date
julian 1cba9f30bc Reverse lights on DO0, Sport + Vehicle screens, per-DDE live data, ECU identification
Firmware / build (push) Successful in 10m49s
- ReverseLight: isolated output DO0 (CH422G OC0 -> PC817 -> NPN sink) drives the
  reverse-lamp relay while the lever is in R on a live bus with ignition on; 10 Hz
  decision confirmed over 200 ms, written through the panel library's expander
  object so the backlight cannot undo it; `reverse status|on|off|force` console,
  default ON (NVS `revlight_en`). Wiki page reverse-lights-output with the wiring.
- Sport screen: BMW-style power + torque gauges (lv_meter on a dial-face image,
  image needle); PNG sources in assets/, tools/png2lvgl.py converter.
- Vehicle: final drive ratio + tyre circumference -> road speed, hp from torque;
  Settings > Vehicle page; `vehicle` console.
- Bench simulation (`sim` console) overlays torque / rpm / shaft on the snapshot.
- EcuIdent: KWP 1A 86 / 1A 80 read once, stored in NVS, shown on Settings >
  Vehicle, passive ECU CHANGED? check; `ecu` console.
- Ignition fallback from the 0x1D2 lever byte on buses without 0x3B4 (Patrol 2).
- Engine data: per-DDE `2C 10` identifier profiles (Patrol 1 vs Patrol 2
  rail 00C2 / boost 003A / battery 002F); DiagProbe liveConfigure().
- Wiki: Patrol 2 captures, vehicles page, obd identifier table per DDE, logs.
2026-10-28 16:46:42 +01:00
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
julian f07590bbc5 Remove the deep-sleep feature entirely (user decision): power manager, Settings switch, NVS key, sleep bit in the shared header, wiki page and cheat-sheet entries
Firmware / build (push) Successful in 6m59s
2026-09-28 17:20:54 +02:00
julian 59fae2c219 Sleep: drive and hold the 20 RGB panel lines low before deep sleep (white flickering edges seen on the bench)
Firmware / build (push) Successful in 7m7s
2026-09-28 16:53:16 +02:00
julian 803af7568f Rename Controller A/B -> Main CTRL / Inst. Cluster (user); Sleep when the car is off: Settings switch, deep sleep on quiet CAN + idle screen, CAN RX wake, switch mirrored to the cluster; docs
Firmware / build (push) Successful in 7m22s
2026-09-28 16:38:13 +02:00
julian 7a74c02b20 docs: COMMANDS.md - build, upload, monitor and console cheat-sheet for both controllers
Firmware / build (push) Failing after 6m11s
2026-09-28 10:21:06 +02:00
julian 63d64362e8 No invented data: shared structure starts with nothing valid, cleared on CAN stop and bus silence; DEFAULT_* removed from the shared header
Firmware / build (push) Successful in 7m19s
2026-09-28 09:30:59 +02:00
100 changed files with 112168 additions and 224 deletions
+3 -3
View File
@@ -1,6 +1,6 @@
name: Firmware name: Firmware
# Controller A firmware, built by PlatformIO on every push. Two outputs: # Main CTRL firmware, built by PlatformIO on every push. Two outputs:
# #
# - push to main -> rolling PRE-release `main-latest` (firmware.bin + .elf), # - push to main -> rolling PRE-release `main-latest` (firmware.bin + .elf),
# unsigned, no manifest. For bench testing / USB flashing. # unsigned, no manifest. For bench testing / USB flashing.
@@ -143,12 +143,12 @@ jobs:
if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
TAG="${GITHUB_REF_NAME}" TAG="${GITHUB_REF_NAME}"
PRE=false PRE=false
NAME="Controller A ${TAG}" NAME="Main CTRL ${TAG}"
BODY="Signed OTA release. Install on the controller with \`ota install\` (parked, Wi-Fi joined)." BODY="Signed OTA release. Install on the controller with \`ota install\` (parked, Wi-Fi joined)."
else else
TAG="main-latest" TAG="main-latest"
PRE=true PRE=true
NAME="Controller A main build" NAME="Main CTRL main build"
BODY="Unsigned build of main @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests." BODY="Unsigned build of main @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests."
# Rolling: drop the previous release and its tag, recreate at this commit. # Rolling: drop the previous release and its tag, recreate at this commit.
OLD=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \ OLD=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \
+44 -13
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview ## Project Overview
Automotive display controller for **Waveshare ESP32-S3-Touch-LCD-5B** (1024x600 RGB LCD). This is a dual-controller system where Controller A (this ESP32-S3-LCD-5B) communicates automotive sensor data via UART to Controller B (ESP32-S3-LCD-1.3). Automotive display controller for **Waveshare ESP32-S3-Touch-LCD-5B** (1024x600 RGB LCD). This is a dual-controller system where Main CTRL (this ESP32-S3-LCD-5B) communicates automotive sensor data via UART to Inst. Cluster (ESP32-S3-LCD-1.3).
**Hardware**: ESP32-S3 dual-core @ 240MHz, 16MB Flash, 8MB OPI PSRAM, 5-inch capacitive touch LCD **Hardware**: ESP32-S3 dual-core @ 240MHz, 16MB Flash, 8MB OPI PSRAM, 5-inch capacitive touch LCD
@@ -12,6 +12,8 @@ Automotive display controller for **Waveshare ESP32-S3-Touch-LCD-5B** (1024x600
## Build & Development Commands ## Build & Development Commands
The complete cheat-sheet for BOTH controllers (build, upload, monitor, every console command, pairing, releasing) is `docs/COMMANDS.md`. Keep it current when a command changes.
### PlatformIO CLI ### PlatformIO CLI
```bash ```bash
@@ -75,7 +77,7 @@ src/
main.cpp # Main application logic only main.cpp # Main application logic only
modules/ modules/
wifi_manager.cpp # Wi-Fi: one remembered network, scans on request (no LVGL code) wifi_manager.cpp # Wi-Fi: one remembered network, scans on request (no LVGL code)
settings_screen.cpp # Hand-coded Settings screen: Wi-Fi / Updates / System (swipe left from Driveline) settings_screen.cpp # Hand-coded Settings screen: Wi-Fi / Updates / System / Vehicle (swipe left from Driveline)
ui_kit.cpp # Shared look for hand-coded screens: header, buttons, switches, confirm dialog ui_kit.cpp # Shared look for hand-coded screens: header, buttons, switches, confirm dialog
uart_manager.cpp # Link transmitter: v2 DATA/CONFIG frames on UART1 + ESP-NOW uart_manager.cpp # Link transmitter: v2 DATA/CONFIG frames on UART1 + ESP-NOW
tunables.cpp # Gauge calibration + alert thresholds (NVS, 'cfg' serial console) tunables.cpp # Gauge calibration + alert thresholds (NVS, 'cfg' serial console)
@@ -84,12 +86,22 @@ src/
diag_probe.cpp # On-demand OBD-II requests ('diag' console) - the ONLY CAN transmitter diag_probe.cpp # On-demand OBD-II requests ('diag' console) - the ONLY CAN transmitter
perf_monitor.cpp # 'perf' console: render fps, flush cost, LVGL/CPU idle, heap (display experiments) perf_monitor.cpp # 'perf' console: render fps, flush cost, LVGL/CPU idle, heap (display experiments)
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console) ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
link_peer.cpp # Controller B over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' 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 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)
reverse_light.cpp # Reverse-light relay on isolated output DO0 (CH422G OC0): follows the lever in R ('reverse' console, default ON)
settings_manager.cpp # NVS persistent storage settings_manager.cpp # NVS persistent storage
ui_state_manager.cpp # Debug flag (performance overlay, sent to B) ui_state_manager.cpp # Debug flag (performance overlay, sent to B)
display_init.cpp # Display initialization; boots into DrivelineScreen display_init.cpp # Display initialization; boots into DrivelineScreen
driveline_screen.cpp # Hand-coded LVGL boot screen (gear, temps, rpm, status) 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)
sport_screen.cpp # BMW-style Sport displays: torque + power gauges (lv_meter), Sport button on Driveline
vehicle.cpp # Final drive ratio + tyre circumference -> road speed; hp from torque x rpm ('vehicle' console, Settings > Vehicle)
bench_sim.cpp # 'sim' console: bench torque / rpm / output shaft overlaid on the driveline snapshot (never saved, off at boot)
ecu_ident.cpp # Which DDE this board is on: KWP ident read ONCE via DiagProbe, stored in NVS, UNKNOWN ECU until then ('ecu' console, Settings > Vehicle)
assets/
needle_img.c # Sport needle image (generated by tools/png2lvgl.py from assets/needle.png - never edit by hand)
dial_img.c # Sport dial face (generated from assets/dial.png - never edit by hand)
drivers/ drivers/
can_driver.cpp # CAN Bus driver (TWAI) can_driver.cpp # CAN Bus driver (TWAI)
@@ -106,10 +118,10 @@ include/
**src/main.cpp** (~1530 lines) **src/main.cpp** (~1530 lines)
- Main application logic, event handlers, FreeRTOS task implementations - Main application logic, event handlers, FreeRTOS task implementations
- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`, `link`), setup order, `loop()` ticks for the three screens - Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`, `link`, `difflock`, `reverse`, `vehicle`, `sim`, `ecu`), setup order, `loop()` ticks for every screen
**include/protocol/automotive_data.h** **include/protocol/automotive_data.h**
- **Shared with Controller B, must stay byte-identical in both repos.** Protocol v2 (2026-09-21). - **Shared with Inst. Cluster, must stay byte-identical in both repos.** Protocol v2 (2026-09-21).
- `automotive_data_t` (DATA payload): gear lever + target/engaged nibbles, rpm, 3 temperatures, battery, alert bitmap, valid flags - `automotive_data_t` (DATA payload): gear lever + target/engaged nibbles, rpm, 3 temperatures, battery, alert bitmap, valid flags
- `link_config_t` (CONFIG payload): Patrol gauge calibration + alert thresholds, pushed A → B - `link_config_t` (CONFIG payload): Patrol gauge calibration + alert thresholds, pushed A → B
- Frame: `0xAA | version | type | length | payload | XOR | 0x55`; helpers `frame_build()` / `frame_parse()` - Frame: `0xAA | version | type | length | payload | XOR | 0x55`; helpers `frame_build()` / `frame_parse()`
@@ -135,13 +147,13 @@ include/
- LVGL 8.4.0 configuration file - LVGL 8.4.0 configuration file
- Memory settings, theme configuration, widget enables - Memory settings, theme configuration, widget enables
**UI**: every screen is hand-coded in `src/modules` (see Screens). SquareLine Studio was decommissioned on 2026-09-27 (`include/ui/` deleted); the LVGL theme is set in `display_init.cpp`. Don't reintroduce a UI generator. **UI**: every screen is hand-coded in `src/modules` (see Screens). SquareLine Studio was decommissioned on 2026-09-27 (`include/ui/` deleted); the LVGL theme is set in `display_init.cpp`. Don't reintroduce a UI generator. **Image assets** (2026-10-13): source PNGs and their editable `.pcraft` files live in `assets/`, drawn with PhotoCraft (open-source Photoshop clone, installed portable with an MCP server `photocraft` registered in Claude Code - headless engine, file root `~/projects`); `python tools/png2lvgl.py <png> src/assets/<name>.c <name>` turns a PNG into an LVGL 8 `LV_IMG_CF_TRUE_COLOR_ALPHA` C array (needs Pillow). Declare them `extern "C" { LV_IMG_DECLARE(name); }` in C++ - the generated file is C.
### NVS Persistent Storage ### NVS Persistent Storage
Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Namespace: "settings" - 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`, `revlight_en` (boolean values); `final_x100`, `tyre_mm` (uint16, `Vehicle`, written 3 s after the last edit or on leaving Settings); `ecu_id86`, `ecu_id80` (blobs, `EcuIdent`: the DDE's raw KWP `1A 86` / `1A 80` identification payloads, written once when first read, removed by Re-read ECU / `ecu forget`)
- Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()` - Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()`
- Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed - Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed
@@ -190,7 +202,8 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- `0x1A2` [bytes 0-1] → Turbine speed - `0x1A2` [bytes 0-1] → Turbine speed
- `0x0AA` [bytes 4-5] → Engine RPM (× 0.25); [byte 3] pedal position - `0x0AA` [bytes 4-5] → Engine RPM (× 0.25); [byte 3] pedal position
- `0x0A8` [bytes 1-2] → Available engine torque - `0x0A8` [bytes 1-2] → Available engine torque
- `0x3B4` [12-bit LE × 0.015] → Battery voltage; [byte 2 low nibble] ignition - `0x3B4` [12-bit LE × 0.015] → Battery voltage; [byte 2 low nibble] ignition. **Patrol 1 only**: Patrol 2's bus has no 0x3B4 (nor 0x332 / 0x3B3; captures 2026-10-18), so while no 0x3B4 has been seen for 10 s `ignition_on` follows the **0x1D2 lever byte** (a P/R/N/D code = key on, `0xF0` = key off; flips within one 200 ms frame, verified on the captures). `driveline_t.ignition_src` says which one decided; the CAN driver logs each change
- Different DDEs broadcast the same frames: the two Patrols' DDEs (part numbers 7796678 / 2006 vs 7794904 / 2004) were byte-for-byte identical on every ID above. Setup differences come from **which other modules are on the bus** - adapt by presence of frames, never by ECU identity for anything broadcast (the identity is a label, see `EcuIdent`; one row per setup in wiki `vehicles`). **The one exception is diagnostic live data**: the KWP `2C 10 <id>` identifiers are addresses inside each DDE's software - Patrol 1's set read junk on Patrol 2 (2026-10-18) - so the Engine data screen selects its identifier set by the identified part number (`PROFILES[]` in `engine_screen.cpp`)
**Task Flow**: **Task Flow**:
- `canTask()` runs on Core 0 with Priority 1 - `canTask()` runs on Core 0 with Priority 1
@@ -211,7 +224,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
### Diagnostic probe (`diag` console) ### 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** (`liveConfigure()` / `liveKeepAlive()` / `liveStop()` / `liveValue()`, used by the Engine data screen): the identifier set installed by the screen for the identified DDE (`live_set_t`: optional one-time define + one `2C 10 <id>` per slot, 0 = never asked; Patrol 1: define `15E0`, then `00DF/0091/16A8/0093`; Patrol 2: rail `00C2`, boost `003A`, battery `002F`, no charge-air temp yet), polled in turn, one in flight, ~100 ms apart, quiet on the console (CANTX echoed only with CANRAW on), paused by the tester guard; nothing is asked until a set is installed; `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`. **Identification hooks (2026-10-18)**: `canSendNow()` (the guards without the console refusal lines), `requestIdent(sub)` (`1A 86` / `1A 80` to the DDE) and `setIdentHandler(cb)` - the handler gets every complete `5A xx` payload the DDE puts on 0x612, from our own request (`ours`) or reassembled **passively** from another tester's exchange (the Launch re-reads `1A 80` every ~270 ms; we see the DDE's frames without sending anything). Used by `EcuIdent` only; it is still DiagProbe doing the transmitting.
### OTA updates (`ota` console) ### OTA updates (`ota` console)
@@ -225,16 +238,34 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association. Never call `WiFi.disconnect(true)` or `WiFi.mode(WIFI_OFF)`: powering the radio off de-initialises ESP-NOW (`send()` re-inits it as a safety net). If Wi-Fi joins an AP the channel follows the AP; B hops to find it. Since 2026-09-27 it also receives (`setReceiveHandler()`, runs in the Wi-Fi task - copy and return) and unicasts to one MAC (`sendTo()`, plain peer added on first use); both are used by `LinkPeer` only. `src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association. Never call `WiFi.disconnect(true)` or `WiFi.mode(WIFI_OFF)`: powering the radio off de-initialises ESP-NOW (`send()` re-inits it as a safety net). If Wi-Fi joins an AP the channel follows the AP; B hops to find it. Since 2026-09-27 it also receives (`setReceiveHandler()`, runs in the Wi-Fi task - copy and return) and unicasts to one MAC (`sendTo()`, plain peer added on first use); both are used by `LinkPeer` only.
### Controller B over the link (`link` console) ### Inst. Cluster over the link (`link` console)
`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, Controller B 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`. `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`.
### Reverse lights (`reverse` console)
`src/modules/reverse_light.cpp` drives the isolated output **DO0** (terminal block) so a 12 V relay lights the Patrol's reverse lamps while the **lever is in R** (`driveline_t.lever == GEAR_REVERSE` from 0x1D2 byte 0, with CAN running and ignition on - the same snapshot the Driveline shows). DO0 is the collector of an NPN power transistor (450 mA sink, emitter on board GND) behind a PC817 driven from the CH422G's **OC0** pin: OC0 LOW = relay on. Written through the panel library's expander object (`DisplayInit::expander()`, pin 8 in its numbering), never raw I2C, because the backlight writes the library's cached OC register back to the chip on every on/off - a raw write would be undone during OTA. The chip and the library both default OC0 high, so DO0 is off from reset; `init()` writes it off once more. Decision at 10 Hz, applied after two equal decisions (200 ms) so a one-frame glitch cannot chatter the relay; the CAN driver's 2 s silence clear and the key-off lever code (`0xF0`) turn it off. Failed writes are retried every tick (one console line after 3 in a row). `reverse status | on | off | force on|off|auto` - `force` is for the wiring check, never saved, ends itself after 60 s. Enabled by default (`revlight_en`; an unwired DO0 is harmless); no Settings row because the System page is full at four. Wiring: wiki `reverse-lights-output`.
### Vehicle (road speed, power) - `vehicle` console
`src/modules/vehicle.cpp` holds the two swap-specific numbers that turn the gearbox output shaft (0x0BA bytes 3-4, the only road-speed signal on this bus) into road speed: **final drive ratio** (x100, default 411 = 4.11:1, user 2026-10-13) and **tyre rolling circumference** (mm, default 2440 = a 265/70 R16). `speedKmhX10(raw)` = `can_output_shaft_rpm(raw)` / ratio x circumference x 60 / 1000, integer maths; the shaft factor (0.1074) is still provisional, so every speed on screen carries a `~`. `powerHpX10(torque_x10, rpm)` = Nm x rpm / 9.5488 W, / 745.7 hp (negative torque = 0). Edited on Settings > Vehicle (-/+ rows, hold to repeat, Reset with confirm, live preview, Saving.../saved footer) or `vehicle show | set final <x.xx> | set tyre <mm> | reset`. NVS writes are deferred like the tunables (3 s idle, `flush()` when Settings is left) because every flash write flickers the panel.
**ECU identification (`ecu` console, `src/modules/ecu_ident.cpp`, 2026-10-18)**: which DDE the board is on, read **once** and remembered (user's rule: never re-asked at boot; UNKNOWN ECU until read). While nothing is stored, `tick()` sends `1A 86` (verified answered on Patrol 1 from this board; `1A 80` was silent that day) and then `1A 80` (what the Launch asks; answered on both Patrols) through `DiagProbe::requestIdent()`, up to 3 spaced attempts each per boot, only with CAN on, ignition on for 5 s, no `sim`, no scan tool for 3 s. The raw payloads are stored as NVS blobs; decode offsets are the observed ones (`1A 86`: `"@B892524 "`, BCD date at 11-13, part numbers from byte 16, VIN prefix at 53-62; `1A 80`: part number BCD at 4-7, date at 15-17) - a block that does not fit is still stored and shown by length. Once anything is stored the module never transmits again until **Re-read ECU** (Settings > Vehicle, confirm) or `ecu forget`. Free passive check: a Launch on the bus reads `1A 80` every cycle; if that block differs from the stored one the Vehicle page shows **ECU CHANGED? bus X, stored Y** in amber. `ecu show | dump | forget`. The identity is a label for captures and the wiki (`vehicles` page); broadcast decoding never depends on it - only the Engine data screen's live-data identifier profile does (`hasPart()`).
**Bench simulation (`sim` console, `src/modules/bench_sim.cpp`)**: `sim torque <Nm> [rpm <n>] [shaft <rpm>] | rpm | shaft | status | off`. `CANDriver::getDriveline()` overlays the values (plus ignition on, engine running) on every snapshot while active, and the Driveline, Sport and Vehicle pages count it as a live bus; the Driveline chip reads `IGN SIM`, the Sport status line says SIMULATION. Off at boot, never saved, nothing transmitted, the Inst. Cluster unaffected. `Ota::isParked()` sees the simulated rpm too, so `sim off` before an install with CAN on.
### Screens ### 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. 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 - **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning, **Sport** and **Engine data** buttons (y 60, left of the diff-lock drawing). Bottom row: torque, pedal, output shaft (~rpm), **speed (~km/h)** from `Vehicle`
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Controller A -> `Ota::requestCheck/requestInstall`, Controller B -> `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 - **Sport** (`sport_screen.cpp`, 2026-10-13) - BMW iDrive "Sport displays" after the user's photo: two `lv_meter` gauges on black, Power (0-320 hp, `Vehicle::powerHpX10`) left and Torque (0-600 Nm, 0x0A8 TORQ_AVL floored at 0) right. Each gauge is a **dial-face image** (`assets/dial.png` 420x420, source `assets/dial.pcraft`, geometry `assets/dial_geometry.json`, C array `src/assets/dial_img.c` 529 KB) rebuilt element by element from the photo (straightened crop + zooms in `assets/reference/`): cells ring r 158-190 with a radial gradient (orange inner edge to dark red) cut into 16 cells by 15 dark gaps, dark ruler ring r 195-207 with 81 rungs (5 per cell), bright lines at r 193-195 and the rim r 207-210 with a halo, 5 light spokes at the numbers; sweep 230 degrees starting at 155 (open at the bottom, like the photo - not 270). An `lv_meter` sits on top with ZERO-WIDTH ticks: it draws only the 5 numbers (label radius `LABEL_R` 136) and the needle. The unit large in the middle with the value small under it, the name below. PhotoCraft lesson: a shape's gradient is mapped to the bbox of ALL its subpaths, subtracted ones included, so the open-bottom wedge must stay symmetric about the dial centre (y to 400, not 800). The needle is an **image** (`assets/needle.png` 240x48, drawn in PhotoCraft via its MCP server, source `assets/needle.pcraft`; converted by `tools/png2lvgl.py` into `src/assets/needle_img.c`, RGB565+alpha, declared `extern "C"` in the screen) rotated by `lv_meter_add_needle_img` about pivot (0, 24): transparent for the first 70 px so it starts away from the centre, tapered red body, glowing orange-white tip reaching the rim at x 212. rpm and ~speed under the gauges. Blank with CAN or ignition off, `sim` counts as live; torque and hp also need `ENGINE_RUN_RUNNING` (key on / engine off, 0x0A8 holds junk: 812 Nm on Patrol 2, 245 on Patrol 1 - the Driveline's torque reads `--` then too). 10 Hz tick, needle written only on a change. Swipe right or the Driveline button goes back
- **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). **Per-DDE profiles (2026-10-18)**: `PROFILES[]` maps the ECU's part numbers (`EcuIdent::hasPart()`) to its `2C 10 <id>` identifier set and which scalings are provisional - Patrol 1 (7796678 / 7799764...) has all four, Patrol 2 (7794904 / 7796156, E65 donor) has rail `00C2`, boost `003A`, battery `002F` (Patrol 1's scalings, provisional - Launch captures 2026-10-18) and no charge-air temp yet; a slot without an identifier says "identifier not known for this ECU yet", an unidentified ECU or one without a profile polls nothing and the status line says why. The profile is re-evaluated every tick so the first identification takes effect while the screen is open. Scalings live in `CHANNELS[]`; every value shows its raw number and identifier. 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), **Vehicle** (final drive ratio and tyre circumference -/+ rows, formula + live "output shaft N rpm = X km/h" preview, the **Engine ECU** line from `EcuIdent` - `DDE 7799764 - 2006-03-07` / muted `UNKNOWN ECU` / amber `ECU CHANGED?` -, Saving.../saved footer, **Re-read ECU** and Reset buttons each behind a confirm; `Vehicle::flush()` on leaving the screen). 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 - **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`) - 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) - **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)
+6 -3
View File
@@ -5,10 +5,11 @@ Automotive display controller for Waveshare ESP32-S3-Touch-LCD-5B (1024x600 RGB
## Features ## Features
- ✅ **CAN bus** - decodes the BMW M57N / ZF 6HP powertrain frames (gear, temperatures, rpm, ...) - ✅ **CAN bus** - decodes the BMW M57N / ZF 6HP powertrain frames (gear, temperatures, rpm, ...)
- ✅ **Link to Controller B** - data + gauge config @ 5 Hz over RS485 (UART1) and ESP-NOW - ✅ **Link to Inst. Cluster** - data + gauge config @ 5 Hz over RS485 (UART1) and ESP-NOW
- ✅ **Screens** - Driveline (boot), Settings (Wi-Fi / Updates / System), Gauge Tuning; LVGL 8.4.0, hand-coded - ✅ **Screens** - Driveline (boot), Sport (torque + power gauges), Engine data, Settings (Wi-Fi / Updates / System / Vehicle), Gauge Tuning; LVGL 8.4.0, hand-coded
- ✅ **Wi-Fi** - one remembered network, joined at boot - ✅ **Wi-Fi** - one remembered network, joined at boot
- ✅ **OTA updates** - signed releases from Gitea, installed from the Settings screen - ✅ **OTA updates** - signed releases from Gitea, installed from the Settings screen
- ✅ **Reverse lights** - the isolated output DO0 switches a relay while the lever is in R
- ✅ **Settings persistence** - NVS - ✅ **Settings persistence** - NVS
- ✅ **FreeRTOS** - Wi-Fi / UART / CAN on Core 0, LVGL on Core 1 - ✅ **FreeRTOS** - Wi-Fi / UART / CAN on Core 0, LVGL on Core 1
@@ -35,6 +36,8 @@ pip install -U platformio
## Build & Upload ## Build & Upload
Full cheat-sheet for both controllers (build, upload, serial monitor, every console command, pairing, releases): [`docs/COMMANDS.md`](docs/COMMANDS.md).
### Using PlatformIO CLI ### Using PlatformIO CLI
```bash ```bash
@@ -74,7 +77,7 @@ src/
include/ include/
config/ # lv_conf.h, ota_config.h, board config config/ # lv_conf.h, ota_config.h, board config
display/ # LVGL port display/ # LVGL port
protocol/automotive_data.h # link protocol shared with Controller B protocol/automotive_data.h # link protocol shared with Inst. Cluster
wiki/ # project knowledge base wiki/ # project knowledge base
``` ```
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 315 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 395 KiB

+237
View File
@@ -0,0 +1,237 @@
# Commands cheat-sheet — both controllers
Everything you type to build, flash, watch and drive the two boards. Kept in the
Main CTRL repo (this one); the Inst. Cluster repo's README points here.
| | Main CTRL | Inst. Cluster |
|---|---|---|
| Board | Waveshare ESP32-S3-Touch-LCD-5B (5" touch) | Waveshare ESP32-S3-LCD-1.3 (1.3" round) |
| Repo / branch | `ESP32-S3-Touch-LCD-5B`, `main` | `ESP32-S3-LCD-1.3`, `master` |
| Platform | pioarduino (Arduino 3.3.3 / IDF 5.5) | espressif32@6 (Arduino 2.0.17 / IDF 4.4) |
| Serial | native USB-CDC | CH343 UART |
| Bench port (2026-09-28) | COM14 | COM10 |
| OTA target / release | `patrol-a`, `v*` tags → signed release | `patrol-b`, `v*` tags → signed release |
Windows ports move around: `pio device list` shows what is plugged in.
---
## 1. Rules of the road (Windows, this machine)
- **PowerShell only.** `pio` refuses to run from Git Bash (`MSys/Mingw is not supported`).
- `pio` lives at `$env:USERPROFILE\.platformio\penv\Scripts\pio.exe` (no global install). The commands below assume this alias:
```powershell
Set-Alias pio "$env:USERPROFILE\.platformio\penv\Scripts\pio.exe"
```
- **The two projects share one PlatformIO environment.** Consequences:
- The first `pio run` after building the *other* project reinstalls the Arduino core and may fail once with `TypeError: expected str, bytes or os.PathLike object, not NoneType`. Run it again.
- After **any B build**, repair the environment before building A, or A fails with `Failed to install Python dependencies into penv`:
```powershell
.\tools\fix_penv_deps.ps1 # run inside the A repo
```
- Never build both projects at the same time.
- **A serial monitor on a port blocks uploads to that port.** Close it (Ctrl+C) first.
- Opening a port with DTR/RTS asserted resets the board. Always monitor with `--dtr 0 --rts 0`.
---
## 2. Build and upload
Run inside the respective repo folder.
### Main CTRL
```powershell
cd <path>\ESP32-S3-Touch-LCD-5B
pio run # build only (dev build, version "dev")
pio run -t upload --upload-port COM14 # build + flash over USB
pio run -t clean # wipe the build directory
```
First build after a `platformio.ini` change rebuilds the ESP-IDF core (~20 min, `custom_sdkconfig`); later builds take 1–3 min.
### Inst. Cluster
```powershell
cd <path>\ESP32-S3-LCD-1.3
pio run
pio run -t upload --upload-port COM10
..\ESP32-S3-Touch-LCD-5B\tools\fix_penv_deps.ps1 # ALWAYS after a B build, before the next A build
```
A USB flash writes bootloader, partition table, `boot_app0` and the app into slot 0. It does **not** touch NVS: saved Wi-Fi network, tunables, pairing key and B's cached gauge config survive.
---
## 3. Serial monitor
```powershell
pio device monitor -p COM14 -b 115200 --dtr 0 --rts 0 --echo # Main CTRL
pio device monitor -p COM10 -b 115200 --dtr 0 --rts 0 --echo # Inst. Cluster
```
Type a command, press Enter. `--echo` shows what you type. Ctrl+C leaves.
One-shot commands and logging from a script (A repo, `tools/`):
```powershell
python tools\serial_cmd.py COM14 "link status" 3 # send one line, print 3 s of reply
python tools\serial_logger.py COM14 # log a port to wiki\raw\ until Ctrl+C
python tools\serial_logger.py COM14,COM10 # both ports at once
python tools\perf_session.py COM14 # display-performance session (PERF lines)
python tools\diag_session.py COM14 "diag pids" "diag vin" # scripted OBD probe run with log
```
---
## 4. Main CTRL console
Type `help` for the list. Unknown lines are reported.
### `cfg` — Patrol gauge calibration and alert thresholds (saved in NVS, pushed to B)
```
cfg show
cfg set <name> <value> tach_ppr tach_trim tach_min_hz tach_max_hz
temp_hz temp_slope(x100) temp_offset temp_min temp_duty_max
tach_en temp_en coolant_hot gearbox_hot batt_low(x100)
cfg override off | rpm <n> | duty <n> | both <rpm> <duty> bench test of B's outputs, never saved
cfg reset
```
### `wifi`
```
wifi status connection, saved network, ESP-NOW health
wifi join <ssid> [pass] join and remember a network (no spaces in the SSID)
wifi forget drop the remembered network (B is told to forget too)
wifi scan list networks in range
wifi on | off
```
### `ota` — this controller's own updates
```
ota status version, slot, rollback state
ota check ask Gitea for the latest release (needs Wi-Fi)
ota install [force] download, verify, flash the idle slot, reboot (parked only)
ota rollback boot the previous slot (parked only)
```
### `link` — Inst. Cluster over the link
```
link status B's version, pairing, update phase, credentials
link pair new shared key → B over the UART WIRE (bench, wire connected)
link unpair forget the key here
link creds send the remembered Wi-Fi network to B now (normally automatic)
link ota check | install [force] | rollback drive B's updater (A must be on Wi-Fi, parked)
```
### `diag` — OBD-II probe (the only thing that ever transmits on the CAN bus)
```
diag pids scan mode-01 supported-PID bitmaps
diag pid <hex> one mode-01 request (0C rpm, 70 boost, ...)
diag dtc mode 03, stored generic DTCs
diag vin mode 09 PID 02
diag ecu mode 09 PID 0A
diag ident [addr] BMW KWP 1A 80 identification (default 12 = DDE)
diag bmw <addr> <hex...> raw BMW request on 0x6F1, read-only services only
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`.
### `reverse` — reverse-light relay on DO0 (follows the gear lever in R; default ON, no Settings row - the System page is full)
```
reverse status enabled?, DO0 on/off, lever / ignition / CAN as seen, write counters
reverse on | off enable / disable (saved); off = DO0 stays off
reverse force on | off drive DO0 regardless of the lever, for the wiring check (not saved, ends after 60 s)
reverse force auto back to the lever
```
Wiring: relay coil between +12 V and `DO0`, flyback diode across the coil (stripe to +12 V); the coil current returns through the board's `GND`. ≤ 450 mA per output. Details: wiki `reverse-lights-output`.
### `vehicle` — road speed from the gearbox output shaft (Settings → Vehicle; saved in NVS)
```
vehicle show final drive ratio, tyre circumference, and what 1000 shaft rpm comes to
vehicle set final <x.xx> final drive (differential) ratio, 2.00..8.00 - 4.11 on this Patrol
vehicle set tyre <mm> tyre rolling circumference, 1500..3500 mm (265/70 R16 ≈ 2440)
vehicle reset back to 4.11:1 and 2440 mm
```
### `ecu` — which engine ECU (DDE) this board is on (read once, saved in NVS)
```
ecu show stored identification: part number, software date, VIN prefix; or UNKNOWN ECU
ecu dump the stored KWP 1A 86 / 1A 80 payloads in hex
ecu forget drop them - UNKNOWN ECU until read again (do this when the board moves to another car)
```
While nothing is stored the board asks the DDE once (`1A 86`, then `1A 80`, up to 3 tries each per boot) as soon as CAN is on, the ignition has been on for 5 s, `sim` is off and no scan tool has spoken for 3 s. Once stored it never asks again. Same thing from the screen: Settings → Vehicle shows the Engine ECU line and has a **Re-read ECU** button. With a Launch connected the board also sees its `1A 80` reads and shows **ECU CHANGED?** if they differ from the stored block.
### `sim` — bench values for the screens (never saved, off at boot, nothing transmitted)
```
sim torque <Nm> [rpm <n>] [shaft <rpm>] e.g. sim torque 350 rpm 2500 shaft 1200
sim rpm <n> | sim shaft <rpm> change one value, the rest stays
sim status
sim off
```
Feeds the Sport gauges, the Driveline's torque / rpm / output / speed and the Vehicle page preview as if the ignition were on; the Driveline's chip reads `IGN SIM` and the Sport screen says SIMULATION meanwhile. The Inst. Cluster is not affected (use `cfg override` for its outputs).
Speed (km/h) = output shaft rpm ÷ ratio × circumference (m) × 60 ÷ 1000. The shaft rpm is still the provisional 0x0BA × 0.1074, so the screens show `~km/h`. The Sport screen's hp = Nm × rpm ÷ 9.5488 ÷ 745.7.
### Diagnostics
```
mem internal heap, PSRAM, LVGL pool
perf one PERF line (fps, flush cost, CPU idle, heap, panel vsync)
perf on [sec] | perf off
```
---
## 5. Inst. Cluster console
```
help
link status pairing, A's MAC, STATUS/SECURE counters, credentials
link unpair forget the pairing key (re-pair from A over the wire)
wifi status stored network name (password never shown)
wifi forget
ota status version, slot, rollback state
ota check join Wi-Fi, ask Gitea for the latest release, leave
ota install [force] download, verify, flash, reboot (parked only)
ota rollback
```
B prints a stats line every 5 s (`applied=… uart … espnow …`) — `uart alive` means the wire works.
---
## 6. Procedures
### Pair a Inst. Cluster (once per board pair)
1. Wire: 5B terminal `485_A` → B `IO1`, GND → GND (a real wire, not just the USB hub), 5B's 120 Ω switch OFF. Both powered. B's stats line must say `uart alive`.
2. A console: `link pair`. Within 5 s A logs `Inst. Cluster confirmed pairing (fingerprint XXXX)`; B logs `PAIRED over the wire`.
3. `link status` on A: `key XXXX (matches)`. About 15 s later `Wi-Fi creds yes` (A pushes them by itself; `link creds` forces it).
The key lives in NVS on both boards and survives every flash and update. Re-pair only after an NVS erase, `link unpair`, or a board swap.
### Release a version
```powershell
git tag -a vX.Y.Z -m "what changed"
git push --follow-tags origin main # A (B: origin master)
```
One push, so only the tag build runs. Gitea builds, signs (`BMW_NISSAN_FIRMWARE_SIGNING_KEY`) and publishes `firmware.bin` + `manifest.txt`: A takes 7–20 min, B 2–5 min. Check: `https://git.infra.msai.al/<owner>/<repo>/releases`. Version strings must stay under 16 characters.
### Update A from the screen
Settings → Updates → Main CTRL → **Check** → **Install vX.Y.Z** (parked, Wi-Fi joined). Progress bar, restart, `A vX.Y.Z` bottom-right. A reset in the first 30 s rolls back.
### Update B from the screen
Settings → Updates → Inst. Cluster → **Check** → **Install** (A on Wi-Fi, parked, B paired). B's round screen shows `Updating vX.Y.Z N%`, the card on A shows the percentage, B restarts and confirms itself after 30 s. Console equivalent: `link ota check`, `link ota install`.
### Something is wrong after an update
`ota rollback` on the affected controller's console (B: `link ota rollback` from A also works). A reset within 30 s of the first boot of a new image rolls back on its own.
---
## 7. Git on several machines
Fetch before you start on another machine; the wikis are edited from every machine:
```powershell
git fetch origin
git status -sb # "behind" → git pull --ff-only before touching anything
```
+4 -4
View File
@@ -3,7 +3,7 @@
**Version:** 2 (`PACKET_VERSION 0x02`) **Version:** 2 (`PACKET_VERSION 0x02`)
**Last Updated:** 2026-09-27 **Last Updated:** 2026-09-27
**Source of truth:** `include/protocol/automotive_data.h` (+ `link_secure.h`) — byte-identical in both repos. **Source of truth:** `include/protocol/automotive_data.h` (+ `link_secure.h`) — byte-identical in both repos.
**Direction:** gauge data Controller A (ESP32-S3-Touch-LCD-5B) → Controller B (ESP32-S3-LCD-1.3). Since 2026-09-27 B answers with `STATUS` frames over ESP-NOW and A sends B maintenance frames (`PAIR` on the wire, `SECURE` over ESP-NOW) — see *Maintenance frames* below. **Direction:** gauge data Main CTRL (ESP32-S3-Touch-LCD-5B) → Inst. Cluster (ESP32-S3-LCD-1.3). Since 2026-09-27 B answers with `STATUS` frames over ESP-NOW and A sends B maintenance frames (`PAIR` on the wire, `SECURE` over ESP-NOW) — see *Maintenance frames* below.
--- ---
@@ -101,7 +101,7 @@ Tach: `f = rpm × tach_ppr / 60 × (1 + trim/100)`, clamped, 50 % duty. Output l
--- ---
## Controller A console commands (USB serial) ## Main CTRL console commands (USB serial)
``` ```
cfg show cfg show
@@ -120,13 +120,13 @@ The same console also carries the OBD-II diagnostic probe (`diag pids | pid <hex
--- ---
## Maintenance frames (2026-09-27) — for Controller B's firmware updates ## Maintenance frames (2026-09-27) — for Inst. Cluster's firmware updates
`PACKET_VERSION` did not change: DATA and CONFIG are byte-identical, and a B built before these types counts them as type errors and carries on. `PACKET_VERSION` did not change: DATA and CONFIG are byte-identical, and a B built before these types counts them as type errors and carries on.
| Type | Direction | Transport | Payload | Purpose | | Type | Direction | Transport | Payload | Purpose |
|---|---|---|---|---| |---|---|---|---|---|
| `STATUS` 0x03 | B → A | ESP-NOW unicast to A's MAC (learned from A's data frames) | `link_status_t` (78 B): B's version, OTA phase (`LINK_OTA_*`, same numbering as A's `Ota::phase_t`), progress %, flags (paired / have Wi-Fi / joined / pending verify), `key_fp`, uptime, free heap, latest tag, message | every 5 s and on every phase change; A's Updates page "Controller B" card | | `STATUS` 0x03 | B → A | ESP-NOW unicast to A's MAC (learned from A's data frames) | `link_status_t` (78 B): B's version, OTA phase (`LINK_OTA_*`, same numbering as A's `Ota::phase_t`), progress %, flags (paired / have Wi-Fi / joined / pending verify), `key_fp`, uptime, free heap, latest tag, message | every 5 s and on every phase change; A's Updates page "Inst. Cluster" card |
| `PAIR` 0x04 | A → B | **UART wire only** — B drops a PAIR heard by radio | `link_pair_t` (42 B): magic `"PAIR"`, 32-byte random key, A's STA MAC | `link pair` on A's console, sent 3×; both sides keep the key in NVS. The only secret in the system (both repos are public) | | `PAIR` 0x04 | A → B | **UART wire only** — B drops a PAIR heard by radio | `link_pair_t` (42 B): magic `"PAIR"`, 32-byte random key, A's STA MAC | `link pair` on A's console, sent 3×; both sides keep the key in NVS. The only secret in the system (both repos are public) |
| `SECURE` 0x05 | A → B | ESP-NOW unicast | `nonce[12] \| tag[16] \| AES-256-GCM(key, nonce, inner_type \| inner)` — helpers in `link_secure.h` | inner `LINK_INNER_OTA_CMD` 0x11 (`link_ota_cmd_t`: check / install [force] / rollback + random nonce, B ignores a repeat of the last 4) or `LINK_INNER_WIFI_CREDS` 0x12 (`link_wifi_creds_t`: SET/FORGET, ssid, pass). B also requires the sender MAC to be the paired A | | `SECURE` 0x05 | A → B | ESP-NOW unicast | `nonce[12] \| tag[16] \| AES-256-GCM(key, nonce, inner_type \| inner)` — helpers in `link_secure.h` | inner `LINK_INNER_OTA_CMD` 0x11 (`link_ota_cmd_t`: check / install [force] / rollback + random nonce, B ignores a repeat of the last 4) or `LINK_INNER_WIFI_CREDS` 0x12 (`link_wifi_creds_t`: SET/FORGET, ssid, pass). B also requires the sender MAC to be the paired A |
+2 -2
View File
@@ -1,5 +1,5 @@
/** /**
* ota_config.h - where Controller A looks for firmware updates, and what it trusts. * ota_config.h - where Main CTRL looks for firmware updates, and what it trusts.
* *
* Updates are pulled over HTTPS from this repo's Gitea releases (public repo, * Updates are pulled over HTTPS from this repo's Gitea releases (public repo,
* no token). CI (.gitea/workflows/firmware.yml) attaches firmware.bin + * no token). CI (.gitea/workflows/firmware.yml) attaches firmware.bin +
@@ -19,7 +19,7 @@
#define FW_VERSION "dev" #define FW_VERSION "dev"
#endif #endif
// Identity inside the signed statement, so a Controller B image can never be // Identity inside the signed statement, so a Inst. Cluster image can never be
// accepted by A (and vice versa) even though both are signed by the same key. // accepted by A (and vice versa) even though both are signed by the same key.
#define OTA_TARGET "patrol-a" #define OTA_TARGET "patrol-a"
+17 -8
View File
@@ -67,9 +67,14 @@ typedef struct {
// DRIVELINE STATE // DRIVELINE STATE
// ============================================================================ // ============================================================================
// Where driveline_t.ignition_on came from (see the field's comment).
#define IGN_SRC_NONE 0 // no frame seen yet
#define IGN_SRC_3B4 1 // 0x3B4 byte 2 nibble, seen within the last IGN_3B4_HOLD_MS
#define IGN_SRC_LEVER 2 // 0x1D2 byte 0: lever code valid = on, 0xF0 = off
/** /**
* Decoded driveline speeds. Deliberately NOT part of automotive_data_t: that * Decoded driveline speeds. Deliberately NOT part of automotive_data_t: that
* struct is the wire format for the UART link to Controller B, and widening it * struct is the wire format for the UART link to Inst. Cluster, and widening it
* would break the receiver. These live here until there's a reason to spend a * would break the receiver. These live here until there's a reason to spend a
* protocol version bump on them. * protocol version bump on them.
* *
@@ -90,9 +95,12 @@ typedef struct {
uint8_t converter_clutch; // 0x0BA ST_CCLT (CCLT_* constants). When CLOSED, uint8_t converter_clutch; // 0x0BA ST_CCLT (CCLT_* constants). When CLOSED,
// turbine_rpm == engine_rpm by design — read this // turbine_rpm == engine_rpm by design — read this
// before interpreting the two as a slip ratio. // before interpreting the two as a slip ratio.
bool ignition_on; // 0x3B4 byte 2 low nibble. This bus's only bool ignition_on; // Terminal 15. From 0x3B4 byte 2 low nibble when
// ignition/terminal signal — CAS (0x130) is not // that frame is on the bus (Patrol 1); otherwise
// present in the swap. // from the 0x1D2 lever byte: a recognised P/R/N/D
// code means key on, 0xF0 means key off (Patrol 2
// has no 0x3B4 at all - captures 2026-10-18).
uint8_t ignition_src; // IGN_SRC_* : which of the two decided ignition_on
uint8_t lever; // 0x1D2 byte 0 as gear_position_t: the selected uint8_t lever; // 0x1D2 byte 0 as gear_position_t: the selected
// detent (P/R/N/D). GEAR_UNKNOWN before first frame. // detent (P/R/N/D). GEAR_UNKNOWN before first frame.
uint8_t engaged_gear; // 0x1D2 byte 1: gear the box is actually in, 1..6; uint8_t engaged_gear; // 0x1D2 byte 1: gear the box is actually in, 1..6;
@@ -147,12 +155,13 @@ namespace CANDriver {
/** /**
* Transmit ONE standard (11-bit) frame, single-shot (no automatic * Transmit ONE standard (11-bit) frame, single-shot (no automatic
* retransmission if nobody ACKs). The only write path onto the vehicle * retransmission if nobody ACKs). The only write path onto the vehicle
* bus; reserved for DiagProbe's on-demand diagnostic requests. Echoes the * bus; reserved for DiagProbe (console requests + the Engine data screen's
* frame on the console as a "CANTX," line (same shape as CANRAW) so * live poll). Echoes the frame on the console as a "CANTX," line (same
* captures hold both halves of an exchange. * 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) * @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). * Enable/disable raw frame logging (candump-style capture of EVERY frame).
+11 -19
View File
@@ -1,8 +1,8 @@
/** /**
* automotive_data.h * automotive_data.h
* *
* Shared wire contract between Controller A (ESP32-S3-Touch-LCD-5B) and * Shared wire contract between Main CTRL (ESP32-S3-Touch-LCD-5B) and
* Controller B (ESP32-S3-LCD-1.3). * Inst. Cluster (ESP32-S3-LCD-1.3).
* *
* THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS. Copy it across whenever it * THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS. Copy it across whenever it
* changes and bump PACKET_VERSION; B rejects frames with any other version. * changes and bump PACKET_VERSION; B rejects frames with any other version.
@@ -45,8 +45,8 @@
// (B hops until it hears A, then locks) // (B hops until it hears A, then locks)
// NOTE: UART pin assignments are controller-specific: // NOTE: UART pin assignments are controller-specific:
// - Controller A (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B) // - Main CTRL (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B)
// - Controller B (1.3): platformio.ini (RX IO1) // - Inst. Cluster (1.3): platformio.ini (RX IO1)
// ============================================================================ // ============================================================================
// FRAME FORMAT (identical on UART and ESP-NOW) // FRAME FORMAT (identical on UART and ESP-NOW)
@@ -90,7 +90,7 @@ typedef enum {
LEVER_UNKNOWN = 0xFF LEVER_UNKNOWN = 0xFF
} gear_lever_t; } gear_lever_t;
// Controller A's internal gear enum (CAN decode helpers below use it). Not on // Main CTRL's internal gear enum (CAN decode helpers below use it). Not on
// the wire any more - B never sees it. // the wire any more - B never sees it.
typedef enum { typedef enum {
GEAR_PARK = 0, GEAR_PARK = 0,
@@ -216,7 +216,7 @@ static inline void link_config_defaults(link_config_t* c) {
} }
// ============================================================================ // ============================================================================
// LINK MAINTENANCE FRAMES (2026-09-27) - Controller B firmware updates // LINK MAINTENANCE FRAMES (2026-09-27) - Inst. Cluster firmware updates
// ============================================================================ // ============================================================================
// //
// B pulls its own signed release over Wi-Fi; A only hands it the credentials // B pulls its own signed release over Wi-Fi; A only hands it the credentials
@@ -241,7 +241,7 @@ typedef struct __attribute__((packed)) {
} link_pair_t; // 42 bytes } link_pair_t; // 42 bytes
// --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ---------- // --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ----------
// ota_phase mirrors Controller A's Ota::phase_t so one UI renders both. // ota_phase mirrors Main CTRL's Ota::phase_t so one UI renders both.
#define LINK_OTA_IDLE 0 #define LINK_OTA_IDLE 0
#define LINK_OTA_CHECKING 1 #define LINK_OTA_CHECKING 1
#define LINK_OTA_UP_TO_DATE 2 #define LINK_OTA_UP_TO_DATE 2
@@ -756,7 +756,7 @@ static inline const char* gear_to_string(gear_position_t gear) {
* @return Pointer to buffer * @return Pointer to buffer
*/ */
static inline char* format_temperature(int16_t temp_x10, char* buffer) { static inline char* format_temperature(int16_t temp_x10, char* buffer) {
// Plain "C": Controller B's UI font has no degree-sign glyph. // Plain "C": Inst. Cluster's UI font has no degree-sign glyph.
sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10)); sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10));
return buffer; return buffer;
} }
@@ -772,16 +772,8 @@ static inline char* format_voltage(uint16_t voltage_x100, char* buffer) {
return buffer; return buffer;
} }
// ============================================================================ // No default / test values: a field is only ever filled from a CAN frame, and
// DEFAULT/TEST VALUES // its VALID_FLAG_* bit says so. Removed 2026-09-28 - the bench defaults
// ============================================================================ // (89 / 85 degC, 12.45 V) looked like real readings on Inst. Cluster.
// Default values for testing (before CAN data is available)
#define DEFAULT_GEAR_LEVER LEVER_PARK
#define DEFAULT_GEARBOX_TEMP 850 // 85.0°C
#define DEFAULT_ENGINE_OIL_TEMP 920 // 92.0°C
#define DEFAULT_COOLANT_TEMP 890 // 89.0°C
#define DEFAULT_BATTERY_VOLTAGE 1245 // 12.45V
#define DEFAULT_ALERTS 0x0000 // No alerts
#endif // _AUTOMOTIVE_DATA_H #endif // _AUTOMOTIVE_DATA_H
+1 -1
View File
@@ -5,7 +5,7 @@
* *
* payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner) * payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner)
* *
* Both cores ship mbedtls (2.28 on Controller B's IDF 4.4, 3.x on Controller * Both cores ship mbedtls (2.28 on Inst. Cluster's IDF 4.4, 3.x on Controller
* A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs. * A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs.
*/ */
+22076
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+55 -5
View File
@@ -11,6 +11,7 @@
#include "modules/serial_lock.h" #include "modules/serial_lock.h"
#include "modules/tunables.h" #include "modules/tunables.h"
#include "modules/diag_probe.h" #include "modules/diag_probe.h"
#include "modules/bench_sim.h"
#include "esp_log.h" #include "esp_log.h"
// Import shared data from UARTManager namespace // Import shared data from UARTManager namespace
@@ -32,6 +33,11 @@ namespace CANDriver {
// Without this window the flag would strobe on every gear change. // Without this window the flag would strobe on every gear change.
#define GEAR_MISMATCH_DEBOUNCE_MS 500 #define GEAR_MISMATCH_DEBOUNCE_MS 500
// 0x3B4 is a 5 s frame. While one has been seen this recently its ignition
// nibble rules; otherwise ignition follows the 0x1D2 lever byte (Patrol 2's bus
// has no 0x3B4 at all; captures 2026-10-18, wiki can-capture-2026-10-18-patrol-2).
#define IGN_3B4_HOLD_MS 10000
// ============================================================================ // ============================================================================
// MODULE STATE // MODULE STATE
// ============================================================================ // ============================================================================
@@ -42,6 +48,7 @@ static QueueHandle_t g_can_event_queue = NULL;
static can_stats_t g_can_stats = {0}; static can_stats_t g_can_stats = {0};
static bool g_uart_auto_stopped = false; // Track if UART was auto-stopped due to CAN timeout static bool g_uart_auto_stopped = false; // Track if UART was auto-stopped due to CAN timeout
// Raw frame logging: capture EVERY frame (candump-style) for offline CAN ID // Raw frame logging: capture EVERY frame (candump-style) for offline CAN ID
// discovery. Default ON since discovery is the current priority. // discovery. Default ON since discovery is the current priority.
static bool g_raw_logging = true; static bool g_raw_logging = true;
@@ -53,6 +60,22 @@ static bool g_verbose_decode = false;
// Guarded by g_data_mutex along with g_automotive_data. // Guarded by g_data_mutex along with g_automotive_data.
static driveline_t g_driveline = {0}; static driveline_t g_driveline = {0};
/**
* Forget every CAN-derived value: nothing may be shown or sent that the bus
* did not say recently. Called when CAN stops and when the bus goes silent.
*/
static void clearSharedData() {
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
uint8_t dbg = UARTManager::g_automotive_data.debug_enabled;
memset(&UARTManager::g_automotive_data, 0, sizeof(UARTManager::g_automotive_data));
UARTManager::g_automotive_data.gear_lever = LEVER_UNKNOWN;
UARTManager::g_automotive_data.debug_enabled = dbg;
xSemaphoreGive(UARTManager::g_data_mutex);
}
memset(&g_driveline, 0, sizeof(g_driveline));
g_driveline.lever = GEAR_UNKNOWN;
}
// Last gear LEVER code seen on 0x1D2, for the lever-vs-gearbox cross-check. // Last gear LEVER code seen on 0x1D2, for the lever-vs-gearbox cross-check.
static gear_position_t g_last_lever = GEAR_UNKNOWN; static gear_position_t g_last_lever = GEAR_UNKNOWN;
// When the current disagreement started (0 = currently in agreement). // When the current disagreement started (0 = currently in agreement).
@@ -60,11 +83,28 @@ static uint32_t g_mismatch_since = 0;
// Gearbox target gear number from 0x0BA (1..6 forward, 0 = P/R/N/none), for the // Gearbox target gear number from 0x0BA (1..6 forward, 0 = P/R/N/none), for the
// wire's target nibble. Lives here because 0x0BA and 0x1D2 arrive separately. // wire's target nibble. Lives here because 0x0BA and 0x1D2 arrive separately.
static uint8_t g_target_gear_num = 0; static uint8_t g_target_gear_num = 0;
// millis() of the last 0x3B4 frame (0 = none since CAN started) - see IGN_3B4_HOLD_MS.
static uint32_t g_last_3b4_ms = 0;
// ============================================================================ // ============================================================================
// PRIVATE FUNCTIONS // PRIVATE FUNCTIONS
// ============================================================================ // ============================================================================
/**
* @brief Set the ignition flag and remember which frame decided it; one console
* line per change so a capture shows when and why the screens blanked.
* Caller must hold g_data_mutex.
*/
static void setIgnition(bool on, uint8_t src) {
if (g_driveline.ignition_on == on && g_driveline.ignition_src == src) return;
g_driveline.ignition_on = on;
g_driveline.ignition_src = src;
SerialLock::lock();
ESP_LOGI("CANDrv", "ignition %s (from %s)", on ? "ON" : "OFF",
src == IGN_SRC_3B4 ? "0x3B4" : "0x1D2 lever - no 0x3B4 on this bus");
SerialLock::unlock();
}
/** /**
* @brief Cross-check the driver's lever selection against the gearbox's own * @brief Cross-check the driver's lever selection against the gearbox's own
* target gear and raise a fault if they disagree for long enough. * target gear and raise a fault if they disagree for long enough.
@@ -226,6 +266,12 @@ static bool parseCANMessage(const twai_message_t& message) {
if (dlc > CAN_BYTE_GEAR_LEVER) { if (dlc > CAN_BYTE_GEAR_LEVER) {
g_last_lever = can_to_gear_lever(data[CAN_BYTE_GEAR_LEVER]); g_last_lever = can_to_gear_lever(data[CAN_BYTE_GEAR_LEVER]);
g_driveline.lever = (uint8_t)g_last_lever; g_driveline.lever = (uint8_t)g_last_lever;
// Ignition fallback: the EGS reports a lever position only with
// terminal 15 on; with the key off the byte reads 0xF0 within one
// frame while the bus stays awake for another 5-10 s (verified on
// Patrol 2's captures). 0x3B4, when present, keeps precedence.
bool have_3b4 = (g_last_3b4_ms != 0) && (millis() - g_last_3b4_ms < IGN_3B4_HOLD_MS);
if (!have_3b4) setIgnition(g_last_lever != GEAR_UNKNOWN, IGN_SRC_LEVER);
} }
if (dlc > CAN_BYTE_GEAR_ENGAGED) { if (dlc > CAN_BYTE_GEAR_ENGAGED) {
g_driveline.engaged_gear = can_to_engaged_gear(data[CAN_BYTE_GEAR_ENGAGED]); g_driveline.engaged_gear = can_to_engaged_gear(data[CAN_BYTE_GEAR_ENGAGED]);
@@ -304,9 +350,9 @@ static bool parseCANMessage(const twai_message_t& message) {
} }
if (dlc > CAN_BYTE_IGNITION) { if (dlc > CAN_BYTE_IGNITION) {
// Byte 2's low nibble tracks ignition (inverted), NOT engine run // Byte 2's low nibble tracks ignition (inverted), NOT engine run
// — verified on this bus against both published claims. // — verified on Patrol 1's bus against both published claims.
g_driveline.ignition_on = g_last_3b4_ms = millis();
((data[CAN_BYTE_IGNITION] & 0x0F) == IGNITION_ON); setIgnition((data[CAN_BYTE_IGNITION] & 0x0F) == IGNITION_ON, IGN_SRC_3B4);
parsed = true; parsed = true;
} }
break; break;
@@ -507,6 +553,7 @@ static void canTask(void* parameter) {
g_last_lever = GEAR_UNKNOWN; g_last_lever = GEAR_UNKNOWN;
g_target_gear_num = 0; g_target_gear_num = 0;
g_mismatch_since = 0; g_mismatch_since = 0;
g_last_3b4_ms = 0;
ESP_LOGI("CANTask", "CAN reception active"); ESP_LOGI("CANTask", "CAN reception active");
// Auto-start UART transmission (CAN drives UART) // Auto-start UART transmission (CAN drives UART)
@@ -523,6 +570,7 @@ static void canTask(void* parameter) {
deinitTWAI(); deinitTWAI();
g_can_active = false; g_can_active = false;
g_uart_auto_stopped = false; // Reset auto-stop flag g_uart_auto_stopped = false; // Reset auto-stop flag
clearSharedData();
// Auto-stop UART transmission (CAN drives UART) // Auto-stop UART transmission (CAN drives UART)
UARTManager::linkToCANState(false); UARTManager::linkToCANState(false);
@@ -595,6 +643,7 @@ static void canTask(void* parameter) {
// CAN data is stale - auto-stop UART to prevent transmitting stale data // CAN data is stale - auto-stop UART to prevent transmitting stale data
ESP_LOGW("CANTask", "⚠ CAN timeout (%dms since last message), auto-stopping UART", time_since_last_rx); ESP_LOGW("CANTask", "⚠ CAN timeout (%dms since last message), auto-stopping UART", time_since_last_rx);
UARTManager::linkToCANState(false); UARTManager::linkToCANState(false);
clearSharedData(); // stale values must not come back as "valid" later
g_uart_auto_stopped = true; g_uart_auto_stopped = true;
} }
} }
@@ -673,6 +722,7 @@ driveline_t getDriveline() {
memset(&snapshot, 0, sizeof(snapshot)); memset(&snapshot, 0, sizeof(snapshot));
snapshot.lever = (uint8_t)GEAR_UNKNOWN; // 0 would mean GEAR_PARK snapshot.lever = (uint8_t)GEAR_UNKNOWN; // 0 would mean GEAR_PARK
} }
BenchSim::apply(snapshot); // `sim` console: bench torque / rpm / shaft, off unless asked
return snapshot; return snapshot;
} }
@@ -680,7 +730,7 @@ bool isActive() {
return g_can_active; 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) { if (!g_can_active || data == NULL || len > 8 || id > 0x7FF) {
g_can_stats.tx_failures++; g_can_stats.tx_failures++;
return false; return false;
@@ -700,7 +750,7 @@ bool transmit(uint32_t id, const uint8_t* data, uint8_t len) {
return false; return false;
} }
g_can_stats.messages_transmitted++; g_can_stats.messages_transmitted++;
emitFrameLine("CANTX", m); if (echo) emitFrameLine("CANTX", m);
return true; return true;
} }
+25 -6
View File
@@ -11,14 +11,21 @@
#include "modules/driveline_screen.h" // Hand-coded driveline screen (boot screen) #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/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/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/sport_screen.h" // Torque + power gauges (Sport button on Driveline)
#include "modules/vehicle.h" // Final drive ratio + tyre circumference -> road speed; power maths (`vehicle` console)
#include "modules/bench_sim.h" // `sim` console: bench torque / rpm / shaft for the screens, never saved
#include "modules/ecu_ident.h" // which DDE this board is on: read once, stored, UNKNOWN ECU until then (`ecu` console)
#include "modules/serial_lock.h" // Global serial write mutex #include "modules/serial_lock.h" // Global serial write mutex
#include "modules/tunables.h" // Gauge calibration + alert thresholds (NVS, serial console) #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 #include "modules/perf_monitor.h" // `perf` console: render fps, flush cost, CPU idle, heap
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B #include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Inst. Cluster
#include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter #include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console) #include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
#include "modules/link_peer.h" // Controller B status, pairing, credential handoff, B updates (`link` 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/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)
#include "modules/reverse_light.h" // Reverse-light relay on DO0, follows the lever in R (`reverse` console)
// ============================================================================ // ============================================================================
// MINIMAL LVGL + UI SETTINGS + WIFI + UART // MINIMAL LVGL + UI SETTINGS + WIFI + UART
@@ -57,11 +64,13 @@ static bool memCommand(const char* line) {
return true; 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) { static bool consoleExtraCommand(const char* line) {
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) || return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
WiFiManager::handleCommand(line) || memCommand(line) || WiFiManager::handleCommand(line) || memCommand(line) ||
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line); PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
DiffLocks::handleCommand(line) || ReverseLight::handleCommand(line) || Vehicle::handleCommand(line) ||
BenchSim::handleCommand(line) || EcuIdent::handleCommand(line);
} }
// ============================================================================ // ============================================================================
@@ -94,10 +103,12 @@ void setup()
// Initialize Settings Manager // Initialize Settings Manager
ESP_LOGI("MAIN", "Initializing Settings Manager..."); ESP_LOGI("MAIN", "Initializing Settings Manager...");
SettingsManager::init(); SettingsManager::init();
Vehicle::init(); // final drive ratio + tyre circumference (road speed)
// Tunables (gauge calibration, alert thresholds) - before CAN/UART start // Tunables (gauge calibration, alert thresholds) - before CAN/UART start
Tunables::init(); Tunables::init();
DiagProbe::init(); DiagProbe::init();
EcuIdent::init(); // stored DDE identification; hooks DiagProbe for the one-shot read
Tunables::setExtraCommandHandler(consoleExtraCommand); Tunables::setExtraCommandHandler(consoleExtraCommand);
PerfMon::init(); PerfMon::init();
@@ -107,6 +118,8 @@ void setup()
bool saved_uart_state = SettingsManager::loadUARTState(); bool saved_uart_state = SettingsManager::loadUARTState();
bool saved_can_state = SettingsManager::loadCANState(); bool saved_can_state = SettingsManager::loadCANState();
bool saved_debug_state = SettingsManager::loadDebugState(); bool saved_debug_state = SettingsManager::loadDebugState();
DiffLocks::init(SettingsManager::loadDiffLockState(), SettingsManager::loadDiffLockInvert()); // CH422G bus is up since DisplayInit
ReverseLight::init(SettingsManager::loadReverseLightState(), DisplayInit::expander()); // DO0 off until the lever says R
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)"); ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
// Initialize UI State Manager // Initialize UI State Manager
@@ -142,7 +155,7 @@ void setup()
ESP_LOGI("MAIN", "- Link: UART1 TX GPIO44 (RS485 A/B) + ESP-NOW broadcast, protocol v%u", PACKET_VERSION); ESP_LOGI("MAIN", "- Link: UART1 TX GPIO44 (RS485 A/B) + ESP-NOW broadcast, protocol v%u", PACKET_VERSION);
ESP_LOGI("MAIN", "- Console: type 'cfg help' to tune the Patrol gauge outputs"); ESP_LOGI("MAIN", "- Console: type 'cfg help' to tune the Patrol gauge outputs");
ESP_LOGI("MAIN", "- Screens: Driveline (boot) <- left: Settings | right: Gauge tuning ->"); ESP_LOGI("MAIN", "- Screens: Driveline (boot) <- left: Settings | right: Gauge tuning ->");
ESP_LOGI("MAIN", "- Settings: Wi-Fi (remembered network), Updates, System"); ESP_LOGI("MAIN", "- Settings: Wi-Fi (remembered network), Updates, System, Vehicle");
ESP_LOGI("MAIN", "- UART transmits at 5Hz (200ms) when enabled"); ESP_LOGI("MAIN", "- UART transmits at 5Hz (200ms) when enabled");
} }
@@ -164,12 +177,18 @@ void loop()
PerfMon::tick(); PerfMon::tick();
DiagProbe::tick(); DiagProbe::tick();
Ota::tick(); // confirms a freshly installed image after healthy uptime Ota::tick(); // confirms a freshly installed image after healthy uptime
LinkPeer::tick(); // Controller B heard/lost, credential sync LinkPeer::tick(); // Inst. Cluster heard/lost, credential sync
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
ReverseLight::tick(); // DO0 follows the lever in R (10 Hz decision, 200 ms confirm)
Vehicle::tick(); // deferred NVS write of the Vehicle settings
EcuIdent::tick(); // one-shot DDE identification read while nothing is stored
DrivelineScreen::tick(); DrivelineScreen::tick();
TuningScreen::tick(); TuningScreen::tick();
SettingsScreen::tick(); SettingsScreen::tick();
StatusOverlay::tick(); StatusOverlay::tick();
EngineScreen::tick();
SportScreen::tick();
delay(100); // Check frequently to catch screen changes quickly delay(100); // Check frequently to catch screen changes quickly
} }
+96
View File
@@ -0,0 +1,96 @@
/*
* Bench Simulation Module Implementation - see bench_sim.h
*/
#include "bench_sim.h"
#include "serial_lock.h"
#include "vehicle.h"
namespace BenchSim {
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
static volatile bool g_active = false;
static volatile int16_t g_torque_x10 = 0;
static volatile uint16_t g_rpm = 0;
static volatile uint16_t g_shaft_raw = 0;
static void print(const char* fmt, ...) {
char buf[200];
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 status() {
if (!g_active) { print("[sim] off - screens show the CAN bus"); return; }
uint16_t shaft_rpm = can_output_shaft_rpm(g_shaft_raw);
uint16_t hp = Vehicle::powerHpX10(g_torque_x10, g_rpm);
uint16_t kmh = Vehicle::speedKmhX10(g_shaft_raw);
print("[sim] ON: torque %d.%d Nm, engine %u rpm -> %u.%u hp; output shaft %u rpm (raw %u) -> %u.%u km/h (not saved)",
g_torque_x10 / 10, abs(g_torque_x10 % 10), g_rpm, hp / 10, hp % 10,
shaft_rpm, g_shaft_raw, kmh / 10, kmh % 10);
}
static void help() {
print("sim torque <Nm> [rpm <n>] [shaft <rpm>] bench values for the Sport / Driveline screens");
print("sim rpm <n> engine speed (power = torque x rpm)");
print("sim shaft <rpm> output shaft speed (road speed on screen)");
print("sim status");
print("sim off back to the CAN bus (also at every boot)");
}
// ============================================================================
// PUBLIC API
// ============================================================================
bool isActive() { return g_active; }
void apply(driveline_t& dl) {
if (!g_active) return;
dl.engine_torque_x10 = g_torque_x10;
dl.engine_rpm = g_rpm;
dl.output_shaft_raw = g_shaft_raw;
dl.ignition_on = true;
dl.engine_run_state = ENGINE_RUN_RUNNING;
}
bool handleCommand(const char* line) {
if (strncmp(line, "sim", 3) != 0 || (line[3] != 0 && line[3] != ' ')) return false;
char buf[96];
snprintf(buf, sizeof(buf), "%s", line);
char* argv[8];
int argc = 0;
for (char* t = strtok(buf, " \t"); t && argc < 8; t = strtok(NULL, " \t")) argv[argc++] = t;
if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; }
if (!strcmp(argv[1], "status")) { status(); return true; }
if (!strcmp(argv[1], "off")) {
g_active = false;
g_torque_x10 = 0; g_rpm = 0; g_shaft_raw = 0;
print("[sim] off");
return true;
}
// any number of "<name> <value>" pairs
bool ok = argc >= 3 && (argc % 2) == 1;
for (int i = 1; ok && i + 1 < argc; i += 2) {
long v = strtol(argv[i + 1], NULL, 0);
if (!strcmp(argv[i], "torque")) g_torque_x10 = (int16_t)constrain(v, -3000, 3000) * 10;
else if (!strcmp(argv[i], "rpm")) g_rpm = (uint16_t)constrain(v, 0, 10000);
else if (!strcmp(argv[i], "shaft")) g_shaft_raw = (uint16_t)constrain((v * OUTPUT_SHAFT_RPM_DEN) / OUTPUT_SHAFT_RPM_NUM, 0, 65535);
else ok = false;
}
if (!ok) { help(); return true; }
g_active = true;
status();
return true;
}
} // namespace BenchSim
+31
View File
@@ -0,0 +1,31 @@
/*
* Bench Simulation Module (`sim` console)
*
* Feeds made-up torque / engine rpm / output shaft values into the driveline
* snapshot so the Sport screen, the Driveline and the Vehicle page can be
* looked at on the bench without a CAN bus. While active, the snapshot also
* reads ignition on + engine running, so the screens treat it as live.
*
* Bench tool only: never saved, off at every boot, nothing is transmitted,
* and the Inst. Cluster is not affected (that side has `cfg override`).
* The screens say "SIM" while it is on so a simulated number is never
* mistaken for the car's.
*/
#pragma once
#include <Arduino.h>
#include "drivers/can_driver.h"
namespace BenchSim {
/** True while a simulation is active (`sim ...` until `sim off`). */
bool isActive();
/** Overlay the simulated fields onto a driveline snapshot. No-op when off. */
void apply(driveline_t& dl);
/** `sim torque <Nm> | rpm <n> | shaft <rpm> | status | off` (several pairs per line). */
bool handleCommand(const char* line);
} // namespace BenchSim
+243 -1
View File
@@ -80,6 +80,36 @@ 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 uint32_t g_tx_fail_at_send = 0; // CANDriver tx_failures when the request went out
static bool g_last_req_unacked = false; static bool g_last_req_unacked = false;
// live engine data (Engine data screen) - liveStop() is public, declared in the header
// Which `2C 10 <id>` identifiers to ask is PER DDE SOFTWARE (Patrol 1's set
// returned junk on Patrol 2, 2026-10-18): the Engine data screen picks a set
// from its per-ECU profile table and installs it with liveConfigure(). Until
// then nothing is asked. 0 = no identifier for that slot (never requested).
static live_set_t g_live_set = {0, {0, 0, 0, 0}};
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];
// ECU identification: handler + a passive reassembler for OTHER testers' `1A xx`
// replies on 0x612 (we see the DDE's frames whoever asked; the asker sends the
// flow control). CAN-task only, so no lock.
static const size_t IDENT_MAX = 96; // `1A 80` is 31-37 bytes, `1A 86` 65
static ident_cb_t g_ident_cb = NULL;
static uint8_t g_pid_buf[IDENT_MAX];
static size_t g_pid_len = 0, g_pid_exp = 0;
static uint8_t g_pid_seq = 0;
static bool g_pid_active = false;
// ============================================================================ // ============================================================================
// HELPERS // HELPERS
// ============================================================================ // ============================================================================
@@ -335,6 +365,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. */ /** A complete ISO-TP payload from `id`. Caller holds g_mutex. */
static void handleReply(uint32_t id, const uint8_t* p, size_t n) { 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]; char hex[3 * 48 + 1];
hexdump(hex, sizeof(hex), p, n > 48 ? 48 : n); hexdump(hex, sizeof(hex), p, n > 48 ? 48 : n);
g_replies++; g_replies++;
@@ -382,6 +434,10 @@ static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
as[k] = 0; as[k] = 0;
print("[diag] +%03u %-48s |%s|", (unsigned)(i - 1), hx, as); print("[diag] +%03u %-48s |%s|", (unsigned)(i - 1), hx, as);
} }
// our own identification read: hand the block to EcuIdent
if (g_req_mode == 0x1A && g_bmw_target == BMW_ADDR_DDE && n >= 2 && g_ident_cb) {
g_ident_cb(p[1], p, n, true);
}
return; return;
} }
@@ -432,10 +488,46 @@ static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
} }
} }
/**
* Reassemble a `5A xx` identification reply the DDE sends to ANOTHER tester
* (our own request's reply goes through handleReply). Extended addressing:
* byte 0 = 0xF1 (the tester), then the ISO-TP PCI.
*/
static void passiveIdent(const twai_message_t& m) {
const uint8_t* d = m.data;
uint8_t dlc = m.data_length_code;
if (dlc < 3 || d[0] != 0xF1) return;
if (g_state == ST_WAITING && g_bmw && g_bmw_target == BMW_ADDR_DDE) return; // ours: handled elsewhere
uint8_t pci = d[1] >> 4;
if (pci == 0x1) { // first frame: F1 1L LL 5A xx ...
if (dlc < 5 || d[3] != 0x5A) { g_pid_active = false; return; }
g_pid_exp = ((size_t)(d[1] & 0x0F) << 8) | d[2];
if (g_pid_exp > IDENT_MAX) g_pid_exp = IDENT_MAX;
g_pid_len = 0;
for (uint8_t i = 3; i < dlc && g_pid_len < g_pid_exp; i++) g_pid_buf[g_pid_len++] = d[i];
g_pid_seq = 1;
g_pid_active = true;
} else if (pci == 0x2) { // consecutive frame: F1 2N ...
if (!g_pid_active || (d[1] & 0x0F) != (g_pid_seq & 0x0F)) return;
for (uint8_t i = 2; i < dlc && g_pid_len < g_pid_exp; i++) g_pid_buf[g_pid_len++] = d[i];
g_pid_seq++;
if (g_pid_len >= g_pid_exp) {
g_pid_active = false;
if (g_pid_len >= 2) g_ident_cb(g_pid_buf[1], g_pid_buf, g_pid_len, false);
}
} else if (pci == 0x0) { // single frame (not seen from a DDE, but cheap)
size_t len = d[1] & 0x0F;
if (len >= 2 && 2 + len <= dlc && d[2] == 0x5A) g_ident_cb(d[3], d + 2, len, false);
}
}
void onFrame(const twai_message_t& m) { void onFrame(const twai_message_t& m) {
if (m.extd) return; if (m.extd) return;
uint32_t id = m.identifier; uint32_t id = m.identifier;
if (id == BMW_RX_BASE + BMW_ADDR_DDE && g_ident_cb) passiveIdent(m);
// Foreign tester activity: our own frames are not looped back in NORMAL mode, // Foreign tester activity: our own frames are not looped back in NORMAL mode,
// so anything on these IDs is somebody else's request. // 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) { if (id == OBD_FUNCTIONAL_ID || (id >= OBD_REQ_FIRST && id <= OBD_REQ_LAST) || id == BMW_TESTER_ID) {
@@ -540,13 +632,84 @@ static void printScanSummary() {
print("[diag] next: `diag pid 0C` (rpm) to prove a data read, `diag vin` for the donor"); 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 ? g_live_set.define_id : g_live_set.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;
if (g_live_set.define_id) { sendLive(-1); return; }
}
// next slot that has an identifier on this DDE (at most one full turn)
for (int i = 0; i < LIVE_COUNT; i++) {
uint8_t slot = (uint8_t)((g_live_next + i) % LIVE_COUNT);
if (g_live_set.ids[slot] == 0) continue;
g_live_next = (uint8_t)((slot + 1) % LIVE_COUNT);
sendLive((int8_t)slot);
return;
}
// no identifiers at all: nothing to ask (the screen says so)
}
void tick() { void tick() {
if (g_state == ST_IDLE) return; if (g_state == ST_IDLE) { liveTick(); return; }
uint32_t now = millis(); uint32_t now = millis();
lock(); lock();
if ((int32_t)(now - g_deadline_ms) < 0) { unlock(); return; } 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 // request over
bool got_reply = g_replies_this_req > 0; bool got_reply = g_replies_this_req > 0;
bool scan = g_scan_active; bool scan = g_scan_active;
@@ -721,4 +884,83 @@ void init() {
if (!g_mutex) g_mutex = xSemaphoreCreateMutex(); if (!g_mutex) g_mutex = xSemaphoreCreateMutex();
} }
// ----------------------------------------------------------------------------
// Live engine data
// ----------------------------------------------------------------------------
static void liveRestart() {
lock();
memset(g_live_vals, 0, sizeof(g_live_vals));
unlock();
g_live_defined = false;
g_live_next = 0;
g_live_misses = 0;
g_live_last_tx = 0;
g_live_state = LIVE_RUNNING;
}
void liveConfigure(const live_set_t* set) {
live_set_t s = set ? *set : live_set_t{0, {0, 0, 0, 0}};
if (memcmp(&s, &g_live_set, sizeof(s)) == 0) return;
g_live_set = s;
if (g_live) liveRestart(); // old values belong to the old identifiers
print("[diag] live engine data identifiers: define %04X, rail %04X, boost %04X, air temp %04X, battery %04X (0 = not asked)",
s.define_id, s.ids[LIVE_RAIL], s.ids[LIVE_BOOST], s.ids[LIVE_AIR_TEMP], s.ids[LIVE_BATTERY]);
}
void liveKeepAlive() {
g_live_keep_ms = millis();
if (g_live) return;
g_live = true;
liveRestart();
print("[diag] live engine data ON: polling the DDE (2C 10 %04X/%04X/%04X/%04X, 0 = not asked)",
g_live_set.ids[LIVE_RAIL], g_live_set.ids[LIVE_BOOST], g_live_set.ids[LIVE_AIR_TEMP], g_live_set.ids[LIVE_BATTERY]);
}
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;
}
// ----------------------------------------------------------------------------
// ECU identification
// ----------------------------------------------------------------------------
bool canSendNow() {
if (!CANDriver::isActive()) return false;
uint32_t now = millis();
lock();
bool busy = (g_state != ST_IDLE);
bool tester = (g_last_tester_ms != 0) && (now - g_last_tester_ms < TESTER_GUARD_MS);
unlock();
return !busy && !tester;
}
bool requestIdent(uint8_t sub) {
uint8_t req[2] = {0x1A, sub};
return sendBmwRequest(BMW_ADDR_DDE, req, sizeof(req));
}
void setIdentHandler(ident_cb_t cb) {
g_ident_cb = cb;
}
} // namespace DiagProbe } // namespace DiagProbe
+78
View File
@@ -28,6 +28,17 @@
* services are whitelisted in sendBmwRequest(): 1A (ident), 18 (DTCs), * services are whitelisted in sendBmwRequest(): 1A (ident), 18 (DTCs),
* 21/22 (read data) — never session control, resets, or writes. * 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 up to four DDE values with the
* same KWP `2C 10 <id>` requests the Launch uses (an optional one-time
* define, then the slot identifiers in turn, one request in flight, ~100 ms
* apart). The identifiers are installed by the screen per identified DDE
* (liveConfigure(); Patrol 1: define 15E0, rail 00DF, boost 0091, charge-air
* temp 16A8, battery 0093; Patrol 2: rail 00C2, boost 003A, battery 002F).
* 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 frames.
*
* Every frame we send is echoed on the console as * Every frame we send is echoed on the console as
* CANTX,<ts_ms>,<id_hex>,0,<dlc>,<data_hex> * CANTX,<ts_ms>,<id_hex>,0,<dlc>,<data_hex>
* — the same shape as CANRAW — so a capture holds both halves of every exchange. * — the same shape as CANRAW — so a capture holds both halves of every exchange.
@@ -58,4 +69,71 @@ void tick();
*/ */
void onFrame(const twai_message_t& m); 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;
/**
* The `2C 10 <id>` identifiers to poll, one per live_id_t slot, 0 = none known
* for this DDE (that slot is never requested, liveValue() stays invalid), plus
* the one-time define id sent first (0 = none). THE IDENTIFIERS DIFFER PER DDE
* SOFTWARE: Patrol 1's set read junk on Patrol 2 (2026-10-18), so the Engine
* data screen installs the set that matches the identified ECU (`EcuIdent`).
* Nothing is asked until a set with at least one identifier is installed.
*/
typedef struct {
uint16_t define_id;
uint16_t ids[LIVE_COUNT];
} live_set_t;
/** Install the identifier set (NULL = none). Restarts the values if polling. */
void liveConfigure(const live_set_t* set);
/** 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);
// ---- ECU identification (EcuIdent module) ----------------------------------
/**
* True when a request could go out right now: CAN running, nothing in flight,
* no foreign tester for TESTER_GUARD_MS. Prints nothing (unlike a refused send).
*/
bool canSendNow();
/**
* One KWP `1A <sub>` identification request to the DDE on 0x6F1 (sub 0x86 or
* 0x80), console-echoed like `diag ident`. Returns false if refused.
*/
bool requestIdent(uint8_t sub);
/**
* Handler for every complete `5A <sub> ...` identification payload the DDE puts
* on 0x612: the reply to our own request (ours = true), or to another tester's
* (ours = false - the Launch re-reads `1A 80` every cycle, so a connected scan
* tool identifies the ECU for free). Runs in the CAN task: copy and return.
*/
typedef void (*ident_cb_t)(uint8_t sub, const uint8_t* payload, size_t n, bool ours);
void setIdentHandler(ident_cb_t cb);
} // namespace DiagProbe } // 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
+4
View File
@@ -10,6 +10,7 @@
namespace DisplayInit { namespace DisplayInit {
static Backlight* g_backlight = nullptr; static Backlight* g_backlight = nullptr;
static esp_expander::Base* g_expander = nullptr;
/** /**
* Firmware version, bottom-right on every screen. Lives on lv_layer_top(), which * Firmware version, bottom-right on every screen. Lives on lv_layer_top(), which
@@ -25,6 +26,8 @@ static void createVersionLabel() {
lv_obj_align(lbl, LV_ALIGN_BOTTOM_RIGHT, -8, -4); lv_obj_align(lbl, LV_ALIGN_BOTTOM_RIGHT, -8, -4);
} }
esp_expander::Base* expander() { return g_expander; }
void setBacklight(bool on) { void setBacklight(bool on) {
if (g_backlight == nullptr) return; if (g_backlight == nullptr) return;
if (on) g_backlight->on(); if (on) g_backlight->on();
@@ -117,6 +120,7 @@ DisplayObjects init() {
// Return board and backlight objects for later use // Return board and backlight objects for later use
g_backlight = backlight; g_backlight = backlight;
g_expander = board->getIO_Expander() ? board->getIO_Expander()->getBase() : nullptr;
return {board, backlight}; return {board, backlight};
} }
+9
View File
@@ -46,4 +46,13 @@ DisplayObjects init();
/** Backlight on/off after init() (e.g. dark during OTA flash writes, which flicker the panel). */ /** Backlight on/off after init() (e.g. dark during OTA flash writes, which flicker the panel). */
void setBacklight(bool on); void setBacklight(bool on);
/**
* The board's CH422G IO expander (panel library object), after init(). Modules
* that drive its OC pins (ReverseLight: OC0 = DO0) must go through this object,
* never raw I2C, so the library's cached output register stays right - the
* backlight writes that cache back to the chip on every on/off. NULL if the
* board has no expander.
*/
esp_expander::Base* expander();
} // namespace DisplayInit } // namespace DisplayInit
+227 -9
View File
@@ -5,10 +5,17 @@
#include "driveline_screen.h" #include "driveline_screen.h"
#include "uart_manager.h" #include "uart_manager.h"
#include <string.h> #include <string.h>
#include <math.h>
#include "display/lvgl_v8_port.h" #include "display/lvgl_v8_port.h"
#include "drivers/can_driver.h" #include "drivers/can_driver.h"
#include "tuning_screen.h" #include "tuning_screen.h"
#include "settings_screen.h" #include "settings_screen.h"
#include "diff_locks.h"
#include "engine_screen.h"
#include "sport_screen.h"
#include "vehicle.h"
#include "bench_sim.h"
#include "ui_kit.h"
#include "esp_log.h" #include "esp_log.h"
namespace DrivelineScreen { namespace DrivelineScreen {
@@ -45,10 +52,12 @@ static lv_obj_t* g_rpm_lbl = NULL;
static lv_obj_t* g_torque_lbl = NULL; static lv_obj_t* g_torque_lbl = NULL;
static lv_obj_t* g_pedal_lbl = NULL; static lv_obj_t* g_pedal_lbl = NULL;
static lv_obj_t* g_shaft_lbl = NULL; static lv_obj_t* g_shaft_lbl = NULL;
static lv_obj_t* g_speed_lbl = NULL;
static lv_obj_t* g_ign_chip = NULL; static lv_obj_t* g_ign_chip = NULL;
static lv_obj_t* g_eng_chip = NULL; static lv_obj_t* g_eng_chip = NULL;
static lv_obj_t* g_clutch_chip = NULL; static lv_obj_t* g_clutch_chip = NULL;
static lv_obj_t* g_cool_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 // PRIVATE HELPERS
@@ -111,6 +120,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. * @brief Compose the hero gear label from the 0x1D2 pieces.
* *
@@ -185,6 +330,16 @@ static void onScreenGesture(lv_event_t* e) {
} }
} }
static void onEngineData(lv_event_t* e) {
(void)e;
EngineScreen::show();
}
static void onSport(lv_event_t* e) {
(void)e;
SportScreen::show();
}
/** /**
* @brief Build the screen. Idempotent — returns immediately if already built. * @brief Build the screen. Idempotent — returns immediately if already built.
*/ */
@@ -212,6 +367,50 @@ static void build() {
g_cool_chip = makeChip(bar, "COOLING --"); g_cool_chip = makeChip(bar, "COOLING --");
// Gear mismatch: the ring and the gear letter turn red, and the overlay banner says so. // 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);
// Sport displays (torque + power gauges), left of the Engine data button.
lv_obj_t* sport = UiKit::button(g_screen, "Sport", 150, 56,
UiKit::BTN_SECONDARY, onSport, NULL);
lv_obj_align(sport, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16 - 200 - 12, 60);
// ---- gear hero ------------------------------------------------------- // ---- gear hero -------------------------------------------------------
g_gear_ring = lv_obj_create(g_screen); g_gear_ring = lv_obj_create(g_screen);
lv_obj_set_size(g_gear_ring, 220, 220); lv_obj_set_size(g_gear_ring, 220, 220);
@@ -259,23 +458,27 @@ static void build() {
lv_obj_set_style_text_color(g_rpm_lbl, COL_TEXT, 0); lv_obj_set_style_text_color(g_rpm_lbl, COL_TEXT, 0);
lv_obj_align(g_rpm_lbl, LV_ALIGN_CENTER, 330, 108); lv_obj_align(g_rpm_lbl, LV_ALIGN_CENTER, 330, 108);
// ---- bottom row: torque | pedal | output shaft ----------------------- // ---- bottom row: torque | pedal | output shaft | speed ---------------
// Turbine speed is intentionally NOT shown: it's a diagnostic (engagement // Turbine speed is intentionally NOT shown: it's a diagnostic (engagement
// proof), not a driver number. Still decoded in the driver. // proof), not a driver number. Still decoded in the driver.
g_torque_lbl = makeStat(g_screen, "TORQUE (Nm)", &lv_font_montserrat_30, g_torque_lbl = makeStat(g_screen, "TORQUE (Nm)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, -340, -34); LV_ALIGN_BOTTOM_MID, -390, -34);
g_pedal_lbl = makeStat(g_screen, "PEDAL (%)", &lv_font_montserrat_30, g_pedal_lbl = makeStat(g_screen, "PEDAL (%)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, 0, -34); LV_ALIGN_BOTTOM_MID, -130, -34);
// Output shaft in rpm via a PROVISIONAL factor (one Launch point). The label // Output shaft in rpm via a PROVISIONAL factor (one Launch point). The label
// carries "~" so the screen doesn't present an unlocked scaling as exact. // carries "~" so the screen doesn't present an unlocked scaling as exact.
g_shaft_lbl = makeStat(g_screen, "OUTPUT (~rpm)", &lv_font_montserrat_30, g_shaft_lbl = makeStat(g_screen, "OUTPUT (~rpm)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, 340, -34); LV_ALIGN_BOTTOM_MID, 130, -34);
// Road speed = output shaft / final drive x tyre circumference (Settings >
// Vehicle). Inherits the "~" of the shaft factor.
g_speed_lbl = makeStat(g_screen, "SPEED (~km/h)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, 390, -34);
lv_obj_t* hint = lv_label_create(g_screen); lv_obj_t* hint = lv_label_create(g_screen);
lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: Settings | swipe right: Gauge tuning " LV_SYMBOL_RIGHT); lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: Settings | swipe right: Gauge tuning " LV_SYMBOL_RIGHT);
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0); lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(hint, COL_MUTED, 0); lv_obj_set_style_text_color(hint, COL_MUTED, 0);
lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -14); lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -8);
ESP_LOGI("Driveline", "Driveline screen built"); ESP_LOGI("Driveline", "Driveline screen built");
} }
@@ -299,7 +502,7 @@ void tick() {
if (millis() - last_refresh < 100) return; if (millis() - last_refresh < 100) return;
last_refresh = millis(); last_refresh = millis();
bool can_up = CANDriver::isActive(); bool can_up = CANDriver::isActive() || BenchSim::isActive(); // `sim` console counts as a live bus
driveline_t dl = CANDriver::getDriveline(); driveline_t dl = CANDriver::getDriveline();
// Snapshot the shared struct under its own mutex, briefly. // Snapshot the shared struct under its own mutex, briefly.
@@ -322,10 +525,13 @@ void tick() {
(void)gear; // gear now comes from the driveline pieces, not the UART enum (void)gear; // gear now comes from the driveline pieces, not the UART enum
lvgl_port_lock(-1); 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 // 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 // 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 // quiet with the car rather than freezing the last frame. 0x3B4 sends its
// ignition nibble on-change, so this reset is effectively instant. // ignition nibble on-change, and the 0x1D2 lever fallback (buses without
// 0x3B4) flips within one 200 ms frame, so this reset is effectively instant.
if (!can_up || !dl.ignition_on) { if (!can_up || !dl.ignition_on) {
setText(g_gear_lbl, "--"); setText(g_gear_lbl, "--");
setText(g_coolant_lbl, "--"); setText(g_coolant_lbl, "--");
@@ -334,6 +540,7 @@ void tick() {
setText(g_torque_lbl, "--"); setText(g_torque_lbl, "--");
setText(g_pedal_lbl, "--"); setText(g_pedal_lbl, "--");
setText(g_shaft_lbl, "--"); setText(g_shaft_lbl, "--");
setText(g_speed_lbl, "--");
lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF); lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF);
setRing(COL_ACCENT); setRing(COL_ACCENT);
setColour(g_gear_lbl, COL_TEXT); setColour(g_gear_lbl, COL_TEXT);
@@ -389,8 +596,13 @@ void tick() {
lv_bar_set_value(g_rpm_bar, dl.engine_rpm > RPM_MAX ? RPM_MAX : dl.engine_rpm, LV_ANIM_OFF); lv_bar_set_value(g_rpm_bar, dl.engine_rpm > RPM_MAX ? RPM_MAX : dl.engine_rpm, LV_ANIM_OFF);
// Torque is signed (negative under overrun/braking); one decimal, matching // Torque is signed (negative under overrun/braking); one decimal, matching
// the 0.5 Nm resolution of the field. // the 0.5 Nm resolution of the field. Engine off: the field holds a junk
// value (812 Nm on Patrol 2, 245 on Patrol 1), so show nothing.
if (dl.engine_run_state == ENGINE_RUN_RUNNING) {
snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10)); snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10));
} else {
snprintf(buf, sizeof(buf), "--");
}
setText(g_torque_lbl, buf); setText(g_torque_lbl, buf);
snprintf(buf, sizeof(buf), "%u", dl.pedal_percent); snprintf(buf, sizeof(buf), "%u", dl.pedal_percent);
@@ -400,8 +612,14 @@ void tick() {
snprintf(buf, sizeof(buf), "%u", can_output_shaft_rpm(dl.output_shaft_raw)); snprintf(buf, sizeof(buf), "%u", can_output_shaft_rpm(dl.output_shaft_raw));
setText(g_shaft_lbl, buf); setText(g_shaft_lbl, buf);
// Road speed from the same shaft reading and the Settings > Vehicle numbers.
uint16_t kmh_x10 = Vehicle::speedKmhX10(dl.output_shaft_raw);
snprintf(buf, sizeof(buf), "%u", kmh_x10 / 10);
setText(g_speed_lbl, buf);
// ---- status chips ---------------------------------------------------- // ---- status chips ----------------------------------------------------
setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF", if (BenchSim::isActive()) setChip(g_ign_chip, "IGN SIM", COL_AMBER); // bench numbers, not the car's
else setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF",
dl.ignition_on ? COL_OK : COL_MUTED); dl.ignition_on ? COL_OK : COL_MUTED);
switch (dl.engine_run_state) { switch (dl.engine_run_state) {
+382
View File
@@ -0,0 +1,382 @@
/*
* ECU Identification Module Implementation - see ecu_ident.h
*
* Threading: onIdent() runs in the CAN task and only parks the payload;
* everything else (sequencing, NVS, console) runs in loop() via tick().
*/
#include "ecu_ident.h"
#include "diag_probe.h"
#include "bench_sim.h"
#include "serial_lock.h"
#include "drivers/can_driver.h"
#include <Preferences.h>
namespace EcuIdent {
// ============================================================================
// CONSTANTS
// ============================================================================
static const char* NVS_NAMESPACE = "settings";
static const char* NVS_KEY_86 = "ecu_id86";
static const char* NVS_KEY_80 = "ecu_id80";
static const size_t BLOCK_MAX = 96;
static const uint8_t SUB_86 = 0x86, SUB_80 = 0x80;
static const uint8_t ATTEMPTS_PER_SUB = 3; // per boot, while nothing is stored
static const uint32_t RETRY_GAP_MS = 10000; // between attempts
static const uint32_t SETTLE_MS = 5000; // ignition on this long before the first ask
static const uint32_t ANSWER_WAIT_MS = 1500; // DiagProbe's own timeout is 500 ms + linger
// ============================================================================
// STATE
// ============================================================================
typedef struct {
uint8_t sub;
uint8_t len; // 0 = empty
uint8_t raw[BLOCK_MAX];
} block_t;
static block_t g_blk[2] = {{SUB_86, 0, {0}}, {SUB_80, 0, {0}}}; // [0] = 1A 86, [1] = 1A 80
// CAN task -> loop handoff (single writer, single reader)
static volatile bool g_pending = false;
static block_t g_pending_blk;
static bool g_pending_ours = false;
// one-shot read sequencing
static bool g_read_session = false; // true while this boot is allowed to transmit
static uint8_t g_attempts[2] = {0, 0};
static uint32_t g_last_try_ms = 0;
static uint32_t g_ign_since_ms = 0; // first tick with ignition on (0 = not yet)
static bool g_waiting = false; // a request of ours is out
static bool g_gave_up_printed = false;
// passive check
static bool g_changed = false;
static char g_bus_part[12] = ""; // part number of the differing 1A 80 block seen on the bus
// ============================================================================
// HELPERS
// ============================================================================
static void print(const char* fmt, ...) {
char buf[200];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static block_t* blockFor(uint8_t sub) {
if (sub == SUB_86) return &g_blk[0];
if (sub == SUB_80) return &g_blk[1];
return NULL;
}
static block_t* primary() {
if (g_blk[0].len) return &g_blk[0];
if (g_blk[1].len) return &g_blk[1];
return NULL;
}
/** BCD bytes -> decimal string without leading zeros ("" if any nibble > 9). */
static bool bcd(const uint8_t* p, size_t n, char* out, size_t out_sz) {
size_t w = 0;
bool started = false;
for (size_t i = 0; i < n; i++) {
uint8_t hi = p[i] >> 4, lo = p[i] & 0x0F;
if (hi > 9 || lo > 9) { out[0] = 0; return false; }
if (started || hi) { if (w + 1 < out_sz) out[w++] = (char)('0' + hi); started = true; }
if (started || lo) { if (w + 1 < out_sz) out[w++] = (char)('0' + lo); started = true; }
}
if (!started && w + 1 < out_sz) out[w++] = '0';
out[w] = 0;
return true;
}
/** The part number this block carries (observed offsets), "" if it does not fit. */
static void partOf(const block_t* b, char* out, size_t out_sz) {
out[0] = 0;
if (!b || !b->len) return;
// 1A 86: 5A 86 "@B892524 " 06 03 07 00 00 [07 79 97 64] ... (Patrol 1, 2026-09-23)
// 1A 80: 5A 80 00 00 [07 79 49 04] 10 00 00 10 35 39 20 04 01 21 ... (Patrol 2, 2026-10-18)
if (b->sub == SUB_86 && b->len >= 20) bcd(b->raw + 16, 4, out, out_sz);
else if (b->sub == SUB_80 && b->len >= 8) bcd(b->raw + 4, 4, out, out_sz);
}
/** "20YY-MM-DD" from the block's BCD date, "" if absent or implausible. */
static void dateOf(const block_t* b, char* out, size_t out_sz) {
out[0] = 0;
if (!b || !b->len) return;
const uint8_t* d = NULL;
if (b->sub == SUB_86 && b->len >= 14) d = b->raw + 11; // after the 9-char "@B892524 "
else if (b->sub == SUB_80 && b->len >= 18) d = b->raw + 15;
if (!d) return;
char y[4], m[4], dd[4];
if (!bcd(d, 1, y, sizeof(y)) || !bcd(d + 1, 1, m, sizeof(m)) || !bcd(d + 2, 1, dd, sizeof(dd))) return;
int mi = atoi(m), di = atoi(dd);
if (mi < 1 || mi > 12 || di < 1 || di > 31) return;
snprintf(out, out_sz, "20%02d-%02d-%02d", atoi(y), mi, di);
}
/** The VIN prefix the 1A 86 block ends with ("" otherwise). */
static void vinOf(const block_t* b, char* out, size_t out_sz) {
out[0] = 0;
if (!b || b->sub != SUB_86 || b->len < 63) return;
size_t w = 0;
for (size_t i = 53; i < 63 && w + 1 < out_sz; i++) {
char c = (char)b->raw[i];
if (c < 0x20 || c >= 0x7F) { out[0] = 0; return; }
out[w++] = c;
}
out[w] = 0;
}
static void save(const block_t* b) {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, false);
const char* key = (b->sub == SUB_86) ? NVS_KEY_86 : NVS_KEY_80;
if (b->len) prefs.putBytes(key, b->raw, b->len);
else prefs.remove(key);
prefs.end();
}
static void load(block_t* b) {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, true);
const char* key = (b->sub == SUB_86) ? NVS_KEY_86 : NVS_KEY_80;
size_t n = prefs.getBytesLength(key);
if (n > 0 && n <= BLOCK_MAX) {
prefs.getBytes(key, b->raw, n);
b->len = (uint8_t)n;
} else {
b->len = 0;
}
prefs.end();
}
static void describeBlock(const block_t* b, char* buf, size_t n) {
char part[12], date[12];
partOf(b, part, sizeof(part));
dateOf(b, date, sizeof(date));
if (part[0] && date[0]) snprintf(buf, n, "DDE %s - %s", part, date);
else if (part[0]) snprintf(buf, n, "DDE %s", part);
else snprintf(buf, n, "DDE ident 1A %02X, %u bytes", b->sub, b->len);
if (b->sub == SUB_80 && !g_blk[0].len) {
size_t l = strlen(buf);
snprintf(buf + l, n - l, " (1A 80)");
}
}
/** CAN task: park the payload for tick(). A second one before it is taken is dropped. */
static void onIdent(uint8_t sub, const uint8_t* payload, size_t n, bool ours) {
if (g_pending || n < 2 || n > BLOCK_MAX) return;
if (sub != SUB_86 && sub != SUB_80) return;
g_pending_blk.sub = sub;
g_pending_blk.len = (uint8_t)n;
memcpy(g_pending_blk.raw, payload, n);
g_pending_ours = ours;
g_pending = true;
}
/** loop(): a block arrived - store it, or compare it with what is stored. */
static void takePending() {
block_t in = g_pending_blk;
bool ours = g_pending_ours;
g_pending = false;
g_waiting = false;
block_t* b = blockFor(in.sub);
if (!b) return;
char desc[64];
if (b->len == 0) {
*b = in;
save(b);
describeBlock(b, desc, sizeof(desc));
print("[ecu] stored 1A %02X (%u bytes, %s): %s", in.sub, in.len, ours ? "our read" : "seen on the bus", desc);
if (in.sub == SUB_80) { g_changed = false; g_bus_part[0] = 0; }
return;
}
bool same = (b->len == in.len) && memcmp(b->raw, in.raw, in.len) == 0;
if (in.sub == SUB_80) {
if (same) {
if (g_changed) print("[ecu] 1A 80 on the bus matches the stored block again");
g_changed = false;
g_bus_part[0] = 0;
} else {
char stored[12];
partOf(&in, g_bus_part, sizeof(g_bus_part));
partOf(b, stored, sizeof(stored));
if (!g_changed) {
print("[ecu] ECU CHANGED? the 1A 80 block on the bus (%s) differs from the stored one (%s) - `ecu forget` or Re-read ECU",
g_bus_part[0] ? g_bus_part : "?", stored[0] ? stored : "?");
}
g_changed = true;
}
} else if (!same) {
print("[ecu] note: a 1A 86 block on the bus differs from the stored one");
}
}
/** loop(): send the next identification request when every condition holds. */
static void readTick() {
if (!g_read_session || g_waiting) return;
if (g_blk[0].len && g_blk[1].len) { g_read_session = false; return; } // both in hand
// the sub-function still missing with attempts left: 86 first, then 80
int idx = -1;
for (int i = 0; i < 2; i++) {
if (!g_blk[i].len && g_attempts[i] < ATTEMPTS_PER_SUB) { idx = i; break; }
}
if (idx < 0) {
g_read_session = false;
if (!known() && !g_gave_up_printed) {
g_gave_up_printed = true;
print("[ecu] no identification answer after %u tries - UNKNOWN ECU, will try again next boot",
(unsigned)(2 * ATTEMPTS_PER_SUB));
}
return;
}
uint32_t now = millis();
if (!CANDriver::isActive() || BenchSim::isActive()) { g_ign_since_ms = 0; return; }
driveline_t dl = CANDriver::getDriveline();
if (!dl.ignition_on) { g_ign_since_ms = 0; return; }
if (g_ign_since_ms == 0) g_ign_since_ms = now;
if (now - g_ign_since_ms < SETTLE_MS) return;
if (g_last_try_ms != 0 && now - g_last_try_ms < RETRY_GAP_MS) return;
if (!DiagProbe::canSendNow()) return;
g_attempts[idx]++;
g_last_try_ms = now;
print("[ecu] reading the DDE identification (1A %02X, try %u of %u)", g_blk[idx].sub,
g_attempts[idx], ATTEMPTS_PER_SUB);
if (DiagProbe::requestIdent(g_blk[idx].sub)) g_waiting = true;
}
// ============================================================================
// PUBLIC API
// ============================================================================
void init() {
load(&g_blk[0]);
load(&g_blk[1]);
DiagProbe::setIdentHandler(onIdent);
g_read_session = !known(); // stored = never ask again
char desc[64];
describe(desc, sizeof(desc));
print("[ecu] %s%s", desc, g_read_session ? " - will read it once the bus is up with the key on" : "");
}
void tick() {
if (g_pending) takePending();
if (g_waiting && millis() - g_last_try_ms > ANSWER_WAIT_MS) g_waiting = false; // no answer: next try later
readTick();
}
bool known() { return g_blk[0].len != 0 || g_blk[1].len != 0; }
bool changed() { return g_changed; }
void describe(char* buf, size_t n) {
if (g_changed) {
char stored[12];
partOf(&g_blk[1], stored, sizeof(stored));
snprintf(buf, n, "ECU CHANGED? bus %s, stored %s", g_bus_part[0] ? g_bus_part : "?", stored[0] ? stored : "?");
return;
}
block_t* p = primary();
if (!p) { snprintf(buf, n, "UNKNOWN ECU"); return; }
describeBlock(p, buf, n);
}
bool hasPart(const char* part) {
if (!part || !part[0]) return false;
if (g_changed) return strcmp(g_bus_part, part) == 0; // the unit actually on the bus
char p[12];
for (int i = 0; i < 2; i++) {
if (!g_blk[i].len) continue;
partOf(&g_blk[i], p, sizeof(p));
if (p[0] && strcmp(p, part) == 0) return true;
}
return false;
}
void forget() {
for (int i = 0; i < 2; i++) {
g_blk[i].len = 0;
save(&g_blk[i]);
g_attempts[i] = 0;
}
g_changed = false;
g_bus_part[0] = 0;
g_gave_up_printed = false;
g_last_try_ms = 0;
g_waiting = false;
g_read_session = true;
print("[ecu] forgotten - UNKNOWN ECU; reading again once the bus is up with the key on");
}
static void show() {
char desc[64];
describe(desc, sizeof(desc));
print("[ecu] %s", desc);
for (int i = 0; i < 2; i++) {
block_t* b = &g_blk[i];
if (!b->len) {
print("[ecu] 1A %02X: not stored%s", b->sub,
g_read_session ? (g_attempts[i] ? " (tried, no answer yet)" : " (will ask)") : "");
continue;
}
char part[12], date[12], vin[12];
partOf(b, part, sizeof(part));
dateOf(b, date, sizeof(date));
vinOf(b, vin, sizeof(vin));
print("[ecu] 1A %02X: %u bytes, part %s, date %s%s%s", b->sub, b->len,
part[0] ? part : "?", date[0] ? date : "?", vin[0] ? ", VIN prefix " : "", vin);
}
print("[ecu] %s", g_read_session ? "read pending: asks once CAN is on, ignition on 5 s, no scan tool"
: "stored: never asked again (`ecu forget` to re-read)");
}
static void dump() {
for (int i = 0; i < 2; i++) {
block_t* b = &g_blk[i];
if (!b->len) { print("[ecu] 1A %02X: empty", b->sub); continue; }
print("[ecu] 1A %02X (%u bytes):", b->sub, b->len);
for (size_t o = 0; o < b->len; o += 16) {
char hx[3 * 16 + 1];
size_t w = 0, k = (b->len - o < 16) ? (b->len - o) : 16;
for (size_t j = 0; j < k; j++) w += snprintf(hx + w, sizeof(hx) - w, "%02X ", b->raw[o + j]);
if (w) hx[w - 1] = 0;
char as[17];
for (size_t j = 0; j < k; j++) as[j] = (b->raw[o + j] >= 0x20 && b->raw[o + j] < 0x7F) ? (char)b->raw[o + j] : '.';
as[k] = 0;
print("[ecu] +%03u %-48s |%s|", (unsigned)o, hx, as);
}
}
}
static void help() {
print("ecu show which engine ECU this board remembers (read once, never re-asked)");
print("ecu dump the stored identification blocks in hex");
print("ecu forget drop them - UNKNOWN ECU until read again (board moved to another car)");
}
bool handleCommand(const char* line) {
if (strncmp(line, "ecu", 3) != 0 || (line[3] != 0 && line[3] != ' ')) return false;
const char* arg = line + 3;
while (*arg == ' ') arg++;
if (*arg == 0 || !strcmp(arg, "show")) { show(); return true; }
if (!strcmp(arg, "dump")) { dump(); return true; }
if (!strcmp(arg, "forget")) { forget(); return true; }
help();
return true;
}
} // namespace EcuIdent
+81
View File
@@ -0,0 +1,81 @@
/*
* ECU Identification Module
*
* Which engine ECU (DDE) is this board bolted to? Read ONCE and remembered.
*
* Two Patrols with "the same" M57N DDE turned out to carry different units
* (part number 7796678 / 2006 vs 7794904 / 2004, captures 2026-10-18), and a
* third setup is coming. The identity is a LABEL - every broadcast frame the
* firmware decodes was identical on both - so it is stored for the record
* (captures, wiki, Settings > Vehicle) and no broadcast decoding depends on it.
* The one exception is the Engine data screen: the KWP `2C` live-data
* identifiers are per DDE software (hasPart() selects its profile).
*
* Rules (user, 2026-10-18):
* - While nothing is stored: read the identification the first time it is
* possible (CAN on, ignition on for a few seconds, no scan tool on the bus,
* not the bench simulation), a few spaced attempts per boot. Until then the
* screen says UNKNOWN ECU.
* - Once stored: NEVER ask again. A board moved to another car keeps the old
* answer until "Re-read ECU" (Settings > Vehicle) or `ecu forget`.
* - Free passive check: a connected Launch re-reads `1A 80` every cycle, and
* we see the DDE's reply without transmitting. If it differs from the stored
* `1A 80` block the screen says ECU CHANGED?.
*
* Two KWP identification blocks are kept, each as its raw payload (NVS blobs
* `ecu_id86`, `ecu_id80` in the "settings" namespace):
* `1A 86` - 65 bytes on Patrol 1 (verified 2026-09-23 from this board): ASCII
* "@B892524 " (bytes 2-10), BCD date YY MM DD at bytes 11-13, three
* BCD part numbers from byte 16 (7799764 / 7799765 / 7793887, six
* bytes each), VIN prefix "WBANC92090" at bytes 53-62. Tried first
* because this board's own `1A 80` went unanswered that day.
* `1A 80` - what the Launch asks (answered on both Patrols, 31 / 37 bytes):
* BCD part number at bytes 4-7, BCD date YY MM DD at bytes 15-17.
* Second in the sequence; also what the passive check compares.
* Field offsets are the ones observed on these two DDEs (wiki vehicles page);
* a block that does not fit them is still stored and shown by length.
*
* Transmits through DiagProbe only (its guards: one request in flight, single
* shot, refused for 3 s after any foreign tester frame).
*/
#pragma once
#include <Arduino.h>
namespace EcuIdent {
/** Load the stored blocks and hook DiagProbe. Call after DiagProbe::init(). */
void init();
/** One-shot read sequencing and the deferred NVS write. Call from loop(). */
void tick();
/** At least one identification block is stored. */
bool known();
/** A `1A 80` block seen on the bus (another tester's read) differs from the stored one. */
bool changed();
/**
* One line for the screens: "DDE 7799764 - 2006-03-07", "UNKNOWN ECU",
* "ECU CHANGED? bus 7796678, stored 7794904", ...
*/
void describe(char* buf, size_t n);
/**
* The ECU in front of us carries this part number: the differing `1A 80` block
* seen on the bus when changed() is set, otherwise any stored block's number
* ("7796678", "7799764", ...). The Engine data screen keys its per-DDE
* live-data identifiers on it - the one place behaviour follows the label,
* because the `2C` identifiers are addresses inside each DDE's own software.
*/
bool hasPart(const char* part);
/** Drop the stored blocks; UNKNOWN ECU until the next successful read. */
void forget();
/** `ecu show | dump | forget`. */
bool handleCommand(const char* line);
} // namespace EcuIdent
+258
View File
@@ -0,0 +1,258 @@
/*
* Engine Data Screen Module Implementation - see engine_screen.h
*/
#include "engine_screen.h"
#include "ui_kit.h"
#include "diag_probe.h"
#include "ecu_ident.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;
} channel_t;
static const channel_t CHANNELS[DiagProbe::LIVE_COUNT] = {
// verified 2026-09-23 against the Launch at two operating points (Patrol 1)
{DiagProbe::LIVE_RAIL, "Rail pressure", "bar", 0.03f, 0.0f, 1},
// 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},
// 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},
// 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},
};
// ============================================================================
// PER-DDE PROFILES
// ============================================================================
//
// The `2C 10 <id>` identifiers are addresses inside each DDE's own software:
// Patrol 1's set, asked on Patrol 2's unit, returned a refused rail read, a
// flat "2800 mbar" boost and a ">300 C" air temperature (user, 2026-10-18).
// The Launch itself reads `1A 80` every cycle to choose its data set, and on
// Patrol 2 it polled `00C2` for rail pressure. So the identifiers follow the
// ECU identity (`EcuIdent`): the first profile whose part number the stored
// identification carries wins. A slot with identifier 0 is never requested and
// its card says so. No identified ECU, or an ECU with no profile = no polling.
//
// Adding a car: capture the Launch on each value (wiki obd-diagnostic-polling,
// "decode recipe"), then add a row - part numbers from `ecu show`.
typedef struct {
const char* name; // for the status line
const char* parts[4]; // any part number (1A 80 or 1A 86) of this DDE, NULL-terminated
DiagProbe::live_set_t set; // define id + one identifier per live_id_t slot (0 = unknown)
uint8_t provisional_mask; // bit per slot: scaling fitted to a single Launch reading
} profile_t;
static const profile_t PROFILES[] = {
// Patrol 1: DDE 7796678 (1A 80, 2006-02) / 7799764, 7799765, 7793887 (1A 86, 2006-03)
{"DDE 7796678 (Patrol 1)", {"7796678", "7799764", "7799765", "7793887"},
{0x15E0, {0x00DF, 0x0091, 0x16A8, 0x0093}},
(1 << DiagProbe::LIVE_BOOST) | (1 << DiagProbe::LIVE_AIR_TEMP) | (1 << DiagProbe::LIVE_BATTERY)},
// Patrol 2: DDE 7794904 (1A 80, 2004-01) = 7796156 / 7796157 / 7789877
// (1A 86, 2006-05-17, VIN prefix WBAGM21070 = E65 7-series; both blocks
// read by this board on 2026-10-18, `ecu dump` in the wiki). Every
// identifier differs from Patrol 1's, the scalings look the same: rail
// `00C2` (~330 bar at idle), boost `003A` (1018 mbar idle, 1186 on a blip),
// battery `002F` (14.0 V running, 12.7 V engine off) - all from Launch
// captures on 2026-10-18 without the Launch's own readings noted, so all
// provisional. No define seen. Charge-air temperature: not captured yet.
{"DDE 7794904 (Patrol 2)", {"7794904", "7796156", "7796157", "7789877"},
{0, {0x00C2, 0x003A, 0, 0x002F}},
(1 << DiagProbe::LIVE_RAIL) | (1 << DiagProbe::LIVE_BOOST) | (1 << DiagProbe::LIVE_BATTERY)},
};
static const int PROFILE_COUNT = sizeof(PROFILES) / sizeof(PROFILES[0]);
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 lv_obj_t* g_tag[DiagProbe::LIVE_COUNT];
static const profile_t* g_profile = NULL; // the one in use (NULL = none)
static bool g_profile_known = false; // g_profile has been evaluated at least once
/** The profile for the identified ECU, NULL when unknown or not in the table. */
static const profile_t* findProfile() {
if (!EcuIdent::known()) return NULL;
for (int i = 0; i < PROFILE_COUNT; i++)
for (int k = 0; k < 4 && PROFILES[i].parts[k]; k++)
if (EcuIdent::hasPart(PROFILES[i].parts[k])) return &PROFILES[i];
return NULL;
}
/** Re-evaluate the profile; install its identifier set on change. */
static void applyProfile() {
const profile_t* p = findProfile();
if (g_profile_known && p == g_profile) return;
g_profile_known = true;
g_profile = p;
DiagProbe::liveConfigure(p ? &p->set : NULL);
if (!p) DiagProbe::liveStop();
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
if (!g_tag[i]) continue;
bool prov = p && (p->provisional_mask & (1 << i));
if (prov) lv_obj_clear_flag(g_tag[i], LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_tag[i], LV_OBJ_FLAG_HIDDEN);
}
}
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);
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_add_flag(tag, LV_OBJ_FLAG_HIDDEN); // shown per profile
g_tag[i] = tag;
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() {
char st[160];
lv_color_t col = UI_COL_MUTED;
if (!g_profile) {
if (!EcuIdent::known()) {
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " Engine ECU not identified yet - no live data until it is read (key on, see Settings > Vehicle)");
} else {
char ecu[64];
EcuIdent::describe(ecu, sizeof(ecu));
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " %s - no live-data identifiers known for this ECU yet (capture it with the Launch)", ecu);
}
col = UI_COL_AMBER;
} else {
switch (DiagProbe::liveState()) {
case DiagProbe::LIVE_RUNNING:
snprintf(st, sizeof(st), LV_SYMBOL_OK " Live from the engine ECU, %s", g_profile->name); col = UI_COL_OK; break;
case DiagProbe::LIVE_PAUSED_TESTER:
snprintf(st, sizeof(st), LV_SYMBOL_PAUSE " Paused: another diagnostic tester is connected (e.g. the Launch)"); col = UI_COL_AMBER; break;
case DiagProbe::LIVE_CAN_OFF:
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System"); col = UI_COL_WARN; break;
case DiagProbe::LIVE_NO_ANSWER:
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " No answer from the engine ECU - is the ignition on?"); col = UI_COL_WARN; break;
default:
snprintf(st, sizeof(st), "Starting..."); break;
}
}
setText(g_status, st);
setTextColor(g_status, col);
char buf[64];
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
const channel_t& ch = CHANNELS[i];
uint16_t vid = g_profile ? g_profile->set.ids[ch.id] : 0;
if (vid == 0) {
setText(g_value[i], "--");
setText(g_raw[i], g_profile ? "identifier not known for this ECU yet" : "no ECU profile");
continue;
}
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) id %04X", v.raw, v.raw, vid);
} else {
setText(g_value[i], "--");
if (v.nrc) snprintf(buf, sizeof(buf), "refused by the ECU (NRC 0x%02X) id %04X", v.nrc, vid);
else if (v.valid) snprintf(buf, sizeof(buf), "raw %u (stale) id %04X", v.raw, vid);
else snprintf(buf, sizeof(buf), "raw -- id %04X", vid);
}
setText(g_raw[i], buf);
}
}
void show() {
build();
applyProfile();
if (g_profile) 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;
static uint32_t last = 0;
if (millis() - last < 250) return;
last = millis();
lvgl_port_lock(-1);
applyProfile(); // the ECU may get identified while we watch
if (g_profile) DiagProbe::liveKeepAlive(); // polling stops ~1.5 s after the screen is left
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
+1 -1
View File
@@ -1,5 +1,5 @@
/* /*
* ESP-NOW Link Module Implementation (Controller A, transmit only) * ESP-NOW Link Module Implementation (Main CTRL, transmit only)
*/ */
#include "espnow_link.h" #include "espnow_link.h"
+1 -1
View File
@@ -1,5 +1,5 @@
/* /*
* ESP-NOW Link Module (Controller A side) * ESP-NOW Link Module (Main CTRL side)
* *
* Second transport for the A -> B link: every frame the UART manager builds * Second transport for the A -> B link: every frame the UART manager builds
* is also broadcast over ESP-NOW, so B keeps receiving if the wire is lost. * is also broadcast over ESP-NOW, so B keeps receiving if the wire is lost.
+21 -21
View File
@@ -1,5 +1,5 @@
/* /*
* Link Peer Module Implementation (Controller A) * Link Peer Module Implementation (Main CTRL)
* *
* Threading: onFrame() runs in the Wi-Fi task and only copies the STATUS into * Threading: onFrame() runs in the Wi-Fi task and only copies the STATUS into
* g_peer under a mutex. Everything else (NVS, sending, console) is the loop task. * g_peer under a mutex. Everything else (NVS, sending, console) is the loop task.
@@ -129,9 +129,9 @@ peer_status_t getStatus() {
// ---- outbound --------------------------------------------------------------- // ---- outbound ---------------------------------------------------------------
static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) { static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) {
peer_status_t p = getStatus(); peer_status_t p = getStatus();
if (!p.heard) { snprintf(why, n, "Controller B not heard"); return false; } if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard"); return false; }
if (!p.paired) { snprintf(why, n, "not paired - run `link pair` with the wire connected"); return false; } if (!p.paired) { snprintf(why, n, "not paired - run `link pair` with the wire connected"); return false; }
if (!p.key_match) { snprintf(why, n, "Controller B holds a different key - run `link pair` again"); return false; } if (!p.key_match) { snprintf(why, n, "Inst. Cluster holds a different key - run `link pair` again"); return false; }
uint8_t payload[PACKET_MAX_PAYLOAD], frame[PACKET_MAX_SIZE]; uint8_t payload[PACKET_MAX_PAYLOAD], frame[PACKET_MAX_SIZE];
size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload); size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload);
@@ -175,8 +175,8 @@ static bool pushCredentials(char* why, size_t n, bool log) {
if (ok) { if (ok) {
g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1; g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1;
g_last_push_ms = millis(); g_last_push_ms = millis();
if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Controller B (encrypted)" if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Inst. Cluster (encrypted)"
: "[link] told Controller B to forget its Wi-Fi credentials", c.ssid); : "[link] told Inst. Cluster to forget its Wi-Fi credentials", c.ssid);
} }
memset(&c, 0, sizeof(c)); memset(&c, 0, sizeof(c));
return ok; return ok;
@@ -204,7 +204,7 @@ static void syncCredentials() {
// ---- pairing ---------------------------------------------------------------- // ---- pairing ----------------------------------------------------------------
static bool pair(char* why, size_t n) { static bool pair(char* why, size_t n) {
if (UARTManager::getState() == UARTManager::UART_STATE_OFF) { if (UARTManager::getState() == UARTManager::UART_STATE_OFF) {
snprintf(why, n, "link is off - enable 'Send to Controller B' in Settings first"); snprintf(why, n, "link is off - enable 'Send to Inst. Cluster' in Settings first");
return false; return false;
} }
link_pair_t pk = {}; link_pair_t pk = {};
@@ -229,31 +229,31 @@ static bool pair(char* why, size_t n) {
g_pushed_hash = 0; // re-send the credentials under the new key g_pushed_hash = 0; // re-send the credentials under the new key
g_last_push_ms = 0; g_last_push_ms = 0;
print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. " print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. "
"Controller B confirms in its next STATUS (`link status`).", sent, g_key_fp); "Inst. Cluster confirms in its next STATUS (`link status`).", sent, g_key_fp);
return true; return true;
} }
// ---- public: requests (UI) -------------------------------------------------- // ---- public: requests (UI) --------------------------------------------------
static bool bReady(char* why, size_t n, bool need_parked) { static bool bReady(char* why, size_t n, bool need_parked) {
peer_status_t p = getStatus(); peer_status_t p = getStatus();
if (!p.heard) { snprintf(why, n, "Controller B not heard - is it powered?"); return false; } if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard - is it powered?"); return false; }
if (!p.paired || !p.key_match) { if (!p.paired || !p.key_match) {
snprintf(why, n, "Controller B is not paired with this controller (console: link pair, wire connected)"); snprintf(why, n, "Inst. Cluster is not paired with this controller (console: link pair, wire connected)");
return false; return false;
} }
if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) { if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) {
snprintf(why, n, "Controller B has no Wi-Fi credentials yet - join a network on this screen first"); snprintf(why, n, "Inst. Cluster has no Wi-Fi credentials yet - join a network on this screen first");
return false; return false;
} }
if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) { if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) {
snprintf(why, n, "Controller B is busy (%s)", phaseName(p.st.ota_phase)); snprintf(why, n, "Inst. Cluster is busy (%s)", phaseName(p.st.ota_phase));
return false; return false;
} }
if (need_parked && !Ota::isParked(why, n)) return false; if (need_parked && !Ota::isParked(why, n)) return false;
// Same network as B => same radio channel, so B's STATUS frames (progress) // Same network as B => same radio channel, so B's STATUS frames (progress)
// keep reaching this screen while B is joined. // keep reaching this screen while B is joined.
if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) { if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) {
snprintf(why, n, "join Wi-Fi on this controller first, so Controller B's progress can be followed"); snprintf(why, n, "join Wi-Fi on this controller first, so Inst. Cluster's progress can be followed");
return false; return false;
} }
return true; return true;
@@ -274,7 +274,7 @@ void init() {
if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex(); if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex();
loadKey(); loadKey();
EspNowLink::setReceiveHandler(onFrame); EspNowLink::setReceiveHandler(onFrame);
print("[link] Controller B: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected"); print("[link] Inst. Cluster: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected");
} }
void tick() { void tick() {
@@ -288,18 +288,18 @@ void tick() {
peer_status_t p = getStatus(); peer_status_t p = getStatus();
if (p.heard != was_heard) { if (p.heard != was_heard) {
was_heard = p.heard; was_heard = p.heard;
if (p.heard) print("[link] Controller B heard: %s, %s, %lu s up", p.st.version, if (p.heard) print("[link] Inst. Cluster heard: %s, %s, %lu s up", p.st.version,
p.key_match ? "paired" : (p.st.key_fp ? "paired with ANOTHER key" : "unpaired"), p.key_match ? "paired" : (p.st.key_fp ? "paired with ANOTHER key" : "unpaired"),
(unsigned long)p.st.uptime_s); (unsigned long)p.st.uptime_s);
else print("[link] Controller B silent for %lu s", (unsigned long)(p.age_ms / 1000)); else print("[link] Inst. Cluster silent for %lu s", (unsigned long)(p.age_ms / 1000));
} }
if (p.heard && p.key_match && !was_match) { if (p.heard && p.key_match && !was_match) {
print("[link] Controller B confirmed pairing (fingerprint %04X)", p.st.key_fp); print("[link] Inst. Cluster confirmed pairing (fingerprint %04X)", p.st.key_fp);
} }
was_match = p.heard && p.key_match; was_match = p.heard && p.key_match;
if (p.heard && p.st.ota_phase != last_phase) { if (p.heard && p.st.ota_phase != last_phase) {
if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE) if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE)
print("[link] Controller B update: %s%s%s%s%s", phaseName(p.st.ota_phase), print("[link] Inst. Cluster update: %s%s%s%s%s", phaseName(p.st.ota_phase),
p.st.latest[0] ? ", latest " : "", p.st.latest, p.st.latest[0] ? ", latest " : "", p.st.latest,
p.st.ota_phase == LINK_OTA_FAILED ? " - " : "", p.st.ota_phase == LINK_OTA_FAILED ? " - " : "",
p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : ""); p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : "");
@@ -310,7 +310,7 @@ void tick() {
// ---- console ---------------------------------------------------------------- // ---- console ----------------------------------------------------------------
static void help() { static void help() {
print("link status Controller B: version, pairing, update phase"); print("link status Inst. Cluster: version, pairing, update phase");
print("link pair new shared key -> B over the UART wire (bench, wire connected)"); print("link pair new shared key -> B over the UART wire (bench, wire connected)");
print("link unpair forget the key here (B keeps its own until re-paired)"); print("link unpair forget the key here (B keeps its own until re-paired)");
print("link creds send the remembered Wi-Fi network to B now"); print("link creds send the remembered Wi-Fi network to B now");
@@ -329,8 +329,8 @@ bool handleCommand(const char* line) {
print("[link] this side: %s (fingerprint %04X) | STATUS frames %lu | SECURE sent %lu, failed %lu", print("[link] this side: %s (fingerprint %04X) | STATUS frames %lu | SECURE sent %lu, failed %lu",
p.paired ? "paired" : "NOT paired", p.key_fp, (unsigned long)g_status_count, p.paired ? "paired" : "NOT paired", p.key_fp, (unsigned long)g_status_count,
(unsigned long)g_secure_sent, (unsigned long)g_secure_fail); (unsigned long)g_secure_sent, (unsigned long)g_secure_fail);
if (!g_ever_heard) { print("[link] Controller B never heard"); return true; } if (!g_ever_heard) { print("[link] Inst. Cluster never heard"); return true; }
print("[link] Controller B %02X:%02X:%02X:%02X:%02X:%02X, %s (%lu s ago)", print("[link] Inst. Cluster %02X:%02X:%02X:%02X:%02X:%02X, %s (%lu s ago)",
p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5], p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5],
p.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000)); p.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000));
print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s", print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s",
@@ -360,7 +360,7 @@ bool handleCommand(const char* line) {
else if (!strcmp(b, "install force")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_INSTALL, LINK_OTA_FORCE, why, sizeof(why)); else if (!strcmp(b, "install force")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_INSTALL, LINK_OTA_FORCE, why, sizeof(why));
else if (!strcmp(b, "rollback")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_ROLLBACK, 0, why, sizeof(why)); else if (!strcmp(b, "rollback")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_ROLLBACK, 0, why, sizeof(why));
else { help(); return true; } else { help(); return true; }
print(ok ? "[link] command sent to Controller B - watch `link status`" : "[link] refused: %s", why); print(ok ? "[link] command sent to Inst. Cluster - watch `link status`" : "[link] refused: %s", why);
return true; return true;
} }
help(); help();
+2 -2
View File
@@ -1,10 +1,10 @@
/* /*
* Link Peer Module (Controller A) - what A knows about Controller B, and the * Link Peer Module (Main CTRL) - what A knows about Inst. Cluster, and the
* maintenance traffic that keeps B updatable. See * maintenance traffic that keeps B updatable. See
* ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md (B's wiki). * ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md (B's wiki).
* *
* STATUS B -> A ESP-NOW unicast every 5 s: B's version, OTA phase, uptime. * STATUS B -> A ESP-NOW unicast every 5 s: B's version, OTA phase, uptime.
* Shown on Settings -> Updates as the "Controller B" card. * Shown on Settings -> Updates as the "Inst. Cluster" card.
* PAIR A -> B `link pair` on the console, UART WIRE ONLY: a fresh random * PAIR A -> B `link pair` on the console, UART WIRE ONLY: a fresh random
* key, kept in NVS on both sides. Both repos are public, so * key, kept in NVS on both sides. Both repos are public, so
* this is the only secret and it never travels by radio. * this is the only secret and it never travels by radio.
+1 -1
View File
@@ -144,7 +144,7 @@ static const char* stateName(esp_ota_img_states_t s) {
/** /**
* The vehicle must be parked to update: installing ends in a reboot that blanks * The vehicle must be parked to update: installing ends in a reboot that blanks
* Controller B's gauges. A silent bus (ignition off, or the bench) counts as * Inst. Cluster's gauges. A silent bus (ignition off, or the bench) counts as
* parked. Lever UNKNOWN is allowed so a missing gear frame can't block a bench * parked. Lever UNKNOWN is allowed so a missing gear frame can't block a bench
* update; engine and output shaft are the checks that matter. * update; engine and output shaft are the checks that matter.
*/ */
+2 -2
View File
@@ -20,7 +20,7 @@
* or crash before that makes the bootloader fall back to the old slot. * or crash before that makes the bootloader fall back to the old slot.
* *
* Needs Wi-Fi joined to a network with internet (Settings screen). Joining an * Needs Wi-Fi joined to a network with internet (Settings screen). Joining an
* AP moves the radio channel; the ESP-NOW link to Controller B follows it. * AP moves the radio channel; the ESP-NOW link to Inst. Cluster follows it.
* See wiki/pages/ota-updates.md. * See wiki/pages/ota-updates.md.
*/ */
@@ -66,7 +66,7 @@ ui_status_t getStatus();
bool requestCheck(char* why, size_t n); bool requestCheck(char* why, size_t n);
bool requestInstall(char* why, size_t n); bool requestInstall(char* why, size_t n);
/** The parking gate on its own (Controller B's install is guarded by it too). */ /** The parking gate on its own (Inst. Cluster's install is guarded by it too). */
bool isParked(char* why, size_t n); bool isParked(char* why, size_t n);
} // namespace Ota } // namespace Ota
+151
View File
@@ -0,0 +1,151 @@
/*
* Reverse lights on DO0 - see reverse_light.h
*/
#include "reverse_light.h"
#include "settings_manager.h"
#include "drivers/can_driver.h"
#include "display/lvgl_v8_port.h"
#include "serial_lock.h"
#include <esp_display_panel.hpp>
#include <stdarg.h>
namespace ReverseLight {
// CH422G pins in the ESP32_IO_Expander numbering: IO0-7 = 0-7, OC0-3 = 8-11.
// OC0 is OD0 on the schematic -> PC817 T1 -> power transistor T2 -> DOUT0.
static const uint8_t OC0_PIN = 8;
static const uint32_t POLL_MS = 100;
static const uint8_t CONFIRM = 2; // equal decisions before the output moves (200 ms)
static const uint8_t FAULT_AFTER = 3; // failed writes in a row before we say so
static const uint32_t FORCE_MAX_MS = 60000; // a forgotten `reverse force on` ends itself
enum force_t : uint8_t { FORCE_AUTO = 0, FORCE_ON, FORCE_OFF };
static esp_expander::Base* g_expander = nullptr;
static bool g_enabled = true;
static force_t g_force = FORCE_AUTO;
static uint32_t g_force_since = 0;
static bool g_output = false; // what the chip was last told successfully
static bool g_output_known = false; // false until the first successful write
static bool g_decided = false; // the current (confirmed) decision
static bool g_candidate = false; // the decision being confirmed
static uint8_t g_candidate_ticks = 0;
static uint8_t g_fail_run = 0;
static uint32_t g_writes = 0, g_fails = 0, g_switches = 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();
}
/** One write to OC0. OC0 LOW lights the opto LED, which turns the output on. */
static bool drive(bool on) {
if (g_expander == nullptr) return false;
if (!lvgl_port_lock(100)) return false; // UI busy: retried next tick
bool ok = g_expander->digitalWrite(OC0_PIN, on ? 0 : 1);
lvgl_port_unlock();
g_writes++;
if (!ok) {
g_fails++;
if (g_fail_run < 255) g_fail_run++;
if (g_fail_run == FAULT_AFTER) print("[reverse] CH422G write failing - DO0 state unknown");
return false;
}
if (g_fail_run >= FAULT_AFTER) print("[reverse] CH422G writes OK again");
g_fail_run = 0;
g_output = on;
g_output_known = true;
return true;
}
void init(bool enabled, esp_expander::Base* expander) {
g_enabled = enabled;
g_expander = expander;
if (g_expander == nullptr) {
print("[reverse] no IO expander - DO0 cannot be driven");
return;
}
drive(false); // known state, whatever the chip held before this boot
print("[reverse] %s (DO0 follows the lever in R)%s", enabled ? "ON" : "OFF - 'reverse on' to enable",
g_output_known ? "" : " - first write failed, will retry");
}
void setEnabled(bool enabled) {
if (enabled == g_enabled) return;
g_enabled = enabled;
SettingsManager::saveReverseLightState(enabled);
}
bool isEnabled() { return g_enabled; }
bool isOn() { return g_output_known && g_output; }
/** The lights should be on: lever in R, on a live bus, key on. */
static bool wanted() {
if (g_force == FORCE_ON) return true;
if (g_force == FORCE_OFF) return false;
if (!g_enabled || !CANDriver::isActive()) return false;
driveline_t dl = CANDriver::getDriveline(); // cleared by the driver after 2 s of silence
return dl.ignition_on && dl.lever == GEAR_REVERSE;
}
void tick() {
if (millis() - g_last_poll < POLL_MS) return;
g_last_poll = millis();
if (g_force != FORCE_AUTO && millis() - g_force_since > FORCE_MAX_MS) {
g_force = FORCE_AUTO;
print("[reverse] force ended after 60 s - back to the lever");
}
bool want = wanted();
if (want != g_candidate) {
g_candidate = want;
g_candidate_ticks = 0;
}
if (g_candidate_ticks < 255) g_candidate_ticks++;
if (g_candidate_ticks >= CONFIRM && want != g_decided) {
g_decided = want;
g_switches++;
print("[reverse] lights %s (%s)", want ? "ON" : "off",
g_force == FORCE_ON ? "forced" : g_force == FORCE_OFF ? "forced off" : want ? "lever R" : "lever left R");
}
// Apply when the chip disagrees with the decision; a failed write is retried every tick.
if (!g_output_known || g_output != g_decided) drive(g_decided);
}
bool handleCommand(const char* line) {
if (strncmp(line, "reverse", 7) != 0 || (line[7] != 0 && line[7] != ' ')) return false;
const char* a = line + 7;
while (*a == ' ') a++;
if (!strcmp(a, "on")) { setEnabled(true); print("[reverse] ON (saved)"); return true; }
if (!strcmp(a, "off")) { setEnabled(false); print("[reverse] OFF (saved) - DO0 stays off"); return true; }
if (!strcmp(a, "force on")) { g_force = FORCE_ON; g_force_since = millis(); print("[reverse] FORCED ON for up to 60 s (not saved)"); return true; }
if (!strcmp(a, "force off")) { g_force = FORCE_OFF; g_force_since = millis(); print("[reverse] FORCED OFF for up to 60 s (not saved)"); return true; }
if (!strcmp(a, "force auto")) { g_force = FORCE_AUTO; print("[reverse] back to the lever"); return true; }
if (!*a || !strcmp(a, "status")) {
driveline_t dl = CANDriver::getDriveline();
print("[reverse] %s | DO0 %s | lever %c, ignition %s, CAN %s | force %s | %lu writes, %lu failed, %lu switches%s",
g_enabled ? "enabled" : "DISABLED",
!g_output_known ? "unknown" : g_output ? "ON (relay energised)" : "off",
gear_lever_char(dl.lever), dl.ignition_on ? "on" : "off", CANDriver::isActive() ? "on" : "off",
g_force == FORCE_ON ? "ON" : g_force == FORCE_OFF ? "OFF" : "auto",
(unsigned long)g_writes, (unsigned long)g_fails, (unsigned long)g_switches,
g_fail_run >= FAULT_AFTER ? " | WRITE FAULT" : "");
return true;
}
print("[reverse] usage: reverse status | on | off | force on|off|auto (DO0 = reverse-light relay)");
return true;
}
} // namespace ReverseLight
+50
View File
@@ -0,0 +1,50 @@
/*
* Reverse lights - the isolated output DO0 follows the gear lever in R
*
* The Patrol's reverse lamps are switched by a 12 V relay whose coil hangs
* between +12 V and the board's DO0 terminal (flyback diode across the coil).
* DO0 is the collector of an NPN power transistor (450 mA sink, emitter on the
* board's GND) driven through a PC817 optocoupler from the CH422G's OC0 pin
* (schematic: OC0 -> R24 100R -> PC817 LED, anode 510R to 3V3; so OC0 LOW =
* LED on = transistor on = relay on). The CH422G comes up with OC0 high and
* the panel library rewrites that default at every display init, so the
* lights are off from reset until this module says otherwise.
*
* Decision, every 100 ms: lever == R (0x1D2 byte 0) with CAN running and the
* ignition on - the same snapshot the Driveline screen shows, so the lights
* never disagree with the big letter. The CAN driver forgets the lever after
* 2 s of bus silence and on key-off, which turns the lights off as well. A
* change is applied after two equal decisions (200 ms) so a one-frame glitch
* cannot chatter the relay. `reverse force on|off` overrides for wiring tests
* (never saved, back to auto after 60 s or `reverse force auto`).
*
* The output is written through the panel library's expander object (not raw
* I2C like the diff-lock reads) so the library's cached OC register stays
* right: the backlight writes that cache back to the chip on every on/off.
*/
#pragma once
#include <Arduino.h>
namespace esp_expander { class Base; }
namespace ReverseLight {
/** Call once after DisplayInit (the expander belongs to the panel library). Drives DO0 off. */
void init(bool enabled, esp_expander::Base* expander);
/** `reverse on|off`, saved to NVS (SettingsManager). Default ON. */
void setEnabled(bool enabled);
bool isEnabled();
/** Decide + drive DO0 (10 Hz, two equal decisions before a change). Call from loop(). */
void tick();
/** What DO0 is being driven to right now (true = relay on). */
bool isOn();
/** `reverse status | on | off | force on|off|auto`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace ReverseLight
+45
View File
@@ -19,6 +19,9 @@ static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
static const char* NVS_KEY_UART_ENABLED = "uart_en"; static const char* NVS_KEY_UART_ENABLED = "uart_en";
static const char* NVS_KEY_DEBUG_ENABLED = "debug_en"; static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
static const char* NVS_KEY_CAN_ENABLED = "can_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";
static const char* NVS_KEY_REVLIGHT_ENABLED = "revlight_en";
// ============================================================================ // ============================================================================
// PUBLIC API IMPLEMENTATION // PUBLIC API IMPLEMENTATION
@@ -89,4 +92,46 @@ bool loadCANState() {
return enabled; 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;
}
void saveReverseLightState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_REVLIGHT_ENABLED, enabled);
preferences.end();
Serial.printf("[SettingsManager] Saved ReverseLight state = %s\n", enabled ? "ON" : "OFF");
}
bool loadReverseLightState() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool enabled = preferences.getBool(NVS_KEY_REVLIGHT_ENABLED, true); // default: ON (an unwired DO0 is harmless)
preferences.end();
return enabled;
}
} // namespace SettingsManager } // namespace SettingsManager
+12
View File
@@ -66,4 +66,16 @@ void saveCANState(bool enabled);
*/ */
bool loadCANState(); 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();
/** Reverse-light relay on DO0 follows the lever in R (ReverseLight). Default ON. */
void saveReverseLightState(bool enabled);
bool loadReverseLightState();
} // namespace SettingsManager } // namespace SettingsManager
+250 -27
View File
@@ -8,6 +8,10 @@
#include "wifi_manager.h" #include "wifi_manager.h"
#include "ota_update.h" #include "ota_update.h"
#include "link_peer.h" #include "link_peer.h"
#include "diff_locks.h"
#include "vehicle.h"
#include "ecu_ident.h"
#include "bench_sim.h"
#include "uart_manager.h" #include "uart_manager.h"
#include "espnow_link.h" #include "espnow_link.h"
#include "settings_manager.h" #include "settings_manager.h"
@@ -30,7 +34,7 @@ static const lv_coord_t NAV_X = 16, NAV_W = 240, NAV_H = 100;
static const lv_coord_t TOP_Y = 88; static const lv_coord_t TOP_Y = 88;
static const lv_coord_t PAGE_X = 272, PAGE_W = 736, PAGE_H = 600 - TOP_Y - 28; // version label below static const lv_coord_t PAGE_X = 272, PAGE_W = 736, PAGE_H = 600 - TOP_Y - 28; // version label below
typedef enum { PAGE_WIFI, PAGE_UPDATES, PAGE_SYSTEM, PAGE_COUNT } page_t; typedef enum { PAGE_WIFI, PAGE_UPDATES, PAGE_SYSTEM, PAGE_VEHICLE, PAGE_COUNT } page_t;
// ============================================================================ // ============================================================================
// MODULE STATE // MODULE STATE
@@ -82,8 +86,19 @@ 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_can = NULL;
static lv_obj_t* g_sys_link = NULL; static lv_obj_t* g_sys_link = NULL;
static lv_obj_t* g_sys_dbg = 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 lv_obj_t* g_sys_info = NULL; // values column; keys are static
// Vehicle page
static lv_obj_t* g_veh_final_lbl = NULL;
static lv_obj_t* g_veh_tyre_lbl = NULL;
static lv_obj_t* g_veh_live = NULL;
static lv_obj_t* g_veh_ecu = NULL; // "Engine ECU: DDE 7799764 - 2006-03-07" / UNKNOWN ECU / ECU CHANGED?
static lv_obj_t* g_veh_save = NULL;
static uint16_t g_repeats = 0; // long-press repeat count of the -/+ button being held
static void refresh(bool force); static void refresh(bool force);
// ============================================================================ // ============================================================================
@@ -108,6 +123,7 @@ static void onNav(lv_event_t* e) {
static void onBack(lv_event_t* e) { static void onBack(lv_event_t* e) {
(void)e; (void)e;
Vehicle::flush(); // write pending Vehicle edits now rather than after the idle delay
DrivelineScreen::show(); DrivelineScreen::show();
} }
@@ -116,6 +132,7 @@ static void onGesture(lv_event_t* e) {
if (g_pw && !lv_obj_has_flag(g_pw, LV_OBJ_FLAG_HIDDEN)) return; // typing a password if (g_pw && !lv_obj_has_flag(g_pw, LV_OBJ_FLAG_HIDDEN)) return; // typing a password
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) { if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act()); lv_indev_wait_release(lv_indev_get_act());
Vehicle::flush();
DrivelineScreen::show(); DrivelineScreen::show();
} }
} }
@@ -208,7 +225,7 @@ static void onForget(lv_event_t* e) {
(void)e; (void)e;
WiFiManager::status_t s = WiFiManager::getStatus(); WiFiManager::status_t s = WiFiManager::getStatus();
char text[128]; char text[128];
snprintf(text, sizeof(text), "Controller A will no longer join \"%s\" by itself.", s.saved_ssid); snprintf(text, sizeof(text), "Main CTRL will no longer join \"%s\" by itself.", s.saved_ssid);
confirm("Forget this network?", text, "Forget", onForgetConfirmed, NULL); confirm("Forget this network?", text, "Forget", onForgetConfirmed, NULL);
} }
@@ -403,7 +420,7 @@ static void buildWifiPage(lv_obj_t* page) {
g_wifi_off_note = label(page, g_wifi_off_note = label(page,
"Wi-Fi is off.\n\nTurn it on to join a network for firmware updates. " "Wi-Fi is off.\n\nTurn it on to join a network for firmware updates. "
"The link to Controller B works without it.", "The link to Inst. Cluster works without it.",
&lv_font_montserrat_20, UI_COL_MUTED); &lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(g_wifi_off_note, LV_LABEL_LONG_WRAP); lv_label_set_long_mode(g_wifi_off_note, LV_LABEL_LONG_WRAP);
lv_obj_set_width(g_wifi_off_note, LV_PCT(100)); lv_obj_set_width(g_wifi_off_note, LV_PCT(100));
@@ -511,7 +528,7 @@ static void buildPasswordOverlay() {
} }
// ============================================================================ // ============================================================================
// UPDATES PAGE - Controller A (this board) and Controller B (over the link) // UPDATES PAGE - Main CTRL (this board) and Inst. Cluster (over the link)
// ============================================================================ // ============================================================================
static lv_obj_t* g_b_installed = NULL; static lv_obj_t* g_b_installed = NULL;
@@ -537,9 +554,8 @@ static void onInstall(lv_event_t* e) {
char title[64]; char title[64];
snprintf(title, sizeof(title), "Install %s?", o.latest); snprintf(title, sizeof(title), "Install %s?", o.latest);
confirm(title, confirm(title,
"A progress bar shows while the new firmware downloads (about a minute), " "This Controller will restart after successful update.\n\nInstrument Cluster's gauges will drop out for a few seconds.\n\n"
"then Controller A restarts. Controller B's gauges drop out for a few seconds.\n\n" "DO NOT SWITCH OFF THE IGNITION!\n\nOnly while parked with the engine off!",
"Do not switch off the ignition until it has restarted. Only while parked with the engine off.",
"Install", onInstallConfirmed, NULL); "Install", onInstallConfirmed, NULL);
} }
@@ -569,9 +585,9 @@ static void onBInstall(lv_event_t* e) {
(void)e; (void)e;
LinkPeer::peer_status_t p = LinkPeer::getStatus(); LinkPeer::peer_status_t p = LinkPeer::getStatus();
char title[64]; char title[64];
snprintf(title, sizeof(title), "Install %s on Controller B?", p.st.latest); snprintf(title, sizeof(title), "Install %s on Inst. Cluster?", p.st.latest);
confirm(title, confirm(title,
"Controller B joins the Wi-Fi network, downloads its new firmware and restarts; " "Inst. Cluster joins the Wi-Fi network, downloads its new firmware and restarts; "
"its gauges hold still meanwhile and this card shows the progress.\n\n" "its gauges hold still meanwhile and this card shows the progress.\n\n"
"Only while parked with the engine off.", "Only while parked with the engine off.",
"Install", onBInstallConfirmed, NULL); "Install", onBInstallConfirmed, NULL);
@@ -637,24 +653,24 @@ static void refreshUpdatesB() {
char msg[160]; char msg[160];
lv_color_t col = UI_COL_MUTED; lv_color_t col = UI_COL_MUTED;
if (!p.heard) { if (!p.heard) {
snprintf(msg, sizeof(msg), "Controller B not heard.%s", snprintf(msg, sizeof(msg), "Inst. Cluster not heard.%s",
p.paired ? "" : " Not paired yet: connect the wire and run 'link pair' on the console."); p.paired ? "" : " Not paired yet: connect the wire and run 'link pair' on the console.");
} else if (!p.paired || !p.key_match) { } else if (!p.paired || !p.key_match) {
snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " Not paired with this controller. " snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " Not paired with this controller. "
"Connect the wire and run 'link pair' on the console."); "Connect the wire and run 'link pair' on the console.");
col = UI_COL_AMBER; col = UI_COL_AMBER;
} else if (!has_wifi) { } else if (!has_wifi) {
snprintf(msg, sizeof(msg), "Controller B has no Wi-Fi credentials yet. Join a network here; " snprintf(msg, sizeof(msg), "Inst. Cluster has no Wi-Fi credentials yet. Join a network here; "
"they are passed on by themselves."); "they are passed on by themselves.");
} else { } else {
switch (p.st.ota_phase) { switch (p.st.ota_phase) {
case LINK_OTA_CHECKING: snprintf(msg, sizeof(msg), "Controller B is checking..."); break; case LINK_OTA_CHECKING: snprintf(msg, sizeof(msg), "Inst. Cluster is checking..."); break;
case LINK_OTA_INSTALLING: snprintf(msg, sizeof(msg), "Installing %s on Controller B... %u %%", case LINK_OTA_INSTALLING: snprintf(msg, sizeof(msg), "Installing %s on Inst. Cluster... %u %%",
p.st.latest, p.st.ota_progress); col = UI_COL_ACCENT; break; p.st.latest, p.st.ota_progress); col = UI_COL_ACCENT; break;
case LINK_OTA_UP_TO_DATE: snprintf(msg, sizeof(msg), LV_SYMBOL_OK " Controller B is up to date."); col = UI_COL_OK; break; case LINK_OTA_UP_TO_DATE: snprintf(msg, sizeof(msg), LV_SYMBOL_OK " Inst. Cluster is up to date."); col = UI_COL_OK; break;
case LINK_OTA_AVAILABLE: snprintf(msg, sizeof(msg), "Version %s is available for Controller B.", p.st.latest); col = UI_COL_ACCENT; break; case LINK_OTA_AVAILABLE: snprintf(msg, sizeof(msg), "Version %s is available for Inst. Cluster.", p.st.latest); col = UI_COL_ACCENT; break;
case LINK_OTA_FAILED: snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", p.st.message); col = UI_COL_WARN; break; case LINK_OTA_FAILED: snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", p.st.message); col = UI_COL_WARN; break;
default: snprintf(msg, sizeof(msg), "Tap Check to look for a new version for Controller B."); break; default: snprintf(msg, sizeof(msg), "Tap Check to look for a new version"); break;
} }
if (p.st.flags & LINK_STATUS_PENDING_VERIFY) { if (p.st.flags & LINK_STATUS_PENDING_VERIFY) {
size_t n = strlen(msg); size_t n = strlen(msg);
@@ -726,7 +742,7 @@ static void buildUpdatesPage(lv_obj_t* page) {
label(page, "Firmware updates", &lv_font_montserrat_24, UI_COL_TEXT); label(page, "Firmware updates", &lv_font_montserrat_24, UI_COL_TEXT);
lv_obj_t* installed_a = NULL; lv_obj_t* installed_a = NULL;
lv_obj_t* a = controllerCard(page, "Controller A", FW_VERSION, &installed_a, &g_upd_latest, &g_upd_state); lv_obj_t* a = controllerCard(page, "Main CTRL", FW_VERSION, &installed_a, &g_upd_latest, &g_upd_state);
lv_obj_t* btns = box(a, LV_FLEX_FLOW_ROW); lv_obj_t* btns = box(a, LV_FLEX_FLOW_ROW);
lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_column(btns, 16, 0); lv_obj_set_style_pad_column(btns, 16, 0);
@@ -734,7 +750,7 @@ static void buildUpdatesPage(lv_obj_t* page) {
g_upd_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onInstall, NULL); g_upd_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onInstall, NULL);
g_upd_wifi = button(btns, LV_SYMBOL_WIFI " Wi-Fi settings", 260, 56, BTN_SECONDARY, onGoWifi, NULL); g_upd_wifi = button(btns, LV_SYMBOL_WIFI " Wi-Fi settings", 260, 56, BTN_SECONDARY, onGoWifi, NULL);
lv_obj_t* b = controllerCard(page, "Controller B", "-", &g_b_installed, &g_b_latest, &g_b_state); lv_obj_t* b = controllerCard(page, "Inst. Cluster", "-", &g_b_installed, &g_b_latest, &g_b_state);
btns = box(b, LV_FLEX_FLOW_ROW); btns = box(b, LV_FLEX_FLOW_ROW);
lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_column(btns, 16, 0); lv_obj_set_style_pad_column(btns, 16, 0);
@@ -742,8 +758,7 @@ static void buildUpdatesPage(lv_obj_t* page) {
g_b_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onBInstall, NULL); g_b_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onBInstall, NULL);
lv_obj_t* note = label(page, lv_obj_t* note = label(page,
"Signed releases from " OTA_SERVER ". Each controller restarts after installing and keeps " "Each controller restarts after updating. DO NOT TURN OFF THE IGNITION DURING THE UPDATE",
"the previous version as a fallback.",
&lv_font_montserrat_20, UI_COL_MUTED); &lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(note, LV_LABEL_LONG_WRAP); lv_label_set_long_mode(note, LV_LABEL_LONG_WRAP);
lv_obj_set_width(note, LV_PCT(100)); lv_obj_set_width(note, LV_PCT(100));
@@ -770,10 +785,30 @@ static void onDebugSwitch(lv_event_t* e) {
UIStateManager::setDebugEnabled(on); 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) { static void refreshSystem(bool force) {
setChecked(g_sys_can, CANDriver::isActive()); setChecked(g_sys_can, CANDriver::isActive());
setChecked(g_sys_link, UARTManager::getState() != UARTManager::UART_STATE_OFF); setChecked(g_sys_link, UARTManager::getState() != UARTManager::UART_STATE_OFF);
setChecked(g_sys_dbg, UIStateManager::isDebugEnabled()); 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 static uint32_t last = 0; // the figures below change slowly; 1 Hz is plenty
if (!force && millis() - last < 1000) return; if (!force && millis() - last < 1000) return;
@@ -784,18 +819,17 @@ static void refreshSystem(bool force) {
uint32_t up = millis() / 1000; uint32_t up = millis() / 1000;
char buf[400]; char buf[400];
snprintf(buf, sizeof(buf), 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" "ESP-NOW %s, %lu frames sent, %lu failed\n"
"%lu frames received\n" "%lu frames received\n"
"%u KB internal free, %u KB PSRAM free\n" "%u KB internal free, %u KB PSRAM free",
"%lu h %02lu min",
FW_VERSION, run ? run->label : "?", FW_VERSION, run ? run->label : "?",
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60),
EspNowLink::isReady() ? "up" : "DOWN", EspNowLink::isReady() ? "up" : "DOWN",
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount(), (unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount(),
(unsigned long)cs.messages_received, (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_INTERNAL | MALLOC_CAP_8BIT) / 1024),
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), (unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60));
setText(g_sys_info, buf); setText(g_sys_info, buf);
} }
@@ -808,22 +842,203 @@ static void buildSystemPage(lv_obj_t* page) {
lv_obj_t* right; lv_obj_t* right;
makeSettingRow(c, "CAN bus", "Read the car's data bus", &right); makeSettingRow(c, "CAN bus", "Read the car's data bus", &right);
g_sys_can = toggle(right, onCanSwitch, NULL); g_sys_can = toggle(right, onCanSwitch, NULL);
makeSettingRow(c, "Send to Controller B", "Gauge data over the wire and ESP-NOW", &right); makeSettingRow(c, "Send to Inst. Cluster", "Gauge data over the wire and ESP-NOW", &right);
g_sys_link = toggle(right, onLinkSwitch, NULL); g_sys_link = toggle(right, onLinkSwitch, NULL);
makeSettingRow(c, "Performance overlay", "Frame rate and CPU load in the corner", &right); makeSettingRow(c, "Performance overlay", "Frame rate and CPU load in the corner", &right);
g_sys_dbg = toggle(right, onDebugSwitch, NULL); 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 // two labels side by side, same line spacing, so keys and values line up
lv_obj_t* info = card(page); lv_obj_t* info = card(page);
lv_obj_set_size(info, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_size(info, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(info, LV_FLEX_FLOW_ROW); lv_obj_set_flex_flow(info, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(info, 24, 0); 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); lv_obj_set_style_text_line_space(keys, 6, 0);
g_sys_info = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT); g_sys_info = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT);
lv_obj_set_style_text_line_space(g_sys_info, 6, 0); lv_obj_set_style_text_line_space(g_sys_info, 6, 0);
} }
// ============================================================================
// VEHICLE PAGE - road speed = output shaft rpm / final drive x tyre circumference
// ============================================================================
typedef enum { VEH_FINAL, VEH_TYRE } veh_field_t;
typedef struct { veh_field_t field; int dir; } veh_step_t;
static veh_step_t g_veh_step[2][2] = {{{VEH_FINAL, -1}, {VEH_FINAL, +1}}, {{VEH_TYRE, -1}, {VEH_TYRE, +1}}};
/** 1x for taps and the first second of a hold, then 5x, then 10x (as on the Tuning screen). */
static int32_t holdMultiplier(lv_event_code_t code) {
if (code == LV_EVENT_PRESSED) { g_repeats = 0; return 0; }
if (code == LV_EVENT_LONG_PRESSED_REPEAT) {
g_repeats++;
return g_repeats > 25 ? 10 : g_repeats > 10 ? 5 : 1;
}
return 1; // CLICKED
}
static void onVehicleStep(lv_event_t* e) {
lv_event_code_t code = lv_event_get_code(e);
int32_t mult = holdMultiplier(code);
if (mult == 0) return;
if (code == LV_EVENT_CLICKED && g_repeats > 0) return; // end of a hold, already applied
veh_step_t* st = (veh_step_t*)lv_event_get_user_data(e);
if (st->field == VEH_FINAL) {
int32_t v = (int32_t)Vehicle::finalDriveX100() + st->dir * 1 * mult; // 0.01 per step
Vehicle::setFinalDriveX100((uint16_t)constrain(v, Vehicle::FINAL_DRIVE_MIN_X100, Vehicle::FINAL_DRIVE_MAX_X100));
} else {
int32_t v = (int32_t)Vehicle::tyreMm() + st->dir * 10 * mult; // 10 mm per step
Vehicle::setTyreMm((uint16_t)constrain(v, Vehicle::TYRE_MM_MIN, Vehicle::TYRE_MM_MAX));
}
refresh(true);
}
static void onVehicleResetConfirmed(bool ok, void* user) {
(void)user;
if (!ok) return;
Vehicle::resetDefaults();
refresh(true);
}
static void onVehicleReset(lv_event_t* e) {
(void)e;
confirm("Reset vehicle settings?", "Final drive back to 4.11:1 and tyre circumference to 2440 mm.",
"Reset", onVehicleResetConfirmed, NULL);
}
static void onEcuRereadConfirmed(bool ok, void* user) {
(void)user;
if (!ok) return;
EcuIdent::forget();
refresh(true);
}
static void onEcuReread(lv_event_t* e) {
(void)e;
confirm("Re-read the engine ECU?",
"Forgets the stored identification. It is read again, once, the next time the bus is up "
"with the key on and no scan tool connected. Use it when this board moves to another car.",
"Re-read", onEcuRereadConfirmed, NULL);
}
static lv_obj_t* makeStepBtn(lv_obj_t* parent, const char* txt, void* ctx) {
lv_obj_t* b = button(parent, txt, 76, 56, BTN_SECONDARY, NULL, NULL);
lv_obj_set_style_text_font(lv_obj_get_child(b, 0), &lv_font_montserrat_24, 0);
lv_obj_add_event_cb(b, onVehicleStep, LV_EVENT_PRESSED, ctx);
lv_obj_add_event_cb(b, onVehicleStep, LV_EVENT_CLICKED, ctx);
lv_obj_add_event_cb(b, onVehicleStep, LV_EVENT_LONG_PRESSED_REPEAT, ctx);
return b;
}
/** [name / hint] ... [-] value [+] - returns the value label. */
static lv_obj_t* makeVehicleRow(lv_obj_t* parent, const char* name, const char* hint, veh_step_t* steps) {
lv_obj_t* row = box(parent, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_PCT(100), 64);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(row, 12, 0);
lv_obj_t* txt = box(row, LV_FLEX_FLOW_COLUMN);
lv_obj_set_height(txt, LV_SIZE_CONTENT);
lv_obj_set_flex_grow(txt, 1);
lv_obj_set_style_pad_row(txt, 2, 0);
label(txt, name, &lv_font_montserrat_24, UI_COL_TEXT);
label(txt, hint, &lv_font_montserrat_14, UI_COL_MUTED);
makeStepBtn(row, LV_SYMBOL_MINUS, &steps[0]);
lv_obj_t* v = label(row, "--", &lv_font_montserrat_30, UI_COL_TEXT);
lv_obj_set_style_text_align(v, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(v, 170);
makeStepBtn(row, LV_SYMBOL_PLUS, &steps[1]);
return v;
}
static void refreshVehicle() {
char buf[160];
uint16_t fd = Vehicle::finalDriveX100();
snprintf(buf, sizeof(buf), "%u.%02u : 1", fd / 100, fd % 100);
setText(g_veh_final_lbl, buf);
snprintf(buf, sizeof(buf), "%u mm", Vehicle::tyreMm());
setText(g_veh_tyre_lbl, buf);
// live preview: the real shaft reading when the bus is up, a worked example otherwise
driveline_t dl = CANDriver::getDriveline();
if ((CANDriver::isActive() || BenchSim::isActive()) && dl.ignition_on) {
uint16_t rpm = can_output_shaft_rpm(dl.output_shaft_raw);
uint16_t v = Vehicle::speedKmhX10FromRpm(rpm);
snprintf(buf, sizeof(buf), "Now: output shaft %u rpm = %u.%u km/h", rpm, v / 10, v % 10);
} else {
uint16_t v = Vehicle::speedKmhX10FromRpm(1000);
snprintf(buf, sizeof(buf), "With these values 1000 output shaft rpm = %u.%u km/h", v / 10, v % 10);
}
setText(g_veh_live, buf);
// which DDE this board remembers (read once; see EcuIdent)
char ecu[80];
EcuIdent::describe(ecu, sizeof(ecu));
snprintf(buf, sizeof(buf), "Engine ECU: %s%s", ecu,
EcuIdent::known() ? "" : " - read once from the bus when the key is on");
static uint8_t ecu_state = 0xFF;
uint8_t st = EcuIdent::changed() ? 2 : EcuIdent::known() ? 1 : 0;
setText(g_veh_ecu, buf);
if (st != ecu_state) {
ecu_state = st;
setTextColor(g_veh_ecu, st == 2 ? UI_COL_AMBER : st == 1 ? UI_COL_TEXT : UI_COL_MUTED);
}
if (Vehicle::isDirty()) { setText(g_veh_save, "Saving..."); setTextColor(g_veh_save, UI_COL_MUTED); }
else { setText(g_veh_save, LV_SYMBOL_OK " All changes saved"); setTextColor(g_veh_save, UI_COL_OK); }
}
static void buildVehiclePage(lv_obj_t* page) {
lv_obj_t* c = card(page);
lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(c, 10, 0);
g_veh_final_lbl = makeVehicleRow(c, "Final drive ratio", "Differential ratio - 4.11:1 on this Patrol", g_veh_step[0]);
g_veh_tyre_lbl = makeVehicleRow(c, "Tyre circumference", "Rolling circumference in mm - a 265/70 R16 is about 2440", g_veh_step[1]);
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_COLUMN);
lv_obj_set_style_pad_row(info, 8, 0);
lv_obj_t* f = label(info, "Speed = output shaft rpm (0x0BA, from the gearbox) / final drive x tyre circumference. "
"The shaft factor itself is still provisional, hence the ~ on the screens.",
&lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(f, LV_LABEL_LONG_WRAP);
lv_obj_set_width(f, LV_PCT(100));
g_veh_live = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT);
lv_label_set_long_mode(g_veh_live, LV_LABEL_LONG_WRAP);
lv_obj_set_width(g_veh_live, LV_PCT(100));
g_veh_ecu = label(info, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(g_veh_ecu, LV_LABEL_LONG_WRAP);
lv_obj_set_width(g_veh_ecu, LV_PCT(100));
lv_obj_t* foot = box(page, LV_FLEX_FLOW_ROW);
lv_obj_set_size(foot, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(foot, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
g_veh_save = label(foot, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_t* btns = box(foot, LV_FLEX_FLOW_ROW);
lv_obj_set_size(btns, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_style_pad_column(btns, 12, 0);
button(btns, LV_SYMBOL_DOWNLOAD " Re-read ECU", 200, 56, BTN_SECONDARY, onEcuReread, NULL);
button(btns, LV_SYMBOL_REFRESH " Reset", 160, 56, BTN_SECONDARY, onVehicleReset, NULL);
}
// ============================================================================ // ============================================================================
// BUILD / REFRESH // BUILD / REFRESH
// ============================================================================ // ============================================================================
@@ -838,11 +1053,13 @@ static void build() {
g_nav[PAGE_WIFI] = makeNav(g_screen, PAGE_WIFI, "Wi-Fi"); g_nav[PAGE_WIFI] = makeNav(g_screen, PAGE_WIFI, "Wi-Fi");
g_nav[PAGE_UPDATES] = makeNav(g_screen, PAGE_UPDATES, "Updates"); g_nav[PAGE_UPDATES] = makeNav(g_screen, PAGE_UPDATES, "Updates");
g_nav[PAGE_SYSTEM] = makeNav(g_screen, PAGE_SYSTEM, "System"); g_nav[PAGE_SYSTEM] = makeNav(g_screen, PAGE_SYSTEM, "System");
g_nav[PAGE_VEHICLE] = makeNav(g_screen, PAGE_VEHICLE, "Vehicle");
for (int i = 0; i < PAGE_COUNT; i++) g_page[i] = makePage(g_screen); for (int i = 0; i < PAGE_COUNT; i++) g_page[i] = makePage(g_screen);
buildWifiPage(g_page[PAGE_WIFI]); buildWifiPage(g_page[PAGE_WIFI]);
buildUpdatesPage(g_page[PAGE_UPDATES]); buildUpdatesPage(g_page[PAGE_UPDATES]);
buildSystemPage(g_page[PAGE_SYSTEM]); buildSystemPage(g_page[PAGE_SYSTEM]);
buildVehiclePage(g_page[PAGE_VEHICLE]);
buildPasswordOverlay(); buildPasswordOverlay();
ESP_LOGI("Settings", "Settings screen built"); ESP_LOGI("Settings", "Settings screen built");
@@ -866,6 +1083,11 @@ static void refreshNav() {
snprintf(sys, sizeof(sys), "CAN %s \xE2\x80\xA2 Link %s", CANDriver::isActive() ? "on" : "off", snprintf(sys, sizeof(sys), "CAN %s \xE2\x80\xA2 Link %s", CANDriver::isActive() ? "on" : "off",
UARTManager::getState() != UARTManager::UART_STATE_OFF ? "on" : "off"); UARTManager::getState() != UARTManager::UART_STATE_OFF ? "on" : "off");
setText(g_nav_sub[PAGE_SYSTEM], sys); setText(g_nav_sub[PAGE_SYSTEM], sys);
char veh[40];
uint16_t fd = Vehicle::finalDriveX100();
snprintf(veh, sizeof(veh), "%u.%02u:1 \xE2\x80\xA2 %u mm", fd / 100, fd % 100, Vehicle::tyreMm());
setText(g_nav_sub[PAGE_VEHICLE], veh);
} }
/** Caller holds the LVGL lock. */ /** Caller holds the LVGL lock. */
@@ -876,6 +1098,7 @@ static void refresh(bool force) {
case PAGE_WIFI: refreshWifi(); break; case PAGE_WIFI: refreshWifi(); break;
case PAGE_UPDATES: refreshUpdates(); break; case PAGE_UPDATES: refreshUpdates(); break;
case PAGE_SYSTEM: refreshSystem(force); break; case PAGE_SYSTEM: refreshSystem(force); break;
case PAGE_VEHICLE: refreshVehicle(); break;
default: break; default: break;
} }
g_refreshing = false; g_refreshing = false;
+1 -1
View File
@@ -6,7 +6,7 @@
* entry; the joined network is remembered (WiFiManager) * entry; the joined network is remembered (WiFiManager)
* Updates - installed vs latest release, Check, Install behind a confirm * Updates - installed vs latest release, Check, Install behind a confirm
* dialog (Ota) * dialog (Ota)
* System - CAN bus / link to Controller B / performance overlay switches, * System - CAN bus / link to Inst. Cluster / performance overlay switches,
* live link and memory figures * live link and memory figures
* *
* Reached by swiping LEFT on the Driveline screen; swipe right or the * Reached by swiping LEFT on the Driveline screen; swipe right or the
+253
View File
@@ -0,0 +1,253 @@
/*
* Sport Screen Module Implementation - see sport_screen.h
*
* Drawn after the BMW iDrive "Sport displays" (user's photo, 2026-10-13):
* a wide dark-red band graded to bright orange at its inner edge, thin radial
* dividers cutting it into segments, white numbers inside the band, a thin red
* needle from the centre with no hub, the unit large in the middle and the
* gauge's name underneath. No digital readout in the original; a small one is
* kept under the unit because the bench has no other way to read the value.
*
* Each gauge is a dial-face IMAGE (assets/dial.png 420x420, rebuilt layer by
* layer in PhotoCraft from the photo, source assets/dial.pcraft: cells ring
* with a radial gradient and 15 dark gaps, dark ruler ring with 81 rungs, two
* bright lines, rim with a halo, 5 light spokes; sweep 230 degrees from 155)
* with an lv_meter on top that draws ONLY the numbers and the needle: its ticks
* are zero-width. The needle is an image
* (assets/needle.png, drawn in PhotoCraft 2026-10-13: tapered red body, lit
* orange-white tip with a soft glow, transparent for the first 70 px so it
* starts away from the pivot), rotated by lv_meter around its pivot at
* (0, 24): x = radius from the dial centre, the tip at 212 = the rim.
*/
#include "sport_screen.h"
#include "ui_kit.h"
#include "vehicle.h"
#include "bench_sim.h"
#include "driveline_screen.h"
#include "drivers/can_driver.h"
#include "display/lvgl_v8_port.h"
namespace SportScreen {
using namespace UiKit;
// ============================================================================
// GAUGE DEFINITIONS
// ============================================================================
// M57N (E60 530d donor): 500 Nm / 160 kW = 218 hp stock. The scales leave
// headroom for a remap; the label steps copy the photo's 5 labels per sweep.
static const int32_t TORQUE_MAX_NM = 600; // labels every 120 Nm, dividers every 12
static const int32_t POWER_MAX_HP = 320; // labels every 80 hp, dividers every 8
static const lv_coord_t GAUGE_SIZE = 420;
static const lv_coord_t GAUGE_Y = 72; // below the header / overlay band
// the dial image's geometry (assets/dial_geometry.json): rim r 210, cells 158..190
static const int32_t SWEEP_DEG = 230, START_DEG = 155; // open at the bottom, as the photo
static const lv_coord_t LABEL_R = 136; // numbers just inside the cells ring
extern "C" { LV_IMG_DECLARE(needle_img); LV_IMG_DECLARE(dial_img); } // src/assets/*.c (C linkage)
static const lv_coord_t NEEDLE_PIVOT_X = 0, NEEDLE_PIVOT_Y = 24;
#define COL_NUMBER lv_color_hex(0xF2F2F2)
typedef struct {
lv_obj_t* meter;
lv_meter_scale_t* scale;
lv_meter_indicator_t* needle;
lv_obj_t* value_lbl;
int32_t max;
int32_t shown; // needle position last written
} gauge_t;
// ============================================================================
// STATE
// ============================================================================
static lv_obj_t* g_screen = NULL;
static lv_obj_t* g_status = NULL;
static lv_obj_t* g_rpm_lbl = NULL;
static lv_obj_t* g_speed_lbl = NULL;
static gauge_t g_torque, g_power;
// ============================================================================
// BUILD
// ============================================================================
static void onBack(lv_event_t* e) {
(void)e;
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());
DrivelineScreen::show();
}
}
/**
* One BMW-style gauge. `minor_ticks` dividers over the sweep (incl. both
* ends), a label every `major_every`-th divider.
*/
static void makeGauge(gauge_t& g, lv_coord_t x, const char* title, const char* unit,
int32_t max, uint16_t minor_ticks, uint16_t major_every) {
g.max = max;
g.shown = -1;
// the dial face, then the meter (numbers + needle) on top of it
lv_obj_t* face = lv_img_create(g_screen);
lv_img_set_src(face, &dial_img);
lv_obj_set_pos(face, x, GAUGE_Y);
lv_obj_clear_flag(face, LV_OBJ_FLAG_CLICKABLE);
lv_obj_t* m = lv_meter_create(g_screen);
g.meter = m;
lv_obj_set_size(m, GAUGE_SIZE, GAUGE_SIZE);
lv_obj_set_pos(m, x, GAUGE_Y);
lv_obj_set_style_bg_opa(m, LV_OPA_TRANSP, 0); // no dial face: the band floats on black
lv_obj_set_style_border_width(m, 0, 0);
lv_obj_set_style_shadow_width(m, 0, 0);
lv_obj_set_style_pad_all(m, 0, 0);
lv_obj_set_style_text_font(m, &lv_font_montserrat_24, LV_PART_TICKS);
lv_obj_set_style_text_color(m, COL_NUMBER, LV_PART_TICKS);
lv_obj_set_style_size(m, 0, LV_PART_INDICATOR); // no needle hub
lv_obj_clear_flag(m, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_clear_flag(m, LV_OBJ_FLAG_CLICKABLE); // swipes pass through to the screen
// same sweep as the image; the image carries the ticks, so the meter's are 0 px wide
// and only the major ticks' labels are drawn (placed r_out - len - gap from the centre)
g.scale = lv_meter_add_scale(m);
lv_meter_set_scale_range(m, g.scale, 0, max, SWEEP_DEG, START_DEG);
lv_meter_set_scale_ticks(m, g.scale, minor_ticks, 0, 1, lv_color_black());
lv_meter_set_scale_major_ticks(m, g.scale, major_every, 0, 1, lv_color_black(),
(GAUGE_SIZE / 2) - 1 - LABEL_R);
// the image needle: lv_meter rotates it about the pivot placed on the dial centre
g.needle = lv_meter_add_needle_img(m, g.scale, &needle_img, NEEDLE_PIVOT_X, NEEDLE_PIVOT_Y);
lv_meter_set_indicator_value(m, g.needle, 0);
// unit large in the middle, the live value small under it
lv_obj_t* u = label(m, unit, &lv_font_montserrat_48, COL_NUMBER);
lv_obj_align(u, LV_ALIGN_CENTER, 0, -14);
g.value_lbl = label(m, "--", &lv_font_montserrat_30, UI_COL_MUTED);
lv_obj_align(g.value_lbl, LV_ALIGN_CENTER, 0, 36);
// the gauge's name in the open bottom of the sweep
lv_obj_t* t = label(g_screen, title, &lv_font_montserrat_30, COL_NUMBER);
lv_obj_align_to(t, m, LV_ALIGN_BOTTOM_MID, 0, -8);
}
static void build() {
if (g_screen) return;
g_screen = screen();
lv_obj_set_style_bg_color(g_screen, lv_color_black(), 0); // the photo's black
lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL);
header(g_screen, "SPORT", onBack);
g_status = label(g_screen, "", &lv_font_montserrat_20, UI_COL_AMBER);
lv_obj_set_pos(g_status, 24, 64);
// two gauges, centred in their halves of the screen: Power left, Torque right (as in the photo)
const lv_coord_t gap = 96;
const lv_coord_t x0 = (1024 - 2 * GAUGE_SIZE - gap) / 2;
// 5 numbers per sweep (the image has 16 cells, 4 per number): 0 80 ... 320 hp, 0 120 ... 600 Nm
makeGauge(g_power, x0, "Power", "hp", POWER_MAX_HP, 5, 1);
makeGauge(g_torque, x0 + GAUGE_SIZE + gap, "Torque", "Nm", TORQUE_MAX_NM, 5, 1);
// rpm and road speed between the gauge names, bottom edge
lv_obj_t* row = box(g_screen, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(row, 14, 0);
lv_obj_align(row, LV_ALIGN_BOTTOM_MID, 0, -14);
label(row, "RPM", &lv_font_montserrat_14, UI_COL_MUTED);
g_rpm_lbl = label(row, "----", &lv_font_montserrat_24, UI_COL_TEXT);
lv_obj_t* sep = box(row, LV_FLEX_FLOW_ROW);
lv_obj_set_size(sep, 24, 1);
label(row, "SPEED", &lv_font_montserrat_14, UI_COL_MUTED);
g_speed_lbl = label(row, "--", &lv_font_montserrat_24, UI_COL_TEXT);
label(row, "~km/h", &lv_font_montserrat_14, UI_COL_MUTED);
}
// ============================================================================
// REFRESH
// ============================================================================
/** Move the needle only when the shown value changes (lv_meter invalidates just the needle). */
static void setGauge(gauge_t& g, int32_t v) {
if (v < 0) v = 0;
if (v > g.max) v = g.max;
if (v == g.shown) return;
g.shown = v;
lv_meter_set_indicator_value(g.meter, g.needle, v);
}
static void refresh() {
bool can_up = CANDriver::isActive() || BenchSim::isActive(); // `sim` console counts as a live bus
driveline_t dl = CANDriver::getDriveline();
bool live = can_up && dl.ignition_on;
const char* st = "";
if (BenchSim::isActive()) st = LV_SYMBOL_SETTINGS " SIMULATION - bench values from the console, not the car";
else if (!can_up) st = LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System";
else if (!dl.ignition_on) st = "Ignition off";
setText(g_status, st);
char buf[24];
if (!live) {
setGauge(g_torque, 0);
setGauge(g_power, 0);
setText(g_torque.value_lbl, "--");
setText(g_power.value_lbl, "--");
setText(g_rpm_lbl, "----");
setText(g_speed_lbl, "--");
return;
}
// torque: TORQ_AVL is signed (negative on overrun); the gauge floors at 0.
// Only while the engine runs: with the key on and the engine off the field
// holds a junk value (812 Nm on Patrol 2, 245 on Patrol 1 - captures 2026-10-18).
bool running = (dl.engine_run_state == ENGINE_RUN_RUNNING);
int32_t nm = running ? dl.engine_torque_x10 / 10 : 0;
setGauge(g_torque, nm);
if (running) snprintf(buf, sizeof(buf), "%ld", (long)(nm < 0 ? 0 : nm));
else snprintf(buf, sizeof(buf), "--");
setText(g_torque.value_lbl, buf);
uint16_t hp_x10 = running ? Vehicle::powerHpX10(dl.engine_torque_x10, dl.engine_rpm) : 0;
setGauge(g_power, hp_x10 / 10);
if (running) snprintf(buf, sizeof(buf), "%u", hp_x10 / 10);
else snprintf(buf, sizeof(buf), "--");
setText(g_power.value_lbl, buf);
snprintf(buf, sizeof(buf), "%u", dl.engine_rpm);
setText(g_rpm_lbl, buf);
uint16_t kmh_x10 = Vehicle::speedKmhX10(dl.output_shaft_raw);
snprintf(buf, sizeof(buf), "%u", kmh_x10 / 10);
setText(g_speed_lbl, buf);
}
// ============================================================================
// PUBLIC API
// ============================================================================
void show() {
build();
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;
static uint32_t last = 0;
if (millis() - last < 100) return; // 10 Hz, like the Driveline
last = millis();
lvgl_port_lock(-1);
refresh();
lvgl_port_unlock();
}
} // namespace SportScreen
+28
View File
@@ -0,0 +1,28 @@
/*
* Sport Screen Module
*
* BMW-style "Sport displays": two round gauges, engine torque (Nm, 0x0A8
* TORQ_AVL straight from the bus) and engine power (hp, computed:
* P(W) = Nm x rpm / 9.5488, hp = W / 745.70 - see Vehicle::powerHpX10()).
* Each gauge has an arc fill, a needle, a thin peak needle that holds for a
* few seconds, and the value in the gap at the bottom. Engine rpm and the
* computed road speed sit under the gauges.
*
* Opened from the "Sport" button on the Driveline screen; the Driveline button
* or a right swipe goes back. Built once and kept, like every screen.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
namespace SportScreen {
/** Build (idempotent) and load. Caller holds the LVGL lock. */
void show();
/** Refresh the gauges while shown (10 Hz). Call from loop(); takes its own lock. */
void tick();
} // namespace SportScreen
+1 -1
View File
@@ -102,7 +102,7 @@ static void help() {
print("cfg override off | rpm <n> | duty <n> | both <rpm> <duty>"); print("cfg override off | rpm <n> | duty <n> | both <rpm> <duty>");
print("cfg reset back to defaults"); print("cfg reset back to defaults");
print("diag help OBD-II diagnostic probe (transmits on the bus)"); print("diag help OBD-II diagnostic probe (transmits on the bus)");
print("link help Controller B: pairing, credentials, its updates"); print("link help Inst. Cluster: pairing, credentials, its updates");
} }
static bool setField(const char* name, long v) { static bool setField(const char* name, long v) {
+1 -1
View File
@@ -1,7 +1,7 @@
/* /*
* Tunables Module * Tunables Module
* *
* Owns the link_config_t that Controller A pushes to Controller B: Patrol gauge * Owns the link_config_t that Main CTRL pushes to Inst. Cluster: Patrol gauge
* calibration (tach pulses/rev, coolant PWM law) and the alert thresholds A * calibration (tach pulses/rev, coolant PWM law) and the alert thresholds A
* evaluates. Persisted in NVS. Editable at runtime over the USB serial console * evaluates. Persisted in NVS. Editable at runtime over the USB serial console
* ("cfg help") until a settings-screen UI exists. * ("cfg help") until a settings-screen UI exists.
+5 -5
View File
@@ -61,9 +61,9 @@ namespace TuningScreen
{F_TEMP_OFFSET, TAB_COOLANT, "Offset", "Duty at 0 \xC2\xB0" "C (duty = slope x temp + offset)", 1, -1000, 1000, NULL}, {F_TEMP_OFFSET, TAB_COOLANT, "Offset", "Duty at 0 \xC2\xB0" "C (duty = slope x temp + offset)", 1, -1000, 1000, NULL},
{F_TEMP_MIN, TAB_COOLANT, "Minimum temperature", "Needle stays at rest below this", 1, -50, 200, NULL}, {F_TEMP_MIN, TAB_COOLANT, "Minimum temperature", "Needle stays at rest below this", 1, -50, 200, NULL},
{F_TEMP_DUTY_MAX, TAB_COOLANT, "Duty limit", "Highest duty sent (255 = full scale)", 5, 0, 255, NULL}, {F_TEMP_DUTY_MAX, TAB_COOLANT, "Duty limit", "Highest duty sent (255 = full scale)", 5, 0, 255, NULL},
{F_COOLANT_HOT, TAB_ALERTS, "Coolant too hot", "Alarm on Controller B at or above this temperature", 1, 0, 200, NULL}, {F_COOLANT_HOT, TAB_ALERTS, "Coolant too hot", "Alarm on Inst. Cluster at or above this temperature", 1, 0, 200, NULL},
{F_GEARBOX_HOT, TAB_ALERTS, "Gearbox oil too hot", "Alarm on Controller B at or above this temperature", 1, 0, 200, NULL}, {F_GEARBOX_HOT, TAB_ALERTS, "Gearbox oil too hot", "Alarm on Inst. Cluster at or above this temperature", 1, 0, 200, NULL},
{F_BATT_LOW, TAB_ALERTS, "Battery low", "Alarm on Controller B below this voltage", 10, 0, 3000, NULL}, {F_BATT_LOW, TAB_ALERTS, "Battery low", "Alarm on Inst. Cluster below this voltage", 10, 0, 3000, NULL},
}; };
static const char *TAB_NAMES[TAB_COUNT] = {"Tachometer", "Coolant gauge", "Alerts", "Simulation"}; static const char *TAB_NAMES[TAB_COUNT] = {"Tachometer", "Coolant gauge", "Alerts", "Simulation"};
@@ -522,7 +522,7 @@ namespace TuningScreen
makeRow(g_tab_page[TAB_TACH], F_TACH_PPR); makeRow(g_tab_page[TAB_TACH], F_TACH_PPR);
makeRow(g_tab_page[TAB_TACH], F_TACH_TRIM); makeRow(g_tab_page[TAB_TACH], F_TACH_TRIM);
makeRow(g_tab_page[TAB_TACH], F_TACH_MAX_HZ); makeRow(g_tab_page[TAB_TACH], F_TACH_MAX_HZ);
g_tach_en_sw = makeSwitchRow(g_tab_page[TAB_TACH], "Tachometer output", "IO7 on Controller B. Off = no signal", g_tach_en_sw = makeSwitchRow(g_tab_page[TAB_TACH], "Tachometer output", "IO7 on Inst. Cluster. Off = no signal",
onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH); onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH);
// ---- Coolant gauge ---- // ---- Coolant gauge ----
@@ -531,7 +531,7 @@ namespace TuningScreen
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_OFFSET); makeRow(g_tab_page[TAB_COOLANT], F_TEMP_OFFSET);
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_MIN); makeRow(g_tab_page[TAB_COOLANT], F_TEMP_MIN);
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_DUTY_MAX); makeRow(g_tab_page[TAB_COOLANT], F_TEMP_DUTY_MAX);
g_temp_en_sw = makeSwitchRow(g_tab_page[TAB_COOLANT], "Coolant gauge output", "IO8 on Controller B. Off = no signal", g_temp_en_sw = makeSwitchRow(g_tab_page[TAB_COOLANT], "Coolant gauge output", "IO8 on Inst. Cluster. Off = no signal",
onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP); onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP);
// ---- Alerts ---- // ---- Alerts ----
+1 -1
View File
@@ -11,7 +11,7 @@
* button (top right) goes back. The Simulation sliders don't bubble gestures, * button (top right) goes back. The Simulation sliders don't bubble gestures,
* so dragging them never changes screens. * so dragging them never changes screens.
* Every change goes through Tunables, so it is saved to NVS (overrides * Every change goes through Tunables, so it is saved to NVS (overrides
* excepted) and pushed to Controller B in the next CONFIG frame. * excepted) and pushed to Inst. Cluster in the next CONFIG frame.
*/ */
#pragma once #pragma once
+10 -23
View File
@@ -3,7 +3,7 @@
* *
* Builds the v2 frames (DATA at 5 Hz, CONFIG on change + every CONFIG_RESEND_MS) * Builds the v2 frames (DATA at 5 Hz, CONFIG on change + every CONFIG_RESEND_MS)
* and sends each one on BOTH transports: UART1 (GPIO 44 -> SP3485 -> 485_A/B) * and sends each one on BOTH transports: UART1 (GPIO 44 -> SP3485 -> 485_A/B)
* and ESP-NOW broadcast. Controller B dedupes on packet_id. * and ESP-NOW broadcast. Inst. Cluster dedupes on packet_id.
*/ */
#include "uart_manager.h" #include "uart_manager.h"
@@ -50,30 +50,17 @@ static volatile bool g_port_ready = false; // Serial1.begin() done (in the tas
// ============================================================================ // ============================================================================
/** /**
* @brief Seed the shared structure until CAN data arrives. * @brief Start from NOTHING valid. Until a CAN frame fills a field, its valid
* @note The temperatures/voltage are marked valid so a bench without CAN still * flag stays clear and B shows no value for it (user decision
* exercises B's display. RPM and gear nibbles are NOT marked valid: the * 2026-09-28: no invented numbers, ever - the old bench defaults of
* tach output must never run on invented data. * 89 / 85 degC and 12.45 V looked like real readings).
*/ */
static void initializeDefaultData() { static void initializeDefaultData() {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
g_automotive_data.gear_lever = DEFAULT_GEAR_LEVER; uint8_t dbg = g_automotive_data.debug_enabled;
g_automotive_data.gear_nibbles = 0; memset(&g_automotive_data, 0, sizeof(g_automotive_data));
g_automotive_data.engine_rpm = 0; g_automotive_data.gear_lever = LEVER_UNKNOWN;
g_automotive_data.gearbox_oil_temp = DEFAULT_GEARBOX_TEMP; g_automotive_data.debug_enabled = dbg;
g_automotive_data.engine_oil_temp = DEFAULT_ENGINE_OIL_TEMP;
g_automotive_data.coolant_temp = DEFAULT_COOLANT_TEMP;
g_automotive_data.battery_voltage = DEFAULT_BATTERY_VOLTAGE;
g_automotive_data.alerts = DEFAULT_ALERTS;
g_automotive_data.valid_flags = VALID_FLAG_GEAR_POS |
VALID_FLAG_GEARBOX_TEMP |
VALID_FLAG_ENGINE_TEMP |
VALID_FLAG_COOLANT_TEMP |
VALID_FLAG_BATTERY_VOLT |
VALID_FLAG_ALERTS;
g_automotive_data.debug_enabled = 0;
xSemaphoreGive(g_data_mutex); xSemaphoreGive(g_data_mutex);
} }
} }
@@ -304,7 +291,7 @@ void setDebugEnabled(bool enabled) {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
g_automotive_data.debug_enabled = enabled ? 1 : 0; g_automotive_data.debug_enabled = enabled ? 1 : 0;
xSemaphoreGive(g_data_mutex); xSemaphoreGive(g_data_mutex);
ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Controller B)", ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Inst. Cluster)",
enabled ? "ENABLED" : "DISABLED"); enabled ? "ENABLED" : "DISABLED");
} }
} }
+1 -1
View File
@@ -117,7 +117,7 @@ void setDebugEnabled(bool enabled);
void linkToCANState(bool can_active); void linkToCANState(bool can_active);
/** /**
* @brief Settings-screen switch: start/stop sending to Controller B (UART1 + * @brief Settings-screen switch: start/stop sending to Inst. Cluster (UART1 +
* ESP-NOW) and remember the choice in NVS. * ESP-NOW) and remember the choice in NVS.
*/ */
void setEnabled(bool enabled); void setEnabled(bool enabled);
+1 -1
View File
@@ -1,7 +1,7 @@
/* /*
* UI State Manager Module * UI State Manager Module
* *
* Holds the debug flag (sent to Controller B, shows LVGL's performance overlay). * Holds the debug flag (sent to Inst. Cluster, shows LVGL's performance overlay).
*/ */
#pragma once #pragma once
+194
View File
@@ -0,0 +1,194 @@
/*
* Vehicle Module Implementation - see vehicle.h
*/
#include "vehicle.h"
#include "serial_lock.h"
#include "protocol/automotive_data.h"
#include <Preferences.h>
namespace Vehicle {
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
static const char* NVS_NAMESPACE = "settings";
static const char* NVS_KEY_FINAL = "final_x100";
static const char* NVS_KEY_TYRE = "tyre_mm";
// Defaults: the Patrol's 4.11:1 final drive (user, 2026-10-13); 2440 mm is a
// 265/70 R16 (overall diameter ~777 mm), a common Patrol tyre - adjust on the screen.
static const uint16_t DEFAULT_FINAL_X100 = 411;
static const uint16_t DEFAULT_TYRE_MM = 2440;
static volatile uint16_t g_final_x100 = DEFAULT_FINAL_X100;
static volatile uint16_t g_tyre_mm = DEFAULT_TYRE_MM;
static const uint32_t SAVE_IDLE_MS = 3000;
static bool g_dirty = false;
static uint32_t g_dirty_ms = 0;
// ============================================================================
// PRIVATE HELPERS
// ============================================================================
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 void markDirty() {
g_dirty = true;
g_dirty_ms = millis();
}
static void save() {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, false);
prefs.putUShort(NVS_KEY_FINAL, g_final_x100);
prefs.putUShort(NVS_KEY_TYRE, g_tyre_mm);
prefs.end();
print("[vehicle] saved final drive %u.%02u:1, tyre %u mm",
g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm);
}
static void show() {
print("[vehicle] final drive %u.%02u:1, tyre circumference %u mm%s",
g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm, g_dirty ? " (saving...)" : "");
// a worked example so the numbers can be sanity-checked without driving
uint16_t v = speedKmhX10FromRpm(1000);
print("[vehicle] 1000 shaft rpm = %u.%u km/h (shaft rpm itself is the provisional 0x0BA x 0.1074)",
v / 10, v % 10);
}
static void help() {
print("vehicle show final drive ratio, tyre circumference");
print("vehicle set final <x.xx> final drive (differential) ratio, 2.00..8.00");
print("vehicle set tyre <mm> tyre rolling circumference, 1500..3500 mm");
print("vehicle reset back to 4.11:1 and 2440 mm");
}
// ============================================================================
// PUBLIC API
// ============================================================================
void init() {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, true);
g_final_x100 = prefs.getUShort(NVS_KEY_FINAL, DEFAULT_FINAL_X100);
g_tyre_mm = prefs.getUShort(NVS_KEY_TYRE, DEFAULT_TYRE_MM);
prefs.end();
g_final_x100 = constrain(g_final_x100, FINAL_DRIVE_MIN_X100, FINAL_DRIVE_MAX_X100);
g_tyre_mm = constrain(g_tyre_mm, TYRE_MM_MIN, TYRE_MM_MAX);
print("[vehicle] final drive %u.%02u:1, tyre %u mm", g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm);
}
uint16_t finalDriveX100() { return g_final_x100; }
uint16_t tyreMm() { return g_tyre_mm; }
void setFinalDriveX100(uint16_t v) {
v = constrain(v, FINAL_DRIVE_MIN_X100, FINAL_DRIVE_MAX_X100);
if (v == g_final_x100) return;
g_final_x100 = v;
markDirty();
}
void setTyreMm(uint16_t v) {
v = constrain(v, TYRE_MM_MIN, TYRE_MM_MAX);
if (v == g_tyre_mm) return;
g_tyre_mm = v;
markDirty();
}
uint16_t speedKmhX10FromRpm(uint16_t shaft_rpm) {
// km/h = shaft_rpm / ratio * circumference_m * 60 / 1000
// = shaft_rpm * tyre_mm * 6 / (final_x100 * 1000)
// (tyre_mm / 1000 -> m, ratio = final_x100 / 100, * 60 min/h, / 1000 m/km)
// km/h x10 = shaft_rpm * tyre_mm * 3 / (final_x100 * 50)
// Integer only: 65535 * 3500 * 3 fits a 32-bit value with room.
// Checked on the bench 2026-10-13: 1199 rpm, 4.11:1, 2440 mm -> 42.7 km/h.
uint32_t num = (uint32_t)shaft_rpm * g_tyre_mm * 3;
uint32_t den = (uint32_t)g_final_x100 * 50;
uint32_t v = (num + den / 2) / den;
return v > 0xFFFF ? 0xFFFF : (uint16_t)v;
}
uint16_t speedKmhX10(uint16_t output_shaft_raw) {
return speedKmhX10FromRpm(can_output_shaft_rpm(output_shaft_raw));
}
uint16_t powerHpX10(int16_t torque_x10, uint16_t rpm) {
if (torque_x10 <= 0 || rpm == 0) return 0;
// P(W) = T * rpm / 9.5488 ; hp = P / 745.70 ; x10 and T in 0.1 Nm:
// hp_x10 = (T_x10 / 10) * rpm / 9.5488 / 745.70 * 10 = T_x10 * rpm / 7120.55
float hp_x10 = (float)torque_x10 * (float)rpm / 7120.55f;
if (hp_x10 > 65535.0f) return 0xFFFF;
return (uint16_t)(hp_x10 + 0.5f);
}
void resetDefaults() {
g_final_x100 = DEFAULT_FINAL_X100;
g_tyre_mm = DEFAULT_TYRE_MM;
markDirty();
flush();
}
void flush() {
if (!g_dirty) return;
g_dirty = false;
save();
}
bool isDirty() { return g_dirty; }
void tick() {
if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush();
}
bool handleCommand(const char* line) {
if (strncmp(line, "vehicle", 7) != 0 || (line[7] != 0 && line[7] != ' ')) return false;
char buf[96];
snprintf(buf, sizeof(buf), "%s", line);
char* argv[5];
int argc = 0;
for (char* t = strtok(buf, " \t"); t && argc < 5; t = strtok(NULL, " \t")) argv[argc++] = t;
if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; }
if (!strcmp(argv[1], "show")) { show(); return true; }
if (!strcmp(argv[1], "reset")) { resetDefaults(); show(); return true; }
if (!strcmp(argv[1], "set") && argc == 4) {
if (!strcmp(argv[2], "final")) {
float r = atof(argv[3]);
long x100 = lroundf(r * 100.0f);
if (x100 < FINAL_DRIVE_MIN_X100 || x100 > FINAL_DRIVE_MAX_X100) {
print("[vehicle] final drive must be %u.%02u..%u.%02u", FINAL_DRIVE_MIN_X100 / 100, FINAL_DRIVE_MIN_X100 % 100,
FINAL_DRIVE_MAX_X100 / 100, FINAL_DRIVE_MAX_X100 % 100);
return true;
}
setFinalDriveX100((uint16_t)x100);
show();
return true;
}
if (!strcmp(argv[2], "tyre")) {
long mm = atol(argv[3]);
if (mm < TYRE_MM_MIN || mm > TYRE_MM_MAX) {
print("[vehicle] tyre circumference must be %u..%u mm", TYRE_MM_MIN, TYRE_MM_MAX);
return true;
}
setTyreMm((uint16_t)mm);
show();
return true;
}
}
help();
return true;
}
} // namespace Vehicle
+71
View File
@@ -0,0 +1,71 @@
/*
* Vehicle Module
*
* The two numbers that turn the gearbox output shaft speed (0x0BA, the only
* road-speed signal on this bus - there is no DSC) into road speed, plus the
* maths that uses them:
*
* wheel rpm = output shaft rpm / final drive ratio
* speed (km/h) = wheel rpm * tyre circumference (m) * 60 / 1000
*
* and the engine power the Sport screen shows:
*
* power (W) = torque (Nm) * rpm / 9.5488
* power (hp) = power (W) / 745.70
*
* Final drive ratio and tyre circumference are the user's (Settings > Vehicle,
* `vehicle` console), saved in NVS (namespace "settings", keys `final_x100`,
* `tyre_mm`). Writes are deferred like the tunables: every flash write flickers
* the RGB panel, so edits are written SAVE_IDLE_MS after the last tap, or on
* flush() when the Settings screen is left.
*
* NB the output shaft factor itself (raw counts -> rpm) is still provisional
* (wiki driveline-speed-signals), so the speed carries the same "~".
*/
#pragma once
#include <Arduino.h>
namespace Vehicle {
/** Load the saved values (defaults if absent). Call after SettingsManager::init(). */
void init();
/** Final drive (differential) ratio x100, e.g. 411 = 4.11:1. */
uint16_t finalDriveX100();
void setFinalDriveX100(uint16_t v);
/** Tyre rolling circumference in mm. */
uint16_t tyreMm();
void setTyreMm(uint16_t v);
/** Limits for the editors. */
static const uint16_t FINAL_DRIVE_MIN_X100 = 200, FINAL_DRIVE_MAX_X100 = 800;
static const uint16_t TYRE_MM_MIN = 1500, TYRE_MM_MAX = 3500;
/** Road speed in km/h x10 from the raw 0x0BA output shaft field. */
uint16_t speedKmhX10(uint16_t output_shaft_raw);
/** Road speed in km/h x10 from an output shaft speed in rpm. */
uint16_t speedKmhX10FromRpm(uint16_t shaft_rpm);
/** Engine power in hp x10 from torque (0.1 Nm, signed) and engine speed. Negative torque gives 0. */
uint16_t powerHpX10(int16_t torque_x10, uint16_t rpm);
/** Back to the defaults (4.11:1, 2440 mm) and save. */
void resetDefaults();
/** Write pending edits to NVS now (call when leaving the Settings screen). */
void flush();
/** True while an edit is waiting for its deferred NVS write. */
bool isDirty();
/** Deferred-save timer. Call from loop(). */
void tick();
/** `vehicle show | set final <x.xx> | set tyre <mm> | reset`. */
bool handleCommand(const char* line);
} // namespace Vehicle
+2 -2
View File
@@ -6,7 +6,7 @@
* the request functions, so screen lifetimes can never leave dangling pointers * the request functions, so screen lifetimes can never leave dangling pointers
* here. * here.
* *
* Radio rules (the ESP-NOW link to Controller B shares the radio): * Radio rules (the ESP-NOW link to Inst. Cluster shares the radio):
* - the radio stays in STA mode forever; "off" only stops association/scans. * - the radio stays in STA mode forever; "off" only stops association/scans.
* Never WiFi.disconnect(true) / WiFi.mode(WIFI_OFF) - that kills ESP-NOW. * Never WiFi.disconnect(true) / WiFi.mode(WIFI_OFF) - that kills ESP-NOW.
* - scans only when asked (each one hops every channel); * - scans only when asked (each one hops every channel);
@@ -84,7 +84,7 @@ bool handleCommand(const char* line);
/** /**
* The remembered network, password included - for LinkPeer, which hands it to * The remembered network, password included - for LinkPeer, which hands it to
* Controller B inside an encrypted frame. Never print the password. * Inst. Cluster inside an encrypted frame. Never print the password.
* @return false if no network is saved * @return false if no network is saved
*/ */
bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n); bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n);
+1 -1
View File
@@ -1,4 +1,4 @@
"""Run the Route A OBD-II diag probe sequence on Controller A and log everything. """Run the Route A OBD-II diag probe sequence on Main CTRL and log everything.
Opens the port once (one reboot), waits for boot, then sends each diag command Opens the port once (one reboot), waits for boot, then sends each diag command
with a generous wait, echoing replies and saving the full console stream with a generous wait, echoing replies and saving the full console stream
+1 -1
View File
@@ -1,4 +1,4 @@
"""Display-performance session: stream PERF lines from Controller A to a log """Display-performance session: stream PERF lines from Main CTRL to a log
while you provoke symptoms on the touchscreen (wiki open question #13). while you provoke symptoms on the touchscreen (wiki open question #13).
Opens the port WITHOUT resetting the board (DTR/RTS low), turns on `perf on 1`, Opens the port WITHOUT resetting the board (DTR/RTS low), turns on `perf on 1`,
+56
View File
@@ -0,0 +1,56 @@
"""Convert a PNG with transparency into an LVGL 8 image C file (LV_IMG_CF_TRUE_COLOR_ALPHA).
Usage: python tools/png2lvgl.py assets/needle.png src/assets/needle_img.c needle_img
Pixel format matches this firmware's lv_conf.h: LV_COLOR_DEPTH 16, LV_COLOR_16_SWAP 0,
so every pixel is RGB565 little-endian followed by one alpha byte (3 bytes per pixel).
Requires Pillow (python -m pip install --user pillow).
"""
import sys
from PIL import Image
src, dst, name = sys.argv[1], sys.argv[2], sys.argv[3]
im = Image.open(src).convert("RGBA")
w, h = im.size
px = im.load()
data = bytearray()
for y in range(h):
for x in range(w):
r, g, b, a = px[x, y]
c = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)
data += bytes((c & 0xFF, c >> 8, a))
lines = []
for i in range(0, len(data), 24):
lines.append(" " + ", ".join("0x%02X" % v for v in data[i:i + 24]) + ",")
with open(dst, "w", encoding="utf-8", newline="\n") as f:
f.write(f"""/*
* {name}: generated by tools/png2lvgl.py from {src.replace(chr(92), '/')} ({w}x{h}).
* LV_IMG_CF_TRUE_COLOR_ALPHA, RGB565 little-endian + alpha, 3 bytes per pixel.
* Regenerate after editing the PNG; do not edit by hand.
*/
#include <lvgl.h>
#ifndef LV_ATTRIBUTE_MEM_ALIGN
#define LV_ATTRIBUTE_MEM_ALIGN
#endif
static const LV_ATTRIBUTE_MEM_ALIGN uint8_t {name}_map[] = {{
{chr(10).join(lines)}
}};
const lv_img_dsc_t {name} = {{
.header = {{
.cf = LV_IMG_CF_TRUE_COLOR_ALPHA,
.always_zero = 0,
.reserved = 0,
.w = {w},
.h = {h},
}},
.data_size = {len(data)},
.data = {name}_map,
}};
""")
print(f"{dst}: {w}x{h}, {len(data)} bytes")
@@ -83,7 +83,7 @@ On BMW PT-CAN (Powertrain CAN) networks, data is divided into two categories: **
1\. Broadcasted Data (Why you see RPM & Temp) 1\. Broadcasted Data (Why you see RPM & Temp)
The DDE (Engine ECU) continuously loops and broadcasts specific telemetry frames that other modules (like the Instrument Cluster, Transmission Control, and Stability Control) *absolutely need* to function. The DDE (Engine ECU) continuously loops and broadcasts specific telemetry frames that other modules (like the Inst. Cluster, Transmission Control, and Stability Control) *absolutely need* to function.
Bimmerforums.com +1 Bimmerforums.com +1
+11 -5
View File
@@ -1,6 +1,6 @@
--- ---
type: index type: index
updated: 2026-09-27 updated: 2026-10-18
--- ---
# Index # Index
@@ -12,15 +12,18 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
- [[patrol-instrument-cluster]] — **what the Patrol cluster expects on its inputs**: tach = 2 pulses/rev (verified by calibration), temp = NTC sender 2.1–2.9 kΩ cold → ~250 Ω at 90 °C; the 1 kHz PWM needle-flutter problem and the mitigation ladder (fixed-duty test → 20 kHz → hardware damping) - [[patrol-instrument-cluster]] — **what the Patrol cluster expects on its inputs**: tach = 2 pulses/rev (verified by calibration), temp = NTC sender 2.1–2.9 kΩ cold → ~250 Ω at 90 °C; the 1 kHz PWM needle-flutter problem and the mitigation ladder (fixed-duty test → 20 kHz → hardware damping)
- [[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 - [[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 - [[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 (Controller A); 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** - [[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**
- [[reverse-lights-output]] — **2026-10-28**: reverse lamps from the board — relay coil between +12 V and `DO0`, diode across; DO0 = NPN sink (450 mA) behind PC817 from CH422G OC0 `(source: schematic)`; firmware follows the lever in R (`reverse` console, default ON) `(repo)`; untested in the car
- [[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
- [[vehicles]] — **one row per setup (2026-10-18)**: Patrol 1 (DDE 7796678 / 2006, `0x3B4` present), Patrol 2 (DDE 7794904 / 2004, no `0x3B4`, `0x38E` new), setup 3 pending; the ECU identity is a label read once by the firmware, behaviour adapts to the frames present — except the `2C 10` live-data identifiers, which are per DDE (Patrol 2: rail `00C2` only so far); capture checklist for a new car
## Concepts ## Concepts
- [[can-bus-integration]] — the core challenge; current firmware ID map flagged as placeholder, verification plan - [[can-bus-integration]] — the core challenge; current firmware ID map flagged as placeholder, verification plan
- [[driveline-speed-signals]] — **engine / turbine / output-shaft speeds**: turbine speed as physical proof of gear engagement, and the output-shaft field that is our **only road-speed source** (no DSC on this bus) — the feedback variable for a future cruise-control PoC, with the safety envelope that would require - [[driveline-speed-signals]] — **engine / turbine / output-shaft speeds**: turbine speed as physical proof of gear engagement, and the output-shaft field that is our **only road-speed source** (no DSC on this bus) — the feedback variable for a future cruise-control PoC, with the safety envelope that would require
- [[dual-controller-architecture]] — Controller A → UART1 + ESP-NOW, protocol v2 → Controller B (1.3" display + Patrol gauge outputs); A owns alerts and the gauge tunables (`cfg` console) - [[dual-controller-architecture]] — Main CTRL → UART1 + ESP-NOW, protocol v2 → Inst. Cluster (1.3" display + Patrol gauge outputs); A owns alerts and the gauge tunables (`cfg` console)
- [[obd-diagnostic-polling]] — **why boost / MAF / rail / injection / DTCs never appear on the sniffer** and how a tester gets them: Route A generic OBD-II mode 01 on `0x7DF` and Route B BMW KWP on `0x6F1` → `0x612` — **BOTH VERIFIED WORKING 2026-09-23** (minimal PID set, no boost PID, mode 09 silent; `1A 86` ident identifies the donor; DTCs read via mode 03), the capture-with-Launch procedure (still wanted for the `22 D1xx` live-data identifiers), and why polling is a transmit-on-the-bus design decision - [[obd-diagnostic-polling]] — **why boost / MAF / rail / injection / DTCs never appear on the sniffer** and how a tester gets them: Route A generic OBD-II mode 01 on `0x7DF` and Route B BMW KWP on `0x6F1` → `0x612` — **BOTH VERIFIED WORKING 2026-09-23** (minimal PID set, no boost PID, mode 09 silent; `1A 86` ident identifies the donor; DTCs read via mode 03), the capture-with-Launch procedure, **the `2C 10` live-data identifier table — per DDE since 2026-10-18** (Patrol 1's set read junk on Patrol 2), and why polling is a transmit-on-the-bus design decision
- [[ota-updates]] — **Controller A updates itself from Gitea releases**: tag `v*` → CI builds + signs (ECDSA P-256) → Settings → Updates (confirm dialog) or `ota install` (manual, parked, Wi-Fi) pulls over HTTPS from the public repo, verifies, flashes the idle slot, 30 s confirm-or-rollback; **verified end-to-end, from the screen since 2026-09-27 (now v0.1.5)**, release with `git push --follow-tags origin main`; dual-slot partition table; **Controller B card on the Updates page (2026-09-27)**: B pulls its own release, A pairs over the wire (`link pair`), hands over credentials in encrypted frames and triggers - details in B's wiki `controller-b-ota` - [[ota-updates]] — **Main CTRL updates itself from Gitea releases**: tag `v*` → CI builds + signs (ECDSA P-256) → Settings → Updates (confirm dialog) or `ota install` (manual, parked, Wi-Fi) pulls over HTTPS from the public repo, verifies, flashes the idle slot, 30 s confirm-or-rollback; **verified end-to-end, from the screen since 2026-09-27 (now v0.1.5)**, release with `git push --follow-tags origin main`; dual-slot partition table; **Inst. Cluster card on the Updates page (2026-09-27)**: B pulls its own release, A pairs over the wire (`link pair`), hands over credentials in encrypted frames and triggers - details in B's wiki `controller-b-ota`
## Synthesis ## Synthesis
@@ -45,5 +48,8 @@ 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 - [[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` - [[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-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
- [[launch-captures-2026-10-18-patrol-2]] — **Patrol 2's boost and battery identifiers** (2026-10-18 evening, Launch + CANNY): charge-air pressure `003A` (1 018 mbar idle → 1 186 on a blip), battery `002F` (14.0 V running → 12.7 V off); every identifier differs from Patrol 1's, the scalings fit unchanged; charge-air temperature still uncaptured
- [[can-capture-2026-10-18-patrol-2]] — **the second Patrol's bus (2026-10-18)**: every decoded frame identical to Patrol 1 (verified: rpm, pedal, torque, turbine, temps, run state, lever, target gear), but **no `0x3B4`** → ignition fallback from the `0x1D2` lever byte (`F0` = key off); the DDE is a different unit (7794904 / 2004 vs 7796678 / 2006, from the Launch's `1A 80`); engine-off torque is junk (812 Nm); Launch polls `00C2` (rail, ~330 bar); `0x1D0` bytes 4–5 look like the fuel counter
- [[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` - [[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 - [[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
+76 -12
View File
@@ -44,15 +44,15 @@ First real dump off the swap's bus, taken with the board's **own new raw-frame l
## [2026-09-21] update | .docs folder retired; UART spec moved to docs/; board photo ingested ## [2026-09-21] update | .docs folder retired; UART spec moved to docs/; board photo ingested
The repo's `.docs/` folder was deleted (user decision). `CAN_BUS_INTEGRATION.md` documented the dead placeholder IDs and an external transceiver the board does not need — superseded by [[can-id-candidates]] and [[can-bus-integration]]. `UART_PROTOCOL.md` (the packet spec, shared with Controller B) moved to `docs/UART_PROTOCOL.md` as the single copy; Controller B's duplicate was removed. The annotated board photo moved to `raw/` → [[esp32-s3-touch-lcd-5-intro-photo]]: confirms the terminal-block order, that GPIO 44 exits only as the RS485 A/B pair, and that one 120 Ω switch serves both CAN and RS485. Root `CLAUDE.md` corrected: verified CAN ID list replaces the placeholders, `TWAI_MODE_NORMAL` replaces "LISTEN_ONLY", UART TX is GPIO 44 (was written as 43), dummy-data references removed. The repo's `.docs/` folder was deleted (user decision). `CAN_BUS_INTEGRATION.md` documented the dead placeholder IDs and an external transceiver the board does not need — superseded by [[can-id-candidates]] and [[can-bus-integration]]. `UART_PROTOCOL.md` (the packet spec, shared with Inst. Cluster) moved to `docs/UART_PROTOCOL.md` as the single copy; Inst. Cluster's duplicate was removed. The annotated board photo moved to `raw/` → [[esp32-s3-touch-lcd-5-intro-photo]]: confirms the terminal-block order, that GPIO 44 exits only as the RS485 A/B pair, and that one 120 Ω switch serves both CAN and RS485. Root `CLAUDE.md` corrected: verified CAN ID list replaces the placeholders, `TWAI_MODE_NORMAL` replaces "LISTEN_ONLY", UART TX is GPIO 44 (was written as 43), dummy-data references removed.
**Missing source**: the schematic PDF (`ESP32-S3-Touch-LCD-5-Sch.pdf`) was in `.docs/` at the start of the 2026-09-21 session and was not on disk by the time of this cleanup (never git-tracked). Its net list was read earlier that session and is reflected in [[esp32-s3-touch-lcd-5b]]; re-download it into `raw/` — still on the sourcing wishlist in [[open-questions]]. **Missing source**: the schematic PDF (`ESP32-S3-Touch-LCD-5-Sch.pdf`) was in `.docs/` at the start of the 2026-09-21 session and was not on disk by the time of this cleanup (never git-tracked). Its net list was read earlier that session and is reflected in [[esp32-s3-touch-lcd-5b]]; re-download it into `raw/` — still on the sourcing wishlist in [[open-questions]].
Sibling wiki instantiated today at `../../ESP32-S3-LCD-1.3/wiki/` for Controller B (link, redundancy, gauge outputs). Cross-references from there use the text form `(sibling: 5B wiki → page)`. Sibling wiki instantiated today at `../../ESP32-S3-LCD-1.3/wiki/` for Inst. Cluster (link, redundancy, gauge outputs). Cross-references from there use the text form `(sibling: 5B wiki → page)`.
## [2026-09-21] update | Link protocol v2: ESP-NOW second transport, gear/rpm/alerts on the wire, tunables console ## [2026-09-21] update | Link protocol v2: ESP-NOW second transport, gear/rpm/alerts on the wire, tunables console
Firmware (not yet committed): shared header v2 with typed DATA/CONFIG frames; `Tunables` module (gauge calibration + alert thresholds in NVS, `cfg show|set|override|reset` on the USB console); `EspNowLink` broadcasts every frame alongside UART1 (radio now stays in STA mode — WiFiManager's off no longer calls `WIFI_OFF`); CAN driver publishes lever + target/engaged gear nibbles and rpm, and evaluates coolant/gearbox/battery/cooling-demand alerts against the tunables. Bench-verified with Controller B: both transports alive, every frame deduplicated, `cfg override rpm 2000` drove B's tach output at 133.3 Hz. `docs/UART_PROTOCOL.md` rewritten for v2. [[dual-controller-architecture]] and index updated. Build note: IDF 5.5's ESP-NOW send callback takes `wifi_tx_info_t*`; and the two repos must not be built concurrently (shared penv). Firmware (not yet committed): shared header v2 with typed DATA/CONFIG frames; `Tunables` module (gauge calibration + alert thresholds in NVS, `cfg show|set|override|reset` on the USB console); `EspNowLink` broadcasts every frame alongside UART1 (radio now stays in STA mode — WiFiManager's off no longer calls `WIFI_OFF`); CAN driver publishes lever + target/engaged gear nibbles and rpm, and evaluates coolant/gearbox/battery/cooling-demand alerts against the tunables. Bench-verified with Inst. Cluster: both transports alive, every frame deduplicated, `cfg override rpm 2000` drove B's tach output at 133.3 Hz. `docs/UART_PROTOCOL.md` rewritten for v2. [[dual-controller-architecture]] and index updated. Build note: IDF 5.5's ESP-NOW send callback takes `wifi_tx_info_t*`; and the two repos must not be built concurrently (shared penv).
## [2026-09-21] update | Gauge Tuning screen ## [2026-09-21] update | Gauge Tuning screen
@@ -70,7 +70,7 @@ User clipped a Google AI Mode conversation into `Clippings/` (Obsidian Web Clipp
User dropped `raw/BMW 335d.csv` and clipped page 1 of the e90post/6post thread "Extended BMW 335d PIDs for Torque" (DWR, 2009 335d = M57N2 on DDE7.3/EDC17CP09) → [[dwr-335d-torque-pids]]. **Every entry is a generic SAE J1979 mode-01 PID** (DWR says so in post 21; header `Auto` = `0x7DF`); nothing BMW-proprietary, nothing broadcast. Two revisions compared: the CSV in `raw/` is the corrected 2017 one (boost ×0.3125 = the J1979 0.03125 kPa/bit; fuel rate ×0.0938 lb/hr; post-#2's ×0.296 and ×5.64 were wrong); residual typos noted (`000031` for 0.0000305, one `+33`). Decoded his table back to SI with the J1979 byte positions. Consequence for us: the generic route is the **cheapest polling experiment** — one `01 00` supported-PID query on `0x7DF` tells whether our DDE answers EOBD on the PT-CAN and which PIDs it has — but the diesel-specific PIDs he relies on for boost (`70`), exhaust pressure (`73`), EGT (`78`), DPF (`7A`), NOx (`83`) are 2007+ J1979 additions an EDC16 almost certainly lacks `(unverified)`, and PID `0B` clips at 255 kPa. [[obd-diagnostic-polling]] restructured into Route A (generic, PID table, first test) and Route B (BMW `0x6F1`/`0x612`). Wishlist: DWR's Testo parameter list (post 175 of the Testo thread). Updated [[open-questions]] #7 + wishlist, index. User dropped `raw/BMW 335d.csv` and clipped page 1 of the e90post/6post thread "Extended BMW 335d PIDs for Torque" (DWR, 2009 335d = M57N2 on DDE7.3/EDC17CP09) → [[dwr-335d-torque-pids]]. **Every entry is a generic SAE J1979 mode-01 PID** (DWR says so in post 21; header `Auto` = `0x7DF`); nothing BMW-proprietary, nothing broadcast. Two revisions compared: the CSV in `raw/` is the corrected 2017 one (boost ×0.3125 = the J1979 0.03125 kPa/bit; fuel rate ×0.0938 lb/hr; post-#2's ×0.296 and ×5.64 were wrong); residual typos noted (`000031` for 0.0000305, one `+33`). Decoded his table back to SI with the J1979 byte positions. Consequence for us: the generic route is the **cheapest polling experiment** — one `01 00` supported-PID query on `0x7DF` tells whether our DDE answers EOBD on the PT-CAN and which PIDs it has — but the diesel-specific PIDs he relies on for boost (`70`), exhaust pressure (`73`), EGT (`78`), DPF (`7A`), NOx (`83`) are 2007+ J1979 additions an EDC16 almost certainly lacks `(unverified)`, and PID `0B` clips at 255 kPa. [[obd-diagnostic-polling]] restructured into Route A (generic, PID table, first test) and Route B (BMW `0x6F1`/`0x612`). Wishlist: DWR's Testo parameter list (post 175 of the Testo thread). Updated [[open-questions]] #7 + wishlist, index.
## [2026-09-21] update | `diag` console probe: Controller A can now send OBD-II requests ## [2026-09-21] update | `diag` console probe: Main CTRL can now send OBD-II requests
User decision: build the Route A probe. New module `src/modules/diag_probe.cpp` and a single sanctioned transmit function `CANDriver::transmit()` (single-shot frames, `CANTX,` console echo mirroring `CANRAW,`). Console: `diag pids` (mode-01 supported-PID bitmap scan, blocks 00/20/40…, per-responder summary with PID names), `diag pid <hex>` (one request, decoded for the Route A table incl. PID 70 boost and 78 EGT), `diag vin`, `diag ecu` (mode 09), `diag status`. ISO-TP single/first/consecutive frames reassembled with a `30 00 00` flow control to the responder's physical ID. Guards: one request in flight, refused for 3 s after any foreign tester frame (`0x7DF`/`0x7E0–7`/`0x6F1`), services 01 and 09 only. Console dispatch chained through `Tunables::setExtraCommandHandler()`. Built (1.49 MB) and flashed to COM11; bench check with no bus attached: `diag pids` sent `02 01 00` on `0x7DF`, the TWAI controller reported the single-shot frame un-ACKed, and the probe reported "not ACKed - no other node saw it" rather than blaming the ECU (the summary distinguishes un-ACKed from ACKed-but-silent). CAN-task warnings now take the serial lock so they no longer splice into `CANTX` lines. The wiki's "firmware never transmits" statements are now qualified on [[can-bus-integration]] and [[obd-diagnostic-polling]] (test-day procedure and the three possible outcomes written there). Root `CLAUDE.md` and `docs/UART_PROTOCOL.md` console section updated. Procedure rewritten as numbered steps with all four outcomes (un-ACKed / ACKed-silent / one responder / two responders) and the log-capture command. User decision: build the Route A probe. New module `src/modules/diag_probe.cpp` and a single sanctioned transmit function `CANDriver::transmit()` (single-shot frames, `CANTX,` console echo mirroring `CANRAW,`). Console: `diag pids` (mode-01 supported-PID bitmap scan, blocks 00/20/40…, per-responder summary with PID names), `diag pid <hex>` (one request, decoded for the Route A table incl. PID 70 boost and 78 EGT), `diag vin`, `diag ecu` (mode 09), `diag status`. ISO-TP single/first/consecutive frames reassembled with a `30 00 00` flow control to the responder's physical ID. Guards: one request in flight, refused for 3 s after any foreign tester frame (`0x7DF`/`0x7E0–7`/`0x6F1`), services 01 and 09 only. Console dispatch chained through `Tunables::setExtraCommandHandler()`. Built (1.49 MB) and flashed to COM11; bench check with no bus attached: `diag pids` sent `02 01 00` on `0x7DF`, the TWAI controller reported the single-shot frame un-ACKed, and the probe reported "not ACKed - no other node saw it" rather than blaming the ECU (the summary distinguishes un-ACKed from ACKed-but-silent). CAN-task warnings now take the serial lock so they no longer splice into `CANTX` lines. The wiki's "firmware never transmits" statements are now qualified on [[can-bus-integration]] and [[obd-diagnostic-polling]] (test-day procedure and the three possible outcomes written there). Root `CLAUDE.md` and `docs/UART_PROTOCOL.md` console section updated. Procedure rewritten as numbered steps with all four outcomes (un-ACKed / ACKed-silent / one responder / two responders) and the log-capture command.
@@ -80,7 +80,7 @@ First in-car test of the dual-controller rig: A reads the bus fine, B receives f
## [2026-09-22] query | Patrol cluster signal research - tach 2 ppr verified, temp sender curve, flutter plan ## [2026-09-22] query | Patrol cluster signal research - tach 2 ppr verified, temp sender curve, flutter plan
First day driving the real cluster from Controller B through the 2SK3069 low-side stage. Tach: needle tracked at double with ppr=4; user set ppr=2 -> tracks correctly (verified). 2 ppr matches an ECU-driven 4-cyl-style tach input (ZD30-era Y61 hint, unverified) rather than the TD42 alternator-W-terminal scheme. Temp gauge on IO8: needle flutters at temp_pwm_hz=1 kHz. Researched: stock Patrol sender is an NTC (2.1-2.9k @ 20C, 0.68-1k @ 50C, 236-260R @ 90C; patrol4x4/sensorgal), gauge is current-measuring; community PWM-gauge experience says flutter dies at ~40-50 kHz. Mitigation ladder filed: fixed-duty override test (data vs electrical), cfg set temp_hz 20000 (firmware clamp), then raise clamp / series drain resistor (~100-240R, also bounds full-on beyond-hot short) / gauge-side cap. Temp law must be re-derived after (FET inverts duty sense). Filed [[patrol-instrument-cluster]]; index updated. Earlier same day: [[canny-5-3-pico-gauge-drive]] hypothesis effectively confirmed by the needles moving through the FET; gauge-output disable bits found off during bench test (B console "disabled") - re-enabled via tuning screen. First day driving the real cluster from Inst. Cluster through the 2SK3069 low-side stage. Tach: needle tracked at double with ppr=4; user set ppr=2 -> tracks correctly (verified). 2 ppr matches an ECU-driven 4-cyl-style tach input (ZD30-era Y61 hint, unverified) rather than the TD42 alternator-W-terminal scheme. Temp gauge on IO8: needle flutters at temp_pwm_hz=1 kHz. Researched: stock Patrol sender is an NTC (2.1-2.9k @ 20C, 0.68-1k @ 50C, 236-260R @ 90C; patrol4x4/sensorgal), gauge is current-measuring; community PWM-gauge experience says flutter dies at ~40-50 kHz. Mitigation ladder filed: fixed-duty override test (data vs electrical), cfg set temp_hz 20000 (firmware clamp), then raise clamp / series drain resistor (~100-240R, also bounds full-on beyond-hot short) / gauge-side cap. Temp law must be re-derived after (FET inverts duty sense). Filed [[patrol-instrument-cluster]]; index updated. Earlier same day: [[canny-5-3-pico-gauge-drive]] hypothesis effectively confirmed by the needles moving through the FET; gauge-output disable bits found off during bench test (B console "disabled") - re-enabled via tuning screen.
## [2026-09-22] update | Temp gauge flutter resolved: temp_hz 1 kHz -> 20 kHz ## [2026-09-22] update | Temp gauge flutter resolved: temp_hz 1 kHz -> 20 kHz
@@ -110,9 +110,9 @@ The capture-with-Launch session, finally run (engine idling, our read-only seria
Tightened the live-data findings after checking the full capture: the Launch used only 1A/2C/22/23 - NO 10 (session), 27 (security), or 3E (tester-present). So self-polling a 2C value (e.g. rail pressure) needs only the 2C 10 15E0 define + 2C 10 00DF poll, no secret; the earlier 21-block NRCs (0x22/0x33) are a different mechanism and do not gate 2C. Corrected the "needs session/define handshake" wording in launch-capture-2026-09-23.md and obd-diagnostic-polling. Recorded the design decision (user, 2026-09-23): active polling, if built, lives behind a password-protected Diagnostics screen (authorized-tech gate, manual, refuses while scan tool connected, read-oriented services) - open-questions #12, and a project memory so the capability is not re-researched later. Tightened the live-data findings after checking the full capture: the Launch used only 1A/2C/22/23 - NO 10 (session), 27 (security), or 3E (tester-present). So self-polling a 2C value (e.g. rail pressure) needs only the 2C 10 15E0 define + 2C 10 00DF poll, no secret; the earlier 21-block NRCs (0x22/0x33) are a different mechanism and do not gate 2C. Corrected the "needs session/define handshake" wording in launch-capture-2026-09-23.md and obd-diagnostic-polling. Recorded the design decision (user, 2026-09-23): active polling, if built, lives behind a password-protected Diagnostics screen (authorized-tech gate, manual, refuses while scan tool connected, read-oriented services) - open-questions #12, and a project memory so the capability is not re-researched later.
## [2026-09-26] build | OTA updates for Controller A ## [2026-09-26] build | OTA updates for Main CTRL
Repartitioned A to dual OTA slots (2 x 7.9 MB, SPIFFS dropped, nvs/otadata offsets kept - tunables v150 survived the one-time USB flash on COM10, verified). New src/modules/ota_update.cpp + include/config/ota_config.h: manual `ota status|check|install|rollback` console; HTTPS pull from the (now public) Gitea repo's latest release, ECDSA P-256 signature over "patrol-a|version|sha256" checked before download, image hashed while streaming, parked gate before download and before slot switch, rollback via verifyRollbackLater() override + 30 s confirm. TLS trusts ISRG Root X1 + Root YR (both verified against the server chain). CI: .gitea/workflows/firmware.yml (main -> rolling unsigned pre-release main-latest; v* tag -> signed release with manifest.txt). Decisions: manual trigger (future Diagnostics screen), public repos instead of a device token, Controller B to be updated by A over ESP-NOW (wire is one-way). Wrote pages/ota-updates.md. Pending: BMW_NISSAN_FIRMWARE_SIGNING_KEY repo secret, enable repo Actions, first v* tag to test end-to-end. Repartitioned A to dual OTA slots (2 x 7.9 MB, SPIFFS dropped, nvs/otadata offsets kept - tunables v150 survived the one-time USB flash on COM10, verified). New src/modules/ota_update.cpp + include/config/ota_config.h: manual `ota status|check|install|rollback` console; HTTPS pull from the (now public) Gitea repo's latest release, ECDSA P-256 signature over "patrol-a|version|sha256" checked before download, image hashed while streaming, parked gate before download and before slot switch, rollback via verifyRollbackLater() override + 30 s confirm. TLS trusts ISRG Root X1 + Root YR (both verified against the server chain). CI: .gitea/workflows/firmware.yml (main -> rolling unsigned pre-release main-latest; v* tag -> signed release with manifest.txt). Decisions: manual trigger (future Diagnostics screen), public repos instead of a device token, Inst. Cluster to be updated by A over ESP-NOW (wire is one-way). Wrote pages/ota-updates.md. Pending: BMW_NISSAN_FIRMWARE_SIGNING_KEY repo secret, enable repo Actions, first v* tag to test end-to-end.
## [2026-09-26] build | OTA bring-up: Wi-Fi switch, ESP-NOW, memory ## [2026-09-26] build | OTA bring-up: Wi-Fi switch, ESP-NOW, memory
@@ -148,7 +148,7 @@ User asked to refactor the Settings and Gauge Tuning UX, save the Wi-Fi connecti
## [2026-09-26] ingest | Schematic re-downloaded; VOUT = H8 solder jumper (3V3 default / 5V) ## [2026-09-26] ingest | Schematic re-downloaded; VOUT = H8 solder jumper (3V3 default / 5V)
User asked whether VOUT becomes 5 V by "unsoldering the resistor". Re-fetched `ESP32-S3-Touch-LCD-5-Sch.pdf` into `raw/` (closes the wishlist item) → [[esp32-s3-touch-lcd-5-schematic]]. Answer: VOUT is net `I2C_VCC`, picked by **`H8`, a 3-pad solder jumper** (1 = 3V3, 2 = VOUT, 3 = 5V; "the default paste is 3V3"): open the 1–2 bridge, bridge 2–3, never all three. The terminal-block I2C lines are level-shifted (NDC7002N, 4.7 k pull-ups to `I2C_VCC`) so they follow the choice. 5 V rail is a SY8293 buck rated 2 A ("run the line at 2A"), screen ≈550 mA, so ≈1 A spare for a load such as Controller B `(unverified estimate)`; not on USB power. Also indexed: SD SPI pins (IO11/12/13, CS EXIO4), CAN IO15/16 and RS485 IO43/44 confirmed. Updated [[esp32-s3-touch-lcd-5b]], [[open-questions]] wishlist, index. User asked whether VOUT becomes 5 V by "unsoldering the resistor". Re-fetched `ESP32-S3-Touch-LCD-5-Sch.pdf` into `raw/` (closes the wishlist item) → [[esp32-s3-touch-lcd-5-schematic]]. Answer: VOUT is net `I2C_VCC`, picked by **`H8`, a 3-pad solder jumper** (1 = 3V3, 2 = VOUT, 3 = 5V; "the default paste is 3V3"): open the 1–2 bridge, bridge 2–3, never all three. The terminal-block I2C lines are level-shifted (NDC7002N, 4.7 k pull-ups to `I2C_VCC`) so they follow the choice. 5 V rail is a SY8293 buck rated 2 A ("run the line at 2A"), screen ≈550 mA, so ≈1 A spare for a load such as Inst. Cluster `(unverified estimate)`; not on USB power. Also indexed: SD SPI pins (IO11/12/13, CS EXIO4), CAN IO15/16 and RS485 IO43/44 confirmed. Updated [[esp32-s3-touch-lcd-5b]], [[open-questions]] wishlist, index.
## [2026-09-27] query | Open question 13 reviewed with the user: full fix committed, dots not gone ## [2026-09-27] query | Open question 13 reviewed with the user: full fix committed, dots not gone
@@ -195,14 +195,78 @@ Tag build died at the link step: `ModuleNotFoundError: No module named 'SCons.To
Second tag build (pioarduino core fork in the workflow) succeeded: release `v0.1.7` on Gitea at 18:28 with `firmware.bin` (1,722,464 B), `firmware.elf`, `manifest.txt` (target patrol-a, sha256 `a2949644…4c09`, ECDSA sig), built from `8e739fa`. Off-device check: downloaded binary's SHA-256 and size match the manifest. The bench board (dev build on COM14) could not `ota check` — Wi-Fi off and no saved network at that moment — so the first on-device install of v0.1.7 is the user's, from Settings → Updates. Expected on the board: "Version v0.1.7 is available", install with the screen lit and the progress bar, restart, `A v0.1.7` bottom-right; the Updates page then says up to date. Second tag build (pioarduino core fork in the workflow) succeeded: release `v0.1.7` on Gitea at 18:28 with `firmware.bin` (1,722,464 B), `firmware.elf`, `manifest.txt` (target patrol-a, sha256 `a2949644…4c09`, ECDSA sig), built from `8e739fa`. Off-device check: downloaded binary's SHA-256 and size match the manifest. The bench board (dev build on COM14) could not `ota check` — Wi-Fi off and no saved network at that moment — so the first on-device install of v0.1.7 is the user's, from Settings → Updates. Expected on the board: "Version v0.1.7 is available", install with the screen lit and the progress bar, restart, `A v0.1.7` bottom-right; the Updates page then says up to date.
## [2026-09-27] update | Controller B updates from A's screen: link_peer, two-way maintenance frames, Updates page with two cards ## [2026-09-27] update | Inst. Cluster updates from A's screen: link_peer, two-way maintenance frames, Updates page with two cards
Implemented A's half of B's OTA (design in B's wiki `controller-b-ota`). Shared `automotive_data.h` (+ new `link_secure.h`, both byte-identical in the two repos): `STATUS` 0x03 B → A, `PAIR` 0x04 A → B wire-only, `SECURE` 0x05 A → B (AES-256-GCM under the pairing key; inner `OTA_CMD` / `WIFI_CREDS`), `PACKET_MAX_PAYLOAD` 64 → 160, `PACKET_VERSION` unchanged (DATA/CONFIG bytes identical). New `src/modules/link_peer.cpp`: pairing key in NVS `linkpeer`, `link pair` sends the key ×3 over UART1 only (`UARTManager::sendWire()`), B's STATUS kept + logged, automatic push of the remembered Wi-Fi network to B (hash-compared, ≥ 15 s apart, FORGET when A forgets), `requestCheck/requestInstall` for the screen behind `Ota::isParked()` + A on Wi-Fi. `EspNowLink` gained a receive callback (IDF 5.5 `esp_now_recv_info_t`) and `sendTo()`; `WiFiManager::getSavedCredentials()` (for LinkPeer only, never printed). Settings → Updates rebuilt as two cards (Controller A / Controller B) that fit the 484 px page without scrolling. Bench: B heard within seconds (`link status`: MAC, `dev`, heap 234 KB), refusals correct; `link pair` cannot be confirmed because **no wire is connected on the bench** (B reports `uart silent`). Build notes: `pio` from PowerShell only (idf_tools refuses MSYS); first build after the B project reinstalls Arduino 3.3.3 and may fail once with a `TypeError` - rerun. Implemented A's half of B's OTA (design in B's wiki `controller-b-ota`). Shared `automotive_data.h` (+ new `link_secure.h`, both byte-identical in the two repos): `STATUS` 0x03 B → A, `PAIR` 0x04 A → B wire-only, `SECURE` 0x05 A → B (AES-256-GCM under the pairing key; inner `OTA_CMD` / `WIFI_CREDS`), `PACKET_MAX_PAYLOAD` 64 → 160, `PACKET_VERSION` unchanged (DATA/CONFIG bytes identical). New `src/modules/link_peer.cpp`: pairing key in NVS `linkpeer`, `link pair` sends the key ×3 over UART1 only (`UARTManager::sendWire()`), B's STATUS kept + logged, automatic push of the remembered Wi-Fi network to B (hash-compared, ≥ 15 s apart, FORGET when A forgets), `requestCheck/requestInstall` for the screen behind `Ota::isParked()` + A on Wi-Fi. `EspNowLink` gained a receive callback (IDF 5.5 `esp_now_recv_info_t`) and `sendTo()`; `WiFiManager::getSavedCredentials()` (for LinkPeer only, never printed). Settings → Updates rebuilt as two cards (Main CTRL / Inst. Cluster) that fit the 484 px page without scrolling. Bench: B heard within seconds (`link status`: MAC, `dev`, heap 234 KB), refusals correct; `link pair` cannot be confirmed because **no wire is connected on the bench** (B reports `uart silent`). Build notes: `pio` from PowerShell only (idf_tools refuses MSYS); first build after the B project reinstalls Arduino 3.3.3 and may fail once with a `TypeError` - rerun.
## [2026-09-27] verify | Controller B updated from A's console, end to end (details in B's wiki log) ## [2026-09-27] verify | Inst. Cluster updated from A's console, end to end (details in B's wiki log)
With the wire connected: pairing, credential push, check and install of B's first signed release `v0.1.0` all worked from A's `link` console; B rebooted and confirmed. A's side needed one cosmetic fix (missing separator in the "Controller B update: failed - <reason>" log line), rebuilt and flashed COM14. Left for the user: tap Check / Install on the Controller B card of Settings → Updates on the next B release and watch B's progress line. With the wire connected: pairing, credential push, check and install of B's first signed release `v0.1.0` all worked from A's `link` console; B rebooted and confirmed. A's side needed one cosmetic fix (missing separator in the "Inst. Cluster update: failed - <reason>" log line), rebuilt and flashed COM14. Left for the user: tap Check / Install on the Inst. Cluster card of Settings → Updates on the next B release and watch B's progress line.
## [2026-09-27] update | Wi-Fi chip and blinking alert banner on every screen; Driveline reds ## [2026-09-27] update | Wi-Fi chip and blinking alert banner on every screen; Driveline reds
User: show Wi-Fi on every screen (top-right) and give a sense of urgency when a threshold is crossed. New `status_overlay.cpp` on `lv_layer_top()`: Wi-Fi chip (fixed 150 px, LONG_DOT) top-right on all three screens - the shared header's back button moved 160 px left to make room; alert banner top-centre, red blinking at 2 Hz (colour toggle from tick, no lv_anim) naming the value (`COOLANT 104 °C HOT`, `GEARBOX OIL ...`, `GEAR MISMATCH`, `BATTERY 11.20 V LOW`), steady amber for `GEARBOX COOLING`; hidden with CAN off / ignition off. Driveline: chips row moved to y 60, crossed values and their titles go red (amber for cooling), gear mismatch turns the hero ring and gear letter red and the separate mismatch label is gone. Built and flashed COM14. Untested visually and untestable on the bench (alerts need CAN frames) - user to look at the car. User: show Wi-Fi on every screen (top-right) and give a sense of urgency when a threshold is crossed. New `status_overlay.cpp` on `lv_layer_top()`: Wi-Fi chip (fixed 150 px, LONG_DOT) top-right on all three screens - the shared header's back button moved 160 px left to make room; alert banner top-centre, red blinking at 2 Hz (colour toggle from tick, no lv_anim) naming the value (`COOLANT 104 °C HOT`, `GEARBOX OIL ...`, `GEAR MISMATCH`, `BATTERY 11.20 V LOW`), steady amber for `GEARBOX COOLING`; hidden with CAN off / ignition off. Driveline: chips row moved to y 60, crossed values and their titles go red (amber for cooling), gear mismatch turns the hero ring and gear letter red and the separate mismatch label is gone. Built and flashed COM14. Untested visually and untestable on the bench (alerts need CAN frames) - user to look at the car.
## [2026-09-28] update | No invented data: A starts with nothing valid and forgets everything when the bus stops
User: "if there is no info from CAN bus, no values should be shown". Until now `UARTManager::initializeDefaultData()` seeded 89.0 / 85.0 degC and 12.45 V with their valid flags SET, so a bench B (and a car with CAN off) showed plausible fake readings. Now the shared structure starts zeroed with `valid_flags = 0` and lever UNKNOWN; every field is valid only after a CAN frame filled it. `can_driver.cpp` gained `clearSharedData()`, called on CAN stop and on the bus-silence timeout (which already stopped the link) so stale values never come back marked valid. The `DEFAULT_*` block left the shared header (copied to B, `cmp`-identical). Driveline and B already key everything off the valid flags, so they show `--` / hidden needles. Flashed COM14; B's RX log now shows `Valid:0x00`. Released as v0.1.9 (v0.1.8, tagged minutes earlier, still carries the defaults - do not install it).
## [2026-09-28] update | Boards renamed Main CTRL / Inst. Cluster; "Sleep when the car is off" switch
User renamed Controller A → **Main CTRL** and Controller B → **Inst. Cluster** across both repos (comments, UI text, workflow names, wiki) and reworded the Updates page; committed here together with the sleep feature. New `power_manager.cpp` + Settings → System switch (NVS `sleep_en`, default OFF), see [[sleep-when-parked]]: deep sleep after 60 s of quiet CAN bus + idle touch + no update job, wake on CAN RX GPIO 16 (ext0, pull-up, TWAI stopped first). The switch travels to the Inst. Cluster as bit 7 of `out_enable` in CONFIG (no version bump). Console `sleep status | on | off | now`. Bench lesson the same evening: the switch was turned on with CAN on and no bus, so the Main CTRL slept a minute later and its USB-CDC port vanished (a deep-sleeping S3 has no USB) - only the reset button or a power cycle brings it back; touching the screen within the minute keeps it awake. Inst. Cluster side verified (see its log): sleep at 60 s of link silence, timer wake after exactly 60 s, 4 s probe with the panel dark, sleep again.
## [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.
## [2026-10-13] update | Road speed from the output shaft; Sport screen (torque + power gauges)
User requirements: road speed = output shaft × differential ratio 4.11:1 × tyre circumference, both numbers as settings under System; and a BMW-style "Sport screen" with two gauges, torque and hp (P(W) = Nm × rpm / 9.5488, hp = W / 745.7). Built as `vehicle.cpp` (final drive x100 + tyre mm in NVS, deferred write, `vehicle` console, speed and power maths) and `sport_screen.cpp` (two `lv_meter` gauges 0-600 Nm / 0-300 hp with arc fill, needle, 3 s peak-hold needle; rpm + ~speed below; Sport button on the Driveline). Settings gained a fourth tab, **Vehicle** (-/+ rows, live preview, Reset). The Driveline's bottom row now has four stats: torque, pedal, output (~rpm), speed (~km/h). The final drive 4.11:1 is recorded on [[nissan-patrol-swap]] (user); tyre size is still open (default 2440 mm = 265/70 R16, unverified), so [[open-questions]] #10 is half closed and every speed keeps the `~` of the provisional shaft factor (#8). Flashed to the Main CTRL on COM11 later the same day, together with the `sim` console (next entry).
## [2026-10-13] update | `sim` console: bench torque / rpm / shaft for the screens
User asked whether torque can be simulated to look at the Sport gauges without the bus; the existing `cfg override` only forces the Inst. Cluster's outputs. Added `bench_sim.cpp`: `sim torque <Nm> [rpm <n>] [shaft <rpm>]`, overlaid on the driveline snapshot with ignition on, shown as `IGN SIM` / SIMULATION on the screens, console only (no slider - user decision), never saved, off at boot. The first bench run of `sim torque 350 rpm 2500 shaft 1200` exposed a x10 slip in the speed maths (4.3 km/h for 1199 shaft rpm); fixed to 42.7 km/h, 122.9 hp checked against the formula, `sim` / `vehicle` commands verified on COM11, flashed.
## [2026-10-13] update | Sport gauges redrawn after the BMW photo; needle as a PhotoCraft image
The user shared a photo of the BMW iDrive Sport displays and wanted the gauges like it. Band rebuilt from stacked `lv_meter` arcs (dark red -> orange inward, bright rim, dark dividers, numbers inside the band, unit in the middle, name below, black background; Power left, Torque right). The needle went through three versions: plain line, a hand-drawn tapered wedge in the meter's draw hook, and finally an **image**: the user asked whether to draw PNGs in Photoshop, then pointed at PhotoCraft (storytold/photocraft, open-source Rust Photoshop clone with a built-in MCP server) - installed portable, its `photocraft-cli mcp` registered in Claude Code, and the needle drawn through it (gradient wedge + bright tip, two outer glows, exported `assets/needle.png`, source `assets/needle.pcraft`). `tools/png2lvgl.py` converts to `src/assets/needle_img.c`; `lv_meter_add_needle_img` rotates it. Flashed COM11 with `sim torque 350 rpm 2500` on for the user to judge.
## [2026-10-13] update | BMW gauge deconstructed element by element with the PhotoCraft MCP; dial face as an image
User: "deconstruct the gauge element by element using this new MCP". Opened the photo in PhotoCraft, perspective-cropped the screen straight (`assets/reference/bmw-screen-straight.png`), cut the Torque gauge and three zooms, fitted the rim circle and profiled the band radially and angularly. Findings (fractions of the outer radius): thin bright rim 0.985-1.0; a ruler ring 0.93-0.985 with ~5 fine rungs per cell between two bright lines; a dark gap; the cells ring 0.75-0.91, brightest orange at its inner edge fading to dark red outward, 16 cells with dark gaps, 5 bright spokes at the numbers; numbers at ~0.64 R; sweep ~230 degrees open at the bottom (the firmware had 270); needle from ~0.33 R with a lit tip. The photo's colours are unusable (glass reflection) - structure only. Rebuilt at 420 px as PhotoCraft layers from computed geometry (`assets/dial_geometry.json`, circles as boolean subpaths, 81 rungs and 15 gaps as polygons), exported `assets/dial.png`, source `assets/dial.pcraft`; the Sport screen now shows the image under an lv_meter that draws only numbers and the image needle. Gotcha found: PhotoCraft maps a shape gradient to the bbox of all subpaths including subtracted ones.
## [2026-10-18] ingest + build | Second Patrol's CAN captures; ignition without 0x3B4; the DDE read once (`EcuIdent`)
User: "I have a new patrol with bmw engine. The ECU is the same. I did collected some can bus logs using canny" — three CANNY logs (`raw/ingnition-only.txt`, `raw/engine-on.txt`, `raw/launch-diag-rail-pressure.txt`) → [[can-capture-2026-10-18-patrol-2]]. Offline analysis with the firmware's scalings: every decoded frame identical in layout and plausible in value; **`0x3B4` / `0x3B3` / `0x332` absent** (the firmware's only ignition source), `0x38E` new, `0x1B6` changed; the Launch's `1A 80` reads show a **different DDE** (7794904 / 2004-01-21 vs 7796678 / 2006-02-16); engine-off `TORQ_AVL` is junk (812 Nm); the Launch polled a new rail identifier `00C2`; `0x1D0` bytes 4–5 behave like a fuel counter. Then "How to differentiate between these different DDEs? Tomorrow I will have another setup" → the identity is a label (read once), behaviour adapts to the frames present; user's rule: save the part number at the first start, never re-check at boot, show UNKNOWN ECU until read. Built `(repo)`: ignition fallback from the `0x1D2` lever byte (`0x3B4` keeps precedence for 10 s after it is seen, source logged), torque gated on the run state (Sport + Driveline), `EcuIdent` (`1A 86` then `1A 80` through `DiagProbe`, NVS blobs, Settings → Vehicle line + Re-read ECU, `ecu show | dump | forget`, passive compare of a Launch's `1A 80` → ECU CHANGED?). Flashed to COM11; on the bench `ecu show` = UNKNOWN ECU, no transmit (CAN off). New page [[vehicles]] (one row per setup + capture checklist for tomorrow); [[can-id-candidates]] callout, [[obd-diagnostic-polling]] identifiers + ident layouts, [[open-questions]] #15, [[nissan-patrol-swap]] note.
## [2026-10-18] build | Live-data identifiers are per DDE: Engine data profiles keyed on the ECU identity
User, with the board on Patrol 2 for the first time: "The rail pressure is wrong. It shows nothing. The air intake temp shows some > 300 degree. The boost is static somewhere 2800 mBar. Also the output speed remains 0." Diagnosis from the logs already in `raw/`: Patrol 1's `2C 10 00DF/0091/16A8/0093` are addresses inside that DDE's software; the Launch polled `00C2` for rail on Patrol 2 and sent no `15E0` define. So the rule "the identity is a label" gets its one exception: `(repo)` the Engine data screen now carries a `PROFILES[]` table (part numbers → identifier set + provisional flags), selected through `EcuIdent::hasPart()`, installed into `DiagProbe` with the new `liveConfigure()` (`live_set_t`, 0 = slot never asked). Patrol 2's profile has rail `00C2` only (scale assumed ×0.03 — the Launch showed ~330 bar at idle); boost, charge-air temp and battery read "identifier not known for this ECU yet". No identified ECU or no profile → nothing is polled and the status line says why; the profile is re-evaluated every tick so the first identification takes effect on screen. The output-speed question stays open: every Patrol 2 log is stationary. Pages: [[obd-diagnostic-polling]] (per-DDE identifier table + callout), [[vehicles]] (rule 3, identifier column, checklist asks for a Launch session per value), [[open-questions]] #15, [[can-capture-2026-10-18-patrol-2]] consequence 5. Built; the board was in the car (no COM port), so not flashed from here yet.
## [2026-10-18] update | Patrol 2's own identification read: DDE 7796156 - 2006-05-17
User: "The actual reading is DDE 7796156 - 2006-05-17" (Settings → Vehicle, the board's first key-on on Patrol 2) — the `1A 86` read succeeded on this unit. Like Patrol 1 (7796678 on `1A 80` vs 7799764 on `1A 86`) the two blocks carry different part numbers; the Launch's `1A 80` says 7794904 / 2004-01-21. Both numbers are in the Patrol 2 `PROFILES[]` row `(repo)`; [[vehicles]] row, [[obd-diagnostic-polling]] table header and [[open-questions]] #15 updated. Rebuilt; flashing waits for the board to be back on USB.
## [2026-10-18] verify | Patrol 2 ident dumped over USB: E65 donor; profile firmware flashed
Board back on COM11 (dev build with the per-DDE profiles flashed, SUCCESS). `ecu show`: both blocks stored on Patrol 2 — `1A 86` 66 B part 7796156 / 2006-05-17 / VIN prefix **WBAGM21070 (E65 7-series)**, `1A 80` 31 B part 7794904 / 2004-01-21 (so this board's `1A 80` is answered here, unlike Patrol 1). `diag status`: 0 requests since boot. All four part numbers are in the Patrol 2 `PROFILES[]` row. Donor difference (E60 vs E65) recorded on [[vehicles]], [[nissan-patrol-swap]], [[open-questions]] #15 as the likely reason for the bus and identifier differences `(unverified)`.
## [2026-10-18] ingest + build | Patrol 2 boost `003A` and battery `002F` from two Launch captures; output shaft confirmed
User: "The output shaft is good now" (the earlier 0 was the stationary car) and two new CANNY logs with the Launch on Patrol 2, `raw/charge-air-pressure.txt` and `raw/battery.txt` → [[launch-captures-2026-10-18-patrol-2]]. The Launch polled `2C 10 00 3A` for charge-air pressure (raw 8 071–9 487: 1 018 mbar at idle, 1 186 at the top of a 2 553 rpm blip, decaying to ambient after key-off at ÷ 8) and `2C 10 00 2F` for battery (5 166–5 723: 14.0 V with the alternator, 12.7 V after the engine stop at × 0.002455). No define, no negatives. The Launch's displayed values were not noted, so both keep Patrol 1's scale as `(unverified scale)`. `(repo)` Patrol 2's `PROFILES[]` row = rail `00C2`, boost `003A`, battery `002F`, all provisional; charge-air temperature still "identifier not known". Pages: [[obd-diagnostic-polling]] table, [[vehicles]] row (shaft resolved), [[open-questions]] #15, index. Built; the board was off USB, flash pending.
## [2026-10-28] setup | Reverse lights from DO0 — relay on the isolated output, firmware follows the lever in R
User: "I need to control a relay from ESP32-S3-LCD-5B ... I have some 2N2222 transistors", then "When the R gear is selected I need to light the rear lights." Read the DO circuit off the schematic PDF text (`raw/ESP32-S3-Touch-LCD-5-Sch.pdf`): CH422G **OC0** (pin 8) → R24 100 Ω → PC817 T1 (anode 510 Ω to 3V3) → 1 kΩ → NPN power transistor T2, collector = `DOUT0`, emitter = board GND; OC1/T3/T4 the same for DO1. So the "isolated" outputs return through the board's GND, and OC0 LOW = output on. No 2N2222 needed (no spare native GPIO anyway). New page [[reverse-lights-output]] with the wiring (coil +12 V ↔ DO0, flyback diode, ≤ 450 mA). `(repo)` new `reverse_light.cpp`: lever == R on a live bus with ignition on → DO0 on, 10 Hz decision confirmed over 200 ms, written through the panel library's expander object (the backlight rewrites the cached OC register, so raw I2C would be undone during OTA), `reverse status | on | off | force on|off|auto`, default ON, no Settings row (System page full). [[esp32-s3-touch-lcd-5b]] I/O row updated, index. Not yet seen in the car.
+4 -1
View File
@@ -1,7 +1,7 @@
--- ---
type: synthesis type: synthesis
tags: [can-bus, reverse-engineering, e60, research] tags: [can-bus, reverse-engineering, e60, research]
updated: 2026-07-17 updated: 2026-10-18
--- ---
# E60/E65 CAN ID Candidates (Research Results) # E60/E65 CAN ID Candidates (Research Results)
@@ -26,6 +26,9 @@ Findings from the 2026-07-15 deep-research run (95 claims extracted from ~15 sou
## The map (replaces the firmware's placeholder IDs) ## The map (replaces the firmware's placeholder IDs)
> [!warning] 2026-10-18 — the map holds on a SECOND Patrol, but `0x3B4` is not there
> [[can-capture-2026-10-18-patrol-2]]: a different DDE unit (7794904 / 2004 vs 7796678 / 2006) broadcasts every ID below byte-for-byte the same; rpm, pedal, torque, turbine, coolant, run state, gearbox temp, lever and target gear all decode correctly `(verified)`. **But `0x3B4`, `0x3B3` and `0x332` (the 5-s trio) are absent** on that bus, `0x38E` is new and `0x1B6` changed — the difference is which modules are wired, not the ECU. Ignition therefore has a fallback: the `0x1D2` lever byte (`0xF0` = key off, any lever code = key on) `(verified timing)`, used whenever no `0x3B4` has been seen for 10 s `(repo)`. `0x0A8` `TORQ_AVL` holds a junk value with the key on and the engine off (812 Nm there, 245 Nm here) — gate it on `ST_ENGINE_RUN`. One row per setup: [[vehicles]].
| Signal | CAN ID | Bytes | Scaling | Sender | Rate | Confidence | | Signal | CAN ID | Bytes | Scaling | Sender | Rate | Confidence |
|--------|--------|-------|---------|--------|------|------------| |--------|--------|-------|---------|--------|------|------------|
| Coolant temp | **0x1D0** | byte 0 | °C = raw − 48 | DME/DDE | 100 ms | **Very high** — verified verbatim in E65 docs, present in E90-gen DBC, confirmed live on a real E60 545i, E60 tool32 table lists 0x1D0 "Motordaten" from DDE1 (diesel!), and the [[e60-vfl-can-codes-xlsx]] sheet shows 0x7A→74 °C on a real E60 VFL (raw−48 checks out) | | Coolant temp | **0x1D0** | byte 0 | °C = raw − 48 | DME/DDE | 100 ms | **Very high** — verified verbatim in E65 docs, present in E90-gen DBC, confirmed live on a real E60 545i, E60 tool32 table lists 0x1D0 "Motordaten" from DDE1 (diesel!), and the [[e60-vfl-can-codes-xlsx]] sheet shows 0x7A→74 °C on a real E60 VFL (raw−48 checks out) |
+2 -2
View File
@@ -6,7 +6,7 @@ updated: 2026-09-22
# CANNY 5.3 pico vs ESP32-S3: driving the Patrol cluster # CANNY 5.3 pico vs ESP32-S3: driving the Patrol cluster
Why the user's old CANNY-based setup moves the Patrol tach and our ESP32 (Controller B, IO7) does not. Researched 2026-09-22 after the first in-car test of the dual-controller rig: temp needle parked mid-scale, tach dead ([[dual-controller-architecture]]). Why the user's old CANNY-based setup moves the Patrol tach and our ESP32 (Inst. Cluster, IO7) does not. Researched 2026-09-22 after the first in-car test of the dual-controller rig: temp needle parked mid-scale, tach dead ([[dual-controller-architecture]]).
## The working reference setup `(verified)` ## The working reference setup `(verified)`
@@ -48,7 +48,7 @@ ESP32 IOx ──[R ~1k]── G/B N-MOSFET (logic-level, e.g. 2N7002/AO3400) o
- If the cluster input turns out to have no internal pull-up, add an external ~4.7–10 kΩ to +12 V. - If the cluster input turns out to have no internal pull-up, add an external ~4.7–10 kΩ to +12 V.
- On hand (2026-09-22): a **2SK3069** (N-ch, 60 V / 75 A, 4 V-drive class) — hugely oversized but suitable; planned for the tach channel with 220 Ω gate series + 10 kΩ gate pulldown `(source: alltransistors.com 2SK3069)`. - On hand (2026-09-22): a **2SK3069** (N-ch, 60 V / 75 A, 4 V-drive class) — hugely oversized but suitable; planned for the tach channel with 220 Ω gate series + 10 kΩ gate pulldown `(source: alltransistors.com 2SK3069)`.
- **Never** connect the 12 V-pulled gauge line directly to an ESP32 pin, including in open-drain mode — the pin is not 12 V tolerant. - **Never** connect the 12 V-pulled gauge line directly to an ESP32 pin, including in open-drain mode — the pin is not 12 V tolerant.
- Grounds must be common: cluster GND ↔ Controller B GND. - Grounds must be common: cluster GND ↔ Inst. Cluster GND.
## Open items ## Open items
+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]]
+3 -1
View File
@@ -139,7 +139,9 @@ Still worth logging **`0x1A2` alongside `0x0BA`** in the same capture: turbine
### Raw counts → km/h ### Raw counts → km/h
Still needs numbers nobody has written down. The 6HP26**X** measures its output shaft **upstream of the transfer case**, so the conversion depends on the swap's driveline: **Firmware since 2026-10-13 `(repo)`**: `~km/h = shaft rpm ÷ final drive × tyre circumference × 60 ÷ 1000`, with final drive 4.11:1 (user) and the tyre circumference as a setting (default 2440 mm, unverified) on Main CTRL's Settings → Vehicle page; shown on the Driveline and the Sport screen. The `~` is inherited from the shaft factor below.
Still needs numbers nobody has written down for the transfer case. The 6HP26**X** measures its output shaft **upstream of the transfer case**, so the conversion depends on the swap's driveline:
- BMW transfer case retained → rear output ~1:1, math unaffected - BMW transfer case retained → rear output ~1:1, math unaffected
- Transfer case deleted, straight to the Patrol driveline → also fine - Transfer case deleted, straight to the Patrol driveline → also fine
+6 -6
View File
@@ -9,27 +9,27 @@ updated: 2026-09-27
The system is two ESP32-S3 boards linked by UART **and ESP-NOW** (repo, protocol v2 since 2026-09-21): The system is two ESP32-S3 boards linked by UART **and ESP-NOW** (repo, protocol v2 since 2026-09-21):
``` ```
BMW M57N CAN bus ──▶ Controller A ──UART1 + ESP-NOW, 5 Hz──▶ Controller B ──▶ Patrol tach + temp gauge BMW M57N CAN bus ──▶ Main CTRL ──UART1 + ESP-NOW, 5 Hz──▶ Inst. Cluster ──▶ Patrol tach + temp gauge
(this repo: (ESP32-S3-LCD-1.3, (this repo: (ESP32-S3-LCD-1.3,
5" 1024×600 display) 1.3" round display, gauge outputs) 5" 1024×600 display) 1.3" round display, gauge outputs)
``` ```
- **Controller A** — [[esp32-s3-touch-lcd-5b]]: listens to the CAN bus, renders the main UI, and re-broadcasts a compact sensor packet over UART1 (GPIO 43/44, 115200 baud) at 5 Hz. - **Main CTRL** — [[esp32-s3-touch-lcd-5b]]: listens to the CAN bus, renders the main UI, and re-broadcasts a compact sensor packet over UART1 (GPIO 43/44, 115200 baud) at 5 Hz.
- **Controller B** — ESP32-S3-Touch-LCD-1.3: a secondary display fed purely by that UART stream. Lives in a sibling repo (`bmw-patrol/` parent directory). - **Inst. Cluster** — ESP32-S3-Touch-LCD-1.3: a secondary display fed purely by that UART stream. Lives in a sibling repo (`bmw-patrol/` parent directory).
## Link protocol v2 (repo, 2026-09-21) ## Link protocol v2 (repo, 2026-09-21)
`0xAA | 0x02 | type | length | payload | XOR | 0x55`, identical on UART1 (GPIO 44 → SP3485 → `485_A`/`485_B`) and ESP-NOW broadcast (channel 1). DATA frames (lever, target/engaged gear nibbles, rpm, temps, battery, alert bitmap, valid flags) every 200 ms; CONFIG frames (`link_config_t`: Patrol gauge calibration + alert thresholds, edited on A via the `cfg` serial console and stored in NVS) on change and every 5 s. Alerts are decided here; B only renders them. Spec: `docs/UART_PROTOCOL.md`. Bench-verified with both transports live and B deduplicating every frame `(verified 2026-09-21)`. `0xAA | 0x02 | type | length | payload | XOR | 0x55`, identical on UART1 (GPIO 44 → SP3485 → `485_A`/`485_B`) and ESP-NOW broadcast (channel 1). DATA frames (lever, target/engaged gear nibbles, rpm, temps, battery, alert bitmap, valid flags) every 200 ms; CONFIG frames (`link_config_t`: Patrol gauge calibration + alert thresholds, edited on A via the `cfg` serial console and stored in NVS) on change and every 5 s. Alerts are decided here; B only renders them. Spec: `docs/UART_PROTOCOL.md`. Bench-verified with both transports live and B deduplicating every frame `(verified 2026-09-21)`.
**ESP-NOW and Wi-Fi share the radio** `(verified 2026-09-26)`. When A joins a Wi-Fi network (for OTA), its channel follows the AP (seen: 6, 9, 11) and B hops to find it; ESP-NOW kept running (6,410 frames, 0 failed). Until 2026-09-26 the Wi-Fi code powered the radio off on connect/disconnect (`WiFi.disconnect(true)`), which silently killed ESP-NOW and left B on the wire only — fixed, and `EspNowLink::send()` now re-initialises ESP-NOW if the driver drops it. Planned: **Controller B's firmware updates will travel from A over ESP-NOW** (bidirectional, unlike the one-way wire) → [[ota-updates]]. **ESP-NOW and Wi-Fi share the radio** `(verified 2026-09-26)`. When A joins a Wi-Fi network (for OTA), its channel follows the AP (seen: 6, 9, 11) and B hops to find it; ESP-NOW kept running (6,410 frames, 0 failed). Until 2026-09-26 the Wi-Fi code powered the radio off on connect/disconnect (`WiFi.disconnect(true)`), which silently killed ESP-NOW and left B on the wire only — fixed, and `EspNowLink::send()` now re-initialises ESP-NOW if the driver drops it. Planned: **Inst. Cluster's firmware updates will travel from A over ESP-NOW** (bidirectional, unlike the one-way wire) → [[ota-updates]].
**A keeps the ESP-NOW channel stable (v0.1.5, 2026-09-27)** `(repo)`: Wi-Fi auto-reconnect is off. A tries the remembered network once at boot and once after a drop, then parks the radio back on channel 1 — an endless reconnect (e.g. driving away from home Wi-Fi) would keep hopping channels under the link to B. Scans happen only when someone opens the Wi-Fi page or taps Scan. **A keeps the ESP-NOW channel stable (v0.1.5, 2026-09-27)** `(repo)`: Wi-Fi auto-reconnect is off. A tries the remembered network once at boot and once after a drop, then parks the radio back on channel 1 — an endless reconnect (e.g. driving away from home Wi-Fi) would keep hopping channels under the link to B. Scans happen only when someone opens the Wi-Fi page or taps Scan.
Controller B's side of this (receiver, ESP-NOW channel hopping, gauge outputs, bench wiring) is documented in the sibling wiki: `../../ESP32-S3-LCD-1.3/wiki/pages/controller-link.md` and `patrol-gauge-outputs.md`. Inst. Cluster's side of this (receiver, ESP-NOW channel hopping, gauge outputs, bench wiring) is documented in the sibling wiki: `../../ESP32-S3-LCD-1.3/wiki/pages/controller-link.md` and `patrol-gauge-outputs.md`.
## Why it matters for the wiki ## Why it matters for the wiki
Any change to what data we extract from the [[can-bus-integration]] ripples into this packet **and** into Controller B's parser — both ends must move together: edit `include/protocol/automotive_data.h` here, bump `PACKET_VERSION`, copy the header byte-identical to B (B rejects other versions). Any change to what data we extract from the [[can-bus-integration]] ripples into this packet **and** into Inst. Cluster's parser — both ends must move together: edit `include/protocol/automotive_data.h` here, bump `PACKET_VERSION`, copy the header byte-identical to B (B rejects other versions).
## Related ## Related
+4 -4
View File
@@ -6,7 +6,7 @@ updated: 2026-09-27
# Waveshare ESP32-S3-Touch-LCD-5B # Waveshare ESP32-S3-Touch-LCD-5B
Controller A of the [[dual-controller-architecture]] — the main in-cabin display. SKU 28151, the 1024×600 capacitive-touch variant of the LCD-5 family. Primary reference: [[esp32-s3-touch-lcd-5b-waveshare-wiki]]. Main CTRL of the [[dual-controller-architecture]] — the main in-cabin display. SKU 28151, the 1024×600 capacitive-touch variant of the LCD-5 family. Primary reference: [[esp32-s3-touch-lcd-5b-waveshare-wiki]].
## Specs (source: waveshare-wiki) ## Specs (source: waveshare-wiki)
@@ -22,7 +22,7 @@ Controller A of the [[dual-controller-architecture]] — the main in-cabin displ
- Draw: ~450 mA @ 5 V (~2.3 W) - Draw: ~450 mA @ 5 V (~2.3 W)
- Remaining caveat: automotive transient/load-dump spikes (ISO 7637) can exceed 36 V `(unverified)` → [[open-questions]] - Remaining caveat: automotive transient/load-dump spikes (ISO 7637) can exceed 36 V `(unverified)` → [[open-questions]]
- **Power path** (source: [[esp32-s3-touch-lcd-5-schematic]]): VIN → 1N5822 reverse diode + SMAJ36CA TVS → SY8293 buck (2 A, "run the line at 2A") → 5 V rail → 3.3 V LDO. Screen alone ≈550 mA @ 5 V. - **Power path** (source: [[esp32-s3-touch-lcd-5-schematic]]): VIN → 1N5822 reverse diode + SMAJ36CA TVS → SY8293 buck (2 A, "run the line at 2A") → 5 V rail → 3.3 V LDO. Screen alone ≈550 mA @ 5 V.
- **VOUT terminal = `I2C_VCC`, selected by solder jumper `H8`** (pad 1 = 3V3, pad 2 = VOUT, pad 3 = 5V; factory bridge 1–2 = 3.3 V). For 5 V: open 1–2, bridge 2–3, never all three. The external SDA/SCL are level-shifted (NDC7002N + 4.7 kΩ pull-ups to `I2C_VCC`), so the I2C lines follow. Headroom for a load on VOUT@5 V from the 12 V input ≈1 A `(unverified estimate)` — enough to power Controller B. Not on USB-only power. - **VOUT terminal = `I2C_VCC`, selected by solder jumper `H8`** (pad 1 = 3V3, pad 2 = VOUT, pad 3 = 5V; factory bridge 1–2 = 3.3 V). For 5 V: open 1–2, bridge 2–3, never all three. The external SDA/SCL are level-shifted (NDC7002N + 4.7 kΩ pull-ups to `I2C_VCC`), so the I2C lines follow. Headroom for a load on VOUT@5 V from the 12 V input ≈1 A `(unverified estimate)` — enough to power Inst. Cluster. Not on USB-only power.
> [!warning] Operating temperature 0–65 °C (source: waveshare-wiki) > [!warning] Operating temperature 0–65 °C (source: waveshare-wiki)
> Tight for a car: sub-zero winters and sun-baked dashboards both fall outside spec. → [[open-questions]] > Tight for a car: sub-zero winters and sun-baked dashboards both fall outside spec. → [[open-questions]]
@@ -39,8 +39,8 @@ Controller A of the [[dual-controller-architecture]] — the main in-cabin displ
| Interface | Details | | Interface | Details |
|-----------|---------| |-----------|---------|
| RS485 | SP3485, auto TX/RX direction; terminal block used for UART1 → Controller B, GPIO 43/44, 115200 baud `(repo)` | | RS485 | SP3485, auto TX/RX direction; terminal block used for UART1 → Inst. Cluster, GPIO 43/44, 115200 baud `(repo)` |
| Isolated I/O | Optocoupler digital in 5–36 V (dry/wet contact), open-drain out sinking 450 mA/ch — could read ignition-on or drive a relay later | | Isolated I/O | Optocoupler digital in 5–36 V (dry/wet contact) — DI0/DI1 read the diff locks ([[diff-lock-inputs]]); outputs DO0/DO1 = NPN power transistor (450 mA sink, emitter on board GND) behind a PC817 from CH422G OC0/OC1 — DO0 drives the reverse-light relay ([[reverse-lights-output]]) `(source: schematic)` |
| I2C | Terminal block SDA/SCL, level-shifted to `I2C_VCC` (= VOUT, 3.3 V or 5 V via `H8`); CH422G expander occupies 0x20–0x27 & 0x30–0x3F, GT911 touch at 0x5D — avoid these addresses | | I2C | Terminal block SDA/SCL, level-shifted to `I2C_VCC` (= VOUT, 3.3 V or 5 V via `H8`); CH422G expander occupies 0x20–0x27 & 0x30–0x3F, GT911 touch at 0x5D — avoid these addresses |
| RTC | PCF85063 + CR927 coin cell | | RTC | PCF85063 + CR927 coin cell |
| TF card | SPI: MOSI IO11, SCK IO12, MISO IO13; SD_CS via CH422G EXIO4 (source: schematic) | | TF card | SPI: MOSI IO11, SCK IO12, MISO IO13; SD_CS via CH422G EXIO4 (source: schematic) |
+4 -2
View File
@@ -1,7 +1,7 @@
--- ---
type: entity type: entity
tags: [vehicle, swap, project-context] tags: [vehicle, swap, project-context]
updated: 2026-07-17 updated: 2026-10-18
--- ---
# Nissan Patrol M57N Swap # Nissan Patrol M57N Swap
@@ -12,6 +12,7 @@ The target vehicle (verified — user, 2026-07-15): a **Nissan Patrol** receivin
- Gearbox: **ZF 6HP26X** (verified — user, 2026-07-17). The "X" is the xDrive output variant — same internal gearset as the 6HP26, different output housing/shaft to drive a transfer case. Ratios: 4.171 / 2.340 / 1.521 / 1.143 / 0.867 / 0.691. - Gearbox: **ZF 6HP26X** (verified — user, 2026-07-17). The "X" is the xDrive output variant — same internal gearset as the 6HP26, different output housing/shaft to drive a transfer case. Ratios: 4.171 / 2.340 / 1.521 / 1.143 / 0.867 / 0.691.
- **This dates the donor**: M57N + xDrive means **E60/E61, not E65** — the 7-series never took that combination. → [[open-questions]] #2 - **This dates the donor**: M57N + xDrive means **E60/E61, not E65** — the 7-series never took that combination. → [[open-questions]] #2
- Final drive (differential) ratio: **4.11:1** (user, 2026-10-13). Tyre rolling circumference: not stated yet; the firmware defaults to 2440 mm (a 265/70 R16, `(unverified)` for this car) and both numbers are editable on Main CTRL's Settings → Vehicle page `(repo)`.
> [!question] Was the BMW transfer case retained? > [!question] Was the BMW transfer case retained?
> Open, and it blocks road-speed display. The EGS measures the gearbox output shaft **upstream of the transfer case**, so the raw→km/h conversion depends on what sits downstream: > Open, and it blocks road-speed display. The EGS measures the gearbox output shaft **upstream of the transfer case**, so the raw→km/h conversion depends on what sits downstream:
@@ -19,13 +20,14 @@ The target vehicle (verified — user, 2026-07-15): a **Nissan Patrol** receivin
> - **Deleted, coupled straight to the Patrol driveline** → also fine > - **Deleted, coupled straight to the Patrol driveline** → also fine
> - **A Patrol transfer case in the path** → its ratio enters the calculation, **and changes with high/low range** — road speed would become range-dependent, which the firmware would have to know about > - **A Patrol transfer case in the path** → its ratio enters the calculation, **and changes with high/low range** — road speed would become range-dependent, which the firmware would have to know about
> >
> Also still needed for km/h: the Patrol's **final drive ratio** and **tyre size**. → [[driveline-speed-signals]], [[open-questions]] #10/#11 > Also needed for km/h: the Patrol's **final drive ratio** (4.11:1, user 2026-10-13) and **tyre size** (still open). The firmware now computes `~km/h = shaft rpm ÷ 4.11 × circumference` on the Driveline and Sport screens `(repo)`; the `~` stays until the shaft factor (#8) and the tyre are confirmed. → [[driveline-speed-signals]], [[open-questions]] #8/#10/#11
## Why this matters for research ## Why this matters for research
- The M57-into-Patrol swap is popular (especially in Australia and the Middle East), so swap-community forums likely contain solved CAN-ID lists and gauge projects for exactly this drivetrain. `(unverified)` → [[can-bus-integration]] - The M57-into-Patrol swap is popular (especially in Australia and the Middle East), so swap-community forums likely contain solved CAN-ID lists and gauge projects for exactly this drivetrain. `(unverified)` → [[can-bus-integration]]
- The bus the display taps is essentially a **BMW island in a Nissan vehicle**: only the modules the swap harness retains (DDE, EGS, possibly others) are broadcasting. Nissan-side electronics are not on this bus. **Confirmed by absence**: no DSC/CAS traffic appears, which is why there is no wheel-speed message and why the gearbox output shaft is our only road-speed source. → [[driveline-speed-signals]] - The bus the display taps is essentially a **BMW island in a Nissan vehicle**: only the modules the swap harness retains (DDE, EGS, possibly others) are broadcasting. Nissan-side electronics are not on this bus. **Confirmed by absence**: no DSC/CAS traffic appears, which is why there is no wheel-speed message and why the gearbox output shaft is our only road-speed source. → [[driveline-speed-signals]]
- Patrol generation, swap-harness maker (or DIY), and which BMW modules were retained are still unknown → [[open-questions]]. - Patrol generation, swap-harness maker (or DIY), and which BMW modules were retained are still unknown → [[open-questions]].
- **There is more than one Patrol (2026-10-18).** A second Patrol with the same M57N carries a different DDE unit and a differently populated bus (no `0x3B4`), and a third setup is expected; the firmware now labels each setup by its DDE identification and adapts to the frames present → [[vehicles]], [[can-capture-2026-10-18-patrol-2]]. Patrol 2's donor is an **E65 7-series** (VIN prefix WBAGM21070 from its `1A 86`), Patrol 1's an E60 530d.
## Related ## Related
+28 -5
View File
@@ -1,12 +1,12 @@
--- ---
type: concept type: concept
tags: [can-bus, dde, egs, diagnostics, kwp2000, uds, obd, design-decision, rail-pressure] tags: [can-bus, dde, egs, diagnostics, kwp2000, uds, obd, design-decision, rail-pressure]
updated: 2026-09-23 updated: 2026-10-18
--- ---
# OBD / Diagnostic Polling # OBD / Diagnostic Polling
Why some values never appear on the sniffer, how a scan tool gets them, and what it would take for Controller A to do the same. Several pages have linked here since July ([[can-id-candidates]], [[open-questions]] #7); the page was created on the [[google-ai-dde7m57-pids]] ingest, 2026-09-21. Why some values never appear on the sniffer, how a scan tool gets them, and what it would take for Main CTRL to do the same. Several pages have linked here since July ([[can-id-candidates]], [[open-questions]] #7); the page was created on the [[google-ai-dde7m57-pids]] ingest, 2026-09-21.
## Broadcast vs polled ## Broadcast vs polled
@@ -59,7 +59,7 @@ The [[dwr-335d-torque-pids]] source is a worked, gauge-checked set of J1979 mode
| `02 01 73` / `78` / `7A` / `83` | — | exhaust pressure / EGT / DPF ΔP / NOx — same caveat; DPF/SCR rows are meaningless on an M57N anyway | | `02 01 73` / `78` / `7A` / `83` | — | exhaust pressure / EGT / DPF ΔP / NOx — same caveat; DPF/SCR rows are meaningless on an M57N anyway |
- **First test = the `01 00` bitmap query.** One frame on `0x7DF` with the engine running (no scan tool attached) answers both open points at once: does this DDE speak EOBD on the PT-CAN at all, and which PIDs does it offer. No reply → the DDE serves EOBD on K-line (or not on this bus) and only Route B remains. - **First test = the `01 00` bitmap query.** One frame on `0x7DF` with the engine running (no scan tool attached) answers both open points at once: does this DDE speak EOBD on the PT-CAN at all, and which PIDs does it offer. No reply → the DDE serves EOBD on K-line (or not on this bus) and only Route B remains.
- **Implemented on Controller A (2026-09-21) `(repo)`** as the `diag` console command — see *Firmware: the `diag` probe* below. The whole test is `diag pids` typed on the USB console. - **Implemented on Main CTRL (2026-09-21) `(repo)`** as the `diag` console command — see *Firmware: the `diag` probe* below. The whole test is `diag pids` typed on the USB console.
- Route A cannot give fault codes beyond generic mode `03` DTCs (P0xxx) — BMW-specific codes need Route B. - Route A cannot give fault codes beyond generic mode `03` DTCs (P0xxx) — BMW-specific codes need Route B.
## Route B — BMW proprietary (KWP2000 on `0x6F1` → `0x612`) — **VERIFIED WORKING (2026-09-23)** ## Route B — BMW proprietary (KWP2000 on `0x6F1` → `0x612`) — **VERIFIED WORKING (2026-09-23)**
@@ -89,7 +89,7 @@ This depends on the DDE variant, which is still open ([[open-questions]] #2, [[b
## Firmware: the `diag` probe `(repo, 2026-09-21)` ## Firmware: the `diag` probe `(repo, 2026-09-21)`
Controller A now has **one** transmit path onto the PT-CAN: `CANDriver::transmit()`, called only by `src/modules/diag_probe.cpp`. It sends nothing on its own; every frame is typed by a human on the USB console. Main CTRL now has **one** transmit path onto the PT-CAN: `CANDriver::transmit()`, called only by `src/modules/diag_probe.cpp`. It sends nothing on its own; every frame is typed by a human on the USB console.
| Command | What it sends | What it prints | | Command | What it sends | What it prints |
|---|---|---| |---|---|---|
@@ -123,12 +123,35 @@ 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. 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. 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`) — PER DDE
> [!warning] The identifiers belong to one DDE software, not to the M57N `(verified 2026-10-18)`
> With the board on Patrol 2 (DDE 7794904) and Patrol 1's set in the firmware, the Engine data screen showed **no rail pressure, a flat "2800 mbar" boost and a charge-air temperature above 300 °C** (user). The Launch, which re-reads `1A 80` on every cycle precisely to pick its data set, polled **`00C2`** for rail pressure on that car instead of `00DF`. So `2C 10 <id>` is an address inside each unit's software (the "define" `15 E0` was not seen on Patrol 2 either). The firmware now keeps **one identifier set per DDE part number** (`(repo)` `engine_screen.cpp` `PROFILES[]`, keyed by `EcuIdent`) and asks nothing for a slot it has no identifier for. Every value on a new DDE must be captured with the Launch again (recipe below).
| Value | DDE 7796678 / 7799764 (Patrol 1) | DDE 7794904 / 7796156 (Patrol 2) | Scaling | Status |
|---|---|---|---|---|
| One-time define sent by the Launch | `15E0` | none seen | — | — |
| Rail pressure, actual | `00DF` | `00C2` | bar = raw × 0.03 | Patrol 1 `(verified 2026-09-23)`, two points; Patrol 2 `(unverified)` — raw 11 016–11 304 at idle = 330–339 bar at the same scale, the Launch showed "rail pressure" while polling it (label/value not noted) |
| Charge-air pressure, actual (boost, absolute) | `0091` | **`003A`** | mbar = raw ÷ 8 | Patrol 1 `(unverified)` one point, engine off; Patrol 2 `(unverified scale)` — 1 018 mbar idle → 1 186 on a rev blip, physically right, Launch value not noted ([[launch-captures-2026-10-18-patrol-2]]) |
| Charge-air temperature | `16A8` | not captured | °C = raw × 0.01 − 15 | `(unverified)` one point, engine off |
| Battery voltage | `0093` | **`002F`** | V = raw × 0.002455 | Patrol 1 `(unverified)` one point; Patrol 2 `(unverified scale)` — 14.0 V running, 12.7 V after the engine stop, Launch value not noted ([[launch-captures-2026-10-18-patrol-2]]) |
Evidence: [[launch-capture-2026-09-23]], [[launch-captures-2026-10-07]], [[can-capture-2026-10-18-patrol-2]], [[launch-captures-2026-10-18-patrol-2]]. Each provisional scaling needs one more capture at a different operating point; the remaining empty Patrol 2 cell (charge-air temperature) needs one Launch session. Note how every identifier moved between the two DDEs while the scalings stayed the same — expect the same on setup 3.
## ECU identification (`1A 80` / `1A 86`) `(verified 2026-09-23 / 2026-10-18)`
The Launch re-reads `1A 80` on every cycle and both Patrols' DDEs answer it in their default state (31 / 37-byte replies); our own probe's `1A 80` was silent on Patrol 1 on 2026-09-23 while `1A 86` answered with 65 bytes. Observed layouts (field names `(unverified)`): `1A 80` → BCD part number at payload bytes 4–7, BCD date YY MM DD at 15–17; `1A 86` → ASCII `"@B892524 "`, date at 11–13, three 6-byte BCD part-number fields from byte 16, VIN prefix at 53–62. The firmware stores both blocks once per setup ([[vehicles]], `(repo)` `EcuIdent`) and compares the Launch's `1A 80` passively.
## 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 profile's define once per start (Patrol 1: `2C 10 15 E0`), then its reads in turn. **Since 2026-10-18 the identifier set is chosen per identified DDE** (table above): an unidentified ECU or one without a profile polls nothing and the status line says so; a slot without an identifier reads "identifier not known for this ECU yet". Provisional scalings are tagged on screen and every value shows its raw number and identifier for calibration against the Launch. A password can still come with a future Diagnostics screen for anything beyond these reads.
## Beyond the probe `(repo)` ## 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). - **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).
- A continuous poller (Route A or B) would reuse the same transmit path with a fixed request list: one request per ≥100 ms, one identifier at a time, only while no scan tool is connected, never a session-control or write service. Still a design decision: a request storm or a malformed frame can disturb the DDE/EGS. - A continuous poller (Route A or B) would reuse the same transmit path with a fixed request list: one request per ≥100 ms, one identifier at a time, only while no scan tool is connected, never a session-control or write service. Still a design decision: a request storm or a malformed frame can disturb the DDE/EGS.
- **What Route B self-polling actually requires (settled 2026-09-23):** just the `2C 10 15 E0` define then the `2C 10 <id>` poll — **no diagnostic session (`10`), no security access (`27`), no tester-present (`3E`)**, proven from the full Launch capture ([[launch-capture-2026-09-23]]). The `21`-block NRCs (0x22/0x33) that earlier looked like a session/security wall are a *different mechanism* and do not gate the `2C` path. `2C` is not strictly read-only (it writes a dynamic-identifier definition — harmless), so it stays out of the probe whitelist by policy. - **What Route B self-polling actually requires (settled 2026-09-23):** just the `2C 10 15 E0` define then the `2C 10 <id>` poll — **no diagnostic session (`10`), no security access (`27`), no tester-present (`3E`)**, proven from the full Launch capture ([[launch-capture-2026-09-23]]). The `21`-block NRCs (0x22/0x33) that earlier looked like a session/security wall are a *different mechanism* and do not gate the `2C` path. `2C` is not strictly read-only (it writes a dynamic-identifier definition — harmless), so it stays out of the probe whitelist by policy.
- **Design decision — the "Diagnostics" screen (2026-09-23):** if active polling is ever built, it lives behind a **password-protected Diagnostics screen** on Controller A (authorized-technician gate), triggered manually, only while no scan tool is connected, read-oriented services only. This is the deliberate on/off switch for transmit-on-the-bus — not a background poller. Not built yet; captured here so the capability and its guard rails are not re-researched later. - **Design decision — the "Diagnostics" screen (2026-09-23):** if active polling is ever built, it lives behind a **password-protected Diagnostics screen** on Main CTRL (authorized-technician gate), triggered manually, only while no scan tool is connected, read-oriented services only. This is the deliberate on/off switch for transmit-on-the-bus — not a background poller. Not built yet; captured here so the capability and its guard rails are not re-researched later.
- Protocol v2 dropped the `fault_codes` field in favour of the alert bitmap ([[dual-controller-architecture]]); polled values would need new DATA fields. - Protocol v2 dropped the `fault_codes` field in favour of the alert bitmap ([[dual-controller-architecture]]); polled values would need new DATA fields.
- The same request path would also be the only way to read DTCs (service `0x18`/`0x19`, variant-dependent) → [[open-questions]] #7. - The same request path would also be the only way to read DTCs (service `0x18`/`0x19`, variant-dependent) → [[open-questions]] #7.
+5 -3
View File
@@ -1,7 +1,7 @@
--- ---
type: synthesis type: synthesis
tags: [meta, todo] tags: [meta, todo]
updated: 2026-09-27 updated: 2026-10-18
--- ---
# Open Questions # Open Questions
@@ -20,11 +20,13 @@ The research frontier. Answering any of these should trigger updates across the
9. **Is a cruise-control PoC worth pursuing, and under what safety envelope?** The bus architecture supports it natively (the DME arbitrates torque requests from the EGS and ACC; `ST_CLCTR_V` reports which regulator has control). But actuation means **transmitting frames that command engine torque**, with unknown checksum/alive-counter algorithms and **no brake-pedal signal on this bus** to build the standard cancel interlock from. Design decision, not a research question. → [[driveline-speed-signals]] 9. **Is a cruise-control PoC worth pursuing, and under what safety envelope?** The bus architecture supports it natively (the DME arbitrates torque requests from the EGS and ACC; `ST_CLCTR_V` reports which regulator has control). But actuation means **transmitting frames that command engine torque**, with unknown checksum/alive-counter algorithms and **no brake-pedal signal on this bus** to build the standard cancel interlock from. Design decision, not a research question. → [[driveline-speed-signals]]
10. **What are the Patrol's final drive ratio and tyre size?** Needed to turn output-shaft rpm into road speed. Swap-specific — not in any donor documentation. → [[nissan-patrol-swap]] 10. **What are the Patrol's final drive ratio and tyre size?** *Half answered 2026-10-13.* Final drive **4.11:1** (user). Tyre size still open — the firmware defaults to a 2440 mm rolling circumference (265/70 R16) and the Settings → Vehicle page lets the user correct it `(repo)`. Road speed is shown as `~km/h` until this, #8 and #11 are settled. → [[nissan-patrol-swap]]
15. **Patrol 2's bus (2026-10-18): who sent the 5-s trio on Patrol 1, and what are `0x38E` / `0x1B6` / `00C2`?** [[can-capture-2026-10-18-patrol-2]]. `0x332` / `0x3B3` / `0x3B4` came every 5 s from one transmitter on Patrol 1 (battery field always invalid) and are absent on Patrol 2 — a retained donor module (CAS? cluster? junction box?) or an EWS-delete difference `(unverified)`; the answer tells which cars keep `0x3B4`'s ignition nibble (the firmware no longer depends on it). `0x38E` (2 B, 10 Hz) is new on Patrol 2, `0x1B6` changed content and rate. The Launch's `2C 10 00 C2` reads 11 016–11 304 raw at idle while showing rail pressure (330–339 bar at the `00DF` scale) — setpoint or actual? Ask the user for the Launch's label next time. **Same evening, with the board on Patrol 2:** Patrol 1's live identifiers returned junk there (no rail, boost flat at 2800 mbar, charge-air temp > 300 °C) — the `2C 10` identifiers are per DDE software, so Patrol 2 needs its own Launch sessions — done the same evening for **boost `003A` and battery `002F`** ([[launch-captures-2026-10-18-patrol-2]]); **charge-air temperature is the one still missing**, and the Launch's own readings for all three Patrol 2 values are still wanted to confirm the (Patrol 1) scales → [[obd-diagnostic-polling]]. The output speed that stayed at 0 was the stationary car: the user confirmed it reads correctly when rolling. Also open: which modules are on each car's PT-CAN ([[vehicles]]). Patrol 2's `1A 86` block was read by the board the same evening: part **7796156**, 2006-05-17 (the Launch's `1A 80` says 7794904 / 2004-01-21 — as on Patrol 1 the two blocks carry different numbers and dates, hardware vs software `(unverified)`); full dump on [[vehicles]]: three part numbers 7796156 / 7796157 / 7789877 and **VIN prefix WBAGM21070 = E65 7-series**, so the two donors are different cars (E60 530d vs E65), which may be the reason for both the missing 5-s trio and the different `2C 10` addresses `(unverified)`.
## Design decisions (parked, not blocking) ## 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 Controller A 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 ## Project context
+6 -6
View File
@@ -6,7 +6,7 @@ updated: 2026-09-27
# OTA Firmware Updates # OTA Firmware Updates
How Controller A updates itself from this repo's Gitea releases, why each piece is the way it is, and what is still to do (Controller B). Built 2026-09-26. Design decisions by the user are marked **(decision)**. How Main CTRL updates itself from this repo's Gitea releases, why each piece is the way it is, and what is still to do (Inst. Cluster). Built 2026-09-26. Design decisions by the user are marked **(decision)**.
## The pipeline ## The pipeline
@@ -16,7 +16,7 @@ git push tag vX.Y.Z ──► Gitea Actions (.gitea/workflows/firmware.yml, runn
sign "patrol-a|vX.Y.Z|<sha256>" with secret BMW_NISSAN_FIRMWARE_SIGNING_KEY sign "patrol-a|vX.Y.Z|<sha256>" with secret BMW_NISSAN_FIRMWARE_SIGNING_KEY
release vX.Y.Z: firmware.bin + firmware.elf + manifest.txt release vX.Y.Z: firmware.bin + firmware.elf + manifest.txt
│ public repo, HTTPS, no token │ public repo, HTTPS, no token
Controller A Settings → Updates → Install ◄──┘ (or `ota install`; parked, Wi-Fi joined) Main CTRL Settings → Updates → Install ◄──┘ (or `ota install`; parked, Wi-Fi joined)
GET /api/v1/repos/art/ESP32-S3-Touch-LCD-5B/releases/latest → tag GET /api/v1/repos/art/ESP32-S3-Touch-LCD-5B/releases/latest → tag
GET /releases/download/<tag>/manifest.txt → verify signature FIRST GET /releases/download/<tag>/manifest.txt → verify signature FIRST
GET /releases/download/<tag>/firmware.bin → idle slot, hashed while streaming GET /releases/download/<tag>/firmware.bin → idle slot, hashed while streaming
@@ -50,11 +50,11 @@ Known quirk: `ota status` shows the *other* slot's "built" date from the framewo
## Decisions and why ## Decisions and why
- **Manual trigger only (decision, 2026-09-26).** An install ends in a reboot, which blanks Controller B's gauges; nothing checks or installs in the background. - **Manual trigger only (decision, 2026-09-26).** An install ends in a reboot, which blanks Inst. Cluster's gauges; nothing checks or installs in the background.
- **On the Settings screen, behind a confirm dialog (decision, 2026-09-27)** — replacing the earlier plan to put it on the password-gated Diagnostics screen. Settings → Updates shows installed vs latest and a **Check for updates** button; **Install vX** appears only when the latest release differs and asks "Install vX? The screen goes dark for about a minute… only while parked". The user chose a confirm dialog over a PIN: the parked gate and the signature already guard the dangerous parts; a PIN can come with the Diagnostics screen ([[open-questions]] #12). The `ota` console stays for bench work and `rollback`. - **On the Settings screen, behind a confirm dialog (decision, 2026-09-27)** — replacing the earlier plan to put it on the password-gated Diagnostics screen. Settings → Updates shows installed vs latest and a **Check for updates** button; **Install vX** appears only when the latest release differs and asks "Install vX? The screen goes dark for about a minute… only while parked". The user chose a confirm dialog over a PIN: the parked gate and the signature already guard the dangerous parts; a PIN can come with the Diagnostics screen ([[open-questions]] #12). The `ota` console stays for bench work and `rollback`.
- **Parked gate** `(repo)`: refused if engine rpm > 0 / run state running or starting, output shaft turning, or lever in a drive gear. A silent bus (>2 s no frames: ignition off, bench) counts as parked. Checked before the download **and again** before the slot switch. `ota check` is exempt (read-only). - **Parked gate** `(repo)`: refused if engine rpm > 0 / run state running or starting, output shaft turning, or lever in a drive gear. A silent bus (>2 s no frames: ignition off, bench) counts as parked. Checked before the download **and again** before the slot switch. `ota check` is exempt (read-only).
- **HTTPS pull from a public repo (decision).** Both repos were made public 2026-09-26 so the device needs **no token** — the same reasoning as `parking_solution`'s public releases mirror: a read token in shipped firmware leaks with the device. History was scanned before/after going public: no secrets, no full VIN (only the 10-char prefix in ident logs), no SSIDs `(verified 2026-09-26)`. - **HTTPS pull from a public repo (decision).** Both repos were made public 2026-09-26 so the device needs **no token** — the same reasoning as `parking_solution`'s public releases mirror: a read token in shipped firmware leaks with the device. History was scanned before/after going public: no secrets, no full VIN (only the 10-char prefix in ident logs), no SSIDs `(verified 2026-09-26)`.
- **Signed images (decision).** HTTPS only proves the file came from the server; the ECDSA P-256 signature proves it came from our CI key. The signed statement is `target|version|sha256`, so a Controller B image can't be installed on A even with a shared key, and the manifest version can't be swapped. The firmware contains no secrets, so public binaries are fine — **keep it that way**: the future Diagnostics-screen password must be a salted hash in NVS, never a literal in source. - **Signed images (decision).** HTTPS only proves the file came from the server; the ECDSA P-256 signature proves it came from our CI key. The signed statement is `target|version|sha256`, so a Inst. Cluster image can't be installed on A even with a shared key, and the manifest version can't be swapped. The firmware contains no secrets, so public binaries are fine — **keep it that way**: the future Diagnostics-screen password must be a salted hash in NVS, never a literal in source.
- **TLS trust = Let's Encrypt roots, not the leaf** `(verified 2026-09-26)`: the server chain is leaf (SAN `git.infra.msai.al`) → YR2 → Root YR (cross-signed by ISRG Root X1). Both ISRG Root X1 (to 2035) and Root YR (to 2045) are embedded in `include/config/ota_config.h`, and each verifies the chain alone. Leaf certs rotate ~90 days — never pin them. The framework's mbedtls has `MBEDTLS_HAVE_TIME_DATE` off, so no NTP is needed (and cert dates aren't checked; the signature is the real guarantee). - **TLS trust = Let's Encrypt roots, not the leaf** `(verified 2026-09-26)`: the server chain is leaf (SAN `git.infra.msai.al`) → YR2 → Root YR (cross-signed by ISRG Root X1). Both ISRG Root X1 (to 2035) and Root YR (to 2045) are embedded in `include/config/ota_config.h`, and each verifies the chain alone. Leaf certs rotate ~90 days — never pin them. The framework's mbedtls has `MBEDTLS_HAVE_TIME_DATE` off, so no NTP is needed (and cert dates aren't checked; the signature is the real guarantee).
- **Rollback**: the framework bootloader has `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y`, but Arduino's `initArduino()` marks a new image valid *before* `setup()`. `ota_update.cpp` overrides `verifyRollbackLater()` → the image stays PENDING_VERIFY until `Ota::tick()` confirms it after 30 s. Consequence: **power off within 30 s of an update's first boot = back to the old version** (by design). - **Rollback**: the framework bootloader has `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y`, but Arduino's `initArduino()` marks a new image valid *before* `setup()`. `ota_update.cpp` overrides `verifyRollbackLater()` → the image stays PENDING_VERIFY until `Ota::tick()` confirms it after 30 s. Consequence: **power off within 30 s of an update's first boot = back to the old version** (by design).
@@ -106,9 +106,9 @@ Wi-Fi must be joined first — Settings → Wi-Fi (remembered from then on) or `
- **Joining Wi-Fi killed ESP-NOW**: the Wi-Fi task used `WiFi.disconnect(true)` (true = radio off), which drops ESP-NOW; B then ran on the wire only. Now `WiFi.disconnect()`, and `EspNowLink::send()` re-initialises ESP-NOW if the driver ever drops it. Verified: joined Personal1 (channel 9), ESP-NOW 195 sent / 0 failed. - **Joining Wi-Fi killed ESP-NOW**: the Wi-Fi task used `WiFi.disconnect(true)` (true = radio off), which drops ESP-NOW; B then ran on the wire only. Now `WiFi.disconnect()`, and `EspNowLink::send()` re-initialises ESP-NOW if the driver ever drops it. Verified: joined Personal1 (channel 9), ESP-NOW 195 sent / 0 failed.
- `showConnectionResult()` took the LVGL lock with a 0 ms try-lock, ignored the result, and touched widgets that are NULL off the Settings screen — now waits for the lock and null-checks. It still showed **no success feedback** on screen (user: "a disaster UX") — resolved by the hand-coded Settings screen in v0.1.5 ([[open-questions]] #14). - `showConnectionResult()` took the LVGL lock with a 0 ms try-lock, ignored the result, and touched widgets that are NULL off the Settings screen — now waits for the lock and null-checks. It still showed **no success feedback** on screen (user: "a disaster UX") — resolved by the hand-coded Settings screen in v0.1.5 ([[open-questions]] #14).
## Controller B (implemented 2026-09-27) ## Inst. Cluster (implemented 2026-09-27)
The 2026-09-26 idea (A streams B's image over ESP-NOW) was dropped for a **pull design** the user chose on 2026-09-27: B downloads its own signed release (target `patrol-b`, B's repo, same key) over Wi-Fi; A only hands over the credentials and the trigger. Full design, verification state and the first-pairing procedure live in B's wiki (`../../ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md`). A's side: `src/modules/link_peer.cpp` - `link pair` sends a random key over the UART wire once (never by radio; both repos are public), B's `STATUS` frames (version, phase, progress) arrive over ESP-NOW unicast, credentials and OTA commands go to B inside AES-256-GCM `SECURE` frames, and Settings → Updates gained a **Controller B** card (Installed / Latest / Check / Install) next to Controller A's. B's install is behind the same parking gate plus "A must be on Wi-Fi" (same AP ⇒ same channel ⇒ B's progress frames keep arriving). Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. **Verified end-to-end on the bench 2026-09-27**: `link pair` over the wire, automatic credential push, `link ota check` / `link ota install` from A's console took B from `dev` to `v0.1.0` (1,248,432 B in ~50 s), B rebooted, reported `v0.1.0` and confirmed itself after 30 s. The Updates-page buttons share the same request functions but have not been tapped yet. The 2026-09-26 idea (A streams B's image over ESP-NOW) was dropped for a **pull design** the user chose on 2026-09-27: B downloads its own signed release (target `patrol-b`, B's repo, same key) over Wi-Fi; A only hands over the credentials and the trigger. Full design, verification state and the first-pairing procedure live in B's wiki (`../../ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md`). A's side: `src/modules/link_peer.cpp` - `link pair` sends a random key over the UART wire once (never by radio; both repos are public), B's `STATUS` frames (version, phase, progress) arrive over ESP-NOW unicast, credentials and OTA commands go to B inside AES-256-GCM `SECURE` frames, and Settings → Updates gained a **Inst. Cluster** card (Installed / Latest / Check / Install) next to Main CTRL's. B's install is behind the same parking gate plus "A must be on Wi-Fi" (same AP ⇒ same channel ⇒ B's progress frames keep arriving). Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. **Verified end-to-end on the bench 2026-09-27**: `link pair` over the wire, automatic credential push, `link ota check` / `link ota install` from A's console took B from `dev` to `v0.1.0` (1,248,432 B in ~50 s), B rebooted, reported `v0.1.0` and confirmed itself after 30 s. The Updates-page buttons share the same request functions but have not been tapped yet.
## Related ## Related
+1 -1
View File
@@ -6,7 +6,7 @@ updated: 2026-09-22
# Patrol instrument cluster — signal expectations # Patrol instrument cluster — signal expectations
What the target vehicle's cluster ([[nissan-patrol-swap]]) needs on its tach and temp inputs, from the first day of driving it with Controller B's outputs through the low-side FET stage ([[canny-5-3-pico-gauge-drive]]). Patrol generation still unidentified — Y60/GQ vs Y61/GU matters for gauge internals → [[open-questions]]. What the target vehicle's cluster ([[nissan-patrol-swap]]) needs on its tach and temp inputs, from the first day of driving it with Inst. Cluster's outputs through the low-side FET stage ([[canny-5-3-pico-gauge-drive]]). Patrol generation still unidentified — Y60/GQ vs Y61/GU matters for gauge internals → [[open-questions]].
## Tachometer ## Tachometer
+54
View File
@@ -0,0 +1,54 @@
---
type: concept
tags: [hardware, patrol, outputs, ch422g, wiring, relay, reverse]
updated: 2026-10-28
---
# Reverse lights from the board (DO0)
The Patrol's reverse lamps have no signal of their own after the swap; the gear lever position is on the bus (`0x1D2` byte 0, `(verified)` → [[can-id-candidates]]). The Main CTRL lights them through a 12 V relay on its isolated output **DO0** whenever the lever is in **R** (user request, 2026-10-28).
## The output circuit `(source: [[esp32-s3-touch-lcd-5-schematic]], sheet 1 "DI/DO", read from the PDF text)`
- CH422G **OC0** (pin 8) → R24 100 Ω → PC817 (T1) LED, anode via R74 510 Ω to 3V3. **OC0 LOW = LED on.**
- PC817 phototransistor → R58 1 kΩ → base of NPN power transistor T2 (R60 10 kΩ base pull-down). T2 collector = terminal **`DOUT0`** (silkscreen `DO0`), **emitter = board GND**, C102 100 nF across.
- DO1 is the same circuit on OC1 / T3 / T4 / `DOUT1`.
- Waveshare's rating: 5–36 V, **450 mA sink per channel** (source: [[esp32-s3-touch-lcd-5b-waveshare-wiki]]). The transistor's part number is not readable in the schematic text `(unverified)`.
> [!warning] "Isolated" only between the expander and the transistor
> There is no `DO_COM` terminal: the load current flows out of DO0 into the board's **GND**. The optocoupler isolates the CH422G from the output transistor, not the output from the board's ground. Fine here, because the board already shares vehicle ground for CAN and for the diff-lock inputs — but never return the relay current anywhere but the board's `GND`/vehicle ground.
The chip powers up with OC0 high (LED off), and the panel library writes that default again at every display init `(source: ESP32_IO_Expander, esp_io_expander_ch422g.c reset())`, so the lamps are off from reset until the firmware decides otherwise.
## Wiring
| Relay pin (ISO mini relay) | Connect to |
|---|---|
| 86 (coil +) | +12 V — the same supply that feeds the board's `VIN` (switched with the ignition is best) |
| 85 (coil −) | **`DO0`** |
| flyback diode (1N4007 or similar) | across 85/86, cathode (stripe) on the +12 V side |
| 30 / 87 | the reverse-lamp feed, as the lamp circuit needs |
- A standard 30 A mini relay coil is 70–90 Ω → 130–200 mA at 14 V, well inside 450 mA `(unverified: typical values)`.
- Not from USB power: the coil must return into the board's GND terminal with the 7–36 V supply on VIN.
- A ready-made 5 V relay module with an opto input also works: DO0 to its active-low `IN`, module VCC from `VOUT` set to 5 V (`H8` jumper, [[esp32-s3-touch-lcd-5b]]), grounds common.
- The 2N2222 the user has is not needed on this board (no spare native GPIO). It would be the right part to drive a relay from an Inst. Cluster GPIO instead: GPIO → 1 kΩ → base, emitter to GND, coil between +12 V and the collector, same diode.
## Firmware `(repo, 2026-10-28)`
`reverse_light.cpp`: every 100 ms, DO0 on ⇔ lever == R **and** CAN running **and** ignition on — the same snapshot the Driveline's big letter shows. A change is applied after two equal decisions (200 ms) so a one-frame glitch cannot chatter the relay. The CAN driver forgets the lever 2 s after the bus goes silent, and the key-off lever code `0xF0` clears ignition, so both turn the lamps off. The output is written through the panel library's expander object (OC0 = pin 8), never raw I2C: the backlight writes the library's cached OC register back to the chip on every on/off, so a raw write would be undone during an OTA install.
Console: `reverse status | on | off | force on|off|auto`. `on/off` is saved (NVS `revlight_en`, default ON); `force` drives DO0 regardless of the lever for the wiring check, never saved, ends itself after 60 s. No Settings row — the System page is full at four rows.
## Check in the car
1. Bench first: `reverse force on` → relay clicks, lamps on; `reverse force off` → off. `reverse status` shows the DO0 state and write counters.
2. Car, key on, engine off: move the lever to R — lamps on within ~0.3 s, `[reverse] lights ON (lever R)` on the console; back to N/P — off.
3. Key off in R: lamps must go off (lever code `0xF0` clears ignition).
4. Watch for relay chatter when the lever passes through R between P and D; if any, raise `CONFIRM` in the module.
Status: **not yet seen in the car** `(unverified)`.
## Related
[[esp32-s3-touch-lcd-5b]] · [[esp32-s3-touch-lcd-5-schematic]] · [[diff-lock-inputs]] · [[can-id-candidates]] · [[nissan-patrol-swap]]
+49
View File
@@ -0,0 +1,49 @@
---
type: entity
tags: [vehicles, patrol, dde, ident, can-bus]
updated: 2026-10-18
---
# Vehicles — one row per setup this firmware has met
The project started on one Patrol; on 2026-10-18 the user brought logs from a **second Patrol** ([[can-capture-2026-10-18-patrol-2]]) and announced a third setup for 2026-10-19. The two DDEs turned out to be different units that broadcast identical frames; what differed was **which other modules sit on the PT-CAN**. Two rules follow `(design, 2026-10-18)`:
1. **The ECU identity is a label.** The firmware reads it once (KWP `1A 86`, then `1A 80`), stores it, shows it on Settings → Vehicle, and never asks again until Re-read ECU (`(repo)` `EcuIdent`). It tags captures and this table; no broadcast scaling depends on it.
2. **Behaviour adapts to the frames present**, never to the ECU name: e.g. ignition from `0x3B4` when that frame is on the bus, from the `0x1D2` lever byte otherwise.
3. **Exception, found the same evening: the diagnostic live-data identifiers are per DDE software.** Patrol 1's `2C 10` set read junk on Patrol 2 (no rail, boost flat at 2800 mbar, charge-air temp above 300 °C); the Launch polls `00C2` there instead of `00DF`. The Engine data screen therefore keys its identifier set on the stored part number and asks nothing it has no identifier for → [[obd-diagnostic-polling]] table.
| Setup | DDE `1A 80` (part number, date) | DDE `1A 86` | IDs on the bus | Live-data identifiers (`2C 10`) | Differences | Evidence |
|---|---|---|---|---|---|---|
| **Patrol 1** (July – October 2026; the board's first car) | **7796678**, 2006-02-16 (from the Launch's reads in `raw/boost.txt`) | 7799764 / 7799765 / 7793887, 2006-03-07, VIN prefix WBANC92090 (E60 530d) — our probe, 2026-09-23 | `0A8 0A9 0AA 0B5 0BA 1A2 1B6 1D0 1D2 200 332 3B3 3B4 492 498 592 598` | define `15E0`; rail `00DF`, boost `0091`, charge-air temp `16A8`, battery `0093` | `0x3B4` present but battery field always invalid; `1A 80` from our probe went unanswered on 2026-09-23 | [[can-capture-2026-07-15]], [[diag-route-b-2026-09-23]], [[launch-captures-2026-10-07]] |
| **Patrol 2** (2026-10-18) | **7794904**, 2004-01-21 (from the Launch's reads) | **7796156** / 7796157 / 7789877, 2006-05-17, `"@DR55820 "`, **VIN prefix WBAGM21070 — an E65 7-series (730d `(unverified)`)**, not an E60 like Patrol 1 — the board's own read, `ecu dump` 2026-10-18 evening (`1A 80` also stored by the board: 7794904 / 2004-01-21, 31 B) | `0A8 0A9 0AA 0B5 0BA 1A2 1B6 1D0 1D2 200 38E 492 498 592 598` | rail `00C2`, boost `003A`, battery `002F` (all `(unverified scale)`, Patrol 1's formulas fit — [[launch-captures-2026-10-18-patrol-2]]); charge-air temp **not captured**; Patrol 1's identifiers return junk here | no `0x332` / `0x3B3` / `0x3B4` (ignition from the lever); `0x38E` new; `0x1B6` content/rate changed; output shaft `0x0BA` bytes 3–4 work here too (user, rolling, 2026-10-18 evening) | [[can-capture-2026-10-18-patrol-2]] |
| **Setup 3** (planned 2026-10-19) | — | — | — | — | said to differ from both | — |
Human names for the part numbers (a parts-catalogue lookup would name the exact DDE variant) are `(unverified)`; both are M57N DDE6-era units by behaviour (KWP2000, same `2C` live-data service, same broadcast map). **The donors differ: Patrol 1's DDE came from an E60 530d (WBANC92090), Patrol 2's from an E65 7-series (WBAGM21070)** — a plausible reason for the different `2C 10` addresses and the different bus population (the E60's 5-s trio `0x332/0x3B3/0x3B4` absent, `0x38E` present) `(unverified link)`.
Raw `1A 86` of Patrol 2 (66 bytes, this board, 2026-10-18):
```
+000 5A 86 40 44 52 35 35 38 32 30 20 06 05 17 00 00 |Z.@DR55820 .....|
+016 07 79 61 56 00 00 07 79 61 57 00 00 07 78 98 77 |.yaV...yaW...x.w|
+032 01 11 11 31 32 33 34 35 9E 30 30 38 39 45 48 30 |...12345.0089EH0|
+048 41 51 39 31 42 57 42 41 47 4D 32 31 30 37 30 FF |AQ91BWBAGM21070.|
+064 FF FF |..|
```
Raw `1A 80` (31 bytes): `5A 80 00 00 07 79 49 04 10 00 00 10 35 39 20 04 01 21 08 08 02 30 08 FF FF 02 03 01 00 00 00`. Same layout as Patrol 1's blocks (part number at `1A 86` byte 16, date at 11; `1A 80` part at 4, date at 15) — the decoder fits both cars `(verified)`.
## What to capture on a new setup `(procedure)`
Three CANNY logs plus notes, the way Patrol 2 was done:
1. **Key on only**, ~15 s, then key off and keep logging until the bus goes quiet (gives the wake-up and after-run timing, and the lever byte's `F0` behaviour).
2. **Start, idle, two throttle blips, lever through R / N / D with the brake held, key off**, keep logging.
3. **Launch connected on each live parameter the Engine data screen shows** — rail pressure, charge-air pressure, charge-air temperature, battery voltage — one at a time, ~20 s each, noting the parameter's name and the value on the Launch screen (the `2C 10 <id>` identifiers differ per DDE, so this is the only way the screen gets its identifiers on a new car). The Launch's `1A 80` cycle identifies the DDE even without our board.
4. A note of **what else is wired to the PT-CAN** besides DDE and EGS.
5. If drivable: a short drive with a GPS speed reading at one steady moment (the output-shaft factor is still provisional, [[driveline-speed-signals]]) — and a check that `0x0BA` bytes 3–4 move at all on that car's EGS.
With the board on the car: `ecu show` after a few seconds with the key on (it reads the identification once by itself), `diag status`, and a `CANRAW` capture for the ID census (`tools/serial_logger.py`). Offline, the per-ID census and the decoded timeline come from the scripts used for Patrol 2 (per-ID counts, rates, per-byte variability; half-second decoded timeline).
## Related
[[can-capture-2026-10-18-patrol-2]] · [[nissan-patrol-swap]] · [[bmw-m57n-engine]] · [[can-id-candidates]] · [[obd-diagnostic-polling]] · [[open-questions]]
File diff suppressed because it is too large Load Diff
+10232
View File
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
File diff suppressed because it is too large Load Diff
+11657
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,82 @@
---
type: source
tags: [can-bus, capture, patrol-2, dde, ignition, kwp2000, ident, launch, rail-pressure]
updated: 2026-10-18
---
# CAN captures — the second Patrol, same M57N, "same" DDE (2026-10-18)
The user has a **second Nissan Patrol with a BMW M57N** and brought three CANNY 5.3 Pico logs (tab-separated, same format as [[launch-captures-2026-10-07]]): `raw/ingnition-only.txt` (14.5 s, 7 693 frames), `raw/engine-on.txt` (21.7 s, 11 657 frames) and `raw/launch-diag-rail-pressure.txt` (15.4 s, 8 971 frames, Launch connected). No malformed lines. Analysed offline against the firmware's own scalings. **Headline: every frame the firmware decodes is byte-for-byte the same layout as on Patrol 1, but this bus has no `0x3B4`, so the firmware's only ignition signal is missing — and the DDE is a different unit.** This page is the evidence for [[vehicles]].
## What happened in each log `(verified from the logs)`
- **ignition-only**: bus wakes at 0 s (EGS boot pattern on `0x0B5`, `0x1D2` byte 0 = `F0`), lever reads `E1` (P) from 1.0 s, **key off at 10.6 s** (`0x1D2` byte 0 back to `F0`, `0x0A8` byte 7 bit 6 clears, `0x0AA` byte 7 `C8` → `00`), bus still alive when the log ends at 14.5 s.
- **engine-on**: key on at 0 s, **crank at 5.8 s** (`0x1D0` run state 1, rpm 138–186, lever flicks `E1`→`B4`→`E1` and `0x0BA` target nibble 3→1→3 for 30 ms), idle 735–760 rpm from 7.5 s (run state 2), three throttle blips (pedal 14 / 51 / 68 %) to 1 551 rpm at 12–14.5 s, **key off at 16.3 s**, rpm decays to 0 by 18 s, bus alive to the end (21.7 s).
- **launch**: engine idling 736–748 rpm in P, coolant 24→25 °C, the Launch polling one live value.
## ID inventory against Patrol 1
| ID | Hz | Patrol 1 (`raw/boost.txt`, 2026-10-07) | Patrol 2 | Note |
|---|---|---|---|---|
| `0A8 0A9 0AA` | 100 | yes | yes | DDE torque / rpm / pedal, same layouts |
| `0B5 0BA 1A2 1D2` | 100 / 50 / 50 / 5 | yes | yes | EGS, same layouts |
| `1D0` | 10 | yes | yes | DDE engine data, same |
| `200` | 5 | yes, constant `2C 81 FC` | yes, same | unknown |
| `492 498 592 598` | 5.5 / 0.2 | yes | yes | network management style, unknown |
| `1B6` | 1 → 10 | constant `00 FC 00 04 00 F8 00` at 1 Hz | `FF FF 00 04-07 xx F0/F8 xx`, speeds up to 10 Hz with the engine running | unknown, changed |
| **`332 3B3 3B4`** | 0.2 | **yes**, every 5 s | **absent in all 51 s** | the 5-s trio from one transmitter is gone |
| **`38E`** | 10 | absent | **yes**, 2 bytes, `FF FF` at wake-up then `00 00` | unknown, new |
| `612 6F1` | — | with the Launch | with the Launch | diagnostics |
The same logger saw `0x3B4` on Patrol 1 at 0.2 Hz, so this is not a tool filter. Whatever module sent the trio on Patrol 1 is not on Patrol 2's bus → [[open-questions]] #15.
## Every firmware-decoded signal matches `(verified)`
| Signal | Patrol 2 reads | Plausible |
|---|---|---|
| `0x0AA` rpm (`raw16 × 0.25`) | 0 key-on, 138–186 cranking, 735–760 idle, blips to 1 551 | yes |
| `0x0AA` pedal | 0 / 14 / 51 / 68 % | yes |
| `0x0A8` torque (`TORQ_AVL`) | 25–30 Nm warm idle, negative on overrun; **812 Nm with key on, engine off** (Patrol 1: 245 Nm) | the engine-off value is junk → firmware now gates torque on run state `(repo)` |
| `0x1A2` turbine (`raw / 8 + 6`) | tracks rpm within 20 rpm in P | yes |
| `0x1D0` coolant (`raw − 48`) | 23 → 25 °C, cold engine | yes |
| `0x1D0` run state (bits 20–21) | 0 off, 1 cranking, 2 running | yes |
| `0x0B5` gearbox oil (`raw − 40`) | 19 → 20 °C | yes |
| `0x1D2` lever | `E1` P, `B4` N during the crank, `F0` with the key off | yes |
| `0x0BA` target nibble / output shaft | 3 (P) / 0 | yes, stationary |
## The DDE is a different unit `(verified from the Launch's ident reads)`
The Launch reads the KWP identification (`6F1: 12 02 1A 80` → `612: F1 10 LL 5A 80 …`) every cycle. Decoded (BCD part number at payload bytes 4–7, BCD date YY MM DD at 15–17; offsets observed, field names `(unverified)`):
| Car | `1A 80` reply length | Part number | Date | Raw (after `5A 80`) |
|---|---|---|---|---|
| Patrol 1 | 37 B | **7796678** | 2006-02-16 | `00 00 07 79 66 78 00 00 00 11 4C 52 20 06 02 16 08 08 02 30 39 36 32 03 03 01 00 00 00 00 00 07 79 54 64 00` |
| Patrol 2 | 31 B | **7794904** | 2004-01-21 | `00 00 07 79 49 04 10 00 00 10 35 39 20 04 01 21 08 08 02 30 08 FF FF 02 03 01 00 00 00 FF` |
Patrol 1's `1A 86` block (read by our own probe, [[diag-route-b-2026-09-23]]) gives other numbers (7799764 / 7799765 / 7793887, 2006-03-07, VIN prefix WBANC92090) — `1A 80` and `1A 86` are different identification blocks of the same ECU. Same family, same broadcast layouts, same diagnostic behaviour; nothing in the decoding changes.
## Ignition without `0x3B4` — the lever rule `(verified timing on both logs)`
`0x1D2` byte 0 is `F0` for the first second after wake-up and from the instant the key goes off, while the bus keeps running another 5–10 s (EGS/DDE after-run). With terminal 15 on it is a lever code (`E1`/`D2`/`B4`/`78`). On Patrol 1 `F0` never appeared in any capture (always `E1`). So: **a recognised lever code = ignition on, `F0` = off**, within one 200 ms frame. A second vote with the same behaviour on both cars: `0x0A8` byte 7 bit 6 (set ~3 s after wake-up while the key is on — `40`/`42`/`E0`/`E2` —, cleared at key-off). Not consistent across the cars: `0x0AA` byte 7 (`C8` with key on / engine off on Patrol 2, `00` on Patrol 1).
Firmware `(repo, 2026-10-18)`: `0x3B4` keeps precedence while seen in the last 10 s, otherwise the lever rule decides; the driver logs which source decided.
## The Launch dialogue — a new rail identifier `(unverified meaning)`
Every ~270 ms: `12 02 1A 80` → multi-frame ident, flow control `12 30 00 00`, then **`12 04 2C 10 00 C2`** → `F1 04 6C 10 HH LL`. Raw `0x2B08`–`0x2C28` (11 016–11 304) at idle. At the verified `0xDF` rail scale (× 0.03 bar) that is 330–339 bar, a normal idle rail pressure, so `00C2` is probably the rail setpoint or the Launch's other rail item — the user did not note the Launch's label/value this time. → [[obd-diagnostic-polling]] identifiers table, [[open-questions]] #15.
## Bonus: a fuel counter on `0x1D0` `(unverified)`
Bytes 4–5 of `0x1D0` are a 16-bit counter that only advances with the engine running: ~400–500 counts/s at idle (0 → 5 433 over the engine-on log, flat before cranking and after key-off). Almost certainly the fuel-consumption counter (E65 docs name one on this ID) — a future fuel-rate readout once scaled against the Launch's consumption figure.
## Consequences `(repo, 2026-10-18)`
1. **Ignition fallback** from the `0x1D2` lever byte (above) — without it every live screen on Patrol 2 stays at "Ignition off".
2. **Torque gated on `ENGINE_RUN_RUNNING`** on the Sport and Driveline screens (the key-on/engine-off junk value).
3. **`EcuIdent`**: the DDE identification is read once (`1A 86` then `1A 80`), stored, shown on Settings → Vehicle (UNKNOWN ECU until then), re-read only on request; a connected Launch's `1A 80` reads are compared passively (ECU CHANGED?). Design: the identity is a label; behaviour adapts to which frames are present.
4. One row per setup from now on: [[vehicles]].
5. **Added the same evening, after the board's first key-on on this car (user report):** the Engine data screen showed no rail pressure, boost flat at ~2800 mbar and a charge-air temperature above 300 °C, and the output speed stayed 0. The first three are Patrol 1's `2C 10` identifiers being read on a different DDE software — the Launch polled `00C2` here, not `00DF` — so the live-data identifier set is now per DDE (`(repo)` `engine_screen.cpp` `PROFILES[]`): Patrol 2 gets rail `00C2` only until its other values are captured with the Launch. The output speed: all three logs here are stationary (`0x0BA` bytes 3–4 = 0 throughout), so a rolling capture is needed before calling the shaft field different on this EGS → [[open-questions]] #15. The board's own identification read worked on this unit: Settings → Vehicle showed **DDE 7796156 - 2006-05-17** (the `1A 86` block; the Launch's `1A 80` reads 7794904 / 2004-01-21) — both numbers now select the Patrol 2 profile. `ecu dump` over USB the same evening: `1A 86` = 66 bytes, `"@DR55820 "`, 2006-05-17, parts 7796156 / 7796157 / 7789877, **VIN prefix WBAGM21070 (E65 7-series)**; `1A 80` = 31 bytes, 7794904 / 2004-01-21 — this board's own `1A 80` is answered on this unit (it was silent on Patrol 1). Full bytes on [[vehicles]].
## Related
[[vehicles]] · [[can-id-candidates]] · [[obd-diagnostic-polling]] · [[launch-captures-2026-10-07]] · [[diag-route-b-2026-09-23]] · [[nissan-patrol-swap]] · [[open-questions]]
+1 -1
View File
@@ -6,7 +6,7 @@ updated: 2026-09-23
# Route A probe — first live run (2026-09-23) # Route A probe — first live run (2026-09-23)
First execution of the [[obd-diagnostic-polling]] Route A test: the `diag` console probe on Controller A, engine idling, Launch unplugged, tapped PT-CAN. Two sessions, raw console logs (CANRAW + CANTX + diag output interleaved): First execution of the [[obd-diagnostic-polling]] Route A test: the `diag` console probe on Main CTRL, engine idling, Launch unplugged, tapped PT-CAN. Two sessions, raw console logs (CANRAW + CANTX + diag output interleaved):
- `raw/diag-20260923-111737.log` — `pids`, `pid 0C`, `pid 05`, `pid 0B`, `pid 70`, `vin`, `ecu`, `status` - `raw/diag-20260923-111737.log` — `pids`, `pid 0C`, `pid 05`, `pid 0B`, `pid 70`, `vin`, `ecu`, `status`
- `raw/diag-20260923-111851.log` — `pid 10`, `pid 04`, `pid 0F`, `pid 0D`, `pid 1C`, `pid 01`, `pid 21`, `status` - `raw/diag-20260923-111851.log` — `pid 10`, `pid 04`, `pid 0F`, `pid 0D`, `pid 1C`, `pid 01`, `pid 21`, `status`
@@ -20,7 +20,7 @@ raw: raw/ESP32-S3-Touch-LCD-5-details-intro.jpg
## Relevance ## Relevance
- Confirms the terminal-block signal set and that the RS485 pair is the only UART1 exit → `(sibling: 1.3 wiki → controller-link)` open question #1 on how the wire to Controller B is really made - Confirms the terminal-block signal set and that the RS485 pair is the only UART1 exit → `(sibling: 1.3 wiki → controller-link)` open question #1 on how the wire to Inst. Cluster is really made
- Confirms one shared termination switch for CAN and RS485 — keep it **OFF** when tapping the vehicle CAN bus, which also leaves the RS485 link unterminated on this end - Confirms one shared termination switch for CAN and RS485 — keep it **OFF** when tapping the vehicle CAN bus, which also leaves the RS485 link unterminated on this end
- Strapping pads IO0/IO3/IO4/IO46 exist as solder points — the only bare GPIO access on the board, and all four are already committed (G3, VSYNC, CTP_IRQ, HSYNC) - Strapping pads IO0/IO3/IO4/IO46 exist as solder points — the only bare GPIO access on the board, and all four are already committed (G3, VSYNC, CTP_IRQ, HSYNC)
@@ -19,7 +19,7 @@ Raw: `raw/ESP32-S3-Touch-LCD-5-Sch.pdf` (3 sheets, V1.2), re-downloaded 2026-09-
## 5 V rail budget (for whatever hangs on VOUT) ## 5 V rail budget (for whatever hangs on VOUT)
- `VIN` (7–36 V terminal) → `D17` 1N5822 reverse-protection Schottky + `D3` SMAJ36CA TVS → `U1` **SY8293** synchronous buck → **`DC_5V`**, `L3` 4.7 µH 8 A, note *"Run the line at current 2A"*. `DC_5V` feeds the 5 V rail (and VBUS via `Q4` AO3401 ideal-diode-style switch). - `VIN` (7–36 V terminal) → `D17` 1N5822 reverse-protection Schottky + `D3` SMAJ36CA TVS → `U1` **SY8293** synchronous buck → **`DC_5V`**, `L3` 4.7 µH 8 A, note *"Run the line at current 2A"*. `DC_5V` feeds the 5 V rail (and VBUS via `Q4` AO3401 ideal-diode-style switch).
- Sheet note: *"The screen itself consumes close to 550 mA"*; the wiki's whole-board figure is ~450 mA @ 5 V. Realistic headroom on VOUT@5 V from the 12 V input: **roughly 1 A**, comfortably enough for Controller B (~150–200 mA) `(unverified estimate; the regulator is rated for 2 A total)`. - Sheet note: *"The screen itself consumes close to 550 mA"*; the wiki's whole-board figure is ~450 mA @ 5 V. Realistic headroom on VOUT@5 V from the 12 V input: **roughly 1 A**, comfortably enough for Inst. Cluster (~150–200 mA) `(unverified estimate; the regulator is rated for 2 A total)`.
- On USB-only power the 5 V rail is the host's 500 mA — do not load VOUT then. - On USB-only power the 5 V rail is the host's 500 mA — do not load VOUT then.
- Caveat for the vehicle: the 36 V TVS is the only transient clamp; the ISO 7637 concern in [[open-questions]] #6 stands. - Caveat for the vehicle: the 36 V TVS is the only transient clamp; the ISO 7637 concern in [[open-questions]] #6 stands.
@@ -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]]). - 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]]. - 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. - 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). - Strapping pads `R87–R94` (IO0/IO3/IO45/IO46).
## Related ## Related
@@ -23,7 +23,7 @@ Official product documentation for the ESP32-S3-Touch-LCD-5 family. Covers four
- **120 Ω termination resistor switch, OFF by default** — correct setting for tapping into an existing, already-terminated vehicle bus; leave it off. - **120 Ω termination resistor switch, OFF by default** — correct setting for tapping into an existing, already-terminated vehicle bus; leave it off.
**Other onboard peripherals:** **Other onboard peripherals:**
- RS485 via SP3485, automatic TX/RX direction switching (this is the terminal block the firmware uses for UART1 → Controller B `(repo)`). - RS485 via SP3485, automatic TX/RX direction switching (this is the terminal block the firmware uses for UART1 → Inst. Cluster `(repo)`).
- Optocoupler-isolated digital I/O: inputs 5–36 V (dry/wet contact, NPN or PNP), open-drain outputs sinking up to 450 mA/channel. - Optocoupler-isolated digital I/O: inputs 5–36 V (dry/wet contact, NPN or PNP), open-drain outputs sinking up to 450 mA/channel.
- PCF85063 RTC with CR927 coin-cell holder. - PCF85063 RTC with CR927 coin-cell holder.
- TF card slot (SD_CS must be driven via CH422G EXIO4). - TF card slot (SD_CS must be driven via CH422G EXIO4).
+2 -2
View File
@@ -6,7 +6,7 @@ updated: 2026-09-23
# Launch live-data capture — rail pressure decoded (2026-09-23) # Launch live-data capture — rail pressure decoded (2026-09-23)
The capture-with-Launch session that [[obd-diagnostic-polling]] had been pointing at since July, finally run. Engine idling, our read-only logger (`tools/serial_logger.py`) on Controller A's USB recording the full `CANRAW` stream while the Launch polled the DDE; then the user selected **Rail Pressure (actual)** and blipped to 2500 rpm for a second calibration point. Raw: `raw/serial-COM10-20260923-163511.log` (~13 MB, both halves of every exchange). The capture-with-Launch session that [[obd-diagnostic-polling]] had been pointing at since July, finally run. Engine idling, our read-only logger (`tools/serial_logger.py`) on Main CTRL's USB recording the full `CANRAW` stream while the Launch polled the DDE; then the user selected **Rail Pressure (actual)** and blipped to 2500 rpm for a second calibration point. Raw: `raw/serial-COM10-20260923-163511.log` (~13 MB, both halves of every exchange).
## Headline: rail pressure actual is decoded and VERIFIED ## Headline: rail pressure actual is decoded and VERIFIED
@@ -41,7 +41,7 @@ This is the key operational finding: **rail pressure is served in the DDE's defa
- **The method generalises**: any value the Launch will display can be decoded the same way — capture the `2C`/`6C` pair while its screen shows the number, calibrate scale against the display at two points. Boost, MAF, injection quantity, EGTs are each one session away. See [[obd-diagnostic-polling]] "Beyond the probe". - **The method generalises**: any value the Launch will display can be decoded the same way — capture the `2C`/`6C` pair while its screen shows the number, calibrate scale against the display at two points. Boost, MAF, injection quantity, EGTs are each one session away. See [[obd-diagnostic-polling]] "Beyond the probe".
- **Self-poll is feasible without any secret.** To read rail pressure ourselves: send the one-time define `2C 10 15 E0`, then poll `2C 10 00 DF` → parse `6C 10 HHLL`. **No `10` session, no `27` security, no `3E` tester-present required** (proven above). The only barriers are our own choices, not the ECU's — see the two below. - **Self-poll is feasible without any secret.** To read rail pressure ourselves: send the one-time define `2C 10 15 E0`, then poll `2C 10 00 DF` → parse `6C 10 HHLL`. **No `10` session, no `27` security, no `3E` tester-present required** (proven above). The only barriers are our own choices, not the ECU's — see the two below.
- **It is still a transmit-on-the-bus action, and `2C` is not strictly read-only** (it writes a definition into the ECU's dynamic-identifier table — harmless, but a state change). So it stays outside the current probe whitelist by policy. - **It is still a transmit-on-the-bus action, and `2C` is not strictly read-only** (it writes a definition into the ECU's dynamic-identifier table — harmless, but a state change). So it stays outside the current probe whitelist by policy.
- **Intended home (design decision, 2026-09-23):** any active polling belongs behind a **password-protected "Diagnostics" screen** on Controller A — authorized-technician gate — never a background/automatic poller and never while a scan tool is connected. Records [[open-questions]]; not built yet. - **Intended home (design decision, 2026-09-23):** any active polling belongs behind a **password-protected "Diagnostics" screen** on Main CTRL — authorized-technician gate — never a background/automatic poller and never while a scan tool is connected. Records [[open-questions]]; not built yet.
- No EGS traffic (`0x618`) — only the DDE (`0x612`) answered; the Launch was on an engine page. - No EGS traffic (`0x618`) — only the DDE (`0x612`) answered; the Launch was on an engine page.
## Related ## 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]]
@@ -0,0 +1,34 @@
---
type: source
tags: [can-bus, capture, patrol-2, dde, launch, kwp2000, boost, battery, live-data]
updated: 2026-10-18
---
# Launch captures on Patrol 2 — charge-air pressure and battery identifiers (2026-10-18)
Two CANNY 5.3 Pico logs the user took on Patrol 2 (DDE 7794904 / 7796156, E65 donor, [[vehicles]]) with the Launch showing one live value each: `raw/charge-air-pressure.txt` (30.8 s, 5 930 frames, idle → one throttle blip to 2 553 rpm → key off) and `raw/battery.txt` (18.8 s, 10 232 frames, idle → engine stop). Same method as [[launch-captures-2026-10-07]] on Patrol 1. The Launch's values on its own screen were **not noted**, so the scalings below are Patrol 1's, checked only for physical plausibility.
## The Launch dialogue `(verified from the logs)`
Per cycle (~270 ms): `12 02 1A 80` → ident reply (flow control `12 30 00 00`), then **one** `12 04 2C 10 <id>` → `F1 04 6C 10 HH LL`. No define (`15 E0`), no session, no security, no negative responses — as on this car's rail capture ([[can-capture-2026-10-18-patrol-2]]).
| Launch screen | Identifier | Raw range | Scaled with Patrol 1's formula | Behaviour | Status |
|---|---|---|---|---|---|
| Charge-air pressure | **`003A`** | 8 071 – 9 487 | mbar = raw ÷ 8 → 1 009 – 1 186 | 1 018 mbar flat at 700 rpm idle; blip to 2 553 rpm (pedal 99 %) → peaks at 1 186 mbar 0.6 s after the rpm peak, decays to 1 021 mbar after key-off (ambient) | `(unverified scale)` — plausible: atmospheric at idle, +170 mbar on a free rev; Launch value not noted |
| Battery voltage | **`002F`** | 5 166 – 5 723 | V = raw × 0.002455 → 12.68 – 14.05 | 13.9 – 14.05 V at idle (alternator), drops with the engine stop (13.7 → 12.9 V within 0.6 s), then creeps down 12.86 → 12.68 V over 4 s key-on | `(unverified scale)` — plausible alternator / rest voltages; Launch value not noted |
Compare Patrol 1 (DDE 7796678): charge-air pressure `0091`, battery `0093`, rail `00DF` — **every identifier is different on this DDE** (rail is `00C2` here). The scalings, however, look identical, which fits the same measurement firmware family with a different variable map.
## Consequences `(repo, 2026-10-18)`
- Patrol 2's profile in `engine_screen.cpp` (`PROFILES[]`) now carries rail `00C2`, boost `003A`, battery `002F`; **charge-air temperature is still unmapped** on this car (one more Launch session: "charge-air temperature" / "intake air temperature").
- All three Patrol 2 values are tagged provisional on the screen until the user reads them next to the Launch (one point each would already confirm the scale).
## Also in these logs
- The output shaft: the user confirmed the Driveline's output speed is fine on Patrol 2 once rolling (the stationary logs had shown 0) — [[open-questions]] #15 closed on that point.
- Both logs show the `0x1D0` fuel-counter bytes advancing only with the engine running, as before.
## Related
[[obd-diagnostic-polling]] · [[vehicles]] · [[can-capture-2026-10-18-patrol-2]] · [[launch-captures-2026-10-07]] · [[launch-capture-2026-09-23]]