Link protocol v2 receiver, ESP-NOW leg, Patrol gauge outputs, gear pulse

- protocol header v2 copied byte-identical from the 5B repo
- uart_receiver: processFrame() shared by the UART framing task and ESP-NOW,
  version check, dedupe on packet_id+timestamp, per-transport liveness,
  CONFIG cache with sequence number
- espnow_receiver: STA mode, channel hopping while silent, locks on frames
- gauge_outputs: tach on IO7 (LEDC ch2, 14-bit), coolant PWM on IO8 (LEDC
  ch4, 8-bit), config cached in NVS, overrides applied but not saved
- main: gear label from lever + engaged/target (pulses while shifting, red on
  mismatch), icons driven by A's alert bits, gauge update at 5 Hz, link stats
- wiki: temp_stage.cfd (user's old CANNY program) decoded as prior art;
  controller-link, link-redundancy, patrol-gauge-outputs, open-questions
  updated with the bench-verified v2 results and calibration procedure

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-21 19:12:38 +02:00
parent 3613387d41
commit 5fe313b7fa
18 changed files with 1658 additions and 514 deletions
+20 -13
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## 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 a 23-byte sensor packet over UART at 5 Hz, shows it, and is the planned driver for the Patrol cluster's tachometer and coolant gauges.
**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.
**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.
@@ -30,7 +30,7 @@ Serial goes through the onboard **CH343 USB-UART chip on UART0**, so the port ap
### Tasks and cores
- **Core 1**: `lvglTask()` calls `DisplayInit::update()` every 5 ms (LVGL tick + handler). The Arduino `loop()` also runs on Core 1 (`ARDUINO_RUNNING_CORE=1`) and is where all UI updates happen: it polls `UARTReceiver` and writes labels/icons.
- **Core 0**: the UART receiver task (byte-level packet state machine). It never touches LVGL. 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. Shared data is guarded by `g_data_mutex` inside `uart_receiver.cpp`.
There is **no LVGL port lock** in this project (unlike Controller A). Keep every LVGL call in `loop()` or `lvglTask()`; if you add a task that must update the UI, add a mutex around `lv_*` calls first.
@@ -41,28 +41,32 @@ src/
main.cpp # setup(), loop(): UI update from received data, warning thresholds
modules/
display_init.cpp/.h # LovyanGFX LGFX class (ST7789VW), LVGL init, circular mask, backlight PWM
uart_receiver.cpp # UART1 RX task, framing state machine, checksum, stats, link timeout
uart_receiver.cpp # Link receiver: UART1 framing task + processFrame() shared with ESP-NOW; dedupe, stats, config cache
espnow_receiver.cpp # ESP-NOW leg: STA mode, channel hopping while silent, feeds processFrame()
gauge_outputs.cpp # Patrol gauges: tach on IO7 (LEDC ch2), coolant PWM on IO8 (LEDC ch4), NVS-cached config
debug_monitor.cpp # shows/hides LVGL perf+mem monitors, mirrors A's debug_enabled flag
include/
config/lv_conf.h # LVGL 8.4.0 config (RGB565, dark theme, arc/label/led/meter widgets)
modules/uart_receiver.h, debug_monitor.h
modules/uart_receiver.h, espnow_receiver.h, gauge_outputs.h, debug_monitor.h
protocol/automotive_data.h # SHARED packet contract — copied from Controller A, must match its version
ui/ # SquareLine Studio exports (ui.c/h, screens/, components/, fonts/)
```
**DisplayInit** — `init()`, `update()`, `setBrightness(0–255)`, `getBrightness()`. Default brightness 128. `DISPLAY_RADIUS 120` defines the circular mask.
**UARTReceiver** — `init()`, `getStats()` (packets, checksum errors, framing errors, timeouts, bytes, last packet time), `isConnected(timeout_ms = 1000)`, `getTimeSinceLastPacket()`, `resetStats()`. The link is considered lost after 1000 ms without a valid packet; `loop()` shows a no-data state and hides sensor icons.
**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.
**EspNowReceiver** — `init()`, `tick()` (channel hopping: starts on `ESPNOW_CHANNEL`, sweeps 1–13 while silent, locks when frames arrive), `currentChannel()`.
**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)`, `isVisible()`. Driven by the `debug_enabled` byte in each packet, so Controller A's debug toggle controls B's overlays.
### UART packet (shared with Controller A)
`0xAA` · version `0x01` · length `0x12` · 18-byte `automotive_data_t` · XOR checksum · `0x55` = 23 bytes, 115200 8N1, 5 Hz, one direction A → B. The spec lives in the sibling repo at `docs/UART_PROTOCOL.md`; the struct in `include/protocol/automotive_data.h` must stay byte-identical to A's. When A changes the packet it bumps `PACKET_VERSION`; copy the header here and reject unexpected versions.
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` must stay byte-identical to A's; B rejects other versions and counts them.
> **Known drift (2026-09-21)**: A's and B's `gear_position_t` enums disagree above value 3 (B: 4 = Sport, 5 = Manual, 6–13 = M1–M8; A: 4–9 = M1–M6). Value 4 on the wire means different things on each end. Resolve before trusting the gear display. See `wiki/pages/controller-link.md`.
Warning thresholds in `main.cpp`: coolant 110 °C, engine oil 130 °C, gearbox oil 130 °C, battery below 11.0 V. Note `engine_oil_temp` has no real source on this engine (A reads 0xFF from CAN); expect it to stay invalid.
Alert thresholds live on A; B turns icons red from the `alerts` bits only. The gear label shows the engaged gear, or the target gear pulsing while `target != engaged`, and turns red on the gear-mismatch alert. `engine_oil_temp` has no source on this engine and stays invalid.
## Hardware-Specific Details
@@ -76,8 +80,10 @@ Warning thresholds in `main.cpp`: coolant 110 °C, engine oil 130 °C, gearbox o
| 43 / 44 | UART0 → CH343 USB bridge (debug console) — not available for the link |
| IO1 | UART1 RX from Controller A (left header, pin 4) |
| IO2 | UART1 TX — unused, link is receive-only |
| IO7 | Tachometer pulse output (GaugeOutputs, LEDC ch 2) |
| IO8 | Coolant gauge PWM output (GaugeOutputs, LEDC ch 4) |
**Header pinout** (USB-C at top): left 5V · GND · 3V3 · IO1 · IO2 · IO3 · IO4 · IO5; right IO14 · IO13 · IO12 · IO11 · IO10 · IO9 · IO8 · IO7. Free for new features: IO4, IO5, IO7–IO14 (IO3 is a strapping pin, avoid). IO7/IO8 are earmarked for the gauge outputs — see `wiki/pages/patrol-gauge-outputs.md`.
**Header pinout** (USB-C at top): left 5V · GND · 3V3 · IO1 · IO2 · IO3 · IO4 · IO5; right IO14 · IO13 · IO12 · IO11 · IO10 · IO9 · IO8 · IO7. Free for new features: IO4, IO5, IO9–IO14 (IO3 is a strapping pin, avoid). Gauge driver design and calibration notes: `wiki/pages/patrol-gauge-outputs.md`.
Pins are set in `src/modules/display_init.cpp` and `platformio.ini` (`-DUART_RX_PIN=1 -DUART_TX_PIN=2`). Older notes claiming backlight on GPIO 2 or 15, SPI on 10/11, or a header carrying IO35–IO42 were wrong and have been removed.
@@ -101,11 +107,12 @@ Pins are set in `src/modules/display_init.cpp` and `platformio.ini` (`-DUART_RX_
- **Blank display**: confirm the pin table above (backlight GPIO 20 is the usual culprit), try `cfg.freq_write = 40000000`, toggle `cfg.invert`. A direct LovyanGFX `fillScreen()` before LVGL init separates hardware from LVGL problems.
- **`lv_tick_inc() is not called`**: the tick handler lives in `DisplayInit::update()`; make sure `lvglTask` is running.
- **Out of memory**: raise `LV_MEM_SIZE` in `include/config/lv_conf.h` or move buffers to PSRAM.
- **No packets** (`Packets: 0`): TX→RX crossed? common ground? A's CAN toggle must be ON (its UART auto-starts with CAN). Framing errors with bytes arriving = baud or wiring; checksum errors = version/struct mismatch between the repos.
- **No packets**: common ground? A's CAN toggle must be ON (its link auto-starts with CAN). `ver=` counting up in the `[Link]` stats line = the two repos run different `PACKET_VERSION`s; framing errors with bytes arriving = baud or wiring. ESP-NOW `silent` with UART `alive` = B still hopping or A's radio on another channel.
- **Gauge outputs stay low**: check `[Gauges]` status line — `no-rpm` means A has no valid rpm (no CAN); use `cfg override rpm 2000` on A's console to test the tach without the car.
- **Last resort**: Waveshare demo `https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32-S3-LCD-1.3-Demo.zip` and schematic `https://files.waveshare.com/wiki/ESP32-S3-LCD-1.3/ESP32S3_1.3inch.pdf`.
## Important Notes
- This board is the **only** one of the two with free hardware-PWM GPIO; Controller A has none. Gauge driving belongs here.
- The wired link's physical layer is unresolved: A's GPIO 44 reaches its terminal block only through an RS485 transceiver. Check `wiki/pages/open-questions.md` #1 before changing wiring.
- Planned: a redundant wireless leg (BLE or ESP-NOW) alongside the wire — design notes in `wiki/pages/link-redundancy.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`.