From 766019a01ebae6170a619eb8df1aca9633c5c611 Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Sun, 27 Sep 2026 00:32:18 +0200 Subject: [PATCH] Fix UI freeze/reboots: LVGL pool to PSRAM, dangling SSID buttons, scan policy - lv_conf: LVGL widget pool 48 KB internal -> 512 KB PSRAM (LV_MEM_POOL_ALLOC). It ran out after a few Settings visits (87% used, 31% frag, 4.5 KB biggest block; lv_mem_buf_get() failed in a label draw - decoded backtrace). Also frees 48 KB of internal RAM: free 16 -> 69 KB, largest block 7.6 -> 31.7 KB - lv_conf: LV_ASSERT_HANDLER abort() instead of while(1), which spun inside the task holding the LVGL lock and froze the UI + console - wifi_manager: SSID buttons clear their g_ssid_buttons[] slot on LV_EVENT_DELETE (SquareLine deletes the Settings screen on leave; stale pointers were lv_obj_del()'d on the next scan). Scan only while the list is on screen and not connected - 10 s background scans caused the display dots - main: `mem` console command (internal heap, PSRAM, LVGL pool) - docs: board page lessons, open-questions #13/#14, ota-updates, CLAUDE.md, log Verified: 10 Settings visits + 9 list rebuilds, pool peak 4%, 0 crashes; user confirms no freeze, no reboot, no dots, swipes better. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +++++- include/config/lv_conf.h | 19 +++++++++++++----- src/main.cpp | 31 +++++++++++++++++++++++++++-- src/modules/wifi_manager.cpp | 23 ++++++++++++++++++--- wiki/log.md | 4 ++++ wiki/pages/esp32-s3-touch-lcd-5b.md | 5 ++++- wiki/pages/open-questions.md | 4 ++-- wiki/pages/ota-updates.md | 2 +- 8 files changed, 79 insertions(+), 15 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7f615ee..6ab6264 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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` - 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**: - 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) - 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 **Connection Flow**: @@ -280,7 +283,8 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): **include/lv_conf.h** - 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 ## Common Patterns diff --git a/include/config/lv_conf.h b/include/config/lv_conf.h index 59b982b..9383cfb 100644 --- a/include/config/lv_conf.h +++ b/include/config/lv_conf.h @@ -49,14 +49,19 @@ #define LV_MEM_CUSTOM 0 #if LV_MEM_CUSTOM == 0 /*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.*/ #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*/ #if LV_MEM_ADR == 0 - #undef LV_MEM_POOL_INCLUDE - #undef LV_MEM_POOL_ALLOC + #define LV_MEM_POOL_INCLUDE + #define LV_MEM_POOL_ALLOC(size) heap_caps_malloc((size), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) #endif #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)*/ /*Add a custom handler when assert happens e.g. to restart the MCU*/ -#define LV_ASSERT_HANDLER_INCLUDE -#define LV_ASSERT_HANDLER while(1); /*Halt by default*/ +#define LV_ASSERT_HANDLER_INCLUDE +/* 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 diff --git a/src/main.cpp b/src/main.cpp index 9e1194d..b30dcf7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "display/lvgl_v8_port.h" // LVGL port layer (for lvgl_port_lock/unlock) #include "modules/display_init.h" // Display initialization module #include "modules/wifi_manager.h" // WiFi manager module @@ -113,10 +114,36 @@ void onDebugToggle(lv_event_t *e) } // extern "C" -// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi. +// `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) { return DiagProbe::handleCommand(line) || Ota::handleCommand(line) || - WiFiManager::handleCommand(line); + WiFiManager::handleCommand(line) || memCommand(line); } // ============================================================================ diff --git a/src/modules/wifi_manager.cpp b/src/modules/wifi_manager.cpp index 4ff90a1..10919f9 100644 --- a/src/modules/wifi_manager.cpp +++ b/src/modules/wifi_manager.cpp @@ -217,6 +217,16 @@ static void updateWifiUIState(wifi_state_t state) { * @brief Update SSID list with dynamic buttons * @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() { // This function MUST be called with lvgl_port_lock held @@ -259,6 +269,7 @@ static void updateSSIDList() { // Add click event handler 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 g_ssid_buttons[i] = btn; @@ -421,9 +432,15 @@ static void wifiTask(void* parameter) { if (g_wifi_state != WIFI_STATE_OFF) { unsigned long current_time = millis(); - // Start scan if requested or periodic scan is due - if (g_wifi_scan_requested || - (current_time - g_last_scan_time > WIFI_SCAN_INTERVAL_MS && !scanning)) { + // Scan only while the network list is on screen and we're not + // connected. Scanning hops the radio across channels (ESP-NOW to B + // 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..."); scanning = true; diff --git a/wiki/log.md b/wiki/log.md index 34072dd..ed44d77 100644 --- a/wiki/log.md +++ b/wiki/log.md @@ -133,3 +133,7 @@ v0.1.3 released (OTA download loop no longer aborts on a momentary TLS connected ## [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. diff --git a/wiki/pages/esp32-s3-touch-lcd-5b.md b/wiki/pages/esp32-s3-touch-lcd-5b.md index c075d16..ce98748 100644 --- a/wiki/pages/esp32-s3-touch-lcd-5b.md +++ b/wiki/pages/esp32-s3-touch-lcd-5b.md @@ -54,7 +54,10 @@ Note: the screen occupies most GPIOs; auxiliary functions (backlight, reset, SD_ - 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 is nearly full** `(verified 2026-09-26)`: 15.9 KB free, largest block 7.6 KB with display + Wi-Fi up (PSRAM 7.1 MB free); the 60-line LVGL draw buffer is ~120 KB of it. Blocked a TLS task outright → [[ota-updates]], [[open-questions]] #13. +- **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 ` (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]]. diff --git a/wiki/pages/open-questions.md b/wiki/pages/open-questions.md index 256ebe1..7af010c 100644 --- a/wiki/pages/open-questions.md +++ b/wiki/pages/open-questions.md @@ -70,6 +70,6 @@ The research frontier. Answering any of these should trigger updates across the - ~~A worked generic-PID set for an M57 diesel~~ ✅ ingested → [[dwr-335d-torque-pids]] (2009 335d, DDE7.3; J1979 mode-01 scalings gauge-checked by the author) - DWR's **Testo parameter list** (e90post "Testo" thread, post 175, German→English names of the DDE's non-standard values) — the pointer for Route B identifiers if our own Launch capture is not enough -13. **Internal RAM is nearly exhausted (found 2026-09-26).** With display + Wi-Fi up: 15.9 KB internal free, largest block 7.6 KB (PSRAM 7.1 MB free). OTA works around it ([[ota-updates]]), but anything else that needs an internal allocation (another task, a TLS client, a bigger Wi-Fi burst) can fail. Biggest known consumer: the LVGL 60-line DMA draw buffer (~120 KB). Options: shrink it to ~30–40 lines, or measure what else lives in internal RAM first (`heap_caps_print_heap_info`). Not urgent, but it limits every future feature. **Same project as the display flicker/lag (2026-09-26):** flash writes flicker the PSRAM-fed RGB panel (no bounce buffer) and full-screen transitions stutter. Espressif's cure is bounce buffers + `CONFIG_SPIRAM_XIP_FROM_PSRAM` (needs pioarduino `custom_sdkconfig`), and bounce buffers need internal RAM — so free RAM, add bounce buffers, and measure real render FPS (LVGL perf monitor; the Debug "FPS" counts `loop()` passes, not frames) in one bench session. Quick mitigations shipped in v0.1.2 (instant screen switches, deferred NVS saves, dark screen during OTA). +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. Housekeeping: **delete the `v0.1.0` release** on Gitea — installing it would strand the board without working OTA (USB only). → [[ota-updates]] +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]] diff --git a/wiki/pages/ota-updates.md b/wiki/pages/ota-updates.md index 510b727..7e07699 100644 --- a/wiki/pages/ota-updates.md +++ b/wiki/pages/ota-updates.md @@ -60,7 +60,7 @@ With the display, Wi-Fi and all tasks up, **internal RAM is nearly exhausted: 15 - This framework's mbedtls is built with `CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y` (~40 KB internal per TLS session → impossible). During a job, `mbedtls_platform_set_calloc_free()` routes TLS to PSRAM, and restores it after (both sides free with `heap_caps_free`, so the swap is safe). - No room for a dedicated 10–16 KB task stack, and a PSRAM stack is forbidden because `esp_ota_write()` disables the flash cache. So jobs run **inside the Arduino loop task** (8 KB internal stack): `ota check` peaked leaving **3.6 KB headroom**. The console and screen value ticks pause while a job runs. -The low internal heap is a system-wide risk beyond OTA (the LVGL 60-line DMA draw buffer alone is ~120 KB of internal SRAM) — see [[open-questions]]. +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)