diff --git a/CLAUDE.md b/CLAUDE.md index 3f76265..090c104 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,6 +84,7 @@ src/ diag_probe.cpp # On-demand OBD-II requests ('diag' console) - the ONLY CAN transmitter perf_monitor.cpp # 'perf' console: render fps, flush cost, LVGL/CPU idle, heap (display experiments) ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console) + link_peer.cpp # Controller B over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' console) settings_manager.cpp # NVS persistent storage ui_state_manager.cpp # Debug flag (performance overlay, sent to B) display_init.cpp # Display initialization; boots into DrivelineScreen @@ -104,13 +105,14 @@ include/ **src/main.cpp** (~1530 lines) - Main application logic, event handlers, FreeRTOS task implementations -- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`), setup order, `loop()` ticks for the three screens +- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`, `link`), setup order, `loop()` ticks for the three screens **include/protocol/automotive_data.h** - **Shared with Controller B, must stay byte-identical in both repos.** Protocol v2 (2026-09-21). - `automotive_data_t` (DATA payload): gear lever + target/engaged nibbles, rpm, 3 temperatures, battery, alert bitmap, valid flags - `link_config_t` (CONFIG payload): Patrol gauge calibration + alert thresholds, pushed A → B - Frame: `0xAA | version | type | length | payload | XOR | 0x55`; helpers `frame_build()` / `frame_parse()` +- Maintenance frames (2026-09-27, `PACKET_VERSION` unchanged): `STATUS` 0x03 B → A, `PAIR` 0x04 A → B **wire only**, `SECURE` 0x05 A → B (AES-256-GCM, `include/protocol/link_secure.h` - shared and byte-identical too). `PACKET_MAX_PAYLOAD` is 160 - Spec: `docs/UART_PROTOCOL.md` - **BMW CAN Bus ID mappings**: 11-bit PT-CAN IDs verified live on the swap bus (evidence: `wiki/pages/can-id-candidates.md`) - UART config: 115200 baud on GPIO 44 (TX) / 43 (RX, unused) — leaves the board via the SP3485 RS485 transceiver @@ -220,14 +222,18 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): ### ESP-NOW link -`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association. Never call `WiFi.disconnect(true)` or `WiFi.mode(WIFI_OFF)`: powering the radio off de-initialises ESP-NOW (`send()` re-inits it as a safety net). If Wi-Fi joins an AP the channel follows the AP; B hops to find it. +`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association. Never call `WiFi.disconnect(true)` or `WiFi.mode(WIFI_OFF)`: powering the radio off de-initialises ESP-NOW (`send()` re-inits it as a safety net). If Wi-Fi joins an AP the channel follows the AP; B hops to find it. Since 2026-09-27 it also receives (`setReceiveHandler()`, runs in the Wi-Fi task - copy and return) and unicasts to one MAC (`sendTo()`, plain peer added on first use); both are used by `LinkPeer` only. + +### Controller B over the link (`link` console) + +`src/modules/link_peer.cpp` keeps B's last `STATUS` frame (version, update phase, progress, flags; "not heard" after 15 s), owns the pairing key (NVS `linkpeer`) and drives B's updater. `link pair` generates a 32-byte key and sends it **three times over UART1 only** (`UARTManager::sendWire()`, never ESP-NOW - both repos are public, this is the one secret); B confirms with `key_fp` in its next STATUS. `tick()` pushes the remembered Wi-Fi network to B in an encrypted `SECURE` frame whenever B lacks it or it changed (hash-compared, ≥ 15 s apart; `WiFiManager::getSavedCredentials()` exists for this alone - never print the password), and a FORGET when A forgets its network. `requestCheck()` / `requestInstall()` (Settings → Updates, Controller B card) require: B heard, paired with *this* key, B has credentials, B not busy, A on Wi-Fi (same AP as B ⇒ same channel ⇒ progress frames arrive), and for install `Ota::isParked()`. Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. Design + procedure: B's wiki `controller-b-ota`. ### Screens All hand-coded in `src/modules`, built once and kept (never deleted - the old generated screens were deleted on leave, which left dangling pointers and caused the 2026-09-27 freezes). Shared look in `ui_kit.cpp` (20/24 px text, >= 56 px touch targets, no shadows/animations, `UiKit::confirm()` modal dialog). Each screen has a `tick()` called from `loop()` that refreshes values under the LVGL lock, only while it is shown, and only re-sets label text that changed. - **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning -- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (installed vs latest, Check, Install behind a confirm dialog -> `Ota::requestCheck/requestInstall`), **System** (CAN / link to B / performance overlay switches, live ESP-NOW, CAN, memory, uptime). Swipe right or the Driveline button goes back +- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Controller A -> `Ota::requestCheck/requestInstall`, Controller B -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay switches, live ESP-NOW, CAN, memory, uptime). Swipe right or the Driveline button goes back - **Gauge Tuning** (`tuning_screen.cpp`) - tabs Tachometer / Coolant gauge / Alerts / Simulation; -/+ rows with hints (hold to repeat, speeds up), per-tab Reset with confirm, "Saving... / All changes saved" footer, SIMULATION ON chip while an override is active. Swipe left or the Driveline button goes back - Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`): full-screen fades are software-blended every frame and stutter at 1024x600. The firmware version is a label on `lv_layer_top()` (bottom-right, every screen, `DisplayInit`) - The System page's "Performance overlay" switch shows LVGL's own perf monitor (real render FPS / CPU) and sets the debug flag sent to B @@ -328,6 +334,7 @@ xTaskCreatePinnedToCore( ### Build Errors +- **Build from PowerShell, not Git Bash**: `idf_tools.py` refuses MSYS ("MSys/Mingw is not supported"). The two projects also share one `framework-arduinoespressif32` package directory, so the first `pio run` after building ESP32-S3-LCD-1.3 reinstalls Arduino 3.3.3 and may fail once with `TypeError: expected str, bytes or os.PathLike object, not NoneType` - run it again. - **`Failed to install Python dependencies into penv (exit code: 2)`** at the start of `pio run`: the sibling ESP32-S3-LCD-1.3 project (official espressif32@6 platform) installs newer `urllib3`/`esptool` into the shared PlatformIO penv, and this project's pioarduino platform needs `urllib3<2`; its install step hides the error. Run `. ools ix_penv_deps.ps1`, then build again. Never build the two projects at the same time (shared penv). - **Missing libraries**: Run `pio lib update` then `pio run --target clean` - **Partition table not found**: Ensure `partition_table.csv` exists in project root diff --git a/docs/UART_PROTOCOL.md b/docs/UART_PROTOCOL.md index c87e2d4..0c7acdd 100644 --- a/docs/UART_PROTOCOL.md +++ b/docs/UART_PROTOCOL.md @@ -1,9 +1,9 @@ # Link Protocol Specification (v2) **Version:** 2 (`PACKET_VERSION 0x02`) -**Last Updated:** 2026-09-21 -**Source of truth:** `include/protocol/automotive_data.h` — byte-identical in both repos. -**Direction:** Controller A (ESP32-S3-Touch-LCD-5B) → Controller B (ESP32-S3-LCD-1.3), one way. +**Last Updated:** 2026-09-27 +**Source of truth:** `include/protocol/automotive_data.h` (+ `link_secure.h`) — byte-identical in both repos. +**Direction:** gauge data Controller A (ESP32-S3-Touch-LCD-5B) → Controller B (ESP32-S3-LCD-1.3). Since 2026-09-27 B answers with `STATUS` frames over ESP-NOW and A sends B maintenance frames (`PAIR` on the wire, `SECURE` over ESP-NOW) — see *Maintenance frames* below. --- @@ -28,8 +28,8 @@ The same frames are sent on two paths at once. B accepts either and deduplicates |---|---|---| | start | 1 | `0xAA` | | version | 1 | `0x02` — B rejects any other value (counted as version error) | -| type | 1 | `0x01` DATA, `0x02` CONFIG | -| length | 1 | payload bytes (21 for DATA, 27 for CONFIG) | +| type | 1 | `0x01` DATA, `0x02` CONFIG, `0x03` STATUS, `0x04` PAIR, `0x05` SECURE | +| length | 1 | payload bytes (21 DATA, 27 CONFIG, 78 STATUS, 42 PAIR, 29–160 SECURE); `PACKET_MAX_PAYLOAD` = 160 | | payload | length | see below, little-endian, packed | | checksum | 1 | XOR of version, type, length and every payload byte | | end | 1 | `0x55` | @@ -120,6 +120,18 @@ The same console also carries the OBD-II diagnostic probe (`diag pids | pid A (ESP-NOW unicast): B's version, OTA phase, uptime + * - PAIR A -> B (UART wire ONLY): the shared secret for SECURE frames + * - SECURE A -> B (ESP-NOW unicast): AES-256-GCM envelope carrying an + * OTA_CMD or WIFI_CREDS payload. See ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md */ #ifndef _AUTOMOTIVE_DATA_H @@ -53,12 +60,19 @@ #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_TYPE_DATA 0x01 // A -> B payload = automotive_data_t +#define PACKET_TYPE_CONFIG 0x02 // A -> B payload = link_config_t +#define PACKET_TYPE_STATUS 0x03 // B -> A payload = link_status_t (ESP-NOW unicast) +#define PACKET_TYPE_PAIR 0x04 // A -> B payload = link_pair_t (UART wire only, never radio) +#define PACKET_TYPE_SECURE 0x05 // A -> B payload = secure envelope, see LINK MAINTENANCE below +// Inner types carried inside a SECURE envelope (never on the wire in the clear): +#define LINK_INNER_OTA_CMD 0x11 // link_ota_cmd_t +#define LINK_INNER_WIFI_CREDS 0x12 // link_wifi_creds_t #define PACKET_HEADER_SIZE 4 // start, version, type, length #define PACKET_TRAILER_SIZE 2 // checksum, end -#define PACKET_MAX_PAYLOAD 64 +#define PACKET_MAX_PAYLOAD 160 // was 64 until 2026-09-27; SECURE(WIFI_CREDS) needs 127. + // Whole frame 166 B < ESP-NOW's 250 B limit. #define PACKET_MAX_SIZE (PACKET_HEADER_SIZE + PACKET_MAX_PAYLOAD + PACKET_TRAILER_SIZE) // ============================================================================ @@ -201,6 +215,88 @@ static inline void link_config_defaults(link_config_t* c) { c->battery_low_x100 = 1100; } +// ============================================================================ +// LINK MAINTENANCE FRAMES (2026-09-27) - Controller B firmware updates +// ============================================================================ +// +// B pulls its own signed release over Wi-Fi; A only hands it the credentials +// and the trigger. Both repos are public, so nothing secret is compiled in: +// the shared key is generated on A at pairing time and travels to B over the +// UART wire only. Everything A later sends B by radio that matters (Wi-Fi +// credentials, OTA commands) goes inside a SECURE envelope under that key. +// STATUS frames carry nothing secret and go in the clear. + +#define LINK_KEY_LEN 32 // AES-256 +#define LINK_NONCE_LEN 12 // GCM IV, random per frame +#define LINK_TAG_LEN 16 // GCM tag +#define LINK_STATUS_PERIOD_MS 5000 // B -> A STATUS cadence +#define LINK_STATUS_TIMEOUT_MS 15000 // A: B "not heard" after this + +// --- PAIR (A -> B, wire only) ----------------------------------------------- +#define LINK_PAIR_MAGIC 0x52494150UL // "PAIR" +typedef struct __attribute__((packed)) { + uint32_t magic; // LINK_PAIR_MAGIC - guards against a torn frame + uint8_t key[LINK_KEY_LEN]; // the shared secret; both sides keep it in NVS + uint8_t a_mac[6]; // A's STA MAC: the only sender B accepts SECURE frames from +} link_pair_t; // 42 bytes + +// --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ---------- +// ota_phase mirrors Controller A's Ota::phase_t so one UI renders both. +#define LINK_OTA_IDLE 0 +#define LINK_OTA_CHECKING 1 +#define LINK_OTA_UP_TO_DATE 2 +#define LINK_OTA_AVAILABLE 3 +#define LINK_OTA_INSTALLING 4 +#define LINK_OTA_FAILED 5 + +#define LINK_STATUS_PAIRED (1 << 0) // B holds a pairing key +#define LINK_STATUS_HAVE_WIFI (1 << 1) // B holds Wi-Fi credentials +#define LINK_STATUS_WIFI_JOINED (1 << 2) // B is currently on the network (during a job) +#define LINK_STATUS_PENDING_VERIFY (1 << 3) // B runs a fresh image not yet confirmed + +typedef struct __attribute__((packed)) { + char version[16]; // B's firmware version ("dev" for local builds) + uint8_t ota_phase; // LINK_OTA_* + uint8_t ota_progress; // 0..100 while installing + uint8_t flags; // LINK_STATUS_* + uint8_t reserved; + uint16_t key_fp; // first two bytes of SHA-256(pairing key); 0 = unpaired. + // Lets A see "paired with MY key" vs "paired with an old one". + uint32_t uptime_s; + uint32_t free_heap; // internal heap free, bytes + char latest[16]; // latest release tag B knows of ("" = never checked) + char message[32]; // failure reason when ota_phase == LINK_OTA_FAILED +} link_status_t; // 78 bytes + +// --- OTA_CMD (inner, A -> B) ------------------------------------------------ +#define LINK_OTA_CMD_CHECK 1 +#define LINK_OTA_CMD_INSTALL 2 +#define LINK_OTA_CMD_ROLLBACK 3 +#define LINK_OTA_FORCE (1 << 0) // reinstall even if versions match + +typedef struct __attribute__((packed)) { + uint8_t cmd; // LINK_OTA_CMD_* + uint8_t flags; // LINK_OTA_FORCE + uint32_t nonce; // random; B drops a repeat of a recently seen one +} link_ota_cmd_t; // 6 bytes + +// --- WIFI_CREDS (inner, A -> B) --------------------------------------------- +#define LINK_WIFI_SET 1 +#define LINK_WIFI_FORGET 2 + +typedef struct __attribute__((packed)) { + uint8_t action; // LINK_WIFI_* + char ssid[33]; + char pass[64]; +} link_wifi_creds_t; // 98 bytes + +// --- SECURE envelope --------------------------------------------------------- +// payload = nonce[12] | tag[16] | ciphertext +// ciphertext = AES-256-GCM(key, nonce, plaintext = inner_type | inner_payload) +// Helpers that do the encryption live in protocol/link_secure.h (mbedtls). +#define LINK_SECURE_OVERHEAD (LINK_NONCE_LEN + LINK_TAG_LEN) +#define LINK_SECURE_MAX_INNER (PACKET_MAX_PAYLOAD - LINK_SECURE_OVERHEAD) // 132: 1 + 98 fits + // ============================================================================ // CAN BUS ID MAPPINGS (BMW-Specific) // ============================================================================ @@ -413,6 +509,12 @@ static inline frame_status_t frame_parse(const uint8_t* f, size_t n, if (l != sizeof(automotive_data_t)) return FRAME_ERR_TYPE; } else if (t == PACKET_TYPE_CONFIG) { if (l != sizeof(link_config_t)) return FRAME_ERR_TYPE; + } else if (t == PACKET_TYPE_STATUS) { + if (l != sizeof(link_status_t)) return FRAME_ERR_TYPE; + } else if (t == PACKET_TYPE_PAIR) { + if (l != sizeof(link_pair_t)) return FRAME_ERR_TYPE; + } else if (t == PACKET_TYPE_SECURE) { + if (l < LINK_SECURE_OVERHEAD + 1) return FRAME_ERR_TYPE; // at least the inner type byte } else { return FRAME_ERR_TYPE; } diff --git a/include/protocol/link_secure.h b/include/protocol/link_secure.h new file mode 100644 index 0000000..3d77a4d --- /dev/null +++ b/include/protocol/link_secure.h @@ -0,0 +1,93 @@ +/** + * link_secure.h - the SECURE envelope of the A <-> B link (see automotive_data.h). + * + * THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS, like automotive_data.h. + * + * payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner) + * + * Both cores ship mbedtls (2.28 on Controller B's IDF 4.4, 3.x on Controller + * A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs. + */ + +#ifndef LINK_SECURE_H +#define LINK_SECURE_H + +#include "automotive_data.h" +#include +#include +#include +#if __has_include() +#include +#else +#include // IDF 4.4: esp_random / esp_fill_random live here +#endif + +/** First two bytes of SHA-256(key), never 0 (0 means "unpaired" on the wire). */ +static inline uint16_t link_key_fingerprint(const uint8_t key[LINK_KEY_LEN]) { + uint8_t h[32]; +#if MBEDTLS_VERSION_MAJOR >= 3 + mbedtls_sha256(key, LINK_KEY_LEN, h, 0); +#else + mbedtls_sha256_ret(key, LINK_KEY_LEN, h, 0); +#endif + uint16_t fp = (uint16_t)((h[0] << 8) | h[1]); + return fp ? fp : 1; +} + +/** + * Seal inner_type + inner into a SECURE payload. + * @param out buffer of PACKET_MAX_PAYLOAD bytes + * @return payload length, or 0 on error / oversize + */ +static inline size_t link_secure_seal(const uint8_t key[LINK_KEY_LEN], uint8_t inner_type, + const void* inner, size_t inner_len, uint8_t* out) { + if (inner_len + 1 > LINK_SECURE_MAX_INNER) return 0; + uint8_t plain[LINK_SECURE_MAX_INNER]; + plain[0] = inner_type; + memcpy(&plain[1], inner, inner_len); + size_t n = inner_len + 1; + + uint8_t* nonce = out; + uint8_t* tag = out + LINK_NONCE_LEN; + uint8_t* ct = out + LINK_SECURE_OVERHEAD; + esp_fill_random(nonce, LINK_NONCE_LEN); + + mbedtls_gcm_context g; + mbedtls_gcm_init(&g); + int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8); + if (rc == 0) { + rc = mbedtls_gcm_crypt_and_tag(&g, MBEDTLS_GCM_ENCRYPT, n, nonce, LINK_NONCE_LEN, + NULL, 0, plain, ct, LINK_TAG_LEN, tag); + } + mbedtls_gcm_free(&g); + return rc == 0 ? LINK_SECURE_OVERHEAD + n : 0; +} + +/** + * Open a SECURE payload. On success *inner_type and inner (LINK_SECURE_MAX_INNER + * bytes) are filled; *inner_len excludes the type byte. + */ +static inline bool link_secure_open(const uint8_t key[LINK_KEY_LEN], const uint8_t* payload, size_t len, + uint8_t* inner_type, uint8_t* inner, size_t* inner_len) { + if (len < LINK_SECURE_OVERHEAD + 1 || len > PACKET_MAX_PAYLOAD) return false; + size_t n = len - LINK_SECURE_OVERHEAD; + uint8_t plain[LINK_SECURE_MAX_INNER]; + + mbedtls_gcm_context g; + mbedtls_gcm_init(&g); + int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8); + if (rc == 0) { + rc = mbedtls_gcm_auth_decrypt(&g, n, payload, LINK_NONCE_LEN, NULL, 0, + payload + LINK_NONCE_LEN, LINK_TAG_LEN, + payload + LINK_SECURE_OVERHEAD, plain); + } + mbedtls_gcm_free(&g); + if (rc != 0) return false; + + *inner_type = plain[0]; + *inner_len = n - 1; + memcpy(inner, &plain[1], n - 1); + return true; +} + +#endif // LINK_SECURE_H diff --git a/src/main.cpp b/src/main.cpp index a3ed687..68aad1d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,6 +17,7 @@ #include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B #include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter #include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console) +#include "modules/link_peer.h" // Controller B status, pairing, credential handoff, B updates (`link` console) // ============================================================================ // MINIMAL LVGL + UI SETTINGS + WIFI + UART @@ -59,7 +60,7 @@ static bool memCommand(const char* line) { static bool consoleExtraCommand(const char* line) { return DiagProbe::handleCommand(line) || Ota::handleCommand(line) || WiFiManager::handleCommand(line) || memCommand(line) || - PerfMon::handleCommand(line); + PerfMon::handleCommand(line) || LinkPeer::handleCommand(line); } // ============================================================================ @@ -117,6 +118,7 @@ void setup() // ESP-NOW transmit leg (needs the radio in STA mode, which WiFiManager keeps) ESP_LOGI("MAIN", "Initializing ESP-NOW link..."); EspNowLink::init(); + LinkPeer::init(); // B's STATUS frames, pairing key, credential handoff // Initialize UART subsystem using UARTManager module ESP_LOGI("MAIN", "Initializing UART subsystem..."); @@ -160,6 +162,7 @@ void loop() PerfMon::tick(); DiagProbe::tick(); Ota::tick(); // confirms a freshly installed image after healthy uptime + LinkPeer::tick(); // Controller B heard/lost, credential sync DrivelineScreen::tick(); TuningScreen::tick(); diff --git a/src/modules/espnow_link.cpp b/src/modules/espnow_link.cpp index b469b97..dc974b6 100644 --- a/src/modules/espnow_link.cpp +++ b/src/modules/espnow_link.cpp @@ -16,6 +16,13 @@ static const uint8_t BROADCAST_MAC[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; static bool g_ready = false; static uint32_t g_sent = 0; static uint32_t g_fail = 0; +static receive_handler_t g_rx_handler = NULL; + +// IDF 5.x receive callback: sender MAC is in the info struct. +static void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len) { + if (g_rx_handler == NULL || info == NULL || len <= 0) return; + g_rx_handler(info->src_addr, data, (size_t)len); +} // IDF 5.5 (pioarduino / Arduino 3.3) passes wifi_tx_info_t*; older cores passed the MAC. static void onSent(const wifi_tx_info_t* info, esp_now_send_status_t status) { @@ -45,6 +52,7 @@ bool init() { return false; } esp_now_register_send_cb(onSent); + esp_now_register_recv_cb(onReceive); esp_now_peer_info_t peer = {}; memcpy(peer.peer_addr, BROADCAST_MAC, 6); @@ -93,4 +101,26 @@ bool isReady() { return g_ready; } uint32_t sentCount() { return g_sent; } uint32_t failCount() { return g_fail; } +void setReceiveHandler(receive_handler_t handler) { g_rx_handler = handler; } + +bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len) { + if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false; + if (!g_ready) { + reinitIfDue(); + if (!g_ready) return false; + } + if (!esp_now_is_peer_exist(mac)) { + esp_now_peer_info_t peer = {}; + memcpy(peer.peer_addr, mac, 6); + peer.channel = 0; // current channel + peer.encrypt = false; // SECURE frames carry their own encryption + peer.ifidx = WIFI_IF_STA; + if (esp_now_add_peer(&peer) != ESP_OK) { + ESP_LOGE("EspNow", "esp_now_add_peer(B) failed"); + return false; + } + } + return esp_now_send(mac, frame, len) == ESP_OK; +} + } // namespace EspNowLink diff --git a/src/modules/espnow_link.h b/src/modules/espnow_link.h index c5f5043..8bf233e 100644 --- a/src/modules/espnow_link.h +++ b/src/modules/espnow_link.h @@ -1,10 +1,14 @@ /* - * ESP-NOW Link Module (Controller A side, transmit only) + * ESP-NOW Link Module (Controller A side) * * Second transport for the A -> B link: every frame the UART manager builds * is also broadcast over ESP-NOW, so B keeps receiving if the wire is lost. * B dedupes on packet_id, so both paths may be live at once. * + * Since 2026-09-27 the radio also listens: B unicasts STATUS frames back and + * A unicasts SECURE frames to B (LinkPeer). Frames received are handed to the + * handler set with setReceiveHandler(); sendTo() unicasts to one MAC. + * * Radio policy: the Wi-Fi radio stays in STA mode permanently (the WiFi * manager's "off" only stops scanning). A transmits on ESPNOW_CHANNEL unless * associated to an access point, in which case the AP's channel is used and @@ -34,4 +38,11 @@ bool isReady(); uint32_t sentCount(); uint32_t failCount(); +/** Frames received from any sender (runs in the Wi-Fi task - copy and return). */ +typedef void (*receive_handler_t)(const uint8_t mac[6], const uint8_t* frame, size_t len); +void setReceiveHandler(receive_handler_t handler); + +/** Unicast one complete frame to a MAC (peer added on first use, unencrypted). */ +bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len); + } // namespace EspNowLink diff --git a/src/modules/link_peer.cpp b/src/modules/link_peer.cpp new file mode 100644 index 0000000..07cbcd7 --- /dev/null +++ b/src/modules/link_peer.cpp @@ -0,0 +1,369 @@ +/* + * Link Peer Module Implementation (Controller A) + * + * Threading: onFrame() runs in the Wi-Fi task and only copies the STATUS into + * g_peer under a mutex. Everything else (NVS, sending, console) is the loop task. + */ + +#include "link_peer.h" +#include "espnow_link.h" +#include "uart_manager.h" +#include "wifi_manager.h" +#include "ota_update.h" +#include "serial_lock.h" +#include "protocol/link_secure.h" +#include +#include +#include +#include + +namespace LinkPeer { + +static const char* NVS_LINK = "linkpeer"; // key (32 B) +#define CREDS_PUSH_MIN_MS 15000 // never push credentials more often than this +#define PAIR_REPEATS 3 // PAIR is sent this many times over the wire + +static bool g_paired = false; +static uint8_t g_key[LINK_KEY_LEN]; +static uint16_t g_key_fp = 0; + +// last STATUS from B (written by the Wi-Fi task) +static SemaphoreHandle_t g_mutex = NULL; +static link_status_t g_st = {}; +static uint8_t g_b_mac[6] = {0}; +static uint32_t g_last_status_ms = 0; +static bool g_ever_heard = false; +static uint32_t g_status_count = 0, g_secure_sent = 0, g_secure_fail = 0; + +// credential sync +static uint32_t g_pushed_hash = 0; +static uint32_t g_last_push_ms = 0; + +static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); } +static void unlock() { xSemaphoreGive(g_mutex); } + +static void print(const char* fmt, ...) { + char buf[200]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + SerialLock::lock(); + Serial.println(buf); + SerialLock::unlock(); +} + +static const char* phaseName(uint8_t p) { + switch (p) { + case LINK_OTA_CHECKING: return "checking"; + case LINK_OTA_UP_TO_DATE: return "up to date"; + case LINK_OTA_AVAILABLE: return "update available"; + case LINK_OTA_INSTALLING: return "installing"; + case LINK_OTA_FAILED: return "failed"; + default: return "idle"; + } +} + +// ---- NVS -------------------------------------------------------------------- +static void loadKey() { + Preferences p; + p.begin(NVS_LINK, true); + g_paired = p.getBytesLength("key") == LINK_KEY_LEN; + if (g_paired) p.getBytes("key", g_key, LINK_KEY_LEN); + p.end(); + g_key_fp = g_paired ? link_key_fingerprint(g_key) : 0; +} + +static void storeKey() { + Preferences p; + p.begin(NVS_LINK, false); + p.putBytes("key", g_key, LINK_KEY_LEN); + p.end(); +} + +static void clearKey() { + Preferences p; + p.begin(NVS_LINK, false); + p.clear(); + p.end(); + g_paired = false; + g_key_fp = 0; + memset(g_key, 0, sizeof(g_key)); +} + +// ---- inbound (Wi-Fi task) --------------------------------------------------- +static void onFrame(const uint8_t mac[6], const uint8_t* frame, size_t len) { + uint8_t type = 0, plen = 0; + const uint8_t* payload = NULL; + if (frame_parse(frame, len, &type, &payload, &plen) != FRAME_OK) return; + if (type != PACKET_TYPE_STATUS) return; + if (xSemaphoreTake(g_mutex, pdMS_TO_TICKS(10)) != pdTRUE) return; + memcpy(&g_st, payload, sizeof(g_st)); + g_st.version[sizeof(g_st.version) - 1] = 0; + g_st.latest[sizeof(g_st.latest) - 1] = 0; + g_st.message[sizeof(g_st.message) - 1] = 0; + memcpy(g_b_mac, mac, 6); + g_last_status_ms = millis(); + g_ever_heard = true; + g_status_count++; + xSemaphoreGive(g_mutex); +} + +// ---- public: status --------------------------------------------------------- +peer_status_t getStatus() { + peer_status_t p = {}; + lock(); + p.st = g_st; + memcpy(p.mac, g_b_mac, 6); + uint32_t last = g_last_status_ms; + bool ever = g_ever_heard; + unlock(); + p.age_ms = ever ? millis() - last : 0xFFFFFFFF; + p.heard = ever && p.age_ms < LINK_STATUS_TIMEOUT_MS; + p.paired = g_paired; + p.key_fp = g_key_fp; + p.key_match = g_paired && p.st.key_fp == g_key_fp; + return p; +} + +// ---- outbound --------------------------------------------------------------- +static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) { + peer_status_t p = getStatus(); + if (!p.heard) { snprintf(why, n, "Controller B not heard"); return false; } + if (!p.paired) { snprintf(why, n, "not paired - run `link pair` with the wire connected"); return false; } + if (!p.key_match) { snprintf(why, n, "Controller B holds a different key - run `link pair` again"); return false; } + + uint8_t payload[PACKET_MAX_PAYLOAD], frame[PACKET_MAX_SIZE]; + size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload); + if (!plen) { snprintf(why, n, "encryption failed"); return false; } + size_t flen = frame_build(PACKET_TYPE_SECURE, payload, (uint8_t)plen, frame); + if (!flen || !EspNowLink::sendTo(p.mac, frame, flen)) { + g_secure_fail++; + snprintf(why, n, "ESP-NOW send failed"); + return false; + } + g_secure_sent++; + return true; +} + +static bool sendOtaCmd(uint8_t cmd, uint8_t flags, char* why, size_t n) { + link_ota_cmd_t c = {}; + c.cmd = cmd; + c.flags = flags; + c.nonce = esp_random(); + return sendSecure(LINK_INNER_OTA_CMD, &c, sizeof(c), why, n); +} + +static uint32_t hashStr(uint32_t h, const char* s) { + for (; *s; s++) h = (h ^ (uint8_t)*s) * 16777619u; // FNV-1a + return h; +} + +/** Push A's remembered network (or a FORGET) to B. */ +static bool pushCredentials(char* why, size_t n, bool log) { + link_wifi_creds_t c = {}; + char pass[65]; + bool have = WiFiManager::getSavedCredentials(c.ssid, sizeof(c.ssid), pass, sizeof(pass)); + if (have) { + c.action = LINK_WIFI_SET; + strlcpy(c.pass, pass, sizeof(c.pass)); + } else { + c.action = LINK_WIFI_FORGET; + } + bool ok = sendSecure(LINK_INNER_WIFI_CREDS, &c, sizeof(c), why, n); + memset(pass, 0, sizeof(pass)); + if (ok) { + g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1; + g_last_push_ms = millis(); + if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Controller B (encrypted)" + : "[link] told Controller B to forget its Wi-Fi credentials", c.ssid); + } + memset(&c, 0, sizeof(c)); + return ok; +} + +// B lacks credentials A has, or A's changed, or A forgot them while B still has them. +static void syncCredentials() { + peer_status_t p = getStatus(); + if (!p.heard || !p.paired || !p.key_match) return; + if (millis() - g_last_push_ms < CREDS_PUSH_MIN_MS && g_last_push_ms != 0) return; + + char ssid[33], pass[65]; + bool have = WiFiManager::getSavedCredentials(ssid, sizeof(ssid), pass, sizeof(pass)); + uint32_t h = have ? hashStr(hashStr(2166136261u, ssid), pass) : 1; + memset(pass, 0, sizeof(pass)); + bool b_has = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0; + + bool need = have ? (!b_has || h != g_pushed_hash) + : (b_has && g_pushed_hash != 1); + if (!need) return; + char why[64]; + pushCredentials(why, sizeof(why), true); +} + +// ---- pairing ---------------------------------------------------------------- +static bool pair(char* why, size_t n) { + if (UARTManager::getState() == UARTManager::UART_STATE_OFF) { + snprintf(why, n, "link is off - enable 'Send to Controller B' in Settings first"); + return false; + } + link_pair_t pk = {}; + pk.magic = LINK_PAIR_MAGIC; + esp_fill_random(pk.key, LINK_KEY_LEN); + esp_wifi_get_mac(WIFI_IF_STA, pk.a_mac); + + uint8_t frame[PACKET_MAX_SIZE]; + size_t flen = frame_build(PACKET_TYPE_PAIR, &pk, sizeof(pk), frame); + int sent = 0; + for (int i = 0; i < PAIR_REPEATS; i++) { + if (UARTManager::sendWire(frame, flen)) sent++; + delay(40); + } + if (!sent) { snprintf(why, n, "UART write failed"); memset(&pk, 0, sizeof(pk)); return false; } + + memcpy(g_key, pk.key, LINK_KEY_LEN); + memset(&pk, 0, sizeof(pk)); + g_paired = true; + g_key_fp = link_key_fingerprint(g_key); + storeKey(); + g_pushed_hash = 0; // re-send the credentials under the new key + g_last_push_ms = 0; + print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. " + "Controller B confirms in its next STATUS (`link status`).", sent, g_key_fp); + return true; +} + +// ---- public: requests (UI) -------------------------------------------------- +static bool bReady(char* why, size_t n, bool need_parked) { + peer_status_t p = getStatus(); + if (!p.heard) { snprintf(why, n, "Controller B not heard - is it powered?"); return false; } + if (!p.paired || !p.key_match) { + snprintf(why, n, "Controller B is not paired with this controller (console: link pair, wire connected)"); + return false; + } + if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) { + snprintf(why, n, "Controller B has no Wi-Fi credentials yet - join a network on this screen first"); + return false; + } + if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) { + snprintf(why, n, "Controller B is busy (%s)", phaseName(p.st.ota_phase)); + return false; + } + if (need_parked && !Ota::isParked(why, n)) return false; + // Same network as B => same radio channel, so B's STATUS frames (progress) + // keep reaching this screen while B is joined. + if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) { + snprintf(why, n, "join Wi-Fi on this controller first, so Controller B's progress can be followed"); + return false; + } + return true; +} + +bool requestCheck(char* why, size_t n) { + if (!bReady(why, n, false)) { print("[link] check refused: %s", why); return false; } + return sendOtaCmd(LINK_OTA_CMD_CHECK, 0, why, n); +} + +bool requestInstall(char* why, size_t n) { + if (!bReady(why, n, true)) { print("[link] install refused: %s", why); return false; } + return sendOtaCmd(LINK_OTA_CMD_INSTALL, 0, why, n); +} + +// ---- lifecycle -------------------------------------------------------------- +void init() { + if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex(); + loadKey(); + EspNowLink::setReceiveHandler(onFrame); + print("[link] Controller B: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected"); +} + +void tick() { + static uint32_t last = 0; + static bool was_heard = false; + static uint8_t last_phase = 0xFF; + static bool was_match = false; + if (millis() - last < 1000) return; + last = millis(); + + peer_status_t p = getStatus(); + if (p.heard != was_heard) { + was_heard = p.heard; + if (p.heard) print("[link] Controller B heard: %s, %s, %lu s up", p.st.version, + p.key_match ? "paired" : (p.st.key_fp ? "paired with ANOTHER key" : "unpaired"), + (unsigned long)p.st.uptime_s); + else print("[link] Controller B silent for %lu s", (unsigned long)(p.age_ms / 1000)); + } + if (p.heard && p.key_match && !was_match) { + print("[link] Controller B confirmed pairing (fingerprint %04X)", p.st.key_fp); + } + was_match = p.heard && p.key_match; + if (p.heard && p.st.ota_phase != last_phase) { + if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE) + print("[link] Controller B update: %s%s%s%s", phaseName(p.st.ota_phase), + p.st.latest[0] ? " latest " : "", p.st.latest, + p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : ""); + last_phase = p.st.ota_phase; + } + syncCredentials(); +} + +// ---- console ---------------------------------------------------------------- +static void help() { + print("link status Controller B: version, pairing, update phase"); + print("link pair new shared key -> B over the UART wire (bench, wire connected)"); + print("link unpair forget the key here (B keeps its own until re-paired)"); + print("link creds send the remembered Wi-Fi network to B now"); + print("link ota check|install [force]|rollback drive B's updater"); +} + +bool handleCommand(const char* line) { + if (strncmp(line, "link", 4) != 0 || (line[4] != 0 && line[4] != ' ')) return false; + const char* a = line + 4; + while (*a == ' ') a++; + char why[96] = ""; + + if (!*a || !strcmp(a, "help")) { help(); return true; } + if (!strcmp(a, "status")) { + peer_status_t p = getStatus(); + print("[link] this side: %s (fingerprint %04X) | STATUS frames %lu | SECURE sent %lu, failed %lu", + p.paired ? "paired" : "NOT paired", p.key_fp, (unsigned long)g_status_count, + (unsigned long)g_secure_sent, (unsigned long)g_secure_fail); + if (!g_ever_heard) { print("[link] Controller B never heard"); return true; } + print("[link] Controller B %02X:%02X:%02X:%02X:%02X:%02X, %s (%lu s ago)", + p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5], + p.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000)); + print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s", + p.st.version, p.st.key_fp, p.key_match ? "matches" : p.st.key_fp ? "DIFFERENT" : "none", + (p.st.flags & LINK_STATUS_HAVE_WIFI) ? "yes" : "no", + (p.st.flags & LINK_STATUS_WIFI_JOINED) ? ", joined" : "", + (p.st.flags & LINK_STATUS_PENDING_VERIFY) ? " | fresh image, unconfirmed" : ""); + print("[link] update: %s%s%s%s%s | up %lu s | heap %lu", + phaseName(p.st.ota_phase), + p.st.latest[0] ? ", latest " : "", p.st.latest, + p.st.message[0] ? " - " : "", p.st.message, + (unsigned long)p.st.uptime_s, (unsigned long)p.st.free_heap); + return true; + } + if (!strcmp(a, "pair")) { if (!pair(why, sizeof(why))) print("[link] pair refused: %s", why); return true; } + if (!strcmp(a, "unpair")) { clearKey(); print("[link] pairing key removed here"); return true; } + if (!strcmp(a, "creds")) { + if (!pushCredentials(why, sizeof(why), true)) print("[link] creds refused: %s", why); + return true; + } + if (!strncmp(a, "ota", 3)) { + const char* b = a + 3; + while (*b == ' ') b++; + bool ok = false; + if (!strcmp(b, "check")) ok = requestCheck(why, sizeof(why)); + else if (!strcmp(b, "install")) ok = requestInstall(why, sizeof(why)); + else if (!strcmp(b, "install force")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_INSTALL, LINK_OTA_FORCE, why, sizeof(why)); + else if (!strcmp(b, "rollback")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_ROLLBACK, 0, why, sizeof(why)); + else { help(); return true; } + print(ok ? "[link] command sent to Controller B - watch `link status`" : "[link] refused: %s", why); + return true; + } + help(); + return true; +} + +} // namespace LinkPeer diff --git a/src/modules/link_peer.h b/src/modules/link_peer.h new file mode 100644 index 0000000..60dd3a5 --- /dev/null +++ b/src/modules/link_peer.h @@ -0,0 +1,49 @@ +/* + * Link Peer Module (Controller A) - what A knows about Controller B, and the + * maintenance traffic that keeps B updatable. See + * ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md (B's wiki). + * + * STATUS B -> A ESP-NOW unicast every 5 s: B's version, OTA phase, uptime. + * Shown on Settings -> Updates as the "Controller B" card. + * PAIR A -> B `link pair` on the console, UART WIRE ONLY: a fresh random + * key, kept in NVS on both sides. Both repos are public, so + * this is the only secret and it never travels by radio. + * SECURE A -> B ESP-NOW unicast, AES-256-GCM under the pairing key: + * the remembered Wi-Fi credentials (pushed automatically + * whenever B lacks them or they change) and OTA commands. + * + * Console: link status | pair | unpair | creds | ota check | ota install [force] | ota rollback + */ + +#pragma once + +#include +#include "protocol/automotive_data.h" + +namespace LinkPeer { + +/** Load the pairing key, hook the ESP-NOW receive path. After EspNowLink::init(). */ +void init(); + +/** Credential sync + logging. Call from loop(). */ +void tick(); + +typedef struct { + bool heard; // STATUS within LINK_STATUS_TIMEOUT_MS + uint32_t age_ms; // since the last STATUS + uint8_t mac[6]; // B's STA MAC + link_status_t st; // last STATUS as received + bool paired; // this controller holds a pairing key + bool key_match; // B reports the fingerprint of OUR key + uint16_t key_fp; // our key's fingerprint (0 = none) +} peer_status_t; + +peer_status_t getStatus(); + +/** Ask B to check / install (behind the same parking gate as A's own update). */ +bool requestCheck(char* why, size_t n); +bool requestInstall(char* why, size_t n); + +bool handleCommand(const char* line); + +} // namespace LinkPeer diff --git a/src/modules/ota_update.cpp b/src/modules/ota_update.cpp index b41ba02..4db3470 100644 --- a/src/modules/ota_update.cpp +++ b/src/modules/ota_update.cpp @@ -685,6 +685,7 @@ ui_status_t getStatus() { bool requestCheck(char* why, size_t n) { return startJob(JOB_CHECK, why, n); } bool requestInstall(char* why, size_t n) { return startJob(JOB_INSTALL, why, n); } +bool isParked(char* why, size_t n) { return parked(why, n); } void init() { const esp_partition_t* run = esp_ota_get_running_partition(); diff --git a/src/modules/ota_update.h b/src/modules/ota_update.h index d84a92d..5a51311 100644 --- a/src/modules/ota_update.h +++ b/src/modules/ota_update.h @@ -66,6 +66,9 @@ ui_status_t getStatus(); bool requestCheck(char* why, size_t n); bool requestInstall(char* why, size_t n); +/** The parking gate on its own (Controller B's install is guarded by it too). */ +bool isParked(char* why, size_t n); + } // namespace Ota #endif // OTA_UPDATE_H diff --git a/src/modules/settings_screen.cpp b/src/modules/settings_screen.cpp index 38f55db..68134e0 100644 --- a/src/modules/settings_screen.cpp +++ b/src/modules/settings_screen.cpp @@ -7,6 +7,7 @@ #include "driveline_screen.h" #include "wifi_manager.h" #include "ota_update.h" +#include "link_peer.h" #include "uart_manager.h" #include "espnow_link.h" #include "settings_manager.h" @@ -510,9 +511,17 @@ static void buildPasswordOverlay() { } // ============================================================================ -// UPDATES PAGE +// UPDATES PAGE - Controller A (this board) and Controller B (over the link) // ============================================================================ +static lv_obj_t* g_b_installed = NULL; +static lv_obj_t* g_b_latest = NULL; +static lv_obj_t* g_b_state = NULL; +static lv_obj_t* g_b_check = NULL; +static lv_obj_t* g_b_install = NULL; +static char g_b_refusal[96] = ""; +static uint8_t g_b_refusal_phase = LINK_OTA_IDLE; + static void onInstallConfirmed(bool ok, void* user) { (void)user; if (!ok) return; @@ -547,7 +556,36 @@ static void onGoWifi(lv_event_t* e) { selectPage(PAGE_WIFI); } -static void refreshUpdates() { +static void onBInstallConfirmed(bool ok, void* user) { + (void)user; + if (!ok) return; + uint8_t before = LinkPeer::getStatus().st.ota_phase; + if (!LinkPeer::requestInstall(g_b_refusal, sizeof(g_b_refusal))) g_b_refusal_phase = before; + else g_b_refusal[0] = 0; + refresh(true); +} + +static void onBInstall(lv_event_t* e) { + (void)e; + LinkPeer::peer_status_t p = LinkPeer::getStatus(); + char title[64]; + snprintf(title, sizeof(title), "Install %s on Controller B?", p.st.latest); + confirm(title, + "Controller B joins the Wi-Fi network, downloads its new firmware and restarts; " + "its gauges hold still meanwhile and this card shows the progress.\n\n" + "Only while parked with the engine off.", + "Install", onBInstallConfirmed, NULL); +} + +static void onBCheck(lv_event_t* e) { + (void)e; + uint8_t before = LinkPeer::getStatus().st.ota_phase; + if (!LinkPeer::requestCheck(g_b_refusal, sizeof(g_b_refusal))) g_b_refusal_phase = before; + else g_b_refusal[0] = 0; + refresh(true); +} + +static void refreshUpdatesA() { Ota::ui_status_t o = Ota::getStatus(); bool wifi_ok = WiFiManager::getStatus().link == WiFiManager::LINK_CONNECTED; if (g_upd_refusal[0] && o.phase != g_upd_refusal_phase) g_upd_refusal[0] = 0; // superseded @@ -570,7 +608,7 @@ static void refreshUpdates() { } else if (!wifi_ok && o.phase != Ota::PHASE_IDLE && o.phase != Ota::PHASE_CHECKING) { // keep the last result, but say why the buttons are off size_t n = strlen(msg); - snprintf(msg + n, sizeof(msg) - n, "\nConnect to Wi-Fi to check again."); + snprintf(msg + n, sizeof(msg) - n, " Connect to Wi-Fi to check again."); } setText(g_upd_state, msg); setTextColor(g_upd_state, col); @@ -590,45 +628,125 @@ static void refreshUpdates() { setVisible(g_upd_wifi, !wifi_ok); } +static void refreshUpdatesB() { + LinkPeer::peer_status_t p = LinkPeer::getStatus(); + if (g_b_refusal[0] && p.st.ota_phase != g_b_refusal_phase) g_b_refusal[0] = 0; + + bool has_wifi = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0; + bool ready = p.heard && p.paired && p.key_match && has_wifi; + char msg[160]; + lv_color_t col = UI_COL_MUTED; + if (!p.heard) { + snprintf(msg, sizeof(msg), "Controller B not heard.%s", + p.paired ? "" : " Not paired yet: connect the wire and run 'link pair' on the console."); + } else if (!p.paired || !p.key_match) { + snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " Not paired with this controller. " + "Connect the wire and run 'link pair' on the console."); + col = UI_COL_AMBER; + } else if (!has_wifi) { + snprintf(msg, sizeof(msg), "Controller B has no Wi-Fi credentials yet. Join a network here; " + "they are passed on by themselves."); + } else { + switch (p.st.ota_phase) { + case LINK_OTA_CHECKING: snprintf(msg, sizeof(msg), "Controller B is checking..."); break; + case LINK_OTA_INSTALLING: snprintf(msg, sizeof(msg), "Installing %s on Controller B... %u %%", + p.st.latest, p.st.ota_progress); col = UI_COL_ACCENT; break; + case LINK_OTA_UP_TO_DATE: snprintf(msg, sizeof(msg), LV_SYMBOL_OK " Controller B is up to date."); col = UI_COL_OK; break; + case LINK_OTA_AVAILABLE: snprintf(msg, sizeof(msg), "Version %s is available for Controller B.", p.st.latest); col = UI_COL_ACCENT; break; + case LINK_OTA_FAILED: snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", p.st.message); col = UI_COL_WARN; break; + default: snprintf(msg, sizeof(msg), "Tap Check to look for a new version for Controller B."); break; + } + if (p.st.flags & LINK_STATUS_PENDING_VERIFY) { + size_t n = strlen(msg); + snprintf(msg + n, sizeof(msg) - n, " (new firmware, confirming...)"); + } + } + if (g_b_refusal[0]) { + snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", g_b_refusal); + col = UI_COL_WARN; + } + setText(g_b_state, msg); + setTextColor(g_b_state, col); + setText(g_b_installed, p.heard ? p.st.version : "-"); + setText(g_b_latest, (p.heard && p.st.latest[0]) ? p.st.latest : "-"); + + bool busy = p.heard && (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING); + setButtonText(g_b_check, busy ? "Working..." : LV_SYMBOL_REFRESH " Check for updates"); + if (busy || !ready) lv_obj_add_state(g_b_check, LV_STATE_DISABLED); + else lv_obj_clear_state(g_b_check, LV_STATE_DISABLED); + + bool can_install = ready && p.st.ota_phase == LINK_OTA_AVAILABLE; + char inst[48]; + snprintf(inst, sizeof(inst), LV_SYMBOL_DOWNLOAD " Install %s", p.st.latest); + setButtonText(g_b_install, inst); + setVisible(g_b_install, can_install); +} + +static void refreshUpdates() { + refreshUpdatesA(); + refreshUpdatesB(); +} + +/** One controller's card: "Name Installed vX Latest vY", a status line, a button row. */ +static lv_obj_t* controllerCard(lv_obj_t* page, const char* name, const char* installed, + lv_obj_t** installed_lbl, lv_obj_t** latest_lbl, lv_obj_t** state_lbl) { + lv_obj_t* c = card(page); + lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(c, 8, 0); + + lv_obj_t* row = box(c, LV_FLEX_FLOW_ROW); + lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END); + lv_obj_set_style_pad_column(row, 36, 0); + lv_obj_t* title = label(row, name, &lv_font_montserrat_24, UI_COL_TEXT); + lv_obj_set_width(title, 190); + + lv_obj_t* a = box(row, LV_FLEX_FLOW_ROW); + lv_obj_set_size(a, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_flex_align(a, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END); + lv_obj_set_style_pad_column(a, 10, 0); + label(a, "Installed", &lv_font_montserrat_20, UI_COL_MUTED); + *installed_lbl = label(a, installed, &lv_font_montserrat_24, UI_COL_TEXT); + + lv_obj_t* b = box(row, LV_FLEX_FLOW_ROW); + lv_obj_set_size(b, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_flex_align(b, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END); + lv_obj_set_style_pad_column(b, 10, 0); + label(b, "Latest", &lv_font_montserrat_20, UI_COL_MUTED); + *latest_lbl = label(b, "-", &lv_font_montserrat_24, UI_COL_TEXT); + + *state_lbl = label(c, "", &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(*state_lbl, LV_LABEL_LONG_WRAP); + lv_obj_set_width(*state_lbl, LV_PCT(100)); + return c; +} + static void buildUpdatesPage(lv_obj_t* page) { label(page, "Firmware updates", &lv_font_montserrat_24, UI_COL_TEXT); - lv_obj_t* c = card(page); - lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_flex_flow(c, LV_FLEX_FLOW_ROW); - lv_obj_set_style_pad_column(c, 60, 0); - - lv_obj_t* a = box(c, LV_FLEX_FLOW_COLUMN); - lv_obj_set_size(a, LV_SIZE_CONTENT, LV_SIZE_CONTENT); - lv_obj_set_style_pad_row(a, 6, 0); - label(a, "Installed", &lv_font_montserrat_20, UI_COL_MUTED); - label(a, FW_VERSION, &lv_font_montserrat_30, UI_COL_TEXT); - - lv_obj_t* b = box(c, LV_FLEX_FLOW_COLUMN); - lv_obj_set_size(b, LV_SIZE_CONTENT, LV_SIZE_CONTENT); - lv_obj_set_style_pad_row(b, 6, 0); - label(b, "Latest release", &lv_font_montserrat_20, UI_COL_MUTED); - g_upd_latest = label(b, "-", &lv_font_montserrat_30, UI_COL_TEXT); - - g_upd_state = label(page, "", &lv_font_montserrat_20, UI_COL_MUTED); - lv_label_set_long_mode(g_upd_state, LV_LABEL_LONG_WRAP); - lv_obj_set_width(g_upd_state, LV_PCT(100)); - - lv_obj_t* btns = box(page, LV_FLEX_FLOW_ROW); + lv_obj_t* installed_a = NULL; + lv_obj_t* a = controllerCard(page, "Controller A", FW_VERSION, &installed_a, &g_upd_latest, &g_upd_state); + lv_obj_t* btns = box(a, LV_FLEX_FLOW_ROW); lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT); lv_obj_set_style_pad_column(btns, 16, 0); - g_upd_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 64, BTN_PRIMARY, onCheck, NULL); - g_upd_install = button(btns, "Install", 280, 64, BTN_SUCCESS, onInstall, NULL); - g_upd_wifi = button(btns, LV_SYMBOL_WIFI " Wi-Fi settings", 260, 64, BTN_SECONDARY, onGoWifi, NULL); + g_upd_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 56, BTN_PRIMARY, onCheck, NULL); + g_upd_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onInstall, NULL); + g_upd_wifi = button(btns, LV_SYMBOL_WIFI " Wi-Fi settings", 260, 56, BTN_SECONDARY, onGoWifi, NULL); + + lv_obj_t* b = controllerCard(page, "Controller B", "-", &g_b_installed, &g_b_latest, &g_b_state); + btns = box(b, LV_FLEX_FLOW_ROW); + lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_column(btns, 16, 0); + g_b_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 56, BTN_PRIMARY, onBCheck, NULL); + g_b_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onBInstall, NULL); lv_obj_t* note = label(page, - "Updates come from " OTA_SERVER " and are signed. Installing takes about a minute: " - "a progress bar shows while the new firmware is written, then the controller restarts. " - "If it doesn't start properly, it goes back to the current version by itself.", + "Signed releases from " OTA_SERVER ". Each controller restarts after installing and keeps " + "the previous version as a fallback.", &lv_font_montserrat_20, UI_COL_MUTED); lv_label_set_long_mode(note, LV_LABEL_LONG_WRAP); lv_obj_set_width(note, LV_PCT(100)); - lv_obj_set_style_pad_top(note, 12, 0); } // ============================================================================ diff --git a/src/modules/tunables.cpp b/src/modules/tunables.cpp index d6c54df..d59a212 100644 --- a/src/modules/tunables.cpp +++ b/src/modules/tunables.cpp @@ -102,6 +102,7 @@ static void help() { print("cfg override off | rpm | duty | both "); print("cfg reset back to defaults"); print("diag help OBD-II diagnostic probe (transmits on the bus)"); + print("link help Controller B: pairing, credentials, its updates"); } static bool setField(const char* name, long v) { diff --git a/src/modules/uart_manager.cpp b/src/modules/uart_manager.cpp index 1953a7b..8b20324 100644 --- a/src/modules/uart_manager.cpp +++ b/src/modules/uart_manager.cpp @@ -43,6 +43,7 @@ static uart_stats_t g_uart_stats = {0}; // CONFIG frame scheduling static uint8_t g_last_cfg_version_sent = 0; static uint32_t g_last_cfg_send_time = 0; +static volatile bool g_port_ready = false; // Serial1.begin() done (in the task) // ============================================================================ // PRIVATE HELPER FUNCTIONS @@ -173,6 +174,7 @@ static void uartTask(void* parameter) { Serial1.setRxBufferSize(256); Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN); + g_port_ready = true; ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u", UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION); @@ -355,4 +357,10 @@ void setEnabled(bool state) ESP_LOGI("UARTMgr", "============================="); } +bool sendWire(const uint8_t* frame, size_t len) { + if (!g_port_ready || len == 0) return false; + return Serial1.write(frame, len) == len; +} + } // namespace UARTManager + diff --git a/src/modules/uart_manager.h b/src/modules/uart_manager.h index 98c908c..187cfea 100644 --- a/src/modules/uart_manager.h +++ b/src/modules/uart_manager.h @@ -122,4 +122,12 @@ void linkToCANState(bool can_active); */ void setEnabled(bool enabled); +/** + * @brief Send one complete frame on the UART wire ONLY (never ESP-NOW). + * Used for the PAIR frame, which must not go over the air. One write + * call, so it cannot interleave with the task's own frames. + * @return true if the port is up and every byte was written + */ +bool sendWire(const uint8_t* frame, size_t len); + } // namespace UARTManager diff --git a/src/modules/wifi_manager.cpp b/src/modules/wifi_manager.cpp index 35b3f25..7285a03 100644 --- a/src/modules/wifi_manager.cpp +++ b/src/modules/wifi_manager.cpp @@ -95,6 +95,14 @@ static void loadSaved() { copyStr(g_saved_pass, pass.c_str(), sizeof(g_saved_pass)); } +bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n) { + lock(); + copyStr(ssid, g_status.saved_ssid, ssid_n); + unlock(); + copyStr(pass, g_saved_pass, pass_n); + return ssid[0] != 0; +} + static void storeSaved(const char* ssid, const char* pass) { Preferences p; p.begin(NVS_NAMESPACE, false); diff --git a/src/modules/wifi_manager.h b/src/modules/wifi_manager.h index 945beca..67e1723 100644 --- a/src/modules/wifi_manager.h +++ b/src/modules/wifi_manager.h @@ -82,4 +82,11 @@ uint8_t getNetworks(network_t* out, uint8_t max); /** Console: `wifi status | join [pass] | forget | on | off`. */ bool handleCommand(const char* line); +/** + * The remembered network, password included - for LinkPeer, which hands it to + * Controller B inside an encrypted frame. Never print the password. + * @return false if no network is saved + */ +bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n); + } // namespace WiFiManager diff --git a/wiki/index.md b/wiki/index.md index 7faf3ae..333a027 100644 --- a/wiki/index.md +++ b/wiki/index.md @@ -20,7 +20,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee - [[driveline-speed-signals]] — **engine / turbine / output-shaft speeds**: turbine speed as physical proof of gear engagement, and the output-shaft field that is our **only road-speed source** (no DSC on this bus) — the feedback variable for a future cruise-control PoC, with the safety envelope that would require - [[dual-controller-architecture]] — Controller A → UART1 + ESP-NOW, protocol v2 → Controller B (1.3" display + Patrol gauge outputs); A owns alerts and the gauge tunables (`cfg` console) - [[obd-diagnostic-polling]] — **why boost / MAF / rail / injection / DTCs never appear on the sniffer** and how a tester gets them: Route A generic OBD-II mode 01 on `0x7DF` and Route B BMW KWP on `0x6F1` → `0x612` — **BOTH VERIFIED WORKING 2026-09-23** (minimal PID set, no boost PID, mode 09 silent; `1A 86` ident identifies the donor; DTCs read via mode 03), the capture-with-Launch procedure (still wanted for the `22 D1xx` live-data identifiers), and why polling is a transmit-on-the-bus design decision -- [[ota-updates]] — **Controller A updates itself from Gitea releases**: tag `v*` → CI builds + signs (ECDSA P-256) → Settings → Updates (confirm dialog) or `ota install` (manual, parked, Wi-Fi) pulls over HTTPS from the public repo, verifies, flashes the idle slot, 30 s confirm-or-rollback; **verified end-to-end, from the screen since 2026-09-27 (now v0.1.5)**, release with `git push --follow-tags origin main`; dual-slot partition table; plan for updating Controller B through A over ESP-NOW +- [[ota-updates]] — **Controller A updates itself from Gitea releases**: tag `v*` → CI builds + signs (ECDSA P-256) → Settings → Updates (confirm dialog) or `ota install` (manual, parked, Wi-Fi) pulls over HTTPS from the public repo, verifies, flashes the idle slot, 30 s confirm-or-rollback; **verified end-to-end, from the screen since 2026-09-27 (now v0.1.5)**, release with `git push --follow-tags origin main`; dual-slot partition table; **Controller B card on the Updates page (2026-09-27)**: B pulls its own release, A pairs over the wire (`link pair`), hands over credentials in encrypted frames and triggers - details in B's wiki `controller-b-ota` ## Synthesis diff --git a/wiki/log.md b/wiki/log.md index c7b21de..fbcabb1 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -194,3 +194,7 @@ Tag build died at the link step: `ModuleNotFoundError: No module named 'SCons.To Second tag build (pioarduino core fork in the workflow) succeeded: release `v0.1.7` on Gitea at 18:28 with `firmware.bin` (1,722,464 B), `firmware.elf`, `manifest.txt` (target patrol-a, sha256 `a2949644…4c09`, ECDSA sig), built from `8e739fa`. Off-device check: downloaded binary's SHA-256 and size match the manifest. The bench board (dev build on COM14) could not `ota check` — Wi-Fi off and no saved network at that moment — so the first on-device install of v0.1.7 is the user's, from Settings → Updates. Expected on the board: "Version v0.1.7 is available", install with the screen lit and the progress bar, restart, `A v0.1.7` bottom-right; the Updates page then says up to date. + +## [2026-09-27] update | Controller B updates from A's screen: link_peer, two-way maintenance frames, Updates page with two cards + +Implemented A's half of B's OTA (design in B's wiki `controller-b-ota`). Shared `automotive_data.h` (+ new `link_secure.h`, both byte-identical in the two repos): `STATUS` 0x03 B → A, `PAIR` 0x04 A → B wire-only, `SECURE` 0x05 A → B (AES-256-GCM under the pairing key; inner `OTA_CMD` / `WIFI_CREDS`), `PACKET_MAX_PAYLOAD` 64 → 160, `PACKET_VERSION` unchanged (DATA/CONFIG bytes identical). New `src/modules/link_peer.cpp`: pairing key in NVS `linkpeer`, `link pair` sends the key ×3 over UART1 only (`UARTManager::sendWire()`), B's STATUS kept + logged, automatic push of the remembered Wi-Fi network to B (hash-compared, ≥ 15 s apart, FORGET when A forgets), `requestCheck/requestInstall` for the screen behind `Ota::isParked()` + A on Wi-Fi. `EspNowLink` gained a receive callback (IDF 5.5 `esp_now_recv_info_t`) and `sendTo()`; `WiFiManager::getSavedCredentials()` (for LinkPeer only, never printed). Settings → Updates rebuilt as two cards (Controller A / Controller B) that fit the 484 px page without scrolling. Bench: B heard within seconds (`link status`: MAC, `dev`, heap 234 KB), refusals correct; `link pair` cannot be confirmed because **no wire is connected on the bench** (B reports `uart silent`). Build notes: `pio` from PowerShell only (idf_tools refuses MSYS); first build after the B project reinstalls Arduino 3.3.3 and may fail once with a `TypeError` - rerun. diff --git a/wiki/pages/ota-updates.md b/wiki/pages/ota-updates.md index af6f4ba..d0dcb65 100644 --- a/wiki/pages/ota-updates.md +++ b/wiki/pages/ota-updates.md @@ -106,9 +106,9 @@ Wi-Fi must be joined first — Settings → Wi-Fi (remembered from then on) or ` - **Joining Wi-Fi killed ESP-NOW**: the Wi-Fi task used `WiFi.disconnect(true)` (true = radio off), which drops ESP-NOW; B then ran on the wire only. Now `WiFi.disconnect()`, and `EspNowLink::send()` re-initialises ESP-NOW if the driver ever drops it. Verified: joined Personal1 (channel 9), ESP-NOW 195 sent / 0 failed. - `showConnectionResult()` took the LVGL lock with a 0 ms try-lock, ignored the result, and touched widgets that are NULL off the Settings screen — now waits for the lock and null-checks. It still showed **no success feedback** on screen (user: "a disaster UX") — resolved by the hand-coded Settings screen in v0.1.5 ([[open-questions]] #14). -## Controller B (not built yet) +## Controller B (implemented 2026-09-27) -Plan agreed 2026-09-26: B is updated **by A over ESP-NOW**, not by the RS485 wire (the wire is one-way A→B; ESP-NOW is bidirectional and faster). A downloads B's signed image (target `patrol-b`) from B's repo releases, sends it with acks, B verifies the signature and swaps slots with the same rollback scheme. Prerequisites: B moves off the stock `default.csv` (1.25 MB slots, 1.07 MB firmware → too tight) to a 16 MB layout (confirm B's flash size first; one USB flash); ESP-NOW pairing/encryption so only A can talk to B; protocol frames for the transfer (shared `automotive_data.h` → version bump in both repos). B's repo is public since 2026-09-27 (anonymous API 200). Wire stays for gauge-data redundancy. +The 2026-09-26 idea (A streams B's image over ESP-NOW) was dropped for a **pull design** the user chose on 2026-09-27: B downloads its own signed release (target `patrol-b`, B's repo, same key) over Wi-Fi; A only hands over the credentials and the trigger. Full design, verification state and the first-pairing procedure live in B's wiki (`../../ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md`). A's side: `src/modules/link_peer.cpp` - `link pair` sends a random key over the UART wire once (never by radio; both repos are public), B's `STATUS` frames (version, phase, progress) arrive over ESP-NOW unicast, credentials and OTA commands go to B inside AES-256-GCM `SECURE` frames, and Settings → Updates gained a **Controller B** card (Installed / Latest / Check / Install) next to Controller A's. B's install is behind the same parking gate plus "A must be on Wi-Fi" (same AP ⇒ same channel ⇒ B's progress frames keep arriving). Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. Verified on the bench: STATUS frames and every refusal path; pairing itself waits for the wire to be connected. ## Related