Compare commits
8 Commits
main-latest
...
v0.1.4
| Author | SHA1 | Date | |
|---|---|---|---|
| 766019a01e | |||
| 842f270398 | |||
| 29711fa25e | |||
| 51fd4a868a | |||
| eb9cbd985f | |||
| 0a76cd8c0e | |||
| bb0895674a | |||
| f5b7f43e7c |
@@ -19,6 +19,12 @@ name: Firmware
|
|||||||
#
|
#
|
||||||
# Releases go through the Gitea API with plain curl (actions/upload-artifact
|
# Releases go through the Gitea API with plain curl (actions/upload-artifact
|
||||||
# is unreliable on this runner - same pattern as parking_solution).
|
# is unreliable on this runner - same pattern as parking_solution).
|
||||||
|
#
|
||||||
|
# A main push skips itself (step "Skip?") when (a) the commit already carries a
|
||||||
|
# v* tag - the tag build covers it; release with ONE push so the tag exists
|
||||||
|
# when this runs: git push --follow-tags origin main - or (b) it only
|
||||||
|
# changes docs (wiki/**, *.md). Done in-job rather than with paths-ignore so a
|
||||||
|
# tag build can never be skipped by a path filter. Tag builds always run.
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -33,7 +39,29 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
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
|
||||||
|
# (a) already tagged v* ? (annotated tags list their commit as <tag>^{})
|
||||||
|
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
|
||||||
|
# (b) docs only? Needs the previous head; a new branch / force push just builds.
|
||||||
|
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
|
- name: Version
|
||||||
|
if: env.SKIP != 'true'
|
||||||
run: |
|
run: |
|
||||||
if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
|
if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
|
||||||
VERSION="${GITHUB_REF_NAME}"
|
VERSION="${GITHUB_REF_NAME}"
|
||||||
@@ -46,6 +74,7 @@ jobs:
|
|||||||
echo "version: ${VERSION}"
|
echo "version: ${VERSION}"
|
||||||
|
|
||||||
- name: Cache PlatformIO
|
- name: Cache PlatformIO
|
||||||
|
if: env.SKIP != 'true'
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
@@ -55,6 +84,7 @@ jobs:
|
|||||||
key: pio-${{ hashFiles('platformio.ini') }}
|
key: pio-${{ hashFiles('platformio.ini') }}
|
||||||
|
|
||||||
- name: Install PlatformIO
|
- name: Install PlatformIO
|
||||||
|
if: env.SKIP != 'true'
|
||||||
run: |
|
run: |
|
||||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||||
export PATH="$HOME/.local/bin:$PATH"
|
export PATH="$HOME/.local/bin:$PATH"
|
||||||
@@ -62,6 +92,7 @@ jobs:
|
|||||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
|
if: env.SKIP != 'true'
|
||||||
run: |
|
run: |
|
||||||
export PLATFORMIO_BUILD_FLAGS="-DFW_VERSION=\\\"${VERSION}\\\""
|
export PLATFORMIO_BUILD_FLAGS="-DFW_VERSION=\\\"${VERSION}\\\""
|
||||||
pio run
|
pio run
|
||||||
@@ -72,7 +103,7 @@ jobs:
|
|||||||
ls -la dist/
|
ls -la dist/
|
||||||
|
|
||||||
- name: Sign + manifest (tags only)
|
- name: Sign + manifest (tags only)
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
if: env.SKIP != 'true' && startsWith(github.ref, 'refs/tags/')
|
||||||
env:
|
env:
|
||||||
BMW_NISSAN_FIRMWARE_SIGNING_KEY: ${{ secrets.BMW_NISSAN_FIRMWARE_SIGNING_KEY }}
|
BMW_NISSAN_FIRMWARE_SIGNING_KEY: ${{ secrets.BMW_NISSAN_FIRMWARE_SIGNING_KEY }}
|
||||||
run: |
|
run: |
|
||||||
@@ -93,6 +124,7 @@ jobs:
|
|||||||
cat dist/manifest.txt
|
cat dist/manifest.txt
|
||||||
|
|
||||||
- name: Publish release
|
- name: Publish release
|
||||||
|
if: env.SKIP != 'true'
|
||||||
env:
|
env:
|
||||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
API: ${{ github.api_url }}
|
API: ${{ github.api_url }}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ Use PlatformIO extension toolbar:
|
|||||||
The application uses **dual-core architecture** to maximize performance:
|
The application uses **dual-core architecture** to maximize performance:
|
||||||
|
|
||||||
- **Core 1** (Arduino core): LVGL rendering task (Priority 2)
|
- **Core 1** (Arduino core): LVGL rendering task (Priority 2)
|
||||||
- UI rendering at ~50 FPS @ 1024x600 resolution
|
- UI rendering @ 1024x600 (real render FPS never measured - the Debug "FPS" counts loop() passes)
|
||||||
- Touch input handling
|
- Touch input handling
|
||||||
- CPU load ~80% under normal operation
|
- CPU load ~80% under normal operation
|
||||||
|
|
||||||
@@ -157,10 +157,13 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
|||||||
- Event types: `WIFI_UI_EVENT_TOGGLE_ON/OFF`, `WIFI_UI_EVENT_SCAN_START`, `WIFI_UI_EVENT_CONNECT`, `WIFI_UI_EVENT_DISCONNECT`
|
- Event types: `WIFI_UI_EVENT_TOGGLE_ON/OFF`, `WIFI_UI_EVENT_SCAN_START`, `WIFI_UI_EVENT_CONNECT`, `WIFI_UI_EVENT_DISCONNECT`
|
||||||
- Shared data protection: `g_wifi_mutex` (FreeRTOS semaphore) guards `g_scanned_networks[]` array
|
- Shared data protection: `g_wifi_mutex` (FreeRTOS semaphore) guards `g_scanned_networks[]` array
|
||||||
|
|
||||||
|
**Scanning**: only while the network list is on screen (`uic_Wifi_Container != NULL`) and not connected - background scans every 10 s caused display glitches (Wi-Fi buffers share PSRAM with the framebuffer) and hop the radio ESP-NOW uses.
|
||||||
|
|
||||||
**Dynamic SSID Buttons**:
|
**Dynamic SSID Buttons**:
|
||||||
- WiFi scan results create dynamically-generated LVGL buttons (`lv_btn_create()` in `updateSSIDList()`)
|
- WiFi scan results create dynamically-generated LVGL buttons (`lv_btn_create()` in `updateSSIDList()`)
|
||||||
- Button array: `g_ssid_buttons[WIFI_SCAN_MAX_NETWORKS]` (max 20 networks)
|
- Button array: `g_ssid_buttons[WIFI_SCAN_MAX_NETWORKS]` (max 20 networks)
|
||||||
- Each button stores network index in user data: `lv_obj_set_user_data(btn, (void*)(intptr_t)i)`
|
- Each button stores network index in user data: `lv_obj_set_user_data(btn, (void*)(intptr_t)i)`
|
||||||
|
- Each button clears its own `g_ssid_buttons[]` slot on `LV_EVENT_DELETE`: SquareLine deletes the whole Settings screen when it is left, and stale pointers here corrupted LVGL's heap
|
||||||
- Click handler: `onSSIDButtonClick()` → shows password entry UI (keyboard + text area) for secured networks, or connects directly for open networks
|
- Click handler: `onSSIDButtonClick()` → shows password entry UI (keyboard + text area) for secured networks, or connects directly for open networks
|
||||||
|
|
||||||
**Connection Flow**:
|
**Connection Flow**:
|
||||||
@@ -223,7 +226,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
|||||||
|
|
||||||
### Tunables (gauge calibration, alert thresholds)
|
### 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)
|
### Diagnostic probe (`diag` console)
|
||||||
|
|
||||||
@@ -231,11 +234,11 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
|||||||
|
|
||||||
### OTA updates (`ota` console)
|
### 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. Details: `wiki/pages/ota-updates.md`.
|
`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`). Release with one push so only the tag build runs: `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin main` (a main push skips itself when its commit is tagged, or when it only touches `wiki/**` / `*.md`). 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
|
### 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
|
### UI State Synchronization
|
||||||
|
|
||||||
@@ -247,7 +250,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`
|
- Syncs toggle switches with actual service states: `g_wifi_state`, `g_uart_state`, `g_debug_enabled`
|
||||||
- Shows loading spinner during sync for smooth UX
|
- 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**:
|
**Debug Mode**:
|
||||||
- Toggle in Settings screen shows/hides `uic_Device_State_Container`
|
- Toggle in Settings screen shows/hides `uic_Device_State_Container`
|
||||||
@@ -280,7 +283,8 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
|
|||||||
|
|
||||||
**include/lv_conf.h**
|
**include/lv_conf.h**
|
||||||
- LVGL 8.4.0 configuration
|
- LVGL 8.4.0 configuration
|
||||||
- Memory: Uses PSRAM for large objects
|
- Memory: LVGL's widget pool (`LV_MEM_SIZE`) is 512 KB in PSRAM via `LV_MEM_POOL_ALLOC` (was 48 KB internal and ran out). `mem` on the console prints internal heap, PSRAM and pool use/fragmentation
|
||||||
|
- Asserts: `LV_ASSERT_HANDLER` is `abort()` (backtrace + core dump + reboot), never `while(1)`, which froze the UI while holding the LVGL lock
|
||||||
- Theme: Material theme enabled
|
- Theme: Material theme enabled
|
||||||
|
|
||||||
## Common Patterns
|
## Common Patterns
|
||||||
@@ -355,7 +359,7 @@ xTaskCreatePinnedToCore(
|
|||||||
|
|
||||||
- **CAN Bus**: GPIO 15 (TX), GPIO 16 (RX) - 500 Kbps, TWAI_MODE_NORMAL, onboard TJA1051 on the terminal block
|
- **CAN Bus**: GPIO 15 (TX), GPIO 16 (RX) - 500 Kbps, TWAI_MODE_NORMAL, onboard TJA1051 on the terminal block
|
||||||
- **UART1**: GPIO 44 (TX), GPIO 43 (RX, unused) - reaches the terminal block only as the RS485 A/B pair (SP3485), 115200 baud. Bench: `485_A` straight into B's IO1 + GND works (verified 2026-09-21)
|
- **UART1**: GPIO 44 (TX), GPIO 43 (RX, unused) - reaches the terminal block only as the RS485 A/B pair (SP3485), 115200 baud. Bench: `485_A` straight into B's IO1 + GND works (verified 2026-09-21)
|
||||||
- **USB Serial**: UART0 (default Serial) - 115200 baud for debug output
|
- **USB Serial**: native USB-CDC (`Serial`, 303A:1001). Opening the port with default DTR/RTS resets the board - attach with `pio device monitor -p COM10 --dtr 0 --rts 0 --echo`
|
||||||
|
|
||||||
### Display Panel
|
### Display Panel
|
||||||
|
|
||||||
@@ -401,7 +405,7 @@ xTaskCreatePinnedToCore(
|
|||||||
|
|
||||||
## Performance Metrics
|
## Performance Metrics
|
||||||
|
|
||||||
- **FPS**: ~50 FPS @ 1024x600 resolution
|
- **FPS**: not measured yet (the Debug-panel counter counts loop() passes, not frames) - see wiki open-questions #13
|
||||||
- **CPU Load**: ~80% on Core 1 (LVGL rendering)
|
- **CPU Load**: ~80% on Core 1 (LVGL rendering)
|
||||||
- **WiFi Scan**: 1-3 seconds for 10-20 networks
|
- **WiFi Scan**: 1-3 seconds for 10-20 networks
|
||||||
- **UART Overhead**: +1-2% CPU @ 5Hz transmission rate
|
- **UART Overhead**: +1-2% CPU @ 5Hz transmission rate
|
||||||
|
|||||||
@@ -49,14 +49,19 @@
|
|||||||
#define LV_MEM_CUSTOM 0
|
#define LV_MEM_CUSTOM 0
|
||||||
#if LV_MEM_CUSTOM == 0
|
#if LV_MEM_CUSTOM == 0
|
||||||
/*Size of the memory available for `lv_mem_alloc()` in bytes (>= 2kB)*/
|
/*Size of the memory available for `lv_mem_alloc()` in bytes (>= 2kB)*/
|
||||||
#define LV_MEM_SIZE (48U * 1024U) /*[bytes]*/
|
/* 512 KB pool in PSRAM (2026-09-27). The old 48 KB pool lived in internal
|
||||||
|
* RAM and ran out: Settings + its Wi-Fi list is ~15 KB, and screen churn +
|
||||||
|
* fragmentation reached 87% used / 4.5 KB biggest block, then a label draw
|
||||||
|
* failed lv_mem_buf_get() -> assert. Moving it out also frees 48 KB of the
|
||||||
|
* scarce internal RAM. `mem` on the console prints the pool state. */
|
||||||
|
#define LV_MEM_SIZE (512U * 1024U) /*[bytes]*/
|
||||||
|
|
||||||
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
|
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
|
||||||
#define LV_MEM_ADR 0 /*0: unused*/
|
#define LV_MEM_ADR 0 /*0: unused*/
|
||||||
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
|
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
|
||||||
#if LV_MEM_ADR == 0
|
#if LV_MEM_ADR == 0
|
||||||
#undef LV_MEM_POOL_INCLUDE
|
#define LV_MEM_POOL_INCLUDE <esp_heap_caps.h>
|
||||||
#undef LV_MEM_POOL_ALLOC
|
#define LV_MEM_POOL_ALLOC(size) heap_caps_malloc((size), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#else /*LV_MEM_CUSTOM*/
|
#else /*LV_MEM_CUSTOM*/
|
||||||
@@ -271,8 +276,12 @@
|
|||||||
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
|
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
|
||||||
|
|
||||||
/*Add a custom handler when assert happens e.g. to restart the MCU*/
|
/*Add a custom handler when assert happens e.g. to restart the MCU*/
|
||||||
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
|
#define LV_ASSERT_HANDLER_INCLUDE <stdlib.h>
|
||||||
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
|
/* Was `while(1);`: a failed assert spun forever inside the calling task while it
|
||||||
|
* held the LVGL lock - the UI froze, loop() blocked on the lock, and only the
|
||||||
|
* link task kept running (2026-09-27). abort() panics instead: backtrace on the
|
||||||
|
* console, core dump to flash (ELF), reboot. A reboot beats a frozen screen. */
|
||||||
|
#define LV_ASSERT_HANDLER abort();
|
||||||
|
|
||||||
/*-------------
|
/*-------------
|
||||||
* Others
|
* Others
|
||||||
|
|||||||
+30
-2
@@ -1,5 +1,6 @@
|
|||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <lvgl.h>
|
#include <lvgl.h>
|
||||||
|
#include <esp_heap_caps.h>
|
||||||
#include "display/lvgl_v8_port.h" // LVGL port layer (for lvgl_port_lock/unlock)
|
#include "display/lvgl_v8_port.h" // LVGL port layer (for lvgl_port_lock/unlock)
|
||||||
#include "modules/display_init.h" // Display initialization module
|
#include "modules/display_init.h" // Display initialization module
|
||||||
#include "modules/wifi_manager.h" // WiFi manager module
|
#include "modules/wifi_manager.h" // WiFi manager module
|
||||||
@@ -113,9 +114,36 @@ void onDebugToggle(lv_event_t *e)
|
|||||||
|
|
||||||
} // extern "C"
|
} // extern "C"
|
||||||
|
|
||||||
// Console lines `cfg` doesn't recognise: diagnostic probe, then OTA.
|
// `mem`: internal heap, PSRAM, and LVGL's own pool (LV_MEM_SIZE, where every
|
||||||
|
// widget lives). Takes the LVGL lock with a timeout so a hung UI is reported
|
||||||
|
// rather than hanging the console too.
|
||||||
|
static bool memCommand(const char* line) {
|
||||||
|
if (strcmp(line, "mem") != 0) return false;
|
||||||
|
SerialLock::lock();
|
||||||
|
Serial.printf("[mem] internal free %u (largest block %u), PSRAM free %u\n",
|
||||||
|
(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));
|
||||||
|
SerialLock::unlock();
|
||||||
|
if (!lvgl_port_lock(500)) {
|
||||||
|
Serial.println("[mem] LVGL lock busy > 500 ms - UI task stuck?");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
lv_mem_monitor_t m;
|
||||||
|
lv_mem_monitor(&m);
|
||||||
|
lvgl_port_unlock();
|
||||||
|
SerialLock::lock();
|
||||||
|
Serial.printf("[mem] LVGL pool: used %u of %u B (%u%%), frag %u%%, biggest free %u\n",
|
||||||
|
(unsigned)(m.total_size - m.free_size), (unsigned)m.total_size,
|
||||||
|
(unsigned)m.used_pct, (unsigned)m.frag_pct, (unsigned)m.free_biggest_size);
|
||||||
|
SerialLock::unlock();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem.
|
||||||
static bool consoleExtraCommand(const char* line) {
|
static bool consoleExtraCommand(const char* line) {
|
||||||
return DiagProbe::handleCommand(line) || Ota::handleCommand(line);
|
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
|
||||||
|
WiFiManager::handleCommand(line) || memCommand(line);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|||||||
@@ -6,9 +6,32 @@
|
|||||||
#include "display/lvgl_v8_port.h"
|
#include "display/lvgl_v8_port.h"
|
||||||
#include "ui/ui.h"
|
#include "ui/ui.h"
|
||||||
#include "driveline_screen.h"
|
#include "driveline_screen.h"
|
||||||
|
#include "config/ota_config.h" // FW_VERSION
|
||||||
|
|
||||||
namespace DisplayInit {
|
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
|
// PUBLIC API IMPLEMENTATION
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -76,6 +99,7 @@ DisplayObjects init() {
|
|||||||
// empty placeholder now (the SquareLine Home screen was removed 2026-09-21);
|
// empty placeholder now (the SquareLine Home screen was removed 2026-09-21);
|
||||||
// swap while the backlight is still off so there's no flash.
|
// swap while the backlight is still off so there's no flash.
|
||||||
DrivelineScreen::show();
|
DrivelineScreen::show();
|
||||||
|
createVersionLabel();
|
||||||
lvgl_port_unlock();
|
lvgl_port_unlock();
|
||||||
Serial.println("[DisplayInit] Step 13: SquareLine UI loaded successfully!");
|
Serial.println("[DisplayInit] Step 13: SquareLine UI loaded successfully!");
|
||||||
|
|
||||||
@@ -91,6 +115,7 @@ DisplayObjects init() {
|
|||||||
Serial.println("[DisplayInit] Display initialization complete!");
|
Serial.println("[DisplayInit] Display initialization complete!");
|
||||||
|
|
||||||
// Return board and backlight objects for later use
|
// Return board and backlight objects for later use
|
||||||
|
g_backlight = backlight;
|
||||||
return {board, backlight};
|
return {board, backlight};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,4 +43,7 @@ struct DisplayObjects {
|
|||||||
*/
|
*/
|
||||||
DisplayObjects init();
|
DisplayObjects init();
|
||||||
|
|
||||||
|
/** Backlight on/off after init() (e.g. dark during OTA flash writes, which flicker the panel). */
|
||||||
|
void setBacklight(bool on);
|
||||||
|
|
||||||
} // namespace DisplayInit
|
} // 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());
|
lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
|
||||||
if (dir == LV_DIR_LEFT) {
|
if (dir == LV_DIR_LEFT) {
|
||||||
lv_indev_wait_release(lv_indev_get_act());
|
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);
|
&ui_Settings_Screen_screen_init);
|
||||||
} else if (dir == LV_DIR_RIGHT) {
|
} else if (dir == LV_DIR_RIGHT) {
|
||||||
lv_indev_wait_release(lv_indev_get_act());
|
lv_indev_wait_release(lv_indev_get_act());
|
||||||
@@ -257,7 +259,7 @@ static void build() {
|
|||||||
|
|
||||||
void show() {
|
void show() {
|
||||||
build();
|
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() {
|
void tick() {
|
||||||
|
|||||||
@@ -62,14 +62,30 @@ bool init() {
|
|||||||
return true;
|
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) {
|
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);
|
esp_err_t err = esp_now_send(BROADCAST_MAC, frame, len);
|
||||||
if (err == ESP_OK) {
|
if (err == ESP_OK) {
|
||||||
g_sent++;
|
g_sent++;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
g_fail++;
|
g_fail++;
|
||||||
|
if (err == ESP_ERR_ESPNOW_NOT_INIT) reinitIfDue();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+141
-44
@@ -17,6 +17,10 @@
|
|||||||
#include "drivers/can_driver.h"
|
#include "drivers/can_driver.h"
|
||||||
#include "protocol/automotive_data.h"
|
#include "protocol/automotive_data.h"
|
||||||
#include "config/ota_config.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 <WiFi.h>
|
||||||
#include <WiFiClientSecure.h>
|
#include <WiFiClientSecure.h>
|
||||||
@@ -25,6 +29,8 @@
|
|||||||
#include <esp_partition.h>
|
#include <esp_partition.h>
|
||||||
#include <mbedtls/sha256.h>
|
#include <mbedtls/sha256.h>
|
||||||
#include <mbedtls/pk.h>
|
#include <mbedtls/pk.h>
|
||||||
|
#include <mbedtls/platform.h>
|
||||||
|
#include <esp_heap_caps.h>
|
||||||
#include <stdarg.h>
|
#include <stdarg.h>
|
||||||
|
|
||||||
// Take over Arduino's rollback hook: by default initArduino() marks a new image
|
// Take over Arduino's rollback hook: by default initArduino() marks a new image
|
||||||
@@ -41,6 +47,12 @@ 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 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 uint32_t STALL_TIMEOUT_MS = 15000; // download aborts if no bytes arrive this long
|
||||||
static const size_t CHUNK = 4096;
|
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 {
|
typedef struct {
|
||||||
char tag[32];
|
char tag[32];
|
||||||
@@ -54,7 +66,8 @@ typedef struct {
|
|||||||
|
|
||||||
enum job_t { JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE };
|
enum job_t { JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE };
|
||||||
|
|
||||||
static volatile bool g_busy = false;
|
static bool g_job_pending = false;
|
||||||
|
static job_t g_job = JOB_CHECK;
|
||||||
static bool g_pending_verify = false;
|
static bool g_pending_verify = false;
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -268,45 +281,27 @@ static bool verifySignature(const manifest_t& m) {
|
|||||||
// Install
|
// Install
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
static void install(bool force) {
|
/** Download firmware.bin into the idle slot, hashing as it streams; true if it matches the signed manifest. */
|
||||||
manifest_t m;
|
static bool writeImage(const manifest_t& m, const esp_partition_t* part) {
|
||||||
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). Screen may flicker while flash is written.",
|
|
||||||
m.version, part->label, (unsigned long)m.size);
|
|
||||||
|
|
||||||
String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/firmware.bin";
|
String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/firmware.bin";
|
||||||
WiFiClientSecure client;
|
WiFiClientSecure client;
|
||||||
client.setCACert(OTA_CA_PEM);
|
client.setCACert(OTA_CA_PEM);
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
http.setConnectTimeout(10000);
|
http.setConnectTimeout(10000);
|
||||||
http.setTimeout(15000);
|
http.setTimeout(15000);
|
||||||
if (!http.begin(client, url)) { print("[ota] bad download URL"); return; }
|
if (!http.begin(client, url)) { print("[ota] bad download URL"); return false; }
|
||||||
http.setUserAgent("patrol-a-ota/" FW_VERSION);
|
http.setUserAgent("patrol-a-ota/" FW_VERSION);
|
||||||
int code = http.GET();
|
int code = http.GET();
|
||||||
if (code != HTTP_CODE_OK) { print("[ota] download failed (HTTP %d)", code); http.end(); return; }
|
if (code != HTTP_CODE_OK) { print("[ota] download failed (HTTP %d)", code); http.end(); return false; }
|
||||||
if (http.getSize() != (int)m.size) {
|
if (http.getSize() != (int)m.size) {
|
||||||
print("[ota] server size %d != manifest size %lu", http.getSize(), (unsigned long)m.size);
|
print("[ota] server size %d != manifest size %lu", http.getSize(), (unsigned long)m.size);
|
||||||
http.end();
|
http.end();
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
esp_ota_handle_t h = 0;
|
esp_ota_handle_t h = 0;
|
||||||
esp_err_t err = esp_ota_begin(part, OTA_WITH_SEQUENTIAL_WRITES, &h);
|
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; }
|
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);
|
uint8_t* buf = (uint8_t*)malloc(CHUNK);
|
||||||
mbedtls_sha256_context sc;
|
mbedtls_sha256_context sc;
|
||||||
@@ -320,7 +315,11 @@ static void install(bool force) {
|
|||||||
while (ok && got < m.size) {
|
while (ok && got < m.size) {
|
||||||
size_t avail = stream->available();
|
size_t avail = stream->available();
|
||||||
if (avail == 0) {
|
if (avail == 0) {
|
||||||
if (!http.connected() || millis() - last_rx > STALL_TIMEOUT_MS) {
|
// connected() can read false for a moment between TLS records, so a
|
||||||
|
// drop only counts after 2 s of silence (it aborted a download at
|
||||||
|
// 570 B once, 2026-09-26; the retry went through).
|
||||||
|
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);
|
print("[ota] download stalled at %lu/%lu bytes", (unsigned long)got, (unsigned long)m.size);
|
||||||
ok = false;
|
ok = false;
|
||||||
break;
|
break;
|
||||||
@@ -352,19 +351,95 @@ static void install(bool force) {
|
|||||||
print("[ota] SHA-256 MISMATCH - image does not match the signed manifest");
|
print("[ota] SHA-256 MISMATCH - image does not match the signed manifest");
|
||||||
ok = false;
|
ok = false;
|
||||||
}
|
}
|
||||||
if (!ok) { esp_ota_abort(h); print("[ota] aborted; still running %s", FW_VERSION); return; }
|
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
|
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; }
|
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.
|
// The download took a while - the driver may have started the engine since.
|
||||||
if (!gate(false)) { print("[ota] new image left inactive in %s; retry when parked", part->label); return; }
|
if (ok && !gate(false)) {
|
||||||
|
print("[ota] new image left inactive in %s; retry when parked", part->label);
|
||||||
err = esp_ota_set_boot_partition(part);
|
ok = false;
|
||||||
if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); return; }
|
}
|
||||||
|
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.",
|
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));
|
m.version, (unsigned long)(OTA_CONFIRM_MS / 1000));
|
||||||
|
snprintf(msg, sizeof(msg), "Installed %s\n\nRestarting...", m.version);
|
||||||
|
showNotice(msg);
|
||||||
|
Tunables::flush();
|
||||||
delay(3000);
|
delay(3000);
|
||||||
esp_restart();
|
esp_restart();
|
||||||
}
|
}
|
||||||
@@ -378,23 +453,38 @@ static void check() {
|
|||||||
same ? " - up to date" : " - `ota install` to update");
|
same ? " - up to date" : " - `ota install` to update");
|
||||||
}
|
}
|
||||||
|
|
||||||
static void jobTask(void* arg) {
|
// This core's mbedtls is built with CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC: every TLS
|
||||||
job_t job = (job_t)(intptr_t)arg;
|
// 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();
|
if (job == JOB_CHECK) check();
|
||||||
else install(job == JOB_INSTALL_FORCE);
|
else install(job == JOB_INSTALL_FORCE);
|
||||||
g_busy = false;
|
mbedtls_platform_set_calloc_free(tlsCallocInternal, heap_caps_free);
|
||||||
vTaskDelete(NULL);
|
print("[ota] loop stack headroom after job: %u B", (unsigned)uxTaskGetStackHighWaterMark(NULL));
|
||||||
}
|
}
|
||||||
|
|
||||||
static void startJob(job_t job) {
|
static void startJob(job_t job) {
|
||||||
if (g_busy) { print("[ota] busy - an ota job is already running"); return; }
|
|
||||||
if (!gate(true, job != JOB_CHECK)) return; // checking is harmless; installing needs parked
|
if (!gate(true, job != JOB_CHECK)) return; // checking is harmless; installing needs parked
|
||||||
g_busy = true;
|
g_job = job;
|
||||||
// TLS needs a deep stack; core 0 alongside the other network tasks.
|
g_job_pending = true; // runs on the next tick(), in the loop task
|
||||||
if (xTaskCreatePinnedToCore(jobTask, "ota", 16384, (void*)(intptr_t)job, 1, NULL, 0) != pdPASS) {
|
print("[ota] working - console and screen values pause until done");
|
||||||
g_busy = false;
|
|
||||||
print("[ota] could not start the ota task (out of memory?)");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -420,12 +510,14 @@ static void status() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
print("[ota] updates from %s/%s/releases (%s)", OTA_SERVER, OTA_REPO, OTA_TARGET);
|
print("[ota] updates from %s/%s/releases (%s)", OTA_SERVER, OTA_REPO, OTA_TARGET);
|
||||||
|
printHeap("now");
|
||||||
}
|
}
|
||||||
|
|
||||||
static void rollback() {
|
static void rollback() {
|
||||||
if (!gate(false)) return;
|
if (!gate(false)) return;
|
||||||
if (g_pending_verify) {
|
if (g_pending_verify) {
|
||||||
print("[ota] rejecting this unconfirmed image; rebooting into the previous one");
|
print("[ota] rejecting this unconfirmed image; rebooting into the previous one");
|
||||||
|
Tunables::flush();
|
||||||
delay(500);
|
delay(500);
|
||||||
esp_ota_mark_app_invalid_rollback_and_reboot();
|
esp_ota_mark_app_invalid_rollback_and_reboot();
|
||||||
return;
|
return;
|
||||||
@@ -444,7 +536,8 @@ static void rollback() {
|
|||||||
}
|
}
|
||||||
esp_err_t err = esp_ota_set_boot_partition(other);
|
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; }
|
if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); return; }
|
||||||
print("[ota] booting %s (built %s %s) in 2 s", other->label, d.date, d.time);
|
print("[ota] booting %s in 2 s", other->label);
|
||||||
|
Tunables::flush();
|
||||||
delay(2000);
|
delay(2000);
|
||||||
esp_restart();
|
esp_restart();
|
||||||
}
|
}
|
||||||
@@ -474,6 +567,10 @@ void init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void tick() {
|
void tick() {
|
||||||
|
if (g_job_pending) {
|
||||||
|
g_job_pending = false;
|
||||||
|
runJob(g_job);
|
||||||
|
}
|
||||||
if (g_pending_verify && millis() > OTA_CONFIRM_MS) {
|
if (g_pending_verify && millis() > OTA_CONFIRM_MS) {
|
||||||
esp_ota_mark_app_valid_cancel_rollback();
|
esp_ota_mark_app_valid_cancel_rollback();
|
||||||
g_pending_verify = false;
|
g_pending_verify = false;
|
||||||
|
|||||||
@@ -43,6 +43,18 @@ static void save() {
|
|||||||
prefs.end();
|
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() {
|
static bool load() {
|
||||||
Preferences prefs;
|
Preferences prefs;
|
||||||
prefs.begin(NVS_NAMESPACE, true);
|
prefs.begin(NVS_NAMESPACE, true);
|
||||||
@@ -113,7 +125,7 @@ static bool setField(const char* name, long v) {
|
|||||||
if (ok) {
|
if (ok) {
|
||||||
g_cfg.cfg_version++;
|
g_cfg.cfg_version++;
|
||||||
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
|
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
|
||||||
save();
|
markDirty();
|
||||||
}
|
}
|
||||||
unlock();
|
unlock();
|
||||||
return ok;
|
return ok;
|
||||||
@@ -159,7 +171,7 @@ void set(const link_config_t& cfg) {
|
|||||||
uint8_t v = g_cfg.cfg_version + 1;
|
uint8_t v = g_cfg.cfg_version + 1;
|
||||||
g_cfg = cfg;
|
g_cfg = cfg;
|
||||||
g_cfg.cfg_version = v ? v : 1;
|
g_cfg.cfg_version = v ? v : 1;
|
||||||
save();
|
markDirty();
|
||||||
unlock();
|
unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,7 +180,7 @@ void resetDefaults() {
|
|||||||
uint8_t v = g_cfg.cfg_version + 1;
|
uint8_t v = g_cfg.cfg_version + 1;
|
||||||
link_config_defaults(&g_cfg);
|
link_config_defaults(&g_cfg);
|
||||||
g_cfg.cfg_version = v ? v : 1;
|
g_cfg.cfg_version = v ? v : 1;
|
||||||
save();
|
markDirty();
|
||||||
unlock();
|
unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,7 +215,7 @@ bool handleCommand(const char* line) {
|
|||||||
if (!strcmp(argv[1], "set") && argc == 4) {
|
if (!strcmp(argv[1], "set") && argc == 4) {
|
||||||
long v = strtol(argv[3], NULL, 0);
|
long v = strtol(argv[3], NULL, 0);
|
||||||
if (setField(argv[2], v)) {
|
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 {
|
} else {
|
||||||
print("[cfg] unknown field '%s'", argv[2]);
|
print("[cfg] unknown field '%s'", argv[2]);
|
||||||
help();
|
help();
|
||||||
@@ -247,7 +259,18 @@ void setExtraCommandHandler(bool (*handler)(const char* line)) {
|
|||||||
g_extra_handler = handler;
|
g_extra_handler = handler;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void flush() {
|
||||||
|
lock();
|
||||||
|
if (g_dirty) {
|
||||||
|
save();
|
||||||
|
g_dirty = false;
|
||||||
|
}
|
||||||
|
unlock();
|
||||||
|
}
|
||||||
|
|
||||||
void pollSerial() {
|
void pollSerial() {
|
||||||
|
if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush();
|
||||||
|
|
||||||
while (Serial.available()) {
|
while (Serial.available()) {
|
||||||
char c = (char)Serial.read();
|
char c = (char)Serial.read();
|
||||||
if (c == '\r' || c == '\n') {
|
if (c == '\r' || c == '\n') {
|
||||||
|
|||||||
@@ -58,6 +58,13 @@ bool handleCommand(const char* line);
|
|||||||
*/
|
*/
|
||||||
void pollSerial();
|
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)
|
* Register a second console command handler (e.g. DiagProbe::handleCommand)
|
||||||
* that gets lines `cfg` does not recognise. Returns true if it consumed the line.
|
* 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)
|
if (lv_event_get_code(e) != LV_EVENT_CLICKED)
|
||||||
return;
|
return;
|
||||||
|
Tunables::flush(); // write pending edits now rather than after the idle delay
|
||||||
DrivelineScreen::show();
|
DrivelineScreen::show();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -584,7 +585,7 @@ namespace TuningScreen
|
|||||||
{
|
{
|
||||||
build();
|
build();
|
||||||
refreshFromTunables();
|
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()
|
void tick()
|
||||||
|
|||||||
@@ -73,6 +73,11 @@ void applySavedStatesToUI() {
|
|||||||
|
|
||||||
lvgl_port_lock(-1);
|
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
|
// Apply WiFi state
|
||||||
if (current_wifi_state) {
|
if (current_wifi_state) {
|
||||||
lv_obj_add_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
|
lv_obj_add_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include "wifi_manager.h"
|
#include "wifi_manager.h"
|
||||||
|
#include "espnow_link.h"
|
||||||
#include "display/lvgl_v8_port.h"
|
#include "display/lvgl_v8_port.h"
|
||||||
|
|
||||||
// External UI element references (from ui_Settings_Screen.c)
|
// 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
|
* @note Must be called with LVGL lock held OR will acquire lock internally
|
||||||
*/
|
*/
|
||||||
static void showConnectionResult(bool success, const char* message) {
|
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
|
// Hide loading spinner
|
||||||
|
if (uic_Settings_Loading_Container != NULL) {
|
||||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
if (success) {
|
if (success) {
|
||||||
// Connection successful
|
// Connection successful
|
||||||
@@ -211,6 +217,16 @@ static void updateWifiUIState(wifi_state_t state) {
|
|||||||
* @brief Update SSID list with dynamic buttons
|
* @brief Update SSID list with dynamic buttons
|
||||||
* @note This function MUST be called with lvgl_port_lock held
|
* @note This function MUST be called with lvgl_port_lock held
|
||||||
*/
|
*/
|
||||||
|
// The SSID buttons live on the Settings screen, which SquareLine deletes every
|
||||||
|
// time it is left. Each button clears its own slot when LVGL deletes it, so
|
||||||
|
// g_ssid_buttons[] never holds a freed pointer. Before this, the next scan
|
||||||
|
// called lv_obj_del() on already-freed buttons, corrupting LVGL's heap until an
|
||||||
|
// LVGL assert froze the UI (found 2026-09-27).
|
||||||
|
static void onSsidButtonDeleted(lv_event_t* e) {
|
||||||
|
intptr_t i = (intptr_t)lv_event_get_user_data(e);
|
||||||
|
if (i >= 0 && i < WIFI_SCAN_MAX_NETWORKS) g_ssid_buttons[i] = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
static void updateSSIDList() {
|
static void updateSSIDList() {
|
||||||
// This function MUST be called with lvgl_port_lock held
|
// This function MUST be called with lvgl_port_lock held
|
||||||
|
|
||||||
@@ -253,6 +269,7 @@ static void updateSSIDList() {
|
|||||||
|
|
||||||
// Add click event handler
|
// Add click event handler
|
||||||
lv_obj_add_event_cb(btn, onSSIDButtonClick, LV_EVENT_CLICKED, NULL);
|
lv_obj_add_event_cb(btn, onSSIDButtonClick, LV_EVENT_CLICKED, NULL);
|
||||||
|
lv_obj_add_event_cb(btn, onSsidButtonDeleted, LV_EVENT_DELETE, (void*)(intptr_t)i);
|
||||||
|
|
||||||
// Store button reference
|
// Store button reference
|
||||||
g_ssid_buttons[i] = btn;
|
g_ssid_buttons[i] = btn;
|
||||||
@@ -331,7 +348,7 @@ static void wifiTask(void* parameter) {
|
|||||||
|
|
||||||
case WIFI_UI_EVENT_TOGGLE_OFF:
|
case WIFI_UI_EVENT_TOGGLE_OFF:
|
||||||
Serial.println("WiFi Task: Disabling WiFi...");
|
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
|
// Radio stays in STA mode: the ESP-NOW link to Controller B
|
||||||
// rides on it. "WiFi off" here means scanning/association off.
|
// rides on it. "WiFi off" here means scanning/association off.
|
||||||
g_wifi_state = WIFI_STATE_OFF;
|
g_wifi_state = WIFI_STATE_OFF;
|
||||||
@@ -358,7 +375,7 @@ static void wifiTask(void* parameter) {
|
|||||||
g_wifi_state = WIFI_STATE_CONNECTED; // Will be updated based on result
|
g_wifi_state = WIFI_STATE_CONNECTED; // Will be updated based on result
|
||||||
|
|
||||||
// Attempt connection
|
// 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);
|
delay(100);
|
||||||
|
|
||||||
if (strlen(creds->password) > 0) {
|
if (strlen(creds->password) > 0) {
|
||||||
@@ -401,7 +418,7 @@ static void wifiTask(void* parameter) {
|
|||||||
|
|
||||||
case WIFI_UI_EVENT_DISCONNECT:
|
case WIFI_UI_EVENT_DISCONNECT:
|
||||||
Serial.println("WiFi Task: Disconnecting...");
|
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_state = WIFI_STATE_SCANNING;
|
||||||
g_wifi_scan_requested = true;
|
g_wifi_scan_requested = true;
|
||||||
break;
|
break;
|
||||||
@@ -415,9 +432,15 @@ static void wifiTask(void* parameter) {
|
|||||||
if (g_wifi_state != WIFI_STATE_OFF) {
|
if (g_wifi_state != WIFI_STATE_OFF) {
|
||||||
unsigned long current_time = millis();
|
unsigned long current_time = millis();
|
||||||
|
|
||||||
// Start scan if requested or periodic scan is due
|
// Scan only while the network list is on screen and we're not
|
||||||
if (g_wifi_scan_requested ||
|
// connected. Scanning hops the radio across channels (ESP-NOW to B
|
||||||
(current_time - g_last_scan_time > WIFI_SCAN_INTERVAL_MS && !scanning)) {
|
// shares it) and churns Wi-Fi buffers in PSRAM, which the RGB panel
|
||||||
|
// streams from; it used to run every 10 s forever, connected or not,
|
||||||
|
// on any screen. A pending request waits until the list is visible.
|
||||||
|
bool list_on_screen = (uic_Wifi_Container != NULL);
|
||||||
|
bool connected = (WiFi.status() == WL_CONNECTED);
|
||||||
|
if (!scanning && list_on_screen && !connected &&
|
||||||
|
(g_wifi_scan_requested || current_time - g_last_scan_time > WIFI_SCAN_INTERVAL_MS)) {
|
||||||
|
|
||||||
Serial.println("Starting WiFi scan...");
|
Serial.println("Starting WiFi scan...");
|
||||||
scanning = true;
|
scanning = true;
|
||||||
@@ -757,4 +780,44 @@ void onSelectSSID(lv_event_t *e) {
|
|||||||
Serial.println("onSelectSSID() called - but dynamic buttons handle clicks now");
|
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
|
} // namespace WiFiManager
|
||||||
|
|||||||
@@ -113,6 +113,12 @@ wifi_state_t getState();
|
|||||||
*/
|
*/
|
||||||
uint8_t getNetworkCount();
|
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)
|
// EVENT HANDLERS (Called from SquareLine Studio UI)
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
type: index
|
type: index
|
||||||
updated: 2026-09-26
|
updated: 2026-09-27
|
||||||
---
|
---
|
||||||
|
|
||||||
# Index
|
# Index
|
||||||
@@ -12,7 +12,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
|
|||||||
- [[patrol-instrument-cluster]] — **what the Patrol cluster expects on its inputs**: tach = 2 pulses/rev (verified by calibration), temp = NTC sender 2.1–2.9 kΩ cold → ~250 Ω at 90 °C; the 1 kHz PWM needle-flutter problem and the mitigation ladder (fixed-duty test → 20 kHz → hardware damping)
|
- [[patrol-instrument-cluster]] — **what the Patrol cluster expects on its inputs**: tach = 2 pulses/rev (verified by calibration), temp = NTC sender 2.1–2.9 kΩ cold → ~250 Ω at 90 °C; the 1 kHz PWM needle-flutter problem and the mitigation ladder (fixed-duty test → 20 kHz → hardware damping)
|
||||||
- [[bmw-m57n-engine]] — the 3.0L BMW diesel whose CAN bus we read; E60/E65 donor (confirmed), DDE ECU, auto box with EGS on bus
|
- [[bmw-m57n-engine]] — the 3.0L BMW diesel whose CAN bus we read; E60/E65 donor (confirmed), DDE ECU, auto box with EGS on bus
|
||||||
- [[nissan-patrol-swap]] — the target vehicle: Patrol receiving the M57N + BMW auto; the tapped bus is a BMW island in a Nissan
|
- [[nissan-patrol-swap]] — the target vehicle: Patrol receiving the M57N + BMW auto; the tapped bus is a BMW island in a Nissan
|
||||||
- [[esp32-s3-touch-lcd-5b]] — Waveshare 5" display board (Controller A); onboard TJA1051 CAN transceiver, 7–36 V input, pinout, PSRAM/LCD gotchas
|
- [[esp32-s3-touch-lcd-5b]] — Waveshare 5" display board (Controller A); onboard TJA1051 CAN transceiver, 7–36 V input, pinout, PSRAM/LCD gotchas — **flash writes flicker the RGB panel, full-screen fades stutter, internal RAM nearly full, opening the serial port resets the board unless DTR/RTS are low**
|
||||||
|
|
||||||
## Concepts
|
## Concepts
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ Catalog of every page in the wiki. Read this first when answering questions. Kee
|
|||||||
- [[driveline-speed-signals]] — **engine / turbine / output-shaft speeds**: turbine speed as physical proof of gear engagement, and the output-shaft field that is our **only road-speed source** (no DSC on this bus) — the feedback variable for a future cruise-control PoC, with the safety envelope that would require
|
- [[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)
|
- [[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
|
- [[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; dual-slot partition table (2026-09-26); plan for updating Controller B through A over ESP-NOW
|
- [[ota-updates]] — **Controller A updates itself from Gitea releases**: tag `v*` → CI builds + signs (ECDSA P-256) → `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 → v0.1.2; v0.1.3 published)**, release with `git push --follow-tags origin main`; dual-slot partition table; plan for updating Controller B through A over ESP-NOW
|
||||||
|
|
||||||
## Synthesis
|
## Synthesis
|
||||||
|
|
||||||
|
|||||||
+24
@@ -113,3 +113,27 @@ Tightened the live-data findings after checking the full capture: the Launch use
|
|||||||
## [2026-09-26] build | OTA updates for Controller A
|
## [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.
|
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.
|
||||||
|
|
||||||
|
## [2026-09-26] build | CI: no duplicate / docs-only builds; v0.1.3
|
||||||
|
|
||||||
|
v0.1.3 released (OTA download loop no longer aborts on a momentary TLS connected()==false; a forced reinstall had stalled at 570 B once, retry succeeded). Pushing main then the tag ran two identical builds, and every wiki commit rebuilt firmware: the workflow's new "Skip?" step makes a main push skip itself when its commit carries a v* tag or only touches wiki/** / *.md (in-job, so tag builds are never path-filtered). Release with `git push --follow-tags origin main`. Logic dry-run locally against the real remote (tagged/untagged/docs/mixed cases).
|
||||||
|
|
||||||
|
## [2026-09-27] lint | Session sweep: OTA status, board gotchas, Wi-Fi follow-ups
|
||||||
|
|
||||||
|
Brought the wiki in line with the whole 2026-09-26 session. ota-updates: status table of every cycle (dev->v0.1.1->v0.1.2, forced reinstall with the 570 B abort + clean failure path, v0.1.3 published but not installed), "installs are done by the running firmware" rule, flicker cause marked verified, Wi-Fi lost on reboot, console-without-reset recipe, B repo now public. esp32-s3-touch-lcd-5b: removed the unmeasured "~50 FPS" claim, USB serial is native CDC (not UART0) with the DTR/RTS reset gotcha, new lessons (flash-write flicker, fade stutter, internal RAM, never power the radio off, dual-slot partitions). dual-controller-architecture: ESP-NOW/Wi-Fi radio sharing + the disconnect(true) bug, B updates via A over ESP-NOW. open-questions #14: Wi-Fi UX redesign, remember network, delete v0.1.0 release. Pending user confirmations: dark-screen OTA shows no flicker; version label placement; instant swipes; Tuning taps.
|
||||||
|
|
||||||
|
## [2026-09-27] build | UI freeze + reboots fixed: LVGL pool to PSRAM, dangling SSID buttons, scans (v0.1.4)
|
||||||
|
|
||||||
|
User: swiping main<->Settings 3x froze the UI; random flickering dots on all screens. Board state while frozen: link task alive (UART+ESP-NOW), loop()/console dead -> LVGL lock held forever. Causes found: (1) LV_ASSERT_HANDLER `while(1);` spins inside the task holding the LVGL lock; (2) g_ssid_buttons[] dangled after SquareLine deleted the Settings screen -> lv_obj_del() on freed objects; (3) with (1) replaced by abort(), the next run rebooted after ~5 round trips and the decoded backtrace showed the real limit: lv_mem_buf_get() failing in a label draw - the 48 KB LVGL pool at 87% / 31% frag / 4.5 KB biggest block; (4) Wi-Fi scanned every 10 s on every screen, connected or not. Fixes: abort() handler, LV_EVENT_DELETE clears button slots, scanning only with the list on screen and not connected, LVGL pool 512 KB in PSRAM (frees 48 KB internal: internal free 16 -> 69 KB), `mem` console command. Verified: 10 Settings visits + 9 list rebuilds, pool peak 4%, 0 crashes; user: swipes better, no dots, no freeze, no reboot. Updated esp32-s3-touch-lcd-5b, open-questions #13/#14, ota-updates, CLAUDE.md.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
type: concept
|
type: concept
|
||||||
tags: [architecture, uart]
|
tags: [architecture, uart]
|
||||||
updated: 2026-09-21
|
updated: 2026-09-27
|
||||||
---
|
---
|
||||||
|
|
||||||
# Dual-Controller Architecture
|
# Dual-Controller Architecture
|
||||||
@@ -21,6 +21,8 @@ BMW M57N CAN bus ──▶ Controller A ──UART1 + ESP-NOW, 5 Hz──▶ Con
|
|||||||
|
|
||||||
`0xAA | 0x02 | type | length | payload | XOR | 0x55`, identical on UART1 (GPIO 44 → SP3485 → `485_A`/`485_B`) and ESP-NOW broadcast (channel 1). DATA frames (lever, target/engaged gear nibbles, rpm, temps, battery, alert bitmap, valid flags) every 200 ms; CONFIG frames (`link_config_t`: Patrol gauge calibration + alert thresholds, edited on A via the `cfg` serial console and stored in NVS) on change and every 5 s. Alerts are decided here; B only renders them. Spec: `docs/UART_PROTOCOL.md`. Bench-verified with both transports live and B deduplicating every frame `(verified 2026-09-21)`.
|
`0xAA | 0x02 | type | length | payload | XOR | 0x55`, identical on UART1 (GPIO 44 → SP3485 → `485_A`/`485_B`) and ESP-NOW broadcast (channel 1). DATA frames (lever, target/engaged gear nibbles, rpm, temps, battery, alert bitmap, valid flags) every 200 ms; CONFIG frames (`link_config_t`: Patrol gauge calibration + alert thresholds, edited on A via the `cfg` serial console and stored in NVS) on change and every 5 s. Alerts are decided here; B only renders them. Spec: `docs/UART_PROTOCOL.md`. Bench-verified with both transports live and B deduplicating every frame `(verified 2026-09-21)`.
|
||||||
|
|
||||||
|
**ESP-NOW and Wi-Fi share the radio** `(verified 2026-09-26)`. When A joins a Wi-Fi network (for OTA), its channel follows the AP (seen: 6, 9, 11) and B hops to find it; ESP-NOW kept running (6,410 frames, 0 failed). Until 2026-09-26 the Wi-Fi code powered the radio off on connect/disconnect (`WiFi.disconnect(true)`), which silently killed ESP-NOW and left B on the wire only — fixed, and `EspNowLink::send()` now re-initialises ESP-NOW if the driver drops it. Planned: **Controller B's firmware updates will travel from A over ESP-NOW** (bidirectional, unlike the one-way wire) → [[ota-updates]].
|
||||||
|
|
||||||
Controller B's side of this (receiver, ESP-NOW channel hopping, gauge outputs, bench wiring) is documented in the sibling wiki: `../../ESP32-S3-LCD-1.3/wiki/pages/controller-link.md` and `patrol-gauge-outputs.md`.
|
Controller B's side of this (receiver, ESP-NOW channel hopping, gauge outputs, bench wiring) is documented in the sibling wiki: `../../ESP32-S3-LCD-1.3/wiki/pages/controller-link.md` and `patrol-gauge-outputs.md`.
|
||||||
|
|
||||||
## Why it matters for the wiki
|
## Why it matters for the wiki
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
type: entity
|
type: entity
|
||||||
tags: [hardware, waveshare, display]
|
tags: [hardware, waveshare, display]
|
||||||
updated: 2026-07-16
|
updated: 2026-09-27
|
||||||
---
|
---
|
||||||
|
|
||||||
# Waveshare ESP32-S3-Touch-LCD-5B
|
# Waveshare ESP32-S3-Touch-LCD-5B
|
||||||
@@ -13,7 +13,7 @@ Controller A of the [[dual-controller-architecture]] — the main in-cabin displ
|
|||||||
- ESP32-S3-WROOM-1-N16R8 module: dual-core LX7 @ 240 MHz, 16 MB flash, 8 MB OPI PSRAM
|
- ESP32-S3-WROOM-1-N16R8 module: dual-core LX7 @ 240 MHz, 16 MB flash, 8 MB OPI PSRAM
|
||||||
- 5" IPS 1024×600, 65K colors (16-bit), 550 cd/m², GT911 5-point capacitive touch, tempered glass
|
- 5" IPS 1024×600, 65K colors (16-bit), 550 cd/m², GT911 5-point capacitive touch, tempered glass
|
||||||
- 2.4 GHz Wi-Fi + BLE 5, onboard antenna (keep metal away from antenna area)
|
- 2.4 GHz Wi-Fi + BLE 5, onboard antenna (keep metal away from antenna area)
|
||||||
- Runs LVGL 8.4.0 at ~50 FPS via ESP32_Display_Panel v1.0.4 `(repo)`
|
- Runs LVGL 8.4.0 via ESP32_Display_Panel v1.0.4 `(repo)`. Real render FPS has **never been measured**: the Debug-panel "FPS" counts `loop()` passes (and `loop()` sleeps 100 ms), and the old "~50 FPS" figure had no measurement behind it `(verified 2026-09-26)`
|
||||||
|
|
||||||
## Power (source: waveshare-wiki)
|
## Power (source: waveshare-wiki)
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ Controller A of the [[dual-controller-architecture]] — the main in-cabin displ
|
|||||||
| I2C | External header; CH422G expander occupies 0x20–0x27 & 0x30–0x3F, GT911 touch at 0x5D — avoid these addresses |
|
| I2C | External header; CH422G expander occupies 0x20–0x27 & 0x30–0x3F, GT911 touch at 0x5D — avoid these addresses |
|
||||||
| RTC | PCF85063 + CR927 coin cell |
|
| RTC | PCF85063 + CR927 coin cell |
|
||||||
| TF card | SD_CS driven via CH422G EXIO4 |
|
| TF card | SD_CS driven via CH422G EXIO4 |
|
||||||
| USB Serial | UART0, debug @ 115200 `(repo)` |
|
| USB Serial | Native USB-CDC (`Serial`, enumerates 303A:1001, ~1 MB/s), console + CANRAW `(repo)`. **Opening the port with default DTR/RTS resets the board** (`rst:0x15`) — set both low before opening (`--dtr 0 --rts 0`) to attach without a reboot `(verified 2026-09-26)` |
|
||||||
|
|
||||||
Note: the screen occupies most GPIOs; auxiliary functions (backlight, reset, SD_CS) route through the CH422G IO expander — spare native GPIOs are scarce.
|
Note: the screen occupies most GPIOs; auxiliary functions (backlight, reset, SD_CS) route through the CH422G IO expander — spare native GPIOs are scarce.
|
||||||
|
|
||||||
@@ -52,7 +52,15 @@ Note: the screen occupies most GPIOs; auxiliary functions (backlight, reset, SD_
|
|||||||
- LCD wants a 16 MHz pixel clock with correct PCLK polarity.
|
- LCD wants a 16 MHz pixel clock with correct PCLK polarity.
|
||||||
- Backlight must be manually sequenced at boot to avoid a white flash.
|
- Backlight must be manually sequenced at boot to avoid a white flash.
|
||||||
- Flashing: use the Type-C port labeled UART; hold BOOT while connecting if the port isn't recognized (source: waveshare-wiki).
|
- Flashing: use the Type-C port labeled UART; hold BOOT while connecting if the port isn't recognized (source: waveshare-wiki).
|
||||||
|
- **Flash writes flicker the screen** `(verified 2026-09-26)`: flash and PSRAM share the MSPI cache, so every flash write/erase (NVS save, OTA) briefly cuts off the PSRAM framebuffer the RGB panel streams from; there is no bounce buffer (`ESP_PANEL_LCD_RGB_BOUNCE_BUF_SIZE=0`). `CONFIG_LCD_RGB_RESTART_IN_VSYNC=y` resyncs next frame → flicker, not permanent drift. Mitigated (v0.1.2): Tuning edits saved to NVS once after 3 s idle, backlight off during OTA writes. Real cure: bounce buffers + `CONFIG_SPIRAM_XIP_FROM_PSRAM` → [[open-questions]] #13.
|
||||||
|
- **Full-screen transitions stutter** `(verified 2026-09-26)`: a fade re-renders and alpha-blends all 614k px in software every frame into the PSRAM framebuffer. Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`) since v0.1.2.
|
||||||
|
- **Internal RAM was nearly full** `(verified 2026-09-26)`: 15.9 KB free, largest block 7.6 KB with display + Wi-Fi up. Half the cause was LVGL's own 48 KB widget pool (`LV_MEM_SIZE`) sitting in internal `.bss`. **Moved to PSRAM and enlarged to 512 KB (2026-09-27)**: internal free now **69 KB, largest block 31.7 KB** `(verified)`. The 60-line LVGL draw buffer (~120 KB) is still internal, by design (render speed).
|
||||||
|
- **LVGL's widget pool ran out** `(verified 2026-09-27)`: Settings + its Wi-Fi list is ~15 KB; screen churn + list rebuilds took the 48 KB pool to 87% used / 31% fragmented / 4.5 KB biggest block, then a label draw failed `lv_mem_buf_get()` (backtrace decoded with addr2line). With the 512 KB PSRAM pool: 10 Settings visits + 9 list rebuilds, peak 4%, 0 crashes; swipes feel better (user).
|
||||||
|
- **LVGL asserts used to freeze the board**: `LV_ASSERT_HANDLER` was `while(1);`, which spins inside the calling task *while it holds the LVGL lock* — UI frozen, `loop()`/console blocked on the lock, only the link task alive. Now `abort()`: backtrace on the console, core dump to flash (ELF), reboot. Decode with `xtensa-esp32s3-elf-addr2line -pfiaC -e firmware.elf <addrs>` (CI attaches `firmware.elf` to every release).
|
||||||
|
- **Background Wi-Fi scans caused the random flickering dots** `(verified by elimination 2026-09-27)`: the Wi-Fi task scanned every 10 s forever, connected or not, on any screen; Wi-Fi buffers live in PSRAM next to the framebuffer. Scanning is now limited to "network list on screen and not connected" — the dots are gone (user).
|
||||||
|
- **Never power the Wi-Fi radio off** (`WiFi.disconnect(true)`, `WiFi.mode(WIFI_OFF)`): it de-initialises ESP-NOW, the wireless leg of the link to B → [[dual-controller-architecture]].
|
||||||
|
- **Partition table is dual-slot OTA** since 2026-09-26 (2 × 7.9 MB, no SPIFFS, NVS offset unchanged) → [[ota-updates]].
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
[[dual-controller-architecture]] · [[can-bus-integration]] · [[esp32-s3-touch-lcd-5b-waveshare-wiki]]
|
[[dual-controller-architecture]] · [[can-bus-integration]] · [[ota-updates]] · [[esp32-s3-touch-lcd-5b-waveshare-wiki]]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
type: synthesis
|
type: synthesis
|
||||||
tags: [meta, todo]
|
tags: [meta, todo]
|
||||||
updated: 2026-09-26
|
updated: 2026-09-27
|
||||||
---
|
---
|
||||||
|
|
||||||
# Open Questions
|
# Open Questions
|
||||||
@@ -69,3 +69,7 @@ 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
|
- ~~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)
|
- ~~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
|
- 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) — largely relieved 2026-09-27:** LVGL's 48 KB pool moved to PSRAM (512 KB) → internal free 16 → **69 KB**, largest block 7.6 → **31.7 KB**, enough for bounce buffers to be attempted. Original finding: 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).
|
||||||
|
|
||||||
|
14. **Wi-Fi UX (found 2026-09-26).** The Settings Wi-Fi screen had never worked (switch shipped disabled) and, now usable, is "a disaster UX" (user): SquareLine-generated, runtime SSID buttons + floating keyboard + loading overlay, **no on-screen confirmation of a successful join**. Also: A **forgets the network on every reboot** (each boot needs `wifi join`). To do: redesign as a hand-coded screen (like Driveline/Tuning, safe from SquareLine re-exports), show connection state, remember the network in NVS and auto-join; consider housing it on the Diagnostics screen (#12) next to the OTA controls, since Wi-Fi now mainly serves updates. Fixed 2026-09-27: the SSID buttons' pointers dangled after SquareLine deleted the Settings screen (use-after-free on the next scan), and scans ran every 10 s on every screen even when connected (flickering dots) — see [[esp32-s3-touch-lcd-5b]]. Housekeeping: **delete the `v0.1.0` release** on Gitea — installing it would strand the board without working OTA (USB only). → [[ota-updates]]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
type: concept
|
type: concept
|
||||||
tags: [ota, firmware, gitea, ci, security, signing, design-decision, controller-a]
|
tags: [ota, firmware, gitea, ci, security, signing, design-decision, controller-a]
|
||||||
updated: 2026-09-26
|
updated: 2026-09-27
|
||||||
---
|
---
|
||||||
|
|
||||||
# OTA Firmware Updates
|
# OTA Firmware Updates
|
||||||
@@ -24,8 +24,26 @@ Controller A `ota install` ◄──────┘ (parked, Wi-Fi joined)
|
|||||||
new image PENDING_VERIFY → confirmed after 30 s uptime, else bootloader rolls back
|
new image PENDING_VERIFY → confirmed after 30 s uptime, else bootloader rolls back
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**To release:** `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin main` — one push, one (tag) build: a `main` push skips itself when its commit already has a `v*` tag, and when it only changes `wiki/**` or `*.md` (checked inside the job, so a tag build is never skipped by a path filter).
|
||||||
|
|
||||||
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)`.
|
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)`
|
||||||
|
|
||||||
|
| Cycle (performed by the *running* firmware) | Result |
|
||||||
|
|---|---|
|
||||||
|
| `dev` (USB-flashed) → **v0.1.1**, into `app1` | ✅ 1.65 MB in ~60 s (~27 KB/s), confirmed after 30 s; v0.1.1 then passed `ota check` itself |
|
||||||
|
| v0.1.1 → **v0.1.2**, into `app0` | ✅ slots alternate as designed |
|
||||||
|
| v0.1.2 → v0.1.2 (`ota install force`), attempt 1 | ❌ download aborted at 570 B — the loop treated a momentary TLS `connected()==false` as a drop. The **failure path worked**: aborted cleanly, "Update failed / still running v0.1.2" notice, stayed on v0.1.2 |
|
||||||
|
| same, attempt 2 | ✅ into `app1`, confirmed — first install run by the dark-screen code |
|
||||||
|
| **v0.1.3** (published 2026-09-26) | fixes the 570 B abort (a drop only counts after 2 s of silence); **not yet installed** — the board runs v0.1.2 |
|
||||||
|
|
||||||
|
Always remember: an install is performed by the firmware that is **already running**, so a fix to the install path only takes effect on the update *after* the one that delivers it (v0.1.1 → v0.1.2 still flickered because v0.1.1 did the writing).
|
||||||
|
|
||||||
|
**Dark-screen writes (v0.1.2+).** Flash writes flicker the PSRAM-fed panel (cause below, and [[esp32-s3-touch-lcd-5b]]), so the backlight is off while the image is written: a full-screen notice "Updating to vX — the screen goes dark for about a minute — do not switch off" shows for 3 s first, then "Installed vX / Restarting…" or "Update failed / Still running vY". Ran for real on the forced reinstall; the user's visual confirmation of "no flicker" is still pending `(unverified)`. The running version is always shown bottom-right on every screen (`A v0.1.2`).
|
||||||
|
|
||||||
|
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
|
## 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.
|
- **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.
|
||||||
@@ -35,6 +53,15 @@ Push to `main` (no tag) builds a rolling **pre-release `main-latest`** — unsig
|
|||||||
- **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).
|
- **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).
|
- **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.
|
||||||
|
|
||||||
|
Update 2026-09-27: with LVGL's pool moved to PSRAM, internal free is 69 KB (largest block 31.7 KB); jobs still run in the loop task (it works, 3.6 KB headroom). The low internal heap was 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)
|
## Partition table (changed 2026-09-26)
|
||||||
|
|
||||||
| Name | Offset | Size |
|
| Name | Offset | Size |
|
||||||
@@ -56,7 +83,11 @@ SPIFFS (3.4 MB, unused by any code) was dropped. Firmware is ~1.65 MB (19.8 % of
|
|||||||
| `ota install [force]` | full install; `force` reinstalls the same version |
|
| `ota install [force]` | full install; `force` reinstalls the same version |
|
||||||
| `ota rollback` | boot the other slot (or reject an unconfirmed image) — parked only |
|
| `ota rollback` | boot the other slot (or reject an unconfirmed image) — parked only |
|
||||||
|
|
||||||
Wi-Fi must be joined via the Settings screen first. 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)`.
|
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.
|
||||||
|
|
||||||
|
- **Wi-Fi does not survive a reboot** — every boot (including the one that ends an update) needs a new `wifi join`; remembering the network is future work ([[open-questions]] #14).
|
||||||
|
- **Open the console without resetting the board**: `pio device monitor -p COM10 -b 115200 --dtr 0 --rts 0 --echo` (pio lives at `%USERPROFILE%\.platformio\penv\Scripts\pio.exe`). Opening the port with default DTR/RTS resets it (`rst:0x15 USB_UART_CHIP_RESET`), which drops the Wi-Fi join `(verified 2026-09-26)`.
|
||||||
|
- **Flicker cause** `(verified 2026-09-26)`: flash and PSRAM share the MSPI cache; every flash write stalls the PSRAM framebuffer the RGB panel streams from (no bounce buffer). Hence the dark screen above.
|
||||||
|
|
||||||
## Secrets and keys
|
## Secrets and keys
|
||||||
|
|
||||||
@@ -64,9 +95,15 @@ Wi-Fi must be joined via the Settings screen first. Joining an AP moves the radi
|
|||||||
- 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).
|
- 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).
|
- 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)
|
## 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.
|
Plan agreed 2026-09-26: B is updated **by A over ESP-NOW**, not by the RS485 wire (the wire is one-way A→B; ESP-NOW is bidirectional and faster). A downloads B's signed image (target `patrol-b`) from B's repo releases, sends it with acks, B verifies the signature and swaps slots with the same rollback scheme. Prerequisites: B moves off the stock `default.csv` (1.25 MB slots, 1.07 MB firmware → too tight) to a 16 MB layout (confirm B's flash size first; one USB flash); ESP-NOW pairing/encryption so only A can talk to B; protocol frames for the transfer (shared `automotive_data.h` → version bump in both repos). B's repo is public since 2026-09-27 (anonymous API 200). Wire stays for gauge-data redundancy.
|
||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user