Files
ESP32-S3-Touch-LCD-5B/CLAUDE.md
T
julian 1cba9f30bc
Firmware / build (push) Successful in 10m49s
Reverse lights on DO0, Sport + Vehicle screens, per-DDE live data, ECU identification
- 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

409 lines
42 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
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
**Key Features**: CAN decode, link to B (UART + ESP-NOW @ 5 Hz), remembered Wi-Fi + on-screen OTA updates, gauge tuning, NVS settings persistence, LVGL 8.4.0 UI (hand-coded screens)
## 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
```bash
# Build project (first build takes ~5-10 min, downloads libraries)
pio run
# Upload to board
pio run --target upload
# Monitor serial output (115200 baud)
pio device monitor
# Combined upload + monitor
pio run --target upload && pio device monitor
# Clean build
pio run --target clean
# Update libraries
pio lib update
# List available serial ports
pio device list
# Upload with manual port specification
pio run --target upload --upload-port /dev/ttyUSB0
```
### VS Code
Use PlatformIO extension toolbar:
- **Build**: Checkmark icon
- **Upload**: Arrow icon
- **Serial Monitor**: Plug icon
## Architecture
### Multi-Core FreeRTOS Design
The application uses **dual-core architecture** to maximize performance:
- **Core 1** (Arduino core): LVGL rendering task (Priority 2)
- UI rendering @ 1024x600 (real render FPS never measured - the Debug "FPS" counts loop() passes)
- Touch input handling
- CPU load ~80% under normal operation
- **Core 0**: WiFi, UART, and CAN tasks (Priority 1)
- WiFi scanning task: Async network scanning every 10 seconds
- UART transmission task: 5Hz automotive data transmission
- CAN Bus task: Real-time CAN message reception and parsing
- All tasks use FreeRTOS queues for event communication
**Thread-Safety**: All UI updates from background tasks MUST acquire `lvgl_port_lock(-1)` before touching LVGL objects, and call `lvgl_port_unlock()` after.
### Component Structure
The project follows a clean, organized structure with logical separation of concerns:
```
src/
main.cpp # Main application logic only
modules/
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 / Vehicle (swipe left from Driveline)
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
tunables.cpp # Gauge calibration + alert thresholds (NVS, 'cfg' serial console)
espnow_link.cpp # ESP-NOW broadcast leg of the link
tuning_screen.cpp # Hand-coded Gauge Tuning screen, 4 tabs (swipe right from Driveline)
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)
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
link_peer.cpp # Inst. Cluster over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' console)
status_overlay.cpp # lv_layer_top() on EVERY screen: Wi-Fi chip top-right, blinking red / steady amber alert banner top-centre
diff_locks.cpp # Diff-lock inputs DI0 rear / DI1 front via CH422G EXIO0/EXIO5 ('difflock' console, Settings switch, default OFF)
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
ui_state_manager.cpp # Debug flag (performance overlay, sent to B)
display_init.cpp # Display initialization; boots into DrivelineScreen
driveline_screen.cpp # Hand-coded LVGL boot screen (gear, temps, rpm, status)
engine_screen.cpp # Live DDE values: rail, boost, charge-air temp, battery (Engine data button)
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/
can_driver.cpp # CAN Bus driver (TWAI)
include/
config/
lv_conf.h # LVGL configuration
display/
lvgl_v8_port.h/cpp # LVGL porting layer for ESP32-S3
drivers/
can_driver.h # CAN Bus driver interface
protocol/
automotive_data.h # UART protocol and CAN ID mappings
```
**src/main.cpp** (~1530 lines)
- Main application logic, event handlers, FreeRTOS task implementations
- 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**
- **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
- `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()`
- Maintenance frames (2026-09-27, `PACKET_VERSION` unchanged): `STATUS` 0x03 B → A, `PAIR` 0x04 A → B **wire only**, `SECURE` 0x05 A → B (AES-256-GCM, `include/protocol/link_secure.h` - shared and byte-identical too). `PACKET_MAX_PAYLOAD` is 160
- Spec: `docs/UART_PROTOCOL.md`
- **BMW CAN Bus ID mappings**: 11-bit PT-CAN IDs verified live on the swap bus (evidence: `wiki/pages/can-id-candidates.md`)
- UART config: 115200 baud on GPIO 44 (TX) / 43 (RX, unused) — leaves the board via the SP3485 RS485 transceiver
**include/drivers/can_driver.h/cpp**
- CAN Bus driver using ESP32 TWAI (Two-Wire Automotive Interface)
- Hardware: GPIO 15 (TX), GPIO 16 (RX) - 500 Kbps baud rate
- Mode: TWAI_MODE_NORMAL (ACKs frames; LISTEN_ONLY caused transmitter retry-flooding). The only transmit path is `CANDriver::transmit()`, used solely by `DiagProbe` for typed `diag` console requests (single-shot, echoed as `CANTX,` lines)
- Parses BMW-specific CAN messages and updates shared automotive data structure
- Task runs on Core 0 with FreeRTOS queue for start/stop commands
**include/display/lvgl_v8_port.h/cpp**
- LVGL 8.4.0 porting layer for ESP32-S3
- Display buffer config: 60-line height single buffer in DMA-capable SRAM for performance
- Task config: 6KB stack, Priority 2, pinned to Core 1
- **Critical**: `lvgl_port_lock()` / `unlock()` for thread-safe LVGL calls from non-LVGL tasks
**include/config/lv_conf.h**
- LVGL 8.4.0 configuration file
- 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. **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
Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Namespace: "settings"
- 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()`
- Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed
### WiFi Architecture
`WiFiManager` (`wifi_manager.cpp`) owns **no LVGL objects**: the Settings screen polls `getStatus()` / `getNetworks()` and calls `setEnabled()`, `requestScan()`, `connect()`, `connectSaved()`, `forget()`. All radio work runs in `wifiTask()` (Core 0) from a command queue.
- **One remembered network** (NVS namespace `wifi`), saved after a successful join, joined automatically ~3 s after boot when Wi-Fi is on (verified 2026-09-27)
- **Scans only on request** (Wi-Fi page opened while not connected, or the Scan button) - background scans every 10 s caused display glitches and hop the radio ESP-NOW uses
- **No endless reconnect**: `setAutoReconnect(false)`; one attempt at boot, one retry after a drop, then idle back on `ESPNOW_CHANNEL`
- Failure reasons come from the STA_DISCONNECTED event (wrong password, not in range, ...) and show on the screen
- Console: `wifi status | join <ssid> [pass] | forget | scan | on | off`
### UART Architecture
**Transmission Protocol** (v2, see `docs/UART_PROTOCOL.md`):
- DATA frame (27 bytes) every 200 ms; CONFIG frame (33 bytes) on start, on every tunables change, and every 5 s
- Every frame goes out on UART1 **and** ESP-NOW broadcast (`EspNowLink`); B dedupes on `packet_id`
- Hardware: Serial1 TX GPIO 44 / RX GPIO 43 (RS485 terminal block on board)
**Task Flow**:
- `uartTask()` runs on Core 0
- Events via `g_uart_event_queue`: `UART_EVENT_START`, `UART_EVENT_STOP`, `UART_EVENT_SEND_DATA`
- Default data: `initializeDefaultData()` seeds the structure until CAN updates it; the dummy generator was removed
- `sendDataFrame()` / `sendConfigFrame()` build frames with `frame_build()` and call `sendFrame()` (UART1 + ESP-NOW)
- Mutex protection: `g_data_mutex` guards `g_automotive_data` structure
**CAN Bus Integration**:
- CAN driver reads BMW-specific messages and updates `g_automotive_data`; `publishGear()` fills lever + nibbles, `updateAlerts()` evaluates the alert bits against `Tunables` thresholds
- UART auto-starts/stops with the CAN task (`linkToCANState()`); no dummy simulation remains
- Shared data structure (`g_automotive_data`) is mutex-protected for thread safety
### CAN Bus Architecture
**Hardware Configuration**:
- Controller: ESP32-S3 TWAI (Two-Wire Automotive Interface)
- Pins: GPIO 15 (TX), GPIO 16 (RX)
- Baud Rate: 500 Kbps (BMW standard)
- Mode: TWAI_MODE_NORMAL (ACKs frames; never transmits data frames)
**BMW CAN Message IDs** (all 11-bit standard frames, verified live; full decode in `wiki/pages/can-id-candidates.md`):
- `0x1D0` [byte 0] → Coolant temperature (raw − 48 °C); [byte 1] engine oil temp (reads 0xFF on this M57N); [byte 2 bits 4-5] engine run state
- `0x0B5` [byte 7] → Gearbox oil temperature (raw − 40 °C); [byte 4 bits 6-7] cooling demand
- `0x1D2` [byte 0] → Gear lever (E1=P D2=R B4=N 78=D/S/M); [byte 1] engaged gear; [byte 4] drive/sport/manual mode
- `0x0BA` [byte 0 low nibble] → Gearbox target gear incl. reverse; [bits 6-7] converter lockup; [bytes 3-4] output shaft speed (scaling open)
- `0x1A2` [bytes 0-1] → Turbine speed
- `0x0AA` [bytes 4-5] → Engine RPM (× 0.25); [byte 3] pedal position
- `0x0A8` [bytes 1-2] → Available engine torque
- `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**:
- `canTask()` runs on Core 0 with Priority 1
- Events via `g_can_event_queue`: `CAN_EVENT_START`, `CAN_EVENT_STOP`
- Message parsing: `parseCANMessage()` extracts data from specific CAN IDs
- Data updates: Acquires `g_data_mutex`, updates `g_automotive_data`, releases mutex
- Statistics tracking: Messages received, parsed, errors
**Safety Features**:
- NORMAL mode: the controller ACKs received frames; nothing is transmitted unless a human types a `diag` command (see Diagnostic probe below)
- Error detection: Bus errors, queue overflow, passive errors
**See Also**: `wiki/pages/can-id-candidates.md` for the verified CAN ID map and evidence, `wiki/pages/can-bus-integration.md` for integration notes
### Tunables (gauge calibration, alert thresholds)
`src/modules/tunables.cpp` owns `link_config_t`: tach pulses/rev + trim + clamps, coolant PWM frequency + duty law + min temp, per-output enables, a bench override (force rpm / duty), and the alert thresholds. Stored as an NVS blob (namespace `tunables`), written 3 s after the last change or on leaving the Tuning screen (`Tunables::flush()`, `isDirty()` drives the screen's save indicator) - every flash write flickers the RGB panel, so no write per tap. Edited over the USB serial console: `cfg show`, `cfg set <name> <value>`, `cfg override rpm <n> | duty <n> | both <rpm> <duty> | off`, `cfg reset`. Every change bumps `cfg_version`, which makes the UART task push a CONFIG frame. Overrides are pushed but never saved. The **Gauge Tuning screen** (`src/modules/tuning_screen.cpp`, see Screens) edits the same values with −/+ buttons, enable switches, and a Simulation tab with RPM and duty sliders. Overrides are never written to NVS (`save()` strips them).
### 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`. **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)
`src/modules/ota_update.cpp` pulls signed firmware from this repo's Gitea releases (`include/config/ota_config.h`: server, repo, Let's Encrypt roots, signing public key). Manual only: Settings → Updates (Check, then Install behind a confirm dialog; verified end-to-end from the screen 2026-09-27) or the console `ota status | check | install [force] | rollback`. `Ota::getStatus()` gives the screen a phase + latest tag + failure reason. Install is refused unless parked (engine off, shaft still, lever not in a drive gear; silent bus = parked), checked before download and again before the slot switch. The manifest's ECDSA P-256 signature over `patrol-a|version|sha256` is checked before download; the streamed image must match that sha256. `verifyRollbackLater()` is overridden so a new image stays pending until `Ota::tick()` confirms it after 30 s - a reset before that rolls back. CI: `.gitea/workflows/firmware.yml` (push `main` -> rolling unsigned pre-release `main-latest`; tag `v*` -> signed release, needs repo secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY`). CI installs **pioarduino's fork of the PlatformIO core** (v6.1.18 zip, same pin as the platform's `penv_setup.py`), not upstream `platformio`: with `custom_sdkconfig` the build goes through the ESP-IDF path, where the upstream core imports `SCons.Tool.FortranCommon` that pioarduino's SCons 4.8.1 does not ship. The core rebuild makes the first CI build after a `platformio.ini` change ~20 min (esp-idf download + rebuild), cached afterwards. Release with one push so only the tag build runs: `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin main` (a main push skips itself when its commit is tagged, or when it only touches `wiki/**` / `*.md`). Never put secrets in firmware source - the repo and its release binaries are public. Jobs run inside the loop task (8 KB stack) with mbedtls routed to PSRAM - internal RAM is too tight for a TLS task (15.9 KB free, largest block 7.6 KB with Wi-Fi up). Wi-Fi is joined on the Settings screen (remembered) or with `wifi join`. Details: `wiki/pages/ota-updates.md`.
### Performance monitor (`perf` console)
`src/modules/perf_monitor.cpp` hooks the LVGL port (`monitor_cb` per rendered frame, a timer around `drawBitmap()` in `flush_callback`) and reads FreeRTOS run-time stats. `perf` prints one `PERF,` CSV line (ts, fps, avg/max ms per frame, kpx per frame, ms per second spent copying into the PSRAM framebuffer, LVGL idle %, core 0/1 idle %, internal free/largest, PSRAM free, **panel vsync/s, longest vsync gap in µs**); `perf on [sec]` prints one every few seconds (from an esp_timer, so it keeps running while the OTA job blocks `loop()`); `perf off`. The vsync columns come from the RGB panel's refresh-finished interrupt (attached in `lvgl_v8_port.cpp` when tearing-avoidance is off): healthy = ~24/s with a 41.5 ms gap; a DMA underrun/restart (flicker, dots) stretches the gap to two frames or more - this is the direct measure for the display work in wiki open-questions #13. Idle Driveline baseline (bench, 2026-09-27, after the `setText()` fix): 0 fps rendered, 0 ms/s flushes, LVGL idle 96 %, core 1 idle 96 % (before the fix: 9.7 fps, 30 ms/frame, 52 ms/s, 68 % / 66 % - the tick re-set every label at 10 Hz). Rule for every screen `tick()`: only write a label or style when the value changed (`lv_label_set_text()` and style setters invalidate even for identical values).
### ESP-NOW link
`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.
### 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, 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
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, **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`
- **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
- 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)
- The System page's "Performance overlay" switch shows LVGL's own perf monitor (real render FPS / CPU) and sets the debug flag sent to B
## Configuration Files
**platformio.ini**
- Custom Arduino core: `pioarduino/platform-espressif32` (Arduino 3.3.3 / ESP-IDF 5.5.1) for RGB LCD support
- Board: Custom `esp32-s3-wroom-1-n16r8` (defined in `boards/esp32-s3-wroom-1-n16r8.json`)
- PSRAM: OPI mode (`qio_opi` memory type) - REQUIRED for 8MB OPI PSRAM and 1024x600 display
- Partition: `partition_table.csv` (dual OTA: 2 x 7.9MB app slots, no SPIFFS) - see OTA updates below
- Debug level: `CORE_DEBUG_LEVEL=1` (1=Error, 5=Verbose)
- Libraries: ESP32_Display_Panel v1.0.4, LVGL 8.4.0 (from GitHub)
**boards/esp32-s3-wroom-1-n16r8.json** (Custom Board Definition)
- Flash: 16MB QIO mode @ 80MHz
- PSRAM: 8MB OPI mode
- CPU: 240MHz
- Partition table: `partition_table.csv`
- Critical settings: `memory_type: qio_opi`, `psram_type: opi`
**partition_table.csv** (Partition Table)
- NVS: 20KB @ 0x9000 (settings storage) - never move it, or saved settings/tunables are lost
- OTA Data: 8KB @ 0xe000 (which slot boots)
- app0 / app1: 7.9MB each @ 0x10000 / 0x800000 (OTA slots; firmware ~1.65MB)
- Coredump: 64KB @ 0xFF0000 (crash debugging)
- Changing this table needs one USB flash; OTA can't repartition
**include/lv_conf.h**
- LVGL 8.4.0 configuration
- Memory: LVGL's widget pool (`LV_MEM_SIZE`) is 512 KB in PSRAM via `LV_MEM_POOL_ALLOC` (was 48 KB internal and ran out). `mem` on the console prints internal heap, PSRAM and pool use/fragmentation
- Asserts: `LV_ASSERT_HANDLER` is `abort()` (backtrace + core dump + reboot), never `while(1)`, which froze the UI while holding the LVGL lock
- Theme: Material theme enabled
## Common Patterns
### Adding a New Setting
See "Adding a setting" under Important Notes: a row + `UiKit::toggle()` on the Settings screen, a `SettingsManager` save/load pair, and a sync line in the page's `refresh*()`.
### Thread-Safe UI Update from Background Task
```cpp
void myBackgroundTask(void* param) {
while (true) {
// Do background work...
// Update UI (MUST use LVGL lock!)
lvgl_port_lock(-1); // Wait indefinitely for lock
lv_label_set_text(my_label, "Updated from task");
lvgl_port_unlock();
vTaskDelay(pdMS_TO_TICKS(100));
}
}
```
### Creating FreeRTOS Task on Specific Core
```cpp
TaskHandle_t task_handle = NULL;
QueueHandle_t event_queue = xQueueCreate(10, sizeof(my_event_t));
xTaskCreatePinnedToCore(
myTaskFunction, // Task function
"MyTask", // Task name (for debugging)
4096, // Stack size (bytes)
NULL, // Parameters
1, // Priority (1=normal, 2=high)
&task_handle, // Task handle output
0 // Core (0 or 1)
);
```
## Hardware-Specific Details
### GPIO Assignments
- **CAN Bus**: GPIO 15 (TX), GPIO 16 (RX) - 500 Kbps, TWAI_MODE_NORMAL, onboard TJA1051 on the terminal block
- **UART1**: GPIO 44 (TX), GPIO 43 (RX, unused) - reaches the terminal block only as the RS485 A/B pair (SP3485), 115200 baud. Bench: `485_A` straight into B's IO1 + GND works (verified 2026-09-21)
- **USB Serial**: native USB-CDC (`Serial`, 303A:1001). Opening the port with default DTR/RTS resets the board - attach with `pio device monitor -p COM10 --dtr 0 --rts 0 --echo`
- **Uploading from a script/pipe on Windows**: set `PYTHONIOENCODING=utf-8` (and `PYTHONUTF8=1`). Otherwise esptool crashes printing its progress bar to a cp1252 pipe *mid-write* and leaves the board frozen until a power cycle (happened 2026-09-27; the bootloader then fell back to the other OTA slot)
### Display Panel
- Resolution: 1024x600 RGB888
- Driver: ESP32_Display_Panel library (v1.0.4)
- Backlight control: Manual on/off to prevent white flash during boot (see setup() steps 9, 14)
- Buffer: 60-line height (1024 * 60 * 2 bytes) in DMA-capable SRAM
### Memory Management
- **PSRAM**: Required for LVGL framebuffers and large objects (8MB OPI PSRAM)
- **Flash**: 16MB total (3MB app partition allows large UI assets)
- **Heap**: Monitor with `ESP.getFreeHeap()` if adding features
## Troubleshooting
### Build Errors
- **Build from PowerShell, not Git Bash**: `idf_tools.py` refuses MSYS ("MSys/Mingw is not supported"). The two projects also share one `framework-arduinoespressif32` package directory, so the first `pio run` after building ESP32-S3-LCD-1.3 reinstalls Arduino 3.3.3 and may fail once with `TypeError: expected str, bytes or os.PathLike object, not NoneType` - run it again.
- **`Failed to install Python dependencies into penv (exit code: 2)`** at the start of `pio run`: the sibling ESP32-S3-LCD-1.3 project (official espressif32@6 platform) installs newer `urllib3`/`esptool` into the shared PlatformIO penv, and this project's pioarduino platform needs `urllib3<2`; its install step hides the error. Run `. ools ix_penv_deps.ps1`, then build again. Never build the two projects at the same time (shared penv).
- **Missing libraries**: Run `pio lib update` then `pio run --target clean`
- **Partition table not found**: Ensure `partition_table.csv` exists in project root
- **Out of memory**: Check PSRAM enabled (`board_build.psram_type = opi` in platformio.ini)
### Upload Issues
- **Port not detected**: Run `pio device list`, manually specify with `--upload-port`
- **Permission denied (Linux)**: Add user to dialout group: `sudo usermod -a -G dialout $USER` (log out/in required)
### Runtime Issues
- **Screen drift/artifacts**: RGB LCD timing issue - already optimized in `platformio.ini` with high-performance platform packages
- **White flash on boot**: Backlight control sequence in setup() minimizes this (lines 1383-1414)
- **UI switches don't match state**: `SettingsScreen::tick()` must run in `loop()` - it re-reads the live state every 250 ms
- **WiFi/UART task not responding**: Check FreeRTOS queue creation succeeded (NULL check in setup())
- **LVGL crash from background task**: Ensure `lvgl_port_lock()` / `unlock()` wraps ALL LVGL API calls
- **Screen flickering**: This was resolved by fixing the proper board configuration and partition table. The key fixes were:
1. Creating custom board definition `boards/esp32-s3-wroom-1-n16r8.json` with correct PSRAM settings (`qio_opi` memory type)
2. Updating partition table `partition_table.csv` to use full 16MB flash (12.5MB app, 3.375MB SPIFFS)
3. Adjusting LCD timing in board header (16MHz pixel clock, correct PCLK polarity)
4. Removing unnecessary loading spinner delay from `applySavedStatesToUI()` function
**Important**: The original ESP32_Display_Panel library works perfectly without modifications when the board configuration and partition table are correct!
## Performance Metrics
- **FPS**: not measured yet (the Debug-panel counter counts loop() passes, not frames) - see wiki open-questions #13
- **CPU Load**: ~80% on Core 1 (LVGL rendering)
- **WiFi Scan**: 1-3 seconds for 10-20 networks
- **UART Overhead**: +1-2% CPU @ 5Hz transmission rate
- **Build Time**: First build ~5-10 min (library downloads), incremental ~10-30 sec
## Important Notes
- **Adding a setting**: add a row to the right page in `settings_screen.cpp` (`makeSettingRow()` + `UiKit::toggle()`), persist it via `SettingsManager`, and sync it in that page's `refresh*()` function
- **CAN Bus Integration**: BMW CAN IDs are defined in `automotive_data.h` (all 11-bit standard frames, verified live on the swap bus). The CAN driver runs in `TWAI_MODE_NORMAL` (it ACKs frames; not LISTEN_ONLY). Evidence and confidence labels live in `wiki/pages/can-id-candidates.md`. Never add a second caller of `CANDriver::transmit()` without a design discussion — transmitting on the vehicle bus is a safety decision
- **Security**: the Wi-Fi password field is cleared when the password page closes; the saved password lives only in NVS and is never logged (the pre-2026-09-27 code printed it on every join)