Controller B OTA: link_peer (STATUS to A, PAIR from the wire, AES-GCM SECURE frames), updater ported from A, console, CI workflow, shared header v2 maintenance frames; wiki + docs
Firmware / build (push) Successful in 2m57s

This commit is contained in:
2026-09-27 20:26:40 +02:00
parent 30ab113218
commit e6773c73ba
24 changed files with 1805 additions and 57 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
- [[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
- [[controller-b-ota]] — **design (2026-09-27, agreed)**: B pulls its own signed release over Wi-Fi; A hands over the credentials once (paired key exchanged over the wire, then encrypted ESP-NOW unicast) and the trigger; B reports version/phase back; same manifest + key as A; work order and risks
- [[controller-b-ota]] — **implemented 2026-09-27 (STATUS + gates verified, pairing/first release pending)**: B pulls its own signed release over Wi-Fi; `link pair` on A sends a random key over the UART wire once; credentials and OTA commands travel in AES-256-GCM `SECURE` frames; B reports version/phase/progress in `STATUS` frames; A's Updates page has a Controller B card; B's updater = port of A's; CI workflow + `v0.1.0` procedure
- [[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
+4
View File
@@ -62,3 +62,7 @@ Mirror of the A-side clean-up. `include/ui/` (SquareLine export) deleted; the sc
User asked about updating B "via ESP-NOW". Compared A-pushes-chunks vs B-pulls-itself; user chose the pull design. Facts checked: B's Arduino 2.0.17 `qio_opi` sdkconfig has bootloader rollback, ECDSA P-256 and PEM parsing enabled (no core rebuild), 235 KB internal free after today's clean-up, partition table already has two OTA slots. Design page [[controller-b-ota]]: credential handoff via a pairing key exchanged over the UART wire on the bench then encrypted ESP-NOW unicast (both repos are public, so a compiled-in key would protect nothing); STATUS frames B→A for version + phase and A's Updates page gets a Controller B row; OTA_CMD trigger behind A's parking gate; B's OTA module = port of A's with link-data gate and a small on-screen notice; B CI workflow + `BMW_NISSAN_FIRMWARE_SIGNING_KEY` secret on the B repo (user action). New frame types 0x03–0x06, PACKET_VERSION stays 2. Open question #12 added.
## [2026-09-27] update | Controller B OTA implemented on both boards; STATUS + gates verified; pairing awaits the wire
Implemented the [[controller-b-ota]] design end to end. Shared header: `STATUS` 0x03 / `PAIR` 0x04 / `SECURE` 0x05 (+ inner `OTA_CMD` 0x11, `WIFI_CREDS` 0x12), `PACKET_MAX_PAYLOAD` 160, new `include/protocol/link_secure.h` (AES-256-GCM seal/open, key fingerprint; mbedtls names differ between IDF 4.4 and 5.5, handled). Decision: application-level GCM instead of ESP-NOW peer encryption (no PMK/LMK bookkeeping, no broadcast-vs-encrypted-peer doubt). B: `link_peer.cpp` (NVS key + A's MAC, credentials in namespace `wifi`, mailboxes so the Wi-Fi/UART tasks never touch NVS, STATUS every 5 s / on change, nonce replay window), `console.cpp` (line reader + handler chain, `help`), `ota_update.cpp` (port of A's: link-data gate, joins Wi-Fi only for the job, notice line on the screen via `GaugeScreen::setNotice()`, pumps STATUS from the download loop), `include/config/ota_config.h` (`patrol-b`, this repo, same roots + public key), `.gitea/workflows/firmware.yml`, `tools/ota/firmware_signing_pub.pem`. A: `link_peer.cpp` (`link status|pair|unpair|creds|ota ...`, automatic credential sync, B card on Settings → Updates), `EspNowLink` receive callback + `sendTo()`, `UARTManager::sendWire()`, `WiFiManager::getSavedCredentials()`, `Ota::isParked()`. Bench (A COM14, B COM13): B's STATUS frames reach A (MAC 10:51:DB:8F:B6:5C, `dev`, heap 234 KB); `ota check` on B refuses "no Wi-Fi credentials from A yet"; `link ota check` on A refuses "not paired"; `link pair` on A sent PAIR ×3 but B never saw it: **B's UART leg is silent (uart=0) — no wire on the bench right now**. Next: connect `485_A → IO1` + GND, `link pair`, credentials, tag `v0.1.0`, install from A's screen. Build notes: run `pio` from PowerShell (idf_tools refuses MSYS/Git Bash); the first build after switching between the two projects reinstalls the other Arduino core and can fail once with a `TypeError` — run it again.
+43 -45
View File
@@ -1,82 +1,80 @@
---
type: concept
tags: [ota, wifi, esp-now, security, design]
tags: [ota, wifi, esp-now, security, design, verified]
updated: 2026-09-27
---
# Over-the-air updates for Controller B
Design agreed 2026-09-27 (user chose this over A streaming the image through ESP-NOW): **B pulls its own signed release from Gitea over Wi-Fi; A only hands B the network credentials and the trigger, over the existing link.** Everything reuses what already works on A ([[ota-updates]] in the sibling wiki).
**Status 2026-09-27: implemented on both controllers, bench-tested up to the pairing step.** B pulls its own signed release from Gitea over Wi-Fi; A hands B the network credentials and the trigger over the existing link, and shows B's progress on its own Updates page. Design chosen by the user over "A streams the image through ESP-NOW" (comparison below). Everything reuses A's proven pipeline ([[ota-updates]] in the sibling wiki).
## What is verified, what is not
| Step | State |
|---|---|
| B → A STATUS frames (version, phase, heap, uptime) over ESP-NOW unicast | `(verified 2026-09-27)` A's console `link status` lists B's MAC, `dev`, heap 234 KB; A's Updates page shows the Controller B card |
| Gates on both sides (unpaired → refused, no credentials → refused, key mismatch → refused) | `(verified 2026-09-27)` each refusal text seen on the consoles |
| `link pair` over the UART wire | **not yet**: the bench had no wire connected when tested (B: `uart=0 ... uart silent`). Needs `485_A → IO1`, GND → GND, 120 Ω switch OFF ([[controller-link]] bench wiring) |
| Encrypted credential handoff, B joins the network | not yet (needs pairing) |
| `link ota check` / install from A's screen, first signed B release | not yet (needs pairing + release `v0.1.0` of this repo) |
## Why pull, not push
| | A pushes over ESP-NOW | B pulls itself (chosen) |
|---|---|---|
| Transport | ~4,400 × 250-byte frames, needs acks/resends both ways (new protocol) | one HTTPS download, TCP does the rest |
| Code | new chunk protocol on both boards | port of A's `ota_update.cpp` (729 lines, proven) |
| RAM | image transits A's scarce internal RAM | B has 235 KB internal free after the 2026-09-27 clean-up `(verified)`; TLS fits without the PSRAM tricks A needs |
| Transport | ~4,400 × 250-byte frames, acks/resends both ways (new protocol) | one HTTPS download, TCP does the rest |
| Code | new chunk protocol on both boards | port of A's `ota_update.cpp` (proven) |
| RAM | image transits A's scarce internal RAM | B has 235 KB internal free `(verified)`; TLS fits without A's PSRAM tricks |
| Integrity | same signed manifest | same signed manifest, same public key, `target=patrol-b` |
| New risk | protocol bugs mid-flash | Wi-Fi credentials must reach B once |
## Prerequisites — all in place `(verified 2026-09-27)`
## How it works
- B's partition table: two 6.5 MB OTA slots (`default_16MB.csv`), NVS untouched.
- B's core (Arduino 2.0.17 / IDF 4.4, `qio_opi` sdkconfig): `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=1`, `MBEDTLS_ECDSA_C`, `SECP256R1`, `PEM_PARSE_C` — no core rebuild needed.
- B has 8 MB PSRAM and a Wi-Fi radio already running in STA mode for ESP-NOW.
### 1. Pairing (once, on the bench, over the wire)
## The pieces
`link pair` on A's console. A generates a random 32-byte key, sends `PAIR` (magic, key, A's STA MAC) **three times over UART1 only** and stores the key in NVS (`linkpeer/key`). B accepts `PAIR` only from the UART source (a `PAIR` heard on the radio is dropped and logged), stores key + A's MAC in NVS (`linkpeer/key`, `linkpeer/amac`) and answers with a STATUS carrying `key_fp` = first two bytes of SHA-256(key). A logs `Controller B confirmed pairing (fingerprint XXXX)` when it matches. Both repos are public, so this is the only secret and it never travels by radio. Survives reflashes (NVS); an NVS erase on either side means re-pairing at home — the car has no wire today ([[controller-link]]).
### 1. Credential handoff (A → B, once)
### 2. SECURE frames (A → B, ESP-NOW unicast)
A knows the remembered network (`WiFiManager`, NVS namespace `wifi`). B must learn it without it being broadcast in the clear — the ESP-NOW data link is unencrypted broadcast and both repos are public, so a compiled-in key would protect nothing.
Everything A sends B by radio that matters goes inside `PACKET_TYPE_SECURE`: `nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner)`. Helpers in the shared `include/protocol/link_secure.h` (mbedtls GCM, same calls on IDF 4.4 and 5.5). B additionally requires the sender MAC to equal the paired A MAC. Decision 2026-09-27: application-level GCM instead of ESP-NOW's built-in peer encryption — no PMK/LMK peer bookkeeping, no doubt about whether an encrypted peer still receives A's plain broadcasts, and the same code on both cores. Inner payloads:
- **Pairing on the bench, over the wire**: a console command on A (`link pair`) generates a random 16-byte key, sends it to B **only over UART1** (the physical wire, not ESP-NOW), both sides store it in NVS. Done once; survives reflashes (NVS).
- After pairing, the credential frame goes **ESP-NOW unicast, encrypted** with that key (ESP-NOW peer with `encrypt=true`, LMK = the pairing key, PMK fixed). B learns A's MAC from the frames it already receives; A learns B's MAC from B's status frames (below).
- B stores the credentials in its own NVS so a later update does not need A awake — and `wifi forget` on A also tells B to forget.
- `WIFI_CREDS` (`action` SET/FORGET, ssid, pass): B stores them in NVS namespace `wifi` (same keys as A's). **Pushed automatically**: A's `LinkPeer::tick()` compares a hash of its remembered network against what B reports (`LINK_STATUS_HAVE_WIFI`) and pushes when B lacks credentials, when A's changed, or a FORGET when A forgot its network and B still has one. At most one push per 15 s. `link creds` pushes now.
- `OTA_CMD` (`check` / `install` [force] / `rollback`, random nonce): B drops a nonce it has seen among the last four (replay).
### 2. Status back-channel (B → A)
### 3. STATUS (B → A, every 5 s and on every phase change)
New frame type `STATUS` (B → A, ESP-NOW unicast to A's MAC, every 5 s): B's firmware version, OTA phase, uptime, free heap. A shows it on Settings → Updates as a second row, **Controller B: vX.Y.Z**, with its own Check / Install. This also gives A the MAC it needs for the encrypted unicast.
`link_status_t`: B's `FW_VERSION`, OTA phase (same numbering as A's `Ota::phase_t`), progress %, flags (paired, have Wi-Fi, Wi-Fi joined, pending verify), `key_fp`, uptime, free heap, latest tag, failure message. Unicast to A's MAC as heard on A's DATA/CONFIG frames (or the MAC from pairing). A keeps the last one (`LinkPeer::getStatus()`), "not heard" after 15 s. **During a job the loop task is blocked, so B's updater pumps a STATUS at most once a second from inside the download loop** — that is how the progress percentage reaches A's screen.
### 3. Trigger (A → B)
### 4. A's Updates page
New frame type `OTA_CMD` (A → B, unicast): `check` or `install`. A applies its own parking gate first (engine off, shaft still, lever P/N — the same one that guards A's install) and refuses otherwise. B additionally refuses while it sees rpm > 0 in the link data.
Settings → Updates now has two cards, **Controller A** and **Controller B**, each with Installed / Latest / a status line / Check / Install. B's buttons are enabled only when B is heard, paired with *this* key and holds credentials; the status line otherwise says which of those is missing. Install asks for confirmation, then `LinkPeer::requestInstall()` applies A's parking gate (engine off, shaft still, lever P/N — `Ota::isParked()`), requires **A itself to be on Wi-Fi** (same network as B ⇒ same radio channel ⇒ B's STATUS frames keep arriving while B is joined) and sends the `OTA_CMD`.
### 4. B's OTA module
### 5. B's updater (`src/modules/ota_update.cpp`)
`src/modules/ota_update.cpp` on B = A's module with these changes:
- gate: link data (rpm == 0, no shaft) instead of the CAN driver; A's gate already ran.
- no `Tunables::flush()`; `GaugeOutputs` are forced low for the duration (parked anyway).
- notice on the 240×240 screen: a small "Updating vX — N %" line under the gear (SPI panel, no flicker problem).
- `OTA_TARGET "patrol-b"`, `OTA_REPO "art/ESP32-S3-LCD-1.3"`, same public key as A (`tools/ota/firmware_signing_pub.pem`), same Let's Encrypt roots.
- `verifyRollbackLater()` override + confirm after 30 s of healthy uptime, else the bootloader rolls back — identical to A.
- Wi-Fi: join with the stored credentials only for the job, then `WiFi.disconnect()` back to a bare STA so ESP-NOW hopping resumes. (During the join B's channel follows the AP; A follows the same AP, so the link keeps working — and the gauges are idle while parked.)
- Console on B (CH343 serial): `ota status | check | install [force] | rollback`, `wifi status | forget`.
Port of A's module. Differences: gate = link data (`rpm == 0`, lever P/N/unknown; a silent link counts as parked, A's gate already ran); no `Tunables`; the gauge outputs are driven to their no-link state before the job; a one-line notice on the round screen (`GaugeScreen::setNotice()`, on `lv_layer_top()`), "Updating vX 42%"; `OTA_TARGET "patrol-b"`, `OTA_REPO "art/ESP32-S3-LCD-1.3"`, same public key and Let's Encrypt roots (`include/config/ota_config.h`); mbedtls 2.28 names. Wi-Fi: `WiFi.begin()` with the stored credentials only for the job (25 s join timeout), `WiFi.disconnect(false)` afterwards so the ESP-NOW receiver hops back to A's channel. `verifyRollbackLater()` override + confirm after 30 s of uptime, else the bootloader rolls back — identical to A. Jobs run in the loop task; the gauges pause (parked anyway). Console (CH343 serial): `ota status | check | install [force] | rollback`, `link status | unpair`, `wifi status | forget`, `help`.
### 5. Release pipeline for B
### 6. Release pipeline
A copy of A's `.gitea/workflows/firmware.yml` in the B repo: `pio run` (no core rebuild — B is on the stock espressif32@6 platform, so upstream PlatformIO is fine there), tag `v*` → signed release with `manifest.txt` (`target=patrol-b`), `main` → unsigned `main-latest`. Needs the repo secret **`BMW_NISSAN_FIRMWARE_SIGNING_KEY`** on the B repo (or as an organisation secret) — *user action*.
`.gitea/workflows/firmware.yml` in this repo (copy of A's): push to `master` → unsigned pre-release `main-latest`; tag `v*` → signed release with `manifest.txt` (`target=patrol-b`, ECDSA P-256 over `patrol-b|<tag>|<sha256>`), self-checked against `tools/ota/firmware_signing_pub.pem`. Upstream PlatformIO core is fine here (stock espressif32@6 platform; the pioarduino fork is only needed on A). Secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY` set on the B repo by the user 2026-09-27. Version strings must be ≤ 15 characters (`link_status_t::version[16]`) — the workflow checks.
### 6. Shared header
### 7. Shared header
`automotive_data.h` gains `PACKET_TYPE_STATUS 0x03`, `PACKET_TYPE_OTA_CMD 0x04`, `PACKET_TYPE_WIFI_CREDS 0x05` (+ `PACKET_TYPE_PAIR 0x06` on the wire only) with their payload structs. DATA/CONFIG unchanged, so `PACKET_VERSION` stays 2 and an older B simply ignores the new types. The header stays byte-identical in both repos.
`automotive_data.h`: `PACKET_TYPE_STATUS 0x03`, `PACKET_TYPE_PAIR 0x04`, `PACKET_TYPE_SECURE 0x05`, inner types `LINK_INNER_OTA_CMD 0x11` / `LINK_INNER_WIFI_CREDS 0x12`, structs `link_pair_t` (42 B), `link_status_t` (78 B), `link_ota_cmd_t`, `link_wifi_creds_t` (98 B); `PACKET_MAX_PAYLOAD` 64 → 160 (a SECURE WIFI_CREDS payload is 127 B; the whole frame stays under ESP-NOW's 250 B). DATA/CONFIG bytes unchanged, so `PACKET_VERSION` stays 2 and an older B logs the new types as type errors and carries on. Header + `link_secure.h` byte-identical in both repos (`cmp`-checked).
## Order of work
## Procedure: first pairing and first update
1. Shared header + B: STATUS frames out, A: receive callback + Updates row (visible progress from day one).
2. Pairing over the wire + encrypted credential handoff; B stores and can join (`wifi status` on B shows it).
3. B OTA module port + on-screen notice + gauge hold; console-driven test with a **dev release** (see below).
4. B CI workflow; first signed `v0.1.0` for B; end-to-end from A's screen.
5. Wiki + CLAUDE.md on both sides.
1. Bench: both boards on USB, `485_A → IO1`, GND → GND, 5B's 120 Ω switch OFF. B's 5-second stats line must say `uart alive`.
2. A console: `link pair` → A prints the fingerprint; within 5 s `link status` shows `key XXXX (matches)` and B's console printed `PAIRED over the wire`.
3. A on Wi-Fi with its remembered network → within ~15 s A logs `Wi-Fi credentials for '<ssid>' sent to Controller B (encrypted)`, B logs `stored`, `link status` shows `Wi-Fi creds yes`.
4. Tag this repo (`git tag -a v0.1.0 -m ... && git push --follow-tags origin master`), wait for the Gitea release with `manifest.txt`.
5. A: Settings → Updates → Controller B → Check → "Version v0.1.0 is available for Controller B" → Install → confirm. B's screen shows "Updating v0.1.0 N%", A's card shows the percentage, B restarts, its STATUS says `v0.1.0` with "new firmware, confirming..." for 30 s, then plain. Console alternative: `link ota check`, `link ota install`.
Test without the secret: nothing can be signed locally (the private key exists only as a Gitea secret), so step 3 is tested against A's signature path by pointing B's `OTA_REPO` at the B repo's first CI release — i.e. step 4 precedes the end-to-end test. Everything up to "manifest signature OK" can be exercised earlier with A's release (target mismatch is the expected, correct refusal).
## Risks / open
## Risks
- **Wi-Fi + ESP-NOW coexistence on B** while joined to the AP: same situation as on A (works, channel follows the AP). If B's ESP-NOW receive stalls during the download it does not matter — parked.
- **Internal RAM on B during TLS**: 235 KB free today; A needed ~40 KB internal per TLS session. Fine, but measure once.
- **A's Updates page** grows a second row; A's LVGL pool is in PSRAM, no concern.
- **Pairing key lost** (NVS erase on either side): re-pair on the bench. The car has no wire today (open question in [[controller-link]]) — pairing must be done at home.
- **Wi-Fi + ESP-NOW coexistence on B while joined**: A and B on the same AP share the channel; B's receiver follows the AP channel while joined and hops back after `WiFi.disconnect(false)`. Not yet observed live.
- **Internal RAM on B during TLS**: 235 KB free today; the job logs heap before/after. Measure once on the first check.
- **Pairing key lost** (NVS erase on either side): re-pair at home over the wire.
- Two boards, one PlatformIO penv: the first `pio run` after switching projects reinstalls the other Arduino core and can fail once with a `TypeError`; run it again. Builds must be started from PowerShell, not Git Bash (`idf_tools.py` refuses MSYS).
## Related
+4
View File
@@ -15,6 +15,10 @@ 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.
## Maintenance frames (2026-09-27) — the link is no longer one-way
Three frame types were added for [[controller-b-ota]] without bumping `PACKET_VERSION` (DATA/CONFIG bytes unchanged): `STATUS` 0x03 (B → A, ESP-NOW unicast to A's MAC, every 5 s: B's version, update phase, heap), `PAIR` 0x04 (A → B, **UART wire only**: the shared key), `SECURE` 0x05 (A → B, ESP-NOW unicast, AES-256-GCM envelope for Wi-Fi credentials and OTA commands). `PACKET_MAX_PAYLOAD` grew 64 → 160. B's ESP-NOW receiver routes non-DATA/CONFIG types to `LinkPeer` and remembers A's MAC from the data frames; A's `EspNowLink` now has a receive callback and `sendTo()`. Verified 2026-09-27: B's STATUS reaches A (`link status` on A lists B's MAC, version, heap).
## Wire-level contract — protocol v2 `(repo, 2026-09-21; spec: 5B repo docs/UART_PROTOCOL.md)`
- 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`.
+1 -1
View File
@@ -22,7 +22,7 @@ The research frontier for Controller B. Answering any of these should trigger up
13. **CANNY 5.3 pico details**: what is the HR PWM base clock (period 255 = what frequency), and what sat between the CANNY pin and the gauge wire? The user may still have the unit and harness. → [[temp-stage-cfd]]
8. ~~**Does `engine_oil_temp` stay in the packet?**~~ **Answered 2026-09-27 (user): dropped from the screen.** The field stays in the packet (protocol v2 unchanged, never valid on this engine), but B's hand-coded screen no longer has an oil quadrant - the battery cell sits alone at the bottom.
12. **OTA for Controller B** — design agreed 2026-09-27 → [[controller-b-ota]]. Open inside it: the signing secret on the B repo (user), pairing key exchange on the bench, first B release.
12. **OTA for Controller B** — design agreed and **implemented 2026-09-27** → [[controller-b-ota]]. STATUS frames and every gate verified on the bench; signing secret set on the B repo (user, 2026-09-27). Still open: `link pair` over the wire (the bench had no wire connected), the automatic credential handoff, the first signed release `v0.1.0` and the first install from A's screen.
## Hardware