diff --git a/.gitea/workflows/firmware.yml b/.gitea/workflows/firmware.yml new file mode 100644 index 0000000..f005a7a --- /dev/null +++ b/.gitea/workflows/firmware.yml @@ -0,0 +1,163 @@ +name: Firmware + +# Controller B firmware, built by PlatformIO on every push. Same scheme as +# Controller A (ESP32-S3-Touch-LCD-5B/.gitea/workflows/firmware.yml): +# +# - push to master -> rolling PRE-release `main-latest` (firmware.bin + .elf), +# unsigned, no manifest. Bench / USB flashing only; the +# device reads /releases/latest, which skips pre-releases. +# - push tag v* -> the OTA release: firmware.bin + firmware.elf + +# manifest.txt (size, sha256, ECDSA P-256 signature over +# "patrol-b||"). Controller B pulls this when +# A's Updates screen (or `ota install` on B) asks for it. +# +# Signing key: secret BMW_NISSAN_FIRMWARE_SIGNING_KEY (PEM, EC P-256), the same +# key as Controller A's; the target string keeps the two apart. Its public half +# is compiled in (include/config/ota_config.h) and kept in +# tools/ota/firmware_signing_pub.pem for the self-check below. +# +# This project is on the stock espressif32@6 platform (Arduino 2.0.17), so the +# upstream PlatformIO core is fine here - the pioarduino fork is only needed +# on A. A master push skips itself when the commit already carries a v* tag or +# only changes docs. + +on: + push: + branches: [master] + tags: ['v*'] + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Skip? + env: + BEFORE: ${{ github.event.before }} + run: | + SKIP=false + if [ "${GITHUB_REF#refs/tags/}" = "${GITHUB_REF}" ] && [ "${GITHUB_EVENT_NAME}" = "push" ]; then + if git ls-remote --tags origin 'v*' | grep -q "^${GITHUB_SHA}"; then + echo "commit ${GITHUB_SHA:0:7} is tagged - the tag build covers it"; SKIP=true + elif [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] && + git fetch -q --depth=1 origin "$BEFORE" 2>/dev/null; then + CHANGED=$(git diff --name-only "$BEFORE" "$GITHUB_SHA") + echo "changed files:"; echo "$CHANGED" + if [ -n "$CHANGED" ] && ! echo "$CHANGED" | grep -qvE '^wiki/|\.md$'; then + echo "docs-only change - no firmware build"; SKIP=true + fi + fi + fi + echo "SKIP=${SKIP}" >> "$GITHUB_ENV" + + - name: Version + if: env.SKIP != 'true' + run: | + if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then + VERSION="${GITHUB_REF_NAME}" + else + VERSION="main-${GITHUB_SHA:0:7}" + fi + case "$VERSION" in *[!A-Za-z0-9._-]*) echo "::error::bad version '$VERSION'"; exit 1;; esac + [ ${#VERSION} -lt 16 ] || { echo "::error::version too long for link_status_t::version (15 chars max)"; exit 1; } + echo "VERSION=${VERSION}" >> "$GITHUB_ENV" + echo "version: ${VERSION}" + + - name: Cache PlatformIO + if: env.SKIP != 'true' + uses: actions/cache@v4 + with: + path: | + ~/.platformio/packages + ~/.platformio/platforms + .pio/libdeps + key: pio-b-${{ hashFiles('platformio.ini') }} + + - name: Install PlatformIO + if: env.SKIP != 'true' + run: | + curl -LsSf https://astral.sh/uv/install.sh | sh + export PATH="$HOME/.local/bin:$PATH" + uv tool install platformio + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + pio --version + + - name: Build + if: env.SKIP != 'true' + run: | + export PLATFORMIO_BUILD_FLAGS="-DFW_VERSION=\\\"${VERSION}\\\"" + pio run + mkdir -p dist + cp .pio/build/esp32_s3_lcd_1_3/firmware.bin dist/ + cp .pio/build/esp32_s3_lcd_1_3/firmware.elf dist/ + grep -q "${VERSION}" dist/firmware.bin || { echo "::error::FW_VERSION not baked into the image"; exit 1; } + ls -la dist/ + + - name: Sign + manifest (tags only) + if: env.SKIP != 'true' && startsWith(github.ref, 'refs/tags/') + env: + BMW_NISSAN_FIRMWARE_SIGNING_KEY: ${{ secrets.BMW_NISSAN_FIRMWARE_SIGNING_KEY }} + run: | + set -e + [ -n "$BMW_NISSAN_FIRMWARE_SIGNING_KEY" ] || { echo "::error::secret BMW_NISSAN_FIRMWARE_SIGNING_KEY is not set"; exit 1; } + SHA=$(sha256sum dist/firmware.bin | cut -d' ' -f1) + SIZE=$(stat -c%s dist/firmware.bin) + printf '%s' "patrol-b|${VERSION}|${SHA}" > stmt.txt + umask 077 + printf '%s\n' "$BMW_NISSAN_FIRMWARE_SIGNING_KEY" > key.pem + openssl dgst -sha256 -sign key.pem -out sig.der stmt.txt + rm -f key.pem + openssl dgst -sha256 -verify tools/ota/firmware_signing_pub.pem -signature sig.der stmt.txt + SIG=$(od -An -v -tx1 sig.der | tr -d ' \n') + printf 'target=patrol-b\nversion=%s\nsize=%s\nsha256=%s\nsig=%s\n' \ + "$VERSION" "$SIZE" "$SHA" "$SIG" > dist/manifest.txt + cat dist/manifest.txt + + - name: Publish release + if: env.SKIP != 'true' + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + API: ${{ github.api_url }} + REPO: ${{ github.repository }} + run: | + set -e + auth="Authorization: token ${TOKEN}" + if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then + TAG="${GITHUB_REF_NAME}" + PRE=false + NAME="Controller B ${TAG}" + BODY="Signed OTA release. Installed from Controller A's Updates screen (parked) or with \`ota install\` on Controller B's console." + else + TAG="main-latest" + PRE=true + NAME="Controller B main build" + BODY="Unsigned build of master @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests." + OLD=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \ + | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true) + if [ -n "$OLD" ]; then + curl -sS -X DELETE -H "$auth" "${API}/repos/${REPO}/releases/${OLD}" || true + curl -sS -X DELETE -H "$auth" "${API}/repos/${REPO}/git/refs/tags/${TAG}" || true + fi + fi + REL=$(curl -sS -X POST -H "$auth" -H "Content-Type: application/json" \ + -d "{\"tag_name\":\"${TAG}\",\"target_commitish\":\"${GITHUB_SHA}\",\"name\":\"${NAME}\",\"body\":\"${BODY}\",\"draft\":false,\"prerelease\":${PRE}}" \ + "${API}/repos/${REPO}/releases" || true) + REL_ID=$(printf '%s' "$REL" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true) + if [ -z "$REL_ID" ]; then + REL_ID=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \ + | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true) + fi + [ -n "$REL_ID" ] || { echo "::error::could not create release: $REL"; exit 1; } + echo "release id: ${REL_ID}" + for f in dist/*; do + name=$(basename "$f") + echo "uploading ${name}" + code=$(curl -sS -o /tmp/up.json -w '%{http_code}' -X POST -H "$auth" \ + -H "Content-Type: application/octet-stream" --data-binary @"${f}" \ + "${API}/repos/${REPO}/releases/${REL_ID}/assets?name=${name}") + [ "$code" = "201" ] || { echo "::error::upload ${name} failed (HTTP ${code}): $(cat /tmp/up.json)"; exit 1; } + done + echo "published ${TAG}" diff --git a/CLAUDE.md b/CLAUDE.md index a560b92..5867caa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,14 +46,19 @@ src/ espnow_receiver.cpp # ESP-NOW leg: STA mode, channel hopping while silent, feeds processFrame() gauge_outputs.cpp # Patrol gauges: tach on IO7 (hardware-timer ISR), coolant PWM on IO8 (LEDC ch4), NVS-cached config debug_monitor.cpp # shows/hides LVGL perf+mem monitors from A's debug_enabled flag (recorded by the receiver, applied in loop) + link_peer.cpp # maintenance side of the link: STATUS to A, PAIR from the wire, SECURE (AES-GCM) frames from A -> Wi-Fi creds / OTA commands + ota_update.cpp # pulls this repo's signed Gitea release over Wi-Fi (port of A's module), 'ota' console + console.cpp # serial line reader + handler chain ('help', 'link', 'wifi', 'ota') assets/ assets.h # LV_FONT_DECLARE / LV_IMG_DECLARE for the files below fonts/ # Ubuntu Light 35 (values) and Ubuntu Bold 110 (gear) - plain LVGL font arrays images/ # 3 status icons x normal/red - plain LVGL image arrays include/ config/lv_conf.h # LVGL 8.4.0 config (RGB565, dark theme, 128 KB pool in PSRAM, millis() tick, log off) - modules/uart_receiver.h, espnow_receiver.h, gauge_outputs.h, debug_monitor.h + config/ota_config.h # FW_VERSION (CI bakes it, "dev" locally), OTA_TARGET "patrol-b", repo URLs, CA roots, signing public key + modules/uart_receiver.h, espnow_receiver.h, gauge_outputs.h, debug_monitor.h, link_peer.h, ota_update.h, console.h protocol/automotive_data.h # SHARED packet contract — copied from Controller A, must match its version + protocol/link_secure.h # SHARED too: AES-256-GCM envelope for SECURE frames (byte-identical in both repos) ``` **UI**: the single screen is hand-coded in `src/modules/gauge_screen.cpp` (SquareLine Studio was retired on 2026-09-27; `include/ui/` is gone - do not reintroduce a UI generator). The font and icon arrays it uses were kept from the old export, symbol names unchanged, under `src/assets/`. The engine-oil quadrant was dropped the same day: this engine has no oil temperature sensor. @@ -70,12 +75,24 @@ include/ **DebugMonitor** — `init()`, `setVisible(bool)` (records only; called from the receiver), `tick()` (applies under the LVGL lock; called from loop), `isVisible()`. Driven by the `debug_enabled` byte in each packet, so Controller A's debug toggle controls B's overlays. +**LinkPeer** (2026-09-27) — `init()` loads the pairing key + A's MAC (NVS `linkpeer`) and the Wi-Fi credentials A handed over (NVS `wifi`, same keys as A's). `onPairFrame()` is called by `UARTReceiver::processFrame()` for `PAIR` frames **from the UART source only**; `onRadioFrame()` by `EspNowReceiver` for every non-DATA/CONFIG frame. Both just fill a one-slot mailbox; `tick()` (loop task) decrypts, checks the sender MAC against the paired A, writes NVS, and sends a `STATUS` frame to A every 5 s or on any phase change (`EspNowReceiver::sendTo()`, A's MAC from its data frames). `setOtaStatus()` / `setOtaCommandHandler()` are the updater's hooks. Nonce replay window of 4 for OTA commands. Console: `link status | unpair`, `wifi status | forget`. The password is never printed. + +**Ota** (2026-09-27) — port of Controller A's `ota_update.cpp`: `ota status | check | install [force] | rollback` and A's `OTA_CMD` land in `startJob()`; the job runs in `tick()` (loop task, blocks the gauges - parked anyway). Gate: link data says rpm 0 and lever P/N/unknown, or the link is silent (A off); credentials present. Joins Wi-Fi only for the job and `WiFi.disconnect(false)` afterwards so the ESP-NOW receiver hops back to A. Manifest signature (ECDSA P-256 over `patrol-b|version|sha256`) checked before download, streamed sha256 checked after, `esp_ota_end()` image check, slot switch, reboot; `verifyRollbackLater()` overridden so the new image stays pending until `tick()` confirms it after `OTA_CONFIRM_MS` (30 s). Progress: `GaugeScreen::setNotice("Updating vX N%")` and a STATUS pumped to A at most once a second from inside the download loop. Never put secrets in source - the repo and its releases are public. + +**Console** — `Console::addHandler()` chain, `tick()` from loop; `help` asks every handler to print its lines. + ### UART packet (shared with Controller A) -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. +Protocol **v2**: `0xAA | 0x02 | type | length | payload | XOR | 0x55`. DATA (21-byte `automotive_data_t`: lever, target/engaged gear nibbles, rpm, temps, battery, alerts, valid flags) every 200 ms; CONFIG (27-byte `link_config_t`: gauge calibration + alert thresholds) on change and every 5 s. Same frames on UART1 and ESP-NOW. Spec: sibling repo `docs/UART_PROTOCOL.md`. `include/protocol/automotive_data.h` (and `link_secure.h`) must stay byte-identical to A's; B rejects other versions and counts them. + +Since 2026-09-27 the link is two-way for maintenance (`PACKET_VERSION` unchanged, `PACKET_MAX_PAYLOAD` 160): `STATUS` 0x03 B → A (ESP-NOW unicast), `PAIR` 0x04 A → B (**wire only**, the shared key), `SECURE` 0x05 A → B (AES-256-GCM envelope carrying `OTA_CMD` or `WIFI_CREDS`). See `wiki/pages/controller-b-ota.md`. 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. +### Firmware updates (OTA) + +B updates itself from this repo's Gitea releases; A triggers it from Settings → Updates (Controller B card) or B's console does (`ota check`, `ota install`). CI: `.gitea/workflows/firmware.yml` - push to `master` → unsigned pre-release `main-latest`; tag `v*` → signed release (`manifest.txt`, target `patrol-b`), needs the repo secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY` (same key as A's). Release with one push: `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin master`. Version strings ≤ 15 chars. First pairing (`link pair` on A, wire connected) and the procedure: `wiki/pages/controller-b-ota.md`. + ## Hardware-Specific Details ### GPIO assignments (verified against the Waveshare demo and the pinout photo) @@ -113,6 +130,8 @@ Pins are set in `src/modules/display_init.cpp` and `platformio.ini` (`-DUART_RX_ ## Troubleshooting +- **Building**: start `pio` from PowerShell, not Git Bash - `idf_tools.py` refuses MSYS ("MSys/Mingw is not supported"). The two projects share one PlatformIO penv and one `framework-arduinoespressif32` package dir: the first `pio run` after building the other project reinstalls the core and can fail once with `TypeError: expected str, bytes or os.PathLike object, not NoneType` - run it again. After any build here, run `../ESP32-S3-Touch-LCD-5B/tools/fix_penv_deps.ps1` before building A. + - **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**: LVGL's 128 KB pool is already in PSRAM (`LV_MEM_POOL_ALLOC` in `lv_conf.h`); raise `LV_MEM_SIZE` there. The two 240×40 draw buffers must stay in internal RAM (SPI DMA). diff --git a/README.md b/README.md index c402f12..64e4813 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ ## Project Status +**2026-09-27**: over-the-air updates implemented (B pulls its own signed release; Controller A triggers and shows progress; pairing over the wire once on the bench) - see `wiki/pages/controller-b-ota.md`. Serial console on the CH343 port: `help`, `link status`, `ota status | check | install`. + **Current Phase**: Phase 1 - Hardware Setup & Basic Display ✅ ## Overview diff --git a/include/config/ota_config.h b/include/config/ota_config.h new file mode 100644 index 0000000..61102f9 --- /dev/null +++ b/include/config/ota_config.h @@ -0,0 +1,105 @@ +/** + * ota_config.h - where Controller B looks for firmware updates, and what it trusts. + * + * Same scheme as Controller A (ESP32-S3-Touch-LCD-5B/include/config/ota_config.h): + * releases of THIS repo on Gitea, manifest signed with the shared project key, + * target string "patrol-b" so an A image is never accepted here. + * See wiki/pages/controller-b-ota.md. + * + * Nothing in here is secret. The signing private key lives only in the Gitea + * secret BMW_NISSAN_FIRMWARE_SIGNING_KEY. + */ + +#ifndef OTA_CONFIG_H +#define OTA_CONFIG_H + +// Version string baked in by CI (-DFW_VERSION="v1.2.3"); local builds say "dev". +#ifndef FW_VERSION +#define FW_VERSION "dev" +#endif + +#define OTA_TARGET "patrol-b" + +#define OTA_SERVER "https://git.infra.msai.al" +#define OTA_REPO "art/ESP32-S3-LCD-1.3" +#define OTA_LATEST_API_URL OTA_SERVER "/api/v1/repos/" OTA_REPO "/releases/latest" +#define OTA_DOWNLOAD_BASE OTA_SERVER "/" OTA_REPO "/releases/download/" + +// A fresh image must run this long before it is confirmed; a reset before that +// makes the bootloader fall back to the previous slot. +#define OTA_CONFIRM_MS 30000 + +// TLS trust: Let's Encrypt roots (ISRG Root X1 + ISRG Root YR), copied from A. +static const char OTA_CA_PEM[] = + // ISRG Root X1 + "-----BEGIN CERTIFICATE-----\n" + "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" + "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" + "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" + "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" + "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" + "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" + "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" + "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" + "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" + "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" + "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" + "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" + "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" + "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" + "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" + "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" + "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" + "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" + "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" + "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" + "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" + "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" + "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" + "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" + "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" + "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" + "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" + "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" + "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" + "-----END CERTIFICATE-----\n" + // ISRG Root YR + "-----BEGIN CERTIFICATE-----\n" + "MIIFKTCCAxGgAwIBAgIRAOxGNJNgz0sP+KmC2Tqpyj0wDQYJKoZIhvcNAQELBQAw\n" + "LjELMAkGA1UEBhMCVVMxDTALBgNVBAoTBElTUkcxEDAOBgNVBAMTB1Jvb3QgWVIw\n" + "HhcNMjUwOTAzMDAwMDAwWhcNNDUwOTAyMjM1OTU5WjAuMQswCQYDVQQGEwJVUzEN\n" + "MAsGA1UEChMESVNSRzEQMA4GA1UEAxMHUm9vdCBZUjCCAiIwDQYJKoZIhvcNAQEB\n" + "BQADggIPADCCAgoCggIBANvGJnN78CTJdWL3+eGfsLN5TrNBJs+VH9hRXqRbwxu9\n" + "sGNiB0BD1fcOxbSUQCJIM1xE13Db+5Cw1w0s0EBYsvuIP/6joF0w8cuImbgR1OGg\n" + "YbSQ4OpzI+DG8SGuTlcE873OCS+kh3srlo6vl43M5OJg4Aeo1sfHp6kTJDoIiFBN\n" + "JAY+OKfX/FUvYKuhjT+no49lmqmupSBI5PkBQiqrEGtWU5uxU/cQWHGu8jSjFBzn\n" + "ZqvbNPLMXMLFxCb3WTfrJBXXjqvWG+v4bjzxjjeAtOlU7qarRDvNOyAuQYLln904\n" + "M+faKx8hnLCpJ15ZqaEgcNlY+9MMWcC5yvL2A2j3l9+2buggZX+dOE91zYmIdawT\n" + "vSZuVvlbRrAlLxIB6pwMBjneXCjYQ8+3BCCjssbSNpZU3hTcBDdhfAlEDlYr6pEa\n" + "tnMdmDT5BqnKC92bd0EhM1fbLHioLccLCuievT8ZkPhZrq7Mii7gNXAcUEAR8+lz\n" + "Yal+9zTg7C5DALyVOeG/CqfRAMn1KSHCR0NSA6P8tn/mGRlnCct5rtVCLnVySVpU\n" + "6H1qGg3DgTOuskf8eahTMiYbI5ezPJmO5ertalskQ1utp74+eDy92PI4ftHKTbq9\n" + "IWhH4YZKh3WnJEIt+oQvlYZbY8tpEroKrFB6PFGzrJIDRyts4HqvuH52RFj2zv/B\n" + "AgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud\n" + "DgQWBBTe51tg0CJtQCh9Pw0B/qS1UrRRlDANBgkqhkiG9w0BAQsFAAOCAgEAWHnf\n" + "713Bdkq7t5yN2dNIgQakUb94X9WuyhMEHHkgx4oDpSUlnG0w4g94MoqaEUE31ZjR\n" + "LU7L5LD1g9ujFHTQu8AD215AHMVQFbm6j8hQxdXHAzDajFNQnOlDJrLjzIx176oy\n" + "AjvUtejZx2NNmdb5fd0WGVGsCdoAJ3N8ozo7ajE8t6vfxStZb4BQ9WYJGHUDrv2N\n" + "i5tJF6CNiPnlzs3BUfECRbE4JSk+jvy8+VoGiFE8qsH/j78x2fjgQhAQFV7P7Zxy\n" + "dBTZ1wEkNpZNW2qnaK1SKBLa+xf6E06YRIq5uaI+HWH8SY1y5VbRgzq40EKg3yxP\n" + "06fz+uYAUIFJoLNfhwRCc3Q6pQVuMX3yAjHAes4gk4moGcLQ5p7HAh39yeylZc1J\n" + "41sx/jKwLIkPE6Rr1Nf4pxdsxf9SA4yOEiAkDgq04DVxn8hgYFdUtBCuiuVC2heA\n" + "EiqVEa+8QZjuw8Gj0EbHXcRd1nInvGqRS1o9Is7YBdQN57X1AYveGBNNqjICSb7c\n" + "awuw1EawTDrs13VUlJVEsbQ0/O/1aaV73mCdOQ8azqL2KTv1Ewu1xbquE2S+kdQU\n" + "To9TUwat3wUA6cwXh1EfpS/3fJ0aGah5hdpRyoCLDlsSn8tkrjMfFFX0viC+GxHc\n" + "sI1ANRYvqSFC2X1VRZfDg+wD6E21BccmifG4yWc=\n" + "-----END CERTIFICATE-----\n"; + +// Firmware signing public key (ECDSA P-256), same key as Controller A. +static const char OTA_SIGNING_PUBKEY_PEM[] = + "-----BEGIN PUBLIC KEY-----\n" + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF\n" + "Y9brIfDTgn8IOWBm8J4nmLUef7zU4ydPM5BKXqUrTshJEpLd74GJIIOtkg==\n" + "-----END PUBLIC KEY-----\n"; + +#endif // OTA_CONFIG_H diff --git a/include/modules/console.h b/include/modules/console.h new file mode 100644 index 0000000..a92edb0 --- /dev/null +++ b/include/modules/console.h @@ -0,0 +1,25 @@ +/** + * Serial console (Controller B) - line reader + command chain. + * + * Commands live in their modules (LinkPeer, Ota); this only splits lines and + * asks each handler in turn. `help` lists them. + */ + +#ifndef CONSOLE_H +#define CONSOLE_H + +#include + +namespace Console { + +typedef bool (*handler_t)(const char* line); + +/** Register up to 8 handlers; each returns true if it consumed the line. */ +void addHandler(handler_t h); + +/** Non-blocking: read whatever is pending on Serial, dispatch complete lines. */ +void tick(); + +} // namespace Console + +#endif // CONSOLE_H diff --git a/include/modules/espnow_receiver.h b/include/modules/espnow_receiver.h index 0473584..eb778f0 100644 --- a/include/modules/espnow_receiver.h +++ b/include/modules/espnow_receiver.h @@ -7,6 +7,10 @@ * 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. + * + * Frames other than DATA/CONFIG (the SECURE envelope from A) are routed to + * LinkPeer, and the sender MAC of A's frames is remembered so LinkPeer can + * unicast STATUS frames back (sendTo). */ #ifndef ESPNOW_RECEIVER_H @@ -31,6 +35,12 @@ bool isReady(); uint8_t currentChannel(); uint32_t framesReceived(); +/** A's MAC as seen on its last DATA/CONFIG frame. False until A was heard by radio. */ +bool peerMac(uint8_t out[6]); + +/** 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 EspNowReceiver #endif // ESPNOW_RECEIVER_H diff --git a/include/modules/link_peer.h b/include/modules/link_peer.h new file mode 100644 index 0000000..0733b35 --- /dev/null +++ b/include/modules/link_peer.h @@ -0,0 +1,61 @@ +/** + * Link Peer Module (Controller B) - the maintenance side of the link to A. + * + * The data path (DATA/CONFIG frames) is UARTReceiver's. This module owns + * everything else on the link, see wiki/pages/controller-b-ota.md: + * + * - STATUS frames B -> A every LINK_STATUS_PERIOD_MS (ESP-NOW unicast to A's + * MAC, learned from the frames A broadcasts): our version, OTA phase, uptime. + * - PAIR frames from A, accepted from the UART wire ONLY: the shared key that + * protects everything below. Kept in NVS, survives reflashes. + * - SECURE frames from A (ESP-NOW unicast, AES-256-GCM under the pairing key): + * WIFI_CREDS -> stored in NVS for the OTA module to join with + * OTA_CMD -> handed to the OTA module (check / install / rollback) + * + * Console (`link ...`, `wifi ...`) via Console::handle chain. + */ + +#ifndef LINK_PEER_H +#define LINK_PEER_H + +#include +#include "protocol/automotive_data.h" + +namespace LinkPeer { + +/** Load pairing key + Wi-Fi credentials from NVS. Call before the receivers start. */ +void init(); + +/** STATUS transmit + housekeeping. Call from loop(). */ +void tick(); + +/** ESP-NOW frames that are not DATA/CONFIG (EspNowReceiver hands them here). */ +void onRadioFrame(const uint8_t* mac, const uint8_t* frame, size_t len); + +/** A PAIR payload that arrived on the UART wire (UARTReceiver hands it here). */ +void onPairFrame(const link_pair_t* p); + +bool isPaired(); +uint16_t keyFingerprint(); // 0 when unpaired + +/** Stored Wi-Fi credentials (from A). False if none. Never printed. */ +bool getWifiCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n); +bool hasWifiCredentials(); +void forgetWifi(); +void unpair(); + +// ---- OTA module integration ------------------------------------------------ + +typedef void (*ota_cmd_handler_t)(uint8_t cmd, uint8_t flags); +void setOtaCommandHandler(ota_cmd_handler_t handler); + +/** What the STATUS frame reports about the updater. */ +void setOtaStatus(uint8_t phase, uint8_t progress, const char* latest, const char* message, + bool wifi_joined, bool pending_verify); + +/** Console: `link status | unpair`, `wifi status | forget`. */ +bool handleCommand(const char* line); + +} // namespace LinkPeer + +#endif // LINK_PEER_H diff --git a/include/modules/ota_update.h b/include/modules/ota_update.h new file mode 100644 index 0000000..efb2802 --- /dev/null +++ b/include/modules/ota_update.h @@ -0,0 +1,50 @@ +/** + * ota_update.h - Controller B pulls its own firmware from this repo's Gitea + * releases. Port of Controller A's module (ESP32-S3-Touch-LCD-5B/src/modules/ + * ota_update.cpp), see wiki/pages/controller-b-ota.md. + * + * Triggered by A (OTA_CMD inside a SECURE frame, behind A's parking gate and + * its Updates screen) or by this console: + * + * ota status running version, slot, rollback state + * ota check join Wi-Fi, ask Gitea for the latest release, leave + * ota install [force] join, download, verify, flash idle slot, reboot + * ota rollback boot the previous slot + * + * Safety, same as A: + * - refused unless parked: link alive with engine rpm 0 and no shaft speed, + * or link silent (ignition off / bench). A has already applied its gate. + * - image must match the signed manifest (sha256 + ECDSA P-256 over + * "patrol-b|version|sha256"); the idle slot is never activated otherwise. + * - a new image must run OTA_CONFIRM_MS before it is marked valid, else the + * bootloader falls back to the old slot. + * + * Wi-Fi: B lives in bare STA mode for ESP-NOW. For a job it joins the network + * whose credentials A handed over (LinkPeer), then disconnects again so the + * receiver can hop back to A's channel. + */ + +#ifndef OTA_UPDATE_H +#define OTA_UPDATE_H + +#include + +namespace Ota { + +/** Log version/slot; flag an unconfirmed new image. Call early in setup(). */ +void init(); + +/** Runs queued jobs, confirms a fresh image after healthy uptime. Call from loop(). */ +void tick(); + +/** LinkPeer hands A's OTA commands here (registered by init()). */ +void onLinkCommand(uint8_t cmd, uint8_t flags); + +/** Console entry point (`ota ...`). */ +bool handleCommand(const char* line); + +const char* version(); + +} // namespace Ota + +#endif // OTA_UPDATE_H diff --git a/include/protocol/automotive_data.h b/include/protocol/automotive_data.h index e81604e..6136624 100644 --- a/include/protocol/automotive_data.h +++ b/include/protocol/automotive_data.h @@ -16,6 +16,13 @@ * - 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 + * + * v2 additions (2026-09-27, PACKET_VERSION unchanged - DATA/CONFIG are the same + * bytes, an older B counts the new types as FRAME_ERR_TYPE and carries on): + * - STATUS B -> 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 6c4d535..53ebf02 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -14,6 +14,10 @@ #include "modules/gauge_outputs.h" #include "modules/debug_monitor.h" #include "modules/gauge_screen.h" +#include "modules/link_peer.h" +#include "modules/console.h" +#include "modules/ota_update.h" +#include "config/ota_config.h" // FreeRTOS task handles TaskHandle_t lvglTaskHandle = NULL; @@ -47,7 +51,7 @@ void setup() { Serial.println("[BOOT] Serial communication ready!"); Serial.println("\n\n================================="); Serial.println("ESP32-S3-LCD-1.3 - Controller B"); - Serial.printf("Link protocol v%u | UART + ESP-NOW | gauge outputs\n", PACKET_VERSION); + Serial.printf("Firmware %s | Link protocol v%u | UART + ESP-NOW | gauge outputs\n", FW_VERSION, PACKET_VERSION); Serial.println("=================================\n"); Serial.printf("CPU Frequency: %d MHz\n", getCpuFrequencyMhz()); @@ -74,6 +78,12 @@ void setup() { Serial.println("\n[Gauges] Initializing Patrol gauge outputs..."); GaugeOutputs::init(); + // Pairing key + Wi-Fi credentials from NVS, before any frame can arrive + LinkPeer::init(); + Ota::init(); // version + slot; hooks A's OTA commands + Console::addHandler(LinkPeer::handleCommand); + Console::addHandler(Ota::handleCommand); + Serial.println("\n[UART] Initializing link receiver..."); if (!UARTReceiver::init()) { Serial.println("[ERROR] Link receiver initialization failed!"); @@ -100,6 +110,10 @@ void loop() { // Wireless leg housekeeping (channel hopping while silent) EspNowReceiver::tick(); + // STATUS to A, PAIR/SECURE frames from A, serial console + LinkPeer::tick(); + Ota::tick(); // runs a queued check/install (blocks the loop while it does) + Console::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. diff --git a/src/modules/console.cpp b/src/modules/console.cpp new file mode 100644 index 0000000..0217b60 --- /dev/null +++ b/src/modules/console.cpp @@ -0,0 +1,46 @@ +/** + * Serial console implementation (Controller B) + */ + +#include "modules/console.h" + +namespace Console { + +static handler_t g_handlers[8]; +static int g_count = 0; +static char g_line[96]; +static size_t g_len = 0; + +void addHandler(handler_t h) { + if (g_count < 8) g_handlers[g_count++] = h; +} + +static void dispatch(const char* line) { + if (line[0] == 0) return; + if (strcmp(line, "help") == 0) { + Serial.println("[console] commands:"); + for (int i = 0; i < g_count; i++) g_handlers[i](line); // each prints its own lines + return; + } + for (int i = 0; i < g_count; i++) { + if (g_handlers[i](line)) return; + } + Serial.printf("[console] unknown command '%s' (try 'help')\n", line); +} + +void tick() { + while (Serial.available()) { + char c = (char)Serial.read(); + if (c == '\r' || c == '\n') { + g_line[g_len] = 0; + // trim trailing spaces + while (g_len && g_line[g_len - 1] == ' ') g_line[--g_len] = 0; + dispatch(g_line); + g_len = 0; + } else if (g_len < sizeof(g_line) - 1 && c >= ' ') { + g_line[g_len++] = c; + } + } +} + +} // namespace Console diff --git a/src/modules/espnow_receiver.cpp b/src/modules/espnow_receiver.cpp index 5801a0c..7a423cc 100644 --- a/src/modules/espnow_receiver.cpp +++ b/src/modules/espnow_receiver.cpp @@ -4,6 +4,7 @@ #include "modules/espnow_receiver.h" #include "modules/uart_receiver.h" +#include "modules/link_peer.h" #include "protocol/automotive_data.h" #include #include @@ -22,12 +23,24 @@ static uint8_t g_channel = ESPNOW_CHANNEL; static uint32_t g_last_hop_ms = 0; static bool g_locked = false; +// A's STA MAC as seen on the last DATA/CONFIG frame: where STATUS frames go. +static uint8_t g_peer_mac[6] = {0}; +static volatile bool g_have_peer = 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); + // Byte 2 is the type; the data path only wants DATA/CONFIG, everything + // else (SECURE from A) is the link peer's. Both validate the frame themselves. + uint8_t type = len > 2 ? data[2] : 0; + if (type == PACKET_TYPE_DATA || type == PACKET_TYPE_CONFIG) { + g_frames++; + g_last_frame_ms = millis(); + memcpy(g_peer_mac, mac, 6); + g_have_peer = true; + UARTReceiver::processFrame(data, (size_t)len, LINK_SOURCE_ESPNOW); + } else { + LinkPeer::onRadioFrame(mac, data, (size_t)len); + } } static void setChannel(uint8_t ch) { @@ -87,4 +100,26 @@ bool isReady() { return g_ready; } uint8_t currentChannel() { return g_channel; } uint32_t framesReceived() { return g_frames; } +bool peerMac(uint8_t out[6]) { + if (!g_have_peer) return false; + memcpy(out, g_peer_mac, 6); + return true; +} + +bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len) { + if (!g_ready || len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false; + if (!esp_now_is_peer_exist(mac)) { + esp_now_peer_info_t peer = {}; + memcpy(peer.peer_addr, mac, 6); + peer.channel = 0; // whatever channel we are locked on + peer.encrypt = false; // SECURE frames carry their own encryption + peer.ifidx = WIFI_IF_STA; + if (esp_now_add_peer(&peer) != ESP_OK) { + Serial.println("[EspNow] esp_now_add_peer(A) failed"); + return false; + } + } + return esp_now_send(mac, frame, len) == ESP_OK; +} + } // namespace EspNowReceiver diff --git a/src/modules/gauge_screen.cpp b/src/modules/gauge_screen.cpp index a3308cf..cf7f825 100644 --- a/src/modules/gauge_screen.cpp +++ b/src/modules/gauge_screen.cpp @@ -25,6 +25,7 @@ struct Cell { }; static lv_obj_t* g_screen = NULL; +static lv_obj_t* g_notice = NULL; // on lv_layer_top(): update progress line static Cell g_coolant = {0}; static Cell g_gearbox = {0}; static Cell g_battery = {0}; @@ -196,11 +197,36 @@ void init() { lv_obj_t* bottom = makeContainer(g_screen, 230, 85, LV_FLEX_FLOW_ROW, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END); makeCell(g_battery, bottom, &ui_img_batteryvoltage_png, &ui_img_batteryvoltagered_png, LV_FLEX_ALIGN_CENTER, true); + // Notice line for the updater: a dark pill low on the round panel, hidden until used. + g_notice = lv_label_create(lv_layer_top()); + lv_obj_set_style_text_font(g_notice, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_color(g_notice, lv_color_white(), 0); + lv_obj_set_style_bg_color(g_notice, lv_color_hex(0x1B2128), 0); + lv_obj_set_style_bg_opa(g_notice, LV_OPA_COVER, 0); + lv_obj_set_style_pad_hor(g_notice, 10, 0); + lv_obj_set_style_pad_ver(g_notice, 4, 0); + lv_obj_set_style_radius(g_notice, 8, 0); + lv_obj_align(g_notice, LV_ALIGN_CENTER, 0, 62); + lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN); + lv_scr_load(g_screen); DisplayInit::unlock(); Serial.println("[GaugeScreen] built (coolant, gearbox oil, gear, battery)"); } +void setNotice(const char* text) { + if (g_notice == NULL) return; + DisplayInit::lock(-1); + if (text == NULL || text[0] == 0) { + lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN); + } else { + setText(g_notice, text); + lv_obj_clear_flag(g_notice, LV_OBJ_FLAG_HIDDEN); + lv_obj_align(g_notice, LV_ALIGN_CENTER, 0, 62); + } + DisplayInit::unlock(); +} + void update(const automotive_data_t& d, bool link_ok) { if (g_screen == NULL) return; if (!DisplayInit::lock(50)) return; // never stall the loop on a busy renderer diff --git a/src/modules/gauge_screen.h b/src/modules/gauge_screen.h index bc6feb6..87f925e 100644 --- a/src/modules/gauge_screen.h +++ b/src/modules/gauge_screen.h @@ -35,4 +35,10 @@ void init(); */ void update(const automotive_data_t& d, bool link_ok); +/** + * One line of text over the gauges (firmware update progress). NULL hides it. + * Takes the LVGL lock itself; safe from the loop task. + */ +void setNotice(const char* text); + } // namespace GaugeScreen diff --git a/src/modules/link_peer.cpp b/src/modules/link_peer.cpp new file mode 100644 index 0000000..1de95fe --- /dev/null +++ b/src/modules/link_peer.cpp @@ -0,0 +1,359 @@ +/** + * Link Peer Module Implementation (Controller B) + * + * Threading: onRadioFrame() runs in the Wi-Fi task, onPairFrame() in the UART + * task. Both only drop a copy into a one-slot mailbox; tick() (loop task) does + * the decrypting, the NVS writes and the STATUS transmit. + */ + +#include "modules/link_peer.h" +#include "modules/espnow_receiver.h" +#include "protocol/link_secure.h" +#include "config/ota_config.h" +#include +#include +#include + +namespace LinkPeer { + +static const char* NVS_LINK = "linkpeer"; // key (32 B), amac (6 B) +static const char* NVS_WIFI = "wifi"; // ssid, pass - same layout as Controller A's + +// ---- state (loop task only, except where noted) ---------------------------- +static bool g_paired = false; +static uint8_t g_key[LINK_KEY_LEN]; +static uint8_t g_a_mac[6]; +static uint16_t g_key_fp = 0; +static char g_ssid[33] = ""; +static char g_pass[65] = ""; + +static uint8_t g_ota_phase = LINK_OTA_IDLE, g_ota_progress = 0; +static char g_latest[16] = "", g_message[32] = ""; +static bool g_wifi_joined = false, g_pending_verify = false; +static ota_cmd_handler_t g_ota_handler = NULL; + +static uint32_t g_recent_nonce[4] = {0}; +static uint8_t g_nonce_idx = 0; + +static uint32_t g_status_sent = 0, g_status_fail = 0; +static uint32_t g_secure_ok = 0, g_secure_bad = 0, g_secure_stranger = 0, g_mailbox_drops = 0; +static uint32_t g_last_status_ms = 0; +static bool g_status_now = false; +static bool g_ota_cmd_seen_unhandled = false; + +// ---- mailboxes filled from other tasks -------------------------------------- +static SemaphoreHandle_t g_mbox_mutex = NULL; +static struct { + bool full; + uint8_t mac[6]; + uint8_t frame[PACKET_MAX_SIZE]; + size_t len; +} g_radio_mbox = {0}; +static struct { + bool full; + link_pair_t pair; +} g_pair_mbox = {0}; + +static bool mboxLock() { return xSemaphoreTake(g_mbox_mutex, pdMS_TO_TICKS(20)) == pdTRUE; } +static void mboxUnlock() { xSemaphoreGive(g_mbox_mutex); } + +// ---- NVS -------------------------------------------------------------------- +static void loadPairing() { + Preferences p; + p.begin(NVS_LINK, true); + bool ok = p.getBytesLength("key") == LINK_KEY_LEN && p.getBytesLength("amac") == 6; + if (ok) { + p.getBytes("key", g_key, LINK_KEY_LEN); + p.getBytes("amac", g_a_mac, 6); + } + p.end(); + g_paired = ok; + g_key_fp = ok ? link_key_fingerprint(g_key) : 0; +} + +static void storePairing() { + Preferences p; + p.begin(NVS_LINK, false); + p.putBytes("key", g_key, LINK_KEY_LEN); + p.putBytes("amac", g_a_mac, 6); + p.end(); +} + +static void loadWifi() { + Preferences p; + p.begin(NVS_WIFI, true); + String s = p.getString("ssid", ""), w = p.getString("pass", ""); + p.end(); + strlcpy(g_ssid, s.c_str(), sizeof(g_ssid)); + strlcpy(g_pass, w.c_str(), sizeof(g_pass)); +} + +static void storeWifi(const char* ssid, const char* pass) { + Preferences p; + p.begin(NVS_WIFI, false); + p.putString("ssid", ssid); + p.putString("pass", pass); + p.end(); + strlcpy(g_ssid, ssid, sizeof(g_ssid)); + strlcpy(g_pass, pass, sizeof(g_pass)); +} + +static void clearNamespace(const char* ns) { + Preferences p; + p.begin(ns, false); + p.clear(); + p.end(); +} + +// ---- public: state ---------------------------------------------------------- +void init() { + if (g_mbox_mutex == NULL) g_mbox_mutex = xSemaphoreCreateMutex(); + loadPairing(); + loadWifi(); + Serial.printf("[LinkPeer] %s | Wi-Fi credentials %s | reporting as %s\n", + g_paired ? "paired with A" : "NOT paired (run `link pair` on A over the wire)", + g_ssid[0] ? "stored" : "none", FW_VERSION); + if (g_paired) { + Serial.printf("[LinkPeer] key fingerprint %04X, A = %02X:%02X:%02X:%02X:%02X:%02X\n", g_key_fp, + g_a_mac[0], g_a_mac[1], g_a_mac[2], g_a_mac[3], g_a_mac[4], g_a_mac[5]); + } +} + +bool isPaired() { return g_paired; } +uint16_t keyFingerprint(){ return g_key_fp; } +bool hasWifiCredentials(){ return g_ssid[0] != 0; } + +bool getWifiCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n) { + if (!g_ssid[0]) return false; + strlcpy(ssid, g_ssid, ssid_n); + strlcpy(pass, g_pass, pass_n); + return true; +} + +void forgetWifi() { + clearNamespace(NVS_WIFI); + g_ssid[0] = 0; + memset(g_pass, 0, sizeof(g_pass)); + g_status_now = true; + Serial.println("[LinkPeer] Wi-Fi credentials forgotten"); +} + +void unpair() { + clearNamespace(NVS_LINK); + g_paired = false; + g_key_fp = 0; + memset(g_key, 0, sizeof(g_key)); + g_status_now = true; + Serial.println("[LinkPeer] Pairing removed - A must `link pair` again over the wire"); +} + +void setOtaCommandHandler(ota_cmd_handler_t handler) { g_ota_handler = handler; } + +void setOtaStatus(uint8_t phase, uint8_t progress, const char* latest, const char* message, + bool wifi_joined, bool pending_verify) { + bool changed = phase != g_ota_phase || wifi_joined != g_wifi_joined || + strcmp(latest ? latest : "", g_latest) != 0; + g_ota_phase = phase; + g_ota_progress = progress; + strlcpy(g_latest, latest ? latest : "", sizeof(g_latest)); + strlcpy(g_message, message ? message : "", sizeof(g_message)); + g_wifi_joined = wifi_joined; + g_pending_verify = pending_verify; + if (changed) g_status_now = true; // A sees phase changes without waiting for the period +} + +// ---- inbound (other tasks) -------------------------------------------------- +void onRadioFrame(const uint8_t* mac, const uint8_t* frame, size_t len) { + if (len == 0 || len > PACKET_MAX_SIZE || g_mbox_mutex == NULL) return; + if (!mboxLock()) { g_mailbox_drops++; return; } + if (g_radio_mbox.full) g_mailbox_drops++; // loop hasn't consumed the last one; newest wins + memcpy(g_radio_mbox.mac, mac, 6); + memcpy(g_radio_mbox.frame, frame, len); + g_radio_mbox.len = len; + g_radio_mbox.full = true; + mboxUnlock(); +} + +void onPairFrame(const link_pair_t* p) { + if (g_mbox_mutex == NULL) return; + if (!mboxLock()) { g_mailbox_drops++; return; } + g_pair_mbox.pair = *p; + g_pair_mbox.full = true; + mboxUnlock(); +} + +// ---- loop-side processing --------------------------------------------------- +static void applyPair(const link_pair_t& p) { + if (p.magic != LINK_PAIR_MAGIC) { + Serial.println("[LinkPeer] PAIR frame with bad magic ignored"); + return; + } + bool same = g_paired && memcmp(p.key, g_key, LINK_KEY_LEN) == 0 && memcmp(p.a_mac, g_a_mac, 6) == 0; + memcpy(g_key, p.key, LINK_KEY_LEN); + memcpy(g_a_mac, p.a_mac, 6); + g_paired = true; + g_key_fp = link_key_fingerprint(g_key); + if (!same) storePairing(); // A sends PAIR a few times for robustness; write NVS once + g_status_now = true; + Serial.printf("[LinkPeer] %s over the wire: key fingerprint %04X, A = %02X:%02X:%02X:%02X:%02X:%02X\n", + same ? "Pairing re-confirmed" : "PAIRED", g_key_fp, + g_a_mac[0], g_a_mac[1], g_a_mac[2], g_a_mac[3], g_a_mac[4], g_a_mac[5]); +} + +static bool nonceSeen(uint32_t n) { + for (int i = 0; i < 4; i++) if (g_recent_nonce[i] == n) return true; + g_recent_nonce[g_nonce_idx] = n; + g_nonce_idx = (uint8_t)((g_nonce_idx + 1) % 4); + return false; +} + +static void applySecure(const uint8_t* mac, 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) { g_secure_bad++; return; } + if (type != PACKET_TYPE_SECURE) return; // STATUS is ours to send, not to receive + if (!g_paired) { + g_secure_bad++; + Serial.println("[LinkPeer] SECURE frame but not paired - ignored"); + return; + } + if (memcmp(mac, g_a_mac, 6) != 0) { g_secure_stranger++; return; } + + uint8_t inner_type = 0, inner[LINK_SECURE_MAX_INNER]; + size_t inner_len = 0; + if (!link_secure_open(g_key, payload, plen, &inner_type, inner, &inner_len)) { + g_secure_bad++; + if (g_secure_bad <= 3 || g_secure_bad % 20 == 0) + Serial.printf("[LinkPeer] SECURE frame failed to authenticate (%lu so far) - keys differ? re-pair\n", + (unsigned long)g_secure_bad); + return; + } + g_secure_ok++; + + if (inner_type == LINK_INNER_WIFI_CREDS && inner_len == sizeof(link_wifi_creds_t)) { + link_wifi_creds_t c; + memcpy(&c, inner, sizeof(c)); + c.ssid[sizeof(c.ssid) - 1] = 0; + c.pass[sizeof(c.pass) - 1] = 0; + if (c.action == LINK_WIFI_SET && c.ssid[0]) { + bool same = strcmp(c.ssid, g_ssid) == 0 && strcmp(c.pass, g_pass) == 0; + if (!same) storeWifi(c.ssid, c.pass); + g_status_now = true; + Serial.printf("[LinkPeer] Wi-Fi credentials for '%s' %s\n", c.ssid, same ? "re-confirmed" : "stored"); + } else if (c.action == LINK_WIFI_FORGET) { + if (g_ssid[0]) forgetWifi(); + } + return; + } + if (inner_type == LINK_INNER_OTA_CMD && inner_len == sizeof(link_ota_cmd_t)) { + link_ota_cmd_t cmd; + memcpy(&cmd, inner, sizeof(cmd)); + if (nonceSeen(cmd.nonce)) { Serial.println("[LinkPeer] OTA command replayed - ignored"); return; } + const char* name = cmd.cmd == LINK_OTA_CMD_CHECK ? "check" : cmd.cmd == LINK_OTA_CMD_INSTALL ? "install" + : cmd.cmd == LINK_OTA_CMD_ROLLBACK ? "rollback" : "?"; + Serial.printf("[LinkPeer] OTA command from A: %s%s\n", name, (cmd.flags & LINK_OTA_FORCE) ? " (force)" : ""); + if (g_ota_handler) g_ota_handler(cmd.cmd, cmd.flags); + else g_ota_cmd_seen_unhandled = true; + return; + } + Serial.printf("[LinkPeer] SECURE inner type 0x%02X len %u not understood\n", inner_type, (unsigned)inner_len); +} + +static void sendStatus() { + uint8_t mac[6]; + bool have = EspNowReceiver::peerMac(mac); // A as heard on the radio + if (!have && g_paired) { memcpy(mac, g_a_mac, 6); have = true; } + if (!have) return; // never heard A on the radio, nothing to aim at + + link_status_t st = {}; + strlcpy(st.version, FW_VERSION, sizeof(st.version)); + st.ota_phase = g_ota_phase; + st.ota_progress = g_ota_progress; + st.flags = (g_paired ? LINK_STATUS_PAIRED : 0) | + (g_ssid[0] ? LINK_STATUS_HAVE_WIFI : 0) | + (g_wifi_joined ? LINK_STATUS_WIFI_JOINED : 0) | + (g_pending_verify ? LINK_STATUS_PENDING_VERIFY : 0); + st.key_fp = g_key_fp; + st.uptime_s = millis() / 1000; + st.free_heap = ESP.getFreeHeap(); + strlcpy(st.latest, g_latest, sizeof(st.latest)); + strlcpy(st.message, g_message, sizeof(st.message)); + + uint8_t frame[PACKET_MAX_SIZE]; + size_t n = frame_build(PACKET_TYPE_STATUS, &st, sizeof(st), frame); + if (n && EspNowReceiver::sendTo(mac, frame, n)) g_status_sent++; + else g_status_fail++; +} + +void tick() { + if (g_mbox_mutex == NULL) return; + + // Drain the mailboxes (copy out under the lock, work outside it) + bool have_pair = false, have_radio = false; + link_pair_t pair; + uint8_t mac[6], frame[PACKET_MAX_SIZE]; + size_t len = 0; + if (mboxLock()) { + if (g_pair_mbox.full) { pair = g_pair_mbox.pair; g_pair_mbox.full = false; have_pair = true; } + if (g_radio_mbox.full) { + memcpy(mac, g_radio_mbox.mac, 6); + len = g_radio_mbox.len; + memcpy(frame, g_radio_mbox.frame, len); + g_radio_mbox.full = false; + have_radio = true; + } + mboxUnlock(); + } + if (have_pair) applyPair(pair); + if (have_radio) applySecure(mac, frame, len); + + uint32_t now = millis(); + if (g_status_now || now - g_last_status_ms >= LINK_STATUS_PERIOD_MS) { + g_status_now = false; + g_last_status_ms = now; + sendStatus(); + } +} + +// ---- console ---------------------------------------------------------------- +static void help() { + Serial.println("link status pairing, credentials, STATUS/SECURE counters"); + Serial.println("link unpair forget the pairing key (re-pair from A over the wire)"); + Serial.println("wifi status stored network name (password never shown)"); + Serial.println("wifi forget drop the stored credentials"); +} + +bool handleCommand(const char* line) { + if (strcmp(line, "help") == 0) { help(); return false; } // let the others print theirs too + + if (strcmp(line, "link status") == 0) { + uint8_t mac[6]; + bool heard = EspNowReceiver::peerMac(mac); + Serial.printf("[link] %s (fingerprint %04X)\n", g_paired ? "paired" : "NOT paired", g_key_fp); + if (g_paired) + Serial.printf("[link] A (from pairing) %02X:%02X:%02X:%02X:%02X:%02X\n", + g_a_mac[0], g_a_mac[1], g_a_mac[2], g_a_mac[3], g_a_mac[4], g_a_mac[5]); + if (heard) + Serial.printf("[link] A (on the radio) %02X:%02X:%02X:%02X:%02X:%02X, channel %u\n", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], EspNowReceiver::currentChannel()); + else + Serial.println("[link] A not heard on the radio yet (STATUS cannot be sent)"); + Serial.printf("[link] STATUS sent %lu, failed %lu | SECURE ok %lu, bad %lu, from strangers %lu | mailbox drops %lu\n", + (unsigned long)g_status_sent, (unsigned long)g_status_fail, + (unsigned long)g_secure_ok, (unsigned long)g_secure_bad, + (unsigned long)g_secure_stranger, (unsigned long)g_mailbox_drops); + Serial.printf("[link] Wi-Fi credentials: %s | OTA phase %u%s\n", g_ssid[0] ? g_ssid : "none", + g_ota_phase, g_ota_handler ? "" : " (no updater module linked in)"); + return true; + } + if (strcmp(line, "link unpair") == 0) { unpair(); return true; } + if (strcmp(line, "wifi status") == 0) { + Serial.printf("[wifi] stored network: %s\n", g_ssid[0] ? g_ssid : "none (A sends it once paired)"); + return true; + } + if (strcmp(line, "wifi forget") == 0) { forgetWifi(); return true; } + if (strncmp(line, "link", 4) == 0 || strncmp(line, "wifi", 4) == 0) { help(); return true; } + return false; +} + +} // namespace LinkPeer diff --git a/src/modules/ota_update.cpp b/src/modules/ota_update.cpp new file mode 100644 index 0000000..ff2467b --- /dev/null +++ b/src/modules/ota_update.cpp @@ -0,0 +1,607 @@ +/** + * ota_update.cpp (Controller B) - see ota_update.h. + * + * Flow of an install: + * 1. gate: parked (link data), credentials present + * 2. join Wi-Fi with the credentials A handed over + * 3. GET /api/v1/repos//releases/latest -> tag_name + * 4. GET manifest.txt; verify ECDSA P-256 over "target|version|sha256" + * 5. GET firmware.bin -> idle OTA slot, hashing as it streams + * 6. esp_ota_end(), gate again, switch boot slot, reboot + * 7. next boot: PENDING_VERIFY until tick() confirms after OTA_CONFIRM_MS + * + * Jobs run inside the Arduino loop task, like on A: the gauges freeze (parked + * anyway) and STATUS frames to A are pumped from the download loop so A's + * Updates screen shows the progress. + * + * Differences from A's module: no CAN gate (link data instead), no Tunables, + * a one-line notice on the 240x240 screen instead of a full-screen panel, + * mbedtls 2.28 names (IDF 4.4), and mbedtls may use internal RAM (235 KB free). + */ + +#include "modules/ota_update.h" +#include "modules/link_peer.h" +#include "modules/uart_receiver.h" +#include "modules/gauge_screen.h" +#include "modules/gauge_outputs.h" +#include "modules/espnow_receiver.h" +#include "protocol/automotive_data.h" +#include "config/ota_config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Arduino marks a new image valid before setup() runs unless this says no. +extern "C" bool verifyRollbackLater() { return true; } + +#if MBEDTLS_VERSION_MAJOR >= 3 +#define SHA256_ONESHOT(in, n, out) mbedtls_sha256((in), (n), (out), 0) +#define SHA256_STARTS(c) mbedtls_sha256_starts((c), 0) +#define SHA256_UPDATE(c, d, n) mbedtls_sha256_update((c), (d), (n)) +#define SHA256_FINISH(c, o) mbedtls_sha256_finish((c), (o)) +#else +#define SHA256_ONESHOT(in, n, out) mbedtls_sha256_ret((in), (n), (out), 0) +#define SHA256_STARTS(c) mbedtls_sha256_starts_ret((c), 0) +#define SHA256_UPDATE(c, d, n) mbedtls_sha256_update_ret((c), (d), (n)) +#define SHA256_FINISH(c, o) mbedtls_sha256_finish_ret((c), (o)) +#endif + +namespace Ota { + +static const uint32_t LINK_SILENT_MS = 2000; // no DATA for this long = A off / bench +static const uint32_t WIFI_JOIN_MS = 25000; +static const uint32_t STALL_TIMEOUT_MS = 15000; +static const size_t CHUNK = 4096; + +typedef struct { + char tag[32]; + char target[16]; + char version[32]; + uint32_t size; + char sha256[65]; + uint8_t sig[80]; + size_t sig_len; +} manifest_t; + +enum job_t { JOB_NONE, JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE, JOB_ROLLBACK }; + +static job_t g_job = JOB_NONE; +static bool g_pending_verify = false; +static bool g_wifi_joined = false; +static uint8_t g_phase = LINK_OTA_IDLE, g_progress = 0; +static char g_latest[16] = "", g_message[32] = "", g_last_msg[96] = ""; +static uint32_t g_last_pump_ms = 0; + +// ---- logging / status reported to A ---------------------------------------- +static void report() { + LinkPeer::setOtaStatus(g_phase, g_progress, g_latest, g_message, g_wifi_joined, g_pending_verify); +} + +static void setPhase(uint8_t p, const char* latest = NULL, const char* msg = NULL) { + g_phase = p; + if (latest) strlcpy(g_latest, latest, sizeof(g_latest)); + strlcpy(g_message, msg ? msg : "", sizeof(g_message)); + if (p != LINK_OTA_INSTALLING) g_progress = 0; + report(); +} + +static void print(const char* fmt, ...) { + char buf[220]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + Serial.println(buf); + const char* m = strncmp(buf, "[ota] ", 6) == 0 ? buf + 6 : buf; + strlcpy(g_last_msg, m, sizeof(g_last_msg)); +} + +static void failPhase() { setPhase(LINK_OTA_FAILED, NULL, g_last_msg); } + +/** Keep A informed while the loop is blocked in a job (rate-limited to 1/s). */ +static void pump(bool force = false) { + if (!force && millis() - g_last_pump_ms < 1000) return; + g_last_pump_ms = millis(); + report(); + LinkPeer::tick(); +} + +static const char* stateName(esp_ota_img_states_t s) { + switch (s) { + case ESP_OTA_IMG_NEW: return "new"; + case ESP_OTA_IMG_PENDING_VERIFY: return "pending-verify"; + case ESP_OTA_IMG_VALID: return "valid"; + case ESP_OTA_IMG_INVALID: return "invalid"; + case ESP_OTA_IMG_ABORTED: return "aborted"; + default: return "undefined"; + } +} + +// ---- gates ----------------------------------------------------------------- +/** Parked according to the link data; a silent link (A off) counts as parked. */ +static bool parked(char* why, size_t n) { + if (!UARTReceiver::isConnected(LINK_SILENT_MS)) return true; + automotive_data_t d = UARTReceiver::getLatestData(); + if ((d.valid_flags & VALID_FLAG_RPM) && d.engine_rpm > 0) { + snprintf(why, n, "engine running (%u rpm)", d.engine_rpm); + return false; + } + if (d.valid_flags & VALID_FLAG_GEAR_POS) { + if (d.gear_lever != LEVER_PARK && d.gear_lever != LEVER_NEUTRAL && d.gear_lever != LEVER_UNKNOWN) { + snprintf(why, n, "lever in a drive gear"); + return false; + } + } + return true; +} + +static bool gate(bool need_parked, char* why_out = NULL, size_t why_n = 0) { + char why[96]; + bool ok = true; + if (need_parked && !parked(why, sizeof(why))) ok = false; + else if (!LinkPeer::hasWifiCredentials()) { snprintf(why, sizeof(why), "no Wi-Fi credentials from A yet"); ok = false; } + if (!ok) { + print("[ota] refused: %s", why); + if (why_out) snprintf(why_out, why_n, "%s", why); + } + return ok; +} + +// ---- Wi-Fi for the duration of a job --------------------------------------- +static bool joinWifi() { + char ssid[33], pass[65]; + if (!LinkPeer::getWifiCredentials(ssid, sizeof(ssid), pass, sizeof(pass))) { + print("[ota] no Wi-Fi credentials"); + return false; + } + print("[ota] joining '%s'...", ssid); + WiFi.mode(WIFI_STA); + WiFi.setSleep(false); + WiFi.begin(ssid, pass); + memset(pass, 0, sizeof(pass)); + uint32_t t0 = millis(); + while (WiFi.status() != WL_CONNECTED && millis() - t0 < WIFI_JOIN_MS) { + delay(100); + pump(); + } + if (WiFi.status() != WL_CONNECTED) { + print("[ota] could not join '%s' (status %d)", ssid, (int)WiFi.status()); + WiFi.disconnect(false); + return false; + } + g_wifi_joined = true; + print("[ota] joined, IP %s, channel %d", WiFi.localIP().toString().c_str(), WiFi.channel()); + pump(true); + return true; +} + +static void leaveWifi() { + if (!g_wifi_joined) return; + WiFi.disconnect(false); // back to a bare STA; the ESP-NOW receiver re-locks on A's channel + g_wifi_joined = false; + print("[ota] left Wi-Fi; ESP-NOW receiver hops back to A"); + pump(true); +} + +// ---- helpers (as on A) ----------------------------------------------------- +static void toHex(const uint8_t* in, size_t n, char* out) { + static const char* d = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { out[2 * i] = d[in[i] >> 4]; out[2 * i + 1] = d[in[i] & 0x0F]; } + out[2 * n] = 0; +} + +static int hexNibble(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static bool fromHex(const char* s, uint8_t* out, size_t cap, size_t* len) { + size_t n = strlen(s); + if (n == 0 || (n % 2) || n / 2 > cap) return false; + for (size_t i = 0; i < n; i += 2) { + int hi = hexNibble(s[i]), lo = hexNibble(s[i + 1]); + if (hi < 0 || lo < 0) return false; + out[i / 2] = (uint8_t)((hi << 4) | lo); + } + *len = n / 2; + return true; +} + +static bool safeToken(const char* s) { + if (!*s) return false; + for (; *s; s++) if (!isalnum((unsigned char)*s) && *s != '.' && *s != '_' && *s != '-') return false; + return true; +} + +static bool httpsGetText(const char* url, String& body, int& code) { + WiFiClientSecure client; + client.setCACert(OTA_CA_PEM); + HTTPClient http; + http.setConnectTimeout(10000); + http.setTimeout(15000); + if (!http.begin(client, url)) { code = -1; return false; } + http.setUserAgent("patrol-b-ota/" FW_VERSION); + code = http.GET(); + bool ok = (code == HTTP_CODE_OK); + if (ok) body = http.getString(); + http.end(); + return ok; +} + +static bool jsonString(const String& s, const char* key, char* out, size_t n) { + String k = String("\"") + key + "\""; + int i = s.indexOf(k); + if (i < 0) return false; + i = s.indexOf(':', i + k.length()); + if (i < 0) return false; + i = s.indexOf('"', i); + if (i < 0) return false; + int j = s.indexOf('"', i + 1); + if (j < 0 || (size_t)(j - i - 1) >= n) return false; + s.substring(i + 1, j).toCharArray(out, n); + return true; +} + +static bool fetchManifest(manifest_t& m) { + memset(&m, 0, sizeof(m)); + String body; + int code; + if (!httpsGetText(OTA_LATEST_API_URL, body, code)) { + if (code == 404) print("[ota] no release published yet (push a v* tag)"); + else print("[ota] release lookup failed (HTTP %d)", code); + return false; + } + if (!jsonString(body, "tag_name", m.tag, sizeof(m.tag)) || !safeToken(m.tag)) { + print("[ota] could not read tag_name from the release reply"); + return false; + } + pump(); + String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/manifest.txt"; + if (!httpsGetText(url.c_str(), body, code)) { + print("[ota] release %s has no manifest.txt (HTTP %d)", m.tag, code); + return false; + } + char sig_hex[2 * sizeof(m.sig) + 1] = {0}; + int start = 0; + while (start < (int)body.length()) { + int nl = body.indexOf('\n', start); + if (nl < 0) nl = body.length(); + String line = body.substring(start, nl); + line.trim(); + start = nl + 1; + int eq = line.indexOf('='); + if (eq <= 0) continue; + String k = line.substring(0, eq), v = line.substring(eq + 1); + if (k == "target") v.toCharArray(m.target, sizeof(m.target)); + else if (k == "version") v.toCharArray(m.version, sizeof(m.version)); + else if (k == "size") m.size = (uint32_t)v.toInt(); + else if (k == "sha256") v.toCharArray(m.sha256, sizeof(m.sha256)); + else if (k == "sig" && v.length() < sizeof(sig_hex)) v.toCharArray(sig_hex, sizeof(sig_hex)); + } + if (strcmp(m.target, OTA_TARGET) != 0) { + print("[ota] manifest is for '%s', not '%s' - refusing", m.target, OTA_TARGET); + return false; + } + if (strcmp(m.version, m.tag) != 0 || m.size == 0 || strlen(m.sha256) != 64 || + !fromHex(sig_hex, m.sig, sizeof(m.sig), &m.sig_len)) { + print("[ota] manifest for %s is malformed", m.tag); + return false; + } + for (char* c = m.sha256; *c; c++) *c = tolower(*c); + return true; +} + +static bool verifySignature(const manifest_t& m) { + char stmt[160]; + int n = snprintf(stmt, sizeof(stmt), "%s|%s|%s", m.target, m.version, m.sha256); + uint8_t h[32]; + SHA256_ONESHOT((const unsigned char*)stmt, n, h); + mbedtls_pk_context pk; + mbedtls_pk_init(&pk); + int rc = mbedtls_pk_parse_public_key(&pk, (const unsigned char*)OTA_SIGNING_PUBKEY_PEM, sizeof(OTA_SIGNING_PUBKEY_PEM)); + if (rc == 0) rc = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, h, sizeof(h), m.sig, m.sig_len); + mbedtls_pk_free(&pk); + if (rc != 0) print("[ota] SIGNATURE INVALID for %s (mbedtls -0x%04X) - refusing", m.tag, -rc); + return rc == 0; +} + +// ---- install --------------------------------------------------------------- +static void notice(const char* fmt, ...) { + char buf[64]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + GaugeScreen::setNotice(buf); +} + +static bool writeImage(const manifest_t& m, const esp_partition_t* part) { + String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/firmware.bin"; + WiFiClientSecure client; + client.setCACert(OTA_CA_PEM); + HTTPClient http; + http.setConnectTimeout(10000); + http.setTimeout(15000); + if (!http.begin(client, url)) { print("[ota] bad download URL"); return false; } + http.setUserAgent("patrol-b-ota/" FW_VERSION); + int code = http.GET(); + if (code != HTTP_CODE_OK) { print("[ota] download failed (HTTP %d)", code); http.end(); return false; } + if (http.getSize() != (int)m.size) { + print("[ota] server size %d != manifest size %lu", http.getSize(), (unsigned long)m.size); + http.end(); + return false; + } + + esp_ota_handle_t h = 0; + esp_err_t err = esp_ota_begin(part, OTA_WITH_SEQUENTIAL_WRITES, &h); + if (err != ESP_OK) { print("[ota] esp_ota_begin: %s", esp_err_to_name(err)); http.end(); return false; } + + uint8_t* buf = (uint8_t*)malloc(CHUNK); + mbedtls_sha256_context sc; + mbedtls_sha256_init(&sc); + SHA256_STARTS(&sc); + + WiFiClient* stream = http.getStreamPtr(); + uint32_t got = 0, last_rx = millis(); + int last_decile = -1, last_pct = -1; + bool ok = (buf != NULL); + while (ok && got < m.size) { + size_t avail = stream->available(); + if (avail == 0) { + uint32_t idle = millis() - last_rx; + if ((!http.connected() && idle > 2000) || idle > STALL_TIMEOUT_MS) { + print("[ota] download stalled at %lu/%lu bytes", (unsigned long)got, (unsigned long)m.size); + ok = false; + break; + } + vTaskDelay(pdMS_TO_TICKS(5)); + pump(); + continue; + } + size_t want = min(min(avail, CHUNK), (size_t)(m.size - got)); + int r = stream->read(buf, want); + if (r <= 0) continue; + last_rx = millis(); + SHA256_UPDATE(&sc, buf, r); + err = esp_ota_write(h, buf, r); + if (err != ESP_OK) { print("[ota] flash write: %s", esp_err_to_name(err)); ok = false; break; } + got += r; + int pct = (int)((uint64_t)got * 100 / m.size); + if (pct != last_pct) { + last_pct = pct; + g_progress = (uint8_t)pct; + notice("Updating %s %d%%", m.version, pct); + pump(); + } + int decile = pct / 10; + if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; } + } + http.end(); + free(buf); + + uint8_t digest[32]; + char digest_hex[65]; + SHA256_FINISH(&sc, digest); + mbedtls_sha256_free(&sc); + toHex(digest, sizeof(digest), digest_hex); + + if (ok && strcmp(digest_hex, m.sha256) != 0) { + print("[ota] SHA-256 MISMATCH - image does not match the signed manifest"); + ok = false; + } + if (!ok) { esp_ota_abort(h); print("[ota] aborted; still running %s", FW_VERSION); return false; } + err = esp_ota_end(h); + if (err != ESP_OK) { print("[ota] image check failed: %s", esp_err_to_name(err)); return false; } + return true; +} + +static void install(bool force) { + manifest_t m; + if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; } + if (!force && strcmp(m.version, FW_VERSION) == 0) { + print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION); + setPhase(LINK_OTA_UP_TO_DATE, m.version); + return; + } + const esp_partition_t* part = esp_ota_get_next_update_partition(NULL); + if (!part) { print("[ota] no idle OTA slot (partition table?)"); failPhase(); return; } + if (m.size > part->size) { + print("[ota] image %lu B does not fit slot %s (%lu B)", (unsigned long)m.size, part->label, (unsigned long)part->size); + failPhase(); + return; + } + print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size); + setPhase(LINK_OTA_INSTALLING, m.version); + notice("Updating %s 0%%", m.version); + bool ok = writeImage(m, part); + + char why[64]; + if (ok && !parked(why, sizeof(why))) { + print("[ota] new image left inactive in %s: %s", part->label, why); + ok = false; + } + if (ok) { + esp_err_t err = esp_ota_set_boot_partition(part); + if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); ok = false; } + } + if (!ok) { + failPhase(); + notice("Update failed"); + pump(true); + delay(3000); + GaugeScreen::setNotice(NULL); + return; + } + print("[ota] verified and installed %s. Rebooting in 3 s; it confirms itself after %lu s of uptime.", + m.version, (unsigned long)(OTA_CONFIRM_MS / 1000)); + notice("Installed %s - restarting", m.version); + g_progress = 100; + pump(true); + delay(3000); + esp_restart(); +} + +static void check() { + manifest_t m; + if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; } + bool same = strcmp(m.version, FW_VERSION) == 0; + print("[ota] running %s | latest release %s (%lu bytes, signature OK)%s", + FW_VERSION, m.version, (unsigned long)m.size, same ? " - up to date" : " - install to update"); + setPhase(same ? LINK_OTA_UP_TO_DATE : LINK_OTA_AVAILABLE, m.version); +} + +static void rollback() { + char why[64]; + if (!parked(why, sizeof(why))) { print("[ota] refused: %s", why); return; } + if (g_pending_verify) { + print("[ota] rejecting this unconfirmed image; rebooting into the previous one"); + delay(500); + esp_ota_mark_app_invalid_rollback_and_reboot(); + return; + } + const esp_partition_t* other = esp_ota_get_next_update_partition(NULL); + esp_app_desc_t d; + esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED; + if (!other || esp_ota_get_partition_description(other, &d) != ESP_OK) { + print("[ota] no previous image to roll back to"); + return; + } + esp_ota_get_state_partition(other, &ost); + if (ost == ESP_OTA_IMG_INVALID || ost == ESP_OTA_IMG_ABORTED) { + print("[ota] previous image in %s is marked %s - refusing", other->label, stateName(ost)); + return; + } + esp_err_t err = esp_ota_set_boot_partition(other); + if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); return; } + print("[ota] booting %s in 2 s", other->label); + delay(2000); + esp_restart(); +} + +static void runJob(job_t job) { + if (job == JOB_ROLLBACK) { rollback(); return; } + Serial.printf("[ota] heap before job: %u free (largest block %u)\n", + (unsigned)ESP.getFreeHeap(), (unsigned)ESP.getMaxAllocHeap()); + // Gauges: the loop is about to block, so drive the outputs to their "no + // link" state (tach off) rather than leaving them frozen mid-value. + automotive_data_t none = {}; + GaugeOutputs::update(none, false); + if (!joinWifi()) { failPhase(); return; } + if (job == JOB_CHECK) check(); + else install(job == JOB_INSTALL_FORCE); + leaveWifi(); + GaugeScreen::setNotice(NULL); + Serial.printf("[ota] heap after job: %u free | loop stack headroom %u B\n", + (unsigned)ESP.getFreeHeap(), (unsigned)uxTaskGetStackHighWaterMark(NULL)); +} + +static bool startJob(job_t job, char* why = NULL, size_t why_n = 0) { + if (g_job != JOB_NONE) { if (why) snprintf(why, why_n, "busy"); return false; } + if (job != JOB_ROLLBACK && !gate(job != JOB_CHECK, why, why_n)) return false; + if (job == JOB_ROLLBACK) { g_job = job; return true; } + setPhase(job == JOB_CHECK ? LINK_OTA_CHECKING : LINK_OTA_INSTALLING); + g_job = job; + print("[ota] working - the gauges pause until done"); + return true; +} + +static void status() { + const esp_partition_t* run = esp_ota_get_running_partition(); + const esp_partition_t* other = esp_ota_get_next_update_partition(NULL); + esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED; + esp_ota_get_state_partition(run, &st); + print("[ota] version %s (built %s %s), slot %s, state %s%s", FW_VERSION, __DATE__, __TIME__, + run ? run->label : "?", stateName(st), g_pending_verify ? " - confirms after healthy uptime" : ""); + if (other) { + esp_app_desc_t d; + esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED; + esp_ota_get_state_partition(other, &ost); + if (esp_ota_get_partition_description(other, &d) == ESP_OK) + print("[ota] other slot %s: image built %s %s, state %s", other->label, d.date, d.time, stateName(ost)); + else + print("[ota] other slot %s: empty", other->label); + } + print("[ota] updates from %s/%s/releases (%s) | credentials %s | paired %s", + OTA_SERVER, OTA_REPO, OTA_TARGET, LinkPeer::hasWifiCredentials() ? "yes" : "no", + LinkPeer::isPaired() ? "yes" : "no"); +} + +static void help() { + Serial.println("ota status running version, slot, rollback state"); + Serial.println("ota check join Wi-Fi, ask Gitea for the latest release"); + Serial.println("ota install [force] download + verify + flash idle slot + reboot (parked only)"); + Serial.println("ota rollback boot the previous slot (parked only)"); +} + +// ---- public ---------------------------------------------------------------- +const char* version() { return FW_VERSION; } + +void onLinkCommand(uint8_t cmd, uint8_t flags) { + char why[96]; + bool ok = false; + switch (cmd) { + case LINK_OTA_CMD_CHECK: ok = startJob(JOB_CHECK, why, sizeof(why)); break; + case LINK_OTA_CMD_INSTALL: ok = startJob((flags & LINK_OTA_FORCE) ? JOB_INSTALL_FORCE : JOB_INSTALL, why, sizeof(why)); break; + case LINK_OTA_CMD_ROLLBACK: ok = startJob(JOB_ROLLBACK, why, sizeof(why)); break; + default: snprintf(why, sizeof(why), "unknown command %u", cmd); break; + } + if (!ok) { + // Tell A on the next STATUS why nothing happened + setPhase(LINK_OTA_FAILED, NULL, why); + } +} + +void init() { + const esp_partition_t* run = esp_ota_get_running_partition(); + esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED; + if (run && esp_ota_get_state_partition(run, &st) == ESP_OK && st == ESP_OTA_IMG_PENDING_VERIFY) { + g_pending_verify = true; + } + LinkPeer::setOtaCommandHandler(onLinkCommand); + report(); + print("[ota] firmware %s, slot %s%s", FW_VERSION, run ? run->label : "?", + g_pending_verify ? " - NEW IMAGE, unconfirmed (a reset before healthy uptime rolls back)" : ""); +} + +void tick() { + if (g_job != JOB_NONE) { + job_t j = g_job; + runJob(j); + g_job = JOB_NONE; + } + if (g_pending_verify && millis() > OTA_CONFIRM_MS) { + esp_ota_mark_app_valid_cancel_rollback(); + g_pending_verify = false; + report(); + print("[ota] firmware %s confirmed - rollback cancelled", FW_VERSION); + } +} + +bool handleCommand(const char* line) { + if (strcmp(line, "help") == 0) { help(); return false; } + char buf[48]; + strlcpy(buf, line, sizeof(buf)); + char* argv[4] = {0}; + int argc = 0; + for (char* t = strtok(buf, " \t"); t && argc < 4; t = strtok(NULL, " \t")) argv[argc++] = t; + if (argc == 0 || strcmp(argv[0], "ota") != 0) return false; + + if (argc == 1 || !strcmp(argv[1], "help")) help(); + else if (!strcmp(argv[1], "status")) status(); + else if (!strcmp(argv[1], "check")) startJob(JOB_CHECK); + else if (!strcmp(argv[1], "install")) startJob(argc > 2 && !strcmp(argv[2], "force") ? JOB_INSTALL_FORCE : JOB_INSTALL); + else if (!strcmp(argv[1], "rollback")) startJob(JOB_ROLLBACK); + else help(); + return true; +} + +} // namespace Ota diff --git a/src/modules/uart_receiver.cpp b/src/modules/uart_receiver.cpp index dfee4c4..ec8564d 100644 --- a/src/modules/uart_receiver.cpp +++ b/src/modules/uart_receiver.cpp @@ -3,6 +3,7 @@ */ #include "modules/uart_receiver.h" +#include "modules/link_peer.h" #include "modules/debug_monitor.h" #include #include @@ -81,6 +82,20 @@ void processFrame(const uint8_t* frame, size_t len, link_source_t source) { uint32_t now = millis(); + if (type == PACKET_TYPE_PAIR) { + // The shared secret. Wire only: a PAIR heard on the radio is somebody + // else's business (or an attack) and is dropped. + if (source == LINK_SOURCE_UART) { + link_pair_t p; + memcpy(&p, payload, sizeof(p)); + LinkPeer::onPairFrame(&p); + } else { + Serial.println("[Link] PAIR frame on the radio ignored - pairing is wire-only"); + } + return; + } + if (type != PACKET_TYPE_DATA && type != PACKET_TYPE_CONFIG) return; // STATUS/SECURE never come this way + if (type == PACKET_TYPE_CONFIG) { link_config_t cfg; memcpy(&cfg, payload, sizeof(cfg)); diff --git a/tools/ota/firmware_signing_pub.pem b/tools/ota/firmware_signing_pub.pem new file mode 100644 index 0000000..f5471b5 --- /dev/null +++ b/tools/ota/firmware_signing_pub.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF +Y9brIfDTgn8IOWBm8J4nmLUef7zU4ydPM5BKXqUrTshJEpLd74GJIIOtkg== +-----END PUBLIC KEY----- diff --git a/wiki/index.md b/wiki/index.md index baff2fd..4595b70 100644 --- a/wiki/index.md +++ b/wiki/index.md @@ -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 diff --git a/wiki/log.md b/wiki/log.md index 757458f..f9e936d 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -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. diff --git a/wiki/pages/controller-b-ota.md b/wiki/pages/controller-b-ota.md index 97012fa..d88ba0c 100644 --- a/wiki/pages/controller-b-ota.md +++ b/wiki/pages/controller-b-ota.md @@ -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||`), 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 '' 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 diff --git a/wiki/pages/controller-link.md b/wiki/pages/controller-link.md index b7c356b..6287faa 100644 --- a/wiki/pages/controller-link.md +++ b/wiki/pages/controller-link.md @@ -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`. diff --git a/wiki/pages/open-questions.md b/wiki/pages/open-questions.md index b3e4e4e..3e2ffbb 100644 --- a/wiki/pages/open-questions.md +++ b/wiki/pages/open-questions.md @@ -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