From 5fe313b7fafb9e142083b9c514b9c709b03eda1e Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Mon, 21 Sep 2026 19:12:38 +0200 Subject: [PATCH] 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 --- CLAUDE.md | 33 +- include/modules/espnow_receiver.h | 36 ++ include/modules/gauge_outputs.h | 56 +++ include/modules/uart_receiver.h | 87 ++-- include/protocol/automotive_data.h | 672 ++++++++++++++++++++++++----- src/main.cpp | 297 +++++++------ src/modules/espnow_receiver.cpp | 90 ++++ src/modules/gauge_outputs.cpp | 227 ++++++++++ src/modules/uart_receiver.cpp | 386 +++++++++-------- wiki/.obsidian/workspace.json | 8 +- wiki/index.md | 9 +- wiki/log.md | 36 ++ wiki/pages/controller-link.md | 53 ++- wiki/pages/link-redundancy.md | 9 +- wiki/pages/open-questions.md | 20 +- wiki/pages/patrol-gauge-outputs.md | 77 +++- wiki/raw/temp_stage.cfd | Bin 0 -> 5394 bytes wiki/sources/temp-stage-cfd.md | 76 ++++ 18 files changed, 1658 insertions(+), 514 deletions(-) create mode 100644 include/modules/espnow_receiver.h create mode 100644 include/modules/gauge_outputs.h create mode 100644 src/modules/espnow_receiver.cpp create mode 100644 src/modules/gauge_outputs.cpp create mode 100644 wiki/raw/temp_stage.cfd create mode 100644 wiki/sources/temp-stage-cfd.md diff --git a/CLAUDE.md b/CLAUDE.md index 2e5384b..8f63b7b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`. diff --git a/include/modules/espnow_receiver.h b/include/modules/espnow_receiver.h new file mode 100644 index 0000000..0473584 --- /dev/null +++ b/include/modules/espnow_receiver.h @@ -0,0 +1,36 @@ +/** + * ESP-NOW Receiver Module (Controller B) + * + * 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. + * + * Channel discovery: A transmits on ESPNOW_CHANNEL unless it is associated to + * an access point. B listens on ESPNOW_CHANNEL first and, while it hears + * nothing, hops through channels 1..13 until frames arrive, then locks. + */ + +#ifndef ESPNOW_RECEIVER_H +#define ESPNOW_RECEIVER_H + +#include + +namespace EspNowReceiver { + +/** + * Bring the radio up in STA mode and register the receive callback. + * @return true if ESP-NOW is listening + */ +bool init(); + +/** + * Channel-hopping housekeeping. Call from loop(). + */ +void tick(); + +bool isReady(); +uint8_t currentChannel(); +uint32_t framesReceived(); + +} // namespace EspNowReceiver + +#endif // ESPNOW_RECEIVER_H diff --git a/include/modules/gauge_outputs.h b/include/modules/gauge_outputs.h new file mode 100644 index 0000000..56769b4 --- /dev/null +++ b/include/modules/gauge_outputs.h @@ -0,0 +1,56 @@ +/** + * Gauge Outputs Module (Controller B) + * + * Drives the Nissan Patrol cluster from the data Controller A sends: + * - tachometer: variable-frequency square wave on IO7 (LEDC timer 1) + * - coolant gauge: fixed-frequency PWM with variable duty on IO8 (LEDC timer 2) + * + * Everything tunable comes from link_config_t (pushed by A in CONFIG frames, + * cached in NVS so a reboot of B does not wait for A). Both outputs are held + * OFF while the link is down or the source value is invalid, unless A has set + * a calibration override. + * + * External driver stages are mandatory: 3.3 V logic drives neither gauge + * directly. See wiki/pages/patrol-gauge-outputs.md + */ + +#ifndef GAUGE_OUTPUTS_H +#define GAUGE_OUTPUTS_H + +#include +#include "protocol/automotive_data.h" + +namespace GaugeOutputs { + +#define GAUGE_TACH_PIN 7 +#define GAUGE_TEMP_PIN 8 + +/** + * Load the last config from NVS (defaults if none) and set up both LEDC channels + * with the outputs OFF. + */ +void init(); + +/** + * Apply a configuration received from A. Persists it to NVS when persist is true + * (overrides arrive unsaved by design: A does not persist them either). + */ +void applyConfig(const link_config_t& cfg, bool persist); + +link_config_t getConfig(); + +/** + * Recompute both outputs from the latest data. Call at the data rate (5 Hz). + * @param d latest automotive_data_t from A + * @param link_ok false when no valid frame has arrived within the link timeout + */ +void update(const automotive_data_t& d, bool link_ok); + +/** + * Print a one-line status (frequency, duty, source of each output) to Serial. + */ +void printStatus(); + +} // namespace GaugeOutputs + +#endif // GAUGE_OUTPUTS_H diff --git a/include/modules/uart_receiver.h b/include/modules/uart_receiver.h index f04f60a..828eeb8 100644 --- a/include/modules/uart_receiver.h +++ b/include/modules/uart_receiver.h @@ -1,15 +1,14 @@ /** - * UART Receiver Module for ESP32-S3-LCD-1.3 (Controller B) + * Link Receiver Module (Controller B) * - * Receives automotive data packets from Controller A (ESP32-S3-Touch-LCD-5B) - * via UART at 115200 baud, 5Hz update rate. + * Receives v2 frames from Controller A on two transports: + * - UART1 (byte stream, framed here with a state machine) + * - ESP-NOW (whole frames, delivered by EspNowReceiver) + * Both feed processFrame(). DATA frames are deduplicated on packet_id so a frame + * that arrives on both paths is applied once; CONFIG frames update the cached + * link_config_t and bump a sequence number the main loop watches. * - * Features: - * - State machine-based packet parsing - * - XOR checksum validation - * - Thread-safe data access - * - Connection monitoring and timeout detection - * - Error statistics tracking + * The namespace keeps its historical name; it is the link receiver for both paths. */ #ifndef UART_RECEIVER_H @@ -18,65 +17,63 @@ #include #include "protocol/automotive_data.h" +typedef enum { + LINK_SOURCE_NONE = 0, + LINK_SOURCE_UART = 1, + LINK_SOURCE_ESPNOW = 2 +} link_source_t; + namespace UARTReceiver { -/** - * @brief UART RX statistics structure - */ typedef struct { - uint32_t packets_received; // Total valid packets received - uint32_t checksum_errors; // Packets with invalid checksum - uint32_t framing_errors; // Packets with framing errors - uint32_t timeout_errors; // Connection timeout events - uint32_t last_packet_time; // millis() when last valid packet received - uint32_t bytes_received; // Total bytes received + uint32_t packets_received; // DATA frames applied (after dedupe) + uint32_t packets_uart; // valid DATA frames seen on UART + uint32_t packets_espnow; // valid DATA frames seen on ESP-NOW + uint32_t duplicates; // DATA frames dropped as already applied + uint32_t config_received; // CONFIG frames accepted + uint32_t checksum_errors; + uint32_t framing_errors; + uint32_t version_errors; // frames from a different PACKET_VERSION + uint32_t timeout_errors; + uint32_t last_packet_time; // millis() of the last applied DATA frame + uint32_t last_uart_time; // millis() of the last valid UART frame + uint32_t last_espnow_time; // millis() of the last valid ESP-NOW frame + uint32_t bytes_received; // UART bytes + link_source_t last_source; // transport of the last applied DATA frame } uart_rx_stats_t; /** - * @brief Initialize UART receiver module - * - * Initializes Serial1 hardware and creates FreeRTOS reception task on Core 0. - * - * @return true if initialization successful, false otherwise + * Create the mutex and the UART1 receive task on Core 0. */ bool init(); /** - * @brief Get the latest received automotive data - * - * Thread-safe access to the most recently received valid packet. - * - * @return Copy of the latest automotive_data_t structure + * Validate and apply one complete frame (start..end). Safe to call from the + * ESP-NOW receive callback or the UART task. */ -automotive_data_t getLatestData(); +void processFrame(const uint8_t* frame, size_t len, link_source_t source); -/** - * @brief Get UART reception statistics - * - * @return Copy of current RX statistics - */ +automotive_data_t getLatestData(); uart_rx_stats_t getStats(); /** - * @brief Check if connection is active - * - * Returns true if a valid packet was received within the last timeout period. - * - * @param timeout_ms Timeout in milliseconds (default: 1000ms) - * @return true if connection is active, false if timed out + * True if a DATA frame was applied within timeout_ms, on either transport. */ bool isConnected(uint32_t timeout_ms = 1000); /** - * @brief Reset statistics counters + * True if the given transport delivered a valid frame within timeout_ms. */ -void resetStats(); +bool isSourceAlive(link_source_t source, uint32_t timeout_ms = 1000); /** - * @brief Get time since last valid packet in milliseconds - * - * @return Milliseconds since last packet, or UINT32_MAX if no packets received + * Latest CONFIG payload from A (defaults until one arrives) and a sequence + * number that increments each time a new one is accepted. */ +link_config_t getConfig(); +uint32_t getConfigSeq(); + +void resetStats(); uint32_t getTimeSinceLastPacket(); } // namespace UARTReceiver diff --git a/include/protocol/automotive_data.h b/include/protocol/automotive_data.h index 989ee5b..e81604e 100644 --- a/include/protocol/automotive_data.h +++ b/include/protocol/automotive_data.h @@ -1,133 +1,368 @@ /** * automotive_data.h * - * Shared data structure and protocol definitions for automotive monitoring system - * ESP32-S3-LCD-5B (Controller A) -> ESP32-S3-LCD-1.3 (Controller B) communication + * Shared wire contract between Controller A (ESP32-S3-Touch-LCD-5B) and + * Controller B (ESP32-S3-LCD-1.3). * - * This header defines the data structure for 6 automotive sensor values and the - * simple packet framing protocol for UART transmission at 115200 baud. + * 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. + * + * v2 (2026-09-21): + * - typed frames: DATA (sensor snapshot, 5 Hz) and CONFIG (tunables, on + * change + every CONFIG_RESEND_MS) + * - gear split into lever (P/R/N/D/S/M) + target/engaged gear nibbles + * - engine RPM + * - alert bitmap decided on A (thresholds live on A, B only renders) + * - link_config_t: Patrol gauge calibration + alert thresholds, edited on A, + * executed on B (tach + coolant PWM outputs) + * - the same frames go out on UART1 and ESP-NOW; B dedupes by packet_id */ #ifndef _AUTOMOTIVE_DATA_H #define _AUTOMOTIVE_DATA_H #include +#include +#include +#include +#include // ============================================================================ -// UART PROTOCOL CONFIGURATION +// LINK CONFIGURATION // ============================================================================ -// Communication parameters (hardware-independent) -#define UART_BAUD_RATE 115200 // Reliable automotive-grade baud rate -#define UART_UPDATE_RATE_MS 200 // 5Hz transmission rate +#define UART_BAUD_RATE 115200 // UART1 on both ends +#define UART_UPDATE_RATE_MS 200 // DATA frame period (5 Hz) +#define CONFIG_RESEND_MS 5000 // CONFIG frame re-broadcast period +#define ESPNOW_CHANNEL 1 // Wi-Fi channel A transmits ESP-NOW on + // (B hops until it hears A, then locks) -// NOTE: UART pin assignments (TX/RX) are controller-specific and defined in: -// - Controller A (5B): uart_manager.cpp -// - Controller B (1.3): uart_receiver.cpp - -// Packet framing bytes -#define PACKET_START_BYTE 0xAA // Start of packet marker -#define PACKET_END_BYTE 0x55 // End of packet marker -#define PACKET_VERSION 0x01 // Protocol version for future compatibility - -// Packet structure offsets -#define PACKET_MIN_SIZE 8 // Start(1) + Version(1) + Length(1) + Data(min 1) + Checksum(1) + End(1) -#define PACKET_MAX_SIZE 64 // Maximum packet size to prevent buffer overruns +// NOTE: UART pin assignments are controller-specific: +// - Controller A (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B) +// - Controller B (1.3): platformio.ini (RX IO1) // ============================================================================ -// AUTOMOTIVE DATA STRUCTURE +// FRAME FORMAT (identical on UART and ESP-NOW) +// ============================================================================ +// +// 0xAA | version | type | length | payload[length] | checksum | 0x55 +// +// checksum = XOR of version, type, length and every payload byte. +// +#define PACKET_START_BYTE 0xAA +#define PACKET_END_BYTE 0x55 +#define PACKET_VERSION 0x02 + +#define PACKET_TYPE_DATA 0x01 // payload = automotive_data_t +#define PACKET_TYPE_CONFIG 0x02 // payload = link_config_t + +#define PACKET_HEADER_SIZE 4 // start, version, type, length +#define PACKET_TRAILER_SIZE 2 // checksum, end +#define PACKET_MAX_PAYLOAD 64 +#define PACKET_MAX_SIZE (PACKET_HEADER_SIZE + PACKET_MAX_PAYLOAD + PACKET_TRAILER_SIZE) + +// ============================================================================ +// GEAR // ============================================================================ -// Gear position enumeration (matches UART protocol specification) +// What the driver selected (0x1D2 byte 0 + byte 4 mode). This is the wire enum. typedef enum { - GEAR_PARK = 0, // Park - transmission locked - GEAR_REVERSE = 1, // Reverse gear - GEAR_NEUTRAL = 2, // Neutral - no gear engaged - GEAR_DRIVE = 3, // Drive - automatic mode - GEAR_SPORT = 4, // Sport mode - GEAR_MANUAL = 5, // Manual/Sequential mode - GEAR_MANUAL_1 = 6, // Manual 1st gear - GEAR_MANUAL_2 = 7, // Manual 2nd gear - GEAR_MANUAL_3 = 8, // Manual 3rd gear - GEAR_MANUAL_4 = 9, // Manual 4th gear - GEAR_MANUAL_5 = 10, // Manual 5th gear - GEAR_MANUAL_6 = 11, // Manual 6th gear - GEAR_MANUAL_7 = 12, // Manual 7th gear - GEAR_MANUAL_8 = 13, // Manual 8th gear - GEAR_ERROR = 14 // Transmission fault/unknown + LEVER_PARK = 0, + LEVER_REVERSE = 1, + LEVER_NEUTRAL = 2, + LEVER_DRIVE = 3, // D detent, automatic mode + LEVER_SPORT = 4, // D detent, Sport mode + LEVER_MANUAL = 5, // D detent, Manual mode + LEVER_UNKNOWN = 0xFF +} gear_lever_t; + +// Controller A's internal gear enum (CAN decode helpers below use it). Not on +// the wire any more - B never sees it. +typedef enum { + GEAR_PARK = 0, + GEAR_REVERSE = 1, + GEAR_NEUTRAL = 2, + GEAR_DRIVE = 3, + GEAR_MANUAL_1 = 4, + GEAR_MANUAL_2 = 5, + GEAR_MANUAL_3 = 6, + GEAR_MANUAL_4 = 7, + GEAR_MANUAL_5 = 8, + GEAR_MANUAL_6 = 9, + GEAR_UNKNOWN = 0xFF } gear_position_t; -// Main automotive data structure (packed for efficient transmission) +// ============================================================================ +// DATA FRAME PAYLOAD +// ============================================================================ + typedef struct __attribute__((packed)) { - // Identification and versioning - uint8_t packet_id; // Incremental packet ID for debugging - uint32_t timestamp_ms; // Milliseconds since boot - - // Sensor data (6 monitored values) - uint8_t gear_position; // Current gear (see gear_position_t enum) - int16_t gearbox_oil_temp; // Gearbox oil temperature in 0.1°C (-3276.8 to +3276.7°C) - int16_t engine_oil_temp; // Engine oil temperature in 0.1°C - int16_t coolant_temp; // Engine coolant temperature in 0.1°C - uint16_t battery_voltage; // Battery voltage in 0.01V (0 to 655.35V) - uint16_t fault_codes; // Bitmap of active fault codes (16 possible codes) - - // Data validity flags (1 bit per sensor) - uint8_t valid_flags; // Bit 0: gear, Bit 1: gearbox temp, etc. - - // Debug mode flag (for Controller B to enable/disable monitors) - uint8_t debug_enabled; // 0 = debug off, 1 = debug on + uint8_t packet_id; // rolling counter; B dedupes UART vs ESP-NOW copies on it + uint32_t timestamp_ms; // A's millis() when the frame was built + uint8_t gear_lever; // gear_lever_t + uint8_t gear_nibbles; // high nibble = gearbox TARGET gear (0x0BA), + // low nibble = ENGAGED gear (0x1D2 byte 1); + // 0 = none / P / R / N, 1..6 = forward gear. + // target != engaged => a shift is in progress + uint16_t engine_rpm; // 1/min (0x0AA) + int16_t gearbox_oil_temp; // 0.1 degC + int16_t engine_oil_temp; // 0.1 degC (no source on this M57N; stays invalid) + int16_t coolant_temp; // 0.1 degC + uint16_t battery_voltage; // 0.01 V + uint16_t alerts; // ALERT_* bitmap, decided on A + uint8_t valid_flags; // VALID_FLAG_* bitmap + uint8_t debug_enabled; // 0/1: B mirrors A's debug overlay toggle } automotive_data_t; -// Size of the data structure #define AUTOMOTIVE_DATA_SIZE sizeof(automotive_data_t) -// Valid flags bit positions +// valid_flags #define VALID_FLAG_GEAR_POS (1 << 0) #define VALID_FLAG_GEARBOX_TEMP (1 << 1) #define VALID_FLAG_ENGINE_TEMP (1 << 2) #define VALID_FLAG_COOLANT_TEMP (1 << 3) #define VALID_FLAG_BATTERY_VOLT (1 << 4) -#define VALID_FLAG_FAULT_CODES (1 << 5) +#define VALID_FLAG_ALERTS (1 << 5) +#define VALID_FLAG_RPM (1 << 6) + +// alerts - set by A from its thresholds (link_config_t) and CAN status bits. +// These are OUR derived alerts, not DDE DTCs (fault codes are not broadcast on +// this bus; see wiki/pages/can-id-candidates.md). +#define ALERT_GEAR_MISMATCH (1 << 0) // lever (0x1D2) vs gearbox target (0x0BA) disagree +#define ALERT_COOLANT_HOT (1 << 1) // coolant_temp >= coolant_hot_c +#define ALERT_GEARBOX_HOT (1 << 2) // gearbox_oil_temp >= gearbox_hot_c +#define ALERT_GEARBOX_COOLING (1 << 3) // the box's own cooling demand (0x0B5 ST_OTMP_GRB >= 1) +#define ALERT_BATTERY_LOW (1 << 4) // battery_voltage < battery_low_x100 + +// Severity ranking for B's display (highest wins): red alarms first. +#define ALERTS_RED (ALERT_COOLANT_HOT | ALERT_GEARBOX_HOT | ALERT_GEAR_MISMATCH | ALERT_BATTERY_LOW) +#define ALERTS_AMBER (ALERT_GEARBOX_COOLING) // ============================================================================ -// CAN BUS ID MAPPINGS (Placeholder - User will provide real IDs) -// ============================================================================ - -// Standard OBD-II PIDs (example placeholders) -// User needs to replace these with actual CAN message IDs for their vehicle -#define CAN_ID_GEAR_POSITION 0x0C0 // Placeholder - vehicle specific -#define CAN_ID_GEARBOX_TEMP 0x5C // Placeholder - typically proprietary -#define CAN_ID_ENGINE_OIL_TEMP 0x5C // Placeholder - not standard OBD-II -#define CAN_ID_COOLANT_TEMP 0x05 // Standard OBD-II PID (if using OBD-II) -#define CAN_ID_BATTERY_VOLTAGE 0x42 // Standard OBD-II PID for system voltage -#define CAN_ID_FAULT_CODES 0x01 // Standard OBD-II PID for DTCs - -// Extended CAN IDs (29-bit) if needed -#define USE_EXTENDED_CAN_IDS false // Set to true for 29-bit CAN IDs - -// ============================================================================ -// PACKET STRUCTURE FOR UART TRANSMISSION +// CONFIG FRAME PAYLOAD - tunables edited on A, executed on B // ============================================================================ typedef struct __attribute__((packed)) { - uint8_t start_byte; // PACKET_START_BYTE (0xAA) - uint8_t version; // Protocol version - uint8_t length; // Length of data payload - automotive_data_t data; // Actual sensor data - uint8_t checksum; // XOR checksum of all bytes except start/end - uint8_t end_byte; // PACKET_END_BYTE (0x55) -} uart_packet_t; + uint8_t cfg_version; // bumped by A on every change; B applies when it changes + + // --- tachometer output (B: IO7, LEDC) --- + uint8_t tach_ppr; // pulses per engine revolution the cluster expects + int8_t tach_trim_pct; // fine trim, -50..+50 % + uint16_t tach_min_hz; // 0 = no lower clamp + uint16_t tach_max_hz; // 0 = no upper clamp + + // --- coolant gauge output (B: IO8, LEDC, 8-bit duty) --- + uint16_t temp_pwm_hz; // PWM frequency + uint16_t temp_slope_x100; // duty per degC x100 (150 = 1.5 duty/degC) + int16_t temp_offset; // duty at 0 degC (may be negative) + int16_t temp_min_c; // output held OFF below this coolant temperature + uint8_t temp_duty_max; // clamp (255 = full scale) + + // --- enables / calibration override --- + uint8_t out_enable; // OUT_ENABLE_* bits + uint8_t override_mode; // OVERRIDE_* bits: force fixed outputs from A's console + uint16_t override_rpm; // used when OVERRIDE_TACH set + uint8_t override_duty; // used when OVERRIDE_TEMP set + + // --- alert thresholds (evaluated on A; sent so B can show them) --- + int16_t coolant_hot_c; // degC + int16_t gearbox_hot_c; // degC + uint16_t battery_low_x100; // 0.01 V +} link_config_t; + +#define OUT_ENABLE_TACH (1 << 0) +#define OUT_ENABLE_TEMP (1 << 1) +#define OVERRIDE_TACH (1 << 0) +#define OVERRIDE_TEMP (1 << 1) + +// Defaults. Tach: user's figure for the Patrol cluster. Temp: the duty law +// recovered from the user's earlier CANNY program (duty = 1.5*T + 50 on 0..255, +// off below 40 degC); 1 kHz is a placeholder until the old unit is measured. +// See ESP32-S3-LCD-1.3/wiki/pages/patrol-gauge-outputs.md +static inline void link_config_defaults(link_config_t* c) { + memset(c, 0, sizeof(*c)); + c->cfg_version = 1; + c->tach_ppr = 4; + c->tach_trim_pct = 0; + c->tach_min_hz = 0; + c->tach_max_hz = 600; + c->temp_pwm_hz = 1000; + c->temp_slope_x100 = 150; + c->temp_offset = 50; + c->temp_min_c = 40; + c->temp_duty_max = 255; + c->out_enable = OUT_ENABLE_TACH | OUT_ENABLE_TEMP; + c->override_mode = 0; + c->override_rpm = 0; + c->override_duty = 0; + c->coolant_hot_c = 100; + c->gearbox_hot_c = 130; + c->battery_low_x100 = 1100; +} // ============================================================================ -// HELPER FUNCTIONS +// CAN BUS ID MAPPINGS (BMW-Specific) +// ============================================================================ + +// BMW E60/E65 PT-CAN, 500 kbps. Every ID below is an 11-bit STANDARD frame and +// has been seen live on the actual swap bus. Decodes cross-checked against +// HeinrichG-V12/E65_ReverseEngineering (per-ID DBC docs) AND our own captures. +// Full evidence + confidence labels: wiki/pages/can-id-candidates.md +// +// The original map (0x4F/0x55/0x201/0x1001/0x101F) was placeholder junk — those +// IDs were verified ABSENT from the bus 2026-07-15. Do not resurrect them. + +// --- 0x1D0 "Engine Data" (DME/DDE, DLC 8, 100 ms) -------------------------- +#define CAN_ID_ENGINE_DATA 0x1D0 +#define CAN_BYTE_COOLANT_TEMP 0 // TEMP_ENG: °C = raw - 48 (verified) +#define CAN_BYTE_ENGINE_OIL_TEMP 1 // TEMP_EOI: °C = raw - 48 (reads 0xFF here — sensor not populated on this M57N) +#define CAN_BYTE_ENGINE_STATUS 2 // bits 4-5 = ST_ENGINE_RUN +#define ENGINE_TEMP_OFFSET 48 // subtract from raw + +// ST_ENGINE_RUN (byte 2, bits 4-5) +#define ENGINE_RUN_OFF 0 +#define ENGINE_RUN_STARTING 1 +#define ENGINE_RUN_RUNNING 2 +#define ENGINE_RUN_INVALID 3 + +// --- 0x0B5 "Torque Request EGS" (EGS, DLC 8, 10 ms) ------------------------ +#define CAN_ID_TORQUE_EGS 0x0B5 +#define CAN_BYTE_GEARBOX_TEMP 7 // TEMP_GRB: °C = raw - 40 (verified two ways) +#define GEARBOX_TEMP_OFFSET 40 // NOT 0, NOT +40 — see wiki; a 40 °C error either way +#define CAN_BYTE_GEARBOX_COOL 4 // bits 38-39 = ST_OTMP_GRB (cooling demand) + +// ST_OTMP_GRB — the box's own overheat opinion (better than thresholding temp) +#define GEARBOX_COOL_NONE 0 +#define GEARBOX_COOL_STAGE1 1 +#define GEARBOX_COOL_STAGE2 2 +#define GEARBOX_COOL_INVALID 3 + +// --- 0x1D2 "Display Gearbox Data" (EGS, DLC 6, 200 ms) --------------------- +// Our decode is AHEAD of the published source here: the E65 repo lists this ID +// with an empty signal table. Byte 1 and byte 4 are our own work. +#define CAN_ID_GEAR_DISPLAY 0x1D2 +#define CAN_BYTE_GEAR_LEVER 0 // whole-byte lever code +#define CAN_BYTE_GEAR_ENGAGED 1 // (raw >> 4) - 4 = gear 1..6; 0x0F = none +#define CAN_BYTE_GEAR_MODE 4 // 0xF0 auto / 0xF1 Sport / 0xF2 Manual + +// Byte 0 lever codes (verified — every code matches the documented table) +#define GEAR_CODE_PARK 0xE1 +#define GEAR_CODE_REVERSE 0xD2 +#define GEAR_CODE_NEUTRAL 0xB4 +#define GEAR_CODE_DRIVE 0x78 // D *and* S/M — the side-gate is physically the same detent + +// Byte 4 mode codes. NOTE: 0xF2 is a PERSISTENT mode, not a downshift event — +// it holds across gears 2..6. The +/- nudges have no distinct code; the first +// tap simply promotes Sport -> Manual. +#define GEAR_MODE_DRIVE_AUTO 0xF0 +#define GEAR_MODE_SPORT 0xF1 +#define GEAR_MODE_MANUAL 0xF2 + +#define GEAR_ENGAGED_NONE 0x0F // byte 1 value in P/R/N — and in R even when engaged + +// --- 0x0BA gearbox state (EGS, DLC 8, 20 ms) ------------------------------- +// The ONLY source of engaged reverse: 0x1D2 byte 1 stays 0x0F in R. +#define CAN_ID_GEARBOX_STATE 0x0BA +#define CAN_BYTE_GEARBOX_TARGET 0 // low nibble = ST_GR_GRB + +// ST_GR_GRB (byte 0, low nibble). Every value 1/2/3/5..0xA observed live in the +// 2026-07-17 drive capture. Value 4 remains unaccounted for. +// This nibble alone is a COMPLETE gear source: P/R/N plus 1st..6th, reverse +// included. 0x1D2 is still needed for the lever and the D/S/M mode, which this +// message does not carry. +#define GRB_TARGET_NEUTRAL 1 +#define GRB_TARGET_REVERSE 2 +#define GRB_TARGET_PARK 3 +#define GRB_TARGET_GEAR1 5 // ..0xA = 6th +#define GRB_TARGET_GEAR6 0xA +#define GRB_TARGET_INVALID 0xF + +// Byte 0 bits 6-7: ST_CCLT, torque converter lockup clutch. Relevant to any +// turbine-vs-engine ratio test: a CLOSED clutch makes turbine == engine exactly, +// so ratio ~1.0 at road speed means "locked up", not "not engaged". +#define CAN_BYTE_CONVERTER_CLUTCH 0 +#define CCLT_DISENGAGED 0 +#define CCLT_CONTROLLED 1 +#define CCLT_CLOSED 2 +#define CCLT_INVALID 3 + +// Bytes 3-4: output shaft speed, 16-bit little-endian. UNDOCUMENTED in every +// source. Identification is verified (rises monotonically 1st->6th under drive, +// zero whenever the output is held, including engaged-in-D). This is the +// project's only road-speed signal — there is no DSC/wheel-speed module on this +// bus. +// +// SCALING IS UNSETTLED. The upshift-schedule test earlier suggested raw * 0.125 +// = rpm, but a direct Launch reference reading (128 rpm at raw 1192, 2026-07-17) +// points to ~0.107 instead and contradicts 0.125. One eyeballed point isn't a +// calibration, so this stays RAW COUNTS until a multi-point Launch sweep fixes +// the factor. Do not convert to a physical unit here. +// See wiki/pages/driveline-speed-signals.md +#define CAN_BYTE_OUTPUT_SHAFT_L 3 +#define CAN_BYTE_OUTPUT_SHAFT_H 4 + +// PROVISIONAL output-shaft factor, from a SINGLE Launch reference reading +// (128 rpm at raw 1192, 2026-07-17) taken through a known zero. Good enough to +// put an approximate rpm on the display (±~10%), NOT good enough to trust for +// anything computed. Replace once a multi-point Launch sweep gives a real fit. +// rpm ~= raw * 1074 / 10000 +#define OUTPUT_SHAFT_RPM_NUM 1074 +#define OUTPUT_SHAFT_RPM_DEN 10000 + +static inline uint16_t can_output_shaft_rpm(uint16_t raw) { + return (uint16_t)(((uint32_t)raw * OUTPUT_SHAFT_RPM_NUM) / OUTPUT_SHAFT_RPM_DEN); +} + +// --- 0x1A2 turbine speed (EGS, DLC 4, 20 ms) ------------------------------- +// Gearbox INPUT speed. Physically proves engagement: free-spins at ~engine +// speed in P/N, collapses to ~0 when the box engages against a held output. +#define CAN_ID_TURBINE_SPEED 0x1A2 +#define CAN_BYTE_TURBINE_L 0 +#define CAN_BYTE_TURBINE_H 1 + +// --- 0x0A8 "Torque 1" (DME/DDE, DLC 8, 10 ms) ------------------------------ +// TORQ_AVL = torque the engine has AVAILABLE/is delivering. (0x0AA's TORQ_DVCH +// is driver DEMAND — same bit layout, so both read ~27 Nm at idle, but they +// diverge under load. This is the one to display as "engine torque".) +#define CAN_ID_TORQUE_1 0x0A8 +#define CAN_BYTE_TORQUE_L 1 // TORQ_AVL low (byte 1) — see can_to_torque_x10 +#define CAN_BYTE_TORQUE_H 2 // TORQ_AVL high (byte 2) + +// --- 0x0AA "Torque 3" (DME/DDE, DLC 8, 10 ms) ------------------------------ +#define CAN_ID_TORQUE_3 0x0AA +#define CAN_BYTE_PEDAL_POS 3 // ANG_ACPD: % = raw * 0.39063 +#define CAN_BYTE_RPM_L 4 // RPM_ENG: 1/min = raw16 * 0.25 +#define CAN_BYTE_RPM_H 5 +#define CAN_BYTE_CRUISE_STATE 6 // low nibble = ST_CLCTR_V + +// --- 0x3B4 "Power Management Battery Voltage" (DLC 8, 5 s) ----------------- +#define CAN_ID_BATTERY_VOLTAGE 0x3B4 +#define CAN_BYTE_BATTERY_VOLT_L 0 // U_BT: 12-bit little-endian, V = raw * 0.015 +#define CAN_BYTE_BATTERY_VOLT_H 1 // low nibble only (high nibble = ST_BTSW) +#define BATTERY_RAW_INVALID 0xFFF // U_BT's not-available marker + +// Byte 2 low nibble. The E65 repo calls this ST_ENGINE_RUN and the E60 VFL sheet +// calls it an engine-running flag with 0x09=running — BOTH ARE WRONG FOR US. +// Verified on this bus 2026-07-17: it tracks IGNITION, inverted, and does not +// move when the engine starts. Use 0x1D0 ST_ENGINE_RUN for engine state. +// Although 0x3B4 is nominally a 5 s periodic message, it ALSO transmits +// on-change: the ignition nibble flips instantly when the key toggles (user- +// verified), so an ignition-driven reset is effectively immediate. +#define CAN_BYTE_IGNITION 2 +#define IGNITION_ON 0x00 +#define IGNITION_OFF 0x09 + +// All IDs are 11-bit standard frames — the extended-ID assumption came from the +// bogus 0x1001/0x101F placeholders and is dead. +#define USE_EXTENDED_CAN_IDS false + +// ============================================================================ +// FRAME HELPERS // ============================================================================ /** - * Calculate XOR checksum for data buffer - * @param data Pointer to data buffer - * @param length Length of data to checksum - * @return XOR checksum value + * XOR checksum over a byte range. */ static inline uint8_t calculate_checksum(const uint8_t* data, size_t length) { uint8_t checksum = 0; @@ -138,40 +373,257 @@ static inline uint8_t calculate_checksum(const uint8_t* data, size_t length) { } /** - * Validate packet checksum - * @param packet Pointer to complete packet - * @return true if checksum is valid, false otherwise + * Build a complete frame (start..end) into out, which must hold PACKET_MAX_SIZE. + * @return total frame length, or 0 if the payload is too large. */ -static inline bool validate_packet(const uart_packet_t* packet) { - if (packet->start_byte != PACKET_START_BYTE || - packet->end_byte != PACKET_END_BYTE) { - return false; +static inline size_t frame_build(uint8_t type, const void* payload, uint8_t len, uint8_t* out) { + if (len > PACKET_MAX_PAYLOAD) return 0; + out[0] = PACKET_START_BYTE; + out[1] = PACKET_VERSION; + out[2] = type; + out[3] = len; + memcpy(&out[PACKET_HEADER_SIZE], payload, len); + out[PACKET_HEADER_SIZE + len] = calculate_checksum(&out[1], 3 + len); + out[PACKET_HEADER_SIZE + len + 1] = PACKET_END_BYTE; + return PACKET_HEADER_SIZE + len + PACKET_TRAILER_SIZE; +} + +typedef enum { + FRAME_OK = 0, + FRAME_ERR_SIZE, // shorter than a minimal frame, or length field disagrees + FRAME_ERR_MARKERS, // start/end byte wrong + FRAME_ERR_VERSION, // other side runs a different PACKET_VERSION + FRAME_ERR_CHECKSUM, + FRAME_ERR_TYPE // unknown type, or length doesn't match the type's payload +} frame_status_t; + +/** + * Validate a complete frame and locate its payload. + */ +static inline frame_status_t frame_parse(const uint8_t* f, size_t n, + uint8_t* type, const uint8_t** payload, uint8_t* len) { + if (n < PACKET_HEADER_SIZE + PACKET_TRAILER_SIZE) return FRAME_ERR_SIZE; + if (f[0] != PACKET_START_BYTE || f[n - 1] != PACKET_END_BYTE) return FRAME_ERR_MARKERS; + uint8_t l = f[3]; + if (n != (size_t)(PACKET_HEADER_SIZE + l + PACKET_TRAILER_SIZE)) return FRAME_ERR_SIZE; + if (f[1] != PACKET_VERSION) return FRAME_ERR_VERSION; + if (calculate_checksum(&f[1], 3 + l) != f[PACKET_HEADER_SIZE + l]) return FRAME_ERR_CHECKSUM; + uint8_t t = f[2]; + if (t == PACKET_TYPE_DATA) { + if (l != sizeof(automotive_data_t)) return FRAME_ERR_TYPE; + } else if (t == PACKET_TYPE_CONFIG) { + if (l != sizeof(link_config_t)) return FRAME_ERR_TYPE; + } else { + return FRAME_ERR_TYPE; } + *type = t; + *payload = &f[PACKET_HEADER_SIZE]; + *len = l; + return FRAME_OK; +} - // Calculate checksum over version, length, and data - size_t checksum_size = 2 + packet->length; // version(1) + length(1) + data(length) - uint8_t calculated = calculate_checksum((uint8_t*)&packet->version, checksum_size); +// ============================================================================ +// GEAR HELPERS (wire enum) +// ============================================================================ - return (calculated == packet->checksum); +static inline char gear_lever_char(uint8_t lever) { + switch (lever) { + case LEVER_PARK: return 'P'; + case LEVER_REVERSE: return 'R'; + case LEVER_NEUTRAL: return 'N'; + case LEVER_DRIVE: return 'D'; + case LEVER_SPORT: return 'S'; + case LEVER_MANUAL: return 'M'; + default: return '-'; + } +} + +static inline uint8_t gear_target(uint8_t nibbles) { return (uint8_t)(nibbles >> 4); } +static inline uint8_t gear_engaged(uint8_t nibbles) { return (uint8_t)(nibbles & 0x0F); } +static inline bool gear_shifting(uint8_t nibbles) { + uint8_t t = gear_target(nibbles), e = gear_engaged(nibbles); + return (t != 0 && e != 0 && t != e); +} + +/** + * "P" / "R" / "N", or letter + gear number in the D detent ("D3", "S4", "M2"). + * @param number gear number to show (caller picks engaged or target) + */ +static inline void gear_compose(uint8_t lever, uint8_t number, char* out, size_t n) { + char c = gear_lever_char(lever); + if ((lever == LEVER_DRIVE || lever == LEVER_SPORT || lever == LEVER_MANUAL) && number >= 1 && number <= 6) { + snprintf(out, n, "%c%u", c, number); + } else { + snprintf(out, n, "%c", c); + } } /** * Convert temperature from CAN format to internal format * @param can_value Raw CAN bus value - * @param offset Temperature offset (usually -40 for automotive) + * @param offset Value to SUBTRACT from raw (48 for 0x1D0 engine temps, 40 for 0x0B5) * @return Temperature in 0.1°C units */ -static inline int16_t can_to_temperature(uint8_t can_value, int16_t offset = -40) { - return (int16_t)((can_value + offset) * 10); // Convert to 0.1°C units +static inline int16_t can_to_temperature(uint8_t can_value, int16_t offset) { + return (int16_t)(((int16_t)can_value - offset) * 10); } /** - * Convert voltage from CAN format to internal format - * @param can_value Raw CAN bus value (typically in 0.1V) + * Extract the raw 12-bit U_BT field from a 0x3B4 frame. + * The high nibble of byte 1 is ST_BTSW, NOT voltage — mask it off or you'll read + * ~4x too high. + * @param d Payload of a 0x3B4 frame (needs DLC >= 2) + * @return Raw 12-bit value; BATTERY_RAW_INVALID (0xFFF) means "not available" + */ +static inline uint16_t can_battery_raw(const uint8_t* d) { + return (uint16_t)(((d[CAN_BYTE_BATTERY_VOLT_H] & 0x0F) << 8) | d[CAN_BYTE_BATTERY_VOLT_L]); +} + +/** + * Decode battery voltage from a 0x3B4 frame. + * U_BT is 12-bit little-endian, factor 0.015 V — i.e. 0.01 V units = raw * 1.5. + * (Source example: raw 0x3D9 = 985 -> 14.775 V.) + * + * CAVEAT: on this bus the field reads BATTERY_RAW_INVALID almost always — the + * Power Module appears not to be retained in the swap. Check can_battery_raw() + * against BATTERY_RAW_INVALID before calling this; 0xFFF would otherwise decode + * to a confident-looking 61 V. The factor itself is also unconfirmed against a + * meter (0.015 here vs ~0.0147 implied by the E60 VFL sheet). + * See wiki/pages/can-id-candidates.md. + * + * @param d Payload of a 0x3B4 frame (needs DLC >= 2) * @return Voltage in 0.01V units */ -static inline uint16_t can_to_voltage(uint16_t can_value) { - return can_value * 10; // Convert 0.1V to 0.01V units +static inline uint16_t can_to_voltage(const uint8_t* d) { + return (uint16_t)((can_battery_raw(d) * 3) / 2); // raw * 0.015 V -> 0.01 V units +} + +/** + * Decode engine RPM from a 0x0AA frame. RPM_ENG = raw16 (Intel) * 0.25. + * @param d Payload of a 0x0AA frame (needs DLC >= 6) + */ +static inline uint16_t can_to_rpm(const uint8_t* d) { + uint16_t raw = (uint16_t)((d[CAN_BYTE_RPM_H] << 8) | d[CAN_BYTE_RPM_L]); + return (uint16_t)(raw / 4); +} + +/** + * Decode available engine torque (TORQ_AVL) from a 0x0A8 frame. + * + * The field is a SIGNED 12-bit value at bits 12-23, factor 0.5 Nm. The user's + * spreadsheet formula (D2*256 + D1)/32 lands on the same number — algebraically + * (D2<<8|D1)/32 == ((D2<<4)|(D1>>4)) * 0.5 — but it sweeps D1's low nibble into + * the result, and those four bits are ALIV_TORQ_1_DME (the alive counter), not + * torque. That adds up to ~0.5 Nm of jitter. We mask it off and sign-extend so + * overrun/braking (negative torque) reads correctly. Verified against the repo's + * 0x0A8 worked example: C7 08 03 00 ... -> 24 Nm, with ALIV=8 in D1's low nibble. + * + * @param d Payload of a 0x0A8 frame (needs DLC >= 3) + * @return Torque in 0.1 Nm units, signed + */ +static inline int16_t can_to_torque_x10(const uint8_t* d) { + uint16_t raw12 = (uint16_t)((d[CAN_BYTE_TORQUE_H] << 4) | (d[CAN_BYTE_TORQUE_L] >> 4)); + int16_t s = (raw12 & 0x800) ? (int16_t)(raw12 | 0xF000) // sign-extend 12->16 bit + : (int16_t)raw12; + return (int16_t)(s * 5); // * 0.5 Nm, expressed in 0.1 Nm units +} + +/** + * Decode gearbox turbine (input) speed from a 0x1A2 frame. + * RPM_GRB_TURB = raw16 (Intel) * 0.125 + 6. + * @param d Payload of a 0x1A2 frame (needs DLC >= 2) + */ +static inline uint16_t can_to_turbine_rpm(const uint8_t* d) { + uint16_t raw = (uint16_t)((d[CAN_BYTE_TURBINE_H] << 8) | d[CAN_BYTE_TURBINE_L]); + return (uint16_t)(raw / 8 + 6); +} + +/** + * Map a raw 0x1D2 byte-0 lever code to a gear_position_t. + * D and S/M share code 0x78 — use decode_gear() to resolve them. + * @param d0 Byte 0 of a 0x1D2 frame + * @return Lever position, or GEAR_UNKNOWN if the code isn't recognized + */ +static inline gear_position_t can_to_gear_lever(uint8_t d0) { + switch (d0) { + case GEAR_CODE_PARK: return GEAR_PARK; + case GEAR_CODE_REVERSE: return GEAR_REVERSE; + case GEAR_CODE_NEUTRAL: return GEAR_NEUTRAL; + case GEAR_CODE_DRIVE: return GEAR_DRIVE; // D or S/M — see decode_gear() + default: return GEAR_UNKNOWN; + } +} + +/** + * Extract the engaged gear number from 0x1D2 byte 1. + * High nibble is a +16 ladder: 0x5F=1st .. 0xAF=6th. 0x0F = no numbered gear. + * @param d1 Byte 1 of a 0x1D2 frame + * @return 1..6, or 0 if no gear is engaged / value out of range. + * Always 0 in REVERSE — reverse is unnumbered here; use 0x0BA instead. + */ +static inline uint8_t can_to_engaged_gear(uint8_t d1) { + if (d1 == GEAR_ENGAGED_NONE) return 0; + uint8_t n = (uint8_t)((d1 >> 4) - 4); + return (n >= 1 && n <= 6) ? n : 0; +} + +/** + * Resolve the full 0x1D2 frame into a single displayable gear_position_t. + * + * P/R/N come straight from the lever. In the D detent, byte 4 splits plain Drive + * from the Sport/Manual side-gate; when in S/M we surface the engaged gear number + * (GEAR_MANUAL_1..6) because that's what a driver in the side-gate wants to read. + * + * @param d Payload of a 0x1D2 frame + * @param dlc Frame DLC (must be >= 5 to reach the mode byte) + * @return Gear to display, or GEAR_UNKNOWN if the lever code isn't recognized + */ +static inline gear_position_t decode_gear(const uint8_t* d, uint8_t dlc) { + if (dlc <= CAN_BYTE_GEAR_LEVER) return GEAR_UNKNOWN; + + gear_position_t lever = can_to_gear_lever(d[CAN_BYTE_GEAR_LEVER]); + if (lever != GEAR_DRIVE) return lever; // P/R/N (or UNKNOWN) need no further work + + // In the D detent. Without the mode byte we can't tell D from S/M — report D. + if (dlc <= CAN_BYTE_GEAR_MODE) return GEAR_DRIVE; + if (d[CAN_BYTE_GEAR_MODE] == GEAR_MODE_DRIVE_AUTO) return GEAR_DRIVE; + + // Sport or Manual: show the engaged gear if the box has told us one. + if (dlc > CAN_BYTE_GEAR_ENGAGED) { + uint8_t n = can_to_engaged_gear(d[CAN_BYTE_GEAR_ENGAGED]); + if (n >= 1 && n <= 6) return (gear_position_t)(GEAR_MANUAL_1 + (n - 1)); + } + return GEAR_DRIVE; +} + +/** + * Map a 0x0BA ST_GR_GRB nibble (the gearbox's own target gear) to a + * gear_position_t, for cross-checking against the lever. + * @param nibble Low nibble of 0x0BA byte 0 + * @return Target gear, or GEAR_UNKNOWN if invalid/unrecognized + */ +static inline gear_position_t can_to_target_gear(uint8_t nibble) { + switch (nibble) { + case GRB_TARGET_PARK: return GEAR_PARK; + case GRB_TARGET_REVERSE: return GEAR_REVERSE; + case GRB_TARGET_NEUTRAL: return GEAR_NEUTRAL; + default: break; + } + // 5..0xA = forward gears 1..6 (same ladder as 0x1D2 byte 1) + if (nibble >= GRB_TARGET_GEAR1 && nibble <= GRB_TARGET_GEAR6) return GEAR_DRIVE; + return GEAR_UNKNOWN; +} + +/** + * Extract the engaged gear number from a 0x0BA ST_GR_GRB nibble. + * Unlike 0x1D2 byte 1, this ladder is the whole picture — but it numbers only + * the forward gears, so P/R/N still return 0. + * @param nibble Low nibble of 0x0BA byte 0 + * @return 1..6, or 0 if not in a numbered forward gear + */ +static inline uint8_t can_to_target_gear_num(uint8_t nibble) { + if (nibble < GRB_TARGET_GEAR1 || nibble > GRB_TARGET_GEAR6) return 0; + return (uint8_t)(nibble - GRB_TARGET_GEAR1 + 1); } /** @@ -185,17 +637,12 @@ static inline const char* gear_to_string(gear_position_t gear) { case GEAR_REVERSE: return "R"; case GEAR_NEUTRAL: return "N"; case GEAR_DRIVE: return "D"; - case GEAR_SPORT: return "S"; - case GEAR_MANUAL: return "M"; case GEAR_MANUAL_1: return "1"; case GEAR_MANUAL_2: return "2"; case GEAR_MANUAL_3: return "3"; case GEAR_MANUAL_4: return "4"; case GEAR_MANUAL_5: return "5"; case GEAR_MANUAL_6: return "6"; - case GEAR_MANUAL_7: return "7"; - case GEAR_MANUAL_8: return "8"; - case GEAR_ERROR: return "?"; default: return "?"; } } @@ -207,6 +654,7 @@ static inline const char* gear_to_string(gear_position_t gear) { * @return Pointer to buffer */ static inline char* format_temperature(int16_t temp_x10, char* buffer) { + // Plain "C": Controller B's UI font has no degree-sign glyph. sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10)); return buffer; } @@ -227,11 +675,11 @@ static inline char* format_voltage(uint16_t voltage_x100, char* buffer) { // ============================================================================ // Default values for testing (before CAN data is available) -#define DEFAULT_GEAR_POS GEAR_PARK +#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_FAULT_CODES 0x0000 // No faults +#define DEFAULT_ALERTS 0x0000 // No alerts #endif // _AUTOMOTIVE_DATA_H \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 464657d..53da658 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,15 +1,17 @@ /** * ESP32-S3-LCD-1.3 - Controller B - * Phase 2: UART Reception & Data Display * - * This firmware receives automotive data packets from Controller A via UART - * and displays real-time sensor data on the 1.3" round display (240x240 ST7789VW). + * Receives the v2 link from Controller A on UART1 and ESP-NOW, shows the data + * on the 1.3" round display, and drives the Nissan Patrol cluster's tachometer + * and coolant gauge from it (GaugeOutputs, IO7 / IO8). */ #include #include #include "modules/display_init.h" #include "modules/uart_receiver.h" +#include "modules/espnow_receiver.h" +#include "modules/gauge_outputs.h" #include "modules/debug_monitor.h" #include "ui/ui.h" #include "ui/screens/ui_Home_Screen.h" @@ -17,51 +19,116 @@ // FreeRTOS task handles TaskHandle_t lvglTaskHandle = NULL; -// Warning thresholds -#define COOLANT_TEMP_WARNING_C 110 // °C (1100 in 0.1°C units) -#define ENGINE_OIL_TEMP_WARNING_C 130 // °C (1300 in 0.1°C units) -#define GEARBOX_OIL_TEMP_WARNING_C 130 // °C (1300 in 0.1°C units) -#define BATTERY_VOLTAGE_WARNING_V 11.0f // V (1100 in 0.01V units) +// Link is considered lost after this long without an applied DATA frame +#define LINK_TIMEOUT_MS 1000 +// A shift pulse is shown for at least this long, so a fast shift still blinks +#define SHIFT_PULSE_MIN_MS 600 /** * Helper function to update sensor icon position, visibility, and color - * - * @param icon_normal Normal color icon object - * @param icon_red Red/warning color icon object - * @param label_ref Label to position relative to - * @param position_below If true, position icon below label; if false, position above - * @param show If true, show appropriate icon; if false, hide both icons - * @param use_red If true and show=true, show red icon; if false, show normal icon */ void update_sensor_icon(lv_obj_t* icon_normal, lv_obj_t* icon_red, lv_obj_t* label_ref, bool position_below, bool show, bool use_red) { if (icon_normal == NULL || icon_red == NULL || label_ref == NULL) { - return; // Safety check + return; } if (show) { - // Determine which icon to show lv_obj_t* icon_to_show = use_red ? icon_red : icon_normal; lv_obj_t* icon_to_hide = use_red ? icon_normal : icon_red; - // Position the icon relative to the label if (position_below) { - lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_BOTTOM_MID, 0, 2); // 2px gap below + lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_BOTTOM_MID, 0, 2); } else { - lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_TOP_MID, 0, -2); // 2px gap above + lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_TOP_MID, 0, -2); } - // Show appropriate icon, hide the other lv_obj_clear_flag(icon_to_show, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(icon_to_hide, LV_OBJ_FLAG_HIDDEN); } else { - // Hide both icons when no data lv_obj_add_flag(icon_normal, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(icon_red, LV_OBJ_FLAG_HIDDEN); } } +// ============================================================================ +// GEAR LABEL: pulse while the gearbox is still moving to the target gear +// ============================================================================ + +static lv_anim_t g_gear_anim; +static bool g_gear_pulsing = false; +static uint32_t g_gear_pulse_started = 0; +static bool g_gear_color_saved = false; +static lv_color_t g_gear_color_default; + +static void gearOpaCb(void* obj, int32_t v) { + lv_obj_set_style_opa((lv_obj_t*)obj, (lv_opa_t)v, 0); +} + +static void startGearPulse() { + if (g_gear_pulsing || ui_Gear_State_LBL == NULL) return; + lv_anim_init(&g_gear_anim); + lv_anim_set_var(&g_gear_anim, ui_Gear_State_LBL); + lv_anim_set_exec_cb(&g_gear_anim, gearOpaCb); + lv_anim_set_values(&g_gear_anim, 255, 60); + lv_anim_set_time(&g_gear_anim, 300); + lv_anim_set_playback_time(&g_gear_anim, 300); + lv_anim_set_repeat_count(&g_gear_anim, LV_ANIM_REPEAT_INFINITE); + lv_anim_start(&g_gear_anim); + g_gear_pulsing = true; + g_gear_pulse_started = millis(); +} + +static void stopGearPulse() { + if (!g_gear_pulsing || ui_Gear_State_LBL == NULL) return; + lv_anim_del(ui_Gear_State_LBL, gearOpaCb); + lv_obj_set_style_opa(ui_Gear_State_LBL, LV_OPA_COVER, 0); + g_gear_pulsing = false; +} + +/** + * Compose and show the gear label from lever + target/engaged nibbles. + * While target != engaged the TARGET digit is shown and the label pulses; + * once they agree the label goes solid on the engaged gear. + */ +static void updateGearLabel(const automotive_data_t& d, bool valid) { + if (ui_Gear_State_LBL == NULL) return; + + if (!g_gear_color_saved) { + g_gear_color_default = lv_obj_get_style_text_color(ui_Gear_State_LBL, 0); + g_gear_color_saved = true; + } + + if (!valid) { + stopGearPulse(); + lv_label_set_text(ui_Gear_State_LBL, "?"); + lv_obj_set_style_text_color(ui_Gear_State_LBL, g_gear_color_default, 0); + return; + } + + uint8_t target = gear_target(d.gear_nibbles); + uint8_t engaged = gear_engaged(d.gear_nibbles); + bool shifting = gear_shifting(d.gear_nibbles); + + uint8_t number = engaged; + if (shifting || (engaged == 0 && target != 0)) number = target; + + char buf[8]; + gear_compose(d.gear_lever, number, buf, sizeof(buf)); + lv_label_set_text(ui_Gear_State_LBL, buf); + + if (shifting) { + startGearPulse(); + } else if (g_gear_pulsing && (millis() - g_gear_pulse_started) >= SHIFT_PULSE_MIN_MS) { + stopGearPulse(); + } + + bool mismatch = (d.valid_flags & VALID_FLAG_ALERTS) && (d.alerts & ALERT_GEAR_MISMATCH); + lv_obj_set_style_text_color(ui_Gear_State_LBL, + mismatch ? lv_color_hex(0xFF3B30) : g_gear_color_default, 0); +} + /** * LVGL update task (runs on Core 1) */ @@ -70,39 +137,32 @@ void lvglTask(void *parameter) { while (true) { DisplayInit::update(); - vTaskDelay(pdMS_TO_TICKS(5)); // ~200 FPS max, actual will be limited by LVGL + vTaskDelay(pdMS_TO_TICKS(5)); } } void setup() { - // Initialize serial (USB CDC on ESP32-S3) Serial.begin(115200); - // Send immediate boot message (may be lost if monitor not connected yet) Serial.println("\n[BOOT] ESP32-S3-LCD-1.3 starting..."); - // Wait for USB CDC to be ready (important for ESP32-S3) unsigned long start_wait = millis(); while (!Serial && (millis() - start_wait < 3000)) { - delay(100); // Wait up to 3 seconds for serial + delay(100); } - - delay(500); // Additional stabilization time + delay(500); Serial.println("[BOOT] Serial communication ready!"); - Serial.println("\n\n================================="); Serial.println("ESP32-S3-LCD-1.3 - Controller B"); - Serial.println("Phase 2: UART Reception"); + Serial.printf("Link protocol v%u | UART + ESP-NOW | gauge outputs\n", PACKET_VERSION); Serial.println("=================================\n"); - // Display hardware info Serial.printf("CPU Frequency: %d MHz\n", getCpuFrequencyMhz()); Serial.printf("Free Heap: %d bytes\n", ESP.getFreeHeap()); Serial.printf("PSRAM Size: %d bytes\n", ESP.getPsramSize()); Serial.printf("PSRAM Free: %d bytes\n", ESP.getFreePsram()); - // Initialize display hardware if (!DisplayInit::init()) { Serial.println("[ERROR] Display initialization failed!"); while (1) { @@ -110,35 +170,33 @@ void setup() { } } - // Initialize SquareLine Studio UI Serial.println("[UI] Initializing SquareLine Studio UI..."); ui_init(); Serial.println("[UI] SquareLine Studio UI initialized"); - // Create LVGL update task on Core 1 - xTaskCreatePinnedToCore( - lvglTask, - "LVGL_Task", - 8192, // Stack size - NULL, - 2, // Priority - &lvglTaskHandle, - 1 // Core 1 - ); + xTaskCreatePinnedToCore(lvglTask, "LVGL_Task", 8192, NULL, 2, &lvglTaskHandle, 1); - // Initialize debug monitor module Serial.println("\n[Debug] Initializing debug monitor control..."); DebugMonitor::init(); - // Initialize UART receiver (creates task on Core 0) - Serial.println("\n[UART] Initializing UART receiver..."); + // Gauge outputs before the receivers, so the first CONFIG frame has + // somewhere to land and the pins are already driven low. + Serial.println("\n[Gauges] Initializing Patrol gauge outputs..."); + GaugeOutputs::init(); + + Serial.println("\n[UART] Initializing link receiver..."); if (!UARTReceiver::init()) { - Serial.println("[ERROR] UART receiver initialization failed!"); + Serial.println("[ERROR] Link receiver initialization failed!"); while (1) { delay(1000); } } - Serial.println("[UART] UART receiver initialized"); + Serial.println("[UART] Link receiver initialized"); + + Serial.println("\n[EspNow] Initializing ESP-NOW receiver..."); + if (!EspNowReceiver::init()) { + Serial.println("[WARN] ESP-NOW receiver failed to start - UART only"); + } Serial.println("\n[Setup] Complete! Starting main loop...\n"); } @@ -147,153 +205,124 @@ void loop() { static uint32_t last_stats_print = 0; static uint32_t last_connection_check = 0; static uint32_t last_ui_update = 0; + static uint32_t last_cfg_seq = 0; static bool was_connected = false; - // Print UART statistics every 5 seconds + // Wireless leg housekeeping (channel hopping while silent) + EspNowReceiver::tick(); + + // Apply a new CONFIG from A. Overrides are a bench tool: applied but not + // persisted, so a reboot never leaves the gauges pinned to a test value. + uint32_t cfg_seq = UARTReceiver::getConfigSeq(); + if (cfg_seq != last_cfg_seq) { + last_cfg_seq = cfg_seq; + link_config_t cfg = UARTReceiver::getConfig(); + GaugeOutputs::applyConfig(cfg, cfg.override_mode == 0); + } + + // Statistics every 5 seconds if (millis() - last_stats_print > 5000) { last_stats_print = millis(); - UARTReceiver::uart_rx_stats_t stats = UARTReceiver::getStats(); - + UARTReceiver::uart_rx_stats_t s = UARTReceiver::getStats(); Serial.printf("[Stats] Uptime: %lu s | Free Heap: %d bytes\n", - millis() / 1000, - ESP.getFreeHeap()); - - Serial.printf("[UART Stats] Packets: %lu | Checksum Errors: %lu | Framing Errors: %lu | Bytes RX: %lu\n", - stats.packets_received, - stats.checksum_errors, - stats.framing_errors, - stats.bytes_received); - - if (stats.packets_received > 0) { - uint32_t time_since = UARTReceiver::getTimeSinceLastPacket(); - Serial.printf("[UART Stats] Last packet: %lu ms ago\n", time_since); + millis() / 1000, ESP.getFreeHeap()); + Serial.printf("[Link] applied=%lu uart=%lu espnow=%lu dup=%lu cfg=%lu | chk=%lu frame=%lu ver=%lu | uart %s, espnow %s (ch %u)\n", + (unsigned long)s.packets_received, (unsigned long)s.packets_uart, + (unsigned long)s.packets_espnow, (unsigned long)s.duplicates, + (unsigned long)s.config_received, + (unsigned long)s.checksum_errors, (unsigned long)s.framing_errors, + (unsigned long)s.version_errors, + UARTReceiver::isSourceAlive(LINK_SOURCE_UART, LINK_TIMEOUT_MS) ? "alive" : "silent", + UARTReceiver::isSourceAlive(LINK_SOURCE_ESPNOW, LINK_TIMEOUT_MS) ? "alive" : "silent", + EspNowReceiver::currentChannel()); + if (s.packets_received > 0) { + Serial.printf("[Link] Last packet: %lu ms ago\n", (unsigned long)UARTReceiver::getTimeSinceLastPacket()); } + GaugeOutputs::printStatus(); } - // Check connection status every second + // Connection state changes if (millis() - last_connection_check > 1000) { last_connection_check = millis(); - - bool is_connected = UARTReceiver::isConnected(1000); // 1 second timeout - - // Log connection state changes + bool is_connected = UARTReceiver::isConnected(LINK_TIMEOUT_MS); if (is_connected && !was_connected) { - Serial.println("[UART] Connection ESTABLISHED with Controller A"); - automotive_data_t data = UARTReceiver::getLatestData(); - char gearbox_buf[16], engine_buf[16], voltage_buf[16]; - Serial.printf("[Data] Gear:%s | Gearbox:%s | Engine:%s | Battery:%s | Debug:%s\n", - gear_to_string((gear_position_t)data.gear_position), - format_temperature(data.gearbox_oil_temp, gearbox_buf), - format_temperature(data.engine_oil_temp, engine_buf), - format_voltage(data.battery_voltage, voltage_buf), - data.debug_enabled ? "ON" : "OFF"); + Serial.println("[Link] Connection ESTABLISHED with Controller A"); } else if (!is_connected && was_connected) { - Serial.println("[UART] Connection LOST - No data from Controller A"); + Serial.println("[Link] Connection LOST - no data from Controller A"); } - was_connected = is_connected; } - // Update UI labels every 200ms (5Hz, matching UART packet rate) + // UI + gauge outputs at the packet rate (5 Hz) if (millis() - last_ui_update > 200) { last_ui_update = millis(); automotive_data_t data = UARTReceiver::getLatestData(); - bool is_connected = UARTReceiver::isConnected(1000); + bool is_connected = UARTReceiver::isConnected(LINK_TIMEOUT_MS); + + GaugeOutputs::update(data, is_connected); if (is_connected) { - // Connection active - update labels with real data - // Check valid_flags per protocol requirement (UART_PROTOCOL.md lines 242, 554, 560) char gearbox_buf[16], engine_buf[16], coolant_buf[16], voltage_buf[16]; + bool alerts_valid = (data.valid_flags & VALID_FLAG_ALERTS); + uint16_t alerts = alerts_valid ? data.alerts : 0; - // Update Gearbox Oil Temperature (check VALID_FLAG_GEARBOX_TEMP) if (data.valid_flags & VALID_FLAG_GEARBOX_TEMP) { lv_label_set_text(ui_GB_Oil_Temp_LBL, format_temperature(data.gearbox_oil_temp, gearbox_buf)); } else { - lv_label_set_text(ui_GB_Oil_Temp_LBL, "---"); // Invalid per protocol line 560 + lv_label_set_text(ui_GB_Oil_Temp_LBL, "---"); } - // Update Engine Oil Temperature (check VALID_FLAG_ENGINE_TEMP) if (data.valid_flags & VALID_FLAG_ENGINE_TEMP) { lv_label_set_text(ui_Engine_Oil_Temp_LBL, format_temperature(data.engine_oil_temp, engine_buf)); } else { lv_label_set_text(ui_Engine_Oil_Temp_LBL, "---"); } - // Update Water/Coolant Temperature (check VALID_FLAG_COOLANT_TEMP) if (data.valid_flags & VALID_FLAG_COOLANT_TEMP) { lv_label_set_text(ui_Water_Temp_LBL, format_temperature(data.coolant_temp, coolant_buf)); } else { lv_label_set_text(ui_Water_Temp_LBL, "---"); } - // Update Battery Voltage (check VALID_FLAG_BATTERY_VOLT) if (data.valid_flags & VALID_FLAG_BATTERY_VOLT) { lv_label_set_text(ui_Battery_Voltage_LBL, format_voltage(data.battery_voltage, voltage_buf)); } else { lv_label_set_text(ui_Battery_Voltage_LBL, "---"); } - // Update Gear Position (check VALID_FLAG_GEAR_POS) - if (ui_Gear_State_LBL != NULL) { - if (data.valid_flags & VALID_FLAG_GEAR_POS) { - lv_label_set_text(ui_Gear_State_LBL, gear_to_string((gear_position_t)data.gear_position)); - } else { - lv_label_set_text(ui_Gear_State_LBL, "?"); - } - } + updateGearLabel(data, (data.valid_flags & VALID_FLAG_GEAR_POS) != 0); - // Update sensor icons with warning logic - // Icons only shown if data is BOTH connected AND valid (per protocol) - // Temperature values are in 0.1°C units (e.g., 850 = 85.0°C) - // Voltage values are in 0.01V units (e.g., 1250 = 12.50V) - - // Top Container Icons (positioned BELOW labels) - // Water/Coolant Temperature - show only if valid, warn if >= 110°C + // Icons: shown when the value is valid, red when A raised the alert. + // Thresholds live on A (Tunables); B only renders the bits. bool coolant_valid = (data.valid_flags & VALID_FLAG_COOLANT_TEMP); - bool coolant_warning = coolant_valid && (data.coolant_temp >= (COOLANT_TEMP_WARNING_C * 10)); - update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red, - ui_Water_Temp_LBL, true, coolant_valid, coolant_warning); + update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red, ui_Water_Temp_LBL, true, + coolant_valid, (alerts & ALERT_COOLANT_HOT) != 0); - // Gearbox Oil Temperature - show only if valid, warn if >= 130°C bool gearbox_valid = (data.valid_flags & VALID_FLAG_GEARBOX_TEMP); - bool gearbox_warning = gearbox_valid && (data.gearbox_oil_temp >= (GEARBOX_OIL_TEMP_WARNING_C * 10)); - update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red, - ui_GB_Oil_Temp_LBL, true, gearbox_valid, gearbox_warning); + update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red, ui_GB_Oil_Temp_LBL, true, + gearbox_valid, (alerts & (ALERT_GEARBOX_HOT | ALERT_GEARBOX_COOLING)) != 0); - // Bottom Container Icons (positioned ABOVE labels) - // Battery Voltage - show only if valid, warn if < threshold bool battery_valid = (data.valid_flags & VALID_FLAG_BATTERY_VOLT); - bool battery_warning = battery_valid && (data.battery_voltage < (uint16_t)(BATTERY_VOLTAGE_WARNING_V * 100)); - update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red, - ui_Battery_Voltage_LBL, false, battery_valid, battery_warning); + update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red, ui_Battery_Voltage_LBL, false, + battery_valid, (alerts & ALERT_BATTERY_LOW) != 0); - // Engine Oil Temperature - show only if valid, warn if >= 130°C + // Engine oil has no sensor on this engine and no alert bit; never red. bool engine_oil_valid = (data.valid_flags & VALID_FLAG_ENGINE_TEMP); - bool engine_oil_warning = engine_oil_valid && (data.engine_oil_temp >= (ENGINE_OIL_TEMP_WARNING_C * 10)); - update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red, - ui_Engine_Oil_Temp_LBL, false, engine_oil_valid, engine_oil_warning); - + update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red, ui_Engine_Oil_Temp_LBL, false, + engine_oil_valid, false); } else { - // No connection - show "N/A" warning and hide all icons lv_label_set_text(ui_GB_Oil_Temp_LBL, "N/A"); lv_label_set_text(ui_Engine_Oil_Temp_LBL, "N/A"); lv_label_set_text(ui_Water_Temp_LBL, "N/A"); lv_label_set_text(ui_Battery_Voltage_LBL, "N/A"); - if (ui_Gear_State_LBL != NULL) { - lv_label_set_text(ui_Gear_State_LBL, "?"); - } + updateGearLabel(data, false); - // Hide all sensor icons when disconnected - update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red, - ui_Water_Temp_LBL, true, false, false); - update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red, - ui_GB_Oil_Temp_LBL, true, false, false); - update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red, - ui_Battery_Voltage_LBL, false, false, false); - update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red, - ui_Engine_Oil_Temp_LBL, false, false, false); + update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red, ui_Water_Temp_LBL, true, false, false); + update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red, ui_GB_Oil_Temp_LBL, true, false, false); + update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red, ui_Battery_Voltage_LBL, false, false, false); + update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red, ui_Engine_Oil_Temp_LBL, false, false, false); } } diff --git a/src/modules/espnow_receiver.cpp b/src/modules/espnow_receiver.cpp new file mode 100644 index 0000000..5801a0c --- /dev/null +++ b/src/modules/espnow_receiver.cpp @@ -0,0 +1,90 @@ +/** + * ESP-NOW Receiver Module Implementation (Controller B) + */ + +#include "modules/espnow_receiver.h" +#include "modules/uart_receiver.h" +#include "protocol/automotive_data.h" +#include +#include +#include + +namespace EspNowReceiver { + +#define HOP_SILENCE_MS 1500 // no frame for this long -> start hopping +#define HOP_DWELL_MS 400 // time spent on each channel while hopping +#define CHANNEL_MAX 13 + +static bool g_ready = false; +static volatile uint32_t g_frames = 0; +static volatile uint32_t g_last_frame_ms = 0; +static uint8_t g_channel = ESPNOW_CHANNEL; +static uint32_t g_last_hop_ms = 0; +static bool g_locked = false; + +static void onReceive(const uint8_t* mac, const uint8_t* data, int len) { + (void)mac; + if (len <= 0) return; + g_frames++; + g_last_frame_ms = millis(); + UARTReceiver::processFrame(data, (size_t)len, LINK_SOURCE_ESPNOW); +} + +static void setChannel(uint8_t ch) { + esp_wifi_set_channel(ch, WIFI_SECOND_CHAN_NONE); + g_channel = ch; +} + +bool init() { + if (g_ready) return true; + + WiFi.mode(WIFI_STA); + WiFi.disconnect(); + WiFi.setSleep(false); + setChannel(ESPNOW_CHANNEL); + + if (esp_now_init() != ESP_OK) { + Serial.println("[EspNow] esp_now_init failed"); + return false; + } + esp_now_register_recv_cb(onReceive); + + g_ready = true; + g_last_hop_ms = millis(); + Serial.printf("[EspNow] Listening: STA %s, channel %u (will hop if silent)\n", + WiFi.macAddress().c_str(), g_channel); + return true; +} + +void tick() { + if (!g_ready) return; + uint32_t now = millis(); + uint32_t since = now - g_last_frame_ms; + + if (g_frames > 0 && since < HOP_SILENCE_MS) { + if (!g_locked) { + g_locked = true; + Serial.printf("[EspNow] Locked on channel %u\n", g_channel); + } + return; + } + + // Silent: hop. Start from the configured channel so the common case + // (A not on an AP) is found without a full sweep. + if (now - g_last_hop_ms >= HOP_DWELL_MS) { + g_last_hop_ms = now; + if (g_locked) { + g_locked = false; + Serial.printf("[EspNow] Silent for %lu ms - hopping\n", (unsigned long)since); + } + uint8_t next = g_channel + 1; + if (next > CHANNEL_MAX) next = 1; + setChannel(next); + } +} + +bool isReady() { return g_ready; } +uint8_t currentChannel() { return g_channel; } +uint32_t framesReceived() { return g_frames; } + +} // namespace EspNowReceiver diff --git a/src/modules/gauge_outputs.cpp b/src/modules/gauge_outputs.cpp new file mode 100644 index 0000000..d09d701 --- /dev/null +++ b/src/modules/gauge_outputs.cpp @@ -0,0 +1,227 @@ +/** + * Gauge Outputs Module Implementation (Controller B) + * + * LEDC channel plan (Arduino-ESP32 2.x: timer = channel / 2): + * channel 1 -> timer 0 : LovyanGFX backlight (display_init.cpp, 44.1 kHz) + * channel 2 -> timer 1 : tachometer (frequency varies with rpm) + * channel 4 -> timer 2 : coolant PWM (fixed frequency, duty varies) + * The two gauge channels sit on their own timers so changing the tach + * frequency never disturbs the backlight or the coolant PWM. + */ + +#include "modules/gauge_outputs.h" +#include +#include + +namespace GaugeOutputs { + +#define TACH_CHANNEL 2 +#define TEMP_CHANNEL 4 +#define TEMP_RESOLUTION 8 // bits; duty 0..255 (matches the config's 8-bit law) +// The tach runs from ~5 Hz to a few hundred Hz. The LEDC divider only reaches +// low frequencies with a high duty resolution (f_min ~= 80 MHz / (2^res * 1024)), +// so the tach timer uses 14 bits: ~4.8 Hz .. ~4.9 kHz. +#define TACH_RESOLUTION 14 +#define TACH_DUTY (1 << (TACH_RESOLUTION - 1)) // 50 % +#define TACH_MIN_HZ 5.0 + +static const char* NVS_NAMESPACE = "gaugecfg"; +static const char* NVS_KEY_BLOB = "cfg"; + +static link_config_t g_cfg; +static bool g_initialized = false; + +// Live output state, for status and change detection +static bool g_tach_on = false; +static double g_tach_hz = 0.0; +static bool g_temp_on = false; +static uint8_t g_temp_duty = 0; +static uint16_t g_temp_hz_setup = 0; +static const char* g_tach_src = "off"; +static const char* g_temp_src = "off"; + +// ============================================================================ +// PRIVATE HELPERS +// ============================================================================ + +static void saveConfig() { + Preferences prefs; + prefs.begin(NVS_NAMESPACE, false); + prefs.putBytes(NVS_KEY_BLOB, &g_cfg, sizeof(g_cfg)); + prefs.end(); +} + +static bool loadConfig() { + Preferences prefs; + prefs.begin(NVS_NAMESPACE, true); + bool ok = false; + if (prefs.getBytesLength(NVS_KEY_BLOB) == sizeof(link_config_t)) { + prefs.getBytes(NVS_KEY_BLOB, &g_cfg, sizeof(g_cfg)); + ok = true; + } + prefs.end(); + return ok; +} + +static void tachOff() { + if (g_tach_on) { + ledcWrite(TACH_CHANNEL, 0); + g_tach_on = false; + } + g_tach_hz = 0.0; +} + +static void tachSet(double hz) { + // Only touch the timer when the frequency actually moved; every change + // restarts the period and would jitter the needle if done each frame. + if (!g_tach_on || fabs(hz - g_tach_hz) > 0.25) { + double got = ledcChangeFrequency(TACH_CHANNEL, hz, TACH_RESOLUTION); + if (got <= 0.0) { + tachOff(); + return; + } + g_tach_hz = hz; + } + if (!g_tach_on) { + ledcWrite(TACH_CHANNEL, TACH_DUTY); + g_tach_on = true; + } +} + +static void tempSetupFrequency(uint16_t hz) { + if (hz < 20) hz = 20; + if (hz == g_temp_hz_setup) return; + ledcSetup(TEMP_CHANNEL, hz, TEMP_RESOLUTION); + ledcAttachPin(GAUGE_TEMP_PIN, TEMP_CHANNEL); + ledcWrite(TEMP_CHANNEL, g_temp_on ? g_temp_duty : 0); + g_temp_hz_setup = hz; +} + +static void tempSet(uint8_t duty) { + if (!g_temp_on || duty != g_temp_duty) { + ledcWrite(TEMP_CHANNEL, duty); + g_temp_duty = duty; + g_temp_on = true; + } +} + +static void tempOff() { + if (g_temp_on) { + ledcWrite(TEMP_CHANNEL, 0); + g_temp_on = false; + } + g_temp_duty = 0; +} + +// ============================================================================ +// PUBLIC API +// ============================================================================ + +void init() { + if (g_initialized) return; + + if (!loadConfig()) { + link_config_defaults(&g_cfg); + Serial.println("[Gauges] No cached config - using defaults until A sends one"); + } else { + Serial.printf("[Gauges] Cached config v%u loaded from NVS\n", g_cfg.cfg_version); + } + + // Tach: set up at a nominal frequency, output low until data arrives. + ledcSetup(TACH_CHANNEL, 100, TACH_RESOLUTION); + ledcAttachPin(GAUGE_TACH_PIN, TACH_CHANNEL); + ledcWrite(TACH_CHANNEL, 0); + + // Temp: fixed frequency from config, duty 0. + tempSetupFrequency(g_cfg.temp_pwm_hz); + ledcWrite(TEMP_CHANNEL, 0); + + g_initialized = true; + Serial.printf("[Gauges] Outputs ready: tach IO%d (LEDC ch%d), temp IO%d (LEDC ch%d @ %u Hz)\n", + GAUGE_TACH_PIN, TACH_CHANNEL, GAUGE_TEMP_PIN, TEMP_CHANNEL, g_cfg.temp_pwm_hz); +} + +void applyConfig(const link_config_t& cfg, bool persist) { + g_cfg = cfg; + tempSetupFrequency(g_cfg.temp_pwm_hz); + // Force the tach to re-evaluate its frequency on the next update(). + g_tach_hz = -1.0; + if (persist) saveConfig(); + Serial.printf("[Gauges] Config v%u applied%s: ppr=%u trim=%d%% temp=%uHz slope=%u.%02u offset=%d min=%dC override=%u\n", + g_cfg.cfg_version, persist ? " (saved)" : "", + g_cfg.tach_ppr, g_cfg.tach_trim_pct, g_cfg.temp_pwm_hz, + g_cfg.temp_slope_x100 / 100, g_cfg.temp_slope_x100 % 100, + g_cfg.temp_offset, g_cfg.temp_min_c, g_cfg.override_mode); +} + +link_config_t getConfig() { + return g_cfg; +} + +void update(const automotive_data_t& d, bool link_ok) { + if (!g_initialized) return; + + // ---------------- tachometer ---------------- + { + bool have = false; + uint32_t rpm = 0; + if (g_cfg.override_mode & OVERRIDE_TACH) { + have = true; rpm = g_cfg.override_rpm; g_tach_src = "override"; + } else if (link_ok && (d.valid_flags & VALID_FLAG_RPM)) { + have = true; rpm = d.engine_rpm; g_tach_src = "can"; + } else { + g_tach_src = link_ok ? "no-rpm" : "no-link"; + } + + if (!(g_cfg.out_enable & OUT_ENABLE_TACH)) { have = false; g_tach_src = "disabled"; } + + if (have && rpm > 0 && g_cfg.tach_ppr > 0) { + double hz = (double)rpm * g_cfg.tach_ppr / 60.0; + hz *= (1.0 + g_cfg.tach_trim_pct / 100.0); + if (g_cfg.tach_min_hz && hz < g_cfg.tach_min_hz) hz = g_cfg.tach_min_hz; + if (g_cfg.tach_max_hz && hz > g_cfg.tach_max_hz) hz = g_cfg.tach_max_hz; + if (hz >= TACH_MIN_HZ) tachSet(hz); else tachOff(); + } else { + tachOff(); + } + } + + // ---------------- coolant gauge ---------------- + { + bool have = false; + int32_t duty = 0; + if (g_cfg.override_mode & OVERRIDE_TEMP) { + have = true; duty = g_cfg.override_duty; g_temp_src = "override"; + } else if (link_ok && (d.valid_flags & VALID_FLAG_COOLANT_TEMP)) { + int32_t t_c = d.coolant_temp / 10; // 0.1 degC -> degC + if (t_c >= g_cfg.temp_min_c) { + have = true; + duty = ((int32_t)g_cfg.temp_slope_x100 * t_c) / 100 + g_cfg.temp_offset; + g_temp_src = "can"; + } else { + g_temp_src = "below-min"; + } + } else { + g_temp_src = link_ok ? "no-temp" : "no-link"; + } + + if (!(g_cfg.out_enable & OUT_ENABLE_TEMP)) { have = false; g_temp_src = "disabled"; } + + if (have) { + if (duty < 0) duty = 0; + if (duty > g_cfg.temp_duty_max) duty = g_cfg.temp_duty_max; + tempSet((uint8_t)duty); + } else { + tempOff(); + } + } +} + +void printStatus() { + Serial.printf("[Gauges] tach: %s %.1f Hz (%s) | temp: %s duty %u/255 @ %u Hz (%s) | cfg v%u\n", + g_tach_on ? "ON " : "off", g_tach_hz > 0 ? g_tach_hz : 0.0, g_tach_src, + g_temp_on ? "ON " : "off", g_temp_duty, g_temp_hz_setup, g_temp_src, + g_cfg.cfg_version); +} + +} // namespace GaugeOutputs diff --git a/src/modules/uart_receiver.cpp b/src/modules/uart_receiver.cpp index 2a50336..dfee4c4 100644 --- a/src/modules/uart_receiver.cpp +++ b/src/modules/uart_receiver.cpp @@ -1,8 +1,5 @@ /** - * UART Receiver Module Implementation - * - * Receives automotive data packets from Controller A via UART1. - * Uses state machine for robust packet parsing and framing. + * Link Receiver Module Implementation (Controller B) */ #include "modules/uart_receiver.h" @@ -13,65 +10,159 @@ namespace UARTReceiver { -// UART Configuration -// Note: UART_RX_PIN, UART_TX_PIN, and UART_BAUD_RATE are defined in platformio.ini -#define UART_SERIAL_PORT Serial1 // Hardware UART1 -#define UART_RX_BUFFER_SIZE 256 // Receive buffer size +#define UART_SERIAL_PORT Serial1 +#define UART_RX_BUFFER_SIZE 256 -// Packet framing state machine states +// UART framing state machine typedef enum { - STATE_WAIT_START, // Waiting for start byte (0xAA) - STATE_READ_VERSION, // Reading protocol version - STATE_READ_LENGTH, // Reading data length - STATE_READ_DATA, // Reading data payload - STATE_READ_CHECKSUM, // Reading checksum byte - STATE_READ_END // Reading end byte (0x55) + STATE_WAIT_START, + STATE_READ_VERSION, + STATE_READ_TYPE, + STATE_READ_LENGTH, + STATE_READ_PAYLOAD, + STATE_READ_CHECKSUM, + STATE_READ_END } rx_state_t; -// Private state variables static automotive_data_t g_latest_data = {0}; +static link_config_t g_config; +static uint32_t g_config_seq = 0; static uart_rx_stats_t g_rx_stats = {0}; static SemaphoreHandle_t g_data_mutex = NULL; static TaskHandle_t g_uart_task_handle = NULL; static bool g_initialized = false; +// Dedupe key of the last applied DATA frame +static bool g_have_last = false; +static uint8_t g_last_id = 0; +static uint32_t g_last_ts = 0; + +static const char* sourceName(link_source_t s) { + switch (s) { + case LINK_SOURCE_UART: return "uart"; + case LINK_SOURCE_ESPNOW: return "espnow"; + default: return "none"; + } +} + +static void bump(uint32_t* counter) { + if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) { + (*counter)++; + xSemaphoreGive(g_data_mutex); + } +} + +void processFrame(const uint8_t* frame, size_t len, link_source_t source) { + uint8_t type = 0, plen = 0; + const uint8_t* payload = NULL; + frame_status_t st = frame_parse(frame, len, &type, &payload, &plen); + + if (st != FRAME_OK) { + switch (st) { + case FRAME_ERR_VERSION: + bump(&g_rx_stats.version_errors); + if (g_rx_stats.version_errors <= 3 || g_rx_stats.version_errors % 50 == 0) { + Serial.printf("[Link] Version mismatch on %s: got v%u, this firmware speaks v%u (%lu so far)\n", + sourceName(source), frame[1], PACKET_VERSION, + (unsigned long)g_rx_stats.version_errors); + } + break; + case FRAME_ERR_CHECKSUM: + bump(&g_rx_stats.checksum_errors); + Serial.printf("[Link] Checksum error on %s\n", sourceName(source)); + break; + default: + bump(&g_rx_stats.framing_errors); + Serial.printf("[Link] Framing error %d on %s (len %u)\n", (int)st, sourceName(source), (unsigned)len); + break; + } + return; + } + + uint32_t now = millis(); + + if (type == PACKET_TYPE_CONFIG) { + link_config_t cfg; + memcpy(&cfg, payload, sizeof(cfg)); + if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(50)) == pdTRUE) { + bool changed = (g_config_seq == 0) || (cfg.cfg_version != g_config.cfg_version); + if (changed) { + g_config = cfg; + g_config_seq++; + } + g_rx_stats.config_received++; + if (source == LINK_SOURCE_UART) g_rx_stats.last_uart_time = now; + else if (source == LINK_SOURCE_ESPNOW) g_rx_stats.last_espnow_time = now; + xSemaphoreGive(g_data_mutex); + if (changed) { + Serial.printf("[Link] CONFIG v%u received on %s\n", cfg.cfg_version, sourceName(source)); + } + } + return; + } + + // DATA + automotive_data_t d; + memcpy(&d, payload, sizeof(d)); + + if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(50)) != pdTRUE) return; + + if (source == LINK_SOURCE_UART) { g_rx_stats.packets_uart++; g_rx_stats.last_uart_time = now; } + else if (source == LINK_SOURCE_ESPNOW) { g_rx_stats.packets_espnow++; g_rx_stats.last_espnow_time = now; } + + bool dup = g_have_last && d.packet_id == g_last_id && d.timestamp_ms == g_last_ts; + if (dup) { + g_rx_stats.duplicates++; + xSemaphoreGive(g_data_mutex); + return; + } + + g_have_last = true; + g_last_id = d.packet_id; + g_last_ts = d.timestamp_ms; + g_latest_data = d; + g_rx_stats.packets_received++; + g_rx_stats.last_packet_time = now; + g_rx_stats.last_source = source; + uint32_t n = g_rx_stats.packets_received; + xSemaphoreGive(g_data_mutex); + + DebugMonitor::setVisible(d.debug_enabled != 0); + + if (n % 25 == 0) { + char gear[8], gearbox_buf[16], coolant_buf[16], voltage_buf[16]; + gear_compose(d.gear_lever, gear_engaged(d.gear_nibbles), gear, sizeof(gear)); + Serial.printf("[Link] RX #%u via %s | Gear:%s (t%u/e%u) | RPM:%u | GB:%s | Cool:%s | Batt:%s | Alerts:0x%02X | Valid:0x%02X\n", + d.packet_id, sourceName(source), gear, + gear_target(d.gear_nibbles), gear_engaged(d.gear_nibbles), + d.engine_rpm, + format_temperature(d.gearbox_oil_temp, gearbox_buf), + format_temperature(d.coolant_temp, coolant_buf), + format_voltage(d.battery_voltage, voltage_buf), + d.alerts, d.valid_flags); + } +} + /** - * @brief UART reception task - runs on Core 0 - * - * Implements state machine for packet parsing: - * 1. Wait for start byte (0xAA) - * 2. Read version and length - * 3. Read data payload - * 4. Read checksum - * 5. Read end byte (0x55) - * 6. Validate packet - * 7. Update shared data structure + * UART1 byte-stream framing task (Core 0) */ static void uartRxTask(void* parameter) { - uint8_t rx_buffer[sizeof(uart_packet_t)]; + uint8_t rx_buffer[PACKET_MAX_SIZE]; rx_state_t state = STATE_WAIT_START; size_t bytes_read = 0; uint8_t expected_length = 0; Serial.println("[UARTReceiver] Task started on Core 0"); - // Initialize UART1 hardware UART_SERIAL_PORT.setRxBufferSize(UART_RX_BUFFER_SIZE); UART_SERIAL_PORT.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN); - - Serial.printf("[UARTReceiver] UART1 initialized: %d baud, RX=GPIO%d, TX=GPIO%d\n", - UART_BAUD_RATE, UART_RX_PIN, UART_TX_PIN); - Serial.printf("[UARTReceiver] Waiting for packets from Controller A...\n"); + Serial.printf("[UARTReceiver] UART1 initialized: %d baud, RX=GPIO%d, protocol v%u\n", + UART_BAUD_RATE, UART_RX_PIN, PACKET_VERSION); while (true) { - // Check if data available - if (UART_SERIAL_PORT.available()) { + while (UART_SERIAL_PORT.available()) { uint8_t byte = UART_SERIAL_PORT.read(); - - if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) { - g_rx_stats.bytes_received++; - xSemaphoreGive(g_data_mutex); - } + g_rx_stats.bytes_received++; // statistic only; a torn read is harmless switch (state) { case STATE_WAIT_START: @@ -80,15 +171,16 @@ static void uartRxTask(void* parameter) { bytes_read = 1; state = STATE_READ_VERSION; } else { - // Ignore byte, still waiting for start - if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) { - g_rx_stats.framing_errors++; - xSemaphoreGive(g_data_mutex); - } + bump(&g_rx_stats.framing_errors); } break; case STATE_READ_VERSION: + rx_buffer[bytes_read++] = byte; + state = STATE_READ_TYPE; + break; + + case STATE_READ_TYPE: rx_buffer[bytes_read++] = byte; state = STATE_READ_LENGTH; break; @@ -96,29 +188,20 @@ static void uartRxTask(void* parameter) { case STATE_READ_LENGTH: rx_buffer[bytes_read++] = byte; expected_length = byte; - - // Validate length is reasonable - if (expected_length > sizeof(automotive_data_t)) { - // Invalid length, reset to wait for start - Serial.printf("[UARTReceiver] ERROR: Invalid length %d (max: %d)\n", - expected_length, sizeof(automotive_data_t)); + if (expected_length > PACKET_MAX_PAYLOAD) { + bump(&g_rx_stats.framing_errors); state = STATE_WAIT_START; bytes_read = 0; - if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) { - g_rx_stats.framing_errors++; - xSemaphoreGive(g_data_mutex); - } + } else if (expected_length == 0) { + state = STATE_READ_CHECKSUM; } else { - state = STATE_READ_DATA; + state = STATE_READ_PAYLOAD; } break; - case STATE_READ_DATA: + case STATE_READ_PAYLOAD: rx_buffer[bytes_read++] = byte; - - // Check if we've read all data bytes - // Packet structure: start(1) + version(1) + length(1) + data(expected_length) - if (bytes_read >= (3 + expected_length)) { + if (bytes_read >= (size_t)(PACKET_HEADER_SIZE + expected_length)) { state = STATE_READ_CHECKSUM; } break; @@ -130,63 +213,13 @@ static void uartRxTask(void* parameter) { case STATE_READ_END: rx_buffer[bytes_read++] = byte; - - if (byte == PACKET_END_BYTE) { - // Complete packet received - validate it - uart_packet_t* packet = (uart_packet_t*)rx_buffer; - - if (validate_packet(packet)) { - // Valid packet - update latest data - if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - memcpy(&g_latest_data, &packet->data, sizeof(automotive_data_t)); - g_rx_stats.packets_received++; - g_rx_stats.last_packet_time = millis(); - xSemaphoreGive(g_data_mutex); - } - - // Update debug monitor visibility based on received flag - DebugMonitor::setVisible(packet->data.debug_enabled != 0); - - // Debug output every 20 packets - if (g_rx_stats.packets_received % 20 == 0) { - char gearbox_buf[16], engine_buf[16], coolant_buf[16], voltage_buf[16]; - Serial.printf("[UARTReceiver] RX #%d | Gear:%s | GB:%s | Eng:%s | Cool:%s | Batt:%s | Valid:0x%02X | Debug:%s\n", - packet->data.packet_id, - gear_to_string((gear_position_t)packet->data.gear_position), - format_temperature(packet->data.gearbox_oil_temp, gearbox_buf), - format_temperature(packet->data.engine_oil_temp, engine_buf), - format_temperature(packet->data.coolant_temp, coolant_buf), - format_voltage(packet->data.battery_voltage, voltage_buf), - packet->data.valid_flags, - packet->data.debug_enabled ? "ON" : "OFF"); - } - } else { - // Invalid checksum - if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) { - g_rx_stats.checksum_errors++; - xSemaphoreGive(g_data_mutex); - } - Serial.printf("[UARTReceiver] Checksum error (packet #%d)\n", - ((uart_packet_t*)rx_buffer)->data.packet_id); - } - } else { - // Invalid end byte - if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) { - g_rx_stats.framing_errors++; - xSemaphoreGive(g_data_mutex); - } - Serial.printf("[UARTReceiver] Framing error: End byte 0x%02X (expected 0x55)\n", byte); - } - - // Reset to wait for next packet + processFrame(rx_buffer, bytes_read, LINK_SOURCE_UART); state = STATE_WAIT_START; bytes_read = 0; break; } } - - // Small delay to prevent CPU hogging - vTaskDelay(pdMS_TO_TICKS(1)); + vTaskDelay(pdMS_TO_TICKS(2)); } } @@ -196,26 +229,18 @@ bool init() { return true; } - Serial.println("[UARTReceiver] Initializing UART receiver..."); + Serial.println("[UARTReceiver] Initializing link receiver..."); + + link_config_defaults(&g_config); - // Create mutex for thread-safe data access g_data_mutex = xSemaphoreCreateMutex(); if (g_data_mutex == NULL) { Serial.println("[UARTReceiver] ERROR: Failed to create mutex"); return false; } - // Create UART reception task on Core 0 BaseType_t result = xTaskCreatePinnedToCore( - uartRxTask, - "UART_RX_Task", - 4096, // Stack size - NULL, // Parameters - 1, // Priority (lower than LVGL task) - &g_uart_task_handle, - 0 // Core 0 - ); - + uartRxTask, "UART_RX_Task", 4096, NULL, 1, &g_uart_task_handle, 0); if (result != pdPASS) { Serial.println("[UARTReceiver] ERROR: Failed to create task"); return false; @@ -223,91 +248,96 @@ bool init() { g_initialized = true; Serial.println("[UARTReceiver] Initialization complete"); - return true; } automotive_data_t getLatestData() { automotive_data_t data; memset(&data, 0, sizeof(data)); - - if (g_data_mutex != NULL) { - if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - memcpy(&data, &g_latest_data, sizeof(automotive_data_t)); - xSemaphoreGive(g_data_mutex); - } + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + data = g_latest_data; + xSemaphoreGive(g_data_mutex); } - return data; } uart_rx_stats_t getStats() { uart_rx_stats_t stats; memset(&stats, 0, sizeof(stats)); - - if (g_data_mutex != NULL) { - if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - memcpy(&stats, &g_rx_stats, sizeof(uart_rx_stats_t)); - xSemaphoreGive(g_data_mutex); - } + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + stats = g_rx_stats; + xSemaphoreGive(g_data_mutex); } - return stats; } bool isConnected(uint32_t timeout_ms) { - if (!g_initialized) { - return false; - } - + if (!g_initialized) return false; bool connected = false; - - if (g_data_mutex != NULL) { - if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - if (g_rx_stats.packets_received > 0) { - uint32_t time_since_last = millis() - g_rx_stats.last_packet_time; - connected = (time_since_last < timeout_ms); - } - xSemaphoreGive(g_data_mutex); + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + if (g_rx_stats.packets_received > 0) { + connected = (millis() - g_rx_stats.last_packet_time) < timeout_ms; } + xSemaphoreGive(g_data_mutex); } - return connected; } -void resetStats() { - if (g_data_mutex != NULL) { - if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - g_rx_stats.packets_received = 0; - g_rx_stats.checksum_errors = 0; - g_rx_stats.framing_errors = 0; - g_rx_stats.timeout_errors = 0; - g_rx_stats.bytes_received = 0; - // Keep last_packet_time - xSemaphoreGive(g_data_mutex); - } +bool isSourceAlive(link_source_t source, uint32_t timeout_ms) { + if (!g_initialized) return false; + bool alive = false; + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + uint32_t t = (source == LINK_SOURCE_UART) ? g_rx_stats.last_uart_time + : (source == LINK_SOURCE_ESPNOW) ? g_rx_stats.last_espnow_time : 0; + alive = (t != 0) && ((millis() - t) < timeout_ms); + xSemaphoreGive(g_data_mutex); } + return alive; +} +link_config_t getConfig() { + link_config_t c; + link_config_defaults(&c); + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + c = g_config; + xSemaphoreGive(g_data_mutex); + } + return c; +} + +uint32_t getConfigSeq() { + uint32_t s = 0; + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + s = g_config_seq; + xSemaphoreGive(g_data_mutex); + } + return s; +} + +void resetStats() { + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + uint32_t keep_last = g_rx_stats.last_packet_time; + uint32_t keep_uart = g_rx_stats.last_uart_time; + uint32_t keep_espnow = g_rx_stats.last_espnow_time; + link_source_t keep_src = g_rx_stats.last_source; + memset(&g_rx_stats, 0, sizeof(g_rx_stats)); + g_rx_stats.last_packet_time = keep_last; + g_rx_stats.last_uart_time = keep_uart; + g_rx_stats.last_espnow_time = keep_espnow; + g_rx_stats.last_source = keep_src; + xSemaphoreGive(g_data_mutex); + } Serial.println("[UARTReceiver] Statistics reset"); } uint32_t getTimeSinceLastPacket() { - if (!g_initialized) { - return UINT32_MAX; + if (!g_initialized) return UINT32_MAX; + uint32_t t = UINT32_MAX; + if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { + if (g_rx_stats.packets_received > 0) t = millis() - g_rx_stats.last_packet_time; + xSemaphoreGive(g_data_mutex); } - - uint32_t time_since = UINT32_MAX; - - if (g_data_mutex != NULL) { - if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - if (g_rx_stats.packets_received > 0) { - time_since = millis() - g_rx_stats.last_packet_time; - } - xSemaphoreGive(g_data_mutex); - } - } - - return time_since; + return t; } } // namespace UARTReceiver diff --git a/wiki/.obsidian/workspace.json b/wiki/.obsidian/workspace.json index a36fcd8..95bf4b8 100644 --- a/wiki/.obsidian/workspace.json +++ b/wiki/.obsidian/workspace.json @@ -197,8 +197,11 @@ "bases:Create new base": false } }, - "active": "414d380b45e2466d", + "active": "d1e54c160baeb57c", "lastOpenFiles": [ + "sources/temp-stage-cfd.md", + "sources/temp-stage-cfd.md.tmp.8664.e5d183fc2b73", + "raw/temp_stage.cfd", "pages/sedyhRU0S", "pages/sedIT5Pq3", "sources/sedWvixlJ", @@ -211,11 +214,8 @@ "index.md", "index.md.tmp.8664.f6325122b3bb", "sources/pinout-photo-details-7.md", - "sources/pinout-photo-details-7.md.tmp.8664.84fea9960617", "sources/waveshare-wiki-esp32-s3-lcd-1-3.md", - "sources/waveshare-wiki-esp32-s3-lcd-1-3.md.tmp.8664.230b4837adb6", "pages/open-questions.md", - "pages/open-questions.md.tmp.8664.fdfb3a9afb71", "pages/patrol-gauge-outputs.md", "pages/link-redundancy.md", "pages/controller-link.md", diff --git a/wiki/index.md b/wiki/index.md index d707f9e..2891f58 100644 --- a/wiki/index.md +++ b/wiki/index.md @@ -13,15 +13,16 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee ## Concepts -- [[controller-link]] — the A → B link: 23-byte UART packet @ 5 Hz, what each field really carries (oil temp is dead, RPM missing), pins (A TX = GPIO 44, B RX = IO1), the **RS485-vs-TTL physical-layer question**, and the **gear-enum drift** between the two repos -- [[link-redundancy]] — design space for wired + wireless redundancy: RS485 vs TTL, BLE GATT vs ESP-NOW, failover policy on B, and why A must always transmit on both paths -- [[patrol-gauge-outputs]] — driving the Patrol cluster's tachometer (variable frequency) and coolant gauge (variable duty) from B's LEDC on IO7/IO8; the external driver stage; what must be measured on the cluster first +- [[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 +- [[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 -- [[open-questions]] — the research frontier: how the wire is really connected, which gear enum is right, which Patrol cluster, RPM field, BLE vs ESP-NOW, gauge behaviour on link loss, vehicle power, missing environmental specs +- [[open-questions]] — the research frontier: will the bare A-line wire survive the car, which Patrol cluster / tach pull-up, temp needle calibration + CANNY PWM clock, gauge behaviour on link loss, pull-the-wire failover test, BLE or not, vehicle power, environmental specs ## Sources - [[waveshare-wiki-esp32-s3-lcd-1-3]] — Waveshare product wiki (condensed fetch 2026-09-21, not a verbatim clip); core spec, CH343, PL4054/ME6217 power, BLE 5; silent on pins and environmental limits - [[pinout-photo-details-7]] — Waveshare annotated header photo (`raw/ESP32-S3-LCD-1.3-details-7.jpg`); the authoritative pinout, contradicts the repo's wiring guide +- [[temp-stage-cfd]] — **the user's earlier CannyLab program** for the same temp gauge (`raw/temp_stage.cfd`, decoded 2026-09-21): CAN 0x1D0 byte 0 − 48, **duty = 1.5·T + 50 on 0–255**, enable gate; PWM frequency and external circuit not in the file diff --git a/wiki/log.md b/wiki/log.md index f09656e..37854a3 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -17,3 +17,39 @@ Findings recorded during setup: ## [2026-09-21] update | .docs folder retired; root CLAUDE.md created The repo's `.docs/` folder (14 files) was deleted (user decision). Its still-true content — verified display pins, brightness API, SquareLine export rules, CH343 serial notes, link facts — was distilled into a new root `CLAUDE.md`; the stale parts (backlight on GPIO 2/15, SPI on 10/11, native USB-CDC, the IO35–IO42 header table, the phase roadmap, the pin-hunting guides) were dropped. `UART_PROTOCOL.md` now exists only in the 5B repo at `docs/UART_PROTOCOL.md`. `README.md` repointed to `CLAUDE.md` and `wiki/`. Wiki citations that named `.docs/` files were reworded to "former … (deleted 2026-09-21)"; [[open-questions]] wishlist gained the Waveshare schematic and demo-zip URLs recovered from the old troubleshooting doc. No page content changed otherwise. + +## [2026-09-21] update | Tach = 4 pulses/rev (user); coolant gauge characterisation procedure + +User states the Patrol cluster's tachometer expects **4 pulses per revolution** (recorded as user-stated, not bench-verified). Clarified that the coolant gauge is a current/resistance meter with no pulse count; added a bench procedure (pot sweep for the resistance → needle curve, sender-wire voltage to tell bimetal/regulated from series coil, series current for MOSFET sizing, PWM 500 Hz–2 kHz clear of any instrument-voltage-regulator chopper, empirical °C → duty lookup, tach pull-up check and two-frequency verification) to [[patrol-gauge-outputs]]. [[open-questions]] #3 and #7 reworded accordingly. + +## [2026-09-21] ingest | temp_stage.cfd — the user's old CANNY 5.3 pico temp-gauge program decoded + +`raw/temp_stage.cfd` (CannyLab, proprietary binary) walked as 165 `[type][len][payload]` records; block names, constants, wiring and an Albanian comment recovered → [[temp-stage-cfd]]. Result: CAN 500k, filter 0x1D0, low byte of D1:D0 minus 48 = °C (matches the 5B's verified decode), **duty = ((T − 40)·15 + 1100)/10 = 1.5·T + 50 on a 0–255 PWM period**, output enabled above a minimum temperature, push-pull pin with PWM pull-up. Not in the file: PWM base clock and the external drive circuit. [[patrol-gauge-outputs]] gained a prior-art section and a starting LEDC law; [[open-questions]] #7 partly answered, #13 added; index updated. + +## [2026-09-21] update | Calibration parameters to live on A; ESP32 as frequency meter for the CANNY + +User has the CANNY unit but no scope, and wants tunable variables on the 5B for both gauges. Recorded on [[patrol-gauge-outputs]]: the proposed `gauge_calibration_t` (tach ppr/trim/clamps; temp PWM Hz, slope/offset, min-temp gate, clamp; enables; calibration override) pushed A → B in a v2 config packet, and the plan to measure the CANNY's PWM frequency/duty with a 1.3 header GPIO + pulse counter instead of a scope. Suggested order: counter sketch → v2 header → A NVS/config TX/serial tuning → B RX + LEDC → A settings UI. + +## [2026-09-21] update | Frequency-counter sketch demoted to fallback + +User decision: do not measure the CANNY's PWM first; implement the v2 protocol and B's LEDC outputs directly, and only feed the CANNY's PWM pin into a free 1.3 header GPIO for troubleshooting if the gauges misbehave. Coolant PWM frequency will default to 1 kHz (tunable from A) in the absence of a measurement. Proposed implementation defaults awaiting the user's go: split gear bytes (lever + target/engaged nibbles), A-side alert bitmap (coolant ≥ 100 °C, gearbox ≥ 130 °C, gearbox cooling demand, battery < 11.0 V, gear mismatch), 16-bit rpm, config packet from A's NVS via serial console first, B outputs tach IO7 / temp IO8 on separate LEDC timers, off when link down or value invalid. + +## [2026-09-21] update | Bench wiring for the A→B link specified + +Added a bench-wiring section to [[controller-link]]: 3.3 V RS485→TTL module on B (MAX3485/SP3485), 5B `485_A`/`485_B`/GND → module → RO to IO1, VCC from 3V3, DE/RE low; termination note (shared CAN/RS485 switch, OFF before the car); the bare-A-line shortcut flagged as unreliable; a v1 baseline check (CAN toggle ON → default packets at 5 Hz → B reports established, zero errors) to run before the v2 protocol work. Running this check answers open question #1. + +## [2026-09-21] update | No RS485 module on hand — zero-parts bench options + +User has no RS485→TTL module. Re-assessed the bare `485_A` → IO1 shortcut against the 5B schematic: SP3485 at 3.3 V, auto-direction drives only zeros, 4.7 kΩ bias holds A high → effectively a 3.3 V UART signal when unterminated; recorded on [[controller-link]] as the bench-only first try (unverified). Wireless leg (ESP-NOW first, BLE later) to be built alongside the v2 protocol regardless; B-as-I2C-slave noted and not pursued. + +## [2026-09-21] update | Bench link VERIFIED on the bare A line; both boards reflashed + +Both boards flashed from current sources (5B → COM11, 1.3 → COM10). Bench check with `485_A` → IO1 + GND, no transceiver on B, 120 Ω OFF: B reports connection established, 38 packets / 10 s, 0 checksum / 0 framing errors, valid flags 0x3F, debug flag mirrored; A logs 23-byte packets on GPIO 44 every 200 ms (UART auto-started from NVS). Open question #1 answered for the bench and re-scoped to "will it survive the car". [[controller-link]] updated. Note: opening the 5B's USB-CDC port from the PC resets the board. + +## [2026-09-21] update | Protocol v2 + ESP-NOW + gauge outputs implemented and bench-verified + +Implemented in both repos (not yet committed): shared header v2 (typed DATA/CONFIG frames, `gear_lever` + target/engaged nibbles, `engine_rpm`, `alerts` bitmap, `link_config_t`); A: `Tunables` (NVS + `cfg` serial console), `EspNowLink` (broadcast leg, radio held in STA), UART manager sends every frame on both paths, CAN driver publishes gear pieces + evaluates alerts; B: `UARTReceiver::processFrame()` shared by the UART framing task and the new `EspNowReceiver` (channel hopping), dedupe on packet_id, CONFIG cache in NVS, `GaugeOutputs` (tach IO7 14-bit LEDC, coolant IO8 8-bit PWM), gear label pulses while target != engaged and turns red on mismatch, icons driven by A's alert bits. Bench: 42/42/42 frames applied/uart/espnow with 42 duplicates and 0 errors; ESP-NOW locked on ch 1; CONFIG on both paths; `cfg override rpm 2000` -> 133.3 Hz on IO7; coolant 89 C -> duty 183. Two bench-found fixes: tach needs 14-bit LEDC resolution (8-bit cannot reach 100 Hz) and the shared temperature formatter must not emit a degree sign (B's font lacks the glyph). Pages updated: [[controller-link]], [[link-redundancy]], [[patrol-gauge-outputs]], [[open-questions]] (#2, #4, BLE-vs-ESP-NOW and tunables-location moved to Answered; #5/#5b reworded); index updated. + +## [2026-09-21] update | Gauge Tuning touchscreen page on A; calibration procedure filed + +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]]. diff --git a/wiki/pages/controller-link.md b/wiki/pages/controller-link.md index 5598333..b7c356b 100644 --- a/wiki/pages/controller-link.md +++ b/wiki/pages/controller-link.md @@ -15,12 +15,20 @@ BMW PT-CAN ──▶ Controller A (5B) ──UART 5 Hz──▶ Controller B (1. Architecture rule: **B never touches CAN.** Anything B needs must be put into the packet by A. See `(sibling: 5B wiki → dual-controller-architecture)` for A's view of the same link. -## Wire-level contract (repo, both repos' `include/protocol/automotive_data.h` and `docs/UART_PROTOCOL.md` (5B repo)) +## Wire-level contract — protocol v2 `(repo, 2026-09-21; spec: 5B repo docs/UART_PROTOCOL.md)` -- 115200 8N1, 3.3 V TTL, one direction A → B, 5 Hz (every 200 ms) -- Frame: `0xAA` · version `0x01` · length `0x12` · 18-byte payload · XOR checksum · `0x55` = **23 bytes** -- Payload (little-endian): `packet_id` u8 · `timestamp_ms` u32 · `gear_position` u8 · `gearbox_oil_temp` i16 (0.1 °C) · `engine_oil_temp` i16 (0.1 °C) · `coolant_temp` i16 (0.1 °C) · `battery_voltage` u16 (0.01 V) · `fault_codes` u16 bitmap · `valid_flags` u8 · `debug_enabled` u8 -- B declares the link **lost after 1000 ms** without a valid packet and shows a no-data state `(repo)`; A only transmits while its CAN task is running (CAN toggle ON → UART auto-starts) `(repo)` +- One direction A → B, on **two transports at once**: UART1 115200 8N1 and **ESP-NOW broadcast** (channel 1; B hops 1–13 while silent and locks when frames arrive). B dedupes DATA frames on `packet_id` + `timestamp_ms`. +- Frame: `0xAA | version 0x02 | type | length | payload | XOR | 0x55`. Types: **DATA** (21-byte payload, every 200 ms) and **CONFIG** (27-byte payload, on start, on every tunables change, and every 5 s). +- DATA payload: `packet_id` · `timestamp_ms` · `gear_lever` (P/R/N/D/S/M) · `gear_nibbles` (target ≪ 4 | engaged) · `engine_rpm` · gearbox / engine-oil / coolant temps (0.1 °C) · `battery_voltage` (0.01 V) · `alerts` bitmap · `valid_flags` · `debug_enabled`. +- CONFIG payload = `link_config_t`: tach ppr/trim/clamps, coolant PWM Hz + duty law + min temp, enables, bench override, alert thresholds — edited on A (`cfg` serial console, NVS), executed on B ([[patrol-gauge-outputs]]). +- Alerts are decided on A from its thresholds; B only renders the bits (icons red, gear label red on mismatch). +- B declares the link **lost after 1000 ms** without an applied DATA frame on any transport and drops both gauge outputs; A transmits while its CAN task runs `(repo)`. + +**Bench-verified 2026-09-21** `(verified)`: 42 frames / 10 s applied, 42 seen on UART, 42 on ESP-NOW, 42 duplicates dropped, 0 checksum / framing / version errors; ESP-NOW locked on channel 1; CONFIG frames received on both paths; `cfg override rpm 2000` typed on A's console reached B and produced a 133.3 Hz tach output within a second, and clearing it dropped the output. + +### v1 for reference + +23-byte single-type frame with one `gear_position` byte and a `fault_codes` word. Retired 2026-09-21; B counts any non-v2 frame as a version error. ### What each field actually carries today (sibling: 5B wiki → can-id-candidates) @@ -29,10 +37,10 @@ Architecture rule: **B never touches CAN.** Anything B needs must be put into th | `coolant_temp` | CAN 0x1D0 byte 0, raw − 48 | verified live | | `gearbox_oil_temp` | CAN 0x0B5 byte 7, raw − 40 | verified live | | `engine_oil_temp` | CAN 0x1D0 byte 1 | **dead — sensor not fitted on this M57N, reads 0xFF**; B will never get a real value | -| `gear_position` | CAN 0x1D2 lever/mode + 0x0BA target gear | verified live | +| `gear_lever` + `gear_nibbles` | CAN 0x1D2 lever/mode + byte 1 engaged gear; 0x0BA target gear | verified live; `target != engaged` = shift in progress (B pulses the digit) | | `battery_voltage` | CAN 0x3B4, 12-bit × 0.015 V | verified live | -| `fault_codes` | A's own derived faults (bit 0 = lever vs gearbox mismatch), **not** DDE DTCs | `(repo)` | -| RPM | **not in the packet** — A has it verified from CAN 0x0AA but the protocol has no field | needed by [[patrol-gauge-outputs]] | +| `engine_rpm` | CAN 0x0AA | verified live on A; on the wire since v2 (2026-09-21) | +| `alerts` | A's thresholds (`link_config_t`) + CAN status bits | v2 | ## Pins @@ -43,11 +51,34 @@ Architecture rule: **B never touches CAN.** Anything B needs must be put into th > The 5B repo's root `CLAUDE.md` (corrected 2026-09-21) and this repo's former `.docs/UART_WIRING_GUIDE.md` (deleted 2026-09-21) both said "GPIO 43 TX". The 5B firmware and `docs/UART_PROTOCOL.md` (5B repo) say **44**. The code wins `(repo)`. > [!warning] GPIO 44 on the 5B is not a bare pin — it feeds an RS485 transceiver -> On the 5B schematic, IO44 is the `RS485_TXD` net into an SP3485 with automatic direction control, and only the differential **A/B pair** reaches the terminal block `(sibling: 5B wiki → esp32-s3-touch-lcd-5b)`. Both wiring guides describe a direct "GPIO 44 → IO1 + GND" TTL wire, which the 5B does not physically expose. So either (a) the RS485 A line is being fed straight into B's TTL input and happens to work, (b) there is an RS485→TTL module on the B side that the docs don't mention, or (c) the wire is soldered to the module pin. **Which one is true is unknown** `(unverified)` and it decides how robust the wired link is in the car → [[open-questions]] #1, [[link-redundancy]]. +> On the 5B schematic, IO44 is the `RS485_TXD` net into an SP3485 with automatic direction control, and only the differential **A/B pair** reaches the terminal block `(sibling: 5B wiki → esp32-s3-touch-lcd-5b)`. Both wiring guides describe a direct "GPIO 44 → IO1 + GND" TTL wire, which the 5B does not physically expose. So either (a) the RS485 A line is being fed straight into B's TTL input and happens to work, (b) there is an RS485→TTL module on the B side that the docs don't mention, or (c) the wire is soldered to the module pin. **Answered 2026-09-21: it is (a)** — the bare A line into IO1 works on the bench (verified, see bench wiring below). Whether it survives a car-length run is a separate question → [[open-questions]] #1, [[link-redundancy]]. -## Protocol drift between the two repos +## Bench wiring (recommended, 2026-09-21 — unverified until run) -> [!warning] The `gear_position_t` enums differ `(repo, 2026-09-21)` +The 5B exposes UART1 only as the RS485 pair on its terminal block (`485_A`, `485_B`), so B needs a **3.3 V RS485→TTL module** (MAX3485 / SP3485; not a 5 V MAX485 without a divider on RO — ESP32 inputs are not 5 V tolerant). + +| 5B terminal | → | Module | → | 1.3 left header | +|---|---|---|---|---| +| `485_A` | | A | | | +| `485_B` | | B | | | +| `GND` | | GND | | pin 2 GND | +| | | VCC | | pin 3 3V3 | +| | | RO | | pin 4 IO1 (UART1 RX) | +| | | DI / DE / RE | | unconnected, or DE+RE tied low (receive-only) | + +Termination: the 5B's single 120 Ω switch serves CAN *and* RS485 — may be ON on the bench with no vehicle bus, **must be OFF before the 5B meets the car's CAN**. Desk-length runs don't care. + +**Zero-parts bench alternative (no RS485 module available, 2026-09-21):** `485_A` → IO1 plus GND → GND. On the 5B schematic the SP3485 runs from 3.3 V (A can never exceed 3.3 V), the auto-direction circuit enables the driver only while sending a 0, and 4.7 kΩ bias resistors hold A high at idle — so with no 120 Ω load, A carries a plain 3.3 V UART signal with GPIO 44's polarity. **(verified on the bench 2026-09-21: 38 packets / 10 s, 0 checksum, 0 framing errors, all valid flags set; both boards on USB, 120 Ω switch OFF.)** This is almost certainly what the old wiring guide's "GPIO 44 → IO1" line described. **Bench only**: the bias pull-up will not hold up over a car-length run; the car gets a transceiver or the wireless leg. Keep the 5B's 120 Ω switch OFF for this. + +Other zero-parts paths considered: ESP-NOW / BLE (the planned wireless leg, → [[link-redundancy]]) and B as an I2C slave on the 5B's I2C terminal (fiddly — A's bus is owned by the display library and shared with touch + RTC; not pursued). + +Bench check before any protocol work: both boards on USB, monitors at 115200; CAN toggle ON on the 5B (its UART starts with the CAN task, no bus needed, default values at 5 Hz); B should report the connection established and packet counts rising with zero checksum/framing errors. Framing errors = A/B swapped; nothing at all = module not in receive or no common ground. + +## Protocol drift between the two repos — resolved by v2 + +> [!note] Resolved 2026-09-21: the wire no longer carries `gear_position_t`. v2 sends `gear_lever` plus target/engaged nibbles, and the header is copied byte-identical to B (`cmp`-checked). The history below is kept for the record. + +> [!warning] The `gear_position_t` enums differed `(repo, before v2)` > - **B's header** (matches `docs/UART_PROTOCOL.md` (5B repo)): 0 P · 1 R · 2 N · 3 D · **4 Sport · 5 Manual** · 6–13 M1–M8 · 14 Error > - **A's header** (rewritten during CAN decoding): 0 P · 1 R · 2 N · 3 D · **4–9 M1–M6** · 0xFF Unknown > diff --git a/wiki/pages/link-redundancy.md b/wiki/pages/link-redundancy.md index 157f0de..2167c55 100644 --- a/wiki/pages/link-redundancy.md +++ b/wiki/pages/link-redundancy.md @@ -6,7 +6,7 @@ updated: 2026-09-21 # Link Redundancy: wired + wireless -Stated goal (user, 2026-09-21): connect B to A "through some serial or BLE, or maybe a combination of both as redundant in case the wired connection is lost." This page is the design space. **Nothing here is decided or verified** — every item is `(unverified)` unless labelled otherwise. +Stated goal (user, 2026-09-21): connect B to A "through some serial or BLE, or maybe a combination of both as redundant in case the wired connection is lost." This page is the design space. **Status 2026-09-21: ESP-NOW is implemented and bench-verified as the second transport** (see below); the RS485 question and BLE remain open. Items are `(unverified)` unless labelled otherwise. ## Why redundancy matters more once B drives gauges @@ -21,6 +21,13 @@ Today a lost link only blanks a secondary display. Once B drives the cluster's t | **BLE 5 GATT** (A = peripheral notifying, B = central) | both boards have BLE 5 `(source: waveshare-wiki-esp32-s3-lcd-1-3)`; connection-oriented, so B gets an explicit disconnect event; notify payload of 23 bytes fits one packet | connection setup/reconnect takes hundreds of ms to seconds; BLE stack costs RAM on both ends (NimBLE is the lighter choice on Arduino-ESP32); A's Core 0 already runs Wi-Fi scanning + CAN + UART, and Wi-Fi/BLE coexistence on one radio can add jitter | The user's stated candidate | | **ESP-NOW** | connectionless, ~ms latency, no pairing state, trivially broadcast the same 23-byte frame; both are ESP32-S3 so it is a one-call API | Wi-Fi-based, so it shares the radio with A's Wi-Fi scanning; no link-layer "disconnected" event — liveness must come from the existing 1 s timeout | Worth benchmarking against BLE before committing; simpler failover semantics | +## What was built (2026-09-21, verified on the bench) + +- A broadcasts every frame on **both** UART1 and ESP-NOW (channel 1, broadcast peer, radio held in STA mode; the WiFi manager's "off" no longer powers the radio down). +- B receives on both, hands every frame to one `processFrame()`, dedupes DATA on `packet_id` + `timestamp_ms`, and tracks per-transport liveness (`uart alive, espnow alive`). While ESP-NOW is silent B hops channels 1–13 every 400 ms and locks when frames arrive. +- Result on the desk: every frame seen on both paths, all duplicates dropped, zero errors. Pulling either path should leave the other carrying the link — **not yet tested by physically pulling the wire** `(unverified)`. +- Not built: B talking back, BLE, an on-screen indicator of which path is live (the serial stats line shows it). + ## Failover design sketch 1. B keeps **one** packet consumer. Every transport (UART, BLE/ESP-NOW) feeds validated `automotive_data_t` frames into the same queue, tagged with a source id. diff --git a/wiki/pages/open-questions.md b/wiki/pages/open-questions.md index dc459f8..2243b96 100644 --- a/wiki/pages/open-questions.md +++ b/wiki/pages/open-questions.md @@ -10,16 +10,16 @@ The research frontier for Controller B. Answering any of these should trigger up ## Blocking -1. **How is the wired link physically connected today?** The 5B's GPIO 44 only leaves the board as an RS485 A/B pair through an SP3485, yet both wiring guides describe a direct TTL wire into IO1. Is the RS485 A line going straight into IO1, is there an RS485→TTL module on B, or is it soldered to the module? Decides whether the wired leg is trustworthy in the car and what [[link-redundancy]] has to cover. → [[controller-link]] -2. **Which `gear_position_t` enum is correct?** A's and B's protocol headers disagree on values 4–13 (Sport/Manual vs M1–M6). Check what A's CAN parser emits, fix the other side, bump `PACKET_VERSION`. → [[controller-link]] -3. **Which Nissan Patrol cluster, and what does its tach input expect** (signal source, pulses per rev, pull-up voltage)? Fixes the frequency range for the tachometer output. → [[patrol-gauge-outputs]] +1. **Will the bare `485_A` → IO1 link survive the car?** On the bench it works (verified 2026-09-21) because the SP3485's 4.7 kΩ bias holds A high when unterminated. Over a car-length harness with noise and possible termination it may not. Decide: RS485 module on B, or rely on the wireless leg → [[link-redundancy]], [[controller-link]] +3. **Which Nissan Patrol cluster, and what does its tach input expect** (signal source, pull-up voltage)? Pulses per rev stated by the user as **4** (2026-09-21), unverified on the bench. Fixes the frequency range for the tachometer output. → [[patrol-gauge-outputs]] ## Active -4. **Add `engine_rpm` to the packet.** A has RPM verified from CAN 0x0AA `(sibling: 5B wiki → can-id-candidates)` but the protocol carries no RPM field. Needed before the tachometer can be driven. → [[controller-link]] -5. **BLE GATT or ESP-NOW for the wireless leg?** Benchmark reconnect time, latency and RAM cost on A (whose Core 0 already runs Wi-Fi + CAN + UART). → [[link-redundancy]] +5. **Is ESP-NOW enough, or is BLE still wanted?** ESP-NOW is built and works on the bench. Open: behaviour when A joins a Wi-Fi AP (channel follows the AP; B hops — untested), range in the car, and whether BLE's disconnect event is worth its RAM. → [[link-redundancy]] +5b. **Pull-the-wire test.** Both transports carry every frame on the desk; physically removing the UART wire (and separately blocking the radio) to confirm seamless failover has not been done. → [[link-redundancy]] 6. **Gauge behaviour on link loss** — zero, hold + warn, or sweep to a "no data" mark? A safety/UX decision the user must make. → [[link-redundancy]] -7. **Temp sender resistance curve** as seen by the gauge, for the °C → duty lookup. → [[patrol-gauge-outputs]] +7. **Temp gauge °C → duty curve — partly answered.** The user's old CANNY program gives `duty = 1.5·T + 50` on 0–255 ([[temp-stage-cfd]]). Still needed: the old circuit's series resistor / driver and PWM frequency, and a needle check with the new MOSFET stage. Measurement procedure is on [[patrol-gauge-outputs]]. +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?** Its CAN source reads 0xFF on this engine (sensor not fitted). B currently reserves screen space and a warning threshold for it `(repo)`. Drop it, or repurpose the slot. ## Hardware @@ -31,6 +31,13 @@ The research frontier for Controller B. Answering any of these should trigger up ## Answered +- ~~Which `gear_position_t` enum is correct?~~ → **Moot**: protocol v2 (2026-09-21) sends lever + target/engaged nibbles; header copied byte-identical to B. → [[controller-link]] +- ~~Add `engine_rpm` to the packet.~~ → **Done in v2** (2026-09-21), `valid_flags` bit 6. → [[controller-link]] +- ~~BLE GATT or ESP-NOW for the wireless leg?~~ → **ESP-NOW first**, implemented and bench-verified 2026-09-21; BLE stays optional (#5). → [[link-redundancy]] +- ~~Where do the gauge tunables live?~~ → **On A** (`Tunables`, NVS, `cfg` console), pushed to B in CONFIG frames, cached on B (verified 2026-09-21). → [[patrol-gauge-outputs]] + +- ~~How is the wired link physically connected today?~~ → **Bare `485_A` straight into IO1, common GND, no transceiver on B.** Bench-verified 2026-09-21: 0 errors at 5 Hz. Works because of the 5B's SP3485 bias resistors; bench-only until proven in the car (now #1). → [[controller-link]] + - ~~Does the 1.3 have free PWM-capable GPIO?~~ → **Yes, 13 on the headers** (IO1–5, IO7–14), 10 fully free today. (verified from pinout photo, 2026-09-21) → [[esp32-s3-lcd-1-3]] - ~~Could the 5B drive the gauges itself?~~ → **No.** All native GPIO consumed; its DO terminals go through an I2C expander + optocoupler and cannot carry hardware PWM. (schematic reviewed 2026-09-21) → [[patrol-gauge-outputs]] - ~~Which GPIO does A transmit on?~~ → **GPIO 44** per A's firmware; the "43" in two docs is stale. `(repo)` → [[controller-link]] @@ -43,3 +50,4 @@ The research frontier for Controller B. Answering any of these should trigger up - Nissan Patrol **cluster wiring diagram** for the target generation — tach input and temp sender pins - Scope capture of the original Patrol tach signal at idle and a known RPM, if the original engine's cluster wiring still exists - Datasheet or Waveshare note on the board's operating temperature range +- CANNY 5.3 pico datasheet / CannyLab HR PWM documentation (PWM clock, output stage), or a scope trace of the old unit's output diff --git a/wiki/pages/patrol-gauge-outputs.md b/wiki/pages/patrol-gauge-outputs.md index 1bb99da..bd1d3b1 100644 --- a/wiki/pages/patrol-gauge-outputs.md +++ b/wiki/pages/patrol-gauge-outputs.md @@ -16,15 +16,18 @@ Controller A (5B) has no free native GPIO on any header: the RGB LCD, I2C, CAN, | Gauge | What the cluster expects | What B must generate | Status | |---|---|---|---| -| Tachometer | a pulse train whose **frequency** tracks engine speed; the source and pulses-per-revolution depend on the cluster variant | variable-frequency square wave at ~50 % duty, on one LEDC channel with its **own timer** | source data (RPM from CAN 0x0AA) verified on A `(sibling: 5B wiki → can-id-candidates)`; **not yet in the packet** | +| Tachometer | a pulse train whose **frequency** tracks engine speed — **4 pulses per revolution** on this cluster (user, 2026-09-21; not yet bench-verified) | variable-frequency square wave at ~50 % duty, on one LEDC channel with its **own timer** | source data (RPM from CAN 0x0AA) verified on A `(sibling: 5B wiki → can-id-candidates)`; **not yet in the packet** | | Coolant temp | a moving-coil/bimetal gauge that reads the **resistance to ground** of the sender | fixed-frequency PWM with variable **duty** into a low-side switch, so the gauge integrates it as an average resistance | coolant already in the packet as 0.1 °C | The two need separate LEDC timers because one varies frequency and the other varies duty. ESP32-S3 LEDC has 8 channels on 4 timers `(unverified — datasheet figure from memory, confirm)`. -## Proposed pin assignment (unverified — proposal only) +## Pin assignment (implemented 2026-09-21) -- **IO7** → tachometer pulse output -- **IO8** → coolant gauge PWM output +- **IO7** → tachometer pulse output — LEDC channel 2 (timer 1), **14-bit** resolution so the divider reaches low frequencies (~4.8 Hz .. ~4.9 kHz; 8-bit could not even do 100 Hz), 50 % duty +- **IO8** → coolant gauge PWM output — LEDC channel 4 (timer 2), 8-bit duty at `temp_pwm_hz` (default 1 kHz) +- LEDC channels 0/1 (timer 0) belong to the display backlight; never reuse them `(repo)` + +**Bench-verified 2026-09-21** `(verified)`: with A's default 89 °C coolant, B drives IO8 at duty 183/255 (1.5·89 + 50); `cfg override rpm 2000` on A's console produced 133.3 Hz on IO7 (2000 × 4 / 60), and clearing it dropped the output. Both outputs stay low with no link or no valid value. Still unverified: the **needle** — nothing is connected to the cluster yet and the external driver stage does not exist. Both on the right header, adjacent to GND-free pins, so add a ground wire from the left header. IO3 deliberately avoided (strapping pin). IO1 stays the UART RX. @@ -36,11 +39,73 @@ Both on the right header, adjacent to GND-free pins, so add a ground wire from t - **Temp gauge**: sender wire goes to ground through the sender's thermistor. Emulate it with a logic-level N-MOSFET (or NPN) pulling the sender wire to ground under PWM, plus a series resistor sized so 100 % duty corresponds to the hottest resistance you want to show. The gauge's thermal/mechanical lag averages the PWM; use a few hundred Hz to 1 kHz so nothing flickers. Calibration is a lookup table from °C → duty, built empirically against the needle. - Optocouplers between B and the 12 V cluster side are cheap insurance; the 5B's own DO stage (PC817 → transistor) is a reasonable pattern to copy. +## Characterising the gauges (procedure, unverified until run) + +The coolant gauge is a **current meter, not a pulse input** — there is no pulse count to find. The sender is a thermistor to ground; the needle follows the current through the gauge coil, which follows the sender's resistance. What has to be measured is the resistance → needle curve. + +Coolant gauge, ignition on, engine off, sender disconnected: +1. 1 kΩ linear pot (or decade box, or fixed 47/100/220/470 Ω) from the sender wire to chassis ground. Sweep; record the resistance at the cold mark, middle, hot mark and start of the red zone (read the pot disconnected). +2. At each point also record the sender-wire voltage. Constant regardless of resistance → regulated supply, bimetal gauge. Proportional drop → plain series coil. +3. Needle lag of seconds → bimetal; near-instant → air core. Both average PWM; bimetal is more forgiving. +4. Series current at the hot-mark resistance = the peak the MOSFET stage must sink (expect tens of mA). + +PWM drive from the curve: +- Logic-level N-MOSFET low side, drain to the sender wire through a fixed resistor equal to the hottest resistance ever to be shown; 100 % duty = hottest reading, the gauge integrates lower duties. +- 500 Hz – 2 kHz. Older Nissan clusters feed gauges from a chopped instrument voltage regulator at a few Hz `(unverified)`; PWM near that rate beats against it. Scope the sender wire once to see whether the chopper exists. +- Build the °C → duty lookup from where the needle actually lands at each duty step, not from any sender datasheet. + +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. + +## 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: + +- Same decode the 5B later verified: CAN 0x1D0 byte 0, raw − 48 °C. +- **Duty = 1.5 × T + 50 on a 0–255 scale**, i.e. 110/255 at 40 °C, 200/255 at 100 °C, saturating near 137 °C. Duty *rises* with temperature (NTC sender emulation). +- Output only enabled above a minimum temperature (constant 0 in the file, 40 °C in the comment). +- Output was the controller's own push-pull pin with PWM pull-up enabled; the external circuit and the PWM frequency are **not** in the file. + +Starting point for the LEDC implementation: 8-bit duty, `duty = clamp(1.5·T + 50, 0, 255)`, output disabled while the coolant value is invalid or the link is down. Verify against the needle before trusting it — the old drive circuit may differ from the new MOSFET stage, which shifts the whole curve. + +## 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: + +| Group | Parameter | Default | Note | +|---|---|---|---| +| Tach | pulses per rev | 4 | user figure | +| Tach | fine trim % | 0 | needle reads N % off at a known rpm | +| Tach | min / max output Hz | tbd | clamp against bad rpm values | +| Temp | PWM frequency Hz | **unknown** | from the CANNY measurement ([[temp-stage-cfd]]) | +| Temp | duty slope, offset (fixed-point) | 1.5, 50 | from the CANNY law | +| Temp | min temperature gate °C | 40 | output off below | +| Temp | duty clamp | 255 | | +| Both | output enable | on | per gauge | +| Both | **calibration override** | off | force a fixed rpm / fixed duty from A's screen and watch the needle | + +Transport: CONFIG frames in protocol v2, sent on start, on every change (`cfg_version` bump) and every 5 s; overrides are pushed but never saved on either side. Console: `cfg show`, `cfg set `, `cfg override rpm | duty | both | off`, `cfg reset` → [[controller-link]]. + +Measuring the CANNY's PWM without a scope: use a free 1.3 header GPIO with the ESP32 pulse-counter peripheral as a frequency/duty meter (resistor divider if the CANNY output exceeds 3.3 V). Same sketch later verifies B's own outputs. Planned as a separate PlatformIO environment in this repo. + +## Calibration procedure (touchscreen or console) + +Tachometer, with the driver stage on the tach wire: +1. Force 1000 rpm (override). The needle should read 1000. +2. A constant-factor error means the wrong pulses/rev — change it until 1000 reads 1000. +3. Force 3000 rpm; a small residual is the trim (%). +4. Override off. + +Coolant gauge, with the MOSFET stage on the sender wire: +1. Force duty 110 (the CANNY program's 40 °C point) and note the needle; sweep 140 / 170 / 200 / 230. +2. From two marks (Tc at duty A, Th at duty B): slope = (B − A)/(Th − Tc), offset = A − slope × Tc; enter slope × 100 and offset. +3. Needle flicker or wander → raise PWM frequency. No response at all → driver stage / pull-up, not the numbers. +4. Override off. Values are saved on A and pushed to B at once. + ## What must be established before any of this is wired -1. **Which Patrol cluster** (Y60/Y61, petrol vs diesel). Diesel clusters were fed from the alternator W-terminal at a much higher frequency and often have a calibration trimmer; petrol clusters expect ~3 pulses/rev for a 6-cylinder from the ignition system `(unverified)`. This fixes the frequency range and therefore the LEDC resolution/prescaler. → [[open-questions]] +1. **Which Patrol cluster** (Y60/Y61, petrol vs diesel). User states **4 pulses/rev** (2026-09-21); confirm on the bench with the procedure above, since diesel clusters fed from an alternator W-terminal and petrol clusters fed from ignition differ `(unverified)`. This fixes the frequency range and therefore the LEDC resolution/prescaler. → [[open-questions]] 2. Whether the cluster's tach input has an internal pull-up, and to what voltage (meter it). -3. The temp sender's resistance-vs-temperature curve as the gauge sees it (meter the original sender at cold/hot, or sweep a pot until the needle sits at known marks). +3. The temp sender's resistance-vs-temperature curve as the gauge sees it (meter the original sender at cold/hot, or sweep a pot until the needle sits at known marks). The CANNY-era duty law in [[temp-stage-cfd]] is the starting table; it still needs a needle check with the new driver stage, plus the old circuit's series resistor and PWM frequency. 4. Protocol change: add `engine_rpm` (u16, 1/min) and a `valid_flags` bit to the packet; bump the version on both repos → [[controller-link]]. 5. The outage policy: what the needles do when the link is lost → [[link-redundancy]]. diff --git a/wiki/raw/temp_stage.cfd b/wiki/raw/temp_stage.cfd new file mode 100644 index 0000000000000000000000000000000000000000..d6ce8a809e72de4ddb7faa53e80a464daee38377 GIT binary patch literal 5394 zcma)A6O702&$#%X4n;_~6p6q;V=i;2^*XWFDq9a`dgoYcjh7-N^PL3;7L*yE3J zu*Z>FiA5p-5(_p|LPAhjAeBm8p{6PuHj!Y#qFu58sVrC|NJ#C1ERbsczdLi2JCkeC zBi%Reocq7$o_p^3cr!6xt9{p=U#LyYPhG5yPuuF$_=UOg8GC+edeZDS#`I|vG!pmr zh~D;S3~TgKBEc^nHs;j6-kE+0j%a|$nbh=~U+V2^9Z6ol6XP{|x?En>lrdlFOnkbt zv-4r{6It+~Bp8B%E{G62JLZ<8cQml<9t0C%eqhdO06|Mm<57)^3-hxJ^Jnd=)#~U{ zv+k5WBe`2{J}@7dyW(mZI*~c3u`oV2Z|5$J&R??6KU*%B&Xj7UN@;dsm!->Eg8%;S zQh!=blDJ)OXc>-nw(Ql5_tee&qPdyJA@50wtC9rs@ZQ`dJ5`-Fz(<(S*em#62gfXkrFJe`%o^9Sx|=(}yvF-l^}bt`6Z;U-1Zz5*R4ZfEvJ)TcEO;k>*}Ri~ zTb#EuN&KD8Y}7Lc_P236|FOB9@4B$$b6WcHoSps7jGfIk8yj`E;^~h1>-hn5-L3HV zmm~)?SDm_OQE&A-v79!W*_y3%?R6*riMf-1PFIe*h{`0~t75C$t=HU&r#gELYQ>;i z!Co99=_6V?)>Z6eGrhdlK2fQ&=7825aBJ{#!L9jxxMp^HZLPF@)otWG^hW=Zd80oJ zvGz?8WEFR;F8EvhtL7~S_hEG({`7sgzrr{B8|F<1zZXjG3ftNhz|)g8=MT=toii{E z!cSgK&fy6tl#^(j77FELR}4?6atBa|CnjThh&rMV3h}(h^l($LeYuU8ev*dVhC=-$ z?6Q+~%ZYzn39)us1M?o&pp?BPW?R4bO|&zX4v@|}iHKO8&(^PIn`vu%Gqta#n+<|! z%VpiTm^D|p{vjMXf0pFT&*gaZ;s1LjmDCLtT}Zc=vUWw|K3qNMsRmBL7d1!n-e0Sn zskaM4yd1dL;||(6-}Xh2rJc-i3Br+k)5B#!GzW0-lNvs-a5jp2>;^_Wde{xU4`}Ri z6yV1@@PEsPEXA()=|EF-QGQUK1C6o4fw}La8bG!bq(2p`toPVq!BPr6_IJXb6dyf5 z;KKoUk20nr{z2!GN=G`#0n?Y{lEnO7{J4gLJBPR)(|XFk#H$7P>uqb}Xt)rHW99W?Ktf5h0YvfmRt4rzqYf}pviV0HxKN?j-# zs~0n*0ko)rk`dF_ms4}yFW7&89@cOdVn%s`Le*_6_L@IPc#Fx?JSfOcWvKd?*&{3V zn?FhTH&hRUa$29_jd%!E_dBZ}arhD{70DI&FO$<*W5+6{ghd>}8pioY_#_%+Z zn-P1gKPIr!ylIX2?YQY;*W?Yw4hLaRQ%gc+AXKr(>S0IPYb#pkrNBIBl4o; zG5?cpySWi4M7csa;iz}TqVgvzj03VlN9J7cYLCtueE;Ft~Z)px+zyN zU(zLAY1MCN3q>tvJGCst7sX@CGaAGcwhXB<@lNB$mUOkXo$4z*)PG8ICtcEa?@M8e z`Iy2Olhe*(zNf<-is+~5or%clgL4r%t&!>sh4#}ee-x3^K!4Mb=k-p_!9Oo*{5K;1 zhUBhc>Nmun+XX)^`L{YT72;o#+}E&BJ|X#V1Yec>uNWo@@sr|X`16wgC4#>oxsR(* z&&#{urzGcV84B^Qh<{99Zcr%yrufx}{nL_vOa~N&_!;rvi{PoJ$0GVKO8#j_4l=1yGp%RNhH^ocVT6NM%C=aS1-6-4 zG+|}AaAnL++NG67YdN)7SF)|v#&XuO>lt&y_S?%@v$1|wOSUrG(mx~H++MZW)^ZCS zc70=u3~yX(yuM-6t>#K*uWUD0w;CJGk>D>=LEiHTL^61u=1UTIo~C;);AyrYo+ca4 z(?rAdG*6Pm>!WGD6!0`lg5S^63<-MA(*y}p&(q{cBG1#@NCwXj>769-{9(Nl{GLCm z_s|~r(4J%BL;difeaFRz_Q8kyll0;K@ZtVN@dUZIhvxH2z|(X{GCxnV>E%f_KTpHx x tmp_min) tmp_min constant = 0 in this file +HR PWM 1 Duty = Enable ? Duty : 0 +``` + +The comment box (Albanian, translated): *"Calculation: D = ((T − RT) × 15 + 1100) / 10. a: D = Duty. b: T = temperature coming from the ECU. c: RT = reference temperature (40 °C). d: 15 → 1.5 (coefficient per degree) × 10. e: 1100 → 110 (duty at 40 °C) × 10. f: everything divided by 10. Note: if temp is not 40, do not activate any function."* + +Simplified: **Duty = 1.5 × T + 50**, on a **0–255** period. Points: + +| T °C | Duty /255 | % | +|---|---|---| +| 40 | 110 | 43 | +| 60 | 140 | 55 | +| 80 | 170 | 67 | +| 90 | 185 | 73 | +| 100 | 200 | 78 | +| 110 | 215 | 84 | +| 120 | 230 | 90 | +| ≈137 | 255 | 100 (saturates) | + +## What this establishes + +- The **CAN decode is the same one the 5B verified** in 2026: ID 0x1D0, byte 0, raw − 48 °C `(sibling: 5B wiki → can-id-candidates)`. Independent confirmation from a working installation years earlier. +- The gauge was driven by **PWM duty rising with temperature**, linearly, with a non-zero floor at 40 °C. Consistent with emulating an NTC sender (resistance falls as temperature rises) through a switch and series resistor. +- The output was the CANNY's own IO channel 1 in push-pull mode with the PWM pull-up enabled — i.e. the gauge line was driven (or a driver stage was fed) directly from the controller pin `(source: file; external circuit unknown)`. +- The linear duty law means the gauge + drive circuit behaved close to linear in duty over 40–120 °C, or the user accepted a linear approximation. Either way this is the °C → duty table to start from. + +## What it does NOT tell us + +- The **PWM frequency**: "HR PWM Period = 255" is in CANNY timer ticks of an unknown base clock `(unverified)`. Look up the CANNY 5.3 pico HR PWM clock, or scope the old unit. +- The **external circuit** between the CANNY pin and the gauge sender wire (series resistor value, any transistor). Ask the user / inspect the old harness. +- Whether the cluster is the same one the 1.3 board will drive (assumed yes). +- Why `tmp_min` is 0 while the comment says 40: either edited later or the gate was relaxed. With 0 the output is enabled for any positive temperature. + +## Relevance + +- Answers most of [[open-questions]] #7 (temp gauge curve) — as a starting table, pending a bench check on the actual needle. +- Sets the initial LEDC design for [[patrol-gauge-outputs]]: 8-bit duty, `duty = 1.5·T + 50` clamped to 0–255, output enabled only with a valid temperature. + +## Related + +[[patrol-gauge-outputs]] · [[controller-link]] · [[open-questions]]