14 Commits

Author SHA1 Message Date
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
julian ae9327d91b Status overlay on every screen: Wi-Fi chip top-right, blinking alert banner; Driveline values red on crossed thresholds, ring red on gear mismatch
Firmware / build (push) Successful in 7m12s
2026-09-27 21:40:37 +02:00
julian 7ae1ab726a link: separator in the Controller B update log line; wiki: B update verified end-to-end
Firmware / build (push) Successful in 7m29s
2026-09-27 20:47:35 +02:00
julian 3e86ca3733 Controller B updates from A: link_peer (pairing over the wire, encrypted credential handoff, B status + commands), ESP-NOW receive/unicast, Updates page with two cards; shared header maintenance frames; docs + wiki
Firmware / build (push) Successful in 7m1s
2026-09-27 20:26:44 +02:00
julian 8338e4e300 Wiki: v0.1.7 published, manifest verified off-device
Firmware / build (push) Successful in 5s
2026-09-27 18:29:46 +02:00
julian 8e739fa24e CI: install pioarduino's PlatformIO core fork (upstream core lacks FortranCommon with the pinned SCons on the ESP-IDF build path)
Firmware / build (push) Successful in 7m4s
2026-09-27 18:21:28 +02:00
julian 929fdfa877 Wiki: v0.1.7 release note (display work merged)
Firmware / build (push) Failing after 3m38s
2026-09-27 18:07:01 +02:00
54 changed files with 1935 additions and 189 deletions
+13 -5
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.
@@ -83,13 +83,21 @@ jobs:
.pio/libdeps .pio/libdeps
key: pio-${{ hashFiles('platformio.ini') }} key: pio-${{ hashFiles('platformio.ini') }}
- name: Install PlatformIO # pioarduino's fork of the PlatformIO core, NOT upstream: the platform pins
# its own SCons 4.8.1 without the Fortran tools, and since the core rebuild
# (custom_sdkconfig, v0.1.7) the ESP-IDF build path is exercised, where the
# upstream core imports SCons.Tool.FortranCommon and dies
# ("ModuleNotFoundError: No module named 'SCons.Tool.FortranCommon'",
# first seen on the v0.1.7 tag build). The pin mirrors
# platform-espressif32/builder/penv_setup.py :: python_deps["platformio"].
- name: Install PlatformIO (pioarduino core)
if: env.SKIP != 'true' if: env.SKIP != 'true'
run: | run: |
curl -LsSf https://astral.sh/uv/install.sh | sh curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH" export PATH="$HOME/.local/bin:$PATH"
uv tool install platformio uv tool install "https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.18.zip"
echo "$HOME/.local/bin" >> "$GITHUB_PATH" echo "$HOME/.local/bin" >> "$GITHUB_PATH"
pio --version
- name: Build - name: Build
if: env.SKIP != 'true' if: env.SKIP != 'true'
@@ -135,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}" \
+23 -7
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
@@ -84,6 +86,9 @@ 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 # Inst. Cluster over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' console)
status_overlay.cpp # lv_layer_top() on EVERY screen: Wi-Fi chip top-right, blinking red / steady amber alert banner top-centre
diff_locks.cpp # Diff-lock inputs DI0 rear / DI1 front via CH422G EXIO0/EXIO5 ('difflock' console, Settings switch, default OFF)
settings_manager.cpp # NVS persistent storage 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
@@ -104,13 +109,14 @@ 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`), setup order, `loop()` ticks for the three screens - Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`, `link`), setup order, `loop()` ticks for the three screens
**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()`
- 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` - 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`) - **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 - UART config: 115200 baud on GPIO 44 (TX) / 43 (RX, unused) — leaves the board via the SP3485 RS485 transceiver
@@ -138,7 +144,7 @@ include/
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` (boolean values)
- 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
@@ -212,7 +218,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
### OTA updates (`ota` console) ### 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`). 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`. `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) ### Performance monitor (`perf` console)
@@ -220,16 +226,25 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
### ESP-NOW link ### 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. `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. Behind the Settings → System switch, default OFF, so a board without the wiring never flips the bank. The Driveline shows a top view of the chassis in the top-right corner, drawn from the user's sketch with `lv_line` objects and two border boxes, geometry in sketch pixels scaled by `DL_S`. All four tyres are the same square-cornered rectangle, and the wheelbase is the sketch's shortened by 20 %. A locked axle turns amber: axle, tyres filled solid, and an X on its diff. A filled tyre is one `lv_line` as wide as the tyre with square ends, because LVGL 8 cannot rotate a box. The front axle turns red if it reads locked without the rear. There is no text caption (user). The whole drawing is hidden when the switch is off; the System row's sub-line shows the live state for testing. Wiring and evidence: wiki `diff-lock-inputs`.
### Screens ### 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
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (installed vs latest, Check, Install behind a confirm dialog -> `Ota::requestCheck/requestInstall`), **System** (CAN / link to B / performance overlay switches, live ESP-NOW, CAN, memory, uptime). Swipe right or the Driveline button goes back - **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Main CTRL -> `Ota::requestCheck/requestInstall`, Inst. Cluster -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay / diff-lock input switches, live ESP-NOW, CAN, memory, uptime on the firmware line - the page is full at four rows). Swipe right or the Driveline button goes back
- **Gauge Tuning** (`tuning_screen.cpp`) - tabs Tachometer / Coolant gauge / Alerts / Simulation; -/+ rows with hints (hold to repeat, speeds up), per-tab Reset with confirm, "Saving... / All changes saved" footer, SIMULATION ON chip while an override is active. Swipe left or the Driveline button goes back - **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)
- 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 - 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 ## Configuration Files
@@ -328,6 +343,7 @@ xTaskCreatePinnedToCore(
### Build Errors ### 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). - **`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` - **Missing libraries**: Run `pio lib update` then `pio run --target clean`
- **Partition table not found**: Ensure `partition_table.csv` exists in project root - **Partition table not found**: Ensure `partition_table.csv` exists in project root
+4 -2
View File
@@ -5,7 +5,7 @@ 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), Settings (Wi-Fi / Updates / System), 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
@@ -35,6 +35,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 +76,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
``` ```
+201
View File
@@ -0,0 +1,201 @@
# 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)
```
Wiring: lock wire (+12 V when locked) → DI0 / DI1, `DI_COM` → vehicle ground. Details: wiki `diff-lock-inputs`.
### 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
```
+20 -8
View File
@@ -1,9 +1,9 @@
# Link Protocol Specification (v2) # Link Protocol Specification (v2)
**Version:** 2 (`PACKET_VERSION 0x02`) **Version:** 2 (`PACKET_VERSION 0x02`)
**Last Updated:** 2026-09-21 **Last Updated:** 2026-09-27
**Source of truth:** `include/protocol/automotive_data.h` — byte-identical in both repos. **Source of truth:** `include/protocol/automotive_data.h` (+ `link_secure.h`) — byte-identical in both repos.
**Direction:** Controller A (ESP32-S3-Touch-LCD-5B) → Controller B (ESP32-S3-LCD-1.3), one way. **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.
--- ---
@@ -28,8 +28,8 @@ The same frames are sent on two paths at once. B accepts either and deduplicates
|---|---|---| |---|---|---|
| start | 1 | `0xAA` | | start | 1 | `0xAA` |
| version | 1 | `0x02` — B rejects any other value (counted as version error) | | version | 1 | `0x02` — B rejects any other value (counted as version error) |
| type | 1 | `0x01` DATA, `0x02` CONFIG | | type | 1 | `0x01` DATA, `0x02` CONFIG, `0x03` STATUS, `0x04` PAIR, `0x05` SECURE |
| length | 1 | payload bytes (21 for DATA, 27 for CONFIG) | | length | 1 | payload bytes (21 DATA, 27 CONFIG, 78 STATUS, 42 PAIR, 29–160 SECURE); `PACKET_MAX_PAYLOAD` = 160 |
| payload | length | see below, little-endian, packed | | payload | length | see below, little-endian, packed |
| checksum | 1 | XOR of version, type, length and every payload byte | | checksum | 1 | XOR of version, type, length and every payload byte |
| end | 1 | `0x55` | | end | 1 | `0x55` |
@@ -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,6 +120,18 @@ The same console also carries the OBD-II diagnostic probe (`diag pids | pid <hex
--- ---
## 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.
| 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 "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) |
| `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 |
B reports `key_fp` = first two bytes of SHA-256(key) so A can tell "paired with my key" from "paired with an old one" and re-pair.
## Receiver behaviour (B) ## Receiver behaviour (B)
- Link considered lost after 1000 ms without an applied DATA frame on any transport; display shows N/A and both gauge outputs go low. - Link considered lost after 1000 ms without an applied DATA frame on any transport; display shows N/A and both gauge outputs go low.
@@ -131,7 +143,7 @@ The same console also carries the OBD-II diagnostic probe (`diag pids | pid <hex
## Changing the protocol ## Changing the protocol
1. Edit `automotive_data.h` on A, bump `PACKET_VERSION`. 1. Edit `automotive_data.h` on A. Bump `PACKET_VERSION` if DATA or CONFIG change; adding a new frame type does not need a bump (a stale B ignores unknown types).
2. Copy the header to B unchanged. 2. Copy the header (and `link_secure.h`) to B unchanged (`cmp` them).
3. Update this document. 3. Update this document.
4. Flash both. A stale B logs version errors and applies nothing. 4. Flash both. A stale B logs version errors and applies nothing.
+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"
+1 -1
View File
@@ -69,7 +69,7 @@ typedef struct {
/** /**
* 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.
* *
+114 -20
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.
@@ -16,6 +16,13 @@
* - link_config_t: Patrol gauge calibration + alert thresholds, edited on A, * - link_config_t: Patrol gauge calibration + alert thresholds, edited on A,
* executed on B (tach + coolant PWM outputs) * executed on B (tach + coolant PWM outputs)
* - the same frames go out on UART1 and ESP-NOW; B dedupes by packet_id * - the same frames go out on UART1 and ESP-NOW; B dedupes by packet_id
*
* v2 additions (2026-09-27, PACKET_VERSION unchanged - DATA/CONFIG are the same
* bytes, an older B counts the new types as FRAME_ERR_TYPE and carries on):
* - STATUS B -> A (ESP-NOW unicast): B's version, OTA phase, uptime
* - PAIR A -> B (UART wire ONLY): the shared secret for SECURE frames
* - SECURE A -> B (ESP-NOW unicast): AES-256-GCM envelope carrying an
* OTA_CMD or WIFI_CREDS payload. See ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md
*/ */
#ifndef _AUTOMOTIVE_DATA_H #ifndef _AUTOMOTIVE_DATA_H
@@ -38,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)
@@ -53,12 +60,19 @@
#define PACKET_END_BYTE 0x55 #define PACKET_END_BYTE 0x55
#define PACKET_VERSION 0x02 #define PACKET_VERSION 0x02
#define PACKET_TYPE_DATA 0x01 // payload = automotive_data_t #define PACKET_TYPE_DATA 0x01 // A -> B payload = automotive_data_t
#define PACKET_TYPE_CONFIG 0x02 // payload = link_config_t #define PACKET_TYPE_CONFIG 0x02 // A -> B payload = link_config_t
#define PACKET_TYPE_STATUS 0x03 // B -> A payload = link_status_t (ESP-NOW unicast)
#define PACKET_TYPE_PAIR 0x04 // A -> B payload = link_pair_t (UART wire only, never radio)
#define PACKET_TYPE_SECURE 0x05 // A -> B payload = secure envelope, see LINK MAINTENANCE below
// Inner types carried inside a SECURE envelope (never on the wire in the clear):
#define LINK_INNER_OTA_CMD 0x11 // link_ota_cmd_t
#define LINK_INNER_WIFI_CREDS 0x12 // link_wifi_creds_t
#define PACKET_HEADER_SIZE 4 // start, version, type, length #define PACKET_HEADER_SIZE 4 // start, version, type, length
#define PACKET_TRAILER_SIZE 2 // checksum, end #define PACKET_TRAILER_SIZE 2 // checksum, end
#define PACKET_MAX_PAYLOAD 64 #define PACKET_MAX_PAYLOAD 160 // was 64 until 2026-09-27; SECURE(WIFI_CREDS) needs 127.
// Whole frame 166 B < ESP-NOW's 250 B limit.
#define PACKET_MAX_SIZE (PACKET_HEADER_SIZE + PACKET_MAX_PAYLOAD + PACKET_TRAILER_SIZE) #define PACKET_MAX_SIZE (PACKET_HEADER_SIZE + PACKET_MAX_PAYLOAD + PACKET_TRAILER_SIZE)
// ============================================================================ // ============================================================================
@@ -76,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,
@@ -201,6 +215,88 @@ static inline void link_config_defaults(link_config_t* c) {
c->battery_low_x100 = 1100; c->battery_low_x100 = 1100;
} }
// ============================================================================
// 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
// and the trigger. Both repos are public, so nothing secret is compiled in:
// the shared key is generated on A at pairing time and travels to B over the
// UART wire only. Everything A later sends B by radio that matters (Wi-Fi
// credentials, OTA commands) goes inside a SECURE envelope under that key.
// STATUS frames carry nothing secret and go in the clear.
#define LINK_KEY_LEN 32 // AES-256
#define LINK_NONCE_LEN 12 // GCM IV, random per frame
#define LINK_TAG_LEN 16 // GCM tag
#define LINK_STATUS_PERIOD_MS 5000 // B -> A STATUS cadence
#define LINK_STATUS_TIMEOUT_MS 15000 // A: B "not heard" after this
// --- PAIR (A -> B, wire only) -----------------------------------------------
#define LINK_PAIR_MAGIC 0x52494150UL // "PAIR"
typedef struct __attribute__((packed)) {
uint32_t magic; // LINK_PAIR_MAGIC - guards against a torn frame
uint8_t key[LINK_KEY_LEN]; // the shared secret; both sides keep it in NVS
uint8_t a_mac[6]; // A's STA MAC: the only sender B accepts SECURE frames from
} link_pair_t; // 42 bytes
// --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ----------
// ota_phase mirrors Main CTRL's Ota::phase_t so one UI renders both.
#define LINK_OTA_IDLE 0
#define LINK_OTA_CHECKING 1
#define LINK_OTA_UP_TO_DATE 2
#define LINK_OTA_AVAILABLE 3
#define LINK_OTA_INSTALLING 4
#define LINK_OTA_FAILED 5
#define LINK_STATUS_PAIRED (1 << 0) // B holds a pairing key
#define LINK_STATUS_HAVE_WIFI (1 << 1) // B holds Wi-Fi credentials
#define LINK_STATUS_WIFI_JOINED (1 << 2) // B is currently on the network (during a job)
#define LINK_STATUS_PENDING_VERIFY (1 << 3) // B runs a fresh image not yet confirmed
typedef struct __attribute__((packed)) {
char version[16]; // B's firmware version ("dev" for local builds)
uint8_t ota_phase; // LINK_OTA_*
uint8_t ota_progress; // 0..100 while installing
uint8_t flags; // LINK_STATUS_*
uint8_t reserved;
uint16_t key_fp; // first two bytes of SHA-256(pairing key); 0 = unpaired.
// Lets A see "paired with MY key" vs "paired with an old one".
uint32_t uptime_s;
uint32_t free_heap; // internal heap free, bytes
char latest[16]; // latest release tag B knows of ("" = never checked)
char message[32]; // failure reason when ota_phase == LINK_OTA_FAILED
} link_status_t; // 78 bytes
// --- OTA_CMD (inner, A -> B) ------------------------------------------------
#define LINK_OTA_CMD_CHECK 1
#define LINK_OTA_CMD_INSTALL 2
#define LINK_OTA_CMD_ROLLBACK 3
#define LINK_OTA_FORCE (1 << 0) // reinstall even if versions match
typedef struct __attribute__((packed)) {
uint8_t cmd; // LINK_OTA_CMD_*
uint8_t flags; // LINK_OTA_FORCE
uint32_t nonce; // random; B drops a repeat of a recently seen one
} link_ota_cmd_t; // 6 bytes
// --- WIFI_CREDS (inner, A -> B) ---------------------------------------------
#define LINK_WIFI_SET 1
#define LINK_WIFI_FORGET 2
typedef struct __attribute__((packed)) {
uint8_t action; // LINK_WIFI_*
char ssid[33];
char pass[64];
} link_wifi_creds_t; // 98 bytes
// --- SECURE envelope ---------------------------------------------------------
// payload = nonce[12] | tag[16] | ciphertext
// ciphertext = AES-256-GCM(key, nonce, plaintext = inner_type | inner_payload)
// Helpers that do the encryption live in protocol/link_secure.h (mbedtls).
#define LINK_SECURE_OVERHEAD (LINK_NONCE_LEN + LINK_TAG_LEN)
#define LINK_SECURE_MAX_INNER (PACKET_MAX_PAYLOAD - LINK_SECURE_OVERHEAD) // 132: 1 + 98 fits
// ============================================================================ // ============================================================================
// CAN BUS ID MAPPINGS (BMW-Specific) // CAN BUS ID MAPPINGS (BMW-Specific)
// ============================================================================ // ============================================================================
@@ -413,6 +509,12 @@ static inline frame_status_t frame_parse(const uint8_t* f, size_t n,
if (l != sizeof(automotive_data_t)) return FRAME_ERR_TYPE; if (l != sizeof(automotive_data_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_CONFIG) { } else if (t == PACKET_TYPE_CONFIG) {
if (l != sizeof(link_config_t)) return FRAME_ERR_TYPE; if (l != sizeof(link_config_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_STATUS) {
if (l != sizeof(link_status_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_PAIR) {
if (l != sizeof(link_pair_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_SECURE) {
if (l < LINK_SECURE_OVERHEAD + 1) return FRAME_ERR_TYPE; // at least the inner type byte
} else { } else {
return FRAME_ERR_TYPE; return FRAME_ERR_TYPE;
} }
@@ -654,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;
} }
@@ -670,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
+93
View File
@@ -0,0 +1,93 @@
/**
* link_secure.h - the SECURE envelope of the A <-> B link (see automotive_data.h).
*
* THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS, like automotive_data.h.
*
* payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner)
*
* 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.
*/
#ifndef LINK_SECURE_H
#define LINK_SECURE_H
#include "automotive_data.h"
#include <mbedtls/gcm.h>
#include <mbedtls/sha256.h>
#include <mbedtls/version.h>
#if __has_include(<esp_random.h>)
#include <esp_random.h>
#else
#include <esp_system.h> // IDF 4.4: esp_random / esp_fill_random live here
#endif
/** First two bytes of SHA-256(key), never 0 (0 means "unpaired" on the wire). */
static inline uint16_t link_key_fingerprint(const uint8_t key[LINK_KEY_LEN]) {
uint8_t h[32];
#if MBEDTLS_VERSION_MAJOR >= 3
mbedtls_sha256(key, LINK_KEY_LEN, h, 0);
#else
mbedtls_sha256_ret(key, LINK_KEY_LEN, h, 0);
#endif
uint16_t fp = (uint16_t)((h[0] << 8) | h[1]);
return fp ? fp : 1;
}
/**
* Seal inner_type + inner into a SECURE payload.
* @param out buffer of PACKET_MAX_PAYLOAD bytes
* @return payload length, or 0 on error / oversize
*/
static inline size_t link_secure_seal(const uint8_t key[LINK_KEY_LEN], uint8_t inner_type,
const void* inner, size_t inner_len, uint8_t* out) {
if (inner_len + 1 > LINK_SECURE_MAX_INNER) return 0;
uint8_t plain[LINK_SECURE_MAX_INNER];
plain[0] = inner_type;
memcpy(&plain[1], inner, inner_len);
size_t n = inner_len + 1;
uint8_t* nonce = out;
uint8_t* tag = out + LINK_NONCE_LEN;
uint8_t* ct = out + LINK_SECURE_OVERHEAD;
esp_fill_random(nonce, LINK_NONCE_LEN);
mbedtls_gcm_context g;
mbedtls_gcm_init(&g);
int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8);
if (rc == 0) {
rc = mbedtls_gcm_crypt_and_tag(&g, MBEDTLS_GCM_ENCRYPT, n, nonce, LINK_NONCE_LEN,
NULL, 0, plain, ct, LINK_TAG_LEN, tag);
}
mbedtls_gcm_free(&g);
return rc == 0 ? LINK_SECURE_OVERHEAD + n : 0;
}
/**
* Open a SECURE payload. On success *inner_type and inner (LINK_SECURE_MAX_INNER
* bytes) are filled; *inner_len excludes the type byte.
*/
static inline bool link_secure_open(const uint8_t key[LINK_KEY_LEN], const uint8_t* payload, size_t len,
uint8_t* inner_type, uint8_t* inner, size_t* inner_len) {
if (len < LINK_SECURE_OVERHEAD + 1 || len > PACKET_MAX_PAYLOAD) return false;
size_t n = len - LINK_SECURE_OVERHEAD;
uint8_t plain[LINK_SECURE_MAX_INNER];
mbedtls_gcm_context g;
mbedtls_gcm_init(&g);
int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8);
if (rc == 0) {
rc = mbedtls_gcm_auth_decrypt(&g, n, payload, LINK_NONCE_LEN, NULL, 0,
payload + LINK_NONCE_LEN, LINK_TAG_LEN,
payload + LINK_SECURE_OVERHEAD, plain);
}
mbedtls_gcm_free(&g);
if (rc != 0) return false;
*inner_type = plain[0];
*inner_len = n - 1;
memcpy(inner, &plain[1], n - 1);
return true;
}
#endif // LINK_SECURE_H
+19
View File
@@ -42,6 +42,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 +54,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).
@@ -523,6 +540,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 +613,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;
} }
} }
+13 -3
View File
@@ -14,9 +14,12 @@
#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" // Inst. Cluster status, pairing, credential handoff, B updates (`link` console)
#include "modules/status_overlay.h" // Every screen: Wi-Fi chip top-right, blinking alert banner top-centre
#include "modules/diff_locks.h" // Diff-lock inputs DI0 rear / DI1 front via the CH422G (`difflock` console)
// ============================================================================ // ============================================================================
// MINIMAL LVGL + UI SETTINGS + WIFI + UART // MINIMAL LVGL + UI SETTINGS + WIFI + UART
@@ -55,11 +58,12 @@ 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); PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
DiffLocks::handleCommand(line);
} }
// ============================================================================ // ============================================================================
@@ -87,6 +91,7 @@ void setup()
ESP_LOGI("MAIN", "Initializing display and UI..."); ESP_LOGI("MAIN", "Initializing display and UI...");
DisplayInit::init(); DisplayInit::init();
ESP_LOGI("MAIN", "Display init COMPLETED!"); ESP_LOGI("MAIN", "Display init COMPLETED!");
StatusOverlay::init(); // Wi-Fi chip + alert banner on lv_layer_top(), above every screen
// Initialize Settings Manager // Initialize Settings Manager
ESP_LOGI("MAIN", "Initializing Settings Manager..."); ESP_LOGI("MAIN", "Initializing Settings Manager...");
@@ -104,6 +109,7 @@ 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()); // CH422G bus is up since DisplayInit
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
@@ -117,6 +123,7 @@ void setup()
// ESP-NOW transmit leg (needs the radio in STA mode, which WiFiManager keeps) // ESP-NOW transmit leg (needs the radio in STA mode, which WiFiManager keeps)
ESP_LOGI("MAIN", "Initializing ESP-NOW link..."); ESP_LOGI("MAIN", "Initializing ESP-NOW link...");
EspNowLink::init(); EspNowLink::init();
LinkPeer::init(); // B's STATUS frames, pairing key, credential handoff
// Initialize UART subsystem using UARTManager module // Initialize UART subsystem using UARTManager module
ESP_LOGI("MAIN", "Initializing UART subsystem..."); ESP_LOGI("MAIN", "Initializing UART subsystem...");
@@ -160,10 +167,13 @@ 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(); // Inst. Cluster heard/lost, credential sync
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
DrivelineScreen::tick(); DrivelineScreen::tick();
TuningScreen::tick(); TuningScreen::tick();
SettingsScreen::tick(); SettingsScreen::tick();
StatusOverlay::tick();
delay(100); // Check frequently to catch screen changes quickly delay(100); // Check frequently to catch screen changes quickly
} }
+149
View File
@@ -0,0 +1,149 @@
/*
* 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_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) {
g_enabled = enabled;
print("[difflock] %s (DI0 = rear, DI1 = front)", enabled ? "ON" : "OFF - Settings > System to enable");
}
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);
}
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))) {
bool rear = !(bits & BIT_REAR); // opto conducting = pin low = locked
bool front = !(bits & BIT_FRONT);
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 (!*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 | raw IO0-7 0x%02X | %lu reads, %lu failed%s",
!isValid() ? "?" : g_rear ? "LOCKED" : "open",
!isValid() ? "?" : g_front ? "LOCKED" : "open",
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 (DI0 = rear, DI1 = front, 12 V = locked)");
return true;
}
} // namespace DiffLocks
+38
View File
@@ -0,0 +1,38 @@
/*
* 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);
/** Settings switch / `difflock on|off`. Saved to NVS (SettingsManager). */
void setEnabled(bool enabled);
bool isEnabled();
/** 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`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace DiffLocks
+217 -14
View File
@@ -5,10 +5,12 @@
#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 "esp_log.h" #include "esp_log.h"
namespace DrivelineScreen { namespace DrivelineScreen {
@@ -24,6 +26,8 @@ namespace DrivelineScreen {
#define COL_ACCENT lv_color_hex(0x3DA9FC) #define COL_ACCENT lv_color_hex(0x3DA9FC)
#define COL_OK lv_color_hex(0x3DD68C) #define COL_OK lv_color_hex(0x3DD68C)
#define COL_WARN lv_color_hex(0xE5484D) #define COL_WARN lv_color_hex(0xE5484D)
#define COL_ALERT lv_color_hex(0xFF3B30) // threshold crossed: value + title
#define COL_AMBER lv_color_hex(0xF5A524)
#define RPM_MAX 5000 // M57N redline is ~4500; a little headroom #define RPM_MAX 5000 // M57N redline is ~4500; a little headroom
@@ -36,6 +40,8 @@ static lv_obj_t* g_gear_lbl = NULL;
static lv_obj_t* g_gear_ring = NULL; static lv_obj_t* g_gear_ring = NULL;
static lv_obj_t* g_coolant_lbl = NULL; static lv_obj_t* g_coolant_lbl = NULL;
static lv_obj_t* g_gearbox_lbl = NULL; static lv_obj_t* g_gearbox_lbl = NULL;
static lv_obj_t* g_coolant_title = NULL;
static lv_obj_t* g_gearbox_title = NULL;
static lv_obj_t* g_rpm_bar = NULL; static lv_obj_t* g_rpm_bar = NULL;
static lv_obj_t* g_rpm_lbl = NULL; static lv_obj_t* g_rpm_lbl = NULL;
static lv_obj_t* g_torque_lbl = NULL; static lv_obj_t* g_torque_lbl = NULL;
@@ -45,7 +51,7 @@ 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_mismatch_lbl = NULL; static lv_obj_t* g_diff_box = NULL; // top-right: chassis top view, locked axles lit
// ============================================================================ // ============================================================================
// PRIVATE HELPERS // PRIVATE HELPERS
@@ -81,6 +87,21 @@ static void setText(lv_obj_t* lbl, const char* text) {
lv_label_set_text(lbl, text); lv_label_set_text(lbl, text);
} }
/** Text colour, written only on change (a style write invalidates regardless). */
static void setColour(lv_obj_t* o, lv_color_t colour) {
if (o == NULL) return;
if (lv_color_to32(lv_obj_get_style_text_color(o, 0)) != lv_color_to32(colour)) {
lv_obj_set_style_text_color(o, colour, 0);
}
}
/** Ring border colour, written only on change. */
static void setRing(lv_color_t colour) {
if (lv_color_to32(lv_obj_get_style_border_color(g_gear_ring, 0)) != lv_color_to32(colour)) {
lv_obj_set_style_border_color(g_gear_ring, colour, 0);
}
}
/** /**
* @brief Set a chip's text and colour, touching the object only on a change * @brief Set a chip's text and colour, touching the object only on a change
* (a style write invalidates the object even for an identical value). * (a style write invalidates the object even for an identical value).
@@ -93,6 +114,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.
* *
@@ -184,20 +341,48 @@ static void build() {
lv_obj_set_size(bar, LV_SIZE_CONTENT, LV_SIZE_CONTENT); lv_obj_set_size(bar, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(bar, LV_FLEX_FLOW_ROW); lv_obj_set_flex_flow(bar, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(bar, 8, 0); lv_obj_set_style_pad_column(bar, 8, 0);
lv_obj_align(bar, LV_ALIGN_TOP_LEFT, 24, 18); // y 60: the top 56 px belong to the StatusOverlay (alert banner centre, Wi-Fi chip right)
lv_obj_align(bar, LV_ALIGN_TOP_LEFT, 24, 60);
lv_obj_clear_flag(bar, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(bar, LV_OBJ_FLAG_SCROLLABLE);
g_ign_chip = makeChip(bar, "IGN --"); g_ign_chip = makeChip(bar, "IGN --");
g_eng_chip = makeChip(bar, "ENG --"); g_eng_chip = makeChip(bar, "ENG --");
g_clutch_chip = makeChip(bar, "CLUTCH --"); g_clutch_chip = makeChip(bar, "CLUTCH --");
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.
// ---- 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);
g_mismatch_lbl = lv_label_create(g_screen);
lv_label_set_text(g_mismatch_lbl, LV_SYMBOL_WARNING " GEAR MISMATCH");
lv_obj_set_style_text_font(g_mismatch_lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_mismatch_lbl, COL_WARN, 0);
lv_obj_align(g_mismatch_lbl, LV_ALIGN_TOP_RIGHT, -24, 24);
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
// ---- gear hero ------------------------------------------------------- // ---- gear hero -------------------------------------------------------
g_gear_ring = lv_obj_create(g_screen); g_gear_ring = lv_obj_create(g_screen);
@@ -220,6 +405,8 @@ static void build() {
LV_ALIGN_LEFT_MID, 110, -40); LV_ALIGN_LEFT_MID, 110, -40);
g_gearbox_lbl = makeStat(g_screen, "GEARBOX OIL", &lv_font_montserrat_40, g_gearbox_lbl = makeStat(g_screen, "GEARBOX OIL", &lv_font_montserrat_40,
LV_ALIGN_RIGHT_MID, -110, -40); LV_ALIGN_RIGHT_MID, -110, -40);
g_coolant_title = lv_obj_get_child(lv_obj_get_parent(g_coolant_lbl), 0);
g_gearbox_title = lv_obj_get_child(lv_obj_get_parent(g_gearbox_lbl), 0);
// ---- RPM bar --------------------------------------------------------- // ---- RPM bar ---------------------------------------------------------
lv_obj_t* rpm_title = lv_label_create(g_screen); lv_obj_t* rpm_title = lv_label_create(g_screen);
@@ -291,11 +478,13 @@ void tick() {
uint8_t gear = GEAR_UNKNOWN; uint8_t gear = GEAR_UNKNOWN;
int16_t coolant = 0, gearbox = 0; int16_t coolant = 0, gearbox = 0;
uint8_t flags = 0; uint8_t flags = 0;
uint16_t alerts = 0;
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) { if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
gear = UARTManager::g_automotive_data.gear_lever; gear = UARTManager::g_automotive_data.gear_lever;
coolant = UARTManager::g_automotive_data.coolant_temp; coolant = UARTManager::g_automotive_data.coolant_temp;
gearbox = UARTManager::g_automotive_data.gearbox_oil_temp; gearbox = UARTManager::g_automotive_data.gearbox_oil_temp;
flags = UARTManager::g_automotive_data.valid_flags; flags = UARTManager::g_automotive_data.valid_flags;
alerts = UARTManager::g_automotive_data.alerts;
xSemaphoreGive(UARTManager::g_data_mutex); xSemaphoreGive(UARTManager::g_data_mutex);
} else { } else {
return; // couldn't read; leave the last frame on screen return; // couldn't read; leave the last frame on screen
@@ -305,6 +494,8 @@ 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
@@ -318,7 +509,10 @@ void tick() {
setText(g_pedal_lbl, "--"); setText(g_pedal_lbl, "--");
setText(g_shaft_lbl, "--"); setText(g_shaft_lbl, "--");
lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF); lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF);
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN); setRing(COL_ACCENT);
setColour(g_gear_lbl, COL_TEXT);
setColour(g_coolant_lbl, COL_TEXT); setColour(g_coolant_title, COL_MUTED);
setColour(g_gearbox_lbl, COL_TEXT); setColour(g_gearbox_title, COL_MUTED);
// Leave the ignition chip telling the truth; mute the rest, since their // Leave the ignition chip telling the truth; mute the rest, since their
// values are meaningless with the key out (or absent with CAN off). // values are meaningless with the key out (or absent with CAN off).
if (!can_up) { if (!can_up) {
@@ -352,6 +546,17 @@ void tick() {
setText(g_gearbox_lbl, buf); setText(g_gearbox_lbl, buf);
} }
// ---- thresholds crossed: the value AND its title go red (amber while the
// box only asks for cooling); the overlay banner blinks on top of it all.
if (!(flags & VALID_FLAG_ALERTS)) alerts = 0;
bool cool_hot = (alerts & ALERT_COOLANT_HOT) != 0;
bool gb_hot = (alerts & ALERT_GEARBOX_HOT) != 0;
bool gb_cool = (alerts & ALERT_GEARBOX_COOLING) != 0;
setColour(g_coolant_lbl, cool_hot ? COL_ALERT : COL_TEXT);
setColour(g_coolant_title, cool_hot ? COL_ALERT : COL_MUTED);
setColour(g_gearbox_lbl, gb_hot ? COL_ALERT : gb_cool ? COL_AMBER : COL_TEXT);
setColour(g_gearbox_title, gb_hot ? COL_ALERT : gb_cool ? COL_AMBER : COL_MUTED);
// ---- speeds ---------------------------------------------------------- // ---- speeds ----------------------------------------------------------
snprintf(buf, sizeof(buf), "%u", dl.engine_rpm); snprintf(buf, sizeof(buf), "%u", dl.engine_rpm);
setText(g_rpm_lbl, buf); setText(g_rpm_lbl, buf);
@@ -394,11 +599,9 @@ void tick() {
default: setChip(g_cool_chip, "COOLING ?", COL_MUTED); break; default: setChip(g_cool_chip, "COOLING ?", COL_MUTED); break;
} }
if (dl.gear_mismatch) { // Gear mismatch: the hero ring and the gear letter turn red.
lv_obj_clear_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN); setRing(dl.gear_mismatch ? COL_ALERT : COL_ACCENT);
} else { setColour(g_gear_lbl, dl.gear_mismatch ? COL_ALERT : COL_TEXT);
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
}
lvgl_port_unlock(); lvgl_port_unlock();
} }
+31 -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"
@@ -16,6 +16,13 @@ static const uint8_t BROADCAST_MAC[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
static bool g_ready = false; static bool g_ready = false;
static uint32_t g_sent = 0; static uint32_t g_sent = 0;
static uint32_t g_fail = 0; static uint32_t g_fail = 0;
static receive_handler_t g_rx_handler = NULL;
// IDF 5.x receive callback: sender MAC is in the info struct.
static void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len) {
if (g_rx_handler == NULL || info == NULL || len <= 0) return;
g_rx_handler(info->src_addr, data, (size_t)len);
}
// IDF 5.5 (pioarduino / Arduino 3.3) passes wifi_tx_info_t*; older cores passed the MAC. // IDF 5.5 (pioarduino / Arduino 3.3) passes wifi_tx_info_t*; older cores passed the MAC.
static void onSent(const wifi_tx_info_t* info, esp_now_send_status_t status) { static void onSent(const wifi_tx_info_t* info, esp_now_send_status_t status) {
@@ -45,6 +52,7 @@ bool init() {
return false; return false;
} }
esp_now_register_send_cb(onSent); esp_now_register_send_cb(onSent);
esp_now_register_recv_cb(onReceive);
esp_now_peer_info_t peer = {}; esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, BROADCAST_MAC, 6); memcpy(peer.peer_addr, BROADCAST_MAC, 6);
@@ -93,4 +101,26 @@ bool isReady() { return g_ready; }
uint32_t sentCount() { return g_sent; } uint32_t sentCount() { return g_sent; }
uint32_t failCount() { return g_fail; } uint32_t failCount() { return g_fail; }
void setReceiveHandler(receive_handler_t handler) { g_rx_handler = handler; }
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len) {
if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
if (!g_ready) {
reinitIfDue();
if (!g_ready) return false;
}
if (!esp_now_is_peer_exist(mac)) {
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, mac, 6);
peer.channel = 0; // current channel
peer.encrypt = false; // SECURE frames carry their own encryption
peer.ifidx = WIFI_IF_STA;
if (esp_now_add_peer(&peer) != ESP_OK) {
ESP_LOGE("EspNow", "esp_now_add_peer(B) failed");
return false;
}
}
return esp_now_send(mac, frame, len) == ESP_OK;
}
} // namespace EspNowLink } // namespace EspNowLink
+12 -1
View File
@@ -1,10 +1,14 @@
/* /*
* ESP-NOW Link Module (Controller A side, transmit only) * 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.
* B dedupes on packet_id, so both paths may be live at once. * B dedupes on packet_id, so both paths may be live at once.
* *
* Since 2026-09-27 the radio also listens: B unicasts STATUS frames back and
* A unicasts SECURE frames to B (LinkPeer). Frames received are handed to the
* handler set with setReceiveHandler(); sendTo() unicasts to one MAC.
*
* Radio policy: the Wi-Fi radio stays in STA mode permanently (the WiFi * Radio policy: the Wi-Fi radio stays in STA mode permanently (the WiFi
* manager's "off" only stops scanning). A transmits on ESPNOW_CHANNEL unless * manager's "off" only stops scanning). A transmits on ESPNOW_CHANNEL unless
* associated to an access point, in which case the AP's channel is used and * associated to an access point, in which case the AP's channel is used and
@@ -34,4 +38,11 @@ bool isReady();
uint32_t sentCount(); uint32_t sentCount();
uint32_t failCount(); uint32_t failCount();
/** Frames received from any sender (runs in the Wi-Fi task - copy and return). */
typedef void (*receive_handler_t)(const uint8_t mac[6], const uint8_t* frame, size_t len);
void setReceiveHandler(receive_handler_t handler);
/** Unicast one complete frame to a MAC (peer added on first use, unencrypted). */
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len);
} // namespace EspNowLink } // namespace EspNowLink
+370
View File
@@ -0,0 +1,370 @@
/*
* Link Peer Module Implementation (Main CTRL)
*
* 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.
*/
#include "link_peer.h"
#include "espnow_link.h"
#include "uart_manager.h"
#include "wifi_manager.h"
#include "ota_update.h"
#include "serial_lock.h"
#include "protocol/link_secure.h"
#include <Preferences.h>
#include <esp_wifi.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
namespace LinkPeer {
static const char* NVS_LINK = "linkpeer"; // key (32 B)
#define CREDS_PUSH_MIN_MS 15000 // never push credentials more often than this
#define PAIR_REPEATS 3 // PAIR is sent this many times over the wire
static bool g_paired = false;
static uint8_t g_key[LINK_KEY_LEN];
static uint16_t g_key_fp = 0;
// last STATUS from B (written by the Wi-Fi task)
static SemaphoreHandle_t g_mutex = NULL;
static link_status_t g_st = {};
static uint8_t g_b_mac[6] = {0};
static uint32_t g_last_status_ms = 0;
static bool g_ever_heard = false;
static uint32_t g_status_count = 0, g_secure_sent = 0, g_secure_fail = 0;
// credential sync
static uint32_t g_pushed_hash = 0;
static uint32_t g_last_push_ms = 0;
static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); }
static void unlock() { xSemaphoreGive(g_mutex); }
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 const char* phaseName(uint8_t p) {
switch (p) {
case LINK_OTA_CHECKING: return "checking";
case LINK_OTA_UP_TO_DATE: return "up to date";
case LINK_OTA_AVAILABLE: return "update available";
case LINK_OTA_INSTALLING: return "installing";
case LINK_OTA_FAILED: return "failed";
default: return "idle";
}
}
// ---- NVS --------------------------------------------------------------------
static void loadKey() {
Preferences p;
p.begin(NVS_LINK, true);
g_paired = p.getBytesLength("key") == LINK_KEY_LEN;
if (g_paired) p.getBytes("key", g_key, LINK_KEY_LEN);
p.end();
g_key_fp = g_paired ? link_key_fingerprint(g_key) : 0;
}
static void storeKey() {
Preferences p;
p.begin(NVS_LINK, false);
p.putBytes("key", g_key, LINK_KEY_LEN);
p.end();
}
static void clearKey() {
Preferences p;
p.begin(NVS_LINK, false);
p.clear();
p.end();
g_paired = false;
g_key_fp = 0;
memset(g_key, 0, sizeof(g_key));
}
// ---- inbound (Wi-Fi task) ---------------------------------------------------
static void onFrame(const uint8_t mac[6], const uint8_t* frame, size_t len) {
uint8_t type = 0, plen = 0;
const uint8_t* payload = NULL;
if (frame_parse(frame, len, &type, &payload, &plen) != FRAME_OK) return;
if (type != PACKET_TYPE_STATUS) return;
if (xSemaphoreTake(g_mutex, pdMS_TO_TICKS(10)) != pdTRUE) return;
memcpy(&g_st, payload, sizeof(g_st));
g_st.version[sizeof(g_st.version) - 1] = 0;
g_st.latest[sizeof(g_st.latest) - 1] = 0;
g_st.message[sizeof(g_st.message) - 1] = 0;
memcpy(g_b_mac, mac, 6);
g_last_status_ms = millis();
g_ever_heard = true;
g_status_count++;
xSemaphoreGive(g_mutex);
}
// ---- public: status ---------------------------------------------------------
peer_status_t getStatus() {
peer_status_t p = {};
lock();
p.st = g_st;
memcpy(p.mac, g_b_mac, 6);
uint32_t last = g_last_status_ms;
bool ever = g_ever_heard;
unlock();
p.age_ms = ever ? millis() - last : 0xFFFFFFFF;
p.heard = ever && p.age_ms < LINK_STATUS_TIMEOUT_MS;
p.paired = g_paired;
p.key_fp = g_key_fp;
p.key_match = g_paired && p.st.key_fp == g_key_fp;
return p;
}
// ---- outbound ---------------------------------------------------------------
static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) {
peer_status_t p = getStatus();
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.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];
size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload);
if (!plen) { snprintf(why, n, "encryption failed"); return false; }
size_t flen = frame_build(PACKET_TYPE_SECURE, payload, (uint8_t)plen, frame);
if (!flen || !EspNowLink::sendTo(p.mac, frame, flen)) {
g_secure_fail++;
snprintf(why, n, "ESP-NOW send failed");
return false;
}
g_secure_sent++;
return true;
}
static bool sendOtaCmd(uint8_t cmd, uint8_t flags, char* why, size_t n) {
link_ota_cmd_t c = {};
c.cmd = cmd;
c.flags = flags;
c.nonce = esp_random();
return sendSecure(LINK_INNER_OTA_CMD, &c, sizeof(c), why, n);
}
static uint32_t hashStr(uint32_t h, const char* s) {
for (; *s; s++) h = (h ^ (uint8_t)*s) * 16777619u; // FNV-1a
return h;
}
/** Push A's remembered network (or a FORGET) to B. */
static bool pushCredentials(char* why, size_t n, bool log) {
link_wifi_creds_t c = {};
char pass[65];
bool have = WiFiManager::getSavedCredentials(c.ssid, sizeof(c.ssid), pass, sizeof(pass));
if (have) {
c.action = LINK_WIFI_SET;
strlcpy(c.pass, pass, sizeof(c.pass));
} else {
c.action = LINK_WIFI_FORGET;
}
bool ok = sendSecure(LINK_INNER_WIFI_CREDS, &c, sizeof(c), why, n);
memset(pass, 0, sizeof(pass));
if (ok) {
g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1;
g_last_push_ms = millis();
if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Inst. Cluster (encrypted)"
: "[link] told Inst. Cluster to forget its Wi-Fi credentials", c.ssid);
}
memset(&c, 0, sizeof(c));
return ok;
}
// B lacks credentials A has, or A's changed, or A forgot them while B still has them.
static void syncCredentials() {
peer_status_t p = getStatus();
if (!p.heard || !p.paired || !p.key_match) return;
if (millis() - g_last_push_ms < CREDS_PUSH_MIN_MS && g_last_push_ms != 0) return;
char ssid[33], pass[65];
bool have = WiFiManager::getSavedCredentials(ssid, sizeof(ssid), pass, sizeof(pass));
uint32_t h = have ? hashStr(hashStr(2166136261u, ssid), pass) : 1;
memset(pass, 0, sizeof(pass));
bool b_has = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0;
bool need = have ? (!b_has || h != g_pushed_hash)
: (b_has && g_pushed_hash != 1);
if (!need) return;
char why[64];
pushCredentials(why, sizeof(why), true);
}
// ---- pairing ----------------------------------------------------------------
static bool pair(char* why, size_t n) {
if (UARTManager::getState() == UARTManager::UART_STATE_OFF) {
snprintf(why, n, "link is off - enable 'Send to Inst. Cluster' in Settings first");
return false;
}
link_pair_t pk = {};
pk.magic = LINK_PAIR_MAGIC;
esp_fill_random(pk.key, LINK_KEY_LEN);
esp_wifi_get_mac(WIFI_IF_STA, pk.a_mac);
uint8_t frame[PACKET_MAX_SIZE];
size_t flen = frame_build(PACKET_TYPE_PAIR, &pk, sizeof(pk), frame);
int sent = 0;
for (int i = 0; i < PAIR_REPEATS; i++) {
if (UARTManager::sendWire(frame, flen)) sent++;
delay(40);
}
if (!sent) { snprintf(why, n, "UART write failed"); memset(&pk, 0, sizeof(pk)); return false; }
memcpy(g_key, pk.key, LINK_KEY_LEN);
memset(&pk, 0, sizeof(pk));
g_paired = true;
g_key_fp = link_key_fingerprint(g_key);
storeKey();
g_pushed_hash = 0; // re-send the credentials under the new key
g_last_push_ms = 0;
print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. "
"Inst. Cluster confirms in its next STATUS (`link status`).", sent, g_key_fp);
return true;
}
// ---- public: requests (UI) --------------------------------------------------
static bool bReady(char* why, size_t n, bool need_parked) {
peer_status_t p = getStatus();
if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard - is it powered?"); return false; }
if (!p.paired || !p.key_match) {
snprintf(why, n, "Inst. Cluster is not paired with this controller (console: link pair, wire connected)");
return false;
}
if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) {
snprintf(why, n, "Inst. Cluster has no Wi-Fi credentials yet - join a network on this screen first");
return false;
}
if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) {
snprintf(why, n, "Inst. Cluster is busy (%s)", phaseName(p.st.ota_phase));
return false;
}
if (need_parked && !Ota::isParked(why, n)) return false;
// Same network as B => same radio channel, so B's STATUS frames (progress)
// keep reaching this screen while B is joined.
if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) {
snprintf(why, n, "join Wi-Fi on this controller first, so Inst. Cluster's progress can be followed");
return false;
}
return true;
}
bool requestCheck(char* why, size_t n) {
if (!bReady(why, n, false)) { print("[link] check refused: %s", why); return false; }
return sendOtaCmd(LINK_OTA_CMD_CHECK, 0, why, n);
}
bool requestInstall(char* why, size_t n) {
if (!bReady(why, n, true)) { print("[link] install refused: %s", why); return false; }
return sendOtaCmd(LINK_OTA_CMD_INSTALL, 0, why, n);
}
// ---- lifecycle --------------------------------------------------------------
void init() {
if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex();
loadKey();
EspNowLink::setReceiveHandler(onFrame);
print("[link] Inst. Cluster: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected");
}
void tick() {
static uint32_t last = 0;
static bool was_heard = false;
static uint8_t last_phase = 0xFF;
static bool was_match = false;
if (millis() - last < 1000) return;
last = millis();
peer_status_t p = getStatus();
if (p.heard != was_heard) {
was_heard = p.heard;
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"),
(unsigned long)p.st.uptime_s);
else print("[link] Inst. Cluster silent for %lu s", (unsigned long)(p.age_ms / 1000));
}
if (p.heard && p.key_match && !was_match) {
print("[link] Inst. Cluster confirmed pairing (fingerprint %04X)", p.st.key_fp);
}
was_match = p.heard && p.key_match;
if (p.heard && p.st.ota_phase != last_phase) {
if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE)
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.ota_phase == LINK_OTA_FAILED ? " - " : "",
p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : "");
last_phase = p.st.ota_phase;
}
syncCredentials();
}
// ---- console ----------------------------------------------------------------
static void help() {
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 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 ota check|install [force]|rollback drive B's updater");
}
bool handleCommand(const char* line) {
if (strncmp(line, "link", 4) != 0 || (line[4] != 0 && line[4] != ' ')) return false;
const char* a = line + 4;
while (*a == ' ') a++;
char why[96] = "";
if (!*a || !strcmp(a, "help")) { help(); return true; }
if (!strcmp(a, "status")) {
peer_status_t p = getStatus();
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,
(unsigned long)g_secure_sent, (unsigned long)g_secure_fail);
if (!g_ever_heard) { print("[link] Inst. Cluster never heard"); return true; }
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.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000));
print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s",
p.st.version, p.st.key_fp, p.key_match ? "matches" : p.st.key_fp ? "DIFFERENT" : "none",
(p.st.flags & LINK_STATUS_HAVE_WIFI) ? "yes" : "no",
(p.st.flags & LINK_STATUS_WIFI_JOINED) ? ", joined" : "",
(p.st.flags & LINK_STATUS_PENDING_VERIFY) ? " | fresh image, unconfirmed" : "");
print("[link] update: %s%s%s%s%s | up %lu s | heap %lu",
phaseName(p.st.ota_phase),
p.st.latest[0] ? ", latest " : "", p.st.latest,
p.st.message[0] ? " - " : "", p.st.message,
(unsigned long)p.st.uptime_s, (unsigned long)p.st.free_heap);
return true;
}
if (!strcmp(a, "pair")) { if (!pair(why, sizeof(why))) print("[link] pair refused: %s", why); return true; }
if (!strcmp(a, "unpair")) { clearKey(); print("[link] pairing key removed here"); return true; }
if (!strcmp(a, "creds")) {
if (!pushCredentials(why, sizeof(why), true)) print("[link] creds refused: %s", why);
return true;
}
if (!strncmp(a, "ota", 3)) {
const char* b = a + 3;
while (*b == ' ') b++;
bool ok = false;
if (!strcmp(b, "check")) ok = requestCheck(why, sizeof(why));
else if (!strcmp(b, "install")) ok = requestInstall(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 { help(); return true; }
print(ok ? "[link] command sent to Inst. Cluster - watch `link status`" : "[link] refused: %s", why);
return true;
}
help();
return true;
}
} // namespace LinkPeer
+49
View File
@@ -0,0 +1,49 @@
/*
* Link Peer Module (Main CTRL) - what A knows about Inst. Cluster, and the
* maintenance traffic that keeps B updatable. See
* 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.
* Shown on Settings -> Updates as the "Inst. Cluster" card.
* 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
* this is the only secret and it never travels by radio.
* SECURE A -> B ESP-NOW unicast, AES-256-GCM under the pairing key:
* the remembered Wi-Fi credentials (pushed automatically
* whenever B lacks them or they change) and OTA commands.
*
* Console: link status | pair | unpair | creds | ota check | ota install [force] | ota rollback
*/
#pragma once
#include <Arduino.h>
#include "protocol/automotive_data.h"
namespace LinkPeer {
/** Load the pairing key, hook the ESP-NOW receive path. After EspNowLink::init(). */
void init();
/** Credential sync + logging. Call from loop(). */
void tick();
typedef struct {
bool heard; // STATUS within LINK_STATUS_TIMEOUT_MS
uint32_t age_ms; // since the last STATUS
uint8_t mac[6]; // B's STA MAC
link_status_t st; // last STATUS as received
bool paired; // this controller holds a pairing key
bool key_match; // B reports the fingerprint of OUR key
uint16_t key_fp; // our key's fingerprint (0 = none)
} peer_status_t;
peer_status_t getStatus();
/** Ask B to check / install (behind the same parking gate as A's own update). */
bool requestCheck(char* why, size_t n);
bool requestInstall(char* why, size_t n);
bool handleCommand(const char* line);
} // namespace LinkPeer
+2 -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.
*/ */
@@ -685,6 +685,7 @@ ui_status_t getStatus() {
bool requestCheck(char* why, size_t n) { return startJob(JOB_CHECK, why, n); } bool requestCheck(char* why, size_t n) { return startJob(JOB_CHECK, why, n); }
bool requestInstall(char* why, size_t n) { return startJob(JOB_INSTALL, why, n); } bool requestInstall(char* why, size_t n) { return startJob(JOB_INSTALL, why, n); }
bool isParked(char* why, size_t n) { return parked(why, n); }
void init() { void init() {
const esp_partition_t* run = esp_ota_get_running_partition(); const esp_partition_t* run = esp_ota_get_running_partition();
+4 -1
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,6 +66,9 @@ 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 (Inst. Cluster's install is guarded by it too). */
bool isParked(char* why, size_t n);
} // namespace Ota } // namespace Ota
#endif // OTA_UPDATE_H #endif // OTA_UPDATE_H
+15
View File
@@ -19,6 +19,7 @@ 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";
// ============================================================================ // ============================================================================
// PUBLIC API IMPLEMENTATION // PUBLIC API IMPLEMENTATION
@@ -89,4 +90,18 @@ 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;
}
} // namespace SettingsManager } // namespace SettingsManager
+4
View File
@@ -66,4 +66,8 @@ void saveCANState(bool enabled);
*/ */
bool loadCANState(); bool loadCANState();
/** Diff-lock inputs DI0/DI1 read (DiffLocks). Default OFF. */
void saveDiffLockState(bool enabled);
bool loadDiffLockState();
} // namespace SettingsManager } // namespace SettingsManager
+178 -44
View File
@@ -7,6 +7,8 @@
#include "driveline_screen.h" #include "driveline_screen.h"
#include "wifi_manager.h" #include "wifi_manager.h"
#include "ota_update.h" #include "ota_update.h"
#include "link_peer.h"
#include "diff_locks.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"
@@ -81,6 +83,8 @@ 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_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
static void refresh(bool force); static void refresh(bool force);
@@ -207,7 +211,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);
} }
@@ -402,7 +406,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));
@@ -510,9 +514,17 @@ static void buildPasswordOverlay() {
} }
// ============================================================================ // ============================================================================
// UPDATES PAGE // 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_latest = NULL;
static lv_obj_t* g_b_state = NULL;
static lv_obj_t* g_b_check = NULL;
static lv_obj_t* g_b_install = NULL;
static char g_b_refusal[96] = "";
static uint8_t g_b_refusal_phase = LINK_OTA_IDLE;
static void onInstallConfirmed(bool ok, void* user) { static void onInstallConfirmed(bool ok, void* user) {
(void)user; (void)user;
if (!ok) return; if (!ok) return;
@@ -528,9 +540,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);
} }
@@ -547,7 +558,36 @@ static void onGoWifi(lv_event_t* e) {
selectPage(PAGE_WIFI); selectPage(PAGE_WIFI);
} }
static void refreshUpdates() { static void onBInstallConfirmed(bool ok, void* user) {
(void)user;
if (!ok) return;
uint8_t before = LinkPeer::getStatus().st.ota_phase;
if (!LinkPeer::requestInstall(g_b_refusal, sizeof(g_b_refusal))) g_b_refusal_phase = before;
else g_b_refusal[0] = 0;
refresh(true);
}
static void onBInstall(lv_event_t* e) {
(void)e;
LinkPeer::peer_status_t p = LinkPeer::getStatus();
char title[64];
snprintf(title, sizeof(title), "Install %s on Inst. Cluster?", p.st.latest);
confirm(title,
"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"
"Only while parked with the engine off.",
"Install", onBInstallConfirmed, NULL);
}
static void onBCheck(lv_event_t* e) {
(void)e;
uint8_t before = LinkPeer::getStatus().st.ota_phase;
if (!LinkPeer::requestCheck(g_b_refusal, sizeof(g_b_refusal))) g_b_refusal_phase = before;
else g_b_refusal[0] = 0;
refresh(true);
}
static void refreshUpdatesA() {
Ota::ui_status_t o = Ota::getStatus(); Ota::ui_status_t o = Ota::getStatus();
bool wifi_ok = WiFiManager::getStatus().link == WiFiManager::LINK_CONNECTED; bool wifi_ok = WiFiManager::getStatus().link == WiFiManager::LINK_CONNECTED;
if (g_upd_refusal[0] && o.phase != g_upd_refusal_phase) g_upd_refusal[0] = 0; // superseded if (g_upd_refusal[0] && o.phase != g_upd_refusal_phase) g_upd_refusal[0] = 0; // superseded
@@ -570,7 +610,7 @@ static void refreshUpdates() {
} else if (!wifi_ok && o.phase != Ota::PHASE_IDLE && o.phase != Ota::PHASE_CHECKING) { } else if (!wifi_ok && o.phase != Ota::PHASE_IDLE && o.phase != Ota::PHASE_CHECKING) {
// keep the last result, but say why the buttons are off // keep the last result, but say why the buttons are off
size_t n = strlen(msg); size_t n = strlen(msg);
snprintf(msg + n, sizeof(msg) - n, "\nConnect to Wi-Fi to check again."); snprintf(msg + n, sizeof(msg) - n, " Connect to Wi-Fi to check again.");
} }
setText(g_upd_state, msg); setText(g_upd_state, msg);
setTextColor(g_upd_state, col); setTextColor(g_upd_state, col);
@@ -590,45 +630,124 @@ static void refreshUpdates() {
setVisible(g_upd_wifi, !wifi_ok); setVisible(g_upd_wifi, !wifi_ok);
} }
static void refreshUpdatesB() {
LinkPeer::peer_status_t p = LinkPeer::getStatus();
if (g_b_refusal[0] && p.st.ota_phase != g_b_refusal_phase) g_b_refusal[0] = 0;
bool has_wifi = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0;
bool ready = p.heard && p.paired && p.key_match && has_wifi;
char msg[160];
lv_color_t col = UI_COL_MUTED;
if (!p.heard) {
snprintf(msg, sizeof(msg), "Inst. Cluster not heard.%s",
p.paired ? "" : " Not paired yet: connect the wire and run 'link pair' on the console.");
} else if (!p.paired || !p.key_match) {
snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " Not paired with this controller. "
"Connect the wire and run 'link pair' on the console.");
col = UI_COL_AMBER;
} else if (!has_wifi) {
snprintf(msg, sizeof(msg), "Inst. Cluster has no Wi-Fi credentials yet. Join a network here; "
"they are passed on by themselves.");
} else {
switch (p.st.ota_phase) {
case LINK_OTA_CHECKING: snprintf(msg, sizeof(msg), "Inst. Cluster is checking..."); break;
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;
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 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;
default: snprintf(msg, sizeof(msg), "Tap Check to look for a new version"); break;
}
if (p.st.flags & LINK_STATUS_PENDING_VERIFY) {
size_t n = strlen(msg);
snprintf(msg + n, sizeof(msg) - n, " (new firmware, confirming...)");
}
}
if (g_b_refusal[0]) {
snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", g_b_refusal);
col = UI_COL_WARN;
}
setText(g_b_state, msg);
setTextColor(g_b_state, col);
setText(g_b_installed, p.heard ? p.st.version : "-");
setText(g_b_latest, (p.heard && p.st.latest[0]) ? p.st.latest : "-");
bool busy = p.heard && (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING);
setButtonText(g_b_check, busy ? "Working..." : LV_SYMBOL_REFRESH " Check for updates");
if (busy || !ready) lv_obj_add_state(g_b_check, LV_STATE_DISABLED);
else lv_obj_clear_state(g_b_check, LV_STATE_DISABLED);
bool can_install = ready && p.st.ota_phase == LINK_OTA_AVAILABLE;
char inst[48];
snprintf(inst, sizeof(inst), LV_SYMBOL_DOWNLOAD " Install %s", p.st.latest);
setButtonText(g_b_install, inst);
setVisible(g_b_install, can_install);
}
static void refreshUpdates() {
refreshUpdatesA();
refreshUpdatesB();
}
/** One controller's card: "Name Installed vX Latest vY", a status line, a button row. */
static lv_obj_t* controllerCard(lv_obj_t* page, const char* name, const char* installed,
lv_obj_t** installed_lbl, lv_obj_t** latest_lbl, lv_obj_t** state_lbl) {
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, 8, 0);
lv_obj_t* row = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(row, 36, 0);
lv_obj_t* title = label(row, name, &lv_font_montserrat_24, UI_COL_TEXT);
lv_obj_set_width(title, 190);
lv_obj_t* a = box(row, LV_FLEX_FLOW_ROW);
lv_obj_set_size(a, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_align(a, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(a, 10, 0);
label(a, "Installed", &lv_font_montserrat_20, UI_COL_MUTED);
*installed_lbl = label(a, installed, &lv_font_montserrat_24, UI_COL_TEXT);
lv_obj_t* b = box(row, LV_FLEX_FLOW_ROW);
lv_obj_set_size(b, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_align(b, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(b, 10, 0);
label(b, "Latest", &lv_font_montserrat_20, UI_COL_MUTED);
*latest_lbl = label(b, "-", &lv_font_montserrat_24, UI_COL_TEXT);
*state_lbl = label(c, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(*state_lbl, LV_LABEL_LONG_WRAP);
lv_obj_set_width(*state_lbl, LV_PCT(100));
return c;
}
static void buildUpdatesPage(lv_obj_t* page) { 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* c = card(page); lv_obj_t* installed_a = NULL;
lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_t* a = controllerCard(page, "Main CTRL", FW_VERSION, &installed_a, &g_upd_latest, &g_upd_state);
lv_obj_set_flex_flow(c, LV_FLEX_FLOW_ROW); lv_obj_t* btns = box(a, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(c, 60, 0);
lv_obj_t* a = box(c, LV_FLEX_FLOW_COLUMN);
lv_obj_set_size(a, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_style_pad_row(a, 6, 0);
label(a, "Installed", &lv_font_montserrat_20, UI_COL_MUTED);
label(a, FW_VERSION, &lv_font_montserrat_30, UI_COL_TEXT);
lv_obj_t* b = box(c, LV_FLEX_FLOW_COLUMN);
lv_obj_set_size(b, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_style_pad_row(b, 6, 0);
label(b, "Latest release", &lv_font_montserrat_20, UI_COL_MUTED);
g_upd_latest = label(b, "-", &lv_font_montserrat_30, UI_COL_TEXT);
g_upd_state = label(page, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(g_upd_state, LV_LABEL_LONG_WRAP);
lv_obj_set_width(g_upd_state, LV_PCT(100));
lv_obj_t* btns = box(page, 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);
g_upd_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 64, BTN_PRIMARY, onCheck, NULL); g_upd_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 56, BTN_PRIMARY, onCheck, NULL);
g_upd_install = button(btns, "Install", 280, 64, 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, 64, 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, "Inst. Cluster", "-", &g_b_installed, &g_b_latest, &g_b_state);
btns = box(b, LV_FLEX_FLOW_ROW);
lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_column(btns, 16, 0);
g_b_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 56, BTN_PRIMARY, onBCheck, 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,
"Updates come from " OTA_SERVER " and are signed. Installing takes about a minute: " "Each controller restarts after updating. DO NOT TURN OFF THE IGNITION DURING THE UPDATE",
"a progress bar shows while the new firmware is written, then the controller restarts. "
"If it doesn't start properly, it goes back to the current version by itself.",
&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));
lv_obj_set_style_pad_top(note, 12, 0);
} }
// ============================================================================ // ============================================================================
@@ -652,10 +771,22 @@ 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 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());
// live state in the sub-line, so the wiring can be tested from this page
if (!DiffLocks::isEnabled()) setText(g_sys_diff_sub, "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;
@@ -666,18 +797,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);
} }
@@ -690,17 +820,21 @@ 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);
g_sys_diff = toggle(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);
+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
+147
View File
@@ -0,0 +1,147 @@
/*
* Status Overlay implementation. See status_overlay.h.
*/
#include "status_overlay.h"
#include "wifi_manager.h"
#include "uart_manager.h"
#include "ui_kit.h"
#include "drivers/can_driver.h"
#include "display/lvgl_v8_port.h"
#include "protocol/automotive_data.h"
#include <lvgl.h>
namespace StatusOverlay {
#define BLINK_MS 500
static lv_obj_t* g_wifi = NULL;
static lv_obj_t* g_banner = NULL;
static bool g_banner_shown = false;
static const lv_color_t COL_RED_HI = lv_color_hex(0xFF3B30);
static const lv_color_t COL_RED_LO = lv_color_hex(0x8F1A14);
static void setText(lv_obj_t* lbl, const char* text) {
const char* cur = lv_label_get_text(lbl);
if (cur != NULL && strcmp(cur, text) == 0) return;
lv_label_set_text(lbl, text);
}
static void setTextColour(lv_obj_t* o, lv_color_t c) {
if (lv_color_to32(lv_obj_get_style_text_color(o, 0)) != lv_color_to32(c)) lv_obj_set_style_text_color(o, c, 0);
}
static void setBgColour(lv_obj_t* o, lv_color_t c) {
if (lv_color_to32(lv_obj_get_style_bg_color(o, 0)) != lv_color_to32(c)) lv_obj_set_style_bg_color(o, c, 0);
}
void init() {
lvgl_port_lock(-1);
// Wi-Fi chip, fixed width so the header layout never moves
g_wifi = lv_label_create(lv_layer_top());
lv_obj_set_width(g_wifi, 150);
lv_label_set_long_mode(g_wifi, LV_LABEL_LONG_DOT);
lv_label_set_text(g_wifi, LV_SYMBOL_WIFI " --");
lv_obj_set_style_text_font(g_wifi, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_wifi, UI_COL_MUTED, 0);
lv_obj_set_style_bg_color(g_wifi, UI_COL_PANEL, 0);
lv_obj_set_style_bg_opa(g_wifi, LV_OPA_COVER, 0);
lv_obj_set_style_radius(g_wifi, 13, 0);
lv_obj_set_style_pad_hor(g_wifi, 10, 0);
lv_obj_set_style_pad_ver(g_wifi, 5, 0);
lv_obj_align(g_wifi, LV_ALIGN_TOP_RIGHT, -16, 25);
// Alert banner, top centre
g_banner = lv_label_create(lv_layer_top());
lv_label_set_text(g_banner, "");
lv_obj_set_style_text_font(g_banner, &lv_font_montserrat_20, 0);
lv_obj_set_style_text_color(g_banner, lv_color_white(), 0);
lv_obj_set_style_bg_color(g_banner, COL_RED_HI, 0);
lv_obj_set_style_bg_opa(g_banner, LV_OPA_COVER, 0);
lv_obj_set_style_radius(g_banner, 10, 0);
lv_obj_set_style_pad_hor(g_banner, 18, 0);
lv_obj_set_style_pad_ver(g_banner, 8, 0);
lv_obj_align(g_banner, LV_ALIGN_TOP_MID, -20, 10);
lv_obj_add_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
lvgl_port_unlock();
}
static void refreshWifi() {
WiFiManager::status_t w = WiFiManager::getStatus();
char txt[64];
lv_color_t col = UI_COL_MUTED;
switch (w.link) {
case WiFiManager::LINK_CONNECTED: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " %s", w.ssid); col = UI_COL_TEXT; break;
case WiFiManager::LINK_CONNECTING: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " joining..."); col = UI_COL_ACCENT; break;
case WiFiManager::LINK_FAILED: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " failed"); col = UI_COL_AMBER; break;
case WiFiManager::LINK_OFF: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " off"); break;
default: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " not connected"); break;
}
setText(g_wifi, txt);
setTextColour(g_wifi, col);
}
static void refreshAlerts() {
bool can_up = CANDriver::isActive();
driveline_t dl = CANDriver::getDriveline();
uint16_t alerts = 0;
uint8_t flags = 0;
int16_t coolant = 0, gearbox = 0;
uint16_t batt = 0;
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
alerts = UARTManager::g_automotive_data.alerts;
flags = UARTManager::g_automotive_data.valid_flags;
coolant = UARTManager::g_automotive_data.coolant_temp;
gearbox = UARTManager::g_automotive_data.gearbox_oil_temp;
batt = UARTManager::g_automotive_data.battery_voltage;
xSemaphoreGive(UARTManager::g_data_mutex);
} else {
return;
}
bool live = can_up && dl.ignition_on && (flags & VALID_FLAG_ALERTS);
bool red = live && (alerts & ALERTS_RED);
bool amber = live && !red && (alerts & ALERTS_AMBER);
bool show = red || amber;
if (show != g_banner_shown) {
g_banner_shown = show;
if (show) lv_obj_clear_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
}
if (!show) return;
char txt[64];
if (alerts & ALERT_COOLANT_HOT) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " COOLANT %d °C HOT", coolant / 10);
else if (alerts & ALERT_GEARBOX_HOT) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEARBOX OIL %d °C HOT", gearbox / 10);
else if (alerts & ALERT_GEAR_MISMATCH) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEAR MISMATCH");
else if (alerts & ALERT_BATTERY_LOW) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " BATTERY %d.%02d V LOW", batt / 100, batt % 100);
else snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEARBOX COOLING");
setText(g_banner, txt);
if (red) {
bool hi = (millis() / BLINK_MS) & 1;
setBgColour(g_banner, hi ? COL_RED_HI : COL_RED_LO);
setTextColour(g_banner, lv_color_white());
} else {
setBgColour(g_banner, UI_COL_AMBER);
setTextColour(g_banner, lv_color_hex(0x1A1200));
}
}
void tick() {
if (g_wifi == NULL) return;
static uint32_t last = 0;
if (millis() - last < 250) return;
last = millis();
lvgl_port_lock(-1);
refreshWifi();
refreshAlerts();
lvgl_port_unlock();
}
} // namespace StatusOverlay
+26
View File
@@ -0,0 +1,26 @@
/*
* Status Overlay - what every screen shows, on lv_layer_top():
*
* top-right Wi-Fi chip: off / not connected / joining / <network>
* top-centre ALERT BANNER: red and blinking (2 Hz) while any red alert from
* Tunables' thresholds is on (coolant hot, gearbox oil hot,
* gear mismatch, battery low), steady amber while the gearbox
* asks for cooling. Hidden with CAN off or ignition off.
*
* Both are labels, so they never take touches from the screen below. tick()
* runs from loop() and only touches an object when its text/colour changes.
*/
#pragma once
#include <Arduino.h>
namespace StatusOverlay {
/** Build the two labels. Call after DisplayInit::init(), before the screens tick. */
void init();
/** Refresh from WiFiManager / the shared automotive data. Call from loop(). */
void tick();
} // namespace StatusOverlay
+1
View File
@@ -102,6 +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 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
+18 -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"
@@ -43,36 +43,24 @@ static uart_stats_t g_uart_stats = {0};
// CONFIG frame scheduling // CONFIG frame scheduling
static uint8_t g_last_cfg_version_sent = 0; static uint8_t g_last_cfg_version_sent = 0;
static uint32_t g_last_cfg_send_time = 0; static uint32_t g_last_cfg_send_time = 0;
static volatile bool g_port_ready = false; // Serial1.begin() done (in the task)
// ============================================================================ // ============================================================================
// PRIVATE HELPER FUNCTIONS // PRIVATE HELPER FUNCTIONS
// ============================================================================ // ============================================================================
/** /**
* @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);
} }
} }
@@ -173,6 +161,7 @@ static void uartTask(void* parameter) {
Serial1.setRxBufferSize(256); Serial1.setRxBufferSize(256);
Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN); Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
g_port_ready = true;
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u", ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u",
UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION); UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION);
@@ -302,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");
} }
} }
@@ -355,4 +344,10 @@ void setEnabled(bool state)
ESP_LOGI("UARTMgr", "============================="); ESP_LOGI("UARTMgr", "=============================");
} }
bool sendWire(const uint8_t* frame, size_t len) {
if (!g_port_ready || len == 0) return false;
return Serial1.write(frame, len) == len;
}
} // namespace UARTManager } // namespace UARTManager
+9 -1
View File
@@ -117,9 +117,17 @@ 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);
/**
* @brief Send one complete frame on the UART wire ONLY (never ESP-NOW).
* Used for the PAIR frame, which must not go over the air. One write
* call, so it cannot interleave with the task's own frames.
* @return true if the port is up and every byte was written
*/
bool sendWire(const uint8_t* frame, size_t len);
} // namespace UARTManager } // namespace UARTManager
+2 -1
View File
@@ -18,8 +18,9 @@ void header(lv_obj_t* scr, const char* title, lv_event_cb_t back_cb) {
lv_obj_t* t = label(scr, title, &lv_font_montserrat_30, UI_COL_TEXT); lv_obj_t* t = label(scr, title, &lv_font_montserrat_30, UI_COL_TEXT);
lv_obj_align(t, LV_ALIGN_TOP_LEFT, 24, 18); lv_obj_align(t, LV_ALIGN_TOP_LEFT, 24, 18);
// -176: the StatusOverlay Wi-Fi chip owns the last 150 px of the top-right corner
lv_obj_t* back = button(scr, LV_SYMBOL_LEFT " Driveline", 200, 56, BTN_SECONDARY, back_cb, NULL); lv_obj_t* back = button(scr, LV_SYMBOL_LEFT " Driveline", 200, 56, BTN_SECONDARY, back_cb, NULL);
lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -16, 10); lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -176, 10);
} }
lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color) { lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color) {
+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
+8
View File
@@ -95,6 +95,14 @@ static void loadSaved() {
copyStr(g_saved_pass, pass.c_str(), sizeof(g_saved_pass)); copyStr(g_saved_pass, pass.c_str(), sizeof(g_saved_pass));
} }
bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n) {
lock();
copyStr(ssid, g_status.saved_ssid, ssid_n);
unlock();
copyStr(pass, g_saved_pass, pass_n);
return ssid[0] != 0;
}
static void storeSaved(const char* ssid, const char* pass) { static void storeSaved(const char* ssid, const char* pass) {
Preferences p; Preferences p;
p.begin(NVS_NAMESPACE, false); p.begin(NVS_NAMESPACE, false);
+8 -1
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);
@@ -82,4 +82,11 @@ uint8_t getNetworks(network_t* out, uint8_t max);
/** Console: `wifi status | join <ssid> [pass] | forget | on | off`. */ /** Console: `wifi status | join <ssid> [pass] | forget | on | off`. */
bool handleCommand(const char* line); bool handleCommand(const char* line);
/**
* The remembered network, password included - for LinkPeer, which hands it to
* Inst. Cluster inside an encrypted frame. Never print the password.
* @return false if no network is saved
*/
bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n);
} // namespace WiFiManager } // namespace WiFiManager
+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`,
@@ -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
+4 -3
View File
@@ -12,15 +12,16 @@ 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**
- [[diff-lock-inputs]] — **2026-09-29**: Patrol diff locks (+12 V = locked) on DI0 rear / DI1 front, `DI_COM` to ground; PC814 → CH422G EXIO0/EXIO5 (active low); the bank flip per read is unverified for panel flicker, so it is behind a Settings switch, default OFF
## Concepts ## 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 (still wanted for the `22 D1xx` live-data identifiers), 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; plan for updating Controller B through A over ESP-NOW - [[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
+49 -8
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
@@ -181,3 +181,44 @@ Branch `display-xip`: pioarduino `custom_sdkconfig` with `CONFIG_SPIRAM_XIP_FROM
## [2026-09-27] build | Step 4: OTA keeps the screen on with a progress bar (branch display-xip) ## [2026-09-27] build | Step 4: OTA keeps the screen on with a progress bar (branch display-xip)
`ota_update.cpp`: the full-screen notice gained an LVGL bar + percent label + amber "Do not switch off the ignition"; the download loop updates it per percent under a 50 ms LVGL try-lock; the backlight off/on around `writeImage()` is gone. Settings texts updated (confirm dialog, Updates note). Second forced install under `perf` → [[perf-xip-ota-2026-09-27]]: 24–25 panel frames/s and a 41.5 ms gap for the whole download, bar redrawing 2–3×/s. User confirmed on the screen: progress bar visible, no flicker. [[ota-updates]] rewritten for the lit screen; [[open-questions]] #13 step 4 done. Left: dots verdict by eye on the XIP build, CI core rebuild, merge + v0.1.7. `ota_update.cpp`: the full-screen notice gained an LVGL bar + percent label + amber "Do not switch off the ignition"; the download loop updates it per percent under a 50 ms LVGL try-lock; the backlight off/on around `writeImage()` is gone. Settings texts updated (confirm dialog, Updates note). Second forced install under `perf` → [[perf-xip-ota-2026-09-27]]: 24–25 panel frames/s and a 41.5 ms gap for the whole download, bar redrawing 2–3×/s. User confirmed on the screen: progress bar visible, no flicker. [[ota-updates]] rewritten for the lit screen; [[open-questions]] #13 step 4 done. Left: dots verdict by eye on the XIP build, CI core rebuild, merge + v0.1.7.
## [2026-09-27] release | v0.1.7: XIP from PSRAM, IRAM-safe panel refill, OTA progress bar, perf monitor, Driveline idle fix
User exercised the `display-xip` build (Wi-Fi scan, update check, install) and reported no flicker or other issues; decision: merge to main and tag **v0.1.7**. Contents since v0.1.6: core rebuilt with `CONFIG_SPIRAM_XIP_FROM_PSRAM` + `CONFIG_LCD_RGB_ISR_IRAM_SAFE` (pioarduino `custom_sdkconfig`, unused IDF components removed); OTA screen stays lit with a progress bar and "Do not switch off the ignition"; `perf` console + `tools/perf_session.py` (fps, PSRAM copy load, idle, panel vsync/gap); Driveline tick writes labels only on change; dead `ESP_PANEL_LCD_RGB_*` flags removed. Verified on the bench: 24–25 panel frames/s and a 41.5 ms gap throughout an OTA download (was 4–8/s). Open: dots in longer use (eyes only), CI core rebuild on the tag build. Pages: [[perf-baseline-2026-09-27]], [[perf-dots-and-ota-2026-09-27]], [[perf-xip-ota-2026-09-27]], [[ota-updates]], [[open-questions]] #13.
## [2026-09-27] build | v0.1.7 CI failure fixed: pioarduino core fork in the workflow, tag moved
Tag build died at the link step: `ModuleNotFoundError: No module named 'SCons.Tool.FortranCommon'`. Cause: CI installed upstream `platformio` via uv while the pioarduino platform pins its own SCons 4.8.1 (no Fortran tools) and, since `custom_sdkconfig`, the build runs through pioarduino's ESP-IDF path where the upstream core imports FortranCommon; locally the penv runs pioarduino's core fork (platform `penv_setup.py` pin v6.1.18), which never hit it — and v0.1.1–v0.1.6 never used that path. Workflow now installs the fork zip; documented in root CLAUDE.md and [[ota-updates]]. No release object existed for v0.1.7, so the tag was deleted on the remote and re-created on the fix commit, pushed with `--follow-tags`.
## [2026-09-27] verify | v0.1.7 published by CI after the core-fork fix
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 | 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 (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 | 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 "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
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.
+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
+46
View File
@@ -0,0 +1,46 @@
---
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. Their switches put **+12 V on a wire while a diff is locked** (source: user, 2026-09-29). 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 (+12 V = locked) |
| `DI1` | front diff-lock wire (+12 V = locked) |
| `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]]
+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
+3 -3
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,7 +39,7 @@ 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), open-drain out sinking 450 mA/ch — could read ignition-on or drive a relay later |
| 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 |
+4 -4
View File
@@ -6,7 +6,7 @@ updated: 2026-09-23
# 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 |
|---|---|---| |---|---|---|
@@ -128,7 +128,7 @@ Run via `tools/diag_session.py` (one serial session, logs straight into `wiki/ra
- **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.
+2 -2
View File
@@ -24,7 +24,7 @@ The research frontier. Answering any of these should trigger updates across the
## 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. 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
@@ -75,7 +75,7 @@ The research frontier. Answering any of these should trigger updates across the
**Decision 2026-09-27 (user): this is a must-fix, all steps through XIP, bench time is no constraint.** Two corrections to the record: (a) the flickering dots **still appear occasionally** on v0.1.6 — the scan policy reduced the trigger, it did not remove the weakness; (b) the dark screen during OTA is a **safety/UX defect**, not a mitigation: with no feedback a driver may switch the ignition off mid-update. Requirement: the screen stays on during an update with a visible progress bar and a "do not switch off" message — which needs Step B (flash writes must stop blanking the panel), plus an OTA progress callback on the Updates page. (The OTA design already survives a power cut — the new image is only confirmed after 30 s, else it rolls back — so the risk is a wasted update and a confused user, not a bricked board.) **Decision 2026-09-27 (user): this is a must-fix, all steps through XIP, bench time is no constraint.** Two corrections to the record: (a) the flickering dots **still appear occasionally** on v0.1.6 — the scan policy reduced the trigger, it did not remove the weakness; (b) the dark screen during OTA is a **safety/UX defect**, not a mitigation: with no feedback a driver may switch the ignition off mid-update. Requirement: the screen stays on during an update with a visible progress bar and a "do not switch off" message — which needs Step B (flash writes must stop blanking the panel), plus an OTA progress callback on the Updates page. (The OTA design already survives a power cut — the new image is only confirmed after 30 s, else it rolls back — so the risk is a wasted update and a confused user, not a bricked board.)
**Plan agreed 2026-09-27 (next display session, bench + USB, `dev` builds only until verified):** **Plan agreed 2026-09-27 (next display session, bench + USB, `dev` builds only until verified):**
1. **Baseline first**: Settings → System → Performance overlay (LVGL's perf monitor = real render FPS + CPU; never measured before). Provoke each symptom on purpose: a Wi-Fi scan (dots), a Tuning edit that gets saved (flash write), an update (flash writes). Without numbers there is no telling whether a change helped. **Tooling landed 2026-09-27 `(repo)`**: the `perf` console command (`perf on 1` streams a `PERF,` CSV line per second: fps, ms/frame, flush ms/s, LVGL idle, core idle, heap). **Idle baseline, Driveline screen, bench/USB, v0.1.6+perf**: 9.7 fps rendered (= the screen's own update rate), 30 ms per frame avg (122 ms worst in the first window), ~40 kpx/frame, 52 ms/s copying into the PSRAM framebuffer, LVGL idle 68 %, core 0 idle 94 %, core 1 idle 66 %, internal 66.9 KB free / 31.7 KB largest, PSRAM 6.6 MB free. **Provoke session logged 2026-09-27 → [[perf-baseline-2026-09-27]]**: Driveline redraws ~10×/s with nothing changing (39 kpx, 30 ms, a third of core 1 — an unconditional `lv_label_set_text` every 100 ms `(repo)`); screen changes are single 140–330 ms frames (= the swipe lag; not a bounce-buffer matter); the Simulation tab is the heaviest normal load (2 Mpx/s, 26 % of the time writing PSRAM, LVGL idle 9 %); a flash write is invisible to the LVGL counters, so the monitor needs a **panel vsync/refresh counter** to see flicker and dots directly; the monitor is blind during OTA (ticks from the blocked `loop()`). Heap flat throughout (66–67 KB internal, 31.7 KB largest, 6.6 MB PSRAM). **Plan amended**: 1b = stop the Driveline redraw + add vsync counter + timer-driven PERF, re-baseline; step 2 judged on the Simulation tab and during a scan, by the refresh counter. **Step 1b done 2026-09-27 `(verified, bench)`**: Driveline `tick()` now writes labels/chips only on change → idle Driveline 0 fps, 0 ms/s PSRAM copies, LVGL idle 96 %, core 1 idle 96 % (was 9.7 fps / 52 ms/s / 68 % / 66 %). `perf` gained the panel counters: **~24 vsync/s, longest gap 41.5 ms when healthy** — a DMA restart must show as a gap ≥ 2 frames (≈ 83 ms). Reporting runs from an esp_timer, so OTA is no longer a blind spot. **Second session 2026-09-27 → [[perf-dots-and-ota-2026-09-27]]**: (a) with dots on screen and everything idle the panel refreshed perfectly (24/s, 41.5 ms) — **dots are sub-frame DMA data glitches, invisible to the vsync counter, judged by eye only; bounce buffers are the designed fix**; (b) during `ota install` the panel drops to **4–8 refreshes/s with 290–747 ms gaps** — flash writes blank it ~75 % of the time; **no progress bar is possible before step 3**; target 24/s + 41.5 ms during an install. Tuning save and `ota check` lost no frame. **Correction the same evening**: the panel library already runs **10-line bounce buffers** and a **21 MHz** clock (the `platformio.ini` flags saying otherwise were dead names) — so the dots are *late bounce refills* re-sending the previous 10-line chunk (the photo shows text pixels echoed below each line), and step 2 as written is moot. **Step 3 (`CONFIG_SPIRAM_XIP_FROM_PSRAM` + `CONFIG_LCD_RGB_ISR_IRAM_SAFE`, pioarduino `custom_sdkconfig`, branch `display-xip`) now targets both the dots and the OTA blanking.** Fallbacks if dots remain: lower pixel clock (18 MHz), larger bounce buffers, Wi-Fi/LWIP buffers back to internal RAM (`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP=n`, costs internal RAM). **Step 3 built and measured 2026-09-27 17:46 → [[perf-xip-ota-2026-09-27]]: during a full `ota install` the panel held 24–25 refreshes/s with a 41.5 ms gap (stock core: 4–8/s, 290–747 ms). The flash-write blanking is fixed `(verified)`; a progress bar during updates is now possible (step 4). PSRAM free 6.6 → 4.9 MB (code resident there); no render slow-down seen in the one full-redraw sample. Dots on the XIP build still to be judged by eye (Wi-Fi up, idle screen).** **Step 4 done 2026-09-27**: the OTA notice keeps the screen on with a progress bar and "Do not switch off the ignition"; second forced install under `perf`: 24–25 frames/s, 41.5 ms gap throughout, bar redrawing 2–3×/s; user: "the progress bar appeared and no flickering or other issues" `(verified)`. Remaining before merging `display-xip` → main and releasing v0.1.7: the user's verdict on the dots (idle screen, Wi-Fi up, several minutes) and a CI run that can rebuild the core. 1. **Baseline first**: Settings → System → Performance overlay (LVGL's perf monitor = real render FPS + CPU; never measured before). Provoke each symptom on purpose: a Wi-Fi scan (dots), a Tuning edit that gets saved (flash write), an update (flash writes). Without numbers there is no telling whether a change helped. **Tooling landed 2026-09-27 `(repo)`**: the `perf` console command (`perf on 1` streams a `PERF,` CSV line per second: fps, ms/frame, flush ms/s, LVGL idle, core idle, heap). **Idle baseline, Driveline screen, bench/USB, v0.1.6+perf**: 9.7 fps rendered (= the screen's own update rate), 30 ms per frame avg (122 ms worst in the first window), ~40 kpx/frame, 52 ms/s copying into the PSRAM framebuffer, LVGL idle 68 %, core 0 idle 94 %, core 1 idle 66 %, internal 66.9 KB free / 31.7 KB largest, PSRAM 6.6 MB free. **Provoke session logged 2026-09-27 → [[perf-baseline-2026-09-27]]**: Driveline redraws ~10×/s with nothing changing (39 kpx, 30 ms, a third of core 1 — an unconditional `lv_label_set_text` every 100 ms `(repo)`); screen changes are single 140–330 ms frames (= the swipe lag; not a bounce-buffer matter); the Simulation tab is the heaviest normal load (2 Mpx/s, 26 % of the time writing PSRAM, LVGL idle 9 %); a flash write is invisible to the LVGL counters, so the monitor needs a **panel vsync/refresh counter** to see flicker and dots directly; the monitor is blind during OTA (ticks from the blocked `loop()`). Heap flat throughout (66–67 KB internal, 31.7 KB largest, 6.6 MB PSRAM). **Plan amended**: 1b = stop the Driveline redraw + add vsync counter + timer-driven PERF, re-baseline; step 2 judged on the Simulation tab and during a scan, by the refresh counter. **Step 1b done 2026-09-27 `(verified, bench)`**: Driveline `tick()` now writes labels/chips only on change → idle Driveline 0 fps, 0 ms/s PSRAM copies, LVGL idle 96 %, core 1 idle 96 % (was 9.7 fps / 52 ms/s / 68 % / 66 %). `perf` gained the panel counters: **~24 vsync/s, longest gap 41.5 ms when healthy** — a DMA restart must show as a gap ≥ 2 frames (≈ 83 ms). Reporting runs from an esp_timer, so OTA is no longer a blind spot. **Second session 2026-09-27 → [[perf-dots-and-ota-2026-09-27]]**: (a) with dots on screen and everything idle the panel refreshed perfectly (24/s, 41.5 ms) — **dots are sub-frame DMA data glitches, invisible to the vsync counter, judged by eye only; bounce buffers are the designed fix**; (b) during `ota install` the panel drops to **4–8 refreshes/s with 290–747 ms gaps** — flash writes blank it ~75 % of the time; **no progress bar is possible before step 3**; target 24/s + 41.5 ms during an install. Tuning save and `ota check` lost no frame. **Correction the same evening**: the panel library already runs **10-line bounce buffers** and a **21 MHz** clock (the `platformio.ini` flags saying otherwise were dead names) — so the dots are *late bounce refills* re-sending the previous 10-line chunk (the photo shows text pixels echoed below each line), and step 2 as written is moot. **Step 3 (`CONFIG_SPIRAM_XIP_FROM_PSRAM` + `CONFIG_LCD_RGB_ISR_IRAM_SAFE`, pioarduino `custom_sdkconfig`, branch `display-xip`) now targets both the dots and the OTA blanking.** Fallbacks if dots remain: lower pixel clock (18 MHz), larger bounce buffers, Wi-Fi/LWIP buffers back to internal RAM (`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP=n`, costs internal RAM). **Step 3 built and measured 2026-09-27 17:46 → [[perf-xip-ota-2026-09-27]]: during a full `ota install` the panel held 24–25 refreshes/s with a 41.5 ms gap (stock core: 4–8/s, 290–747 ms). The flash-write blanking is fixed `(verified)`; a progress bar during updates is now possible (step 4). PSRAM free 6.6 → 4.9 MB (code resident there); no render slow-down seen in the one full-redraw sample. Dots on the XIP build still to be judged by eye (Wi-Fi up, idle screen).** **Step 4 done 2026-09-27**: the OTA notice keeps the screen on with a progress bar and "Do not switch off the ignition"; second forced install under `perf`: 24–25 frames/s, 41.5 ms gap throughout, bar redrawing 2–3×/s; user: "the progress bar appeared and no flickering or other issues" `(verified)`. **Merged to main and tagged v0.1.7 (2026-09-27, user decision)** after the user exercised the XIP build (Wi-Fi scan, update check and install) with no flicker or other issues reported. Whether the dots are fully gone in longer use stays open — report any sighting on v0.1.7 and the fallbacks above apply. First CI run with the core rebuild = the v0.1.7 tag build; if it fails, the release is missing until the workflow is fixed.
2. ~~**Step A - bounce buffers only**~~ **(void — already on, 10 lines, via the board header; 2026-09-27)** (`ESP_PANEL_LCD_RGB_BOUNCE_BUF_SIZE`, today 0; start at 10 lines = 1024x10 px, ~20 KB each, two buffers, internal DMA-capable RAM). The panel then reads from internal RAM that the CPU refills from PSRAM, so it tolerates short PSRAM stalls. **Expected to cure the Wi-Fi-traffic dots; will NOT cure flash-write flicker**: while flash is written the cache is disabled, so the refill has nothing to read from either. RAM: 67 KB internal free but the largest block is ~32 KB, so two 20 KB buffers may not fit - if not, shrink the LVGL draw buffer 60 -> 40 lines (frees ~40 KB) and check render speed. The refill costs CPU (measure). 2. ~~**Step A - bounce buffers only**~~ **(void — already on, 10 lines, via the board header; 2026-09-27)** (`ESP_PANEL_LCD_RGB_BOUNCE_BUF_SIZE`, today 0; start at 10 lines = 1024x10 px, ~20 KB each, two buffers, internal DMA-capable RAM). The panel then reads from internal RAM that the CPU refills from PSRAM, so it tolerates short PSRAM stalls. **Expected to cure the Wi-Fi-traffic dots; will NOT cure flash-write flicker**: while flash is written the cache is disabled, so the refill has nothing to read from either. RAM: 67 KB internal free but the largest block is ~32 KB, so two 20 KB buffers may not fit - if not, shrink the LVGL draw buffer 60 -> 40 lines (frees ~40 KB) and check render speed. The refill costs CPU (measure).
3. **Step B - `CONFIG_SPIRAM_XIP_FROM_PSRAM` (+ `CONFIG_SPIRAM_RODATA`)** via pioarduino `custom_sdkconfig`: code and constants run from PSRAM, so flash writes no longer block PSRAM. **Cures flash-write flicker** (screen could stay on during OTA with a progress bar instead of going dark). Cost/risk: `custom_sdkconfig` rebuilds the Arduino core from source (much slower builds, locally and in CI), and may not work cleanly with this platform version - do it on a branch, release only once it works. 3. **Step B - `CONFIG_SPIRAM_XIP_FROM_PSRAM` (+ `CONFIG_SPIRAM_RODATA`)** via pioarduino `custom_sdkconfig`: code and constants run from PSRAM, so flash writes no longer block PSRAM. **Cures flash-write flicker** (screen could stay on during OTA with a progress bar instead of going dark). Cost/risk: `custom_sdkconfig` rebuilds the Arduino core from source (much slower builds, locally and in CI), and may not work cleanly with this platform version - do it on a branch, release only once it works.
4. **Measure again after each step** (FPS, CPU, which symptoms still reproduce) and record the numbers here and on [[esp32-s3-touch-lcd-5b]]. 4. **Measure again after each step** (FPS, CPU, which symptoms still reproduce) and record the numbers here and on [[esp32-s3-touch-lcd-5b]].
+8 -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
@@ -42,17 +42,19 @@ Push to `main` (no tag) builds a rolling **pre-release `main-latest`** — unsig
Always remember: an install is performed by the firmware that is **already running**, so a fix to the install path only takes effect on the update *after* the one that delivers it (v0.1.1 → v0.1.2 still flickered because v0.1.1 did the writing). Always remember: an install is performed by the firmware that is **already running**, so a fix to the install path only takes effect on the update *after* the one that delivers it (v0.1.1 → v0.1.2 still flickered because v0.1.1 did the writing).
**CI note (2026-09-27):** the v0.1.7 tag build failed with `ModuleNotFoundError: No module named 'SCons.Tool.FortranCommon'` — upstream PlatformIO core + pioarduino's stripped SCons 4.8.1 on the new ESP-IDF (custom_sdkconfig) build path. Fixed by installing pioarduino's core fork in the workflow (same pin the platform uses locally); the tag was moved to the fix commit and pushed again.
**Progress bar on screen (branch `display-xip`, 2026-09-27; supersedes the dark-screen writes of v0.1.2–v0.1.6).** With the core rebuilt to execute from PSRAM and an IRAM-safe panel refill (see [[perf-xip-ota-2026-09-27]]), flash writes no longer blank the panel, so the full-screen notice now stays lit: "Updating to vX", a bar driven per percent from the download loop, and an amber "Do not switch off the ignition". Verified 2026-09-27 by the user ("the progress bar appeared and no flickering") and by `perf`: 24–25 panel frames/s, 41.5 ms gap for the whole download. Previously (v0.1.2–v0.1.6) the backlight was off while the image was written: a full-screen notice "Updating to vX — the screen goes dark for about a minute — do not switch off" shows for 3 s first, then "Installed vX / Restarting…" or "Update failed / Still running vY". Seen by the user on the 2026-09-27 screen installs: dark for about a minute, then the restart. The running version is always shown bottom-right on every screen (`A v0.1.2`). **Progress bar on screen (branch `display-xip`, 2026-09-27; supersedes the dark-screen writes of v0.1.2–v0.1.6).** With the core rebuilt to execute from PSRAM and an IRAM-safe panel refill (see [[perf-xip-ota-2026-09-27]]), flash writes no longer blank the panel, so the full-screen notice now stays lit: "Updating to vX", a bar driven per percent from the download loop, and an amber "Do not switch off the ignition". Verified 2026-09-27 by the user ("the progress bar appeared and no flickering") and by `perf`: 24–25 panel frames/s, 41.5 ms gap for the whole download. Previously (v0.1.2–v0.1.6) the backlight was off while the image was written: a full-screen notice "Updating to vX — the screen goes dark for about a minute — do not switch off" shows for 3 s first, then "Installed vX / Restarting…" or "Update failed / Still running vY". Seen by the user on the 2026-09-27 screen installs: dark for about a minute, then the restart. The running version is always shown bottom-right on every screen (`A v0.1.2`).
Known quirk: `ota status` shows the *other* slot's "built" date from the framework's precompiled app descriptor (e.g. "Nov 4 2025"), not our build time — ignore it. Known quirk: `ota status` shows the *other* slot's "built" date from the framework's precompiled app descriptor (e.g. "Nov 4 2025"), not our build time — ignore it.
## 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).
@@ -104,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 (not built yet) ## Inst. Cluster (implemented 2026-09-27)
Plan agreed 2026-09-26: B is updated **by A over ESP-NOW**, not by the RS485 wire (the wire is one-way A→B; ESP-NOW is bidirectional and faster). A downloads B's signed image (target `patrol-b`) from B's repo releases, sends it with acks, B verifies the signature and swaps slots with the same rollback scheme. Prerequisites: B moves off the stock `default.csv` (1.25 MB slots, 1.07 MB firmware → too tight) to a 16 MB layout (confirm B's flash size first; one USB flash); ESP-NOW pairing/encryption so only A can talk to B; protocol frames for the transfer (shared `automotive_data.h` → version bump in both repos). B's repo is public since 2026-09-27 (anonymous API 200). Wire stays for gauge-data redundancy. 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
+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