Compare commits
6 Commits
da4c96903b
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
| eb9cbd985f | |||
| 0a76cd8c0e | |||
| bb0895674a | |||
| f5b7f43e7c | |||
| 1ec93dc413 | |||
| effa949429 |
@@ -0,0 +1,139 @@
|
||||
name: Firmware
|
||||
|
||||
# Controller A firmware, built by PlatformIO on every push. Two outputs:
|
||||
#
|
||||
# - push to main -> rolling PRE-release `main-latest` (firmware.bin + .elf),
|
||||
# unsigned, no manifest. For bench testing / USB flashing.
|
||||
# The device never installs it: it only reads
|
||||
# /releases/latest, which skips pre-releases, and it
|
||||
# needs a signed manifest.txt anyway.
|
||||
# - push tag v* -> the OTA release: firmware.bin + firmware.elf +
|
||||
# manifest.txt (size, sha256, ECDSA P-256 signature over
|
||||
# "patrol-a|<tag>|<sha256>"). This is what `ota install`
|
||||
# on the controller pulls.
|
||||
#
|
||||
# Signing key: repo secret BMW_NISSAN_FIRMWARE_SIGNING_KEY (PEM, EC P-256). Its public
|
||||
# half is compiled into the firmware (include/config/ota_config.h) and kept in
|
||||
# tools/ota/firmware_signing_pub.pem, which this job uses to self-check the
|
||||
# signature before publishing. See wiki/pages/ota-updates.md.
|
||||
#
|
||||
# Releases go through the Gitea API with plain curl (actions/upload-artifact
|
||||
# is unreliable on this runner - same pattern as parking_solution).
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Version
|
||||
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 32 ] || { echo "::error::version too long"; exit 1; }
|
||||
echo "VERSION=${VERSION}" >> "$GITHUB_ENV"
|
||||
echo "version: ${VERSION}"
|
||||
|
||||
- name: Cache PlatformIO
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.platformio/packages
|
||||
~/.platformio/platforms
|
||||
.pio/libdeps
|
||||
key: pio-${{ hashFiles('platformio.ini') }}
|
||||
|
||||
- name: Install PlatformIO
|
||||
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"
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
export PLATFORMIO_BUILD_FLAGS="-DFW_VERSION=\\\"${VERSION}\\\""
|
||||
pio run
|
||||
mkdir -p dist
|
||||
cp .pio/build/waveshare_esp32_s3_lcd_5b/firmware.bin dist/
|
||||
cp .pio/build/waveshare_esp32_s3_lcd_5b/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: 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-a|${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
|
||||
# Self-check against the public key the firmware carries.
|
||||
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-a\nversion=%s\nsize=%s\nsha256=%s\nsig=%s\n' \
|
||||
"$VERSION" "$SIZE" "$SHA" "$SIG" > dist/manifest.txt
|
||||
cat dist/manifest.txt
|
||||
|
||||
- name: Publish release
|
||||
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 A ${TAG}"
|
||||
BODY="Signed OTA release. Install on the controller with \`ota install\` (parked, Wi-Fi joined)."
|
||||
else
|
||||
TAG="main-latest"
|
||||
PRE=true
|
||||
NAME="Controller A main build"
|
||||
BODY="Unsigned build of main @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests."
|
||||
# Rolling: drop the previous release and its tag, recreate at this commit.
|
||||
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}"
|
||||
@@ -80,6 +80,7 @@ src/
|
||||
espnow_link.cpp # ESP-NOW broadcast leg of the link
|
||||
tuning_screen.cpp # Hand-coded LVGL Gauge Tuning screen (swipe right from Driveline)
|
||||
diag_probe.cpp # On-demand OBD-II requests ('diag' console) - the ONLY CAN transmitter
|
||||
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
|
||||
settings_manager.cpp # NVS persistent storage
|
||||
ui_state_manager.cpp # UI synchronization logic
|
||||
display_init.cpp # Display initialization; boots into DrivelineScreen
|
||||
@@ -222,15 +223,19 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
||||
|
||||
### Tunables (gauge calibration, alert thresholds)
|
||||
|
||||
`src/modules/tunables.cpp` owns `link_config_t`: tach pulses/rev + trim + clamps, coolant PWM frequency + duty law + min temp, per-output enables, a bench override (force rpm / duty), and the alert thresholds. Stored as an NVS blob (namespace `tunables`). Edited over the USB serial console: `cfg show`, `cfg set <name> <value>`, `cfg override rpm <n> | duty <n> | both <rpm> <duty> | off`, `cfg reset`. Every change bumps `cfg_version`, which makes the UART task push a CONFIG frame. Overrides are pushed but never saved. The **Gauge Tuning screen** (`src/modules/tuning_screen.cpp`, hand-coded like the driveline screen so SquareLine exports cannot clobber it; Home → swipe right → Driveline → swipe right → Tuning) edits the same values with −/+ buttons, enable switches, and an override panel with RPM and duty sliders. Overrides are never written to NVS (`save()` strips them).
|
||||
`src/modules/tunables.cpp` owns `link_config_t`: tach pulses/rev + trim + clamps, coolant PWM frequency + duty law + min temp, per-output enables, a bench override (force rpm / duty), and the alert thresholds. Stored as an NVS blob (namespace `tunables`), written 3 s after the last change or on leaving the Tuning screen (`Tunables::flush()`) - every flash write flickers the RGB panel, so no write per tap. Edited over the USB serial console: `cfg show`, `cfg set <name> <value>`, `cfg override rpm <n> | duty <n> | both <rpm> <duty> | off`, `cfg reset`. Every change bumps `cfg_version`, which makes the UART task push a CONFIG frame. Overrides are pushed but never saved. The **Gauge Tuning screen** (`src/modules/tuning_screen.cpp`, hand-coded like the driveline screen so SquareLine exports cannot clobber it; Home → swipe right → Driveline → swipe right → Tuning) edits the same values with −/+ buttons, enable switches, and an override panel with RPM and duty sliders. Overrides are never written to NVS (`save()` strips them).
|
||||
|
||||
### Diagnostic probe (`diag` console)
|
||||
|
||||
`src/modules/diag_probe.cpp` is the only code allowed to call `CANDriver::transmit()`. It sends single diagnostic requests and reassembles the ISO-TP replies, on two routes: generic OBD-II on `0x7DF` (replies `0x7E8..0x7EF`) and BMW-addressed KWP2000 on `0x6F1` with target byte (replies `0x600`+addr, extended addressing). Commands: `diag pids` (supported-PID bitmap scan), `diag pid <hex>`, `diag dtc` (mode 03), `diag vin`, `diag ecu`, `diag ident [addr]` (KWP `1A 80`), `diag bmw <addr> <hex...>` (raw, whitelisted), `diag raw on|off` (CANRAW mute for scans), `diag status`. One request in flight, single-shot frames, refused for 3 s after any foreign tester frame (`0x7DF`, `0x7E0-7`, `0x6F1`); read-only services only — generic 01/03/09, BMW `1A`/`18`/`21`/`22` (whitelist enforced in `sendBmwRequest()`), never session control or writes. Transmitted frames are echoed as `CANTX,` lines in the same format as `CANRAW,`. Console lines that `cfg` does not recognise are passed to it via `Tunables::setExtraCommandHandler()`. Background and test procedure: `wiki/pages/obd-diagnostic-polling.md`.
|
||||
|
||||
### OTA updates (`ota` console)
|
||||
|
||||
`src/modules/ota_update.cpp` pulls signed firmware from this repo's Gitea releases (`include/config/ota_config.h`: server, repo, Let's Encrypt roots, signing public key). Manual only: `ota status | check | install [force] | rollback` - the future password-gated Diagnostics screen will call the same code. Install is refused unless parked (engine off, shaft still, lever not in a drive gear; silent bus = parked), checked before download and again before the slot switch. The manifest's ECDSA P-256 signature over `patrol-a|version|sha256` is checked before download; the streamed image must match that sha256. `verifyRollbackLater()` is overridden so a new image stays pending until `Ota::tick()` confirms it after 30 s - a reset before that rolls back. CI: `.gitea/workflows/firmware.yml` (push `main` -> rolling unsigned pre-release `main-latest`; tag `v*` -> signed release, needs repo secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY`). Never put secrets in firmware source - the repo and its release binaries are public. Jobs run inside the loop task (8 KB stack) with mbedtls routed to PSRAM - internal RAM is too tight for a TLS task (15.9 KB free, largest block 7.6 KB with Wi-Fi up). `wifi join <ssid> [pass] | status | off` (in `wifi_manager.cpp`) joins a network from the console. Details: `wiki/pages/ota-updates.md`.
|
||||
|
||||
### ESP-NOW link
|
||||
|
||||
`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association (it no longer calls `WiFi.mode(WIFI_OFF)`). If Wi-Fi joins an AP the channel follows the AP; B hops to find it.
|
||||
`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association. Never call `WiFi.disconnect(true)` or `WiFi.mode(WIFI_OFF)`: powering the radio off de-initialises ESP-NOW (`send()` re-inits it as a safety net). If Wi-Fi joins an AP the channel follows the AP; B hops to find it.
|
||||
|
||||
### UI State Synchronization
|
||||
|
||||
@@ -242,7 +247,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
||||
- Syncs toggle switches with actual service states: `g_wifi_state`, `g_uart_state`, `g_debug_enabled`
|
||||
- Shows loading spinner during sync for smooth UX
|
||||
|
||||
**Screens**: Driveline (boot, hand-coded) ← swipe left → Settings (SquareLine); Driveline → swipe right → Gauge Tuning (hand-coded).
|
||||
**Screens**: Driveline (boot, hand-coded) ← swipe left → Settings (SquareLine); Driveline → swipe right → Gauge Tuning (hand-coded). Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`): full-screen fades are software-blended every frame and stutter at 1024x600. The firmware version is a label on `lv_layer_top()` (bottom-right, every screen, `DisplayInit`).
|
||||
|
||||
**Debug Mode**:
|
||||
- Toggle in Settings screen shows/hides `uic_Device_State_Container`
|
||||
@@ -255,7 +260,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
||||
- Custom Arduino core: `pioarduino/platform-espressif32` (Arduino 3.3.3 / ESP-IDF 5.5.1) for RGB LCD support
|
||||
- Board: Custom `esp32-s3-wroom-1-n16r8` (defined in `boards/esp32-s3-wroom-1-n16r8.json`)
|
||||
- PSRAM: OPI mode (`qio_opi` memory type) - REQUIRED for 8MB OPI PSRAM and 1024x600 display
|
||||
- Partition: `partition_table.csv` (12.5MB app / 3.375MB SPIFFS) - optimized for 16MB flash
|
||||
- Partition: `partition_table.csv` (dual OTA: 2 x 7.9MB app slots, no SPIFFS) - see OTA updates below
|
||||
- Debug level: `CORE_DEBUG_LEVEL=1` (1=Error, 5=Verbose)
|
||||
- Libraries: ESP32_Display_Panel v1.0.4, LVGL 8.4.0 (from GitHub)
|
||||
|
||||
@@ -267,11 +272,11 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
||||
- Critical settings: `memory_type: qio_opi`, `psram_type: opi`
|
||||
|
||||
**partition_table.csv** (Partition Table)
|
||||
- NVS: 20KB @ 0x9000 (settings storage)
|
||||
- OTA Data: 8KB @ 0xe000 (for future OTA support)
|
||||
- App: 12.5MB @ 0x10000 (large partition for UI assets)
|
||||
- SPIFFS: 3.375MB @ 0xC90000 (file system)
|
||||
- NVS: 20KB @ 0x9000 (settings storage) - never move it, or saved settings/tunables are lost
|
||||
- OTA Data: 8KB @ 0xe000 (which slot boots)
|
||||
- app0 / app1: 7.9MB each @ 0x10000 / 0x800000 (OTA slots; firmware ~1.65MB)
|
||||
- Coredump: 64KB @ 0xFF0000 (crash debugging)
|
||||
- Changing this table needs one USB flash; OTA can't repartition
|
||||
|
||||
**include/lv_conf.h**
|
||||
- LVGL 8.4.0 configuration
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* ota_config.h - where Controller A looks for firmware updates, and what it trusts.
|
||||
*
|
||||
* Updates are pulled over HTTPS from this repo's Gitea releases (public repo,
|
||||
* no token). CI (.gitea/workflows/firmware.yml) attaches firmware.bin +
|
||||
* manifest.txt to every v* tag; manifest carries size, sha256 and an ECDSA
|
||||
* P-256 signature. See wiki/pages/ota-updates.md.
|
||||
*
|
||||
* Nothing in here is secret: the CA roots and the signing PUBLIC key are meant
|
||||
* to be public. The signing private key lives only in the Gitea repo secret
|
||||
* BMW_NISSAN_FIRMWARE_SIGNING_KEY (plus the owner's offline backup).
|
||||
*/
|
||||
|
||||
#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
|
||||
|
||||
// Identity inside the signed statement, so a Controller B image can never be
|
||||
// accepted by A (and vice versa) even though both are signed by the same key.
|
||||
#define OTA_TARGET "patrol-a"
|
||||
|
||||
#define OTA_SERVER "https://git.infra.msai.al"
|
||||
#define OTA_REPO "art/ESP32-S3-Touch-LCD-5B"
|
||||
// Latest non-draft, non-prerelease release (the rolling `main` build is a
|
||||
// prerelease, so it is never offered to the car).
|
||||
#define OTA_LATEST_API_URL OTA_SERVER "/api/v1/repos/" OTA_REPO "/releases/latest"
|
||||
// + "<tag>/<asset>"
|
||||
#define OTA_DOWNLOAD_BASE OTA_SERVER "/" OTA_REPO "/releases/download/"
|
||||
|
||||
// TLS trust: Let's Encrypt roots. The server's chain (2026-09-26) is
|
||||
// leaf -> YR2 -> Root YR (cross-signed by ISRG Root X1); both roots verify it
|
||||
// on their own, so either survives LE dropping the cross-sign. Valid to
|
||||
// 2035 (X1) / 2045 (YR). Leaf certs rotate every ~90 days - never pin them.
|
||||
static const char OTA_CA_PEM[] =
|
||||
// ISRG Root X1
|
||||
"-----BEGIN CERTIFICATE-----\n"
|
||||
"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\n"
|
||||
"-----END CERTIFICATE-----\n"
|
||||
// ISRG Root YR
|
||||
"-----BEGIN CERTIFICATE-----\n"
|
||||
"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\n"
|
||||
"sI1ANRYvqSFC2X1VRZfDg+wD6E21BccmifG4yWc=\n"
|
||||
"-----END CERTIFICATE-----\n";
|
||||
|
||||
// Firmware signing public key (ECDSA P-256). The device verifies
|
||||
// sig over SHA-256("<target>|<version>|<sha256-of-image-hex>").
|
||||
static const char OTA_SIGNING_PUBKEY_PEM[] =
|
||||
"-----BEGIN PUBLIC KEY-----\n"
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF\n"
|
||||
"Y9brIfDTgn8IOWBm8J4nmLUef7zU4ydPM5BKXqUrTshJEpLd74GJIIOtkg==\n"
|
||||
"-----END PUBLIC KEY-----\n";
|
||||
|
||||
#endif // OTA_CONFIG_H
|
||||
+10
-4
@@ -1,7 +1,13 @@
|
||||
# ESP32-S3-WROOM-1-N16R8 Partition Table (16MB Flash)
|
||||
# ESP32-S3-WROOM-1-N16R8 Partition Table (16MB Flash) - dual-slot OTA
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
#
|
||||
# nvs + otadata keep their original offsets so saved settings/tunables survive
|
||||
# the change. Two equal app slots for OTA (src/modules/ota_update.cpp): the
|
||||
# running image writes the new one into the idle slot and flips otadata.
|
||||
# SPIFFS was dropped (nothing used it) to give each slot ~7.9 MB; firmware is
|
||||
# ~1.5 MB. Changing this table needs one USB flash; OTA works after that.
|
||||
nvs, data, nvs, 0x9000, 0x5000,
|
||||
otadata, data, ota, 0xe000, 0x2000,
|
||||
app0, app, ota_0, 0x10000, 0xC80000,
|
||||
spiffs, data, spiffs, 0xC90000, 0x360000,
|
||||
coredump, data, coredump,0xFF0000, 0x10000,
|
||||
app0, app, ota_0, 0x10000, 0x7F0000,
|
||||
app1, app, ota_1, 0x800000, 0x7F0000,
|
||||
coredump, data, coredump,0xFF0000, 0x10000,
|
||||
|
||||
|
+11
-2
@@ -13,6 +13,7 @@
|
||||
#include "modules/tunables.h" // Gauge calibration + alert thresholds (NVS, serial console)
|
||||
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B
|
||||
#include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter
|
||||
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
|
||||
|
||||
// ============================================================================
|
||||
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
|
||||
@@ -112,6 +113,12 @@ void onDebugToggle(lv_event_t *e)
|
||||
|
||||
} // extern "C"
|
||||
|
||||
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi.
|
||||
static bool consoleExtraCommand(const char* line) {
|
||||
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
|
||||
WiFiManager::handleCommand(line);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// SETUP - Initialize hardware and UI
|
||||
// ============================================================================
|
||||
@@ -131,6 +138,7 @@ void setup()
|
||||
// Use ESP_LOG instead of Serial.println to match library output
|
||||
ESP_LOGI("MAIN", "=== ESP32-S3-LCD-5B Minimal Setup ===");
|
||||
ESP_LOGI("MAIN", "Firmware compiled: %s %s", __DATE__, __TIME__);
|
||||
Ota::init(); // version + slot; flags an unconfirmed freshly-installed image
|
||||
|
||||
// Initialize display hardware and UI
|
||||
ESP_LOGI("MAIN", "Initializing display and UI...");
|
||||
@@ -144,7 +152,7 @@ void setup()
|
||||
// Tunables (gauge calibration, alert thresholds) - before CAN/UART start
|
||||
Tunables::init();
|
||||
DiagProbe::init();
|
||||
Tunables::setExtraCommandHandler(DiagProbe::handleCommand);
|
||||
Tunables::setExtraCommandHandler(consoleExtraCommand);
|
||||
|
||||
// Load saved switch states from NVS
|
||||
ESP_LOGI("MAIN", "Loading saved switch states from NVS...");
|
||||
@@ -210,9 +218,10 @@ void loop()
|
||||
// (Settings screen gets destroyed/recreated when swiping)
|
||||
UIStateManager::applySavedStatesToUI();
|
||||
|
||||
// Serial console: gauge tunables (cfg ...) and the diagnostic probe (diag ...)
|
||||
// Serial console: gauge tunables (cfg ...), diagnostic probe (diag ...), updates (ota ...)
|
||||
Tunables::pollSerial();
|
||||
DiagProbe::tick();
|
||||
Ota::tick(); // confirms a freshly installed image after healthy uptime
|
||||
|
||||
DrivelineScreen::tick();
|
||||
TuningScreen::tick();
|
||||
|
||||
@@ -6,9 +6,32 @@
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include "ui/ui.h"
|
||||
#include "driveline_screen.h"
|
||||
#include "config/ota_config.h" // FW_VERSION
|
||||
|
||||
namespace DisplayInit {
|
||||
|
||||
static Backlight* g_backlight = nullptr;
|
||||
|
||||
/**
|
||||
* Firmware version, bottom-right on every screen. Lives on lv_layer_top(), which
|
||||
* sits above all screens and survives screen switches. Labels aren't
|
||||
* clickable, so it never steals touches or swipes from the screen below.
|
||||
* Call with the LVGL lock held.
|
||||
*/
|
||||
static void createVersionLabel() {
|
||||
lv_obj_t* lbl = lv_label_create(lv_layer_top());
|
||||
lv_label_set_text(lbl, "A " FW_VERSION);
|
||||
lv_obj_set_style_text_font(lbl, &lv_font_montserrat_14, 0);
|
||||
lv_obj_set_style_text_color(lbl, lv_color_hex(0x808080), 0);
|
||||
lv_obj_align(lbl, LV_ALIGN_BOTTOM_RIGHT, -8, -4);
|
||||
}
|
||||
|
||||
void setBacklight(bool on) {
|
||||
if (g_backlight == nullptr) return;
|
||||
if (on) g_backlight->on();
|
||||
else g_backlight->off();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
@@ -76,6 +99,7 @@ DisplayObjects init() {
|
||||
// empty placeholder now (the SquareLine Home screen was removed 2026-09-21);
|
||||
// swap while the backlight is still off so there's no flash.
|
||||
DrivelineScreen::show();
|
||||
createVersionLabel();
|
||||
lvgl_port_unlock();
|
||||
Serial.println("[DisplayInit] Step 13: SquareLine UI loaded successfully!");
|
||||
|
||||
@@ -91,6 +115,7 @@ DisplayObjects init() {
|
||||
Serial.println("[DisplayInit] Display initialization complete!");
|
||||
|
||||
// Return board and backlight objects for later use
|
||||
g_backlight = backlight;
|
||||
return {board, backlight};
|
||||
}
|
||||
|
||||
|
||||
@@ -43,4 +43,7 @@ struct DisplayObjects {
|
||||
*/
|
||||
DisplayObjects init();
|
||||
|
||||
/** Backlight on/off after init() (e.g. dark during OTA flash writes, which flicker the panel). */
|
||||
void setBacklight(bool on);
|
||||
|
||||
} // namespace DisplayInit
|
||||
|
||||
@@ -145,7 +145,9 @@ static void onScreenGesture(lv_event_t* e) {
|
||||
lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
|
||||
if (dir == LV_DIR_LEFT) {
|
||||
lv_indev_wait_release(lv_indev_get_act());
|
||||
_ui_screen_change(&ui_Settings_Screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0,
|
||||
// No transition animation: a full-screen fade is re-rendered and blended
|
||||
// in software every frame and stutters on this 1024x600 panel.
|
||||
_ui_screen_change(&ui_Settings_Screen, LV_SCR_LOAD_ANIM_NONE, 0, 0,
|
||||
&ui_Settings_Screen_screen_init);
|
||||
} else if (dir == LV_DIR_RIGHT) {
|
||||
lv_indev_wait_release(lv_indev_get_act());
|
||||
@@ -257,7 +259,7 @@ static void build() {
|
||||
|
||||
void show() {
|
||||
build();
|
||||
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
|
||||
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
|
||||
}
|
||||
|
||||
void tick() {
|
||||
|
||||
@@ -62,14 +62,30 @@ bool init() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Anything that restarts the Wi-Fi driver drops ESP-NOW with it. Re-init at
|
||||
// most once a second instead of failing every frame from then on.
|
||||
static void reinitIfDue() {
|
||||
static uint32_t last = 0;
|
||||
if (millis() - last < 1000) return;
|
||||
last = millis();
|
||||
g_ready = false;
|
||||
ESP_LOGW("EspNow", "ESP-NOW not initialised - re-initialising");
|
||||
init();
|
||||
}
|
||||
|
||||
bool send(const uint8_t* frame, size_t len) {
|
||||
if (!g_ready || len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
|
||||
if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
|
||||
if (!g_ready) {
|
||||
reinitIfDue();
|
||||
if (!g_ready) return false;
|
||||
}
|
||||
esp_err_t err = esp_now_send(BROADCAST_MAC, frame, len);
|
||||
if (err == ESP_OK) {
|
||||
g_sent++;
|
||||
return true;
|
||||
}
|
||||
g_fail++;
|
||||
if (err == ESP_ERR_ESPNOW_NOT_INIT) reinitIfDue();
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,595 @@
|
||||
/**
|
||||
* ota_update.cpp - see ota_update.h for the command set and safety rules.
|
||||
*
|
||||
* Flow of `ota install`:
|
||||
* 1. gate: Wi-Fi joined, vehicle parked
|
||||
* 2. GET /api/v1/repos/<repo>/releases/latest -> tag_name
|
||||
* 3. GET /<repo>/releases/download/<tag>/manifest.txt
|
||||
* 4. verify ECDSA P-256 signature over "target|version|sha256" (before download)
|
||||
* 5. GET /<repo>/releases/download/<tag>/firmware.bin -> idle OTA slot,
|
||||
* hashing as it streams; sha256 must equal the signed one
|
||||
* 6. esp_ota_end() (image self-check), gate again, switch boot slot, reboot
|
||||
* 7. next boot: the image is PENDING_VERIFY until tick() confirms it
|
||||
*/
|
||||
|
||||
#include "modules/ota_update.h"
|
||||
#include "modules/serial_lock.h"
|
||||
#include "drivers/can_driver.h"
|
||||
#include "protocol/automotive_data.h"
|
||||
#include "config/ota_config.h"
|
||||
#include "modules/display_init.h"
|
||||
#include "modules/tunables.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include <lvgl.h>
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <esp_ota_ops.h>
|
||||
#include <esp_partition.h>
|
||||
#include <mbedtls/sha256.h>
|
||||
#include <mbedtls/pk.h>
|
||||
#include <mbedtls/platform.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
// Take over Arduino's rollback hook: by default initArduino() marks a new image
|
||||
// valid before setup() even runs, so a crash in setup would never roll back.
|
||||
// Returning true leaves the image PENDING_VERIFY until Ota::tick() confirms it.
|
||||
extern "C" bool verifyRollbackLater() { return true; }
|
||||
|
||||
namespace Ota {
|
||||
|
||||
#define OTA_CONFIRM_S 30 // healthy uptime before a new image is kept
|
||||
#define TOSTR_(x) #x
|
||||
#define TOSTR(x) TOSTR_(x)
|
||||
static const uint32_t OTA_CONFIRM_MS = OTA_CONFIRM_S * 1000;
|
||||
static const uint32_t BUS_SILENT_MS = 2000; // no frames for this long = ignition off / bench
|
||||
static const uint32_t STALL_TIMEOUT_MS = 15000; // download aborts if no bytes arrive this long
|
||||
static const size_t CHUNK = 4096;
|
||||
// Jobs run inside the Arduino loop task (8 KB internal stack), not a task of
|
||||
// their own: with the display + Wi-Fi up, internal RAM has no block big enough
|
||||
// for another TLS-capable stack (measured 2026-09-26: 15.9 KB free, largest
|
||||
// block 7.6 KB), and the stack can't go to PSRAM because esp_ota_write()
|
||||
// disables the flash cache. The loop (screen value ticks, console) pauses
|
||||
// while a job runs - acceptable: parked, and an install ends in a reboot.
|
||||
|
||||
typedef struct {
|
||||
char tag[32];
|
||||
char target[16];
|
||||
char version[32];
|
||||
uint32_t size;
|
||||
char sha256[65]; // lowercase hex
|
||||
uint8_t sig[80]; // DER ECDSA signature
|
||||
size_t sig_len;
|
||||
} manifest_t;
|
||||
|
||||
enum job_t { JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE };
|
||||
|
||||
static bool g_job_pending = false;
|
||||
static job_t g_job = JOB_CHECK;
|
||||
static bool g_pending_verify = false;
|
||||
|
||||
// ============================================================================
|
||||
// Helpers
|
||||
// ============================================================================
|
||||
|
||||
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);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The vehicle must be parked to update: installing ends in a reboot that blanks
|
||||
* Controller B's gauges. A silent bus (ignition off, or the bench) counts as
|
||||
* parked. Lever UNKNOWN is allowed so a missing gear frame can't block a bench
|
||||
* update; engine and output shaft are the checks that matter.
|
||||
*/
|
||||
static bool parked(char* why, size_t n) {
|
||||
if (!CANDriver::isActive()) return true;
|
||||
can_stats_t s = CANDriver::getStats();
|
||||
if (millis() - s.last_receive_time > BUS_SILENT_MS) return true;
|
||||
|
||||
driveline_t d = CANDriver::getDriveline();
|
||||
if (d.engine_rpm > 0 || d.engine_run_state == ENGINE_RUN_RUNNING ||
|
||||
d.engine_run_state == ENGINE_RUN_STARTING) {
|
||||
snprintf(why, n, "engine running (%u rpm) - switch the engine off", d.engine_rpm);
|
||||
return false;
|
||||
}
|
||||
if (d.output_shaft_raw != 0) {
|
||||
snprintf(why, n, "vehicle moving (output shaft turning)");
|
||||
return false;
|
||||
}
|
||||
if (d.lever != GEAR_PARK && d.lever != GEAR_NEUTRAL && d.lever != GEAR_UNKNOWN) {
|
||||
snprintf(why, n, "lever in a drive gear - select P");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool gate(bool need_wifi, bool need_parked = true) {
|
||||
char why[96];
|
||||
if (need_parked && !parked(why, sizeof(why))) {
|
||||
print("[ota] refused: %s", why);
|
||||
return false;
|
||||
}
|
||||
if (need_wifi && WiFi.status() != WL_CONNECTED) {
|
||||
print("[ota] refused: Wi-Fi not connected - join a network on the Settings screen first");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Tags end up in URLs; accept only [A-Za-z0-9._-]. */
|
||||
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;
|
||||
}
|
||||
|
||||
/** HTTPS GET of a small text body (API reply, manifest). */
|
||||
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-a-ota/" FW_VERSION);
|
||||
code = http.GET();
|
||||
bool ok = (code == HTTP_CODE_OK);
|
||||
if (ok) body = http.getString();
|
||||
http.end();
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Pull "key":"value" out of a flat JSON reply without a JSON library. */
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** ECDSA P-256 over SHA-256("target|version|sha256hex"), checked before downloading. */
|
||||
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];
|
||||
mbedtls_sha256((const unsigned char*)stmt, n, h, 0);
|
||||
|
||||
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
|
||||
// ============================================================================
|
||||
|
||||
/** Download firmware.bin into the idle slot, hashing as it streams; true if it matches the signed manifest. */
|
||||
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-a-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);
|
||||
mbedtls_sha256_starts(&sc, 0);
|
||||
|
||||
NetworkClient* stream = http.getStreamPtr();
|
||||
uint32_t got = 0, last_rx = millis();
|
||||
int last_decile = -1;
|
||||
bool ok = (buf != NULL);
|
||||
while (ok && got < m.size) {
|
||||
size_t avail = stream->available();
|
||||
if (avail == 0) {
|
||||
if (!http.connected() || millis() - last_rx > 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));
|
||||
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();
|
||||
mbedtls_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 decile = (int)((uint64_t)got * 10 / m.size);
|
||||
if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; }
|
||||
}
|
||||
http.end();
|
||||
free(buf);
|
||||
|
||||
uint8_t digest[32];
|
||||
char digest_hex[65];
|
||||
mbedtls_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); // validates the image structure + its embedded hash
|
||||
if (err != ESP_OK) { print("[ota] image check failed: %s", esp_err_to_name(err)); return false; }
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
// ---- Full-screen notice on lv_layer_top() (above every screen) ----------------
|
||||
static lv_obj_t* g_notice = NULL;
|
||||
static lv_obj_t* g_notice_lbl = NULL;
|
||||
|
||||
static void showNotice(const char* text) {
|
||||
lvgl_port_lock(-1);
|
||||
if (g_notice == NULL) {
|
||||
g_notice = lv_obj_create(lv_layer_top());
|
||||
lv_obj_remove_style_all(g_notice);
|
||||
lv_obj_set_size(g_notice, LV_PCT(100), LV_PCT(100));
|
||||
lv_obj_set_style_bg_color(g_notice, lv_color_black(), 0);
|
||||
lv_obj_set_style_bg_opa(g_notice, LV_OPA_COVER, 0);
|
||||
lv_obj_add_flag(g_notice, LV_OBJ_FLAG_CLICKABLE); // swallow touches while shown
|
||||
g_notice_lbl = lv_label_create(g_notice);
|
||||
lv_obj_set_style_text_font(g_notice_lbl, &lv_font_montserrat_30, 0);
|
||||
lv_obj_set_style_text_color(g_notice_lbl, lv_color_white(), 0);
|
||||
lv_obj_set_style_text_align(g_notice_lbl, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_center(g_notice_lbl);
|
||||
}
|
||||
lv_label_set_text(g_notice_lbl, text);
|
||||
lv_obj_clear_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
static void hideNotice() {
|
||||
lvgl_port_lock(-1);
|
||||
if (g_notice) lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
static void install(bool force) {
|
||||
manifest_t m;
|
||||
if (!fetchManifest(m) || !verifySignature(m)) return;
|
||||
|
||||
if (!force && strcmp(m.version, FW_VERSION) == 0) {
|
||||
print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION);
|
||||
return;
|
||||
}
|
||||
|
||||
const esp_partition_t* part = esp_ota_get_next_update_partition(NULL);
|
||||
if (!part) { print("[ota] no idle OTA slot (partition table?)"); 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);
|
||||
return;
|
||||
}
|
||||
|
||||
print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size);
|
||||
|
||||
// Flash writes stall the PSRAM-fed RGB panel (flicker), so the screen is
|
||||
// dark while the image is written, with a notice before and after.
|
||||
char msg[160];
|
||||
snprintf(msg, sizeof(msg), "Updating to %s\n\nThe screen goes dark for about a minute.\nDo not switch off.", m.version);
|
||||
showNotice(msg);
|
||||
delay(3000); // time to read it; LVGL renders on its own task
|
||||
DisplayInit::setBacklight(false);
|
||||
bool ok = writeImage(m, part);
|
||||
DisplayInit::setBacklight(true);
|
||||
|
||||
// The download took a while - the driver may have started the engine since.
|
||||
if (ok && !gate(false)) {
|
||||
print("[ota] new image left inactive in %s; retry when parked", part->label);
|
||||
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) {
|
||||
snprintf(msg, sizeof(msg), "Update failed\n\nStill running %s", FW_VERSION);
|
||||
showNotice(msg);
|
||||
delay(5000);
|
||||
hideNotice();
|
||||
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));
|
||||
snprintf(msg, sizeof(msg), "Installed %s\n\nRestarting...", m.version);
|
||||
showNotice(msg);
|
||||
Tunables::flush();
|
||||
delay(3000);
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
static void check() {
|
||||
manifest_t m;
|
||||
if (!fetchManifest(m) || !verifySignature(m)) 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" : " - `ota install` to update");
|
||||
}
|
||||
|
||||
// This core's mbedtls is built with CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC: every TLS
|
||||
// session wants ~40 KB of *internal* RAM, which the display + Wi-Fi leave no
|
||||
// room for. Route mbedtls to PSRAM (internal as fallback) while a job runs.
|
||||
// Both allocators free with heap_caps_free(), so swapping them is always safe.
|
||||
static void* tlsCallocPsram(size_t n, size_t size) {
|
||||
return heap_caps_calloc_prefer(n, size, 2, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
|
||||
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
|
||||
}
|
||||
static void* tlsCallocInternal(size_t n, size_t size) {
|
||||
return heap_caps_calloc(n, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
|
||||
}
|
||||
|
||||
static void printHeap(const char* when) {
|
||||
print("[ota] heap %s: internal free %u (largest block %u), PSRAM free %u", when,
|
||||
(unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
|
||||
(unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
|
||||
(unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
|
||||
}
|
||||
|
||||
static void runJob(job_t job) {
|
||||
mbedtls_platform_set_calloc_free(tlsCallocPsram, heap_caps_free);
|
||||
if (job == JOB_CHECK) check();
|
||||
else install(job == JOB_INSTALL_FORCE);
|
||||
mbedtls_platform_set_calloc_free(tlsCallocInternal, heap_caps_free);
|
||||
print("[ota] loop stack headroom after job: %u B", (unsigned)uxTaskGetStackHighWaterMark(NULL));
|
||||
}
|
||||
|
||||
static void startJob(job_t job) {
|
||||
if (!gate(true, job != JOB_CHECK)) return; // checking is harmless; installing needs parked
|
||||
g_job = job;
|
||||
g_job_pending = true; // runs on the next tick(), in the loop task
|
||||
print("[ota] working - console and screen values pause until done");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Status / rollback
|
||||
// ============================================================================
|
||||
|
||||
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 " TOSTR(OTA_CONFIRM_S) " s 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)", OTA_SERVER, OTA_REPO, OTA_TARGET);
|
||||
printHeap("now");
|
||||
}
|
||||
|
||||
static void rollback() {
|
||||
if (!gate(false)) return;
|
||||
if (g_pending_verify) {
|
||||
print("[ota] rejecting this unconfirmed image; rebooting into the previous one");
|
||||
Tunables::flush();
|
||||
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);
|
||||
Tunables::flush();
|
||||
delay(2000);
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
static void help() {
|
||||
print("ota status running version, slot, rollback state");
|
||||
print("ota check ask Gitea for the latest release (needs Wi-Fi)");
|
||||
print("ota install [force] download + verify + flash idle slot + reboot (parked only)");
|
||||
print("ota rollback boot the previous slot (parked only)");
|
||||
print("Tip: `diag raw off` first so CANRAW lines don't bury the progress output.");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Public API
|
||||
// ============================================================================
|
||||
|
||||
const char* version() { return FW_VERSION; }
|
||||
|
||||
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;
|
||||
}
|
||||
print("[ota] firmware %s, slot %s%s", FW_VERSION, run ? run->label : "?",
|
||||
g_pending_verify ? " - NEW IMAGE, unconfirmed (a reset in the next " TOSTR(OTA_CONFIRM_S) " s rolls back)" : "");
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (g_job_pending) {
|
||||
g_job_pending = false;
|
||||
runJob(g_job);
|
||||
}
|
||||
if (g_pending_verify && millis() > OTA_CONFIRM_MS) {
|
||||
esp_ota_mark_app_valid_cancel_rollback();
|
||||
g_pending_verify = false;
|
||||
print("[ota] firmware %s confirmed - rollback cancelled", FW_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
char buf[48];
|
||||
strncpy(buf, line, sizeof(buf) - 1);
|
||||
buf[sizeof(buf) - 1] = 0;
|
||||
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")) rollback();
|
||||
else help();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Ota
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* ota_update.h - pull firmware updates from this repo's Gitea releases.
|
||||
*
|
||||
* Manual only: nothing checks or installs by itself. The `ota` serial console
|
||||
* drives it today; the planned password-gated Diagnostics screen will call the
|
||||
* same functions (wiki/pages/open-questions.md #12).
|
||||
*
|
||||
* ota status running version, slot, rollback state
|
||||
* ota check ask Gitea for the latest release, compare versions
|
||||
* ota install [force] download, verify signature, flash idle slot, reboot
|
||||
* ota rollback boot the previous slot
|
||||
*
|
||||
* Safety:
|
||||
* - refused unless the vehicle is parked (engine off, output shaft still, lever
|
||||
* not in a drive gear) - checked before the download AND again before the
|
||||
* boot slot is switched. Silent bus (bench / ignition off) counts as parked.
|
||||
* - image must match the signed manifest (sha256 + ECDSA P-256 over
|
||||
* "target|version|sha256"); otherwise the idle slot is never activated.
|
||||
* - a new image must run OTA_CONFIRM_MS before it is marked valid; a reset
|
||||
* or crash before that makes the bootloader fall back to the old slot.
|
||||
*
|
||||
* Needs Wi-Fi joined to a network with internet (Settings screen). Joining an
|
||||
* AP moves the radio channel; the ESP-NOW link to Controller B follows it.
|
||||
* See wiki/pages/ota-updates.md.
|
||||
*/
|
||||
|
||||
#ifndef OTA_UPDATE_H
|
||||
#define OTA_UPDATE_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace Ota {
|
||||
|
||||
/** Log version/slot; note if this boot is an unconfirmed new image. Call early in setup(). */
|
||||
void init();
|
||||
|
||||
/** Confirms a freshly installed image once it has run long enough. Call from loop(). */
|
||||
void tick();
|
||||
|
||||
/** Console entry point (`ota ...`). Returns false if the line isn't an ota command. */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
/** Firmware version baked in at build time ("dev" for local builds). */
|
||||
const char* version();
|
||||
|
||||
} // namespace Ota
|
||||
|
||||
#endif // OTA_UPDATE_H
|
||||
@@ -43,6 +43,18 @@ static void save() {
|
||||
prefs.end();
|
||||
}
|
||||
|
||||
// Every flash write briefly stalls the PSRAM-fed RGB panel (flicker), so edits
|
||||
// are applied + pushed to B at once but written to NVS only after the user
|
||||
// stops tapping (SAVE_IDLE_MS), on leaving the Tuning screen, or before reboot.
|
||||
static const uint32_t SAVE_IDLE_MS = 3000;
|
||||
static bool g_dirty = false;
|
||||
static uint32_t g_dirty_ms = 0;
|
||||
|
||||
static void markDirty() { // call with the mutex held
|
||||
g_dirty = true;
|
||||
g_dirty_ms = millis();
|
||||
}
|
||||
|
||||
static bool load() {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, true);
|
||||
@@ -113,7 +125,7 @@ static bool setField(const char* name, long v) {
|
||||
if (ok) {
|
||||
g_cfg.cfg_version++;
|
||||
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
|
||||
save();
|
||||
markDirty();
|
||||
}
|
||||
unlock();
|
||||
return ok;
|
||||
@@ -159,7 +171,7 @@ void set(const link_config_t& cfg) {
|
||||
uint8_t v = g_cfg.cfg_version + 1;
|
||||
g_cfg = cfg;
|
||||
g_cfg.cfg_version = v ? v : 1;
|
||||
save();
|
||||
markDirty();
|
||||
unlock();
|
||||
}
|
||||
|
||||
@@ -168,7 +180,7 @@ void resetDefaults() {
|
||||
uint8_t v = g_cfg.cfg_version + 1;
|
||||
link_config_defaults(&g_cfg);
|
||||
g_cfg.cfg_version = v ? v : 1;
|
||||
save();
|
||||
markDirty();
|
||||
unlock();
|
||||
}
|
||||
|
||||
@@ -203,7 +215,7 @@ bool handleCommand(const char* line) {
|
||||
if (!strcmp(argv[1], "set") && argc == 4) {
|
||||
long v = strtol(argv[3], NULL, 0);
|
||||
if (setField(argv[2], v)) {
|
||||
print("[cfg] %s = %ld (version %u, saved)", argv[2], v, version());
|
||||
print("[cfg] %s = %ld (version %u, saved to NVS in 3 s)", argv[2], v, version());
|
||||
} else {
|
||||
print("[cfg] unknown field '%s'", argv[2]);
|
||||
help();
|
||||
@@ -247,7 +259,18 @@ void setExtraCommandHandler(bool (*handler)(const char* line)) {
|
||||
g_extra_handler = handler;
|
||||
}
|
||||
|
||||
void flush() {
|
||||
lock();
|
||||
if (g_dirty) {
|
||||
save();
|
||||
g_dirty = false;
|
||||
}
|
||||
unlock();
|
||||
}
|
||||
|
||||
void pollSerial() {
|
||||
if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush();
|
||||
|
||||
while (Serial.available()) {
|
||||
char c = (char)Serial.read();
|
||||
if (c == '\r' || c == '\n') {
|
||||
|
||||
@@ -58,6 +58,13 @@ bool handleCommand(const char* line);
|
||||
*/
|
||||
void pollSerial();
|
||||
|
||||
/**
|
||||
* Write pending edits to NVS now. Edits are otherwise saved SAVE_IDLE_MS after
|
||||
* the last change (each flash write flickers the RGB panel). Call before a
|
||||
* reboot or when leaving the Tuning screen.
|
||||
*/
|
||||
void flush();
|
||||
|
||||
/**
|
||||
* Register a second console command handler (e.g. DiagProbe::handleCommand)
|
||||
* that gets lines `cfg` does not recognise. Returns true if it consumed the line.
|
||||
|
||||
@@ -334,6 +334,7 @@ namespace TuningScreen
|
||||
{
|
||||
if (lv_event_get_code(e) != LV_EVENT_CLICKED)
|
||||
return;
|
||||
Tunables::flush(); // write pending edits now rather than after the idle delay
|
||||
DrivelineScreen::show();
|
||||
}
|
||||
|
||||
@@ -584,7 +585,7 @@ namespace TuningScreen
|
||||
{
|
||||
build();
|
||||
refreshFromTunables();
|
||||
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
|
||||
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
|
||||
}
|
||||
|
||||
void tick()
|
||||
|
||||
@@ -73,6 +73,11 @@ void applySavedStatesToUI() {
|
||||
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
// The SquareLine project ships the WiFi switch with LV_STATE_DISABLED (since
|
||||
// the first export), which swallows every touch. Wi-Fi is needed to join a
|
||||
// network for OTA updates, so re-enable it here - survives re-exports.
|
||||
lv_obj_clear_state(uic_Toggle_Wifi_Switch, LV_STATE_DISABLED);
|
||||
|
||||
// Apply WiFi state
|
||||
if (current_wifi_state) {
|
||||
lv_obj_add_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
|
||||
#include "wifi_manager.h"
|
||||
#include "espnow_link.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
|
||||
// External UI element references (from ui_Settings_Screen.c)
|
||||
@@ -91,10 +92,15 @@ static String formatNetworkName(const wifi_network_t& network) {
|
||||
* @note Must be called with LVGL lock held OR will acquire lock internally
|
||||
*/
|
||||
static void showConnectionResult(bool success, const char* message) {
|
||||
lvgl_port_lock(0);
|
||||
// Wait for the lock (a 0 ms try-lock whose result was ignored used to race
|
||||
// the LVGL task). Widgets are NULL whenever the Settings screen isn't
|
||||
// loaded - e.g. a `wifi join` from the console - so check before touching.
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
// Hide loading spinner
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
if (uic_Settings_Loading_Container != NULL) {
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
// Connection successful
|
||||
@@ -331,7 +337,7 @@ static void wifiTask(void* parameter) {
|
||||
|
||||
case WIFI_UI_EVENT_TOGGLE_OFF:
|
||||
Serial.println("WiFi Task: Disabling WiFi...");
|
||||
WiFi.disconnect(true);
|
||||
WiFi.disconnect(); // NOT (true): that powers the radio off and kills ESP-NOW
|
||||
// Radio stays in STA mode: the ESP-NOW link to Controller B
|
||||
// rides on it. "WiFi off" here means scanning/association off.
|
||||
g_wifi_state = WIFI_STATE_OFF;
|
||||
@@ -358,7 +364,7 @@ static void wifiTask(void* parameter) {
|
||||
g_wifi_state = WIFI_STATE_CONNECTED; // Will be updated based on result
|
||||
|
||||
// Attempt connection
|
||||
WiFi.disconnect(true); // Clear any previous connection
|
||||
WiFi.disconnect(); // Clear any previous connection (radio stays on: ESP-NOW rides on it)
|
||||
delay(100);
|
||||
|
||||
if (strlen(creds->password) > 0) {
|
||||
@@ -401,7 +407,7 @@ static void wifiTask(void* parameter) {
|
||||
|
||||
case WIFI_UI_EVENT_DISCONNECT:
|
||||
Serial.println("WiFi Task: Disconnecting...");
|
||||
WiFi.disconnect(true);
|
||||
WiFi.disconnect(); // NOT (true): that powers the radio off and kills ESP-NOW
|
||||
g_wifi_state = WIFI_STATE_SCANNING;
|
||||
g_wifi_scan_requested = true;
|
||||
break;
|
||||
@@ -757,4 +763,44 @@ void onSelectSSID(lv_event_t *e) {
|
||||
Serial.println("onSelectSSID() called - but dynamic buttons handle clicks now");
|
||||
}
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// CONSOLE (`wifi ...`) - join a network without the Settings screen, e.g. for OTA
|
||||
// ============================================================================
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
char buf[128];
|
||||
strncpy(buf, line, sizeof(buf) - 1);
|
||||
buf[sizeof(buf) - 1] = 0;
|
||||
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], "wifi") != 0) return false;
|
||||
|
||||
if (argc >= 3 && !strcmp(argv[1], "join")) {
|
||||
// SSIDs with spaces aren't supported here; use the Settings screen.
|
||||
Serial.printf("[wifi] joining '%s'...\n", argv[2]);
|
||||
connectToWiFi(argv[2], argc >= 4 ? argv[3] : NULL); // result logged by the WiFi task
|
||||
} else if (argc == 2 && !strcmp(argv[1], "off")) {
|
||||
wifi_queue_event_t evt = {WIFI_UI_EVENT_TOGGLE_OFF, NULL};
|
||||
if (g_wifi_event_queue) xQueueSend(g_wifi_event_queue, &evt, 0);
|
||||
Serial.println("[wifi] scanning/association off (radio stays up for ESP-NOW)");
|
||||
} else if (argc == 2 && !strcmp(argv[1], "status")) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.printf("[wifi] connected to '%s', IP %s, RSSI %d dBm, channel %d\n",
|
||||
WiFi.SSID().c_str(), WiFi.localIP().toString().c_str(),
|
||||
(int)WiFi.RSSI(), (int)WiFi.channel());
|
||||
} else {
|
||||
Serial.printf("[wifi] not connected (state %d), channel %d\n", (int)g_wifi_state, (int)WiFi.channel());
|
||||
}
|
||||
Serial.printf("[wifi] ESP-NOW %s, sent %lu, failed %lu\n", EspNowLink::isReady() ? "ready" : "DOWN",
|
||||
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount());
|
||||
} else {
|
||||
Serial.println("wifi status connection, IP, channel, ESP-NOW health");
|
||||
Serial.println("wifi join <ssid> [pass] join a network (no spaces in the SSID)");
|
||||
Serial.println("wifi off stop scanning/association (radio stays on)");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace WiFiManager
|
||||
|
||||
@@ -113,6 +113,12 @@ wifi_state_t getState();
|
||||
*/
|
||||
uint8_t getNetworkCount();
|
||||
|
||||
/**
|
||||
* @brief Console handler for `wifi status | join <ssid> [pass] | off`.
|
||||
* @return false if the line isn't a wifi command
|
||||
*/
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS (Called from SquareLine Studio UI)
|
||||
// ============================================================================
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF
|
||||
Y9brIfDTgn8IOWBm8J4nmLUef7zU4ydPM5BKXqUrTshJEpLd74GJIIOtkg==
|
||||
-----END PUBLIC KEY-----
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
---
|
||||
type: index
|
||||
updated: 2026-09-23
|
||||
updated: 2026-09-26
|
||||
---
|
||||
|
||||
# Index
|
||||
@@ -20,6 +20,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
|
||||
- [[driveline-speed-signals]] — **engine / turbine / output-shaft speeds**: turbine speed as physical proof of gear engagement, and the output-shaft field that is our **only road-speed source** (no DSC on this bus) — the feedback variable for a future cruise-control PoC, with the safety envelope that would require
|
||||
- [[dual-controller-architecture]] — Controller A → UART1 + ESP-NOW, protocol v2 → Controller B (1.3" display + Patrol gauge outputs); A owns alerts and the gauge tunables (`cfg` console)
|
||||
- [[obd-diagnostic-polling]] — **why boost / MAF / rail / injection / DTCs never appear on the sniffer** and how a tester gets them: Route A generic OBD-II mode 01 on `0x7DF` and Route B BMW KWP on `0x6F1` → `0x612` — **BOTH VERIFIED WORKING 2026-09-23** (minimal PID set, no boost PID, mode 09 silent; `1A 86` ident identifies the donor; DTCs read via mode 03), the capture-with-Launch procedure (still wanted for the `22 D1xx` live-data identifiers), and why polling is a transmit-on-the-bus design decision
|
||||
- [[ota-updates]] — **Controller A updates itself from Gitea releases**: tag `v*` → CI builds + signs (ECDSA P-256) → `ota install` (manual, parked, Wi-Fi) pulls over HTTPS from the public repo, verifies, flashes the idle slot, 30 s confirm-or-rollback; **verified end-to-end 2026-09-26 (dev → v0.1.1)**; dual-slot partition table; plan for updating Controller B through A over ESP-NOW
|
||||
|
||||
## Synthesis
|
||||
|
||||
|
||||
+16
@@ -109,3 +109,19 @@ The capture-with-Launch session, finally run (engine idling, our read-only seria
|
||||
## [2026-09-23] lint | Clarify self-poll requirements; record Diagnostics-screen plan
|
||||
|
||||
Tightened the live-data findings after checking the full capture: the Launch used only 1A/2C/22/23 - NO 10 (session), 27 (security), or 3E (tester-present). So self-polling a 2C value (e.g. rail pressure) needs only the 2C 10 15E0 define + 2C 10 00DF poll, no secret; the earlier 21-block NRCs (0x22/0x33) are a different mechanism and do not gate 2C. Corrected the "needs session/define handshake" wording in launch-capture-2026-09-23.md and obd-diagnostic-polling. Recorded the design decision (user, 2026-09-23): active polling, if built, lives behind a password-protected Diagnostics screen (authorized-tech gate, manual, refuses while scan tool connected, read-oriented services) - open-questions #12, and a project memory so the capability is not re-researched later.
|
||||
|
||||
## [2026-09-26] build | OTA updates for Controller A
|
||||
|
||||
Repartitioned A to dual OTA slots (2 x 7.9 MB, SPIFFS dropped, nvs/otadata offsets kept - tunables v150 survived the one-time USB flash on COM10, verified). New src/modules/ota_update.cpp + include/config/ota_config.h: manual `ota status|check|install|rollback` console; HTTPS pull from the (now public) Gitea repo's latest release, ECDSA P-256 signature over "patrol-a|version|sha256" checked before download, image hashed while streaming, parked gate before download and before slot switch, rollback via verifyRollbackLater() override + 30 s confirm. TLS trusts ISRG Root X1 + Root YR (both verified against the server chain). CI: .gitea/workflows/firmware.yml (main -> rolling unsigned pre-release main-latest; v* tag -> signed release with manifest.txt). Decisions: manual trigger (future Diagnostics screen), public repos instead of a device token, Controller B to be updated by A over ESP-NOW (wire is one-way). Wrote pages/ota-updates.md. Pending: BMW_NISSAN_FIRMWARE_SIGNING_KEY repo secret, enable repo Actions, first v* tag to test end-to-end.
|
||||
|
||||
## [2026-09-26] build | OTA bring-up: Wi-Fi switch, ESP-NOW, memory
|
||||
|
||||
First CI runs green (main-latest built with version main-1ec93dc baked in; v0.1.0 signed release verified off-device: sha256 + signature + /releases/latest). Bring-up on the board found: (1) the Settings Wi-Fi switch has been LV_STATE_DISABLED since the first SquareLine export - re-enabled at runtime; (2) WiFi.disconnect(true) in the Wi-Fi task powered the radio off and killed ESP-NOW whenever Wi-Fi was used - fixed + ESP-NOW self-heal; (3) internal RAM has 15.9 KB free / 7.6 KB largest block with Wi-Fi up, so neither a TLS task stack nor mbedtls's internal-only buffers fit - OTA jobs now run in the loop task with mbedtls routed to PSRAM; `ota check` then worked on-device (signature verified on the board, 3.6 KB stack headroom). Added `wifi join|status|off` console. v0.1.0 must not be installed (pre-fix OTA can't run once installed). Updated pages/ota-updates.md, CLAUDE.md.
|
||||
|
||||
## [2026-09-26] verify | First OTA update end-to-end
|
||||
|
||||
Bench (home, both controllers on laptop USB, no car): A running USB-flashed `dev` ran `ota install` -> v0.1.1 from the signed CI release: 1.65 MB in ~60 s, verified, rebooted into app1, confirmed after 30 s (rollback cancelled). v0.1.1 then passed `ota check` ("up to date"), so OTA-from-OTA works. ota-updates.md marked VERIFIED.
|
||||
|
||||
## [2026-09-26] build | Display quick fixes (v0.1.2)
|
||||
|
||||
User reported heavy flicker during OTA and on Gauge Tuning taps, and laggy swipes. Diagnosis: flash and PSRAM share the MSPI cache; every flash write (OTA, or the NVS save on each Tuning tap) stalls the PSRAM framebuffer the RGB panel streams from, with no bounce buffer (ESP_PANEL_LCD_RGB_BOUNCE_BUF_SIZE=0) - a known ESP32-S3 RGB issue. Swipes: every transition was LV_SCR_LOAD_ANIM_FADE_ON 100 ms - a full 1024x600 software re-render + alpha blend per frame. Also: the Debug "FPS" counts loop() passes (loop sleeps 100 ms), not rendering - real render FPS has never been measured. Quick fixes: instant screen switches; Tunables NVS writes deferred to 3 s idle / leaving Tuning; backlight off during OTA writes with before/after notices; firmware version label bottom-right on every screen. Real cure (bounce buffers + SPIRAM_XIP_FROM_PSRAM via custom_sdkconfig, needs internal RAM freed first) is planned as one measured bench session with open-questions #13.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
type: synthesis
|
||||
tags: [meta, todo]
|
||||
updated: 2026-09-23
|
||||
updated: 2026-09-26
|
||||
---
|
||||
|
||||
# Open Questions
|
||||
@@ -24,7 +24,7 @@ The research frontier. Answering any of these should trigger updates across the
|
||||
|
||||
## Design decisions (parked, not blocking)
|
||||
|
||||
12. **The "Diagnostics" screen (planned 2026-09-23).** Active diagnostic polling — replaying the `2C` live-data reads we decoded ([[launch-capture-2026-09-23]]) so values like rail pressure appear on Controller A without the Launch — is now technically unblocked (no session/security needed). Intended design when built: a **password-protected Diagnostics screen**, authorized-technician access only, manual trigger, refuses while a scan tool is connected, read-oriented services only. The same gate covers the general transmit-on-the-bus decision. This is deliberately deferred, but the capability, the byte sequences, and these guard rails are recorded so the work resumes from here, not from scratch. → [[obd-diagnostic-polling]], [[dual-controller-architecture]]
|
||||
12. **The "Diagnostics" screen (planned 2026-09-23).** Active diagnostic polling — replaying the `2C` live-data reads we decoded ([[launch-capture-2026-09-23]]) so values like rail pressure appear on Controller A without the Launch — is now technically unblocked (no session/security needed). Intended design when built: a **password-protected Diagnostics screen**, authorized-technician access only, manual trigger, refuses while a scan tool is connected, read-oriented services only. The same gate covers the general transmit-on-the-bus decision. This is deliberately deferred, but the capability, the byte sequences, and these guard rails are recorded so the work resumes from here, not from scratch. **Also the home of the OTA "check / install" controls (2026-09-26)** — today they are the `ota` console; the password must be stored as a salted hash in NVS because the firmware is public. → [[obd-diagnostic-polling]], [[dual-controller-architecture]], [[ota-updates]]
|
||||
|
||||
## Project context
|
||||
|
||||
@@ -69,3 +69,5 @@ The research frontier. Answering any of these should trigger updates across the
|
||||
- ~~Web search on DDE7 M57 PIDs~~ ✅ clipped → [[google-ai-dde7m57-pids]] — uncited AI summary; identifiers `(unverified)`, addressing claim contradicted
|
||||
- ~~A worked generic-PID set for an M57 diesel~~ ✅ ingested → [[dwr-335d-torque-pids]] (2009 335d, DDE7.3; J1979 mode-01 scalings gauge-checked by the author)
|
||||
- DWR's **Testo parameter list** (e90post "Testo" thread, post 175, German→English names of the DDE's non-standard values) — the pointer for Route B identifiers if our own Launch capture is not enough
|
||||
|
||||
13. **Internal RAM is nearly exhausted (found 2026-09-26).** With display + Wi-Fi up: 15.9 KB internal free, largest block 7.6 KB (PSRAM 7.1 MB free). OTA works around it ([[ota-updates]]), but anything else that needs an internal allocation (another task, a TLS client, a bigger Wi-Fi burst) can fail. Biggest known consumer: the LVGL 60-line DMA draw buffer (~120 KB). Options: shrink it to ~30–40 lines, or measure what else lives in internal RAM first (`heap_caps_print_heap_info`). Not urgent, but it limits every future feature. **Same project as the display flicker/lag (2026-09-26):** flash writes flicker the PSRAM-fed RGB panel (no bounce buffer) and full-screen transitions stutter. Espressif's cure is bounce buffers + `CONFIG_SPIRAM_XIP_FROM_PSRAM` (needs pioarduino `custom_sdkconfig`), and bounce buffers need internal RAM — so free RAM, add bounce buffers, and measure real render FPS (LVGL perf monitor; the Debug "FPS" counts `loop()` passes, not frames) in one bench session. Quick mitigations shipped in v0.1.2 (instant screen switches, deferred NVS saves, dark screen during OTA).
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [ota, firmware, gitea, ci, security, signing, design-decision, controller-a]
|
||||
updated: 2026-09-26
|
||||
---
|
||||
|
||||
# OTA Firmware Updates
|
||||
|
||||
How Controller A updates itself from this repo's Gitea releases, why each piece is the way it is, and what is still to do (Controller B). Built 2026-09-26. Design decisions by the user are marked **(decision)**.
|
||||
|
||||
## The pipeline
|
||||
|
||||
```
|
||||
git push tag vX.Y.Z ──► Gitea Actions (.gitea/workflows/firmware.yml, runner ubuntu-latest)
|
||||
pio run (-DFW_VERSION="vX.Y.Z")
|
||||
sign "patrol-a|vX.Y.Z|<sha256>" with secret BMW_NISSAN_FIRMWARE_SIGNING_KEY
|
||||
release vX.Y.Z: firmware.bin + firmware.elf + manifest.txt
|
||||
│ public repo, HTTPS, no token
|
||||
Controller A `ota install` ◄──────┘ (parked, Wi-Fi joined)
|
||||
GET /api/v1/repos/art/ESP32-S3-Touch-LCD-5B/releases/latest → tag
|
||||
GET /releases/download/<tag>/manifest.txt → verify signature FIRST
|
||||
GET /releases/download/<tag>/firmware.bin → idle slot, hashed while streaming
|
||||
sha256 == signed sha256 → esp_ota_end → parked again? → switch slot → reboot
|
||||
new image PENDING_VERIFY → confirmed after 30 s uptime, else bootloader rolls back
|
||||
```
|
||||
|
||||
Push to `main` (no tag) builds a rolling **pre-release `main-latest`** — unsigned, no manifest, for bench/USB testing. `/releases/latest` skips pre-releases, so the car is never offered it `(repo)`.
|
||||
|
||||
## Status: VERIFIED end-to-end `(verified 2026-09-26, bench, USB power, Wi-Fi Personal1)`
|
||||
|
||||
`dev` (USB-flashed) → `ota install` → **v0.1.1** from CI: 1.65 MB downloaded + written in ~60 s (~27 KB/s), sha256 + signature OK, rebooted into `app1` as PENDING_VERIFY, ESP-NOW up, **confirmed after 30 s**. The installed v0.1.1 then ran `ota check` itself ("up to date") — it can take the next update. Previous image kept in `app0` for `ota rollback`.
|
||||
|
||||
During the write the backlight is off (flash writes flicker the PSRAM-fed panel): a full-screen notice "Updating to vX … do not switch off" shows for 3 s first, then "Installed vX / Restarting" or "Update failed / still running vY" (v0.1.2+). The running version is always shown bottom-right on every screen.
|
||||
|
||||
Known quirk: `ota status` shows the *other* slot's "built" date from the framework's precompiled app descriptor (e.g. "Nov 4 2025"), not our build time — ignore it.
|
||||
|
||||
## Decisions and why
|
||||
|
||||
- **Manual trigger only (decision, 2026-09-26).** An install ends in a reboot, which blanks Controller B's gauges; nothing checks or installs in the background. Today the trigger is the `ota` serial console; the intended home is the password-gated **Diagnostics screen** ([[open-questions]] #12), the same gate as active CAN polling.
|
||||
- **Parked gate** `(repo)`: refused if engine rpm > 0 / run state running or starting, output shaft turning, or lever in a drive gear. A silent bus (>2 s no frames: ignition off, bench) counts as parked. Checked before the download **and again** before the slot switch. `ota check` is exempt (read-only).
|
||||
- **HTTPS pull from a public repo (decision).** Both repos were made public 2026-09-26 so the device needs **no token** — the same reasoning as `parking_solution`'s public releases mirror: a read token in shipped firmware leaks with the device. History was scanned before/after going public: no secrets, no full VIN (only the 10-char prefix in ident logs), no SSIDs `(verified 2026-09-26)`.
|
||||
- **Signed images (decision).** HTTPS only proves the file came from the server; the ECDSA P-256 signature proves it came from our CI key. The signed statement is `target|version|sha256`, so a Controller B image can't be installed on A even with a shared key, and the manifest version can't be swapped. The firmware contains no secrets, so public binaries are fine — **keep it that way**: the future Diagnostics-screen password must be a salted hash in NVS, never a literal in source.
|
||||
- **TLS trust = Let's Encrypt roots, not the leaf** `(verified 2026-09-26)`: the server chain is leaf (SAN `git.infra.msai.al`) → YR2 → Root YR (cross-signed by ISRG Root X1). Both ISRG Root X1 (to 2035) and Root YR (to 2045) are embedded in `include/config/ota_config.h`, and each verifies the chain alone. Leaf certs rotate ~90 days — never pin them. The framework's mbedtls has `MBEDTLS_HAVE_TIME_DATE` off, so no NTP is needed (and cert dates aren't checked; the signature is the real guarantee).
|
||||
- **Rollback**: the framework bootloader has `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y`, but Arduino's `initArduino()` marks a new image valid *before* `setup()`. `ota_update.cpp` overrides `verifyRollbackLater()` → the image stays PENDING_VERIFY until `Ota::tick()` confirms it after 30 s. Consequence: **power off within 30 s of an update's first boot = back to the old version** (by design).
|
||||
|
||||
## Memory: why jobs run in the loop task `(verified 2026-09-26)`
|
||||
|
||||
With the display, Wi-Fi and all tasks up, **internal RAM is nearly exhausted: 15.9 KB free, largest block 7.6 KB** (PSRAM: 7.1 MB free). Two consequences, both handled in `ota_update.cpp`:
|
||||
|
||||
- This framework's mbedtls is built with `CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y` (~40 KB internal per TLS session → impossible). During a job, `mbedtls_platform_set_calloc_free()` routes TLS to PSRAM, and restores it after (both sides free with `heap_caps_free`, so the swap is safe).
|
||||
- No room for a dedicated 10–16 KB task stack, and a PSRAM stack is forbidden because `esp_ota_write()` disables the flash cache. So jobs run **inside the Arduino loop task** (8 KB internal stack): `ota check` peaked leaving **3.6 KB headroom**. The console and screen value ticks pause while a job runs.
|
||||
|
||||
The low internal heap is a system-wide risk beyond OTA (the LVGL 60-line DMA draw buffer alone is ~120 KB of internal SRAM) — see [[open-questions]].
|
||||
|
||||
## Partition table (changed 2026-09-26)
|
||||
|
||||
| Name | Offset | Size |
|
||||
|---|---|---|
|
||||
| nvs | 0x9000 | 20 KB — **unchanged offset, settings survive** |
|
||||
| otadata | 0xE000 | 8 KB |
|
||||
| app0 (ota_0) | 0x10000 | 7.9 MB |
|
||||
| app1 (ota_1) | 0x800000 | 7.9 MB |
|
||||
| coredump | 0xFF0000 | 64 KB |
|
||||
|
||||
SPIFFS (3.4 MB, unused by any code) was dropped. Firmware is ~1.65 MB (19.8 % of a slot). Moving to this layout needed **one USB flash** (done 2026-09-26 on COM10; tunables v150 survived — `(verified)`).
|
||||
|
||||
## Console
|
||||
|
||||
| Command | What |
|
||||
|---|---|
|
||||
| `ota status` | version, build time, running slot + state, other slot's image |
|
||||
| `ota check` | latest release vs running, signature checked (Wi-Fi only, no parked gate) |
|
||||
| `ota install [force]` | full install; `force` reinstalls the same version |
|
||||
| `ota rollback` | boot the other slot (or reject an unconfirmed image) — parked only |
|
||||
|
||||
Wi-Fi must be joined first — `wifi join <ssid> [pass]` on the console (`wifi status`, `wifi off`), or the Settings screen. **Do not install `v0.1.0`**: it predates the loop-task/PSRAM-TLS fix, so once installed it can't run OTA again (it boots fine, so rollback won't save it — USB only). Joining an AP moves the radio channel; the ESP-NOW link to B follows it (B hops). `diag raw off` first keeps CANRAW from burying the progress lines. The screen may flicker while flash is written (RGB panel + flash cache) `(unverified)`.
|
||||
|
||||
## Secrets and keys
|
||||
|
||||
- `BMW_NISSAN_FIRMWARE_SIGNING_KEY` — Gitea **repo secret** (Settings → Actions → Secrets), the EC P-256 private key PEM. Generated 2026-09-26; keep an offline backup. Losing it means devices only accept updates after one USB flash with a new public key.
|
||||
- Public key: compiled in (`OTA_SIGNING_PUBKEY_PEM`) and in `tools/ota/firmware_signing_pub.pem` (CI self-checks each signature against it before publishing).
|
||||
- Rotating the key: new keypair → update both public-key copies → USB-flash once (a device only trusts the key it was built with).
|
||||
|
||||
## Bugs found while bringing it up (2026-09-26)
|
||||
|
||||
- **Settings Wi-Fi switch was disabled since the first SquareLine export** (`LV_STATE_DISABLED`) — the Wi-Fi UI had never worked. Re-enabled at runtime in `UIStateManager` (survives re-exports; untick "Disabled" in the SquareLine project too).
|
||||
- **Joining Wi-Fi killed ESP-NOW**: the Wi-Fi task used `WiFi.disconnect(true)` (true = radio off), which drops ESP-NOW; B then ran on the wire only. Now `WiFi.disconnect()`, and `EspNowLink::send()` re-initialises ESP-NOW if the driver ever drops it. Verified: joined Personal1 (channel 9), ESP-NOW 195 sent / 0 failed.
|
||||
- `showConnectionResult()` took the LVGL lock with a 0 ms try-lock, ignored the result, and touched widgets that are NULL off the Settings screen — now waits for the lock and null-checks. It still shows **no success feedback** on screen; the Wi-Fi UI needs a redesign (user: "a disaster UX").
|
||||
|
||||
## Controller B (not built yet)
|
||||
|
||||
Plan agreed 2026-09-26: B is updated **by A over ESP-NOW**, not by the RS485 wire (the wire is one-way A→B; ESP-NOW is bidirectional and faster). A downloads B's signed image (target `patrol-b`) from B's repo releases, sends it with acks, B verifies the signature and swaps slots with the same rollback scheme. Prerequisites: B moves off the stock `default.csv` (1.25 MB slots, 1.07 MB firmware → too tight) to a 16 MB layout (confirm B's flash size first; one USB flash); ESP-NOW pairing/encryption so only A can talk to B; protocol frames for the transfer (shared `automotive_data.h` → version bump in both repos). B's repo still answered 404 anonymously on 2026-09-26 — check its visibility setting. Wire stays for gauge-data redundancy.
|
||||
|
||||
## Related
|
||||
|
||||
[[dual-controller-architecture]] · [[esp32-s3-touch-lcd-5b]] · [[open-questions]] · [[obd-diagnostic-polling]]
|
||||
Reference in New Issue
Block a user