9 Commits

Author SHA1 Message Date
julian a41800acc2 Remove the deep-sleep feature entirely (user decision): power manager, Settings switch, NVS key, sleep bit in the shared header, docs
Firmware / build (push) Successful in 2m58s
2026-09-28 17:20:35 +02:00
julian 6854aa1c46 Rename -> Inst. Cluster (user); power manager: deep sleep on link silence, wake on IO1 or 60 s probe boot; Ota::isBusy; sleep bit in shared header
Firmware / build (push) Successful in 2m59s
2026-09-28 16:38:23 +02:00
julian 43697f3cc8 Wiki: 2N2222 stage verified on the cluster with 2.6 k base resistors
Firmware / build (push) Successful in 6s
2026-09-28 12:12:15 +02:00
julian 8f54c79587 Wiki: 2N2222 open-collector wiring for the tach and temp output stages
Firmware / build (push) Successful in 5s
2026-09-28 10:42:52 +02:00
julian d047fb1bbc docs: point to the shared commands cheat-sheet in the A repo
Firmware / build (push) Successful in 5s
2026-09-28 10:21:07 +02:00
julian 3a751cfdfa Shared header: DEFAULT_* bench values removed (A no longer sends invented data)
Firmware / build (push) Successful in 3m0s
2026-09-28 09:31:01 +02:00
julian 7bc2188ae7 Gauge screen: coolant and gearbox oil as gradient arc gauges with needles on the rim, icons past the hot ends; digits only for the battery
Firmware / build (push) Successful in 3m16s
2026-09-28 08:48:16 +02:00
julian 232eacc8a1 Gauge screen: round-panel layout with warning ring (red blink on alerts, amber on cooling), whole-degree values, Wi-Fi and link tell-tales
Firmware / build (push) Successful in 3m0s
2026-09-27 21:40:18 +02:00
julian 2262996690 Wiki: Controller B OTA verified end-to-end (pair over the wire, credential push, dev -> v0.1.0 from A); open question 12 answered
Firmware / build (push) Successful in 5s
2026-09-27 20:47:33 +02:00
33 changed files with 445 additions and 197 deletions
+7 -7
View File
@@ -1,18 +1,18 @@
name: Firmware name: Firmware
# Controller B firmware, built by PlatformIO on every push. Same scheme as # Inst. Cluster firmware, built by PlatformIO on every push. Same scheme as
# Controller A (ESP32-S3-Touch-LCD-5B/.gitea/workflows/firmware.yml): # Main CTRL (ESP32-S3-Touch-LCD-5B/.gitea/workflows/firmware.yml):
# #
# - push to master -> rolling PRE-release `main-latest` (firmware.bin + .elf), # - push to master -> rolling PRE-release `main-latest` (firmware.bin + .elf),
# unsigned, no manifest. Bench / USB flashing only; the # unsigned, no manifest. Bench / USB flashing only; the
# device reads /releases/latest, which skips pre-releases. # device reads /releases/latest, which skips pre-releases.
# - push tag v* -> the OTA release: firmware.bin + firmware.elf + # - push tag v* -> the OTA release: firmware.bin + firmware.elf +
# manifest.txt (size, sha256, ECDSA P-256 signature over # manifest.txt (size, sha256, ECDSA P-256 signature over
# "patrol-b|<tag>|<sha256>"). Controller B pulls this when # "patrol-b|<tag>|<sha256>"). Inst. Cluster pulls this when
# A's Updates screen (or `ota install` on B) asks for it. # A's Updates screen (or `ota install` on B) asks for it.
# #
# Signing key: secret BMW_NISSAN_FIRMWARE_SIGNING_KEY (PEM, EC P-256), the same # Signing key: secret BMW_NISSAN_FIRMWARE_SIGNING_KEY (PEM, EC P-256), the same
# key as Controller A's; the target string keeps the two apart. Its public half # key as Main CTRL's; the target string keeps the two apart. Its public half
# is compiled in (include/config/ota_config.h) and kept in # is compiled in (include/config/ota_config.h) and kept in
# tools/ota/firmware_signing_pub.pem for the self-check below. # tools/ota/firmware_signing_pub.pem for the self-check below.
# #
@@ -128,12 +128,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 B ${TAG}" NAME="Inst. Cluster ${TAG}"
BODY="Signed OTA release. Installed from Controller A's Updates screen (parked) or with \`ota install\` on Controller B's console." BODY="Signed OTA release. Installed from Main CTRL's Updates screen (parked) or with \`ota install\` on Inst. Cluster's console."
else else
TAG="main-latest" TAG="main-latest"
PRE=true PRE=true
NAME="Controller B main build" NAME="Inst. Cluster main build"
BODY="Unsigned build of master @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests." BODY="Unsigned build of master @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests."
OLD=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \ OLD=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true) | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
+13 -11
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview ## Project Overview
**Controller B** of the BMW M57N → Nissan Patrol swap display system, running on a **Waveshare ESP32-S3-LCD-1.3** (1.3" 240×240 ST7789VW, shown with a circular mask). It is a slave/extension of Controller A (ESP32-S3-Touch-LCD-5B, sibling repo `../ESP32-S3-Touch-LCD-5B`): it receives protocol v2 frames over UART1 **and** ESP-NOW at 5 Hz, shows them, and drives the Patrol cluster's tachometer and coolant gauges from them on IO7 / IO8. **Inst. Cluster** of the BMW M57N → Nissan Patrol swap display system, running on a **Waveshare ESP32-S3-LCD-1.3** (1.3" 240×240 ST7789VW, shown with a circular mask). It is a slave/extension of Main CTRL (ESP32-S3-Touch-LCD-5B, sibling repo `../ESP32-S3-Touch-LCD-5B`): it receives protocol v2 frames over UART1 **and** ESP-NOW at 5 Hz, shows them, and drives the Patrol cluster's tachometer and coolant gauges from them on IO7 / IO8.
**Hardware**: ESP32-S3R8 dual-core @ 240 MHz, 16 MB flash, 8 MB OPI PSRAM, CH343 USB-serial bridge (not native USB-CDC), Wi-Fi + BLE 5, 13 free-function GPIOs on two 8-pin headers. **Hardware**: ESP32-S3R8 dual-core @ 240 MHz, 16 MB flash, 8 MB OPI PSRAM, CH343 USB-serial bridge (not native USB-CDC), Wi-Fi + BLE 5, 13 free-function GPIOs on two 8-pin headers.
@@ -12,6 +12,8 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Build & Development Commands ## Build & Development Commands
The complete cheat-sheet for both controllers lives in the sibling repo: `ESP32-S3-Touch-LCD-5B/docs/COMMANDS.md`. Update it when a B command changes.
```bash ```bash
pio run # build pio run # build
pio run --target upload # upload pio run --target upload # upload
@@ -32,7 +34,7 @@ Serial goes through the onboard **CH343 USB-UART chip on UART0**, so the port ap
- **Core 1**: `lvglTask()` calls `DisplayInit::update()` every 5 ms (`lv_timer_handler()` under the LVGL lock; the tick comes from `millis()` via `LV_TICK_CUSTOM`). The Arduino `loop()` also runs on Core 1 (`ARDUINO_RUNNING_CORE=1`) and drives the screen: every 200 ms it calls `GaugeScreen::update()` and `DebugMonitor::tick()`. - **Core 1**: `lvglTask()` calls `DisplayInit::update()` every 5 ms (`lv_timer_handler()` under the LVGL lock; the tick comes from `millis()` via `LV_TICK_CUSTOM`). The Arduino `loop()` also runs on Core 1 (`ARDUINO_RUNNING_CORE=1`) and drives the screen: every 200 ms it calls `GaugeScreen::update()` and `DebugMonitor::tick()`.
- **Core 0**: the UART receiver task (byte-level framing state machine) and the Wi-Fi/ESP-NOW receive callback. Both hand complete frames to `UARTReceiver::processFrame()`, which validates, dedupes DATA frames on `packet_id`, and caches CONFIG frames. Neither touches LVGL (the debug flag is only *recorded* there). Shared data is guarded by `g_data_mutex` inside `uart_receiver.cpp`. - **Core 0**: the UART receiver task (byte-level framing state machine) and the Wi-Fi/ESP-NOW receive callback. Both hand complete frames to `UARTReceiver::processFrame()`, which validates, dedupes DATA frames on `packet_id`, and caches CONFIG frames. Neither touches LVGL (the debug flag is only *recorded* there). Shared data is guarded by `g_data_mutex` inside `uart_receiver.cpp`.
**LVGL lock** (added 2026-09-27, same rule as Controller A's `lvgl_port_lock()`): `DisplayInit::lock(timeout_ms)` / `unlock()`, a recursive mutex. `lvglTask` holds it while rendering; every `lv_*` call anywhere else must hold it too. Before it existed, `loop()` wrote labels while the higher-priority LVGL task could preempt mid-call - the bug class that froze A. **LVGL lock** (added 2026-09-27, same rule as Main CTRL's `lvgl_port_lock()`): `DisplayInit::lock(timeout_ms)` / `unlock()`, a recursive mutex. `lvglTask` holds it while rendering; every `lv_*` call anywhere else must hold it too. Before it existed, `loop()` wrote labels while the higher-priority LVGL task could preempt mid-call - the bug class that froze A.
### Modules ### Modules
@@ -57,7 +59,7 @@ include/
config/lv_conf.h # LVGL 8.4.0 config (RGB565, dark theme, 128 KB pool in PSRAM, millis() tick, log off) config/lv_conf.h # LVGL 8.4.0 config (RGB565, dark theme, 128 KB pool in PSRAM, millis() tick, log off)
config/ota_config.h # FW_VERSION (CI bakes it, "dev" locally), OTA_TARGET "patrol-b", repo URLs, CA roots, signing public key config/ota_config.h # FW_VERSION (CI bakes it, "dev" locally), OTA_TARGET "patrol-b", repo URLs, CA roots, signing public key
modules/uart_receiver.h, espnow_receiver.h, gauge_outputs.h, debug_monitor.h, link_peer.h, ota_update.h, console.h modules/uart_receiver.h, espnow_receiver.h, gauge_outputs.h, debug_monitor.h, link_peer.h, ota_update.h, console.h
protocol/automotive_data.h # SHARED packet contract — copied from Controller A, must match its version protocol/automotive_data.h # SHARED packet contract — copied from Main CTRL, must match its version
protocol/link_secure.h # SHARED too: AES-256-GCM envelope for SECURE frames (byte-identical in both repos) protocol/link_secure.h # SHARED too: AES-256-GCM envelope for SECURE frames (byte-identical in both repos)
``` ```
@@ -65,7 +67,7 @@ include/
**DisplayInit** — `init()`, `update()`, `lock(timeout_ms)` / `unlock()`, `setBrightness(0–255)`, `getBrightness()`. Default brightness 128. `DISPLAY_RADIUS 120` defines the circular mask. **DisplayInit** — `init()`, `update()`, `lock(timeout_ms)` / `unlock()`, `setBrightness(0–255)`, `getBrightness()`. Default brightness 128. `DISPLAY_RADIUS 120` defines the circular mask.
**GaugeScreen** — `init()` builds and loads the screen once; `update(data, link_ok)` at 5 Hz writes a label, colour or icon **only when it changed** (`lv_label_set_text()` and style setters invalidate even for identical values, and every redraw is SPI time). Gear label: engaged gear, or the target gear pulsing while `target != engaged`, red on the mismatch alert; icons red from A's alert bits; everything N/A when the link is lost. **GaugeScreen** (round-panel layout, user's design 2026-09-28: two ARC GAUGES on the rim with no digits - coolant on the left from compass 230° (bottom, 50 °C) to 320° (top, 120 °C), gearbox oil on the right from 140° (bottom, 40 °C) to 40° (top, 150 °C); each a blue→neutral→red gradient built from 10° `lv_arc` segments, a white `lv_line` needle recomputed only when its angle changes, and the gauge's icon just past the hot end (red variant while that alert is on); 6 px warning-lamp ring at the very rim - dim / RED BLINKING 2 Hz on any red alert / amber on gearbox cooling; gear 110 px centre; battery [icon][12.4] bottom; Wi-Fi tell-tale at 9 o'clock (green only while joined for an update), red `!` at 3 o'clock when the link is lost. LVGL angle = compass − 90; everything placed absolutely inside the circle) — `init()` builds and loads the screen once; `setNotice(text)` shows the updater's progress line; `update(data, link_ok)` at 5 Hz writes a label, colour or icon **only when it changed** (`lv_label_set_text()` and style setters invalidate even for identical values, and every redraw is SPI time). Gear label: engaged gear, or the target gear pulsing while `target != engaged`, red on the mismatch alert; icons red from A's alert bits; everything N/A when the link is lost.
**UARTReceiver** — `init()`, `processFrame(frame, len, source)`, `getLatestData()`, `getStats()` (applied / per-transport / duplicate / config counts, checksum / framing / version errors, last times), `isConnected()`, `isSourceAlive(source)`, `getConfig()` + `getConfigSeq()`. Link lost after 1000 ms without an applied DATA frame on any transport. **UARTReceiver** — `init()`, `processFrame(frame, len, source)`, `getLatestData()`, `getStats()` (applied / per-transport / duplicate / config counts, checksum / framing / version errors, last times), `isConnected()`, `isSourceAlive(source)`, `getConfig()` + `getConfigSeq()`. Link lost after 1000 ms without an applied DATA frame on any transport.
@@ -73,15 +75,15 @@ include/
**GaugeOutputs** — `init()`, `applyConfig(cfg, persist)`, `update(data, link_ok)` at 5 Hz, `printStatus()`. Tach = `rpm × ppr / 60 × (1 + trim)` at 50 % duty on LEDC channel 2 (timer 1); coolant = `slope × T + offset` 8-bit duty at `temp_pwm_hz` on channel 4 (timer 2). Channels 0/1 (timer 0) belong to the LovyanGFX backlight — never reuse them. Both outputs low when the link is down, the value is invalid, the output is disabled, or T is below `temp_min_c`; A's override forces fixed values. Last config cached in NVS namespace `gaugecfg`. **GaugeOutputs** — `init()`, `applyConfig(cfg, persist)`, `update(data, link_ok)` at 5 Hz, `printStatus()`. Tach = `rpm × ppr / 60 × (1 + trim)` at 50 % duty on LEDC channel 2 (timer 1); coolant = `slope × T + offset` 8-bit duty at `temp_pwm_hz` on channel 4 (timer 2). Channels 0/1 (timer 0) belong to the LovyanGFX backlight — never reuse them. Both outputs low when the link is down, the value is invalid, the output is disabled, or T is below `temp_min_c`; A's override forces fixed values. Last config cached in NVS namespace `gaugecfg`.
**DebugMonitor** — `init()`, `setVisible(bool)` (records only; called from the receiver), `tick()` (applies under the LVGL lock; called from loop), `isVisible()`. Driven by the `debug_enabled` byte in each packet, so Controller A's debug toggle controls B's overlays. **DebugMonitor** — `init()`, `setVisible(bool)` (records only; called from the receiver), `tick()` (applies under the LVGL lock; called from loop), `isVisible()`. Driven by the `debug_enabled` byte in each packet, so Main CTRL's debug toggle controls B's overlays.
**LinkPeer** (2026-09-27) — `init()` loads the pairing key + A's MAC (NVS `linkpeer`) and the Wi-Fi credentials A handed over (NVS `wifi`, same keys as A's). `onPairFrame()` is called by `UARTReceiver::processFrame()` for `PAIR` frames **from the UART source only**; `onRadioFrame()` by `EspNowReceiver` for every non-DATA/CONFIG frame. Both just fill a one-slot mailbox; `tick()` (loop task) decrypts, checks the sender MAC against the paired A, writes NVS, and sends a `STATUS` frame to A every 5 s or on any phase change (`EspNowReceiver::sendTo()`, A's MAC from its data frames). `setOtaStatus()` / `setOtaCommandHandler()` are the updater's hooks. Nonce replay window of 4 for OTA commands. Console: `link status | unpair`, `wifi status | forget`. The password is never printed. **LinkPeer** (2026-09-27) — `init()` loads the pairing key + A's MAC (NVS `linkpeer`) and the Wi-Fi credentials A handed over (NVS `wifi`, same keys as A's). `onPairFrame()` is called by `UARTReceiver::processFrame()` for `PAIR` frames **from the UART source only**; `onRadioFrame()` by `EspNowReceiver` for every non-DATA/CONFIG frame. Both just fill a one-slot mailbox; `tick()` (loop task) decrypts, checks the sender MAC against the paired A, writes NVS, and sends a `STATUS` frame to A every 5 s or on any phase change (`EspNowReceiver::sendTo()`, A's MAC from its data frames). `setOtaStatus()` / `setOtaCommandHandler()` are the updater's hooks. Nonce replay window of 4 for OTA commands. Console: `link status | unpair`, `wifi status | forget`. The password is never printed.
**Ota** (2026-09-27) — port of Controller A's `ota_update.cpp`: `ota status | check | install [force] | rollback` and A's `OTA_CMD` land in `startJob()`; the job runs in `tick()` (loop task, blocks the gauges - parked anyway). Gate: link data says rpm 0 and lever P/N/unknown, or the link is silent (A off); credentials present. Joins Wi-Fi only for the job and `WiFi.disconnect(false)` afterwards so the ESP-NOW receiver hops back to A. Manifest signature (ECDSA P-256 over `patrol-b|version|sha256`) checked before download, streamed sha256 checked after, `esp_ota_end()` image check, slot switch, reboot; `verifyRollbackLater()` overridden so the new image stays pending until `tick()` confirms it after `OTA_CONFIRM_MS` (30 s). Progress: `GaugeScreen::setNotice("Updating vX N%")` and a STATUS pumped to A at most once a second from inside the download loop. Never put secrets in source - the repo and its releases are public. **Ota** (2026-09-27) — port of Main CTRL's `ota_update.cpp`: `ota status | check | install [force] | rollback` and A's `OTA_CMD` land in `startJob()`; the job runs in `tick()` (loop task, blocks the gauges - parked anyway). Gate: link data says rpm 0 and lever P/N/unknown, or the link is silent (A off); credentials present. Joins Wi-Fi only for the job and `WiFi.disconnect(false)` afterwards so the ESP-NOW receiver hops back to A. Manifest signature (ECDSA P-256 over `patrol-b|version|sha256`) checked before download, streamed sha256 checked after, `esp_ota_end()` image check, slot switch, reboot; `verifyRollbackLater()` overridden so the new image stays pending until `tick()` confirms it after `OTA_CONFIRM_MS` (30 s). Progress: `GaugeScreen::setNotice("Updating vX N%")` and a STATUS pumped to A at most once a second from inside the download loop. Never put secrets in source - the repo and its releases are public.
**Console** — `Console::addHandler()` chain, `tick()` from loop; `help` asks every handler to print its lines. **Console** — `Console::addHandler()` chain, `tick()` from loop; `help` asks every handler to print its lines.
### UART packet (shared with Controller A) ### UART packet (shared with Main CTRL)
Protocol **v2**: `0xAA | 0x02 | type | length | payload | XOR | 0x55`. DATA (21-byte `automotive_data_t`: lever, target/engaged gear nibbles, rpm, temps, battery, alerts, valid flags) every 200 ms; CONFIG (27-byte `link_config_t`: gauge calibration + alert thresholds) on change and every 5 s. Same frames on UART1 and ESP-NOW. Spec: sibling repo `docs/UART_PROTOCOL.md`. `include/protocol/automotive_data.h` (and `link_secure.h`) must stay byte-identical to A's; B rejects other versions and counts them. Protocol **v2**: `0xAA | 0x02 | type | length | payload | XOR | 0x55`. DATA (21-byte `automotive_data_t`: lever, target/engaged gear nibbles, rpm, temps, battery, alerts, valid flags) every 200 ms; CONFIG (27-byte `link_config_t`: gauge calibration + alert thresholds) on change and every 5 s. Same frames on UART1 and ESP-NOW. Spec: sibling repo `docs/UART_PROTOCOL.md`. `include/protocol/automotive_data.h` (and `link_secure.h`) must stay byte-identical to A's; B rejects other versions and counts them.
@@ -91,7 +93,7 @@ Alert thresholds live on A; B turns icons red from the `alerts` bits only. The g
### Firmware updates (OTA) ### Firmware updates (OTA)
B updates itself from this repo's Gitea releases; A triggers it from Settings → Updates (Controller B card) or B's console does (`ota check`, `ota install`). CI: `.gitea/workflows/firmware.yml` - push to `master` → unsigned pre-release `main-latest`; tag `v*` → signed release (`manifest.txt`, target `patrol-b`), needs the repo secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY` (same key as A's). Release with one push: `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin master`. Version strings ≤ 15 chars. First pairing (`link pair` on A, wire connected) and the procedure: `wiki/pages/controller-b-ota.md`. B updates itself from this repo's Gitea releases; A triggers it from Settings → Updates (Inst. Cluster card) or B's console does (`ota check`, `ota install`). CI: `.gitea/workflows/firmware.yml` - push to `master` → unsigned pre-release `main-latest`; tag `v*` → signed release (`manifest.txt`, target `patrol-b`), needs the repo secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY` (same key as A's). Release with one push: `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin master`. Version strings ≤ 15 chars. First pairing (`link pair` on A, wire connected) and the procedure: `wiki/pages/controller-b-ota.md`.
## Hardware-Specific Details ## Hardware-Specific Details
@@ -103,7 +105,7 @@ B updates itself from this repo's Gitea releases; A triggers it from Settings
| 38 / 39 / 42 | LCD DC / CS / RST | | 38 / 39 / 42 | LCD DC / CS / RST |
| 20 | LCD backlight, LEDC PWM | | 20 | LCD backlight, LEDC PWM |
| 43 / 44 | UART0 → CH343 USB bridge (debug console) — not available for the link | | 43 / 44 | UART0 → CH343 USB bridge (debug console) — not available for the link |
| IO1 | UART1 RX from Controller A (left header, pin 4) | | IO1 | UART1 RX from Main CTRL (left header, pin 4) |
| IO2 | UART1 TX — unused, link is receive-only | | IO2 | UART1 TX — unused, link is receive-only |
| IO7 | Tachometer pulse output (GaugeOutputs, hardware-timer ISR, phase-continuous) | | IO7 | Tachometer pulse output (GaugeOutputs, hardware-timer ISR, phase-continuous) |
| IO8 | Coolant gauge PWM output (GaugeOutputs, LEDC ch 4) | | IO8 | Coolant gauge PWM output (GaugeOutputs, LEDC ch 4) |
@@ -125,7 +127,7 @@ Pins are set in `src/modules/display_init.cpp` and `platformio.ini` (`-DUART_RX_
- Init order: `DisplayInit::init()` → `GaugeScreen::init()` → create `lvglTask`. - Init order: `DisplayInit::init()` → `GaugeScreen::init()` → create `lvglTask`.
- Hold `DisplayInit::lock()` around every `lv_*` call outside `lvglTask`; never call LVGL from the receiver task or the ESP-NOW callback. - Hold `DisplayInit::lock()` around every `lv_*` call outside `lvglTask`; never call LVGL from the receiver task or the ESP-NOW callback.
- Write a label or style only when the value changed (`setText()` / `setIcon()` in `gauge_screen.cpp` do this). - Write a label or style only when the value changed (`setText()` / `setIcon()` in `gauge_screen.cpp` do this).
- Screens are built once and kept; do not delete and rebuild them on the fly (dangling pointers froze Controller A). - Screens are built once and kept; do not delete and rebuild them on the fly (dangling pointers froze Main CTRL).
- Colour depth stays `LV_COLOR_DEPTH 16` (the icon arrays are RGB565 with alpha). - Colour depth stays `LV_COLOR_DEPTH 16` (the icon arrays are RGB565 with alpha).
## Troubleshooting ## Troubleshooting
@@ -141,6 +143,6 @@ Pins are set in `src/modules/display_init.cpp` and `platformio.ini` (`-DUART_RX_
## Important Notes ## Important Notes
- This board is the **only** one of the two with free hardware-PWM GPIO; Controller A has none. Gauge driving belongs here. - This board is the **only** one of the two with free hardware-PWM GPIO; Main CTRL has none. Gauge driving belongs here.
- Bench wiring: A's `485_A` straight into IO1 plus common GND (verified 2026-09-21). In the car, A's GPIO 44 only exists as the RS485 pair, so use a transceiver on B or rely on the ESP-NOW leg. See `wiki/pages/controller-link.md`. - Bench wiring: A's `485_A` straight into IO1 plus common GND (verified 2026-09-21). In the car, A's GPIO 44 only exists as the RS485 pair, so use a transceiver on B or rely on the ESP-NOW leg. See `wiki/pages/controller-link.md`.
- ESP-NOW is the redundant leg (implemented 2026-09-21); BLE remains an option — `wiki/pages/link-redundancy.md`. - ESP-NOW is the redundant leg (implemented 2026-09-21); BLE remains an option — `wiki/pages/link-redundancy.md`.
+7 -5
View File
@@ -1,16 +1,18 @@
# ESP32-S3-LCD-1.3 - Controller B (Phase 1) # ESP32-S3-LCD-1.3 - Inst. Cluster (Phase 1)
**Compact Automotive Display Unit** **Compact Automotive Display Unit**
## Project Status ## Project Status
**2026-09-27**: over-the-air updates implemented (B pulls its own signed release; Controller A triggers and shows progress; pairing over the wire once on the bench) - see `wiki/pages/controller-b-ota.md`. Serial console on the CH343 port: `help`, `link status`, `ota status | check | install`. All build / upload / monitor / console commands for both controllers: `../ESP32-S3-Touch-LCD-5B/docs/COMMANDS.md`.
**2026-09-27**: over-the-air updates implemented (B pulls its own signed release; Main CTRL triggers and shows progress; pairing over the wire once on the bench) - see `wiki/pages/controller-b-ota.md`. Serial console on the CH343 port: `help`, `link status`, `ota status | check | install`.
**Current Phase**: Phase 1 - Hardware Setup & Basic Display ✅ **Current Phase**: Phase 1 - Hardware Setup & Basic Display ✅
## Overview ## Overview
This is Controller B in the BMW Patrol automotive data display system. It receives UART data from Controller A (ESP32-S3-Touch-LCD-5B) and displays it on a compact 1.3" round display. This is Inst. Cluster in the BMW Patrol automotive data display system. It receives UART data from Main CTRL (ESP32-S3-Touch-LCD-5B) and displays it on a compact 1.3" round display.
### Phase 1 Goals ### Phase 1 Goals
@@ -67,7 +69,7 @@ ESP32-S3-LCD-1.3/
│ │ └── lv_conf.h # LVGL 8.4.0 configuration │ │ └── lv_conf.h # LVGL 8.4.0 configuration
│ ├── modules/ # module headers │ ├── modules/ # module headers
│ └── protocol/ │ └── protocol/
│ └── automotive_data.h # link protocol, shared with Controller A │ └── automotive_data.h # link protocol, shared with Main CTRL
├── src/ ├── src/
│ ├── main.cpp # setup/loop: link, gauges, screen update │ ├── main.cpp # setup/loop: link, gauges, screen update
│ ├── modules/ # display init + LVGL lock, gauge screen, receivers, gauge outputs │ ├── modules/ # display init + LVGL lock, gauge screen, receivers, gauge outputs
@@ -108,7 +110,7 @@ Expected output during Phase 1:
``` ```
================================= =================================
ESP32-S3-LCD-1.3 - Controller B ESP32-S3-LCD-1.3 - Inst. Cluster
Phase 1: Display Initialization Phase 1: Display Initialization
================================= =================================
+1 -1
View File
@@ -14,7 +14,7 @@
/* Memory settings */ /* Memory settings */
#define LV_MEM_CUSTOM 0 // Use LVGL's built-in memory manager #define LV_MEM_CUSTOM 0 // Use LVGL's built-in memory manager
/* 128 KB pool in PSRAM (2026-09-27, as on Controller A): the old 64 KB pool sat /* 128 KB pool in PSRAM (2026-09-27, as on Main CTRL): the old 64 KB pool sat
* in the scarce internal RAM. Draw buffers stay internal (SPI DMA). */ * in the scarce internal RAM. Draw buffers stay internal (SPI DMA). */
#define LV_MEM_SIZE (128 * 1024U) #define LV_MEM_SIZE (128 * 1024U)
#define LV_MEM_ADR 0 #define LV_MEM_ADR 0
+3 -3
View File
@@ -1,7 +1,7 @@
/** /**
* ota_config.h - where Controller B looks for firmware updates, and what it trusts. * ota_config.h - where Inst. Cluster looks for firmware updates, and what it trusts.
* *
* Same scheme as Controller A (ESP32-S3-Touch-LCD-5B/include/config/ota_config.h): * Same scheme as Main CTRL (ESP32-S3-Touch-LCD-5B/include/config/ota_config.h):
* releases of THIS repo on Gitea, manifest signed with the shared project key, * releases of THIS repo on Gitea, manifest signed with the shared project key,
* target string "patrol-b" so an A image is never accepted here. * target string "patrol-b" so an A image is never accepted here.
* See wiki/pages/controller-b-ota.md. * See wiki/pages/controller-b-ota.md.
@@ -95,7 +95,7 @@ static const char OTA_CA_PEM[] =
"sI1ANRYvqSFC2X1VRZfDg+wD6E21BccmifG4yWc=\n" "sI1ANRYvqSFC2X1VRZfDg+wD6E21BccmifG4yWc=\n"
"-----END CERTIFICATE-----\n"; "-----END CERTIFICATE-----\n";
// Firmware signing public key (ECDSA P-256), same key as Controller A. // Firmware signing public key (ECDSA P-256), same key as Main CTRL.
static const char OTA_SIGNING_PUBKEY_PEM[] = static const char OTA_SIGNING_PUBKEY_PEM[] =
"-----BEGIN PUBLIC KEY-----\n" "-----BEGIN PUBLIC KEY-----\n"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF\n" "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF\n"
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Serial console (Controller B) - line reader + command chain. * Serial console (Inst. Cluster) - line reader + command chain.
* *
* Commands live in their modules (LinkPeer, Ota); this only splits lines and * Commands live in their modules (LinkPeer, Ota); this only splits lines and
* asks each handler in turn. `help` lists them. * asks each handler in turn. `help` lists them.
+3 -3
View File
@@ -1,7 +1,7 @@
/** /**
* Debug Monitor Module for ESP32-S3-LCD-1.3 (Controller B) * Debug Monitor Module for ESP32-S3-LCD-1.3 (Inst. Cluster)
* *
* Synchronizes LVGL performance and memory monitor visibility with Controller A. * Synchronizes LVGL performance and memory monitor visibility with Main CTRL.
* Monitors are shown/hidden based on the debug_enabled flag received via UART. * Monitors are shown/hidden based on the debug_enabled flag received via UART.
*/ */
@@ -23,7 +23,7 @@ void init();
* @brief Set debug monitor visibility * @brief Set debug monitor visibility
* *
* Controls the visibility of LVGL's built-in performance and memory monitors. * Controls the visibility of LVGL's built-in performance and memory monitors.
* This should be called when receiving packets from Controller A to sync * This should be called when receiving packets from Main CTRL to sync
* with the debug_enabled flag. * with the debug_enabled flag.
* *
* @param enabled True to show monitors, false to hide them * @param enabled True to show monitors, false to hide them
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* ESP-NOW Receiver Module (Controller B) * ESP-NOW Receiver Module (Inst. Cluster)
* *
* Wireless leg of the A -> B link. Frames are byte-identical to the UART ones * Wireless leg of the A -> B link. Frames are byte-identical to the UART ones
* and are handed to UARTReceiver::processFrame(), which dedupes on packet_id. * and are handed to UARTReceiver::processFrame(), which dedupes on packet_id.
+2 -2
View File
@@ -1,7 +1,7 @@
/** /**
* Gauge Outputs Module (Controller B) * Gauge Outputs Module (Inst. Cluster)
* *
* Drives the Nissan Patrol cluster from the data Controller A sends: * Drives the Nissan Patrol cluster from the data Main CTRL sends:
* - tachometer: variable-frequency square wave on IO7 (LEDC timer 1) * - tachometer: variable-frequency square wave on IO7 (LEDC timer 1)
* - coolant gauge: fixed-frequency PWM with variable duty on IO8 (LEDC timer 2) * - coolant gauge: fixed-frequency PWM with variable duty on IO8 (LEDC timer 2)
* *
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Link Peer Module (Controller B) - the maintenance side of the link to A. * Link Peer Module (Inst. Cluster) - the maintenance side of the link to A.
* *
* The data path (DATA/CONFIG frames) is UARTReceiver's. This module owns * The data path (DATA/CONFIG frames) is UARTReceiver's. This module owns
* everything else on the link, see wiki/pages/controller-b-ota.md: * everything else on the link, see wiki/pages/controller-b-ota.md:
+2 -2
View File
@@ -1,6 +1,6 @@
/** /**
* ota_update.h - Controller B pulls its own firmware from this repo's Gitea * ota_update.h - Inst. Cluster pulls its own firmware from this repo's Gitea
* releases. Port of Controller A's module (ESP32-S3-Touch-LCD-5B/src/modules/ * releases. Port of Main CTRL's module (ESP32-S3-Touch-LCD-5B/src/modules/
* ota_update.cpp), see wiki/pages/controller-b-ota.md. * ota_update.cpp), see wiki/pages/controller-b-ota.md.
* *
* Triggered by A (OTA_CMD inside a SECURE frame, behind A's parking gate and * Triggered by A (OTA_CMD inside a SECURE frame, behind A's parking gate and
+2 -2
View File
@@ -1,7 +1,7 @@
/** /**
* Link Receiver Module (Controller B) * Link Receiver Module (Inst. Cluster)
* *
* Receives v2 frames from Controller A on two transports: * Receives v2 frames from Main CTRL on two transports:
* - UART1 (byte stream, framed here with a state machine) * - UART1 (byte stream, framed here with a state machine)
* - ESP-NOW (whole frames, delivered by EspNowReceiver) * - ESP-NOW (whole frames, delivered by EspNowReceiver)
* Both feed processFrame(). DATA frames are deduplicated on packet_id so a frame * Both feed processFrame(). DATA frames are deduplicated on packet_id so a frame
+11 -19
View File
@@ -1,8 +1,8 @@
/** /**
* automotive_data.h * automotive_data.h
* *
* Shared wire contract between Controller A (ESP32-S3-Touch-LCD-5B) and * Shared wire contract between Main CTRL (ESP32-S3-Touch-LCD-5B) and
* Controller B (ESP32-S3-LCD-1.3). * Inst. Cluster (ESP32-S3-LCD-1.3).
* *
* THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS. Copy it across whenever it * THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS. Copy it across whenever it
* changes and bump PACKET_VERSION; B rejects frames with any other version. * changes and bump PACKET_VERSION; B rejects frames with any other version.
@@ -45,8 +45,8 @@
// (B hops until it hears A, then locks) // (B hops until it hears A, then locks)
// NOTE: UART pin assignments are controller-specific: // NOTE: UART pin assignments are controller-specific:
// - Controller A (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B) // - Main CTRL (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B)
// - Controller B (1.3): platformio.ini (RX IO1) // - Inst. Cluster (1.3): platformio.ini (RX IO1)
// ============================================================================ // ============================================================================
// FRAME FORMAT (identical on UART and ESP-NOW) // FRAME FORMAT (identical on UART and ESP-NOW)
@@ -90,7 +90,7 @@ typedef enum {
LEVER_UNKNOWN = 0xFF LEVER_UNKNOWN = 0xFF
} gear_lever_t; } gear_lever_t;
// Controller A's internal gear enum (CAN decode helpers below use it). Not on // Main CTRL's internal gear enum (CAN decode helpers below use it). Not on
// the wire any more - B never sees it. // the wire any more - B never sees it.
typedef enum { typedef enum {
GEAR_PARK = 0, GEAR_PARK = 0,
@@ -216,7 +216,7 @@ static inline void link_config_defaults(link_config_t* c) {
} }
// ============================================================================ // ============================================================================
// LINK MAINTENANCE FRAMES (2026-09-27) - Controller B firmware updates // LINK MAINTENANCE FRAMES (2026-09-27) - Inst. Cluster firmware updates
// ============================================================================ // ============================================================================
// //
// B pulls its own signed release over Wi-Fi; A only hands it the credentials // B pulls its own signed release over Wi-Fi; A only hands it the credentials
@@ -241,7 +241,7 @@ typedef struct __attribute__((packed)) {
} link_pair_t; // 42 bytes } link_pair_t; // 42 bytes
// --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ---------- // --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ----------
// ota_phase mirrors Controller A's Ota::phase_t so one UI renders both. // ota_phase mirrors Main CTRL's Ota::phase_t so one UI renders both.
#define LINK_OTA_IDLE 0 #define LINK_OTA_IDLE 0
#define LINK_OTA_CHECKING 1 #define LINK_OTA_CHECKING 1
#define LINK_OTA_UP_TO_DATE 2 #define LINK_OTA_UP_TO_DATE 2
@@ -756,7 +756,7 @@ static inline const char* gear_to_string(gear_position_t gear) {
* @return Pointer to buffer * @return Pointer to buffer
*/ */
static inline char* format_temperature(int16_t temp_x10, char* buffer) { static inline char* format_temperature(int16_t temp_x10, char* buffer) {
// Plain "C": Controller B's UI font has no degree-sign glyph. // Plain "C": Inst. Cluster's UI font has no degree-sign glyph.
sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10)); sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10));
return buffer; return buffer;
} }
@@ -772,16 +772,8 @@ static inline char* format_voltage(uint16_t voltage_x100, char* buffer) {
return buffer; return buffer;
} }
// ============================================================================ // No default / test values: a field is only ever filled from a CAN frame, and
// DEFAULT/TEST VALUES // its VALID_FLAG_* bit says so. Removed 2026-09-28 - the bench defaults
// ============================================================================ // (89 / 85 degC, 12.45 V) looked like real readings on Inst. Cluster.
// Default values for testing (before CAN data is available)
#define DEFAULT_GEAR_LEVER LEVER_PARK
#define DEFAULT_GEARBOX_TEMP 850 // 85.0°C
#define DEFAULT_ENGINE_OIL_TEMP 920 // 92.0°C
#define DEFAULT_COOLANT_TEMP 890 // 89.0°C
#define DEFAULT_BATTERY_VOLTAGE 1245 // 12.45V
#define DEFAULT_ALERTS 0x0000 // No alerts
#endif // _AUTOMOTIVE_DATA_H #endif // _AUTOMOTIVE_DATA_H
+1 -1
View File
@@ -5,7 +5,7 @@
* *
* payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner) * payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner)
* *
* Both cores ship mbedtls (2.28 on Controller B's IDF 4.4, 3.x on Controller * Both cores ship mbedtls (2.28 on Inst. Cluster's IDF 4.4, 3.x on Controller
* A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs. * A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs.
*/ */
+5 -5
View File
@@ -1,7 +1,7 @@
/** /**
* ESP32-S3-LCD-1.3 - Controller B * ESP32-S3-LCD-1.3 - Inst. Cluster
* *
* Receives the v2 link from Controller A on UART1 and ESP-NOW, shows the data * Receives the v2 link from Main CTRL on UART1 and ESP-NOW, shows the data
* on the 1.3" round display, and drives the Nissan Patrol cluster's tachometer * on the 1.3" round display, and drives the Nissan Patrol cluster's tachometer
* and coolant gauge from it (GaugeOutputs, IO7 / IO8). * and coolant gauge from it (GaugeOutputs, IO7 / IO8).
*/ */
@@ -50,7 +50,7 @@ void setup() {
Serial.println("[BOOT] Serial communication ready!"); Serial.println("[BOOT] Serial communication ready!");
Serial.println("\n\n================================="); Serial.println("\n\n=================================");
Serial.println("ESP32-S3-LCD-1.3 - Controller B"); Serial.println("ESP32-S3-LCD-1.3 - Inst. Cluster");
Serial.printf("Firmware %s | Link protocol v%u | UART + ESP-NOW | gauge outputs\n", FW_VERSION, PACKET_VERSION); Serial.printf("Firmware %s | Link protocol v%u | UART + ESP-NOW | gauge outputs\n", FW_VERSION, PACKET_VERSION);
Serial.println("=================================\n"); Serial.println("=================================\n");
@@ -151,9 +151,9 @@ void loop() {
last_connection_check = millis(); last_connection_check = millis();
bool is_connected = UARTReceiver::isConnected(LINK_TIMEOUT_MS); bool is_connected = UARTReceiver::isConnected(LINK_TIMEOUT_MS);
if (is_connected && !was_connected) { if (is_connected && !was_connected) {
Serial.println("[Link] Connection ESTABLISHED with Controller A"); Serial.println("[Link] Connection ESTABLISHED with Main CTRL");
} else if (!is_connected && was_connected) { } else if (!is_connected && was_connected) {
Serial.println("[Link] Connection LOST - no data from Controller A"); Serial.println("[Link] Connection LOST - no data from Main CTRL");
} }
was_connected = is_connected; was_connected = is_connected;
} }
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Serial console implementation (Controller B) * Serial console implementation (Inst. Cluster)
*/ */
#include "modules/console.h" #include "modules/console.h"
+2 -2
View File
@@ -2,7 +2,7 @@
* Debug Monitor Module Implementation * Debug Monitor Module Implementation
* *
* Controls LVGL performance and memory monitor visibility at runtime * Controls LVGL performance and memory monitor visibility at runtime
* based on debug_enabled flag from Controller A. * based on debug_enabled flag from Main CTRL.
*/ */
#include "modules/debug_monitor.h" #include "modules/debug_monitor.h"
@@ -28,7 +28,7 @@ void init() {
g_initialized = true; g_initialized = true;
Serial.println("[DebugMonitor] Debug monitors are VISIBLE (default state)"); Serial.println("[DebugMonitor] Debug monitors are VISIBLE (default state)");
Serial.println("[DebugMonitor] Waiting for debug_enabled flag from Controller A..."); Serial.println("[DebugMonitor] Waiting for debug_enabled flag from Main CTRL...");
} }
static bool g_wanted_visible = true; static bool g_wanted_visible = true;
+1 -1
View File
@@ -27,7 +27,7 @@ void update();
/** /**
* LVGL lock. lv_timer_handler() runs in lvglTask on Core 1 at priority 2 and * LVGL lock. lv_timer_handler() runs in lvglTask on Core 1 at priority 2 and
* can preempt loop() mid-call; every lv_* call outside that task must hold * can preempt loop() mid-call; every lv_* call outside that task must hold
* this (recursive) mutex - the same rule as Controller A's lvgl_port_lock(). * this (recursive) mutex - the same rule as Main CTRL's lvgl_port_lock().
* @param timeout_ms <0 waits forever * @param timeout_ms <0 waits forever
* @return true if acquired * @return true if acquired
*/ */
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* ESP-NOW Receiver Module Implementation (Controller B) * ESP-NOW Receiver Module Implementation (Inst. Cluster)
*/ */
#include "modules/espnow_receiver.h" #include "modules/espnow_receiver.h"
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Gauge Outputs Module Implementation (Controller B) * Gauge Outputs Module Implementation (Inst. Cluster)
* *
* LEDC channel plan (Arduino-ESP32 2.x: timer = channel / 2): * LEDC channel plan (Arduino-ESP32 2.x: timer = channel / 2):
* channel 1 -> timer 0 : LovyanGFX backlight (display_init.cpp, 44.1 kHz) * channel 1 -> timer 0 : LovyanGFX backlight (display_init.cpp, 44.1 kHz)
+294 -84
View File
@@ -1,46 +1,104 @@
/* /*
* Gauge Screen implementation. See gauge_screen.h. * Gauge Screen implementation. See gauge_screen.h.
*
* Layout for the ROUND 240x240 panel (2026-09-28, user's design):
*
* - two ARC GAUGES on the rim, no digits: coolant on the LEFT (compass 230°
* at the bottom-left up to 320° at the top-left), gearbox oil on the RIGHT
* (compass 140° bottom-right up to 40° top-right). Each arc is a blue ->
* red gradient (cold at the bottom, hot at the top) with a white needle.
* LVGL angles are compass - 90: coolant 140..230, gearbox 310..410 (=50).
* - the gauge's icon sits just past the hot end, upper-left / upper-right;
* it switches to its red variant while that alert is on.
* - outer ring, 6 px, at the very rim: dim normally, RED BLINKING while any
* red alert is on, amber while the gearbox asks for cooling.
* - gear letter 110 px in the centre, battery [icon][12.4] at the bottom.
* - tell-tales: Wi-Fi at 9 o'clock (green only while joined for an update),
* red "!" at 3 o'clock when the link to A is lost.
*
* Geometry (centre 120,120): ring r 114-120, arc band r 100-110, needle
* r 92-113, icons centred at r 66, gear ink roughly y 94-174, battery row
* y 176-220. Everything placed absolutely inside the circle.
*/ */
#include "modules/gauge_screen.h" #include "modules/gauge_screen.h"
#include "modules/display_init.h" #include "modules/display_init.h"
#include "assets/assets.h" #include "assets/assets.h"
#include <lvgl.h> #include <lvgl.h>
#include <WiFi.h>
#include <string.h> #include <string.h>
#include <math.h>
namespace GaugeScreen { namespace GaugeScreen {
// A shift pulse is shown for at least this long, so a fast shift still blinks
#define SHIFT_PULSE_MIN_MS 600 #define SHIFT_PULSE_MIN_MS 600
#define BLINK_MS 500
static const lv_color_t COL_TEXT = lv_color_hex(0xE8EDF2);
static const lv_color_t COL_MUTED = lv_color_hex(0x3A4450);
static const lv_color_t COL_ALERT = lv_color_hex(0xFF3B30); static const lv_color_t COL_ALERT = lv_color_hex(0xFF3B30);
static const lv_color_t COL_ALERT2 = lv_color_hex(0x7A1410); // blink low phase
static const lv_color_t COL_AMBER = lv_color_hex(0xF5A524);
static const lv_color_t COL_RING = lv_color_hex(0x2A323C);
static const lv_color_t COL_OK = lv_color_hex(0x3DD68C);
static const lv_color_t COL_COLD = lv_color_hex(0x2F80ED); // arc, cold end
static const lv_color_t COL_MID = lv_color_hex(0xC8D0D8); // arc, middle
static const lv_color_t COL_HOT = lv_color_hex(0xFF3B30); // arc, hot end
// ---- one value cell: label + normal/red icon pair -------------------------- // Arc geometry / scales
struct Cell { #define ARC_DIAMETER 220 // outer radius 110
#define ARC_WIDTH 10 // band r 100..110
#define NEEDLE_R0 92
#define NEEDLE_R1 113
#define ICON_R 66
#define COOL_A0 140 // LVGL degrees, cold end (bottom-left)
#define COOL_A1 230 // hot end (top-left)
#define COOL_T_MIN 50 // degC at the cold end
#define COOL_T_MAX 120 // degC at the hot end
#define GB_A0 50 // cold end (bottom-right)
#define GB_A1 -50 // hot end (top-right) == 310
#define GB_T_MIN 40
#define GB_T_MAX 150
// ---- an arc gauge -------------------------------------------------------------
struct Gauge {
lv_obj_t* needle;
lv_point_t pts[2];
int last_angle; // LVGL degrees, -1000 = hidden
lv_obj_t* icon;
lv_obj_t* icon_red;
int8_t shown; // -1 none, 0 normal, 1 red
};
struct Cell { // battery: icon + digits
lv_obj_t* cont; lv_obj_t* cont;
lv_obj_t* lbl; lv_obj_t* lbl;
lv_obj_t* icon; lv_obj_t* icon;
lv_obj_t* icon_red; lv_obj_t* icon_red;
int8_t shown; // -1 none, 0 normal icon, 1 red icon int8_t shown;
bool red;
}; };
static lv_obj_t* g_screen = NULL; static lv_obj_t* g_screen = NULL;
static lv_obj_t* g_notice = NULL; // on lv_layer_top(): update progress line static lv_obj_t* g_ring = NULL;
static Cell g_coolant = {0}; static lv_obj_t* g_wifi_tt = NULL;
static Cell g_gearbox = {0}; static lv_obj_t* g_link_tt = NULL;
static lv_obj_t* g_notice = NULL;
static Gauge g_coolant = {0};
static Gauge g_gearbox = {0};
static Cell g_battery = {0}; static Cell g_battery = {0};
static lv_obj_t* g_gear_lbl = NULL; static lv_obj_t* g_gear_lbl = NULL;
static lv_color_t g_gear_col_default;
static bool g_gear_red = false; static bool g_gear_red = false;
static lv_color_t g_ring_col;
static bool g_wifi_bright = false;
static bool g_link_lost_shown = false;
// gear pulse
static lv_anim_t g_gear_anim; static lv_anim_t g_gear_anim;
static bool g_gear_pulsing = false; static bool g_gear_pulsing = false;
static uint32_t g_gear_pulse_started = 0; static uint32_t g_gear_pulse_started = 0;
// ---- helpers --------------------------------------------------------------- // ---- helpers ---------------------------------------------------------------
/** lv_label_set_text() only when the text differs. */
static void setText(lv_obj_t* lbl, const char* text) { static void setText(lv_obj_t* lbl, const char* text) {
if (lbl == NULL) return; if (lbl == NULL) return;
const char* cur = lv_label_get_text(lbl); const char* cur = lv_label_get_text(lbl);
@@ -48,60 +106,154 @@ static void setText(lv_obj_t* lbl, const char* text) {
lv_label_set_text(lbl, text); lv_label_set_text(lbl, text);
} }
/** Show the normal icon, the red icon, or neither - touching objects only on change. */ static void setTextColour(lv_obj_t* lbl, lv_color_t c) {
static void setIcon(Cell& c, bool visible, bool red) { if (lv_color_to32(lv_obj_get_style_text_color(lbl, 0)) != lv_color_to32(c))
lv_obj_set_style_text_color(lbl, c, 0);
}
static void showIconPair(lv_obj_t* icon, lv_obj_t* icon_red, int8_t& shown, bool visible, bool red) {
int8_t want = !visible ? -1 : (red ? 1 : 0); int8_t want = !visible ? -1 : (red ? 1 : 0);
if (want == c.shown) return; if (want == shown) return;
c.shown = want; shown = want;
if (want == 0) lv_obj_clear_flag(c.icon, LV_OBJ_FLAG_HIDDEN); else lv_obj_add_flag(c.icon, LV_OBJ_FLAG_HIDDEN); if (want == 0) lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); else lv_obj_add_flag(icon, LV_OBJ_FLAG_HIDDEN);
if (want == 1) lv_obj_clear_flag(c.icon_red, LV_OBJ_FLAG_HIDDEN); else lv_obj_add_flag(c.icon_red, LV_OBJ_FLAG_HIDDEN); if (want == 1) lv_obj_clear_flag(icon_red, LV_OBJ_FLAG_HIDDEN); else lv_obj_add_flag(icon_red, LV_OBJ_FLAG_HIDDEN);
}
static lv_obj_t* makeContainer(lv_obj_t* parent, lv_coord_t w, lv_coord_t h, lv_flex_flow_t flow,
lv_flex_align_t main_place, lv_flex_align_t cross_place) {
lv_obj_t* o = lv_obj_create(parent);
lv_obj_remove_style_all(o);
lv_obj_set_size(o, w, h);
lv_obj_set_flex_flow(o, flow);
lv_obj_set_flex_align(o, main_place, cross_place, cross_place);
lv_obj_clear_flag(o, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
return o;
}
static lv_obj_t* makeValueLabel(lv_obj_t* parent) {
lv_obj_t* l = lv_label_create(parent);
lv_label_set_text(l, "---");
lv_obj_set_style_text_font(l, &ui_font_UbuntuLight_35, 0);
return l;
} }
static lv_obj_t* makeIcon(lv_obj_t* parent, const lv_img_dsc_t* src) { static lv_obj_t* makeIcon(lv_obj_t* parent, const lv_img_dsc_t* src) {
lv_obj_t* i = lv_img_create(parent); lv_obj_t* i = lv_img_create(parent);
lv_img_set_src(i, src); lv_img_set_src(i, src);
lv_obj_add_flag(i, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(i, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(i, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(i, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
return i; return i;
} }
/** Blue -> neutral -> red along t in [0,1]. */
static lv_color_t arcColour(float t) {
if (t < 0.5f) return lv_color_mix(COL_MID, COL_COLD, (uint8_t)(t * 2 * 255));
return lv_color_mix(COL_HOT, COL_MID, (uint8_t)((t - 0.5f) * 2 * 255));
}
/** One static arc segment on the rim band. Angles in LVGL degrees, may exceed 360. */
static void makeArcSegment(lv_obj_t* parent, int a0, int a1, lv_color_t col) {
lv_obj_t* a = lv_arc_create(parent);
lv_obj_remove_style(a, NULL, LV_PART_KNOB);
lv_obj_set_style_arc_opa(a, LV_OPA_TRANSP, LV_PART_INDICATOR);
lv_obj_set_style_arc_width(a, ARC_WIDTH, LV_PART_MAIN);
lv_obj_set_style_arc_color(a, col, LV_PART_MAIN);
lv_obj_set_style_arc_rounded(a, false, LV_PART_MAIN);
lv_obj_set_style_bg_opa(a, LV_OPA_TRANSP, 0);
lv_obj_set_size(a, ARC_DIAMETER, ARC_DIAMETER);
lv_obj_center(a);
lv_arc_set_rotation(a, 0);
lv_arc_set_bg_angles(a, (uint16_t)((a0 % 360 + 360) % 360), (uint16_t)((a1 % 360 + 360) % 360));
lv_obj_clear_flag(a, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
}
/** /**
* A cell: 112x80, column. icon_above=false puts the value on top and the icon * The gradient band from angle a_cold to a_hot (either direction), in ~10°
* under it (top row); icon_above=true puts the icon on top (bottom row), as * segments overlapping by 1° so no seams show.
* the original screen did.
*/ */
static void makeCell(Cell& c, lv_obj_t* parent, const lv_img_dsc_t* icon, const lv_img_dsc_t* icon_red, static void makeBand(lv_obj_t* parent, int a_cold, int a_hot) {
lv_flex_align_t cross, bool icon_above) { int span = a_hot - a_cold; // signed
c.cont = makeContainer(parent, 112, icon_above ? 85 : 80, LV_FLEX_FLOW_COLUMN, int n = abs(span) / 10;
icon_above ? LV_FLEX_ALIGN_SPACE_BETWEEN : LV_FLEX_ALIGN_START, cross); int dir = span > 0 ? 1 : -1;
if (icon_above) { for (int k = 0; k < n; k++) {
c.icon_red = makeIcon(c.cont, icon_red); int s = a_cold + dir * 10 * k;
c.icon = makeIcon(c.cont, icon); int e = s + dir * 10;
c.lbl = makeValueLabel(c.cont); if (k < n - 1) e += dir; // overlap the next segment by 1°
} else { int lo = dir > 0 ? s : e, hi = dir > 0 ? e : s;
c.lbl = makeValueLabel(c.cont); makeArcSegment(parent, lo, hi, arcColour((k + 0.5f) / n));
c.icon_red = makeIcon(c.cont, icon_red);
c.icon = makeIcon(c.cont, icon);
} }
}
static void makeNeedle(Gauge& g, lv_obj_t* parent) {
g.needle = lv_line_create(parent);
lv_obj_set_pos(g.needle, 0, 0);
lv_obj_set_size(g.needle, 240, 240);
lv_obj_set_style_line_width(g.needle, 3, 0);
lv_obj_set_style_line_color(g.needle, lv_color_white(), 0);
lv_obj_set_style_line_rounded(g.needle, true, 0);
lv_obj_clear_flag(g.needle, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
g.pts[0].x = g.pts[1].x = 120;
g.pts[0].y = g.pts[1].y = 120;
lv_line_set_points(g.needle, g.pts, 2);
lv_obj_add_flag(g.needle, LV_OBJ_FLAG_HIDDEN);
g.last_angle = -1000;
}
/** Point the needle at an LVGL angle (degrees), or hide it (angle == -1000). */
static void setNeedle(Gauge& g, int angle) {
if (angle == g.last_angle) return;
g.last_angle = angle;
if (angle == -1000) { lv_obj_add_flag(g.needle, LV_OBJ_FLAG_HIDDEN); return; }
float rad = angle * (float)M_PI / 180.0f;
float c = cosf(rad), s = sinf(rad);
g.pts[0].x = (lv_coord_t)lroundf(120 + NEEDLE_R0 * c);
g.pts[0].y = (lv_coord_t)lroundf(120 + NEEDLE_R0 * s);
g.pts[1].x = (lv_coord_t)lroundf(120 + NEEDLE_R1 * c);
g.pts[1].y = (lv_coord_t)lroundf(120 + NEEDLE_R1 * s);
lv_line_set_points(g.needle, g.pts, 2);
lv_obj_clear_flag(g.needle, LV_OBJ_FLAG_HIDDEN);
}
/** Temperature (0.1 degC) -> LVGL angle on a gauge running a_cold..a_hot over t_min..t_max. */
static int tempAngle(int16_t t_x10, int t_min, int t_max, int a_cold, int a_hot) {
float t = (t_x10 / 10.0f - t_min) / (float)(t_max - t_min);
if (t < 0) t = 0;
if (t > 1) t = 1;
return (int)lroundf(a_cold + (a_hot - a_cold) * t);
}
static void placeIcon(lv_obj_t* icon, int angle) {
float rad = angle * (float)M_PI / 180.0f;
lv_coord_t cx = (lv_coord_t)lroundf(120 + ICON_R * cosf(rad));
lv_coord_t cy = (lv_coord_t)lroundf(120 + ICON_R * sinf(rad));
lv_obj_set_pos(icon, cx - 25, cy - 22); // icons are 50x44
}
static void makeGauge(Gauge& g, lv_obj_t* parent, int a_cold, int a_hot, int icon_angle,
const lv_img_dsc_t* icon, const lv_img_dsc_t* icon_red) {
makeBand(parent, a_cold, a_hot);
makeNeedle(g, parent);
g.icon_red = makeIcon(parent, icon_red);
g.icon = makeIcon(parent, icon);
placeIcon(g.icon, icon_angle);
placeIcon(g.icon_red, icon_angle);
g.shown = -1;
}
static void setCellIcon(Cell& c, bool visible, bool red) {
showIconPair(c.icon, c.icon_red, c.shown, visible, red);
bool want_red = visible && red;
if (want_red != c.red) {
c.red = want_red;
setTextColour(c.lbl, want_red ? COL_ALERT : COL_TEXT);
}
}
static void makeBatteryCell(Cell& c, lv_obj_t* parent) {
c.cont = lv_obj_create(parent);
lv_obj_remove_style_all(c.cont);
lv_obj_set_pos(c.cont, 55, 176);
lv_obj_set_size(c.cont, 130, 44);
lv_obj_set_flex_flow(c.cont, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(c.cont, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(c.cont, 8, 0);
lv_obj_clear_flag(c.cont, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* icons = lv_obj_create(c.cont);
lv_obj_remove_style_all(icons);
lv_obj_set_size(icons, 50, 44);
lv_obj_clear_flag(icons, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
c.icon_red = makeIcon(icons, &ui_img_batteryvoltagered_png);
c.icon = makeIcon(icons, &ui_img_batteryvoltage_png);
c.lbl = lv_label_create(c.cont);
lv_label_set_text(c.lbl, "--");
lv_obj_set_style_text_font(c.lbl, &ui_font_UbuntuLight_35, 0);
lv_obj_set_style_text_color(c.lbl, COL_TEXT, 0);
c.shown = -1; c.shown = -1;
c.red = false;
} }
// ---- gear pulse -------------------------------------------------------------- // ---- gear pulse --------------------------------------------------------------
@@ -134,14 +286,9 @@ static void stopGearPulse() {
static void setGearColour(bool red) { static void setGearColour(bool red) {
if (red == g_gear_red) return; if (red == g_gear_red) return;
g_gear_red = red; g_gear_red = red;
lv_obj_set_style_text_color(g_gear_lbl, red ? COL_ALERT : g_gear_col_default, 0); lv_obj_set_style_text_color(g_gear_lbl, red ? COL_ALERT : COL_TEXT, 0);
} }
/**
* Gear label from lever + target/engaged nibbles. While target != engaged the
* TARGET digit is shown and the label pulses; once they agree it goes solid on
* the engaged gear. Red on the gear-mismatch alert.
*/
static void updateGear(const automotive_data_t& d, bool valid) { static void updateGear(const automotive_data_t& d, bool valid) {
if (!valid) { if (!valid) {
stopGearPulse(); stopGearPulse();
@@ -170,6 +317,40 @@ static void updateGear(const automotive_data_t& d, bool valid) {
setGearColour(mismatch); setGearColour(mismatch);
} }
// ---- ring + tell-tales -------------------------------------------------------
static void setRing(lv_color_t c) {
if (lv_color_to32(c) == lv_color_to32(g_ring_col)) return;
g_ring_col = c;
lv_obj_set_style_border_color(g_ring, c, 0);
}
static void updateRing(uint16_t alerts, bool alerts_valid) {
if (!alerts_valid) { setRing(COL_RING); return; }
if (alerts & ALERTS_RED) {
bool hi = (millis() / BLINK_MS) & 1;
setRing(hi ? COL_ALERT : COL_ALERT2);
} else if (alerts & ALERTS_AMBER) {
setRing(COL_AMBER);
} else {
setRing(COL_RING);
}
}
static void updateTellTales(bool link_ok) {
bool joined = WiFi.status() == WL_CONNECTED;
if (joined != g_wifi_bright) {
g_wifi_bright = joined;
lv_obj_set_style_text_color(g_wifi_tt, joined ? COL_OK : COL_MUTED, 0);
}
bool lost = !link_ok;
if (lost != g_link_lost_shown) {
g_link_lost_shown = lost;
if (lost) lv_obj_clear_flag(g_link_tt, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_link_tt, LV_OBJ_FLAG_HIDDEN);
}
}
// ---- public ----------------------------------------------------------------- // ---- public -----------------------------------------------------------------
void init() { void init() {
@@ -178,26 +359,49 @@ void init() {
g_screen = lv_obj_create(NULL); g_screen = lv_obj_create(NULL);
lv_obj_clear_flag(g_screen, LV_OBJ_FLAG_SCROLLABLE); lv_obj_clear_flag(g_screen, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_flex_flow(g_screen, LV_FLEX_FLOW_COLUMN); lv_obj_set_style_bg_color(g_screen, lv_color_black(), 0);
lv_obj_set_flex_align(g_screen, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
// top row: coolant (left, contents left-aligned) | gearbox oil (right, contents right-aligned) // Warning-lamp ring at the rim
lv_obj_t* top = makeContainer(g_screen, 230, 80, LV_FLEX_FLOW_ROW, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_START); g_ring = lv_obj_create(g_screen);
makeCell(g_coolant, top, &ui_img_enginetemp_png, &ui_img_enginetempred_png, LV_FLEX_ALIGN_START, false); lv_obj_remove_style_all(g_ring);
makeCell(g_gearbox, top, &ui_img_gearboxoiltemp_png, &ui_img_gearboxoiltempred_png, LV_FLEX_ALIGN_END, false); lv_obj_set_pos(g_ring, 0, 0);
lv_obj_set_size(g_ring, 240, 240);
lv_obj_set_style_radius(g_ring, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_border_width(g_ring, 6, 0);
lv_obj_set_style_border_color(g_ring, COL_RING, 0);
lv_obj_set_style_border_opa(g_ring, LV_OPA_COVER, 0);
lv_obj_clear_flag(g_ring, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
g_ring_col = COL_RING;
// middle: the gear // Arc gauges: coolant left (140 -> 230), gearbox right (50 -> -50 i.e. 310); icons past the hot ends
lv_obj_t* mid = makeContainer(g_screen, 115, 100, LV_FLEX_FLOW_ROW, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); makeGauge(g_coolant, g_screen, COOL_A0, COOL_A1, 245, &ui_img_enginetemp_png, &ui_img_enginetempred_png);
g_gear_lbl = lv_label_create(mid); makeGauge(g_gearbox, g_screen, GB_A0, GB_A1, 295, &ui_img_gearboxoiltemp_png, &ui_img_gearboxoiltempred_png);
// Centre: the gear
g_gear_lbl = lv_label_create(g_screen);
lv_label_set_text(g_gear_lbl, "?"); lv_label_set_text(g_gear_lbl, "?");
lv_obj_set_style_text_font(g_gear_lbl, &ui_font_UbuntuBold_110, 0); lv_obj_set_style_text_font(g_gear_lbl, &ui_font_UbuntuBold_110, 0);
g_gear_col_default = lv_obj_get_style_text_color(g_gear_lbl, 0); lv_obj_set_style_text_color(g_gear_lbl, COL_TEXT, 0);
lv_obj_align(g_gear_lbl, LV_ALIGN_CENTER, 0, 20);
// bottom row: battery, centred (the engine-oil cell that used to sit beside it is gone) // Bottom: battery [icon][value]
lv_obj_t* bottom = makeContainer(g_screen, 230, 85, LV_FLEX_FLOW_ROW, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END); makeBatteryCell(g_battery, g_screen);
makeCell(g_battery, bottom, &ui_img_batteryvoltage_png, &ui_img_batteryvoltagered_png, LV_FLEX_ALIGN_CENTER, true);
// Notice line for the updater: a dark pill low on the round panel, hidden until used. // Tell-tales at 9 and 3 o'clock
g_wifi_tt = lv_label_create(g_screen);
lv_label_set_text(g_wifi_tt, LV_SYMBOL_WIFI);
lv_obj_set_style_text_font(g_wifi_tt, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_wifi_tt, COL_MUTED, 0);
lv_obj_align(g_wifi_tt, LV_ALIGN_LEFT_MID, 24, 0);
g_link_tt = lv_label_create(g_screen);
lv_label_set_text(g_link_tt, LV_SYMBOL_WARNING);
lv_obj_set_style_text_font(g_link_tt, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_link_tt, COL_ALERT, 0);
lv_obj_align(g_link_tt, LV_ALIGN_RIGHT_MID, -24, 0);
lv_obj_add_flag(g_link_tt, LV_OBJ_FLAG_HIDDEN);
// Updater notice line, on the top layer
g_notice = lv_label_create(lv_layer_top()); g_notice = lv_label_create(lv_layer_top());
lv_obj_set_style_text_font(g_notice, &lv_font_montserrat_14, 0); lv_obj_set_style_text_font(g_notice, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_notice, lv_color_white(), 0); lv_obj_set_style_text_color(g_notice, lv_color_white(), 0);
@@ -211,7 +415,7 @@ void init() {
lv_scr_load(g_screen); lv_scr_load(g_screen);
DisplayInit::unlock(); DisplayInit::unlock();
Serial.println("[GaugeScreen] built (coolant, gearbox oil, gear, battery)"); Serial.println("[GaugeScreen] built (ring, coolant arc, gearbox arc, gear, battery, tell-tales)");
} }
void setNotice(const char* text) { void setNotice(const char* text) {
@@ -229,16 +433,19 @@ void setNotice(const char* text) {
void update(const automotive_data_t& d, bool link_ok) { void update(const automotive_data_t& d, bool link_ok) {
if (g_screen == NULL) return; if (g_screen == NULL) return;
if (!DisplayInit::lock(50)) return; // never stall the loop on a busy renderer if (!DisplayInit::lock(50)) return;
updateTellTales(link_ok);
if (!link_ok) { if (!link_ok) {
setText(g_coolant.lbl, "N/A"); setNeedle(g_coolant, -1000);
setText(g_gearbox.lbl, "N/A"); setNeedle(g_gearbox, -1000);
setText(g_battery.lbl, "N/A"); showIconPair(g_coolant.icon, g_coolant.icon_red, g_coolant.shown, true, false);
setIcon(g_coolant, false, false); showIconPair(g_gearbox.icon, g_gearbox.icon_red, g_gearbox.shown, true, false);
setIcon(g_gearbox, false, false); setText(g_battery.lbl, "--");
setIcon(g_battery, false, false); setCellIcon(g_battery, true, false);
updateGear(d, false); updateGear(d, false);
updateRing(0, false);
DisplayInit::unlock(); DisplayInit::unlock();
return; return;
} }
@@ -248,18 +455,21 @@ void update(const automotive_data_t& d, bool link_ok) {
uint16_t alerts = alerts_valid ? d.alerts : 0; uint16_t alerts = alerts_valid ? d.alerts : 0;
bool coolant_valid = (d.valid_flags & VALID_FLAG_COOLANT_TEMP) != 0; bool coolant_valid = (d.valid_flags & VALID_FLAG_COOLANT_TEMP) != 0;
setText(g_coolant.lbl, coolant_valid ? format_temperature(d.coolant_temp, buf) : "---"); setNeedle(g_coolant, coolant_valid ? tempAngle(d.coolant_temp, COOL_T_MIN, COOL_T_MAX, COOL_A0, COOL_A1) : -1000);
setIcon(g_coolant, coolant_valid, (alerts & ALERT_COOLANT_HOT) != 0); showIconPair(g_coolant.icon, g_coolant.icon_red, g_coolant.shown, true, (alerts & ALERT_COOLANT_HOT) != 0);
bool gearbox_valid = (d.valid_flags & VALID_FLAG_GEARBOX_TEMP) != 0; bool gearbox_valid = (d.valid_flags & VALID_FLAG_GEARBOX_TEMP) != 0;
setText(g_gearbox.lbl, gearbox_valid ? format_temperature(d.gearbox_oil_temp, buf) : "---"); setNeedle(g_gearbox, gearbox_valid ? tempAngle(d.gearbox_oil_temp, GB_T_MIN, GB_T_MAX, GB_A0, GB_A1) : -1000);
setIcon(g_gearbox, gearbox_valid, (alerts & (ALERT_GEARBOX_HOT | ALERT_GEARBOX_COOLING)) != 0); showIconPair(g_gearbox.icon, g_gearbox.icon_red, g_gearbox.shown, true,
(alerts & (ALERT_GEARBOX_HOT | ALERT_GEARBOX_COOLING)) != 0);
bool battery_valid = (d.valid_flags & VALID_FLAG_BATTERY_VOLT) != 0; bool battery_valid = (d.valid_flags & VALID_FLAG_BATTERY_VOLT) != 0;
setText(g_battery.lbl, battery_valid ? format_voltage(d.battery_voltage, buf) : "---"); if (battery_valid) snprintf(buf, sizeof(buf), "%d.%d", d.battery_voltage / 100, (d.battery_voltage % 100) / 10);
setIcon(g_battery, battery_valid, (alerts & ALERT_BATTERY_LOW) != 0); setText(g_battery.lbl, battery_valid ? buf : "--");
setCellIcon(g_battery, true, (alerts & ALERT_BATTERY_LOW) != 0);
updateGear(d, (d.valid_flags & VALID_FLAG_GEAR_POS) != 0); updateGear(d, (d.valid_flags & VALID_FLAG_GEAR_POS) != 0);
updateRing(alerts, alerts_valid);
DisplayInit::unlock(); DisplayInit::unlock();
} }
+3 -3
View File
@@ -1,7 +1,7 @@
/* /*
* Gauge Screen - the one screen Controller B shows. * Gauge Screen - the one screen Inst. Cluster shows.
* *
* Hand-coded LVGL (SquareLine Studio was retired 2026-09-27, as on Controller A). * Hand-coded LVGL (SquareLine Studio was retired 2026-09-27, as on Main CTRL).
* Built once at boot and never deleted. Layout on the 240x240 round panel: * Built once at boot and never deleted. Layout on the 240x240 round panel:
* *
* coolant temp gearbox oil temp (value above icon) * coolant temp gearbox oil temp (value above icon)
@@ -30,7 +30,7 @@ void init();
/** /**
* Refresh from the latest link data. Call at the packet rate (5 Hz) from loop(). * Refresh from the latest link data. Call at the packet rate (5 Hz) from loop().
* @param d latest DATA payload from Controller A * @param d latest DATA payload from Main CTRL
* @param link_ok false when the link is considered lost - shows N/A everywhere * @param link_ok false when the link is considered lost - shows N/A everywhere
*/ */
void update(const automotive_data_t& d, bool link_ok); void update(const automotive_data_t& d, bool link_ok);
+2 -2
View File
@@ -1,5 +1,5 @@
/** /**
* Link Peer Module Implementation (Controller B) * Link Peer Module Implementation (Inst. Cluster)
* *
* Threading: onRadioFrame() runs in the Wi-Fi task, onPairFrame() in the UART * Threading: onRadioFrame() runs in the Wi-Fi task, onPairFrame() in the UART
* task. Both only drop a copy into a one-slot mailbox; tick() (loop task) does * task. Both only drop a copy into a one-slot mailbox; tick() (loop task) does
@@ -17,7 +17,7 @@
namespace LinkPeer { namespace LinkPeer {
static const char* NVS_LINK = "linkpeer"; // key (32 B), amac (6 B) static const char* NVS_LINK = "linkpeer"; // key (32 B), amac (6 B)
static const char* NVS_WIFI = "wifi"; // ssid, pass - same layout as Controller A's static const char* NVS_WIFI = "wifi"; // ssid, pass - same layout as Main CTRL's
// ---- state (loop task only, except where noted) ---------------------------- // ---- state (loop task only, except where noted) ----------------------------
static bool g_paired = false; static bool g_paired = false;
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* ota_update.cpp (Controller B) - see ota_update.h. * ota_update.cpp (Inst. Cluster) - see ota_update.h.
* *
* Flow of an install: * Flow of an install:
* 1. gate: parked (link data), credentials present * 1. gate: parked (link data), credentials present
+1 -1
View File
@@ -1,5 +1,5 @@
/** /**
* Link Receiver Module Implementation (Controller B) * Link Receiver Module Implementation (Inst. Cluster)
*/ */
#include "modules/uart_receiver.h" #include "modules/uart_receiver.h"
+6 -6
View File
@@ -1,22 +1,22 @@
# Wiki Schema # Wiki Schema
This directory is a **personal knowledge wiki** for the ESP32-S3-LCD-1.3 project — Controller B, the slave/extension unit of the BMW M57N → Nissan Patrol swap display system. It is maintained by the LLM agent; the human curates sources and asks questions. Read this file before doing anything in `wiki/`. This directory is a **personal knowledge wiki** for the ESP32-S3-LCD-1.3 project — Inst. Cluster, the slave/extension unit of the BMW M57N → Nissan Patrol swap display system. It is maintained by the LLM agent; the human curates sources and asks questions. Read this file before doing anything in `wiki/`.
It is the sibling of the wiki in `../../ESP32-S3-Touch-LCD-5B/wiki/` (Controller A). The two repos are separate git repositories with separate remotes. **Never create or edit files outside this repo's directory.** Cross-references into the sibling wiki are plain text, not `[[wikilinks]]` (Obsidian vaults do not link across vaults) — write them as `(sibling: 5B wiki → page-name)`. It is the sibling of the wiki in `../../ESP32-S3-Touch-LCD-5B/wiki/` (Main CTRL). The two repos are separate git repositories with separate remotes. **Never create or edit files outside this repo's directory.** Cross-references into the sibling wiki are plain text, not `[[wikilinks]]` (Obsidian vaults do not link across vaults) — write them as `(sibling: 5B wiki → page-name)`.
## What this wiki is for ## What this wiki is for
Domain knowledge that is NOT derivable from the firmware repo: Domain knowledge that is NOT derivable from the firmware repo:
- Waveshare ESP32-S3-LCD-1.3 hardware: pinout, free GPIO, peripherals, power, quirks, gotchas - Waveshare ESP32-S3-LCD-1.3 hardware: pinout, free GPIO, peripherals, power, quirks, gotchas
- The link between Controller A and Controller B: physical layer, packet contract, timing, failure modes, and the wired + BLE redundancy design - The link between Main CTRL and Inst. Cluster: physical layer, packet contract, timing, failure modes, and the wired + BLE redundancy design
- Controller B's outputs into the Nissan Patrol: driving the cluster's RPM and coolant-temperature gauges, driver electronics, cluster behaviour - Inst. Cluster's outputs into the Nissan Patrol: driving the cluster's RPM and coolant-temperature gauges, driver electronics, cluster behaviour
- Design decisions and their rationale; what was tried and why it was rejected - Design decisions and their rationale; what was tried and why it was rejected
- Findings from datasheets, forum posts, Waveshare docs, bench measurements, scope traces - Findings from datasheets, forum posts, Waveshare docs, bench measurements, scope traces
What does NOT belong here: code structure, build commands, firmware implementation details. The repo (its root `CLAUDE.md` and `README.md`) is the source of truth for those. The wiki may *reference* firmware facts when they matter for domain reasoning (e.g. "firmware currently times out after 1 s without a packet"), always marked `(repo)`. What does NOT belong here: code structure, build commands, firmware implementation details. The repo (its root `CLAUDE.md` and `README.md`) is the source of truth for those. The wiki may *reference* firmware facts when they matter for domain reasoning (e.g. "firmware currently times out after 1 s without a packet"), always marked `(repo)`.
Division of labour with the sibling wiki: **CAN bus decoding, the BMW engine, the donor vehicle and the swap itself live in the 5B wiki.** This wiki only records what Controller B needs from that work (which signals it consumes, which packet fields carry them). Do not duplicate CAN ID tables here — point at the sibling. Division of labour with the sibling wiki: **CAN bus decoding, the BMW engine, the donor vehicle and the swap itself live in the 5B wiki.** This wiki only records what Inst. Cluster needs from that work (which signals it consumes, which packet fields carry them). Do not duplicate CAN ID tables here — point at the sibling.
## Layout ## Layout
@@ -46,7 +46,7 @@ wiki/
- `(verified)` — confirmed on real hardware / with a meter or scope by the user - `(verified)` — confirmed on real hardware / with a meter or scope by the user
- `(source: X)` — from an ingested source in `raw/` (summarised in `sources/`) - `(source: X)` — from an ingested source in `raw/` (summarised in `sources/`)
- `(repo)` — what the firmware currently does (not necessarily correct!) - `(repo)` — what the firmware currently does (not necessarily correct!)
- `(sibling: 5B wiki → page)` — established in the Controller A wiki; check there before relying on it - `(sibling: 5B wiki → page)` — established in the Main CTRL wiki; check there before relying on it
- `(unverified)` — LLM prior knowledge, forum lore, or a design proposal; treat as a hypothesis - `(unverified)` — LLM prior knowledge, forum lore, or a design proposal; treat as a hypothesis
- Contradictions between sources — including between the two repos' copies of the shared protocol header — get flagged inline with a `> [!warning]` callout, not silently resolved. - Contradictions between sources — including between the two repos' copies of the shared protocol header — get flagged inline with a `> [!warning]` callout, not silently resolved.
+2 -2
View File
@@ -9,13 +9,13 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
## Entities ## Entities
- [[esp32-s3-lcd-1-3]] — Waveshare 1.3" round-display board (Controller B): specs, the **verified 16-pin header pinout** (IO1–5, IO7–14 all free-function), GPIO budget (10 clean spares), CH343 console on UART0, BLE 5 - [[esp32-s3-lcd-1-3]] — Waveshare 1.3" round-display board (Inst. Cluster): specs, the **verified 16-pin header pinout** (IO1–5, IO7–14 all free-function), GPIO budget (10 clean spares), CH343 console on UART0, BLE 5
## Concepts ## Concepts
- [[controller-link]] — the A → B link, **protocol v2 (verified 2026-09-21)**: typed DATA/CONFIG frames on UART1 **and** ESP-NOW with dedupe, split gear fields, rpm, A-side alerts; pins (A TX = GPIO 44 → 485_A → B IO1 on the bench); the RS485-in-the-car question; v1 and the old enum drift kept for the record - [[controller-link]] — the A → B link, **protocol v2 (verified 2026-09-21)**: typed DATA/CONFIG frames on UART1 **and** ESP-NOW with dedupe, split gear fields, rpm, A-side alerts; pins (A TX = GPIO 44 → 485_A → B IO1 on the bench); the RS485-in-the-car question; v1 and the old enum drift kept for the record
- [[link-redundancy]] — wired + wireless redundancy: **ESP-NOW leg built and bench-verified** (both paths carry every frame, B dedupes and hops channels); RS485 for the car and BLE still open; failover policy notes - [[link-redundancy]] — wired + wireless redundancy: **ESP-NOW leg built and bench-verified** (both paths carry every frame, B dedupes and hops channels); RS485 for the car and BLE still open; failover policy notes
- [[controller-b-ota]] — **implemented 2026-09-27 (STATUS + gates verified, pairing/first release pending)**: B pulls its own signed release over Wi-Fi; `link pair` on A sends a random key over the UART wire once; credentials and OTA commands travel in AES-256-GCM `SECURE` frames; B reports version/phase/progress in `STATUS` frames; A's Updates page has a Controller B card; B's updater = port of A's; CI workflow + `v0.1.0` procedure - [[controller-b-ota]] — **implemented and verified end-to-end 2026-09-27 (B `dev` → `v0.1.0` from A's console)**: B pulls its own signed release over Wi-Fi; `link pair` on A sends a random key over the UART wire once; credentials and OTA commands travel in AES-256-GCM `SECURE` frames; B reports version/phase/progress in `STATUS` frames; A's Updates page has a Inst. Cluster card; B's updater = port of A's; CI workflow + `v0.1.0` procedure
- [[patrol-gauge-outputs]] — Patrol tachometer (IO7, 14-bit LEDC, 4 ppr) and coolant gauge (IO8, 8-bit PWM, CANNY duty law) **outputs implemented and bench-verified**; tunables on A via `cfg` console; prior art from the CANNY program; driver stage and needle calibration still to do - [[patrol-gauge-outputs]] — Patrol tachometer (IO7, 14-bit LEDC, 4 ppr) and coolant gauge (IO8, 8-bit PWM, CANNY duty law) **outputs implemented and bench-verified**; tunables on A via `cfg` console; prior art from the CANNY program; driver stage and needle calibration still to do
## Synthesis ## Synthesis
+24 -4
View File
@@ -8,7 +8,7 @@ Created schema (`CLAUDE.md`, modelled on the sibling 5B wiki with a sibling-refe
Findings recorded during setup: Findings recorded during setup:
- Header pinout verified from the photo: IO1–5 and IO7–14, 13 free-function GPIOs; the wiring guide's IO35–42 table is wrong. - Header pinout verified from the photo: IO1–5 and IO7–14, 13 free-function GPIOs; the wiring guide's IO35–42 table is wrong.
- Controller A cannot drive the Patrol gauges (no free native GPIO; DO terminals are I2C-expander + optocoupler). B can, via LEDC on IO7/IO8 — proposal only. - Main CTRL cannot drive the Patrol gauges (no free native GPIO; DO terminals are I2C-expander + optocoupler). B can, via LEDC on IO7/IO8 — proposal only.
- A transmits on GPIO 44 (code), not 43 (two stale docs). GPIO 44 leaves the 5B only as an RS485 A/B pair — how that reaches B's IO1 is unknown and is now open question #1. - A transmits on GPIO 44 (code), not 43 (two stale docs). GPIO 44 leaves the 5B only as an RS485 A/B pair — how that reaches B's IO1 is unknown and is now open question #1.
- The two repos' `gear_position_t` enums have drifted (Sport/Manual vs M1–M6 at values 4+). Open question #2. - The two repos' `gear_position_t` enums have drifted (Sport/Manual vs M1–M6 at values 4+). Open question #2.
- The packet has no RPM field; A has RPM verified from CAN 0x0AA. `engine_oil_temp` has no real source on this engine. - The packet has no RPM field; A has RPM verified from CAN 0x0AA. `engine_oil_temp` has no real source on this engine.
@@ -54,15 +54,35 @@ Implemented in both repos (not yet committed): shared header v2 (typed DATA/CONF
A gained a hand-coded LVGL Gauge Tuning screen (Home → right → Driveline → right): −/+ rows for every `link_config_t` field, enable switches, and an override panel with RPM/duty sliders; changes go through `Tunables` (saved + pushed), overrides never persisted (A's NVS save strips them). Built and flashed. Step-by-step needle calibration procedure added to [[patrol-gauge-outputs]]. A gained a hand-coded LVGL Gauge Tuning screen (Home → right → Driveline → right): −/+ rows for every `link_config_t` field, enable switches, and an override panel with RPM/duty sliders; changes go through `Tunables` (saved + pushed), overrides never persisted (A's NVS save strips them). Built and flashed. Step-by-step needle calibration procedure added to [[patrol-gauge-outputs]].
## [2026-09-27] update | SquareLine retired on Controller B; LVGL lock; oil quadrant dropped; 16 MB flash declared ## [2026-09-27] update | SquareLine retired on Inst. Cluster; LVGL lock; oil quadrant dropped; 16 MB flash declared
Mirror of the A-side clean-up. `include/ui/` (SquareLine export) deleted; the screen is now `src/modules/gauge_screen.cpp` - same layout minus the engine-oil cell (user decision, closes open question #8: the M57N has no oil temperature sensor), battery centred at the bottom. Kept the two fonts and six icons the screen uses as plain LVGL arrays in `src/assets/`. New `DisplayInit::lock()/unlock()` recursive mutex: `lvglTask` renders under it and `loop()` updates under it - before, the higher-priority render task could preempt `loop()` mid-`lv_label_set_text()`, the bug class that froze A. Labels, colours and icons are written only on change. `DebugMonitor` now records A's debug flag in the receiver and applies it from `loop()` under the lock (it used to touch LVGL from the ESP-NOW callback). `lv_conf.h`: 128 KB pool in PSRAM, logging off, `LV_TICK_CUSTOM` from `millis()`. `platformio.ini`: flash declared 16 MB with `default_16MB.csv` (two 6.5 MB OTA slots; NVS unchanged so the cached gauge config survives), stale `-mfix-esp32-psram-cache-issue` and include paths removed. Waveshare's page adds nothing new for firmware (Arduino core 2.0.x, LVGL 8.3.7 demo, 800 mA LDO); no operating-temperature figure. Built and flashed COM13. Updated [[esp32-s3-lcd-1-3]], [[open-questions]] #8, index; root CLAUDE.md and README. Mirror of the A-side clean-up. `include/ui/` (SquareLine export) deleted; the screen is now `src/modules/gauge_screen.cpp` - same layout minus the engine-oil cell (user decision, closes open question #8: the M57N has no oil temperature sensor), battery centred at the bottom. Kept the two fonts and six icons the screen uses as plain LVGL arrays in `src/assets/`. New `DisplayInit::lock()/unlock()` recursive mutex: `lvglTask` renders under it and `loop()` updates under it - before, the higher-priority render task could preempt `loop()` mid-`lv_label_set_text()`, the bug class that froze A. Labels, colours and icons are written only on change. `DebugMonitor` now records A's debug flag in the receiver and applies it from `loop()` under the lock (it used to touch LVGL from the ESP-NOW callback). `lv_conf.h`: 128 KB pool in PSRAM, logging off, `LV_TICK_CUSTOM` from `millis()`. `platformio.ini`: flash declared 16 MB with `default_16MB.csv` (two 6.5 MB OTA slots; NVS unchanged so the cached gauge config survives), stale `-mfix-esp32-psram-cache-issue` and include paths removed. Waveshare's page adds nothing new for firmware (Arduino core 2.0.x, LVGL 8.3.7 demo, 800 mA LDO); no operating-temperature figure. Built and flashed COM13. Updated [[esp32-s3-lcd-1-3]], [[open-questions]] #8, index; root CLAUDE.md and README.
## [2026-09-27] query | OTA for B: pull design chosen, written up ## [2026-09-27] query | OTA for B: pull design chosen, written up
User asked about updating B "via ESP-NOW". Compared A-pushes-chunks vs B-pulls-itself; user chose the pull design. Facts checked: B's Arduino 2.0.17 `qio_opi` sdkconfig has bootloader rollback, ECDSA P-256 and PEM parsing enabled (no core rebuild), 235 KB internal free after today's clean-up, partition table already has two OTA slots. Design page [[controller-b-ota]]: credential handoff via a pairing key exchanged over the UART wire on the bench then encrypted ESP-NOW unicast (both repos are public, so a compiled-in key would protect nothing); STATUS frames B→A for version + phase and A's Updates page gets a Controller B row; OTA_CMD trigger behind A's parking gate; B's OTA module = port of A's with link-data gate and a small on-screen notice; B CI workflow + `BMW_NISSAN_FIRMWARE_SIGNING_KEY` secret on the B repo (user action). New frame types 0x03–0x06, PACKET_VERSION stays 2. Open question #12 added. User asked about updating B "via ESP-NOW". Compared A-pushes-chunks vs B-pulls-itself; user chose the pull design. Facts checked: B's Arduino 2.0.17 `qio_opi` sdkconfig has bootloader rollback, ECDSA P-256 and PEM parsing enabled (no core rebuild), 235 KB internal free after today's clean-up, partition table already has two OTA slots. Design page [[controller-b-ota]]: credential handoff via a pairing key exchanged over the UART wire on the bench then encrypted ESP-NOW unicast (both repos are public, so a compiled-in key would protect nothing); STATUS frames B→A for version + phase and A's Updates page gets a Inst. Cluster row; OTA_CMD trigger behind A's parking gate; B's OTA module = port of A's with link-data gate and a small on-screen notice; B CI workflow + `BMW_NISSAN_FIRMWARE_SIGNING_KEY` secret on the B repo (user action). New frame types 0x03–0x06, PACKET_VERSION stays 2. Open question #12 added.
## [2026-09-27] update | Controller B OTA implemented on both boards; STATUS + gates verified; pairing awaits the wire ## [2026-09-27] update | Inst. Cluster OTA implemented on both boards; STATUS + gates verified; pairing awaits the wire
Implemented the [[controller-b-ota]] design end to end. Shared header: `STATUS` 0x03 / `PAIR` 0x04 / `SECURE` 0x05 (+ inner `OTA_CMD` 0x11, `WIFI_CREDS` 0x12), `PACKET_MAX_PAYLOAD` 160, new `include/protocol/link_secure.h` (AES-256-GCM seal/open, key fingerprint; mbedtls names differ between IDF 4.4 and 5.5, handled). Decision: application-level GCM instead of ESP-NOW peer encryption (no PMK/LMK bookkeeping, no broadcast-vs-encrypted-peer doubt). B: `link_peer.cpp` (NVS key + A's MAC, credentials in namespace `wifi`, mailboxes so the Wi-Fi/UART tasks never touch NVS, STATUS every 5 s / on change, nonce replay window), `console.cpp` (line reader + handler chain, `help`), `ota_update.cpp` (port of A's: link-data gate, joins Wi-Fi only for the job, notice line on the screen via `GaugeScreen::setNotice()`, pumps STATUS from the download loop), `include/config/ota_config.h` (`patrol-b`, this repo, same roots + public key), `.gitea/workflows/firmware.yml`, `tools/ota/firmware_signing_pub.pem`. A: `link_peer.cpp` (`link status|pair|unpair|creds|ota ...`, automatic credential sync, B card on Settings → Updates), `EspNowLink` receive callback + `sendTo()`, `UARTManager::sendWire()`, `WiFiManager::getSavedCredentials()`, `Ota::isParked()`. Bench (A COM14, B COM13): B's STATUS frames reach A (MAC 10:51:DB:8F:B6:5C, `dev`, heap 234 KB); `ota check` on B refuses "no Wi-Fi credentials from A yet"; `link ota check` on A refuses "not paired"; `link pair` on A sent PAIR ×3 but B never saw it: **B's UART leg is silent (uart=0) — no wire on the bench right now**. Next: connect `485_A → IO1` + GND, `link pair`, credentials, tag `v0.1.0`, install from A's screen. Build notes: run `pio` from PowerShell (idf_tools refuses MSYS/Git Bash); the first build after switching between the two projects reinstalls the other Arduino core and can fail once with a `TypeError` — run it again. Implemented the [[controller-b-ota]] design end to end. Shared header: `STATUS` 0x03 / `PAIR` 0x04 / `SECURE` 0x05 (+ inner `OTA_CMD` 0x11, `WIFI_CREDS` 0x12), `PACKET_MAX_PAYLOAD` 160, new `include/protocol/link_secure.h` (AES-256-GCM seal/open, key fingerprint; mbedtls names differ between IDF 4.4 and 5.5, handled). Decision: application-level GCM instead of ESP-NOW peer encryption (no PMK/LMK bookkeeping, no broadcast-vs-encrypted-peer doubt). B: `link_peer.cpp` (NVS key + A's MAC, credentials in namespace `wifi`, mailboxes so the Wi-Fi/UART tasks never touch NVS, STATUS every 5 s / on change, nonce replay window), `console.cpp` (line reader + handler chain, `help`), `ota_update.cpp` (port of A's: link-data gate, joins Wi-Fi only for the job, notice line on the screen via `GaugeScreen::setNotice()`, pumps STATUS from the download loop), `include/config/ota_config.h` (`patrol-b`, this repo, same roots + public key), `.gitea/workflows/firmware.yml`, `tools/ota/firmware_signing_pub.pem`. A: `link_peer.cpp` (`link status|pair|unpair|creds|ota ...`, automatic credential sync, B card on Settings → Updates), `EspNowLink` receive callback + `sendTo()`, `UARTManager::sendWire()`, `WiFiManager::getSavedCredentials()`, `Ota::isParked()`. Bench (A COM14, B COM13): B's STATUS frames reach A (MAC 10:51:DB:8F:B6:5C, `dev`, heap 234 KB); `ota check` on B refuses "no Wi-Fi credentials from A yet"; `link ota check` on A refuses "not paired"; `link pair` on A sent PAIR ×3 but B never saw it: **B's UART leg is silent (uart=0) — no wire on the bench right now**. Next: connect `485_A → IO1` + GND, `link pair`, credentials, tag `v0.1.0`, install from A's screen. Build notes: run `pio` from PowerShell (idf_tools refuses MSYS/Git Bash); the first build after switching between the two projects reinstalls the other Arduino core and can fail once with a `TypeError` — run it again.
## [2026-09-27] verify | Inst. Cluster updated over the air from A: dev → v0.1.0, end to end
User connected `485_A → IO1` (ground via the USB hub). B had rebooted on plug-in (A's card flipped to "not heard" for 15 s) and logged checksum-error bursts, but `uart alive` with good frames. `link pair` on A: PAIR ×3 over the wire, B `PAIRED ... fingerprint A9B7`, A `Inst. Cluster confirmed pairing` in < 5 s, then A pushed the `ArtServis` credentials by itself and B stored them. `link ota check` before the release existed: B joined the AP in ~2 s, got 404 → "no release published yet", reported to A as *failed* + reason (truncated to 32 chars), left Wi-Fi, re-locked on channel 1. CI: B's `main-latest` built in < 3 min; the `v0.1.0` tag build took ~12 min but published `firmware.bin` 1,248,432 B + `manifest.txt` (target patrol-b, sha256 `3c33d20f…3415`, ECDSA sig). `link ota check` → `update available, latest v0.1.0`; `link ota install` → download + flash to app1 in ~50 s with 0/10/…/100 % on B's console, `verified and installed v0.1.0`, reboot, `Firmware v0.1.0` banner, STATUS to A resumed, `confirmed - rollback cancelled` at 30 s, `ota status` slot app1 valid. Heap 230 KB before/after, loop stack headroom 3.4 KB. Not yet eyeballed: the Updates-page buttons on A and the progress line on B's screen (same code path as the console). Wiki [[controller-b-ota]] verification table and risks updated, [[open-questions]] #12 answered.
## [2026-09-27] update | Round-panel redesign of B's screen: warning ring, tell-tales, whole-degree values
User asked for an automotive look, a Wi-Fi indicator and a sense of urgency on crossed thresholds. `gauge_screen.cpp` rebuilt for the circle: a 6 px ring at the rim acts as a warning lamp (dim; red blinking at 2 Hz while any red alert bit is set; amber while the gearbox asks for cooling), the affected value's digits and icon go red, temperatures show whole degrees and the battery a tenth (fewer, bigger digits), coolant/gearbox sit at 10 and 2 o'clock as icon + digits, the 110 px gear stays in the centre, battery centred low; tell-tales at 9 o'clock (Wi-Fi: green only while joined for an update) and 3 o'clock (red `!` when the link to A is lost). Everything is positioned absolutely inside the circle - the old flex column overflowed 240 px, so the battery digits sat partly off-panel. Built and flashed COM13; the user has not yet looked at it. The bench cannot show an alert (A's alerts come from CAN frames only), so the ring/red-value path is untested until the car.
## [2026-09-28] update | B's screen: arc gauges with needles instead of digits (user's design)
User saw the 2026-09-27 layout ("not bad") and redesigned it: no temperature digits; coolant as an arc on the LEFT rim from compass 230° (bottom-left, cold) to 320° (top-left, hot) with a needle, gearbox oil mirrored on the RIGHT from 140° to 40°; arcs blue when cool grading to red at the hot end; each icon just past the hot end, upper-left / upper-right; battery digits stay at the bottom. Implemented in `gauge_screen.cpp`: gradient = 9-10 `lv_arc` segments of 10° (1° overlap, no seams) coloured blue→neutral→red, needle = 3 px white `lv_line` from r 92 to 113 recomputed only on an angle change, band r 100-110 inside the 6 px warning ring, icons centred at r 66 (angles 245° / 295° LVGL). Scales: coolant 50-120 °C, gearbox 40-150 °C (thresholds 100 / 130 sit at ~70 % / ~80 % of the sweep). Ring blink / red icons / tell-tales unchanged. Built and flashed COM13, clean boot; the user is looking at it.
## [2026-09-28] verify | Renamed Inst. Cluster; deep sleep on link silence with wire + timer wake, verified on the bench
User renamed the boards (Controller A → Main CTRL, Controller B → Inst. Cluster) across the repo. New `power_manager.cpp`: when the Main CTRL's "Sleep when the car is off" switch arrives as `CFG_SLEEP_WHEN_SILENT` (bit 7 of `out_enable`, cached in NVS with the gauge config), the board deep-sleeps after 60 s without a DATA frame (gauges low, backlight off), waking on UART RX IO1 (ext0, pull-up) or a 60 s timer. A timer wake is a *probe boot*: setup skips the serial waits, the panel stays dark, 4 s of listening, then sleep again unless the Main CTRL is heard. `Ota::isBusy()` blocks sleep during a job. Console `sleep status | now`. Bench, timestamps from the console: `t=60442 ms: link silent for 60 s - deep sleep` → `rst:0x5 (DSLEEP)` **60.1 s later** → `probe boot (timer)` → `t=4043 ms: probe: nothing heard - deep sleep`. Bug found and fixed on the way: the flag was printed at init before `GaugeOutputs::init()` had loaded the cached config ("off" while it was on). Not verified: wake through the wire (needs the Main CTRL awake and the wire), and how the probe boot looks on the panel (should stay dark).
## [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).
+17 -13
View File
@@ -1,22 +1,24 @@
--- ---
type: concept type: concept
tags: [ota, wifi, esp-now, security, design, verified] tags: [ota, wifi, esp-now, security, verified]
updated: 2026-09-27 updated: 2026-09-27
--- ---
# Over-the-air updates for Controller B # Over-the-air updates for Inst. Cluster
**Status 2026-09-27: implemented on both controllers, bench-tested up to the pairing step.** B pulls its own signed release from Gitea over Wi-Fi; A hands B the network credentials and the trigger over the existing link, and shows B's progress on its own Updates page. Design chosen by the user over "A streams the image through ESP-NOW" (comparison below). Everything reuses A's proven pipeline ([[ota-updates]] in the sibling wiki). **Status 2026-09-27: implemented on both controllers and VERIFIED END-TO-END on the bench - B went from `dev` to `v0.1.0` on a command typed on A, rebooted and confirmed itself.** B pulls its own signed release from Gitea over Wi-Fi; A hands B the network credentials and the trigger over the existing link, and shows B's progress on its own Updates page. Design chosen by the user over "A streams the image through ESP-NOW" (comparison below). Everything reuses A's proven pipeline ([[ota-updates]] in the sibling wiki).
## What is verified, what is not ## What is verified, what is not
| Step | State | | Step | State |
|---|---| |---|---|
| B → A STATUS frames (version, phase, heap, uptime) over ESP-NOW unicast | `(verified 2026-09-27)` A's console `link status` lists B's MAC, `dev`, heap 234 KB; A's Updates page shows the Controller B card | | B → A STATUS frames (version, phase, heap, uptime) over ESP-NOW unicast | `(verified 2026-09-27)` A's console `link status` lists B's MAC, `dev`, heap 234 KB; A's Updates page shows the Inst. Cluster card |
| Gates on both sides (unpaired → refused, no credentials → refused, key mismatch → refused) | `(verified 2026-09-27)` each refusal text seen on the consoles | | Gates on both sides (unpaired → refused, no credentials → refused, key mismatch → refused) | `(verified 2026-09-27)` each refusal text seen on the consoles |
| `link pair` over the UART wire | **not yet**: the bench had no wire connected when tested (B: `uart=0 ... uart silent`). Needs `485_A → IO1`, GND → GND, 120 Ω switch OFF ([[controller-link]] bench wiring) | | `link pair` over the UART wire | `(verified 2026-09-27 21:2x)` wire `485_A → IO1`, ground shared through the USB hub only. A: `PAIR sent over the wire 3 time(s); new key fingerprint A9B7`; B: `PAIRED over the wire ... A = 30:ED:A0:17:B2:4C` (+ one "re-confirmed" for the repeats); A: `Inst. Cluster confirmed pairing (fingerprint A9B7)` within 5 s |
| Encrypted credential handoff, B joins the network | not yet (needs pairing) | | Encrypted credential handoff | `(verified)` A pushed `ArtServis` on its own right after pairing; B: `Wi-Fi credentials for 'ArtServis' stored`; `wifi status` on B lists the network |
| `link ota check` / install from A's screen, first signed B release | not yet (needs pairing + release `v0.1.0` of this repo) | | `link ota check` from A | `(verified)` B joined the AP (IP 10.0.10.101, channel 1) in ~2 s, before the release existed: `no release published yet (push a v* tag)` reported back to A as phase *failed* + message; after the release: `latest release v0.1.0 (1248432 bytes, signature OK)`, A: `update available, latest v0.1.0` |
| `link ota install` from A, first signed release `v0.1.0` | `(verified)` download + flash of 1,248,432 B into `app1` in ~50 s, `verified and installed v0.1.0`, reboot, banner `Firmware v0.1.0`, `NEW IMAGE, unconfirmed`, STATUS to A resumed within seconds (`firmware v0.1.0`), `firmware v0.1.0 confirmed - rollback cancelled` at 30 s; `ota status`: slot app1 state valid. Loop stack headroom after a job: 3.4 KB; heap 230 KB before/after |
| Screen path (Inst. Cluster card on A's Updates page, B's on-screen notice line) | same request functions as the console commands, but the buttons have **not been tapped yet** and the "Updating v0.1.0 N%" line on B's round screen was not watched - user to confirm on the next update |
## Why pull, not push ## Why pull, not push
@@ -32,7 +34,7 @@ updated: 2026-09-27
### 1. Pairing (once, on the bench, over the wire) ### 1. Pairing (once, on the bench, over the wire)
`link pair` on A's console. A generates a random 32-byte key, sends `PAIR` (magic, key, A's STA MAC) **three times over UART1 only** and stores the key in NVS (`linkpeer/key`). B accepts `PAIR` only from the UART source (a `PAIR` heard on the radio is dropped and logged), stores key + A's MAC in NVS (`linkpeer/key`, `linkpeer/amac`) and answers with a STATUS carrying `key_fp` = first two bytes of SHA-256(key). A logs `Controller B confirmed pairing (fingerprint XXXX)` when it matches. Both repos are public, so this is the only secret and it never travels by radio. Survives reflashes (NVS); an NVS erase on either side means re-pairing at home — the car has no wire today ([[controller-link]]). `link pair` on A's console. A generates a random 32-byte key, sends `PAIR` (magic, key, A's STA MAC) **three times over UART1 only** and stores the key in NVS (`linkpeer/key`). B accepts `PAIR` only from the UART source (a `PAIR` heard on the radio is dropped and logged), stores key + A's MAC in NVS (`linkpeer/key`, `linkpeer/amac`) and answers with a STATUS carrying `key_fp` = first two bytes of SHA-256(key). A logs `Inst. Cluster confirmed pairing (fingerprint XXXX)` when it matches. Both repos are public, so this is the only secret and it never travels by radio. Survives reflashes (NVS); an NVS erase on either side means re-pairing at home — the car has no wire today ([[controller-link]]).
### 2. SECURE frames (A → B, ESP-NOW unicast) ### 2. SECURE frames (A → B, ESP-NOW unicast)
@@ -47,7 +49,7 @@ Everything A sends B by radio that matters goes inside `PACKET_TYPE_SECURE`: `no
### 4. A's Updates page ### 4. A's Updates page
Settings → Updates now has two cards, **Controller A** and **Controller B**, each with Installed / Latest / a status line / Check / Install. B's buttons are enabled only when B is heard, paired with *this* key and holds credentials; the status line otherwise says which of those is missing. Install asks for confirmation, then `LinkPeer::requestInstall()` applies A's parking gate (engine off, shaft still, lever P/N — `Ota::isParked()`), requires **A itself to be on Wi-Fi** (same network as B ⇒ same radio channel ⇒ B's STATUS frames keep arriving while B is joined) and sends the `OTA_CMD`. Settings → Updates now has two cards, **Main CTRL** and **Inst. Cluster**, each with Installed / Latest / a status line / Check / Install. B's buttons are enabled only when B is heard, paired with *this* key and holds credentials; the status line otherwise says which of those is missing. Install asks for confirmation, then `LinkPeer::requestInstall()` applies A's parking gate (engine off, shaft still, lever P/N — `Ota::isParked()`), requires **A itself to be on Wi-Fi** (same network as B ⇒ same radio channel ⇒ B's STATUS frames keep arriving while B is joined) and sends the `OTA_CMD`.
### 5. B's updater (`src/modules/ota_update.cpp`) ### 5. B's updater (`src/modules/ota_update.cpp`)
@@ -65,14 +67,16 @@ Port of A's module. Differences: gate = link data (`rpm == 0`, lever P/N/unknown
1. Bench: both boards on USB, `485_A → IO1`, GND → GND, 5B's 120 Ω switch OFF. B's 5-second stats line must say `uart alive`. 1. Bench: both boards on USB, `485_A → IO1`, GND → GND, 5B's 120 Ω switch OFF. B's 5-second stats line must say `uart alive`.
2. A console: `link pair` → A prints the fingerprint; within 5 s `link status` shows `key XXXX (matches)` and B's console printed `PAIRED over the wire`. 2. A console: `link pair` → A prints the fingerprint; within 5 s `link status` shows `key XXXX (matches)` and B's console printed `PAIRED over the wire`.
3. A on Wi-Fi with its remembered network → within ~15 s A logs `Wi-Fi credentials for '<ssid>' sent to Controller B (encrypted)`, B logs `stored`, `link status` shows `Wi-Fi creds yes`. 3. A on Wi-Fi with its remembered network → within ~15 s A logs `Wi-Fi credentials for '<ssid>' sent to Inst. Cluster (encrypted)`, B logs `stored`, `link status` shows `Wi-Fi creds yes`.
4. Tag this repo (`git tag -a v0.1.0 -m ... && git push --follow-tags origin master`), wait for the Gitea release with `manifest.txt`. 4. Tag this repo (`git tag -a v0.1.0 -m ... && git push --follow-tags origin master`), wait for the Gitea release with `manifest.txt`.
5. A: Settings → Updates → Controller B → Check → "Version v0.1.0 is available for Controller B" → Install → confirm. B's screen shows "Updating v0.1.0 N%", A's card shows the percentage, B restarts, its STATUS says `v0.1.0` with "new firmware, confirming..." for 30 s, then plain. Console alternative: `link ota check`, `link ota install`. 5. A: Settings → Updates → Inst. Cluster → Check → "Version v0.1.0 is available for Inst. Cluster" → Install → confirm. B's screen shows "Updating v0.1.0 N%", A's card shows the percentage, B restarts, its STATUS says `v0.1.0` with "new firmware, confirming..." for 30 s, then plain. Console alternative: `link ota check`, `link ota install`.
## Risks / open ## Risks / open
- **Wi-Fi + ESP-NOW coexistence on B while joined**: A and B on the same AP share the channel; B's receiver follows the AP channel while joined and hops back after `WiFi.disconnect(false)`. Not yet observed live. - **Wi-Fi + ESP-NOW coexistence on B while joined**: `(verified)` A on `ArtServis` channel 1, B joined the same AP on channel 1, STATUS kept flowing during the download (A saw phase *installing*), B re-locked on channel 1 after `WiFi.disconnect(false)`. Untested: A **not** on Wi-Fi or on a different AP - by design A refuses B commands unless it is on Wi-Fi itself.
- **Internal RAM on B during TLS**: 235 KB free today; the job logs heap before/after. Measure once on the first check. - **Internal RAM on B during TLS**: `(verified)` 230.7 KB free before the job, 230.4 KB after; largest block 164 KB. No PSRAM tricks needed.
- **UART wire quality on the bench**: with ground shared only through the USB hub, B logs bursts of `Checksum error on uart` (7 in a row at times) and an occasional `Framing error` / `Version mismatch got v0`; 2026-09-21 with a direct GND wire it was 0 errors. Harmless for the data (ESP-NOW copy wins, dedupe) and PAIR got through (sent 3×), but run a real GND wire next time → [[open-questions]] #1 / [[link-redundancy]].
- **`link_status_t::message` is 32 bytes**: B's failure reason `no release published yet (push a v* tag)` arrived truncated at "(push". Cosmetic; lengthen if it ever matters.
- **Pairing key lost** (NVS erase on either side): re-pair at home over the wire. - **Pairing key lost** (NVS erase on either side): re-pair at home over the wire.
- Two boards, one PlatformIO penv: the first `pio run` after switching projects reinstalls the other Arduino core and can fail once with a `TypeError`; run it again. Builds must be started from PowerShell, not Git Bash (`idf_tools.py` refuses MSYS). - Two boards, one PlatformIO penv: the first `pio run` after switching projects reinstalls the other Arduino core and can fail once with a `TypeError`; run it again. Builds must be started from PowerShell, not Git Bash (`idf_tools.py` refuses MSYS).
+2 -2
View File
@@ -6,10 +6,10 @@ updated: 2026-09-21
# Controller Link (A → B) # Controller Link (A → B)
The system is two ESP32-S3 boards. Controller A (Waveshare ESP32-S3-Touch-LCD-5B, sibling repo) reads the BMW PT-CAN bus and owns all decoding; Controller B ([[esp32-s3-lcd-1-3]], this repo) is a **slave / extension**: it consumes a compact packet, displays it, and will drive the Patrol gauges from it ([[patrol-gauge-outputs]]). The system is two ESP32-S3 boards. Main CTRL (Waveshare ESP32-S3-Touch-LCD-5B, sibling repo) reads the BMW PT-CAN bus and owns all decoding; Inst. Cluster ([[esp32-s3-lcd-1-3]], this repo) is a **slave / extension**: it consumes a compact packet, displays it, and will drive the Patrol gauges from it ([[patrol-gauge-outputs]]).
``` ```
BMW PT-CAN ──▶ Controller A (5B) ──UART 5 Hz──▶ Controller B (1.3) BMW PT-CAN ──▶ Main CTRL (5B) ──UART 5 Hz──▶ Inst. Cluster (1.3)
╰── BLE (planned, redundant) ──╯ → [[link-redundancy]] ╰── BLE (planned, redundant) ──╯ → [[link-redundancy]]
``` ```
+2 -2
View File
@@ -6,7 +6,7 @@ updated: 2026-09-27
# Waveshare ESP32-S3-LCD-1.3 # Waveshare ESP32-S3-LCD-1.3
Controller B of the [[controller-link]] — the compact secondary unit. Receives the sensor stream from Controller A, shows it on a 1.3" round-masked display, and is the board chosen to drive the Patrol cluster gauges ([[patrol-gauge-outputs]]) because it is the only one of the two with free hardware-PWM pins on a header. Inst. Cluster of the [[controller-link]] — the compact secondary unit. Receives the sensor stream from Main CTRL, shows it on a 1.3" round-masked display, and is the board chosen to drive the Patrol cluster gauges ([[patrol-gauge-outputs]]) because it is the only one of the two with free hardware-PWM pins on a header.
## Specs (source: waveshare-wiki-esp32-s3-lcd-1-3) ## Specs (source: waveshare-wiki-esp32-s3-lcd-1-3)
@@ -56,7 +56,7 @@ Header GPIOs and their current use `(repo)`:
| GPIO | Use today | Note | | GPIO | Use today | Note |
|---|---|---| |---|---|---|
| IO1 | UART1 RX from Controller A | keep | | IO1 | UART1 RX from Main CTRL | keep |
| IO2 | UART1 TX (link is receive-only, so idle) | effectively free | | IO2 | UART1 TX (link is receive-only, so idle) | effectively free |
| IO3 | free | S3 strapping pin (JTAG select) — avoid | | IO3 | free | S3 strapping pin (JTAG select) — avoid |
| IO4, IO5 | free | | | IO4, IO5 | free | |
+2 -2
View File
@@ -6,7 +6,7 @@ updated: 2026-09-21
# Open Questions # Open Questions
The research frontier for Controller B. Answering any of these should trigger updates across the wiki. Ordered roughly by how much they block progress. The research frontier for Inst. Cluster. Answering any of these should trigger updates across the wiki. Ordered roughly by how much they block progress.
## Blocking ## Blocking
@@ -22,7 +22,7 @@ The research frontier for Controller B. Answering any of these should trigger up
13. **CANNY 5.3 pico details**: what is the HR PWM base clock (period 255 = what frequency), and what sat between the CANNY pin and the gauge wire? The user may still have the unit and harness. → [[temp-stage-cfd]] 13. **CANNY 5.3 pico details**: what is the HR PWM base clock (period 255 = what frequency), and what sat between the CANNY pin and the gauge wire? The user may still have the unit and harness. → [[temp-stage-cfd]]
8. ~~**Does `engine_oil_temp` stay in the packet?**~~ **Answered 2026-09-27 (user): dropped from the screen.** The field stays in the packet (protocol v2 unchanged, never valid on this engine), but B's hand-coded screen no longer has an oil quadrant - the battery cell sits alone at the bottom. 8. ~~**Does `engine_oil_temp` stay in the packet?**~~ **Answered 2026-09-27 (user): dropped from the screen.** The field stays in the packet (protocol v2 unchanged, never valid on this engine), but B's hand-coded screen no longer has an oil quadrant - the battery cell sits alone at the bottom.
12. **OTA for Controller B** — design agreed and **implemented 2026-09-27** → [[controller-b-ota]]. STATUS frames and every gate verified on the bench; signing secret set on the B repo (user, 2026-09-27). Still open: `link pair` over the wire (the bench had no wire connected), the automatic credential handoff, the first signed release `v0.1.0` and the first install from A's screen. 12. **OTA for Inst. Cluster** — **answered 2026-09-27** → [[controller-b-ota]]: implemented and verified end-to-end on the bench (pair over the wire, automatic credential handoff, `link ota check` / `install` from A, B `dev` → `v0.1.0`, reboot, self-confirm). Left to eyeball: the Inst. Cluster card on A's Updates page and B's on-screen progress line during the next update; the bench wire wants a proper GND (checksum-error bursts with hub-only ground).
## Hardware ## Hardware
+21 -3
View File
@@ -6,11 +6,11 @@ updated: 2026-09-21
# Driving the Patrol Cluster Gauges # Driving the Patrol Cluster Gauges
Goal (user, 2026-09-21): generate signals from Controller B to drive the Nissan Patrol instrument cluster's **RPM (tachometer)** and **engine coolant temperature** gauges, fed by the BMW data that arrives over the [[controller-link]]. Goal (user, 2026-09-21): generate signals from Inst. Cluster to drive the Nissan Patrol instrument cluster's **RPM (tachometer)** and **engine coolant temperature** gauges, fed by the BMW data that arrives over the [[controller-link]].
## Why B and not A ## Why B and not A
Controller A (5B) has no free native GPIO on any header: the RGB LCD, I2C, CAN, RS485, USB and PSRAM consume every pin, and its two "DO" terminals are optocoupled outputs driven through a CH422G I2C expander — no hardware timer can reach them `(sibling: 5B wiki → esp32-s3-touch-lcd-5b; schematic reviewed 2026-09-21)`. B exposes 13 free GPIOs on headers ([[esp32-s3-lcd-1-3]]), all usable by the ESP32-S3 LEDC peripheral. Main CTRL (5B) has no free native GPIO on any header: the RGB LCD, I2C, CAN, RS485, USB and PSRAM consume every pin, and its two "DO" terminals are optocoupled outputs driven through a CH422G I2C expander — no hardware timer can reach them `(sibling: 5B wiki → esp32-s3-touch-lcd-5b; schematic reviewed 2026-09-21)`. B exposes 13 free GPIOs on headers ([[esp32-s3-lcd-1-3]]), all usable by the ESP32-S3 LEDC peripheral.
## Two very different signals ## Two very different signals
@@ -56,6 +56,24 @@ PWM drive from the curve:
Tachometer, 4 ppr: f = rpm × 4 / 60 → ~47 Hz at 700 rpm, ~267 Hz at 4000 rpm. Before wiring: measure the tach input's open-circuit voltage with ignition on — battery voltage means the cluster has its own pull-up (open-collector output suffices); near zero means add a pull-up to 12 V. Verify the needle at two known LEDC frequencies before trusting the scaling. Tachometer, 4 ppr: f = rpm × 4 / 60 → ~47 Hz at 700 rpm, ~267 Hz at 4000 rpm. Before wiring: measure the tach input's open-circuit voltage with ignition on — battery voltage means the cluster has its own pull-up (open-collector output suffices); near zero means add a pull-up to 12 V. Verify the needle at two known LEDC frequencies before trusting the scaling.
## 2N2222 output stage — concrete wiring (2026-09-28, user's part choice; **verified on the cluster the same day**)
> [!note] Built and verified 2026-09-28: base resistors are **2.6 kΩ** (no 1 kΩ at hand) on both IO7 and IO8, and the instrument cluster responded. ~1 mA base current saturates the 2N2222 up to ~50 mA collector current, enough for both wires. Still to confirm: the transistor stays cool after minutes of running, and `cfg override duty 255` takes the temp needle to the hot mark; if not, drop to 1 kΩ.
One NPN per output, low-side open-collector switch. TO-92 P2N2222A / PN2222A with the flat face toward you: **E - B - C** left to right (metal-can 2N2222: the tab is next to the emitter). Check the datasheet of the exact part - the EBC order is not universal.
| Pin | Goes to | Why |
|---|---|---|
| Emitter | GND, shared by B, the transistor and the cluster (chassis) | the switch pulls the cluster wire toward this ground |
| Base | B's GPIO (IO7 tach, IO8 temp) through **1 kΩ** | 3.3 V pin → ~2.6 mA base current → saturated for anything up to ~100 mA collector; without it the pin drives a diode directly |
| Base | also **10 kΩ to GND** | keeps the transistor OFF while the ESP32 boots and the pin floats |
| Collector | the cluster wire (see below) | open collector: pulls low when the GPIO is high |
- **Tach (IO7)**: collector straight to the cluster's tach input. Meter the input first, ignition on: ~12 V = the cluster has its own pull-up, done; ~0 V = add **4.7 kΩ from the collector to +12 V**.
- **Temp (IO8)**: collector → **series resistor** → sender wire; the resistor equals the hottest sender resistance the needle should ever show (100 % duty = that value, the meter integrates lower duties). Add a **1N4148 from collector (cathode) to +12 V (anode)** — the gauge coil is inductive enough to spike the collector when the PWM switches; 40 V rating on the 2N2222 is otherwise fine.
- Never let the 12 V side reach a GPIO: the base resistor and the collector being the only 12 V-side node take care of that. No diode/resistor is needed on the GPIO itself.
- A logic-level N-MOSFET (e.g. IRLZ44N, AO3400) does the same job without base current: gate to GPIO through 100 Ω, 10 kΩ gate-to-GND, source to GND, drain as the collector above.
## Prior art: the user's CANNY 5.3 pico program (source: temp-stage-cfd) ## Prior art: the user's CANNY 5.3 pico program (source: temp-stage-cfd)
The user drove this gauge before, from the BMW CAN bus, with a CannyLab program → [[temp-stage-cfd]]. Recovered from the file: The user drove this gauge before, from the BMW CAN bus, with a CannyLab program → [[temp-stage-cfd]]. Recovered from the file:
@@ -69,7 +87,7 @@ Starting point for the LEDC implementation: 8-bit duty, `duty = clamp(1.5·T + 5
## Tuning parameters — declared on A, executed on B (implemented 2026-09-21) ## Tuning parameters — declared on A, executed on B (implemented 2026-09-21)
Calibration lives on Controller A (NVS; the **Gauge Tuning touchscreen page** — Home → right → Driveline → right — or the `cfg` serial console) and is pushed to B in CONFIG frames; B executes and caches the last config in its own NVS. `link_config_t` in the shared protocol header: Calibration lives on Main CTRL (NVS; the **Gauge Tuning touchscreen page** — Home → right → Driveline → right — or the `cfg` serial console) and is pushed to B in CONFIG frames; B executes and caches the last config in its own NVS. `link_config_t` in the shared protocol header:
| Group | Parameter | Default | Note | | Group | Parameter | Default | Note |
|---|---|---|---| |---|---|---|---|