Add perf console (render fps, flush cost, CPU idle, heap) for the display work; record idle baseline
Firmware / build (push) Successful in 4m8s

This commit is contained in:
2026-09-27 16:43:53 +02:00
parent 43ca6b96ec
commit d3e499efed
8 changed files with 277 additions and 4 deletions
+6 -1
View File
@@ -82,6 +82,7 @@ src/
espnow_link.cpp # ESP-NOW broadcast leg of the link
tuning_screen.cpp # Hand-coded Gauge Tuning screen, 4 tabs (swipe right from Driveline)
diag_probe.cpp # On-demand OBD-II requests ('diag' console) - the ONLY CAN transmitter
perf_monitor.cpp # 'perf' console: render fps, flush cost, LVGL/CPU idle, heap (display experiments)
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
settings_manager.cpp # NVS persistent storage
ui_state_manager.cpp # Debug flag (performance overlay, sent to B)
@@ -103,7 +104,7 @@ include/
**src/main.cpp** (~1530 lines)
- Main application logic, event handlers, FreeRTOS task implementations
- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`), setup order, `loop()` ticks for the three screens
- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`), setup order, `loop()` ticks for the three screens
**include/protocol/automotive_data.h**
- **Shared with Controller B, must stay byte-identical in both repos.** Protocol v2 (2026-09-21).
@@ -213,6 +214,10 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
`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: Settings → Updates (Check, then Install behind a confirm dialog; verified end-to-end from the screen 2026-09-27) or the console `ota status | check | install [force] | rollback`. `Ota::getStatus()` gives the screen a phase + latest tag + failure reason. 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). Wi-Fi is joined on the Settings screen (remembered) or with `wifi join`. Details: `wiki/pages/ota-updates.md`.
### Performance monitor (`perf` console)
`src/modules/perf_monitor.cpp` hooks the LVGL port (`monitor_cb` per rendered frame, a timer around `drawBitmap()` in `flush_callback`) and reads FreeRTOS run-time stats. `perf` prints one `PERF,` CSV line (ts, fps, avg/max ms per frame, kpx per frame, ms per second spent copying into the PSRAM framebuffer, LVGL idle %, core 0/1 idle %, internal free/largest, PSRAM free); `perf on [sec]` prints one every few seconds while a symptom is provoked; `perf off`. This is the measuring stick for the display work in wiki open-questions #13 - record numbers before and after every change. Baseline (idle Driveline, bench, 2026-09-27): ~9.7 fps rendered, ~30 ms per frame, ~52 ms/s in flushes, LVGL idle ~68 %, core 1 idle ~66 %.
### 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. 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.
+28 -1
View File
@@ -9,6 +9,8 @@
#define ESP_UTILS_LOG_TAG "LvPort"
#include "esp_lib_utils.h"
#include "lvgl_v8_port.h"
#include "modules/perf_monitor.h"
#include "esp_timer.h"
using namespace esp_panel::drivers;
@@ -478,14 +480,27 @@ void flush_callback(lv_disp_drv_t *drv, const lv_area_t *area, lv_color_t *color
const int offsetx2 = area->x2;
const int offsety1 = area->y1;
const int offsety2 = area->y2;
const int w = offsetx2 - offsetx1 + 1;
const int h = offsety2 - offsety1 + 1;
lcd->drawBitmap(offsetx1, offsety1, offsetx2 - offsetx1 + 1, offsety2 - offsety1 + 1, (const uint8_t *)color_map);
// Time the pixel copy into the (PSRAM) framebuffer - this is the PSRAM
// write cost the display experiments (open question #13) change.
const int64_t t0 = esp_timer_get_time();
lcd->drawBitmap(offsetx1, offsety1, w, h, (const uint8_t *)color_map);
PerfMon::onFlush((uint32_t)(esp_timer_get_time() - t0), (uint32_t)(w * h));
// For RGB LCD, directly notify LVGL that the buffer is ready
if (lcd->getBus()->getBasicAttributes().type == ESP_PANEL_BUS_TYPE_RGB) {
lv_disp_flush_ready(drv);
}
}
// LVGL calls this once per rendered frame (render + flush time, pixels drawn).
static void monitor_callback(lv_disp_drv_t *drv, uint32_t time_ms, uint32_t px)
{
(void)drv;
PerfMon::onFrame(time_ms, px);
}
static void update_callback(lv_disp_drv_t *drv)
{
LCD *lcd = (LCD *)drv->user_data;
@@ -605,6 +620,9 @@ static lv_disp_t *display_init(LCD *lcd)
ESP_UTILS_LOGD("Register display driver to LVGL");
lv_disp_drv_init(&disp_drv);
disp_drv.flush_cb = flush_callback;
#if LVGL_PORT_AVOID_TEARING_MODE == 0
disp_drv.monitor_cb = monitor_callback;
#endif
#if (LVGL_PORT_ROTATION_DEGREE == 90) || (LVGL_PORT_ROTATION_DEGREE == 270)
disp_drv.hor_res = lcd_height;
disp_drv.ver_res = lcd_width;
@@ -815,6 +833,15 @@ bool lvgl_port_lock(int timeout_ms)
return (xSemaphoreTakeRecursive(lvgl_mux, timeout_ticks) == pdTRUE);
}
bool lvgl_port_lock_available(void)
{
if (!lvgl_port_lock(0)) {
return false;
}
lvgl_port_unlock();
return true;
}
bool lvgl_port_unlock(void)
{
ESP_UTILS_CHECK_NULL_RETURN(lvgl_mux, false, "LVGL mutex is not initialized");
+8
View File
@@ -171,6 +171,14 @@ bool lvgl_port_lock(int timeout_ms);
*/
bool lvgl_port_unlock(void);
/**
* @brief Try the LVGL lock without waiting and release it at once.
* Used by the perf monitor to read lv_timer_get_idle() only when the
* UI task is not mid-render (the value is a plain int, so a stale read
* is harmless; a blocked console is not).
*/
bool lvgl_port_lock_available(void);
#ifdef __cplusplus
}
#endif
+5 -1
View File
@@ -13,6 +13,7 @@
#include "modules/settings_screen.h" // Hand-coded settings screen (swipe left from Driveline)
#include "modules/serial_lock.h" // Global serial write mutex
#include "modules/tunables.h" // Gauge calibration + alert thresholds (NVS, serial console)
#include "modules/perf_monitor.h" // `perf` console: render fps, flush cost, CPU idle, heap
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B
#include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
@@ -57,7 +58,8 @@ static bool memCommand(const char* line) {
// 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) || memCommand(line);
WiFiManager::handleCommand(line) || memCommand(line) ||
PerfMon::handleCommand(line);
}
// ============================================================================
@@ -94,6 +96,7 @@ void setup()
Tunables::init();
DiagProbe::init();
Tunables::setExtraCommandHandler(consoleExtraCommand);
PerfMon::init();
// Load saved switch states from NVS
ESP_LOGI("MAIN", "Loading saved switch states from NVS...");
@@ -154,6 +157,7 @@ void loop()
// LVGL renders in its own task; the screen ticks below only refresh values.
// Serial console: gauge tunables (cfg ...), diagnostic probe (diag ...), updates (ota ...)
Tunables::pollSerial();
PerfMon::tick();
DiagProbe::tick();
Ota::tick(); // confirms a freshly installed image after healthy uptime
+179
View File
@@ -0,0 +1,179 @@
/*
* Performance Monitor implementation. See perf_monitor.h.
*
* onFrame()/onFlush() run in the LVGL task; everything else in loop(). The
* counters are plain 32-bit words read under a short critical section, so the
* hooks cost nothing measurable.
*/
#include "perf_monitor.h"
#include "serial_lock.h"
#include "display/lvgl_v8_port.h"
#include <lvgl.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <string.h>
namespace PerfMon {
// ---- accumulators (LVGL task writes, loop reads) ---------------------------
static portMUX_TYPE g_mux = portMUX_INITIALIZER_UNLOCKED;
static uint32_t g_frames = 0;
static uint32_t g_frame_ms_sum = 0;
static uint32_t g_frame_ms_max = 0;
static uint32_t g_frame_px_sum = 0;
static uint32_t g_flushes = 0;
static uint32_t g_flush_us_sum = 0;
static uint32_t g_flush_px_sum = 0;
// ---- window bookkeeping (loop) --------------------------------------------
static int64_t g_window_start_us = 0;
static uint64_t g_idle_start[2] = {0, 0};
static bool g_periodic = false;
static uint32_t g_period_ms = 1000;
static uint32_t g_last_report_ms = 0;
static void print(const char* fmt, ...) {
char buf[240];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static uint64_t idleCounter(int core) {
#if CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
// Run-time counter unit is microseconds (esp_timer) on ESP-IDF.
return (uint64_t)ulTaskGetIdleRunTimeCounterForCore(core);
#else
(void)core;
return 0;
#endif
}
static void resetWindow() {
portENTER_CRITICAL(&g_mux);
g_frames = g_frame_ms_sum = g_frame_ms_max = g_frame_px_sum = 0;
g_flushes = g_flush_us_sum = g_flush_px_sum = 0;
portEXIT_CRITICAL(&g_mux);
g_window_start_us = esp_timer_get_time();
g_idle_start[0] = idleCounter(0);
g_idle_start[1] = idleCounter(1);
}
void init() {
resetWindow();
}
void onFrame(uint32_t time_ms, uint32_t px) {
portENTER_CRITICAL(&g_mux);
g_frames++;
g_frame_ms_sum += time_ms;
if (time_ms > g_frame_ms_max) g_frame_ms_max = time_ms;
g_frame_px_sum += px;
portEXIT_CRITICAL(&g_mux);
}
void onFlush(uint32_t time_us, uint32_t px) {
portENTER_CRITICAL(&g_mux);
g_flushes++;
g_flush_us_sum += time_us;
g_flush_px_sum += px;
portEXIT_CRITICAL(&g_mux);
}
/** Emit one PERF line for the window since the last reset, then reset. */
static void report() {
int64_t now_us = esp_timer_get_time();
uint64_t win_us = (uint64_t)(now_us - g_window_start_us);
if (win_us < 1000) win_us = 1000;
uint32_t frames, ms_sum, ms_max, px_sum, flushes, fl_us, fl_px;
portENTER_CRITICAL(&g_mux);
frames = g_frames; ms_sum = g_frame_ms_sum; ms_max = g_frame_ms_max; px_sum = g_frame_px_sum;
flushes = g_flushes; fl_us = g_flush_us_sum; fl_px = g_flush_px_sum;
portEXIT_CRITICAL(&g_mux);
uint64_t idle0 = idleCounter(0) - g_idle_start[0];
uint64_t idle1 = idleCounter(1) - g_idle_start[1];
unsigned idle0_pct = (unsigned)((idle0 * 100) / win_us);
unsigned idle1_pct = (unsigned)((idle1 * 100) / win_us);
if (idle0_pct > 100) idle0_pct = 100;
if (idle1_pct > 100) idle1_pct = 100;
// fps x10 for one decimal without floats in the format
unsigned fps10 = (unsigned)((uint64_t)frames * 10000000ULL / win_us);
unsigned avg_ms10 = frames ? (ms_sum * 10) / frames : 0;
unsigned kpx = frames ? (px_sum / frames) / 1000 : 0;
unsigned flush_ms_per_s = (unsigned)(((uint64_t)fl_us * 1000ULL) / win_us); // ms of copying per second
unsigned lv_idle = 0;
if (lvgl_port_lock_available()) {
lv_idle = lv_timer_get_idle();
}
print("PERF,%lu,%u.%u,%u.%u,%lu,%u,%u,%u,%u,%u,%u,%u,%u",
(unsigned long)millis(),
fps10 / 10, fps10 % 10,
avg_ms10 / 10, avg_ms10 % 10,
(unsigned long)ms_max,
kpx,
flush_ms_per_s,
lv_idle,
idle0_pct, idle1_pct,
(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));
(void)flushes; (void)fl_px;
resetWindow();
}
static void help() {
print("perf one PERF line for the window since the last report");
print("perf on [sec] PERF line every <sec> seconds (default 1) while you provoke symptoms");
print("perf off");
print("PERF,ts,fps,avg_ms,max_ms,kpx/frame,flush_ms/s,lvgl_idle%%,idle0%%,idle1%%,int_free,int_largest,psram_free");
}
bool handleCommand(const char* line) {
char buf[48];
strncpy(buf, line, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
char* argv[3] = {0};
int argc = 0;
for (char* tok = strtok(buf, " \t"); tok && argc < 3; tok = strtok(NULL, " \t")) argv[argc++] = tok;
if (argc == 0 || strcmp(argv[0], "perf") != 0) return false;
if (argc == 1) { report(); return true; }
if (!strcmp(argv[1], "help")) { help(); return true; }
if (!strcmp(argv[1], "on")) {
long s = (argc == 3) ? strtol(argv[2], NULL, 10) : 1;
if (s < 1) s = 1;
if (s > 60) s = 60;
g_period_ms = (uint32_t)s * 1000;
g_periodic = true;
g_last_report_ms = millis();
resetWindow();
print("[perf] periodic every %ld s (columns: ts,fps,avg_ms,max_ms,kpx,flush_ms/s,lv_idle,idle0,idle1,int_free,int_largest,psram)", s);
return true;
}
if (!strcmp(argv[1], "off")) { g_periodic = false; print("[perf] periodic off"); return true; }
help();
return true;
}
void tick() {
if (!g_periodic) return;
uint32_t now = millis();
if (now - g_last_report_ms >= g_period_ms) {
g_last_report_ms = now;
report();
}
}
} // namespace PerfMon
+46
View File
@@ -0,0 +1,46 @@
/*
* Performance Monitor
*
* Measures what the display pipeline actually does, so display experiments
* (bounce buffers, draw-buffer size, XIP from PSRAM - wiki open question #13)
* can be compared with numbers instead of impressions:
*
* - render frames/s and ms per frame (LVGL's monitor_cb: render + flush)
* - time spent copying pixels into the PSRAM framebuffer (flush_cb)
* - LVGL task idle % (lv_timer_get_idle)
* - CPU idle % per core (FreeRTOS run-time stats)
* - internal heap, largest block, PSRAM free
*
* Console:
* perf one line for the last window
* perf on [sec] print a PERF, line every <sec> s (default 1) - use while
* provoking symptoms (Wi-Fi scan, tuning save, OTA)
* perf off
*
* PERF line (CSV, greppable like CANRAW):
* PERF,<ts_ms>,<fps>,<avg_ms>,<max_ms>,<kpx/frame>,<flush_ms/s>,
* <lvgl_idle%>,<idle0%>,<idle1%>,<int_free>,<int_largest>,<psram_free>
*/
#pragma once
#include <Arduino.h>
namespace PerfMon {
/** Call once in setup(), before the LVGL port starts. */
void init();
/** Hook for lv_disp_drv_t::monitor_cb - one rendered frame (ms, pixels). */
void onFrame(uint32_t time_ms, uint32_t px);
/** Hook for the flush callback - one pixel copy into the framebuffer. */
void onFlush(uint32_t time_us, uint32_t px);
/** Console line beginning with "perf". */
bool handleCommand(const char* line);
/** Periodic reporting. Call from loop(). */
void tick();
} // namespace PerfMon
+4
View File
@@ -154,3 +154,7 @@ User asked whether VOUT becomes 5 V by "unsoldering the resistor". Re-fetched `E
I argued for the cheap half only (baseline, 40-line draw buffer, time-boxed bounce buffers) and deferring XIP-from-PSRAM as cosmetic. User corrected two premises: the dots still appear occasionally on v0.1.6 (the "gone" claim on [[esp32-s3-touch-lcd-5b]] was too strong — now qualified), and a dark screen during OTA is a safety/UX defect (no feedback → driver may turn the ignition off mid-update). Decision (user): fix everything, all steps through XIP, bench time is no constraint; add an on-screen progress bar + "do not switch off" during updates. Recorded on [[open-questions]] #13. Also explained in plain terms why the coolant duty law still needs re-deriving through the FET stage ([[patrol-instrument-cluster]]); that remains the higher-priority car-facing item.
## [2026-09-27] build | `perf` console: the measuring stick for open question 13
Step 1 of the display plan. New `src/modules/perf_monitor.cpp`: LVGL `monitor_cb` (frames, ms/frame, px), a timer around `drawBitmap()` in the port's flush callback (ms per second spent writing the PSRAM framebuffer), `lv_timer_get_idle()`, FreeRTOS run-time stats for per-core idle (enabled in the Arduino core's sdkconfig), heap figures. `perf` / `perf on [sec]` / `perf off`; `PERF,` CSV lines sit next to `CANRAW` in a session log. Built and flashed COM14 (the 5B enumerates as COM14 today; the 1.3 as COM13). Idle baseline recorded on [[open-questions]] #13. Next: the provoke session (Wi-Fi scan, tuning save, OTA) with `perf on 1` logging, then bounce buffers.
+1 -1
View File
@@ -75,7 +75,7 @@ The research frontier. Answering any of these should trigger updates across the
**Decision 2026-09-27 (user): this is a must-fix, all steps through XIP, bench time is no constraint.** Two corrections to the record: (a) the flickering dots **still appear occasionally** on v0.1.6 — the scan policy reduced the trigger, it did not remove the weakness; (b) the dark screen during OTA is a **safety/UX defect**, not a mitigation: with no feedback a driver may switch the ignition off mid-update. Requirement: the screen stays on during an update with a visible progress bar and a "do not switch off" message — which needs Step B (flash writes must stop blanking the panel), plus an OTA progress callback on the Updates page. (The OTA design already survives a power cut — the new image is only confirmed after 30 s, else it rolls back — so the risk is a wasted update and a confused user, not a bricked board.)
**Plan agreed 2026-09-27 (next display session, bench + USB, `dev` builds only until verified):**
1. **Baseline first**: Settings → System → Performance overlay (LVGL's perf monitor = real render FPS + CPU; never measured before). Provoke each symptom on purpose: a Wi-Fi scan (dots), a Tuning edit that gets saved (flash write), an update (flash writes). Without numbers there is no telling whether a change helped.
1. **Baseline first**: Settings → System → Performance overlay (LVGL's perf monitor = real render FPS + CPU; never measured before). Provoke each symptom on purpose: a Wi-Fi scan (dots), a Tuning edit that gets saved (flash write), an update (flash writes). Without numbers there is no telling whether a change helped. **Tooling landed 2026-09-27 `(repo)`**: the `perf` console command (`perf on 1` streams a `PERF,` CSV line per second: fps, ms/frame, flush ms/s, LVGL idle, core idle, heap). **Idle baseline, Driveline screen, bench/USB, v0.1.6+perf**: 9.7 fps rendered (= the screen's own update rate), 30 ms per frame avg (122 ms worst in the first window), ~40 kpx/frame, 52 ms/s copying into the PSRAM framebuffer, LVGL idle 68 %, core 0 idle 94 %, core 1 idle 66 %, internal 66.9 KB free / 31.7 KB largest, PSRAM 6.6 MB free. Provoke runs (scan / tuning save / OTA) still to be logged.
2. **Step A - bounce buffers only** (`ESP_PANEL_LCD_RGB_BOUNCE_BUF_SIZE`, today 0; start at 10 lines = 1024x10 px, ~20 KB each, two buffers, internal DMA-capable RAM). The panel then reads from internal RAM that the CPU refills from PSRAM, so it tolerates short PSRAM stalls. **Expected to cure the Wi-Fi-traffic dots; will NOT cure flash-write flicker**: while flash is written the cache is disabled, so the refill has nothing to read from either. RAM: 67 KB internal free but the largest block is ~32 KB, so two 20 KB buffers may not fit - if not, shrink the LVGL draw buffer 60 -> 40 lines (frees ~40 KB) and check render speed. The refill costs CPU (measure).
3. **Step B - `CONFIG_SPIRAM_XIP_FROM_PSRAM` (+ `CONFIG_SPIRAM_RODATA`)** via pioarduino `custom_sdkconfig`: code and constants run from PSRAM, so flash writes no longer block PSRAM. **Cures flash-write flicker** (screen could stay on during OTA with a progress bar instead of going dark). Cost/risk: `custom_sdkconfig` rebuilds the Arduino core from source (much slower builds, locally and in CI), and may not work cleanly with this platform version - do it on a branch, release only once it works.
4. **Measure again after each step** (FPS, CPU, which symptoms still reproduce) and record the numbers here and on [[esp32-s3-touch-lcd-5b]].