diff --git a/CLAUDE.md b/CLAUDE.md index 6ab6264..27faba4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ Automotive display controller for **Waveshare ESP32-S3-Touch-LCD-5B** (1024x600 **Hardware**: ESP32-S3 dual-core @ 240MHz, 16MB Flash, 8MB OPI PSRAM, 5-inch capacitive touch LCD -**Key Features**: WiFi scanning, UART data transmission @ 5Hz, debug metrics (FPS/CPU), NVS settings persistence, LVGL 8.4.0 UI (SquareLine Studio exports) +**Key Features**: CAN decode, link to B (UART + ESP-NOW @ 5 Hz), remembered Wi-Fi + on-screen OTA updates, gauge tuning, NVS settings persistence, LVGL 8.4.0 UI (hand-coded screens) ## Build & Development Commands @@ -74,15 +74,17 @@ The project follows a clean, organized structure with logical separation of conc src/ main.cpp # Main application logic only modules/ - wifi_manager.cpp # WiFi scanning and connection + wifi_manager.cpp # Wi-Fi: one remembered network, scans on request (no LVGL code) + settings_screen.cpp # Hand-coded Settings screen: Wi-Fi / Updates / System (swipe left from Driveline) + ui_kit.cpp # Shared look for hand-coded screens: header, buttons, switches, confirm dialog uart_manager.cpp # Link transmitter: v2 DATA/CONFIG frames on UART1 + ESP-NOW tunables.cpp # Gauge calibration + alert thresholds (NVS, 'cfg' serial console) espnow_link.cpp # ESP-NOW broadcast leg of the link - tuning_screen.cpp # Hand-coded LVGL Gauge Tuning screen (swipe right from Driveline) + 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 ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console) settings_manager.cpp # NVS persistent storage - ui_state_manager.cpp # UI synchronization logic + ui_state_manager.cpp # Debug flag (performance overlay, sent to B) display_init.cpp # Display initialization; boots into DrivelineScreen driveline_screen.cpp # Hand-coded LVGL boot screen (gear, temps, rpm, status) drivers/ @@ -103,10 +105,7 @@ include/ **src/main.cpp** (~1530 lines) - Main application logic, event handlers, FreeRTOS task implementations -- WiFi state machine: `wifiTask()` on Core 0 with async scanning -- UART state machine: `uartTask()` on Core 0 with periodic transmission -- Settings synchronization: `applySavedStatesToUI()` syncs toggle states when Settings screen loads -- Thread-safe UI updates via `lvgl_port_lock()`/`unlock()` +- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`), 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). @@ -134,11 +133,8 @@ include/ - LVGL 8.4.0 configuration file - Memory settings, theme configuration, widget enables -**include/ui/** directory (SquareLine Studio exports) -- `ui_Settings_Screen.c/h`: WiFi, UART, CAN Bus, Debug toggle switches and containers. Its right-swipe calls `app_show_driveline()` (C entry point in `driveline_screen.cpp`) -- The SquareLine **Home screen was removed on 2026-09-21** (its meters module too). `ui_init()` loads an empty placeholder; `display_init.cpp` then shows the Driveline screen. If SquareLine re-exports a Home screen, delete it from the SquareLine project — do not wire it back in -- External UI references: `uic_Toggle_Wifi_Switch`, `uic_Toggle_UART_Switch`, `uic_Toggle_CAN_Bus_Switch`, `uic_Toggle_Debug_Switch`, `uic_Wifi_Container`, `uic_Settings_Loading_Container`, `uic_Device_State_Container` -- Event handlers: `onWifiToggle()`, `onUARTToggle()`, `onCANBusToggle()`, `onDebugToggle()` +**include/ui/** directory (SquareLine Studio exports) - now only `ui_init()` (theme + an empty placeholder screen) and helpers +- **No SquareLine screens remain**: Home was removed 2026-09-21, Settings on 2026-09-27 (replaced by `settings_screen.cpp`). Every screen is hand-coded in `src/modules`. If SquareLine ever re-exports a screen, delete it from the SquareLine project - do not wire it back in - **Important**: SquareLine Studio exports to `include/ui/` directory to avoid overwriting custom code in `src/` ### NVS Persistent Storage @@ -147,32 +143,17 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): - Namespace: "settings" - Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en` (boolean values) - Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()` +- Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed ### WiFi Architecture -**State Machine**: `WIFI_STATE_OFF` → `WIFI_STATE_SCANNING` → `WIFI_STATE_SCAN_COMPLETE` → `WIFI_STATE_CONNECTED` +`WiFiManager` (`wifi_manager.cpp`) owns **no LVGL objects**: the Settings screen polls `getStatus()` / `getNetworks()` and calls `setEnabled()`, `requestScan()`, `connect()`, `connectSaved()`, `forget()`. All radio work runs in `wifiTask()` (Core 0) from a command queue. -**Task Communication**: -- Main thread → WiFi task: Via `g_wifi_event_queue` (FreeRTOS queue) -- 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**: -1. User clicks SSID button → `onSSIDButtonClick()` -2. If secured: Show `uic_Wifi_Passkey_TB` (password text area) + `uic_Keyboard` -3. User enters password → `onKeyboardEvent()` (LV_EVENT_READY) -4. Allocate `wifi_credentials_t`, send `WIFI_UI_EVENT_CONNECT` to WiFi task -5. WiFi task: `WiFi.begin(ssid, password)` with 10-second timeout -6. Result: `showConnectionResult()` updates UI with success/failure +- **One remembered network** (NVS namespace `wifi`), saved after a successful join, joined automatically ~3 s after boot when Wi-Fi is on (verified 2026-09-27) +- **Scans only on request** (Wi-Fi page opened while not connected, or the Scan button) - background scans every 10 s caused display glitches and hop the radio ESP-NOW uses +- **No endless reconnect**: `setAutoReconnect(false)`; one attempt at boot, one retry after a drop, then idle back on `ESPNOW_CHANNEL` +- Failure reasons come from the STA_DISCONNECTED event (wrong password, not in range, ...) and show on the screen +- Console: `wifi status | join [pass] | forget | scan | on | off` ### UART Architecture @@ -226,7 +207,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): ### Tunables (gauge calibration, alert thresholds) -`src/modules/tunables.cpp` owns `link_config_t`: tach pulses/rev + trim + clamps, coolant PWM frequency + duty law + min temp, per-output enables, a bench override (force rpm / duty), and the alert thresholds. Stored as an NVS blob (namespace `tunables`), 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 `, `cfg override rpm | duty | both | 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()`, `isDirty()` drives the screen's save indicator) - every flash write flickers the RGB panel, so no write per tap. Edited over the USB serial console: `cfg show`, `cfg set `, `cfg override rpm | duty | both | 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`, see Screens) edits the same values with −/+ buttons, enable switches, and a Simulation tab with RPM and duty sliders. Overrides are never written to NVS (`save()` strips them). ### Diagnostic probe (`diag` console) @@ -234,28 +215,21 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): ### 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`). 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 [pass] | status | off` (in `wifi_manager.cpp`) joins a network from the console. 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: 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`. ### 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. -### UI State Synchronization +### Screens -**Problem**: SquareLine Studio screens get destroyed/recreated when swiping between screens, losing runtime state. +All hand-coded in `src/modules`, built once and kept (never deleted - SquareLine's delete-on-leave caused dangling pointers and the 2026-09-27 freezes). Shared look in `ui_kit.cpp` (20/24 px text, >= 56 px touch targets, no shadows/animations, `UiKit::confirm()` modal dialog). Each screen has a `tick()` called from `loop()` that refreshes values under the LVGL lock, only while it is shown, and only re-sets label text that changed. -**Solution**: `applySavedStatesToUI()` function (called continuously in `loop()`) -- Detects when Settings screen loads by checking if `uic_Toggle_Wifi_Switch != NULL` -- Tracks screen instance via `g_last_synced_screen` pointer to prevent redundant syncing -- Syncs toggle switches with actual service states: `g_wifi_state`, `g_uart_state`, `g_debug_enabled` -- Shows loading spinner during sync for smooth UX - -**Screens**: Driveline (boot, hand-coded) ← swipe left → Settings (SquareLine); Driveline → swipe right → Gauge Tuning (hand-coded). Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`): full-screen fades are software-blended every frame and stutter at 1024x600. The firmware version is a label on `lv_layer_top()` (bottom-right, every screen, `DisplayInit`). - -**Debug Mode**: -- Toggle in Settings screen shows/hides `uic_Device_State_Container` -- Updates FPS (`uic_FPS_Values_LBL`) and CPU usage (`uic_CPU_Values_LBL`) every second -- Frame counting: `g_frame_count` incremented in `updateDebugMetrics()` called from `loop()` +- **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning +- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (installed vs latest, Check, Install behind a confirm dialog -> `Ota::requestCheck/requestInstall`), **System** (CAN / link to B / performance overlay switches, live ESP-NOW, CAN, memory, uptime). Swipe right or the Driveline button goes back +- **Gauge Tuning** (`tuning_screen.cpp`) - tabs Tachometer / Coolant gauge / Alerts / Simulation; -/+ rows with hints (hold to repeat, speeds up), per-tab Reset with confirm, "Saving... / All changes saved" footer, SIMULATION ON chip while an override is active. Swipe left or the Driveline button goes back +- 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`) +- The System page's "Performance overlay" switch shows LVGL's own perf monitor (real render FPS / CPU) and sets the debug flag sent to B ## Configuration Files @@ -289,35 +263,9 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage): ## Common Patterns -### Adding a New Toggle Switch +### Adding a New Setting -1. Add NVS keys in main.cpp: - ```cpp - #define NVS_KEY_FEATURE_ENABLED "feature_en" - ``` - -2. Add save/load functions: - ```cpp - void saveFeatureState(bool enabled) { - preferences.begin(NVS_NAMESPACE, false); - preferences.putBool(NVS_KEY_FEATURE_ENABLED, enabled); - preferences.end(); - } - ``` - -3. Add global state variable: `static bool g_feature_enabled = false;` - -4. Create event handler (called from SquareLine UI): - ```cpp - void onFeatureToggle(lv_event_t *e) { - lv_obj_t *target = lv_event_get_target(e); - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); - saveFeatureState(state); - // Update state, send to task if needed - } - ``` - -5. Add sync logic in `applySavedStatesToUI()` to restore state when Settings screen loads +See "Adding a setting" under Important Notes: a row + `UiKit::toggle()` on the Settings screen, a `SettingsManager` save/load pair, and a sync line in the page's `refresh*()`. ### Thread-Safe UI Update from Background Task @@ -360,6 +308,7 @@ xTaskCreatePinnedToCore( - **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) - **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` +- **Uploading from a script/pipe on Windows**: set `PYTHONIOENCODING=utf-8` (and `PYTHONUTF8=1`). Otherwise esptool crashes printing its progress bar to a cp1252 pipe *mid-write* and leaves the board frozen until a power cycle (happened 2026-09-27; the bootloader then fell back to the other OTA slot) ### Display Panel @@ -392,7 +341,7 @@ xTaskCreatePinnedToCore( - **Screen drift/artifacts**: RGB LCD timing issue - already optimized in `platformio.ini` with high-performance platform packages - **White flash on boot**: Backlight control sequence in setup() minimizes this (lines 1383-1414) -- **UI toggles don't match state**: Check `applySavedStatesToUI()` is called in `loop()` - this syncs UI with running services +- **UI switches don't match state**: `SettingsScreen::tick()` must run in `loop()` - it re-reads the live state every 250 ms - **WiFi/UART task not responding**: Check FreeRTOS queue creation succeeded (NULL check in setup()) - **LVGL crash from background task**: Ensure `lvgl_port_lock()` / `unlock()` wraps ALL LVGL API calls - **Screen flickering**: This was resolved by fixing the proper board configuration and partition table. The key fixes were: @@ -414,6 +363,6 @@ xTaskCreatePinnedToCore( ## Important Notes - **SquareLine Studio Export**: ALWAYS export UI files to `ui/` directory, NEVER to `src/` (prevents overwriting main.cpp) -- **Event Handler Registration**: Event handlers for SquareLine UI elements are registered in `ui_Settings_Screen.c` auto-generated code. When adding new toggles, add event callback registration via `lv_obj_add_event_cb()` and declare handler in `ui_events.h` +- **Adding a setting**: add a row to the right page in `settings_screen.cpp` (`makeSettingRow()` + `UiKit::toggle()`), persist it via `SettingsManager`, and sync it in that page's `refresh*()` function - **CAN Bus Integration**: BMW CAN IDs are defined in `automotive_data.h` (all 11-bit standard frames, verified live on the swap bus). The CAN driver runs in `TWAI_MODE_NORMAL` (it ACKs frames; not LISTEN_ONLY). Evidence and confidence labels live in `wiki/pages/can-id-candidates.md`. Never add a second caller of `CANDriver::transmit()` without a design discussion — transmitting on the vehicle bus is a safety decision -- **Security**: Password field (`uic_Wifi_Passkey_TB`) is cleared after connection attempt for security (line 1015, 1029) +- **Security**: the Wi-Fi password field is cleared when the password page closes; the saved password lives only in NVS and is never logged (the pre-2026-09-27 code printed it on every join) diff --git a/include/config/lv_conf.h b/include/config/lv_conf.h index 9383cfb..399f7de 100644 --- a/include/config/lv_conf.h +++ b/include/config/lv_conf.h @@ -376,9 +376,9 @@ #define LV_FONT_MONTSERRAT_14 1 #define LV_FONT_MONTSERRAT_16 0 #define LV_FONT_MONTSERRAT_18 0 -#define LV_FONT_MONTSERRAT_20 0 +#define LV_FONT_MONTSERRAT_20 1 #define LV_FONT_MONTSERRAT_22 0 -#define LV_FONT_MONTSERRAT_24 0 +#define LV_FONT_MONTSERRAT_24 1 #define LV_FONT_MONTSERRAT_26 0 #define LV_FONT_MONTSERRAT_28 0 #define LV_FONT_MONTSERRAT_30 1 diff --git a/include/drivers/can_driver.h b/include/drivers/can_driver.h index 59b1072..bfc62ff 100644 --- a/include/drivers/can_driver.h +++ b/include/drivers/can_driver.h @@ -178,10 +178,9 @@ namespace CANDriver { void setVerboseDecode(bool enabled); /** - * UI event handler for CAN toggle switch - * @param e LVGL event + * Settings-screen switch: start/stop the CAN task and remember the choice in NVS. */ - void onCANToggle(lv_event_t *e); + void setEnabled(bool enabled); } #endif // _CAN_DRIVER_H diff --git a/include/ui/CMakeLists.txt b/include/ui/CMakeLists.txt index 7063356..5690e29 100644 --- a/include/ui/CMakeLists.txt +++ b/include/ui/CMakeLists.txt @@ -1,5 +1,4 @@ -SET(SOURCES screens/ui_Settings_Screen.c - ui_theme_manager.c +SET(SOURCES ui_theme_manager.c ui_themes.c ui.c components/ui_comp_hook.c diff --git a/include/ui/filelist.txt b/include/ui/filelist.txt index b0c0d91..76453f7 100644 --- a/include/ui/filelist.txt +++ b/include/ui/filelist.txt @@ -1,4 +1,3 @@ -screens/ui_Settings_Screen.c ui_theme_manager.c ui_themes.c ui.c diff --git a/include/ui/screens/ui_Settings_Screen.c b/include/ui/screens/ui_Settings_Screen.c deleted file mode 100644 index c54eabd..0000000 --- a/include/ui/screens/ui_Settings_Screen.c +++ /dev/null @@ -1,552 +0,0 @@ -// This file was generated by SquareLine Studio -// SquareLine Studio version: SquareLine Studio 1.5.4 -// LVGL version: 8.3.6 -// Project name: ESP32-S3-Touch-LCD-5B - -#include "../ui.h" - -// Hand-coded Driveline screen (src/modules/driveline_screen.cpp) - replaces Home -void app_show_driveline(void); - -lv_obj_t * uic_Settings_Loading_Spinner; -lv_obj_t * uic_Settings_Loading_Container; -lv_obj_t * uic_CPU_Values_LBL; -lv_obj_t * uic_FPS_Values_LBL; -lv_obj_t * uic_Device_State_Values_LBL; -lv_obj_t * uic_CPU_Static_LBL; -lv_obj_t * uic_FPS_Static_LBL; -lv_obj_t * uic_Static_LBLS_Container; -lv_obj_t * uic_Device_State_Container; -lv_obj_t * uic_Keyboard; -lv_obj_t * uic_Wifi_Passkey_TB; -lv_obj_t * uic_Select_SSID_BTN; -lv_obj_t * uic_Wifi_Container; -lv_obj_t * uic_Enable_Debug_LBL; -lv_obj_t * uic_Toggle_Debug_Switch; -lv_obj_t * uic_Debug_CTRL_Panel; -lv_obj_t * uic_Enable_BLE_LBL; -lv_obj_t * uic_Toggle_BLE_Switch; -lv_obj_t * uic_BLE_CTRL_Panel; -lv_obj_t * uic_Enable_Wifi_LBL; -lv_obj_t * uic_Toggle_Wifi_Switch; -lv_obj_t * uic_Wifi_CTRL_Panel; -lv_obj_t * uic_Enable_UART_LBL; -lv_obj_t * uic_Toggle_UART_Switch; -lv_obj_t * uic_UART_CTRL_Panel; -lv_obj_t * uic_Enable_CAN_Bus_LBL; -lv_obj_t * uic_Toggle_CAN_Bus_Switch; -lv_obj_t * uic_CAN_Bus_CTRL_Panel; -lv_obj_t * uic_Settings_CTRL_Container; -lv_obj_t * uic_Main_Container; -lv_obj_t * uic_Settings_Screen_LBL; -lv_obj_t * uic_Settings_Screen; -lv_obj_t * ui_Settings_Screen = NULL; -lv_obj_t * ui_Settings_Screen_LBL = NULL; -lv_obj_t * ui_Main_Container = NULL; -lv_obj_t * ui_Settings_CTRL_Container = NULL; -lv_obj_t * ui_CAN_Bus_CTRL_Panel = NULL; -lv_obj_t * ui_Toggle_CAN_Bus_Switch = NULL; -lv_obj_t * ui_Enable_CAN_Bus_LBL = NULL; -lv_obj_t * ui_UART_CTRL_Panel = NULL; -lv_obj_t * ui_Toggle_UART_Switch = NULL; -lv_obj_t * ui_Enable_UART_LBL = NULL; -lv_obj_t * ui_Wifi_CTRL_Panel = NULL; -lv_obj_t * ui_Toggle_Wifi_Switch = NULL; -lv_obj_t * ui_Enable_Wifi_LBL = NULL; -lv_obj_t * ui_BLE_CTRL_Panel = NULL; -lv_obj_t * ui_Toggle_BLE_Switch = NULL; -lv_obj_t * ui_Enable_BLE_LBL = NULL; -lv_obj_t * ui_Debug_CTRL_Panel = NULL; -lv_obj_t * ui_Toggle_Debug_Switch = NULL; -lv_obj_t * ui_Enable_Debug_LBL = NULL; -lv_obj_t * ui_Wifi_Container = NULL; -lv_obj_t * ui_Select_SSID_BTN = NULL; -lv_obj_t * ui_Wifi_Passkey_TB = NULL; -lv_obj_t * ui_Keyboard = NULL; -lv_obj_t * ui_Device_State_Container = NULL; -lv_obj_t * ui_Static_LBLS_Container = NULL; -lv_obj_t * ui_FPS_Static_LBL = NULL; -lv_obj_t * ui_CPU_Static_LBL = NULL; -lv_obj_t * ui_Device_State_Values_LBL = NULL; -lv_obj_t * ui_FPS_Values_LBL = NULL; -lv_obj_t * ui_CPU_Values_LBL = NULL; -lv_obj_t * ui_Settings_Loading_Container = NULL; -lv_obj_t * ui_Settings_Loading_Spinner = NULL; -// event funtions -void ui_event_Settings_Screen(lv_event_t * e) -{ - lv_event_code_t event_code = lv_event_get_code(e); - - if(event_code == LV_EVENT_GESTURE && lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) { - lv_indev_wait_release(lv_indev_get_act()); - app_show_driveline(); // Home screen removed; back goes to the Driveline screen - } -} - -void ui_event_Toggle_UART_Switch(lv_event_t * e) -{ - lv_event_code_t event_code = lv_event_get_code(e); - - if(event_code == LV_EVENT_RELEASED) { - onUARTToggle(e); - } -} - -void ui_event_Toggle_Wifi_Switch(lv_event_t * e) -{ - lv_event_code_t event_code = lv_event_get_code(e); - - if(event_code == LV_EVENT_RELEASED) { - onWifiToggle(e); - } -} - -void ui_event_Toggle_CAN_Bus_Switch(lv_event_t * e) -{ - lv_event_code_t event_code = lv_event_get_code(e); - - if(event_code == LV_EVENT_RELEASED) { - onCANBusToggle(e); - } -} - -void ui_event_Toggle_Debug_Switch(lv_event_t * e) -{ - lv_event_code_t event_code = lv_event_get_code(e); - - if(event_code == LV_EVENT_RELEASED) { - onDebugToggle(e); - } -} - -void ui_event_Select_SSID_BTN(lv_event_t * e) -{ - lv_event_code_t event_code = lv_event_get_code(e); - - if(event_code == LV_EVENT_CLICKED) { - onSelectSSID(e); - } -} - -// build funtions - -void ui_Settings_Screen_screen_init(void) -{ - ui_Settings_Screen = lv_obj_create(NULL); - lv_obj_clear_flag(ui_Settings_Screen, LV_OBJ_FLAG_SCROLLABLE); /// Flags - lv_obj_add_event_cb(ui_Settings_Screen, scr_unloaded_delete_cb, LV_EVENT_SCREEN_UNLOADED, - ui_Settings_Screen_screen_destroy); - - ui_Settings_Screen_LBL = lv_label_create(ui_Settings_Screen); - lv_obj_set_width(ui_Settings_Screen_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_Settings_Screen_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_Settings_Screen_LBL, -405); - lv_obj_set_y(ui_Settings_Screen_LBL, -268); - lv_obj_set_align(ui_Settings_Screen_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_Settings_Screen_LBL, "Settings"); - lv_obj_set_style_text_font(ui_Settings_Screen_LBL, &lv_font_montserrat_48, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_Main_Container = lv_obj_create(ui_Settings_Screen); - lv_obj_remove_style_all(ui_Main_Container); - lv_obj_set_width(ui_Main_Container, 1024); - lv_obj_set_height(ui_Main_Container, 530); - lv_obj_set_x(ui_Main_Container, 0); - lv_obj_set_y(ui_Main_Container, 34); - lv_obj_set_align(ui_Main_Container, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Main_Container, LV_FLEX_FLOW_ROW_WRAP); - lv_obj_set_flex_align(ui_Main_Container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_Main_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_Settings_CTRL_Container = lv_obj_create(ui_Main_Container); - lv_obj_remove_style_all(ui_Settings_CTRL_Container); - lv_obj_set_width(ui_Settings_CTRL_Container, 410); - lv_obj_set_height(ui_Settings_CTRL_Container, 530); - lv_obj_set_x(ui_Settings_CTRL_Container, -130); - lv_obj_set_y(ui_Settings_CTRL_Container, 8); - lv_obj_set_align(ui_Settings_CTRL_Container, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Settings_CTRL_Container, LV_FLEX_FLOW_COLUMN); - lv_obj_set_flex_align(ui_Settings_CTRL_Container, LV_FLEX_ALIGN_SPACE_AROUND, LV_FLEX_ALIGN_CENTER, - LV_FLEX_ALIGN_SPACE_EVENLY); - lv_obj_clear_flag(ui_Settings_CTRL_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_CAN_Bus_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container); - lv_obj_set_width(ui_CAN_Bus_CTRL_Panel, 400); - lv_obj_set_height(ui_CAN_Bus_CTRL_Panel, 100); - lv_obj_set_x(ui_CAN_Bus_CTRL_Panel, 0); - lv_obj_set_y(ui_CAN_Bus_CTRL_Panel, 1); - lv_obj_set_align(ui_CAN_Bus_CTRL_Panel, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_CAN_Bus_CTRL_Panel, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_CAN_Bus_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_CAN_Bus_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags - lv_obj_set_style_bg_color(ui_CAN_Bus_CTRL_Panel, lv_color_hex(0x7F7A9C), LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_bg_opa(ui_CAN_Bus_CTRL_Panel, 255, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_Toggle_CAN_Bus_Switch = lv_switch_create(ui_CAN_Bus_CTRL_Panel); - lv_obj_set_width(ui_Toggle_CAN_Bus_Switch, 110); - lv_obj_set_height(ui_Toggle_CAN_Bus_Switch, 60); - lv_obj_set_x(ui_Toggle_CAN_Bus_Switch, -181); - lv_obj_set_y(ui_Toggle_CAN_Bus_Switch, -3); - lv_obj_set_align(ui_Toggle_CAN_Bus_Switch, LV_ALIGN_CENTER); - - ui_Enable_CAN_Bus_LBL = lv_label_create(ui_CAN_Bus_CTRL_Panel); - lv_obj_set_width(ui_Enable_CAN_Bus_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_Enable_CAN_Bus_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_Enable_CAN_Bus_LBL, -117); - lv_obj_set_y(ui_Enable_CAN_Bus_LBL, -2); - lv_obj_set_align(ui_Enable_CAN_Bus_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_Enable_CAN_Bus_LBL, "Enable CANBus"); - lv_obj_set_style_text_font(ui_Enable_CAN_Bus_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_UART_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container); - lv_obj_set_width(ui_UART_CTRL_Panel, 400); - lv_obj_set_height(ui_UART_CTRL_Panel, 100); - lv_obj_set_x(ui_UART_CTRL_Panel, 0); - lv_obj_set_y(ui_UART_CTRL_Panel, 1); - lv_obj_set_align(ui_UART_CTRL_Panel, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_UART_CTRL_Panel, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_UART_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_UART_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags - ui_object_set_themeable_style_property(ui_UART_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR, - _ui_theme_color_panel_backgroung); - ui_object_set_themeable_style_property(ui_UART_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA, - _ui_theme_alpha_panel_backgroung); - - ui_Toggle_UART_Switch = lv_switch_create(ui_UART_CTRL_Panel); - lv_obj_set_width(ui_Toggle_UART_Switch, 110); - lv_obj_set_height(ui_Toggle_UART_Switch, 60); - lv_obj_set_x(ui_Toggle_UART_Switch, -181); - lv_obj_set_y(ui_Toggle_UART_Switch, -3); - lv_obj_set_align(ui_Toggle_UART_Switch, LV_ALIGN_CENTER); - - ui_Enable_UART_LBL = lv_label_create(ui_UART_CTRL_Panel); - lv_obj_set_width(ui_Enable_UART_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_Enable_UART_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_Enable_UART_LBL, -117); - lv_obj_set_y(ui_Enable_UART_LBL, -2); - lv_obj_set_align(ui_Enable_UART_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_Enable_UART_LBL, "Enable UART"); - lv_obj_set_style_text_font(ui_Enable_UART_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_Wifi_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container); - lv_obj_set_width(ui_Wifi_CTRL_Panel, 405); - lv_obj_set_height(ui_Wifi_CTRL_Panel, 100); - lv_obj_set_x(ui_Wifi_CTRL_Panel, 0); - lv_obj_set_y(ui_Wifi_CTRL_Panel, 1); - lv_obj_set_align(ui_Wifi_CTRL_Panel, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Wifi_CTRL_Panel, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_Wifi_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_Wifi_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags - ui_object_set_themeable_style_property(ui_Wifi_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR, - _ui_theme_color_panel_backgroung); - ui_object_set_themeable_style_property(ui_Wifi_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA, - _ui_theme_alpha_panel_backgroung); - - ui_Toggle_Wifi_Switch = lv_switch_create(ui_Wifi_CTRL_Panel); - lv_obj_set_width(ui_Toggle_Wifi_Switch, 110); - lv_obj_set_height(ui_Toggle_Wifi_Switch, 60); - lv_obj_set_x(ui_Toggle_Wifi_Switch, -181); - lv_obj_set_y(ui_Toggle_Wifi_Switch, -3); - lv_obj_set_align(ui_Toggle_Wifi_Switch, LV_ALIGN_CENTER); - lv_obj_add_state(ui_Toggle_Wifi_Switch, LV_STATE_DISABLED); /// States - - ui_Enable_Wifi_LBL = lv_label_create(ui_Wifi_CTRL_Panel); - lv_obj_set_width(ui_Enable_Wifi_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_Enable_Wifi_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_Enable_Wifi_LBL, -117); - lv_obj_set_y(ui_Enable_Wifi_LBL, -2); - lv_obj_set_align(ui_Enable_Wifi_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_Enable_Wifi_LBL, "Enable Wifi"); - lv_obj_set_style_text_font(ui_Enable_Wifi_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_BLE_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container); - lv_obj_set_width(ui_BLE_CTRL_Panel, 400); - lv_obj_set_height(ui_BLE_CTRL_Panel, 100); - lv_obj_set_x(ui_BLE_CTRL_Panel, 0); - lv_obj_set_y(ui_BLE_CTRL_Panel, 1); - lv_obj_set_align(ui_BLE_CTRL_Panel, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_BLE_CTRL_Panel, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_BLE_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_BLE_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags - ui_object_set_themeable_style_property(ui_BLE_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR, - _ui_theme_color_panel_backgroung); - ui_object_set_themeable_style_property(ui_BLE_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA, - _ui_theme_alpha_panel_backgroung); - - ui_Toggle_BLE_Switch = lv_switch_create(ui_BLE_CTRL_Panel); - lv_obj_set_width(ui_Toggle_BLE_Switch, 110); - lv_obj_set_height(ui_Toggle_BLE_Switch, 60); - lv_obj_set_x(ui_Toggle_BLE_Switch, -181); - lv_obj_set_y(ui_Toggle_BLE_Switch, -3); - lv_obj_set_align(ui_Toggle_BLE_Switch, LV_ALIGN_CENTER); - lv_obj_add_state(ui_Toggle_BLE_Switch, LV_STATE_DISABLED); /// States - - ui_Enable_BLE_LBL = lv_label_create(ui_BLE_CTRL_Panel); - lv_obj_set_width(ui_Enable_BLE_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_Enable_BLE_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_Enable_BLE_LBL, -117); - lv_obj_set_y(ui_Enable_BLE_LBL, -2); - lv_obj_set_align(ui_Enable_BLE_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_Enable_BLE_LBL, "Enable BLE"); - lv_obj_set_style_text_font(ui_Enable_BLE_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_Debug_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container); - lv_obj_set_width(ui_Debug_CTRL_Panel, 400); - lv_obj_set_height(ui_Debug_CTRL_Panel, 100); - lv_obj_set_x(ui_Debug_CTRL_Panel, 0); - lv_obj_set_y(ui_Debug_CTRL_Panel, 1); - lv_obj_set_align(ui_Debug_CTRL_Panel, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Debug_CTRL_Panel, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_Debug_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_Debug_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags - ui_object_set_themeable_style_property(ui_Debug_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR, - _ui_theme_color_panel_backgroung); - ui_object_set_themeable_style_property(ui_Debug_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA, - _ui_theme_alpha_panel_backgroung); - - ui_Toggle_Debug_Switch = lv_switch_create(ui_Debug_CTRL_Panel); - lv_obj_set_width(ui_Toggle_Debug_Switch, 110); - lv_obj_set_height(ui_Toggle_Debug_Switch, 60); - lv_obj_set_x(ui_Toggle_Debug_Switch, -181); - lv_obj_set_y(ui_Toggle_Debug_Switch, -3); - lv_obj_set_align(ui_Toggle_Debug_Switch, LV_ALIGN_CENTER); - - ui_Enable_Debug_LBL = lv_label_create(ui_Debug_CTRL_Panel); - lv_obj_set_width(ui_Enable_Debug_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_Enable_Debug_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_Enable_Debug_LBL, -117); - lv_obj_set_y(ui_Enable_Debug_LBL, -2); - lv_obj_set_align(ui_Enable_Debug_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_Enable_Debug_LBL, "Enable Debug"); - lv_obj_set_style_text_font(ui_Enable_Debug_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_Wifi_Container = lv_obj_create(ui_Main_Container); - lv_obj_remove_style_all(ui_Wifi_Container); - lv_obj_set_width(ui_Wifi_Container, 610); - lv_obj_set_height(ui_Wifi_Container, 530); - lv_obj_set_x(ui_Wifi_Container, -100); - lv_obj_set_y(ui_Wifi_Container, 8); - lv_obj_set_align(ui_Wifi_Container, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Wifi_Container, LV_FLEX_FLOW_COLUMN); - lv_obj_set_flex_align(ui_Wifi_Container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START); - lv_obj_clear_flag(ui_Wifi_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_Select_SSID_BTN = lv_btn_create(ui_Wifi_Container); - lv_obj_set_width(ui_Select_SSID_BTN, 668); - lv_obj_set_height(ui_Select_SSID_BTN, 50); - lv_obj_set_x(ui_Select_SSID_BTN, 7); - lv_obj_set_y(ui_Select_SSID_BTN, -4); - lv_obj_set_align(ui_Select_SSID_BTN, LV_ALIGN_CENTER); - lv_obj_add_flag(ui_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN); /// Flags - lv_obj_set_style_bg_color(ui_Select_SSID_BTN, lv_color_hex(0x7F7A9C), LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_bg_opa(ui_Select_SSID_BTN, 255, LV_PART_MAIN | LV_STATE_DEFAULT); - - ui_Wifi_Passkey_TB = lv_textarea_create(ui_Wifi_Container); - lv_obj_set_width(ui_Wifi_Passkey_TB, 200); - lv_obj_set_height(ui_Wifi_Passkey_TB, LV_SIZE_CONTENT); /// 70 - lv_obj_set_x(ui_Wifi_Passkey_TB, 129); - lv_obj_set_y(ui_Wifi_Passkey_TB, -173); - lv_obj_set_align(ui_Wifi_Passkey_TB, LV_ALIGN_CENTER); - lv_textarea_set_placeholder_text(ui_Wifi_Passkey_TB, "Placeholder..."); - lv_textarea_set_one_line(ui_Wifi_Passkey_TB, true); - lv_obj_add_flag(ui_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN); /// Flags - - ui_Keyboard = lv_keyboard_create(ui_Settings_Screen); - lv_obj_set_width(ui_Keyboard, 1012); - lv_obj_set_height(ui_Keyboard, 268); - lv_obj_set_x(ui_Keyboard, 3); - lv_obj_set_y(ui_Keyboard, 161); - lv_obj_set_align(ui_Keyboard, LV_ALIGN_CENTER); - lv_obj_add_flag(ui_Keyboard, LV_OBJ_FLAG_HIDDEN); /// Flags - - ui_Device_State_Container = lv_obj_create(ui_Settings_Screen); - lv_obj_remove_style_all(ui_Device_State_Container); - lv_obj_set_width(ui_Device_State_Container, 75); - lv_obj_set_height(ui_Device_State_Container, 30); - lv_obj_set_x(ui_Device_State_Container, 470); - lv_obj_set_y(ui_Device_State_Container, -282); - lv_obj_set_align(ui_Device_State_Container, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Device_State_Container, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_Device_State_Container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START); - lv_obj_add_flag(ui_Device_State_Container, LV_OBJ_FLAG_HIDDEN); /// Flags - lv_obj_clear_flag(ui_Device_State_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_Static_LBLS_Container = lv_obj_create(ui_Device_State_Container); - lv_obj_remove_style_all(ui_Static_LBLS_Container); - lv_obj_set_width(ui_Static_LBLS_Container, 35); - lv_obj_set_height(ui_Static_LBLS_Container, 30); - lv_obj_set_align(ui_Static_LBLS_Container, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Static_LBLS_Container, LV_FLEX_FLOW_COLUMN); - lv_obj_set_flex_align(ui_Static_LBLS_Container, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_START); - lv_obj_clear_flag(ui_Static_LBLS_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_FPS_Static_LBL = lv_label_create(ui_Static_LBLS_Container); - lv_obj_set_width(ui_FPS_Static_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_FPS_Static_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_FPS_Static_LBL, -176); - lv_obj_set_y(ui_FPS_Static_LBL, 34); - lv_obj_set_align(ui_FPS_Static_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_FPS_Static_LBL, "FPS:"); - - ui_CPU_Static_LBL = lv_label_create(ui_Static_LBLS_Container); - lv_obj_set_width(ui_CPU_Static_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_CPU_Static_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_CPU_Static_LBL, -1); - lv_obj_set_y(ui_CPU_Static_LBL, -1); - lv_obj_set_align(ui_CPU_Static_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_CPU_Static_LBL, "CPU:"); - - ui_Device_State_Values_LBL = lv_obj_create(ui_Device_State_Container); - lv_obj_remove_style_all(ui_Device_State_Values_LBL); - lv_obj_set_width(ui_Device_State_Values_LBL, 35); - lv_obj_set_height(ui_Device_State_Values_LBL, 30); - lv_obj_set_align(ui_Device_State_Values_LBL, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Device_State_Values_LBL, LV_FLEX_FLOW_COLUMN); - lv_obj_set_flex_align(ui_Device_State_Values_LBL, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START); - lv_obj_clear_flag(ui_Device_State_Values_LBL, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_FPS_Values_LBL = lv_label_create(ui_Device_State_Values_LBL); - lv_obj_set_width(ui_FPS_Values_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_FPS_Values_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_FPS_Values_LBL, -176); - lv_obj_set_y(ui_FPS_Values_LBL, 34); - lv_obj_set_align(ui_FPS_Values_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_FPS_Values_LBL, "0"); - - ui_CPU_Values_LBL = lv_label_create(ui_Device_State_Values_LBL); - lv_obj_set_width(ui_CPU_Values_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_height(ui_CPU_Values_LBL, LV_SIZE_CONTENT); /// 1 - lv_obj_set_x(ui_CPU_Values_LBL, -1); - lv_obj_set_y(ui_CPU_Values_LBL, -1); - lv_obj_set_align(ui_CPU_Values_LBL, LV_ALIGN_CENTER); - lv_label_set_text(ui_CPU_Values_LBL, "0%"); - - ui_Settings_Loading_Container = lv_obj_create(ui_Settings_Screen); - lv_obj_remove_style_all(ui_Settings_Loading_Container); - lv_obj_set_width(ui_Settings_Loading_Container, 1024); - lv_obj_set_height(ui_Settings_Loading_Container, 600); - lv_obj_set_align(ui_Settings_Loading_Container, LV_ALIGN_CENTER); - lv_obj_set_flex_flow(ui_Settings_Loading_Container, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(ui_Settings_Loading_Container, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(ui_Settings_Loading_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags - - ui_Settings_Loading_Spinner = lv_spinner_create(ui_Settings_Loading_Container, 1000, 90); - lv_obj_set_width(ui_Settings_Loading_Spinner, 80); - lv_obj_set_height(ui_Settings_Loading_Spinner, 80); - lv_obj_set_x(ui_Settings_Loading_Spinner, -22); - lv_obj_set_y(ui_Settings_Loading_Spinner, -22); - lv_obj_set_align(ui_Settings_Loading_Spinner, LV_ALIGN_CENTER); - lv_obj_add_flag(ui_Settings_Loading_Spinner, LV_OBJ_FLAG_HIDDEN); /// Flags - lv_obj_clear_flag(ui_Settings_Loading_Spinner, LV_OBJ_FLAG_CLICKABLE); /// Flags - - lv_obj_add_event_cb(ui_Toggle_UART_Switch, ui_event_Toggle_UART_Switch, LV_EVENT_ALL, NULL); - lv_obj_add_event_cb(ui_Toggle_Wifi_Switch, ui_event_Toggle_Wifi_Switch, LV_EVENT_ALL, NULL); - lv_obj_add_event_cb(ui_Toggle_CAN_Bus_Switch, ui_event_Toggle_CAN_Bus_Switch, LV_EVENT_ALL, NULL); - lv_obj_add_event_cb(ui_Toggle_Debug_Switch, ui_event_Toggle_Debug_Switch, LV_EVENT_ALL, NULL); - lv_obj_add_event_cb(ui_Select_SSID_BTN, ui_event_Select_SSID_BTN, LV_EVENT_ALL, NULL); - lv_obj_add_event_cb(ui_Settings_Screen, ui_event_Settings_Screen, LV_EVENT_ALL, NULL); - uic_Settings_Screen = ui_Settings_Screen; - uic_Settings_Screen_LBL = ui_Settings_Screen_LBL; - uic_Main_Container = ui_Main_Container; - uic_Settings_CTRL_Container = ui_Settings_CTRL_Container; - uic_CAN_Bus_CTRL_Panel = ui_CAN_Bus_CTRL_Panel; - uic_Toggle_CAN_Bus_Switch = ui_Toggle_CAN_Bus_Switch; - uic_Enable_CAN_Bus_LBL = ui_Enable_CAN_Bus_LBL; - uic_UART_CTRL_Panel = ui_UART_CTRL_Panel; - uic_Toggle_UART_Switch = ui_Toggle_UART_Switch; - uic_Enable_UART_LBL = ui_Enable_UART_LBL; - uic_Wifi_CTRL_Panel = ui_Wifi_CTRL_Panel; - uic_Toggle_Wifi_Switch = ui_Toggle_Wifi_Switch; - uic_Enable_Wifi_LBL = ui_Enable_Wifi_LBL; - uic_BLE_CTRL_Panel = ui_BLE_CTRL_Panel; - uic_Toggle_BLE_Switch = ui_Toggle_BLE_Switch; - uic_Enable_BLE_LBL = ui_Enable_BLE_LBL; - uic_Debug_CTRL_Panel = ui_Debug_CTRL_Panel; - uic_Toggle_Debug_Switch = ui_Toggle_Debug_Switch; - uic_Enable_Debug_LBL = ui_Enable_Debug_LBL; - uic_Wifi_Container = ui_Wifi_Container; - uic_Select_SSID_BTN = ui_Select_SSID_BTN; - uic_Wifi_Passkey_TB = ui_Wifi_Passkey_TB; - uic_Keyboard = ui_Keyboard; - uic_Device_State_Container = ui_Device_State_Container; - uic_Static_LBLS_Container = ui_Static_LBLS_Container; - uic_FPS_Static_LBL = ui_FPS_Static_LBL; - uic_CPU_Static_LBL = ui_CPU_Static_LBL; - uic_Device_State_Values_LBL = ui_Device_State_Values_LBL; - uic_FPS_Values_LBL = ui_FPS_Values_LBL; - uic_CPU_Values_LBL = ui_CPU_Values_LBL; - uic_Settings_Loading_Container = ui_Settings_Loading_Container; - uic_Settings_Loading_Spinner = ui_Settings_Loading_Spinner; - -} - -void ui_Settings_Screen_screen_destroy(void) -{ - if(ui_Settings_Screen) lv_obj_del(ui_Settings_Screen); - - // NULL screen variables - uic_Settings_Screen = NULL; - ui_Settings_Screen = NULL; - uic_Settings_Screen_LBL = NULL; - ui_Settings_Screen_LBL = NULL; - uic_Main_Container = NULL; - ui_Main_Container = NULL; - uic_Settings_CTRL_Container = NULL; - ui_Settings_CTRL_Container = NULL; - uic_CAN_Bus_CTRL_Panel = NULL; - ui_CAN_Bus_CTRL_Panel = NULL; - uic_Toggle_CAN_Bus_Switch = NULL; - ui_Toggle_CAN_Bus_Switch = NULL; - uic_Enable_CAN_Bus_LBL = NULL; - ui_Enable_CAN_Bus_LBL = NULL; - uic_UART_CTRL_Panel = NULL; - ui_UART_CTRL_Panel = NULL; - uic_Toggle_UART_Switch = NULL; - ui_Toggle_UART_Switch = NULL; - uic_Enable_UART_LBL = NULL; - ui_Enable_UART_LBL = NULL; - uic_Wifi_CTRL_Panel = NULL; - ui_Wifi_CTRL_Panel = NULL; - uic_Toggle_Wifi_Switch = NULL; - ui_Toggle_Wifi_Switch = NULL; - uic_Enable_Wifi_LBL = NULL; - ui_Enable_Wifi_LBL = NULL; - uic_BLE_CTRL_Panel = NULL; - ui_BLE_CTRL_Panel = NULL; - uic_Toggle_BLE_Switch = NULL; - ui_Toggle_BLE_Switch = NULL; - uic_Enable_BLE_LBL = NULL; - ui_Enable_BLE_LBL = NULL; - uic_Debug_CTRL_Panel = NULL; - ui_Debug_CTRL_Panel = NULL; - uic_Toggle_Debug_Switch = NULL; - ui_Toggle_Debug_Switch = NULL; - uic_Enable_Debug_LBL = NULL; - ui_Enable_Debug_LBL = NULL; - uic_Wifi_Container = NULL; - ui_Wifi_Container = NULL; - uic_Select_SSID_BTN = NULL; - ui_Select_SSID_BTN = NULL; - uic_Wifi_Passkey_TB = NULL; - ui_Wifi_Passkey_TB = NULL; - uic_Keyboard = NULL; - ui_Keyboard = NULL; - uic_Device_State_Container = NULL; - ui_Device_State_Container = NULL; - uic_Static_LBLS_Container = NULL; - ui_Static_LBLS_Container = NULL; - uic_FPS_Static_LBL = NULL; - ui_FPS_Static_LBL = NULL; - uic_CPU_Static_LBL = NULL; - ui_CPU_Static_LBL = NULL; - uic_Device_State_Values_LBL = NULL; - ui_Device_State_Values_LBL = NULL; - uic_FPS_Values_LBL = NULL; - ui_FPS_Values_LBL = NULL; - uic_CPU_Values_LBL = NULL; - ui_CPU_Values_LBL = NULL; - uic_Settings_Loading_Container = NULL; - ui_Settings_Loading_Container = NULL; - uic_Settings_Loading_Spinner = NULL; - ui_Settings_Loading_Spinner = NULL; - -} diff --git a/include/ui/screens/ui_Settings_Screen.h b/include/ui/screens/ui_Settings_Screen.h deleted file mode 100644 index c80ce1a..0000000 --- a/include/ui/screens/ui_Settings_Screen.h +++ /dev/null @@ -1,92 +0,0 @@ -// This file was generated by SquareLine Studio -// SquareLine Studio version: SquareLine Studio 1.5.4 -// LVGL version: 8.3.6 -// Project name: ESP32-S3-Touch-LCD-5B - -#ifndef UI_SETTINGS_SCREEN_H -#define UI_SETTINGS_SCREEN_H - -#ifdef __cplusplus -extern "C" { -#endif - -// SCREEN: ui_Settings_Screen -extern void ui_Settings_Screen_screen_init(void); -extern void ui_Settings_Screen_screen_destroy(void); -extern void ui_event_Settings_Screen(lv_event_t * e); -extern lv_obj_t * ui_Settings_Screen; -extern lv_obj_t * ui_Settings_Screen_LBL; -extern lv_obj_t * ui_Main_Container; -extern lv_obj_t * ui_Settings_CTRL_Container; -extern lv_obj_t * ui_CAN_Bus_CTRL_Panel; -extern lv_obj_t * ui_Toggle_CAN_Bus_Switch; -extern lv_obj_t * ui_Enable_CAN_Bus_LBL; -extern lv_obj_t * ui_UART_CTRL_Panel; -extern void ui_event_Toggle_UART_Switch(lv_event_t * e); -extern lv_obj_t * ui_Toggle_UART_Switch; -extern lv_obj_t * ui_Enable_UART_LBL; -extern lv_obj_t * ui_Wifi_CTRL_Panel; -extern void ui_event_Toggle_Wifi_Switch(lv_event_t * e); -extern lv_obj_t * ui_Toggle_Wifi_Switch; -extern lv_obj_t * ui_Enable_Wifi_LBL; -extern lv_obj_t * ui_BLE_CTRL_Panel; -extern lv_obj_t * ui_Toggle_BLE_Switch; -extern lv_obj_t * ui_Enable_BLE_LBL; -extern lv_obj_t * ui_Debug_CTRL_Panel; -extern void ui_event_Toggle_Debug_Switch(lv_event_t * e); -extern lv_obj_t * ui_Toggle_Debug_Switch; -extern lv_obj_t * ui_Enable_Debug_LBL; -extern lv_obj_t * ui_Wifi_Container; -extern void ui_event_Select_SSID_BTN(lv_event_t * e); -extern lv_obj_t * ui_Select_SSID_BTN; -extern lv_obj_t * ui_Wifi_Passkey_TB; -extern lv_obj_t * ui_Keyboard; -extern lv_obj_t * ui_Device_State_Container; -extern lv_obj_t * ui_Static_LBLS_Container; -extern lv_obj_t * ui_FPS_Static_LBL; -extern lv_obj_t * ui_CPU_Static_LBL; -extern lv_obj_t * ui_Device_State_Values_LBL; -extern lv_obj_t * ui_FPS_Values_LBL; -extern lv_obj_t * ui_CPU_Values_LBL; -extern lv_obj_t * ui_Settings_Loading_Container; -extern lv_obj_t * ui_Settings_Loading_Spinner; -// CUSTOM VARIABLES -extern lv_obj_t * uic_Settings_Screen; -extern lv_obj_t * uic_Settings_Screen_LBL; -extern lv_obj_t * uic_Main_Container; -extern lv_obj_t * uic_Settings_CTRL_Container; -extern lv_obj_t * uic_CAN_Bus_CTRL_Panel; -extern lv_obj_t * uic_Toggle_CAN_Bus_Switch; -extern lv_obj_t * uic_Enable_CAN_Bus_LBL; -extern lv_obj_t * uic_UART_CTRL_Panel; -extern lv_obj_t * uic_Toggle_UART_Switch; -extern lv_obj_t * uic_Enable_UART_LBL; -extern lv_obj_t * uic_Wifi_CTRL_Panel; -extern lv_obj_t * uic_Toggle_Wifi_Switch; -extern lv_obj_t * uic_Enable_Wifi_LBL; -extern lv_obj_t * uic_BLE_CTRL_Panel; -extern lv_obj_t * uic_Toggle_BLE_Switch; -extern lv_obj_t * uic_Enable_BLE_LBL; -extern lv_obj_t * uic_Debug_CTRL_Panel; -extern lv_obj_t * uic_Toggle_Debug_Switch; -extern lv_obj_t * uic_Enable_Debug_LBL; -extern lv_obj_t * uic_Wifi_Container; -extern lv_obj_t * uic_Select_SSID_BTN; -extern lv_obj_t * uic_Wifi_Passkey_TB; -extern lv_obj_t * uic_Keyboard; -extern lv_obj_t * uic_Device_State_Container; -extern lv_obj_t * uic_Static_LBLS_Container; -extern lv_obj_t * uic_FPS_Static_LBL; -extern lv_obj_t * uic_CPU_Static_LBL; -extern lv_obj_t * uic_Device_State_Values_LBL; -extern lv_obj_t * uic_FPS_Values_LBL; -extern lv_obj_t * uic_CPU_Values_LBL; -extern lv_obj_t * uic_Settings_Loading_Container; -extern lv_obj_t * uic_Settings_Loading_Spinner; - -#ifdef __cplusplus -} /*extern "C"*/ -#endif - -#endif - diff --git a/include/ui/ui.c b/include/ui/ui.c index d7f17df..130c058 100644 --- a/include/ui/ui.c +++ b/include/ui/ui.c @@ -33,14 +33,12 @@ void ui_init(void) lv_theme_t * theme = lv_theme_default_init(dispp, lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_RED), true, LV_FONT_DEFAULT); lv_disp_set_theme(dispp, theme); - // Home screen removed (2026-09-21): the firmware boots into the hand-coded - // Driveline screen (DrivelineScreen::show() in display_init.cpp). Settings is - // created lazily by _ui_screen_change() when swiped to. + // Home (2026-09-21) and Settings (2026-09-27) screens removed: every screen + // is hand-coded in src/modules; display_init.cpp shows the Driveline screen. ui____initial_actions0 = lv_obj_create(NULL); lv_disp_load_scr(ui____initial_actions0); } void ui_destroy(void) { - ui_Settings_Screen_screen_destroy(); } diff --git a/include/ui/ui.h b/include/ui/ui.h index 89f997e..57ffbfe 100644 --- a/include/ui/ui.h +++ b/include/ui/ui.h @@ -28,7 +28,8 @@ extern "C" { #include "ui_themes.h" ///////////////////// SCREENS //////////////////// -#include "screens/ui_Settings_Screen.h" +// None: every screen is hand-coded in src/modules (Driveline, Settings, Gauge +// Tuning). The SquareLine Settings screen was removed on 2026-09-27. ///////////////////// VARIABLES //////////////////// diff --git a/include/ui/ui_events.h b/include/ui/ui_events.h index c1a6f2a..38801e5 100644 --- a/include/ui/ui_events.h +++ b/include/ui/ui_events.h @@ -10,11 +10,6 @@ extern "C" { #endif -void onUARTToggle(lv_event_t * e); -void onWifiToggle(lv_event_t * e); -void onCANBusToggle(lv_event_t * e); -void onDebugToggle(lv_event_t * e); -void onSelectSSID(lv_event_t * e); #ifdef __cplusplus } /*extern "C"*/ diff --git a/src/drivers/can_driver.cpp b/src/drivers/can_driver.cpp index 649920a..c686cc4 100644 --- a/src/drivers/can_driver.cpp +++ b/src/drivers/can_driver.cpp @@ -718,14 +718,7 @@ void setVerboseDecode(bool enabled) { ESP_LOGI("CANDrv", "Verbose decode logging %s", enabled ? "ENABLED" : "disabled"); } -void onCANToggle(lv_event_t *e) { - lv_obj_t *target = lv_event_get_target(e); - if (target == NULL) { - ESP_LOGE("CANDrv", "ERROR: CAN toggle target is NULL!"); - return; - } - - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); +void setEnabled(bool state) { ESP_LOGI("CANDrv", "===== CAN Toggle Event ====="); ESP_LOGI("CANDrv", "CAN Toggle State: %s", state ? "ON" : "OFF"); diff --git a/src/main.cpp b/src/main.cpp index b30dcf7..038f86a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,6 +10,7 @@ #include "modules/ui_state_manager.h" // UI state manager module #include "modules/driveline_screen.h" // Hand-coded driveline screen (boot screen) #include "modules/tuning_screen.h" // Hand-coded gauge tuning screen (swipe right from Driveline) +#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/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B @@ -21,99 +22,12 @@ // ============================================================================ // This is a minimal setup with: // - LVGL display and touch initialization -// - Hand-coded Driveline (boot) + Gauge Tuning screens, SquareLine Settings screen -// - WiFi module with async scanning (managed by WiFiManager) +// - Hand-coded Driveline (boot), Settings and Gauge Tuning screens +// - WiFi: one remembered network, scans on request (WiFiManager) // - UART data transmission at 5Hz (managed by UARTManager) -// - UI state synchronization (managed by UIStateManager) // - Persistent settings storage (managed by SettingsManager) // ============================================================================ -// External UI element references (from ui_Settings_Screen.c) -extern "C" { - extern lv_obj_t *uic_Main_Container; - extern lv_obj_t *uic_Toggle_Wifi_Switch; - extern lv_obj_t *uic_Toggle_UART_Switch; - extern lv_obj_t *uic_Toggle_CAN_Bus_Switch; -} - - -// ============================================================================ -// EVENT HANDLERS (C linkage for SquareLine Studio UI callbacks) -// ============================================================================ - -extern "C" { - -// WiFi-related event handlers (delegated to WiFiManager) -void onSelectSSID(lv_event_t *e) { - WiFiManager::onSelectSSID(e); -} - -// WiFi toggle event handler - delegates to WiFiManager module -void onWifiToggle(lv_event_t *e) -{ - // Get the actual widget from the event (safer than global variable) - lv_obj_t *target = lv_event_get_target(e); - - // Verify the widget is valid - if (target == NULL) { - Serial.println("ERROR: WiFi toggle target is NULL!"); - Serial.flush(); - return; - } - - // Check the toggle state - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); - - Serial.printf("WiFi Toggle RELEASED - State: %s\n", state ? "ON" : "OFF"); - Serial.flush(); - - // Save state to NVS for persistence across power cycles - SettingsManager::saveWiFiState(state); - - // Delegate to WiFiManager module - WiFiManager::onWifiToggle(e); -} - -// UART toggle event handler - delegates to UARTManager module -void onUARTToggle(lv_event_t *e) -{ - // Get the actual widget from the event (safer than global variable) - lv_obj_t *target = lv_event_get_target(e); - - // Verify the widget is valid - if (target == NULL) { - Serial.println("ERROR: UART toggle target is NULL!"); - Serial.flush(); - return; - } - - // Check the toggle state - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); - - Serial.printf("UART Toggle RELEASED - State: %s\n", state ? "ON" : "OFF"); - Serial.flush(); - - // Save state to NVS for persistence across power cycles - SettingsManager::saveUARTState(state); - - // Delegate to UARTManager module - UARTManager::onUARTToggle(e); -} - -// CAN Bus toggle event handler - delegates to CANDriver module -void onCANBusToggle(lv_event_t *e) -{ - CANDriver::onCANToggle(e); -} - -// Debug toggle event handler - delegates to UIStateManager module -void onDebugToggle(lv_event_t *e) -{ - UIStateManager::onDebugToggle(e); -} - -} // extern "C" - // `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. @@ -221,8 +135,7 @@ void setup() ESP_LOGI("MAIN", "- Link: UART1 TX GPIO44 (RS485 A/B) + ESP-NOW broadcast, protocol v%u", PACKET_VERSION); ESP_LOGI("MAIN", "- Console: type 'cfg help' to tune the Patrol gauge outputs"); ESP_LOGI("MAIN", "- Screens: Driveline (boot) <- left: Settings | right: Gauge tuning ->"); - ESP_LOGI("MAIN", "- Settings screen has WiFi and UART toggles"); - ESP_LOGI("MAIN", "- WiFi scan updates every 10 seconds when enabled"); + ESP_LOGI("MAIN", "- Settings: Wi-Fi (remembered network), Updates, System"); ESP_LOGI("MAIN", "- UART transmits at 5Hz (200ms) when enabled"); } @@ -238,13 +151,7 @@ void loop() last_print = millis(); } - // LVGL task runs automatically in separate task - // Keep loop() minimal and empty to avoid interfering with LVGL rendering - - // Continuously sync UI switches with actual service states - // (Settings screen gets destroyed/recreated when swiping) - UIStateManager::applySavedStatesToUI(); - + // 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(); DiagProbe::tick(); @@ -252,6 +159,7 @@ void loop() DrivelineScreen::tick(); TuningScreen::tick(); + SettingsScreen::tick(); delay(100); // Check frequently to catch screen changes quickly } diff --git a/src/modules/display_init.cpp b/src/modules/display_init.cpp index fde4f98..114dfde 100644 --- a/src/modules/display_init.cpp +++ b/src/modules/display_init.cpp @@ -94,7 +94,6 @@ DisplayObjects init() { Serial.println("[DisplayInit] Step 12: Loading SquareLine Studio UI..."); lvgl_port_lock(-1); ui_init(); // Initialize the SquareLine Studio generated UI - // Note: onSelectSSID event handler is registered in ui_Settings_Screen.c // Boot screen: the hand-coded Driveline screen. ui_init() only loads an // empty placeholder now (the SquareLine Home screen was removed 2026-09-21); // swap while the backlight is still off so there's no flash. diff --git a/src/modules/driveline_screen.cpp b/src/modules/driveline_screen.cpp index 7093d10..2d27b32 100644 --- a/src/modules/driveline_screen.cpp +++ b/src/modules/driveline_screen.cpp @@ -7,12 +7,9 @@ #include "display/lvgl_v8_port.h" #include "drivers/can_driver.h" #include "tuning_screen.h" +#include "settings_screen.h" #include "esp_log.h" -extern "C" { -#include "ui.h" -} - namespace DrivelineScreen { // ============================================================================ @@ -137,18 +134,15 @@ static lv_obj_t* makeStat(lv_obj_t* parent, const char* title, } /** - * @brief Gesture handler on OUR screen: swipe LEFT opens Settings (SquareLine), - * swipe RIGHT continues to the Gauge Tuning screen. + * @brief Gesture handler: swipe LEFT opens Settings, swipe RIGHT the Gauge + * Tuning screen (both hand-coded, instant switches). */ static void onScreenGesture(lv_event_t* e) { if (lv_event_get_code(e) != LV_EVENT_GESTURE) return; lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act()); if (dir == LV_DIR_LEFT) { lv_indev_wait_release(lv_indev_get_act()); - // 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); + SettingsScreen::show(); } else if (dir == LV_DIR_RIGHT) { lv_indev_wait_release(lv_indev_get_act()); TuningScreen::show(); @@ -392,9 +386,3 @@ void tick() { } } // namespace DrivelineScreen - -// C entry point used by the SquareLine-generated Settings screen's back gesture. -// Runs inside an LVGL event handler, so the LVGL lock is already held. -extern "C" void app_show_driveline(void) { - DrivelineScreen::show(); -} diff --git a/src/modules/ota_update.cpp b/src/modules/ota_update.cpp index 5fb82c7..4afe0cd 100644 --- a/src/modules/ota_update.cpp +++ b/src/modules/ota_update.cpp @@ -70,19 +70,63 @@ static bool g_job_pending = false; static job_t g_job = JOB_CHECK; static bool g_pending_verify = false; +// What the Settings screen shows. Written by the loop task (jobs) and the LVGL +// task (requests), read by the loop task - a spinlock keeps copies consistent. +static portMUX_TYPE g_ui_mux = portMUX_INITIALIZER_UNLOCKED; +static ui_status_t g_ui = {PHASE_IDLE, "", ""}; +static char g_last_msg[96] = ""; // last console line, reused as the failure reason + +static void setPhase(phase_t p, const char* latest = NULL, const char* msg = NULL) { + portENTER_CRITICAL(&g_ui_mux); + g_ui.phase = p; + if (latest) { strncpy(g_ui.latest, latest, sizeof(g_ui.latest) - 1); g_ui.latest[sizeof(g_ui.latest) - 1] = 0; } + const char* m = msg ? msg : ""; + strncpy(g_ui.message, m, sizeof(g_ui.message) - 1); + g_ui.message[sizeof(g_ui.message) - 1] = 0; + portEXIT_CRITICAL(&g_ui_mux); +} + // ============================================================================ // Helpers // ============================================================================ -static void print(const char* fmt, ...) { +static void vlog(bool remember, const char* fmt, va_list ap) { char buf[220]; - va_list ap; - va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); SerialLock::lock(); Serial.println(buf); SerialLock::unlock(); + if (remember) { + const char* m = strncmp(buf, "[ota] ", 6) == 0 ? buf + 6 : buf; + portENTER_CRITICAL(&g_ui_mux); + strncpy(g_last_msg, m, sizeof(g_last_msg) - 1); + g_last_msg[sizeof(g_last_msg) - 1] = 0; + portEXIT_CRITICAL(&g_ui_mux); + } +} + +/** Console line; also kept as the reason the screen shows if the job fails. */ +static void print(const char* fmt, ...) { + va_list ap; + va_start(ap, fmt); + vlog(true, fmt, ap); + va_end(ap); +} + +/** Console-only diagnostics (heap, stack) that must not replace a failure reason. */ +static void debug(const char* fmt, ...) { + va_list ap; + va_start(ap, fmt); + vlog(false, fmt, ap); + va_end(ap); +} + +static void failPhase() { + char m[96]; + portENTER_CRITICAL(&g_ui_mux); + memcpy(m, g_last_msg, sizeof(m)); + portEXIT_CRITICAL(&g_ui_mux); + setPhase(PHASE_FAILED, NULL, m); } static const char* stateName(esp_ota_img_states_t s) { @@ -124,17 +168,20 @@ static bool parked(char* why, size_t n) { return true; } -static bool gate(bool need_wifi, bool need_parked = true) { +static bool gate(bool need_wifi, bool need_parked = true, char* why_out = NULL, size_t why_n = 0) { char why[96]; + bool ok = true; if (need_parked && !parked(why, sizeof(why))) { + ok = false; + } else if (need_wifi && WiFi.status() != WL_CONNECTED) { + snprintf(why, sizeof(why), "Wi-Fi not connected - join a network first"); + ok = false; + } + if (!ok) { print("[ota] refused: %s", why); - return false; + if (why_out) snprintf(why_out, why_n, "%s", why); } - if (need_wifi && WiFi.status() != WL_CONNECTED) { - print("[ota] refused: Wi-Fi not connected - join a network on the Settings screen first"); - return false; - } - return true; + return ok; } static void toHex(const uint8_t* in, size_t n, char* out) { @@ -391,18 +438,20 @@ static void hideNotice() { static void install(bool force) { manifest_t m; - if (!fetchManifest(m) || !verifySignature(m)) return; + if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; } if (!force && strcmp(m.version, FW_VERSION) == 0) { print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION); + setPhase(PHASE_UP_TO_DATE, m.version); return; } const esp_partition_t* part = esp_ota_get_next_update_partition(NULL); - if (!part) { print("[ota] no idle OTA slot (partition table?)"); return; } + if (!part) { print("[ota] no idle OTA slot (partition table?)"); failPhase(); return; } if (m.size > part->size) { print("[ota] image %lu B does not fit slot %s (%lu B)", (unsigned long)m.size, part->label, (unsigned long)part->size); + failPhase(); return; } @@ -428,6 +477,7 @@ static void install(bool force) { if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); ok = false; } } if (!ok) { + failPhase(); snprintf(msg, sizeof(msg), "Update failed\n\nStill running %s", FW_VERSION); showNotice(msg); delay(5000); @@ -446,11 +496,12 @@ static void install(bool force) { static void check() { manifest_t m; - if (!fetchManifest(m) || !verifySignature(m)) return; + if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; } bool same = strcmp(m.version, FW_VERSION) == 0; print("[ota] running %s | latest release %s (%lu bytes, signature OK)%s", FW_VERSION, m.version, (unsigned long)m.size, same ? " - up to date" : " - `ota install` to update"); + setPhase(same ? PHASE_UP_TO_DATE : PHASE_AVAILABLE, m.version); } // This core's mbedtls is built with CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC: every TLS @@ -466,7 +517,7 @@ static void* tlsCallocInternal(size_t n, size_t size) { } static void printHeap(const char* when) { - print("[ota] heap %s: internal free %u (largest block %u), PSRAM free %u", when, + debug("[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)); @@ -477,14 +528,20 @@ static void runJob(job_t job) { if (job == JOB_CHECK) check(); else install(job == JOB_INSTALL_FORCE); mbedtls_platform_set_calloc_free(tlsCallocInternal, heap_caps_free); - print("[ota] loop stack headroom after job: %u B", (unsigned)uxTaskGetStackHighWaterMark(NULL)); + debug("[ota] loop stack headroom after job: %u B", (unsigned)uxTaskGetStackHighWaterMark(NULL)); } -static void startJob(job_t job) { - if (!gate(true, job != JOB_CHECK)) return; // checking is harmless; installing needs parked +static bool startJob(job_t job, char* why = NULL, size_t why_n = 0) { + if (g_job_pending) { + if (why) snprintf(why, why_n, "busy"); + return false; + } + if (!gate(true, job != JOB_CHECK, why, why_n)) return false; // checking is harmless; installing needs parked + setPhase(job == JOB_CHECK ? PHASE_CHECKING : PHASE_INSTALLING); g_job = job; g_job_pending = true; // runs on the next tick(), in the loop task print("[ota] working - console and screen values pause until done"); + return true; } // ============================================================================ @@ -556,6 +613,17 @@ static void help() { const char* version() { return FW_VERSION; } +ui_status_t getStatus() { + ui_status_t s; + portENTER_CRITICAL(&g_ui_mux); + s = g_ui; + portEXIT_CRITICAL(&g_ui_mux); + return s; +} + +bool requestCheck(char* why, size_t n) { return startJob(JOB_CHECK, why, n); } +bool requestInstall(char* why, size_t n) { return startJob(JOB_INSTALL, why, n); } + void init() { const esp_partition_t* run = esp_ota_get_running_partition(); esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED; diff --git a/src/modules/ota_update.h b/src/modules/ota_update.h index 7d0dfd7..d84a92d 100644 --- a/src/modules/ota_update.h +++ b/src/modules/ota_update.h @@ -1,9 +1,9 @@ /** * ota_update.h - pull firmware updates from this repo's Gitea releases. * - * Manual only: nothing checks or installs by itself. The `ota` serial console - * drives it today; the planned password-gated Diagnostics screen will call the - * same functions (wiki/pages/open-questions.md #12). + * Manual only: nothing checks or installs by itself. Driven from the Settings + * screen (Updates section: check, then install behind a confirm dialog) and the + * `ota` serial console. * * ota status running version, slot, rollback state * ota check ask Gitea for the latest release, compare versions @@ -43,6 +43,29 @@ bool handleCommand(const char* line); /** Firmware version baked in at build time ("dev" for local builds). */ const char* version(); +// ---- Settings screen ------------------------------------------------------- + +typedef enum { + PHASE_IDLE, // nothing asked yet this boot + PHASE_CHECKING, + PHASE_UP_TO_DATE, // latest == running + PHASE_AVAILABLE, // latest != running + PHASE_INSTALLING, + PHASE_FAILED // message says why +} phase_t; + +typedef struct { + phase_t phase; + char latest[32]; // latest release tag, once known + char message[96]; // failure reason +} ui_status_t; + +ui_status_t getStatus(); + +/** Queue a check / install (runs in the loop task). False + reason if refused now. */ +bool requestCheck(char* why, size_t n); +bool requestInstall(char* why, size_t n); + } // namespace Ota #endif // OTA_UPDATE_H diff --git a/src/modules/settings_screen.cpp b/src/modules/settings_screen.cpp new file mode 100644 index 0000000..49d4229 --- /dev/null +++ b/src/modules/settings_screen.cpp @@ -0,0 +1,789 @@ +/* + * Settings Screen Module Implementation - see settings_screen.h + */ + +#include "settings_screen.h" +#include "ui_kit.h" +#include "driveline_screen.h" +#include "wifi_manager.h" +#include "ota_update.h" +#include "uart_manager.h" +#include "espnow_link.h" +#include "settings_manager.h" +#include "ui_state_manager.h" +#include "drivers/can_driver.h" +#include "display/lvgl_v8_port.h" +#include "config/ota_config.h" +#include +#include + +namespace SettingsScreen { + +using namespace UiKit; + +// ============================================================================ +// LAYOUT +// ============================================================================ + +static const lv_coord_t NAV_X = 16, NAV_W = 240, NAV_H = 100; +static const lv_coord_t TOP_Y = 88; +static const lv_coord_t PAGE_X = 272, PAGE_W = 736, PAGE_H = 600 - TOP_Y - 28; // version label below + +typedef enum { PAGE_WIFI, PAGE_UPDATES, PAGE_SYSTEM, PAGE_COUNT } page_t; + +// ============================================================================ +// MODULE STATE +// ============================================================================ + +static lv_obj_t* g_screen = NULL; +static lv_obj_t* g_nav[PAGE_COUNT]; +static lv_obj_t* g_nav_sub[PAGE_COUNT]; +static lv_obj_t* g_page[PAGE_COUNT]; +static page_t g_cur = PAGE_WIFI; +static bool g_refreshing = false; // setting widget states from code: ignore their events + +// Wi-Fi page +static lv_obj_t* g_wifi_sw = NULL; +static lv_obj_t* g_wifi_off_note = NULL; +static lv_obj_t* g_wifi_body = NULL; +static lv_obj_t* g_st_icon = NULL; +static lv_obj_t* g_st_spinner = NULL; +static lv_obj_t* g_st_title = NULL; +static lv_obj_t* g_st_detail = NULL; +static lv_obj_t* g_st_connect = NULL; +static lv_obj_t* g_st_forget = NULL; +static lv_obj_t* g_scan_btn = NULL; +static lv_obj_t* g_list = NULL; +static lv_obj_t* g_list_note = NULL; +static WiFiManager::network_t g_rows[WIFI_SCAN_MAX_NETWORKS]; +static uint8_t g_row_count = 0; +static uint32_t g_list_gen = 0xFFFFFFFF; +static char g_list_connected[33] = ""; +static bool g_want_scan = false; + +// Password entry (full-screen overlay on this screen) +static lv_obj_t* g_pw = NULL; +static lv_obj_t* g_pw_title = NULL; +static lv_obj_t* g_pw_ta = NULL; +static lv_obj_t* g_pw_show = NULL; +static char g_pw_ssid[33] = ""; + +// Updates page +static lv_obj_t* g_upd_latest = NULL; +static lv_obj_t* g_upd_state = NULL; +static lv_obj_t* g_upd_check = NULL; +static lv_obj_t* g_upd_install = NULL; +static lv_obj_t* g_upd_wifi = NULL; +static char g_upd_refusal[96] = ""; +static Ota::phase_t g_upd_refusal_phase = Ota::PHASE_IDLE; + +// System page +static lv_obj_t* g_sys_can = NULL; +static lv_obj_t* g_sys_link = NULL; +static lv_obj_t* g_sys_dbg = NULL; +static lv_obj_t* g_sys_info = NULL; // values column; keys are static + +static void refresh(bool force); + +// ============================================================================ +// NAVIGATION +// ============================================================================ + +static void selectPage(page_t p) { + g_cur = p; + for (int i = 0; i < PAGE_COUNT; i++) { + bool on = (i == p); + setVisible(g_page[i], on); + lv_obj_set_style_bg_opa(g_nav[i], on ? LV_OPA_COVER : LV_OPA_TRANSP, 0); + lv_obj_set_style_border_width(g_nav[i], on ? 5 : 0, 0); + } + if (p == PAGE_WIFI) g_want_scan = true; + refresh(true); +} + +static void onNav(lv_event_t* e) { + selectPage((page_t)(uintptr_t)lv_event_get_user_data(e)); +} + +static void onBack(lv_event_t* e) { + (void)e; + DrivelineScreen::show(); +} + +static void onGesture(lv_event_t* e) { + (void)e; + if (g_pw && !lv_obj_has_flag(g_pw, LV_OBJ_FLAG_HIDDEN)) return; // typing a password + if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) { + lv_indev_wait_release(lv_indev_get_act()); + DrivelineScreen::show(); + } +} + +static lv_obj_t* makeNav(lv_obj_t* parent, page_t p, const char* title) { + lv_obj_t* n = lv_obj_create(parent); + lv_obj_set_size(n, NAV_W, NAV_H); + lv_obj_set_pos(n, NAV_X, TOP_Y + p * (NAV_H + 12)); + lv_obj_set_style_radius(n, 12, 0); + lv_obj_set_style_bg_color(n, UI_COL_PANEL, 0); + lv_obj_set_style_bg_opa(n, LV_OPA_TRANSP, 0); + lv_obj_set_style_bg_color(n, UI_COL_PANEL2, LV_STATE_PRESSED); + lv_obj_set_style_bg_opa(n, LV_OPA_COVER, LV_STATE_PRESSED); + lv_obj_set_style_border_side(n, LV_BORDER_SIDE_LEFT, 0); + lv_obj_set_style_border_color(n, UI_COL_ACCENT, 0); + lv_obj_set_style_border_width(n, 0, 0); + lv_obj_set_style_shadow_width(n, 0, 0); + lv_obj_set_style_pad_left(n, 20, 0); + lv_obj_set_style_pad_ver(n, 18, 0); + lv_obj_set_flex_flow(n, LV_FLEX_FLOW_COLUMN); + lv_obj_set_flex_align(n, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START); + lv_obj_set_style_pad_row(n, 6, 0); + lv_obj_clear_flag(n, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(n, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_event_cb(n, onNav, LV_EVENT_CLICKED, (void*)(uintptr_t)p); + + label(n, title, &lv_font_montserrat_24, UI_COL_TEXT); + g_nav_sub[p] = label(n, "", &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(g_nav_sub[p], LV_LABEL_LONG_DOT); + lv_obj_set_width(g_nav_sub[p], NAV_W - 40); + return n; +} + +static lv_obj_t* makePage(lv_obj_t* parent) { + lv_obj_t* p = box(parent, LV_FLEX_FLOW_COLUMN); + lv_obj_set_size(p, PAGE_W, PAGE_H); + lv_obj_set_pos(p, PAGE_X, TOP_Y); + lv_obj_set_style_pad_row(p, 12, 0); + return p; +} + +/** "Title" on the left, a widget (switch) on the right, optional sub-line. */ +static lv_obj_t* makeSettingRow(lv_obj_t* parent, const char* title, const char* sub, lv_obj_t** right_parent) { + lv_obj_t* row = box(parent, LV_FLEX_FLOW_ROW); + lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_min_height(row, 64, 0); + + lv_obj_t* col = box(row, LV_FLEX_FLOW_COLUMN); + lv_obj_set_size(col, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_style_pad_row(col, 4, 0); + label(col, title, &lv_font_montserrat_24, UI_COL_TEXT); + if (sub) label(col, sub, &lv_font_montserrat_20, UI_COL_MUTED); + *right_parent = row; + return row; +} + +// ============================================================================ +// WI-FI PAGE +// ============================================================================ + +static void onWifiSwitch(lv_event_t* e) { + if (g_refreshing) return; + bool on = lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED); + WiFiManager::setEnabled(on); + if (on) g_want_scan = true; + refresh(true); +} + +static void onScan(lv_event_t* e) { + (void)e; + WiFiManager::requestScan(); + refresh(true); +} + +static void onConnectSaved(lv_event_t* e) { + (void)e; + WiFiManager::connectSaved(); + refresh(true); +} + +static void onForgetConfirmed(bool ok, void* user) { + (void)user; + if (!ok) return; + WiFiManager::forget(); + g_want_scan = true; +} + +static void onForget(lv_event_t* e) { + (void)e; + WiFiManager::status_t s = WiFiManager::getStatus(); + char text[128]; + snprintf(text, sizeof(text), "Controller A will no longer join \"%s\" by itself.", s.saved_ssid); + confirm("Forget this network?", text, "Forget", onForgetConfirmed, NULL); +} + +static void openPassword(const char* ssid) { + snprintf(g_pw_ssid, sizeof(g_pw_ssid), "%s", ssid); + char t[64]; + snprintf(t, sizeof(t), "Join \"%s\"", ssid); + lv_label_set_text(g_pw_title, t); + lv_textarea_set_text(g_pw_ta, ""); + lv_textarea_set_password_mode(g_pw_ta, true); + setButtonText(g_pw_show, LV_SYMBOL_EYE_OPEN " Show"); + setVisible(g_pw, true); + lv_obj_move_foreground(g_pw); +} + +static void closePassword() { + lv_textarea_set_text(g_pw_ta, ""); // don't leave the password in a widget + setVisible(g_pw, false); +} + +static void submitPassword() { + const char* pw = lv_textarea_get_text(g_pw_ta); + if (pw == NULL || pw[0] == 0) return; + WiFiManager::connect(g_pw_ssid, pw); + closePassword(); + refresh(true); +} + +static void onPwKeyboard(lv_event_t* e) { + lv_event_code_t code = lv_event_get_code(e); + if (code == LV_EVENT_READY) submitPassword(); + else if (code == LV_EVENT_CANCEL) closePassword(); +} + +static void onPwConnect(lv_event_t* e) { (void)e; submitPassword(); } +static void onPwCancel(lv_event_t* e) { (void)e; closePassword(); } + +static void onPwShow(lv_event_t* e) { + (void)e; + bool hidden = lv_textarea_get_password_mode(g_pw_ta); + lv_textarea_set_password_mode(g_pw_ta, !hidden); + setButtonText(g_pw_show, hidden ? LV_SYMBOL_EYE_CLOSE " Hide" : LV_SYMBOL_EYE_OPEN " Show"); +} + +static void onNetworkRow(lv_event_t* e) { + uint8_t i = (uint8_t)(uintptr_t)lv_event_get_user_data(e); + if (i >= g_row_count) return; + const WiFiManager::network_t& n = g_rows[i]; + if (strcmp(n.ssid, g_list_connected) == 0) return; // already on it + if (n.secured) { + openPassword(n.ssid); + } else { + WiFiManager::connect(n.ssid, ""); + refresh(true); + } +} + +static const char* strengthWord(int rssi) { + if (rssi >= -55) return "Strong"; + if (rssi >= -67) return "Good"; + if (rssi >= -77) return "Fair"; + return "Weak"; +} + +static lv_color_t strengthColour(int rssi) { + if (rssi >= -67) return UI_COL_OK; + if (rssi >= -77) return UI_COL_AMBER; + return UI_COL_WARN; +} + +static void rebuildList(const WiFiManager::status_t& s) { + g_row_count = WiFiManager::getNetworks(g_rows, WIFI_SCAN_MAX_NETWORKS); + g_list_gen = s.scan_gen; + snprintf(g_list_connected, sizeof(g_list_connected), "%s", s.link == WiFiManager::LINK_CONNECTED ? s.ssid : ""); + + lv_obj_clean(g_list); + for (uint8_t i = 0; i < g_row_count; i++) { + const WiFiManager::network_t& n = g_rows[i]; + bool connected = strcmp(n.ssid, g_list_connected) == 0; + + lv_obj_t* row = lv_obj_create(g_list); + lv_obj_set_size(row, LV_PCT(100), 64); + lv_obj_set_style_bg_color(row, UI_COL_PANEL, 0); + lv_obj_set_style_bg_color(row, UI_COL_PANEL2, LV_STATE_PRESSED); + lv_obj_set_style_border_width(row, 0, 0); + lv_obj_set_style_shadow_width(row, 0, 0); + lv_obj_set_style_radius(row, 10, 0); + lv_obj_set_style_pad_hor(row, 18, 0); + lv_obj_set_style_pad_ver(row, 0, 0); + lv_obj_set_style_pad_column(row, 16, 0); + lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW); + lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(row, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_event_cb(row, onNetworkRow, LV_EVENT_CLICKED, (void*)(uintptr_t)i); + + label(row, LV_SYMBOL_WIFI, &lv_font_montserrat_24, strengthColour(n.rssi)); + lv_obj_t* name = label(row, n.ssid, &lv_font_montserrat_24, UI_COL_TEXT); + lv_label_set_long_mode(name, LV_LABEL_LONG_DOT); + lv_obj_set_flex_grow(name, 1); + + char right[40]; + if (connected) snprintf(right, sizeof(right), LV_SYMBOL_OK " Connected"); + else snprintf(right, sizeof(right), "%s %s", strengthWord(n.rssi), n.secured ? "Secured" : "Open"); + label(row, right, &lv_font_montserrat_20, connected ? UI_COL_OK : UI_COL_MUTED); + } +} + +static void refreshWifi() { + WiFiManager::status_t s = WiFiManager::getStatus(); + bool on = s.link != WiFiManager::LINK_OFF; + + setChecked(g_wifi_sw, on); + setVisible(g_wifi_off_note, !on); + setVisible(g_wifi_body, on); + if (!on) return; + + // Scan when the page opens (not while connected: a scan hops channels + // under the ESP-NOW link - the Scan button still works then). + if (g_want_scan && (s.link == WiFiManager::LINK_IDLE || s.link == WiFiManager::LINK_FAILED)) { + g_want_scan = false; + WiFiManager::requestScan(); + s = WiFiManager::getStatus(); + } + + // ---- status card + char title[80], detail[96]; + bool spinner = false, show_connect = false, show_forget = s.saved_ssid[0] != 0; + const char* icon = LV_SYMBOL_WIFI; + lv_color_t icon_col = UI_COL_MUTED; + switch (s.link) { + case WiFiManager::LINK_CONNECTED: + snprintf(title, sizeof(title), "Connected to %s", s.ssid); + snprintf(detail, sizeof(detail), "IP %s \xE2\x80\xA2 signal %s (%d dBm)", s.ip, strengthWord(s.rssi), s.rssi); + icon_col = UI_COL_OK; + break; + case WiFiManager::LINK_CONNECTING: + snprintf(title, sizeof(title), "Connecting to %s...", s.ssid); + snprintf(detail, sizeof(detail), "This takes up to 15 seconds."); + spinner = true; + show_forget = false; + break; + case WiFiManager::LINK_FAILED: + snprintf(title, sizeof(title), "Couldn't connect to %s", s.ssid); + snprintf(detail, sizeof(detail), "%s", s.error); + icon = LV_SYMBOL_WARNING; + icon_col = UI_COL_WARN; + show_connect = s.saved_ssid[0] != 0; + break; + default: // IDLE + if (s.saved_ssid[0]) { + snprintf(title, sizeof(title), "Not connected"); + snprintf(detail, sizeof(detail), "Saved network: %s", s.saved_ssid); + show_connect = true; + } else { + snprintf(title, sizeof(title), "Not connected"); + snprintf(detail, sizeof(detail), "Pick a network below. It is remembered once it works."); + } + break; + } + setText(g_st_title, title); + setText(g_st_detail, detail); + setText(g_st_icon, icon); + setTextColor(g_st_icon, icon_col); + setVisible(g_st_icon, !spinner); + setVisible(g_st_spinner, spinner); + setVisible(g_st_connect, show_connect); + setVisible(g_st_forget, show_forget); + + // ---- scan button + list + setButtonText(g_scan_btn, s.scanning ? "Scanning..." : LV_SYMBOL_REFRESH " Scan"); + if (s.scanning || s.link == WiFiManager::LINK_CONNECTING) lv_obj_add_state(g_scan_btn, LV_STATE_DISABLED); + else lv_obj_clear_state(g_scan_btn, LV_STATE_DISABLED); + + const char* connected_now = s.link == WiFiManager::LINK_CONNECTED ? s.ssid : ""; + if (s.scan_gen != g_list_gen || strcmp(connected_now, g_list_connected) != 0) rebuildList(s); + + if (g_row_count == 0) { + setText(g_list_note, s.scanning ? "Looking for networks..." : + s.link == WiFiManager::LINK_CONNECTED ? "Tap Scan to see other networks." : + "No networks found. Tap Scan to look again."); + setVisible(g_list_note, true); + } else { + setVisible(g_list_note, false); + } +} + +static void buildWifiPage(lv_obj_t* page) { + lv_obj_t* right; + makeSettingRow(page, "Wi-Fi", "Used for firmware updates", &right); + g_wifi_sw = toggle(right, onWifiSwitch, NULL); + + g_wifi_off_note = label(page, + "Wi-Fi is off.\n\nTurn it on to join a network for firmware updates. " + "The link to Controller B works without it.", + &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(g_wifi_off_note, LV_LABEL_LONG_WRAP); + lv_obj_set_width(g_wifi_off_note, LV_PCT(100)); + + g_wifi_body = box(page, LV_FLEX_FLOW_COLUMN); + lv_obj_set_width(g_wifi_body, LV_PCT(100)); + lv_obj_set_flex_grow(g_wifi_body, 1); + lv_obj_set_style_pad_row(g_wifi_body, 12, 0); + + // status card: [icon|spinner] [title / detail] [Connect] [Forget] + lv_obj_t* c = card(g_wifi_body); + lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(c, LV_FLEX_FLOW_ROW); + lv_obj_set_flex_align(c, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_pad_column(c, 16, 0); + lv_obj_set_style_min_height(c, 96, 0); + + g_st_icon = label(c, LV_SYMBOL_WIFI, &lv_font_montserrat_30, UI_COL_MUTED); + g_st_spinner = lv_spinner_create(c, 1000, 60); + lv_obj_set_size(g_st_spinner, 40, 40); + lv_obj_set_style_arc_width(g_st_spinner, 5, LV_PART_MAIN); + lv_obj_set_style_arc_width(g_st_spinner, 5, LV_PART_INDICATOR); + lv_obj_set_style_arc_color(g_st_spinner, UI_COL_ACCENT, LV_PART_INDICATOR); + lv_obj_add_flag(g_st_spinner, LV_OBJ_FLAG_HIDDEN); + + lv_obj_t* txt = box(c, LV_FLEX_FLOW_COLUMN); + lv_obj_set_height(txt, LV_SIZE_CONTENT); + lv_obj_set_flex_grow(txt, 1); + lv_obj_set_style_pad_row(txt, 6, 0); + g_st_title = label(txt, "", &lv_font_montserrat_24, UI_COL_TEXT); + lv_label_set_long_mode(g_st_title, LV_LABEL_LONG_DOT); + lv_obj_set_width(g_st_title, LV_PCT(100)); + g_st_detail = label(txt, "", &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(g_st_detail, LV_LABEL_LONG_WRAP); + lv_obj_set_width(g_st_detail, LV_PCT(100)); + + g_st_connect = button(c, "Connect", 140, 56, BTN_PRIMARY, onConnectSaved, NULL); + g_st_forget = button(c, "Forget", 120, 56, BTN_SECONDARY, onForget, NULL); + + // list header + lv_obj_t* hdr = box(g_wifi_body, LV_FLEX_FLOW_ROW); + lv_obj_set_size(hdr, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_align(hdr, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + label(hdr, "Networks nearby", &lv_font_montserrat_20, UI_COL_MUTED); + g_scan_btn = button(hdr, LV_SYMBOL_REFRESH " Scan", 180, 52, BTN_SECONDARY, onScan, NULL); + + g_list_note = label(g_wifi_body, "", &lv_font_montserrat_20, UI_COL_MUTED); + + g_list = box(g_wifi_body, LV_FLEX_FLOW_COLUMN); + lv_obj_set_width(g_list, LV_PCT(100)); + lv_obj_set_flex_grow(g_list, 1); + lv_obj_set_style_pad_row(g_list, 8, 0); + lv_obj_add_flag(g_list, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_scroll_dir(g_list, LV_DIR_VER); + lv_obj_set_scrollbar_mode(g_list, LV_SCROLLBAR_MODE_ACTIVE); +} + +static void buildPasswordOverlay() { + g_pw = lv_obj_create(g_screen); + lv_obj_remove_style_all(g_pw); + lv_obj_set_size(g_pw, 1024, 600); + lv_obj_set_style_bg_color(g_pw, UI_COL_BG, 0); + lv_obj_set_style_bg_opa(g_pw, LV_OPA_COVER, 0); + lv_obj_clear_flag(g_pw, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(g_pw, LV_OBJ_FLAG_CLICKABLE); // swallow touches meant for the page below + lv_obj_add_flag(g_pw, LV_OBJ_FLAG_HIDDEN); + + g_pw_title = label(g_pw, "", &lv_font_montserrat_30, UI_COL_TEXT); + lv_label_set_long_mode(g_pw_title, LV_LABEL_LONG_DOT); + lv_obj_set_width(g_pw_title, 760); + lv_obj_set_pos(g_pw_title, 24, 22); + + lv_obj_t* cancel = button(g_pw, "Cancel", 180, 56, BTN_SECONDARY, onPwCancel, NULL); + lv_obj_align(cancel, LV_ALIGN_TOP_RIGHT, -16, 10); + + g_pw_ta = lv_textarea_create(g_pw); + lv_textarea_set_one_line(g_pw_ta, true); + lv_textarea_set_password_mode(g_pw_ta, true); + lv_textarea_set_placeholder_text(g_pw_ta, "Password"); + lv_textarea_set_max_length(g_pw_ta, 63); + lv_obj_set_style_text_font(g_pw_ta, &lv_font_montserrat_30, 0); + lv_obj_set_style_bg_color(g_pw_ta, UI_COL_PANEL, 0); + lv_obj_set_style_text_color(g_pw_ta, UI_COL_TEXT, 0); + lv_obj_set_style_border_color(g_pw_ta, UI_COL_ACCENT, 0); + lv_obj_set_width(g_pw_ta, 640); + lv_obj_set_pos(g_pw_ta, 24, 100); + lv_obj_add_state(g_pw_ta, LV_STATE_FOCUSED); // keep the cursor visible + + g_pw_show = button(g_pw, LV_SYMBOL_EYE_OPEN " Show", 150, 60, BTN_SECONDARY, onPwShow, NULL); + lv_obj_set_pos(g_pw_show, 680, 100); + lv_obj_t* go = button(g_pw, "Connect", 170, 60, BTN_PRIMARY, onPwConnect, NULL); + lv_obj_set_pos(go, 842, 100); + + lv_obj_t* kb = lv_keyboard_create(g_pw); + lv_obj_set_size(kb, 1024, 360); + lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0); + lv_obj_set_style_text_font(kb, &lv_font_montserrat_24, 0); + lv_obj_set_style_bg_color(kb, UI_COL_PANEL, 0); + lv_obj_set_style_bg_color(kb, UI_COL_PANEL2, LV_PART_ITEMS); + lv_obj_set_style_text_color(kb, UI_COL_TEXT, LV_PART_ITEMS); + lv_obj_set_style_shadow_width(kb, 0, LV_PART_ITEMS); + lv_keyboard_set_textarea(kb, g_pw_ta); + lv_obj_add_event_cb(kb, onPwKeyboard, LV_EVENT_READY, NULL); + lv_obj_add_event_cb(kb, onPwKeyboard, LV_EVENT_CANCEL, NULL); +} + +// ============================================================================ +// UPDATES PAGE +// ============================================================================ + +static void onInstallConfirmed(bool ok, void* user) { + (void)user; + if (!ok) return; + Ota::phase_t before = Ota::getStatus().phase; + if (!Ota::requestInstall(g_upd_refusal, sizeof(g_upd_refusal))) g_upd_refusal_phase = before; + else g_upd_refusal[0] = 0; + refresh(true); +} + +static void onInstall(lv_event_t* e) { + (void)e; + Ota::ui_status_t o = Ota::getStatus(); + char title[64]; + snprintf(title, sizeof(title), "Install %s?", o.latest); + confirm(title, + "The screen goes dark for about a minute while the new firmware is written, " + "then Controller A restarts. Controller B's gauges drop out for a few seconds.\n\n" + "Only while parked with the engine off.", + "Install", onInstallConfirmed, NULL); +} + +static void onCheck(lv_event_t* e) { + (void)e; + Ota::phase_t before = Ota::getStatus().phase; + if (!Ota::requestCheck(g_upd_refusal, sizeof(g_upd_refusal))) g_upd_refusal_phase = before; + else g_upd_refusal[0] = 0; + refresh(true); +} + +static void onGoWifi(lv_event_t* e) { + (void)e; + selectPage(PAGE_WIFI); +} + +static void refreshUpdates() { + Ota::ui_status_t o = Ota::getStatus(); + bool wifi_ok = WiFiManager::getStatus().link == WiFiManager::LINK_CONNECTED; + if (g_upd_refusal[0] && o.phase != g_upd_refusal_phase) g_upd_refusal[0] = 0; // superseded + + char msg[140]; + lv_color_t col = UI_COL_MUTED; + switch (o.phase) { + case Ota::PHASE_CHECKING: snprintf(msg, sizeof(msg), "Checking for updates..."); break; + case Ota::PHASE_INSTALLING: snprintf(msg, sizeof(msg), "Installing %s...", o.latest); break; + case Ota::PHASE_UP_TO_DATE: snprintf(msg, sizeof(msg), LV_SYMBOL_OK " You're up to date."); col = UI_COL_OK; break; + case Ota::PHASE_AVAILABLE: snprintf(msg, sizeof(msg), "Version %s is available.", o.latest); col = UI_COL_ACCENT; break; + case Ota::PHASE_FAILED: snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", o.message); col = UI_COL_WARN; break; + default: + snprintf(msg, sizeof(msg), "%s", wifi_ok ? "Tap Check to look for a new version." : "Connect to Wi-Fi to check for updates."); + break; + } + if (g_upd_refusal[0]) { + snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", g_upd_refusal); + col = UI_COL_WARN; + } else if (!wifi_ok && o.phase != Ota::PHASE_IDLE && o.phase != Ota::PHASE_CHECKING) { + // keep the last result, but say why the buttons are off + size_t n = strlen(msg); + snprintf(msg + n, sizeof(msg) - n, "\nConnect to Wi-Fi to check again."); + } + setText(g_upd_state, msg); + setTextColor(g_upd_state, col); + + setText(g_upd_latest, o.latest[0] ? o.latest : "-"); + + bool busy = o.phase == Ota::PHASE_CHECKING || o.phase == Ota::PHASE_INSTALLING; + setButtonText(g_upd_check, busy ? "Working..." : LV_SYMBOL_REFRESH " Check for updates"); + if (busy || !wifi_ok) lv_obj_add_state(g_upd_check, LV_STATE_DISABLED); + else lv_obj_clear_state(g_upd_check, LV_STATE_DISABLED); + + bool can_install = o.phase == Ota::PHASE_AVAILABLE && wifi_ok; + char inst[48]; + snprintf(inst, sizeof(inst), LV_SYMBOL_DOWNLOAD " Install %s", o.latest); + setButtonText(g_upd_install, inst); + setVisible(g_upd_install, can_install); + setVisible(g_upd_wifi, !wifi_ok); +} + +static void buildUpdatesPage(lv_obj_t* page) { + label(page, "Firmware updates", &lv_font_montserrat_24, UI_COL_TEXT); + + lv_obj_t* c = card(page); + lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(c, LV_FLEX_FLOW_ROW); + lv_obj_set_style_pad_column(c, 60, 0); + + lv_obj_t* a = box(c, LV_FLEX_FLOW_COLUMN); + lv_obj_set_size(a, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_style_pad_row(a, 6, 0); + label(a, "Installed", &lv_font_montserrat_20, UI_COL_MUTED); + label(a, FW_VERSION, &lv_font_montserrat_30, UI_COL_TEXT); + + lv_obj_t* b = box(c, LV_FLEX_FLOW_COLUMN); + lv_obj_set_size(b, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_style_pad_row(b, 6, 0); + label(b, "Latest release", &lv_font_montserrat_20, UI_COL_MUTED); + g_upd_latest = label(b, "-", &lv_font_montserrat_30, UI_COL_TEXT); + + g_upd_state = label(page, "", &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(g_upd_state, LV_LABEL_LONG_WRAP); + lv_obj_set_width(g_upd_state, LV_PCT(100)); + + lv_obj_t* btns = box(page, LV_FLEX_FLOW_ROW); + lv_obj_set_size(btns, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_style_pad_column(btns, 16, 0); + g_upd_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 64, BTN_PRIMARY, onCheck, NULL); + g_upd_install = button(btns, "Install", 280, 64, BTN_SUCCESS, onInstall, NULL); + g_upd_wifi = button(btns, LV_SYMBOL_WIFI " Wi-Fi settings", 260, 64, BTN_SECONDARY, onGoWifi, NULL); + + lv_obj_t* note = label(page, + "Updates come from " OTA_SERVER " and are signed. Installing takes about a minute: " + "the screen goes dark while the new firmware is written, then the controller restarts. " + "If it doesn't start properly, it goes back to the current version by itself.", + &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(note, LV_LABEL_LONG_WRAP); + lv_obj_set_width(note, LV_PCT(100)); + lv_obj_set_style_pad_top(note, 12, 0); +} + +// ============================================================================ +// SYSTEM PAGE +// ============================================================================ + +static void onCanSwitch(lv_event_t* e) { + if (g_refreshing) return; + CANDriver::setEnabled(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED)); +} + +static void onLinkSwitch(lv_event_t* e) { + if (g_refreshing) return; + UARTManager::setEnabled(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED)); +} + +static void onDebugSwitch(lv_event_t* e) { + if (g_refreshing) return; + bool on = lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED); + SettingsManager::saveDebugState(on); + UIStateManager::setDebugEnabled(on); +} + +static void refreshSystem(bool force) { + setChecked(g_sys_can, CANDriver::isActive()); + setChecked(g_sys_link, UARTManager::getState() != UARTManager::UART_STATE_OFF); + setChecked(g_sys_dbg, UIStateManager::isDebugEnabled()); + + static uint32_t last = 0; // the figures below change slowly; 1 Hz is plenty + if (!force && millis() - last < 1000) return; + last = millis(); + + can_stats_t cs = CANDriver::getStats(); + const esp_partition_t* run = esp_ota_get_running_partition(); + uint32_t up = millis() / 1000; + char buf[400]; + snprintf(buf, sizeof(buf), + "%s (slot %s)\n" + "ESP-NOW %s, %lu frames sent, %lu failed\n" + "%lu frames received\n" + "%u KB internal free, %u KB PSRAM free\n" + "%lu h %02lu min", + FW_VERSION, run ? run->label : "?", + EspNowLink::isReady() ? "up" : "DOWN", + (unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount(), + (unsigned long)cs.messages_received, + (unsigned)(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) / 1024), + (unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), + (unsigned long)(up / 3600), (unsigned long)((up / 60) % 60)); + setText(g_sys_info, buf); +} + +static void buildSystemPage(lv_obj_t* page) { + lv_obj_t* c = card(page); + lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(c, 10, 0); + + lv_obj_t* right; + makeSettingRow(c, "CAN bus", "Read the car's data bus", &right); + g_sys_can = toggle(right, onCanSwitch, NULL); + makeSettingRow(c, "Send to Controller B", "Gauge data over the wire and ESP-NOW", &right); + g_sys_link = toggle(right, onLinkSwitch, NULL); + makeSettingRow(c, "Performance overlay", "Frame rate and CPU load in the corner", &right); + g_sys_dbg = toggle(right, onDebugSwitch, NULL); + + // two labels side by side, same line spacing, so keys and values line up + lv_obj_t* info = card(page); + lv_obj_set_size(info, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(info, LV_FLEX_FLOW_ROW); + lv_obj_set_style_pad_column(info, 24, 0); + lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory\nUptime", &lv_font_montserrat_20, UI_COL_MUTED); + lv_obj_set_style_text_line_space(keys, 6, 0); + g_sys_info = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT); + lv_obj_set_style_text_line_space(g_sys_info, 6, 0); +} + +// ============================================================================ +// BUILD / REFRESH +// ============================================================================ + +static void build() { + if (g_screen != NULL) return; + + g_screen = screen(); + lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL); + header(g_screen, "SETTINGS", onBack); + + g_nav[PAGE_WIFI] = makeNav(g_screen, PAGE_WIFI, "Wi-Fi"); + g_nav[PAGE_UPDATES] = makeNav(g_screen, PAGE_UPDATES, "Updates"); + g_nav[PAGE_SYSTEM] = makeNav(g_screen, PAGE_SYSTEM, "System"); + + for (int i = 0; i < PAGE_COUNT; i++) g_page[i] = makePage(g_screen); + buildWifiPage(g_page[PAGE_WIFI]); + buildUpdatesPage(g_page[PAGE_UPDATES]); + buildSystemPage(g_page[PAGE_SYSTEM]); + buildPasswordOverlay(); + + ESP_LOGI("Settings", "Settings screen built"); +} + +static void refreshNav() { + WiFiManager::status_t s = WiFiManager::getStatus(); + const char* w = "Not connected"; + if (s.link == WiFiManager::LINK_OFF) w = "Off"; + else if (s.link == WiFiManager::LINK_CONNECTED) w = s.ssid; + else if (s.link == WiFiManager::LINK_CONNECTING) w = "Connecting..."; + setText(g_nav_sub[PAGE_WIFI], w); + setTextColor(g_nav_sub[PAGE_WIFI], s.link == WiFiManager::LINK_CONNECTED ? UI_COL_OK : UI_COL_MUTED); + + Ota::ui_status_t o = Ota::getStatus(); + bool avail = o.phase == Ota::PHASE_AVAILABLE; + setText(g_nav_sub[PAGE_UPDATES], avail ? "Update available" : FW_VERSION); + setTextColor(g_nav_sub[PAGE_UPDATES], avail ? UI_COL_ACCENT : UI_COL_MUTED); + + char sys[40]; + snprintf(sys, sizeof(sys), "CAN %s \xE2\x80\xA2 Link %s", CANDriver::isActive() ? "on" : "off", + UARTManager::getState() != UARTManager::UART_STATE_OFF ? "on" : "off"); + setText(g_nav_sub[PAGE_SYSTEM], sys); +} + +/** Caller holds the LVGL lock. */ +static void refresh(bool force) { + g_refreshing = true; + refreshNav(); + switch (g_cur) { + case PAGE_WIFI: refreshWifi(); break; + case PAGE_UPDATES: refreshUpdates(); break; + case PAGE_SYSTEM: refreshSystem(force); break; + default: break; + } + g_refreshing = false; +} + +// ============================================================================ +// PUBLIC API +// ============================================================================ + +void show() { + bool first = (g_screen == NULL); + build(); + if (first) selectPage(PAGE_WIFI); + else if (g_cur == PAGE_WIFI) g_want_scan = true; + refresh(true); + lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600 +} + +void tick() { + if (g_screen == NULL || lv_scr_act() != g_screen) return; + static uint32_t last = 0; + if (millis() - last < 250) return; + last = millis(); + lvgl_port_lock(-1); + refresh(false); + lvgl_port_unlock(); +} + +} // namespace SettingsScreen diff --git a/src/modules/settings_screen.h b/src/modules/settings_screen.h new file mode 100644 index 0000000..e6d5384 --- /dev/null +++ b/src/modules/settings_screen.h @@ -0,0 +1,31 @@ +/* + * Settings Screen Module + * + * Hand-coded (replaces the SquareLine Settings screen, 2026-09-27). Sidebar + * with three sections: + * Wi-Fi - switch, connection status, networks nearby, full-screen password + * entry; the joined network is remembered (WiFiManager) + * Updates - installed vs latest release, Check, Install behind a confirm + * dialog (Ota) + * System - CAN bus / link to Controller B / performance overlay switches, + * live link and memory figures + * + * Reached by swiping LEFT on the Driveline screen; swipe right or the + * Driveline button goes back. Built once and kept (never deleted), so nothing + * elsewhere ever holds a pointer into a destroyed screen. + */ + +#pragma once + +#include +#include + +namespace SettingsScreen { + +/** Build (idempotent), refresh and load. Caller holds the LVGL lock. */ +void show(); + +/** Refresh live values while the screen is shown. Call from loop(); takes its own lock. */ +void tick(); + +} // namespace SettingsScreen diff --git a/src/modules/tunables.cpp b/src/modules/tunables.cpp index 83ba462..d6c54df 100644 --- a/src/modules/tunables.cpp +++ b/src/modules/tunables.cpp @@ -268,6 +268,10 @@ void flush() { unlock(); } +bool isDirty() { + return g_dirty; +} + void pollSerial() { if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush(); diff --git a/src/modules/tunables.h b/src/modules/tunables.h index 83c3cba..f27e912 100644 --- a/src/modules/tunables.h +++ b/src/modules/tunables.h @@ -65,6 +65,9 @@ void pollSerial(); */ void flush(); +/** True while edits are waiting for their deferred NVS write. */ +bool isDirty(); + /** * Register a second console command handler (e.g. DiagProbe::handleCommand) * that gets lines `cfg` does not recognise. Returns true if it consumed the line. diff --git a/src/modules/tuning_screen.cpp b/src/modules/tuning_screen.cpp index 9db942c..88775dd 100644 --- a/src/modules/tuning_screen.cpp +++ b/src/modules/tuning_screen.cpp @@ -1,35 +1,25 @@ /* * Gauge Tuning Screen Module Implementation + * + * Four tabs (Tachometer / Coolant gauge / Alerts / Simulation), one value per + * row with a plain-language hint, car-sized -/+ buttons (hold to repeat, + * speeding up the longer you hold). Tabs are plain buttons + hidden panels: + * no sliding tabview animation, which re-renders the whole panel per frame. */ #include "tuning_screen.h" #include "tunables.h" +#include "ui_kit.h" #include "driveline_screen.h" #include "display/lvgl_v8_port.h" #include "esp_log.h" -extern "C" -{ -#include "ui.h" -} - namespace TuningScreen { + using namespace UiKit; // ============================================================================ - // THEME - // ============================================================================ - -#define COL_BG lv_color_hex(0x101418) -#define COL_PANEL lv_color_hex(0x1B2128) -#define COL_TEXT lv_color_hex(0xE8EDF2) -#define COL_MUTED lv_color_hex(0x6E7B88) -#define COL_ACCENT lv_color_hex(0x3DA9FC) -#define COL_OK lv_color_hex(0x3DD68C) -#define COL_WARN lv_color_hex(0xE5484D) - - // ============================================================================ - // FIELD TABLE — one row per numeric tunable + // FIELD TABLE - one row per numeric tunable // ============================================================================ typedef enum @@ -48,11 +38,14 @@ namespace TuningScreen F_COUNT } field_t; + typedef enum { TAB_TACH, TAB_COOLANT, TAB_ALERTS, TAB_SIM, TAB_COUNT } tab_t; + typedef struct { field_t id; + tab_t tab; const char *name; - const char *unit; + const char *hint; int32_t step; int32_t min; int32_t max; @@ -60,47 +53,37 @@ namespace TuningScreen } row_t; static row_t g_rows[F_COUNT] = { - {F_TACH_PPR, "Pulses / rev", "", 1, 1, 32, NULL}, - {F_TACH_TRIM, "Trim", "%", 1, -50, 50, NULL}, - {F_TACH_MAX_HZ, "Max output", "Hz", 10, 0, 5000, NULL}, - {F_TEMP_HZ, "PWM frequency", "Hz", 50, 20, 20000, NULL}, - {F_TEMP_SLOPE, "Slope", "x100", 5, 0, 5000, NULL}, - {F_TEMP_OFFSET, "Offset", "", 1, -1000, 1000, NULL}, - {F_TEMP_MIN, "Min temp", "C", 1, -50, 200, NULL}, - {F_TEMP_DUTY_MAX, "Duty clamp", "", 5, 0, 255, NULL}, - {F_COOLANT_HOT, "Coolant hot", "C", 1, 0, 200, NULL}, - {F_GEARBOX_HOT, "Gearbox hot", "C", 1, 0, 200, NULL}, - {F_BATT_LOW, "Battery low", "x0.01V", 10, 0, 3000, NULL}, + {F_TACH_PPR, TAB_TACH, "Pulses per revolution", "Pulses per engine revolution the Patrol tach expects", 1, 1, 32, NULL}, + {F_TACH_TRIM, TAB_TACH, "Trim", "Fine correction if the needle reads high or low", 1, -50, 50, NULL}, + {F_TACH_MAX_HZ, TAB_TACH, "Maximum output", "Highest tach frequency sent (0 = no limit)", 10, 0, 5000, NULL}, + {F_TEMP_HZ, TAB_COOLANT, "PWM frequency", "Drive frequency of the coolant gauge signal", 50, 20, 20000, NULL}, + {F_TEMP_SLOPE, TAB_COOLANT, "Slope", "Duty added per \xC2\xB0" "C of coolant", 5, 0, 5000, NULL}, + {F_TEMP_OFFSET, TAB_COOLANT, "Offset", "Duty at 0 \xC2\xB0" "C (duty = slope x temp + offset)", 1, -1000, 1000, NULL}, + {F_TEMP_MIN, TAB_COOLANT, "Minimum temperature", "Needle stays at rest below this", 1, -50, 200, NULL}, + {F_TEMP_DUTY_MAX, TAB_COOLANT, "Duty limit", "Highest duty sent (255 = full scale)", 5, 0, 255, NULL}, + {F_COOLANT_HOT, TAB_ALERTS, "Coolant too hot", "Alarm on Controller B at or above this temperature", 1, 0, 200, NULL}, + {F_GEARBOX_HOT, TAB_ALERTS, "Gearbox oil too hot", "Alarm on Controller B at or above this temperature", 1, 0, 200, NULL}, + {F_BATT_LOW, TAB_ALERTS, "Battery low", "Alarm on Controller B below this voltage", 10, 0, 3000, NULL}, }; + static const char *TAB_NAMES[TAB_COUNT] = {"Tachometer", "Coolant gauge", "Alerts", "Simulation"}; + static int32_t getField(const link_config_t &c, field_t f) { switch (f) { - case F_TACH_PPR: - return c.tach_ppr; - case F_TACH_TRIM: - return c.tach_trim_pct; - case F_TACH_MAX_HZ: - return c.tach_max_hz; - case F_TEMP_HZ: - return c.temp_pwm_hz; - case F_TEMP_SLOPE: - return c.temp_slope_x100; - case F_TEMP_OFFSET: - return c.temp_offset; - case F_TEMP_MIN: - return c.temp_min_c; - case F_TEMP_DUTY_MAX: - return c.temp_duty_max; - case F_COOLANT_HOT: - return c.coolant_hot_c; - case F_GEARBOX_HOT: - return c.gearbox_hot_c; - case F_BATT_LOW: - return c.battery_low_x100; - default: - return 0; + case F_TACH_PPR: return c.tach_ppr; + case F_TACH_TRIM: return c.tach_trim_pct; + case F_TACH_MAX_HZ: return c.tach_max_hz; + case F_TEMP_HZ: return c.temp_pwm_hz; + case F_TEMP_SLOPE: return c.temp_slope_x100; + case F_TEMP_OFFSET: return c.temp_offset; + case F_TEMP_MIN: return c.temp_min_c; + case F_TEMP_DUTY_MAX: return c.temp_duty_max; + case F_COOLANT_HOT: return c.coolant_hot_c; + case F_GEARBOX_HOT: return c.gearbox_hot_c; + case F_BATT_LOW: return c.battery_low_x100; + default: return 0; } } @@ -108,41 +91,36 @@ namespace TuningScreen { switch (f) { - case F_TACH_PPR: - c.tach_ppr = (uint8_t)v; - break; - case F_TACH_TRIM: - c.tach_trim_pct = (int8_t)v; - break; - case F_TACH_MAX_HZ: - c.tach_max_hz = (uint16_t)v; - break; - case F_TEMP_HZ: - c.temp_pwm_hz = (uint16_t)v; - break; - case F_TEMP_SLOPE: - c.temp_slope_x100 = (uint16_t)v; - break; - case F_TEMP_OFFSET: - c.temp_offset = (int16_t)v; - break; + case F_TACH_PPR: c.tach_ppr = (uint8_t)v; break; + case F_TACH_TRIM: c.tach_trim_pct = (int8_t)v; break; + case F_TACH_MAX_HZ: c.tach_max_hz = (uint16_t)v; break; + case F_TEMP_HZ: c.temp_pwm_hz = (uint16_t)v; break; + case F_TEMP_SLOPE: c.temp_slope_x100 = (uint16_t)v; break; + case F_TEMP_OFFSET: c.temp_offset = (int16_t)v; break; + case F_TEMP_MIN: c.temp_min_c = (int16_t)v; break; + case F_TEMP_DUTY_MAX: c.temp_duty_max = (uint8_t)v; break; + case F_COOLANT_HOT: c.coolant_hot_c = (int16_t)v; break; + case F_GEARBOX_HOT: c.gearbox_hot_c = (int16_t)v; break; + case F_BATT_LOW: c.battery_low_x100 = (uint16_t)v; break; + default: break; + } + } + + static void formatValue(field_t f, int32_t v, char *out, size_t n) + { + switch (f) + { + case F_TACH_TRIM: snprintf(out, n, "%+ld %%", (long)v); break; + case F_TACH_MAX_HZ: if (v == 0) snprintf(out, n, "no limit"); else snprintf(out, n, "%ld Hz", (long)v); break; + case F_TEMP_HZ: snprintf(out, n, "%ld Hz", (long)v); break; + case F_TEMP_SLOPE: snprintf(out, n, "%ld.%02ld", (long)(v / 100), (long)labs(v % 100)); break; + case F_TEMP_OFFSET: snprintf(out, n, "%+ld", (long)v); break; case F_TEMP_MIN: - c.temp_min_c = (int16_t)v; - break; - case F_TEMP_DUTY_MAX: - c.temp_duty_max = (uint8_t)v; - break; case F_COOLANT_HOT: - c.coolant_hot_c = (int16_t)v; - break; - case F_GEARBOX_HOT: - c.gearbox_hot_c = (int16_t)v; - break; - case F_BATT_LOW: - c.battery_low_x100 = (uint16_t)v; - break; - default: - break; + case F_GEARBOX_HOT: snprintf(out, n, "%ld \xC2\xB0" "C", (long)v); break; + case F_TEMP_DUTY_MAX: snprintf(out, n, "%ld / 255", (long)v); break; + case F_BATT_LOW: snprintf(out, n, "%ld.%02ld V", (long)(v / 100), (long)(v % 100)); break; + default: snprintf(out, n, "%ld", (long)v); break; } } @@ -151,6 +129,12 @@ namespace TuningScreen // ============================================================================ static lv_obj_t *g_screen = NULL; + static lv_obj_t *g_tab_btn[TAB_COUNT]; + static lv_obj_t *g_tab_page[TAB_COUNT]; + static tab_t g_tab = TAB_TACH; + static lv_obj_t *g_reset_btn = NULL; + static lv_obj_t *g_sim_chip = NULL; + static lv_obj_t *g_save_lbl = NULL; static lv_obj_t *g_tach_en_sw = NULL; static lv_obj_t *g_temp_en_sw = NULL; static lv_obj_t *g_ovr_rpm_sw = NULL; @@ -159,32 +143,34 @@ namespace TuningScreen static lv_obj_t *g_ovr_duty_sl = NULL; static lv_obj_t *g_ovr_rpm_lbl = NULL; static lv_obj_t *g_ovr_duty_lbl = NULL; - static lv_obj_t *g_status_lbl = NULL; static uint8_t g_shown_version = 0; static bool g_refreshing = false; // suppress event handlers while we set widget values + static uint16_t g_repeats = 0; // long-press repeat count of the button being held + + static const int32_t RPM_MAX = 6000, RPM_STEP = 100; + static const int32_t DUTY_MAX = 255, DUTY_STEP = 5; // ============================================================================ - // HELPERS + // REFRESH // ============================================================================ - static void formatValue(const row_t &r, int32_t v, char *out, size_t n) + static void refreshSaveState() { - if (r.id == F_TEMP_SLOPE) - { - snprintf(out, n, "%ld.%02ld", (long)(v / 100), (long)labs(v % 100)); - } - else if (r.id == F_BATT_LOW) - { - snprintf(out, n, "%ld.%02ld V", (long)(v / 100), (long)(v % 100)); - } - else if (r.unit[0]) - { - snprintf(out, n, "%ld %s", (long)v, r.unit); - } + link_config_t c = Tunables::get(); + const char *txt; + lv_color_t col = UI_COL_MUTED; + if (g_tab == TAB_SIM) + txt = "Simulation values are never saved - a restart returns to live data"; + else if (Tunables::isDirty()) + txt = "Saving..."; else { - snprintf(out, n, "%ld", (long)v); + txt = LV_SYMBOL_OK " All changes saved"; + col = UI_COL_OK; } + setText(g_save_lbl, txt); + setTextColor(g_save_lbl, col); + setVisible(g_sim_chip, c.override_mode != 0); } static void refreshFromTunables() @@ -192,58 +178,38 @@ namespace TuningScreen link_config_t c = Tunables::get(); g_refreshing = true; - char buf[24]; + char buf[32]; for (int i = 0; i < F_COUNT; i++) { if (g_rows[i].value_lbl == NULL) continue; - formatValue(g_rows[i], getField(c, g_rows[i].id), buf, sizeof(buf)); - lv_label_set_text(g_rows[i].value_lbl, buf); + formatValue(g_rows[i].id, getField(c, g_rows[i].id), buf, sizeof(buf)); + setText(g_rows[i].value_lbl, buf); } - auto setSw = [](lv_obj_t *sw, bool on) - { - if (sw == NULL) - return; - if (on) - lv_obj_add_state(sw, LV_STATE_CHECKED); - else - lv_obj_clear_state(sw, LV_STATE_CHECKED); - }; - setSw(g_tach_en_sw, c.out_enable & OUT_ENABLE_TACH); - setSw(g_temp_en_sw, c.out_enable & OUT_ENABLE_TEMP); - setSw(g_ovr_rpm_sw, c.override_mode & OVERRIDE_TACH); - setSw(g_ovr_duty_sw, c.override_mode & OVERRIDE_TEMP); + setChecked(g_tach_en_sw, c.out_enable & OUT_ENABLE_TACH); + setChecked(g_temp_en_sw, c.out_enable & OUT_ENABLE_TEMP); + setChecked(g_ovr_rpm_sw, c.override_mode & OVERRIDE_TACH); + setChecked(g_ovr_duty_sw, c.override_mode & OVERRIDE_TEMP); - if (g_ovr_rpm_sl) + if (g_ovr_rpm_sl && !lv_obj_has_state(g_ovr_rpm_sl, LV_STATE_PRESSED)) lv_slider_set_value(g_ovr_rpm_sl, c.override_rpm, LV_ANIM_OFF); - if (g_ovr_duty_sl) + if (g_ovr_duty_sl && !lv_obj_has_state(g_ovr_duty_sl, LV_STATE_PRESSED)) lv_slider_set_value(g_ovr_duty_sl, c.override_duty, LV_ANIM_OFF); - if (g_ovr_rpm_lbl) - { - snprintf(buf, sizeof(buf), "%u rpm", c.override_rpm); - lv_label_set_text(g_ovr_rpm_lbl, buf); - } - if (g_ovr_duty_lbl) - { - snprintf(buf, sizeof(buf), "%u / 255", c.override_duty); - lv_label_set_text(g_ovr_duty_lbl, buf); - } - - if (g_status_lbl) - { - snprintf(buf, sizeof(buf), "config v%u", c.cfg_version); - lv_label_set_text(g_status_lbl, buf); - lv_obj_set_style_text_color(g_status_lbl, c.override_mode ? COL_WARN : COL_MUTED, 0); - } + snprintf(buf, sizeof(buf), "%u rpm", c.override_rpm); + setText(g_ovr_rpm_lbl, buf); + snprintf(buf, sizeof(buf), "%u / 255", c.override_duty); + setText(g_ovr_duty_lbl, buf); + refreshSaveState(); g_shown_version = c.cfg_version; g_refreshing = false; } - // ---- event handlers -------------------------------------------------------- + // ============================================================================ + // EVENT HANDLERS + // ============================================================================ - // user_data = row pointer; the button's own user data (+1/-1) is in lv_event_get_user_data typedef struct { row_t *row; @@ -251,29 +217,44 @@ namespace TuningScreen } step_ctx_t; static step_ctx_t g_step_ctx[F_COUNT][2]; + /** 1x for taps and the first second of a hold, then 5x, then 10x. */ + static int32_t holdMultiplier(lv_event_code_t code) + { + if (code == LV_EVENT_PRESSED) + { + g_repeats = 0; + return 0; + } + if (code == LV_EVENT_LONG_PRESSED_REPEAT) + { + g_repeats++; + return g_repeats > 25 ? 10 : g_repeats > 10 ? 5 : 1; + } + return 1; // CLICKED + } + static void onStep(lv_event_t *e) { lv_event_code_t code = lv_event_get_code(e); - if (code != LV_EVENT_CLICKED && code != LV_EVENT_LONG_PRESSED_REPEAT) + int32_t mult = holdMultiplier(code); + if (mult == 0) return; + if (code == LV_EVENT_CLICKED && g_repeats > 0) + return; // end of a hold, already applied step_ctx_t *ctx = (step_ctx_t *)lv_event_get_user_data(e); link_config_t c = Tunables::get(); - int32_t v = getField(c, ctx->row->id) + ctx->dir * ctx->row->step; - if (v < ctx->row->min) - v = ctx->row->min; - if (v > ctx->row->max) - v = ctx->row->max; + int32_t v = getField(c, ctx->row->id) + ctx->dir * ctx->row->step * mult; + v = constrain(v, ctx->row->min, ctx->row->max); setField(c, ctx->row->id, v); - Tunables::set(c); // saves + bumps version -> CONFIG frame goes out + Tunables::set(c); // bumps version -> CONFIG frame goes out; NVS write after 3 s idle refreshFromTunables(); } static void onEnableSwitch(lv_event_t *e) { - if (g_refreshing || lv_event_get_code(e) != LV_EVENT_VALUE_CHANGED) + if (g_refreshing) return; - lv_obj_t *sw = lv_event_get_target(e); - bool on = lv_obj_has_state(sw, LV_STATE_CHECKED); + bool on = lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED); uint8_t bit = (uint8_t)(uintptr_t)lv_event_get_user_data(e); link_config_t c = Tunables::get(); c.out_enable = on ? (c.out_enable | bit) : (c.out_enable & ~bit); @@ -283,23 +264,21 @@ namespace TuningScreen static void pushOverride() { - link_config_t c = Tunables::get(); uint8_t mode = 0; - if (g_ovr_rpm_sw && lv_obj_has_state(g_ovr_rpm_sw, LV_STATE_CHECKED)) + if (lv_obj_has_state(g_ovr_rpm_sw, LV_STATE_CHECKED)) mode |= OVERRIDE_TACH; - if (g_ovr_duty_sw && lv_obj_has_state(g_ovr_duty_sw, LV_STATE_CHECKED)) + if (lv_obj_has_state(g_ovr_duty_sw, LV_STATE_CHECKED)) mode |= OVERRIDE_TEMP; - uint16_t rpm = g_ovr_rpm_sl ? (uint16_t)lv_slider_get_value(g_ovr_rpm_sl) : c.override_rpm; - uint8_t duty = g_ovr_duty_sl ? (uint8_t)lv_slider_get_value(g_ovr_duty_sl) : c.override_duty; - Tunables::setOverride(mode, rpm, duty); // pushed to B, never saved + Tunables::setOverride(mode, (uint16_t)lv_slider_get_value(g_ovr_rpm_sl), + (uint8_t)lv_slider_get_value(g_ovr_duty_sl)); // pushed to B, never saved refreshFromTunables(); } static void onOverrideSwitch(lv_event_t *e) { - if (g_refreshing || lv_event_get_code(e) != LV_EVENT_VALUE_CHANGED) - return; - pushOverride(); + (void)e; + if (!g_refreshing) + pushOverride(); } static void onOverrideSlider(lv_event_t *e) @@ -307,21 +286,21 @@ namespace TuningScreen if (g_refreshing) return; lv_event_code_t code = lv_event_get_code(e); - // Update the readout while dragging; push to B on release so we don't - // flood the link with CONFIG frames at touch rate. + lv_obj_t *sl = lv_event_get_target(e); + // Readout follows the finger; push to B on release so we don't flood + // the link with CONFIG frames at touch rate. if (code == LV_EVENT_VALUE_CHANGED) { char buf[24]; - lv_obj_t *sl = lv_event_get_target(e); - if (sl == g_ovr_rpm_sl && g_ovr_rpm_lbl) + if (sl == g_ovr_rpm_sl) { snprintf(buf, sizeof(buf), "%d rpm", (int)lv_slider_get_value(sl)); - lv_label_set_text(g_ovr_rpm_lbl, buf); + setText(g_ovr_rpm_lbl, buf); } - else if (sl == g_ovr_duty_sl && g_ovr_duty_lbl) + else { snprintf(buf, sizeof(buf), "%d / 255", (int)lv_slider_get_value(sl)); - lv_label_set_text(g_ovr_duty_lbl, buf); + setText(g_ovr_duty_lbl, buf); } } else if (code == LV_EVENT_RELEASED) @@ -330,250 +309,252 @@ namespace TuningScreen } } + /** Fine -/+ next to a slider; user data = +/-1, slider picked by the button's parent row. */ + static void onSimStep(lv_event_t *e) + { + lv_event_code_t code = lv_event_get_code(e); + int32_t mult = holdMultiplier(code); + if (mult == 0 || (code == LV_EVENT_CLICKED && g_repeats > 0)) + return; + int dir = (int)(intptr_t)lv_event_get_user_data(e); + lv_obj_t *btn = lv_event_get_target(e); + bool rpm = lv_obj_get_parent(btn) == lv_obj_get_parent(g_ovr_rpm_sl); + lv_obj_t *sl = rpm ? g_ovr_rpm_sl : g_ovr_duty_sl; + int32_t v = lv_slider_get_value(sl) + dir * (rpm ? RPM_STEP : DUTY_STEP) * mult; + lv_slider_set_value(sl, constrain(v, 0, rpm ? RPM_MAX : DUTY_MAX), LV_ANIM_OFF); + pushOverride(); + } + static void onBack(lv_event_t *e) { - if (lv_event_get_code(e) != LV_EVENT_CLICKED) - return; - Tunables::flush(); // write pending edits now rather than after the idle delay + (void)e; + Tunables::flush(); // write pending edits now rather than after the idle delay DrivelineScreen::show(); } + static void onGesture(lv_event_t *e) + { + (void)e; + if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_LEFT) + { + lv_indev_wait_release(lv_indev_get_act()); + Tunables::flush(); + DrivelineScreen::show(); + } + } + + static void onResetConfirmed(bool ok, void *user) + { + if (!ok) + return; + tab_t tab = (tab_t)(uintptr_t)user; + link_config_t d, c = Tunables::get(); + link_config_defaults(&d); + for (int i = 0; i < F_COUNT; i++) + if (g_rows[i].tab == tab) + setField(c, g_rows[i].id, getField(d, g_rows[i].id)); + uint8_t bit = tab == TAB_TACH ? OUT_ENABLE_TACH : tab == TAB_COOLANT ? OUT_ENABLE_TEMP : 0; + c.out_enable = (c.out_enable & ~bit) | (d.out_enable & bit); + Tunables::set(c); + refreshFromTunables(); + } + static void onReset(lv_event_t *e) { - if (lv_event_get_code(e) != LV_EVENT_CLICKED) - return; - Tunables::resetDefaults(); - refreshFromTunables(); + (void)e; + char title[64]; + snprintf(title, sizeof(title), "Reset %s?", TAB_NAMES[g_tab]); + confirm(title, "Every value on this tab goes back to its default. The other tabs are not touched.", + "Reset", onResetConfirmed, (void *)(uintptr_t)g_tab); } - // ---- builders -------------------------------------------------------------- - - static lv_obj_t *makePanel(lv_obj_t *parent, const char *title, lv_coord_t w) + static void selectTab(tab_t t) { - lv_obj_t *p = lv_obj_create(parent); - lv_obj_set_size(p, w, LV_SIZE_CONTENT); - lv_obj_set_style_bg_color(p, COL_PANEL, 0); - lv_obj_set_style_border_width(p, 0, 0); - lv_obj_set_style_radius(p, 12, 0); - lv_obj_set_style_pad_all(p, 12, 0); - lv_obj_set_style_pad_row(p, 6, 0); - lv_obj_set_flex_flow(p, LV_FLEX_FLOW_COLUMN); - lv_obj_clear_flag(p, LV_OBJ_FLAG_SCROLLABLE); - - lv_obj_t *t = lv_label_create(p); - lv_label_set_text(t, title); - lv_obj_set_style_text_font(t, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(t, COL_ACCENT, 0); - lv_obj_set_style_pad_bottom(t, 4, 0); - return p; + g_tab = t; + for (int i = 0; i < TAB_COUNT; i++) + { + bool on = (i == t); + setVisible(g_tab_page[i], on); + lv_obj_set_style_bg_color(g_tab_btn[i], on ? UI_COL_ACCENT : UI_COL_PANEL, 0); + lv_obj_set_style_text_color(g_tab_btn[i], on ? lv_color_hex(0x0B1620) : UI_COL_TEXT, 0); + } + setVisible(g_reset_btn, t != TAB_SIM); + refreshSaveState(); } - static lv_obj_t *makeStepBtn(lv_obj_t *parent, const char *txt, step_ctx_t *ctx) + static void onTab(lv_event_t *e) { - lv_obj_t *b = lv_btn_create(parent); - lv_obj_set_size(b, 44, 36); - lv_obj_set_style_bg_color(b, COL_BG, 0); - lv_obj_set_style_radius(b, 8, 0); - lv_obj_add_event_cb(b, onStep, LV_EVENT_CLICKED, ctx); - lv_obj_add_event_cb(b, onStep, LV_EVENT_LONG_PRESSED_REPEAT, ctx); - lv_obj_t *l = lv_label_create(b); - lv_label_set_text(l, txt); - lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0); - lv_obj_center(l); + selectTab((tab_t)(uintptr_t)lv_event_get_user_data(e)); + } + + // ============================================================================ + // BUILDERS + // ============================================================================ + + static lv_obj_t *makeStepBtn(lv_obj_t *parent, const char *txt, lv_event_cb_t cb, void *ctx) + { + lv_obj_t *b = button(parent, txt, 76, 56, BTN_SECONDARY, NULL, NULL); + lv_obj_set_style_text_font(lv_obj_get_child(b, 0), &lv_font_montserrat_24, 0); + lv_obj_add_event_cb(b, cb, LV_EVENT_PRESSED, ctx); + lv_obj_add_event_cb(b, cb, LV_EVENT_CLICKED, ctx); + lv_obj_add_event_cb(b, cb, LV_EVENT_LONG_PRESSED_REPEAT, ctx); return b; } - static void makeRow(lv_obj_t *panel, field_t f) + /** [name / hint] ... [-] value [+] */ + static void makeRow(lv_obj_t *page, field_t f) { row_t *r = &g_rows[f]; - lv_obj_t *row = lv_obj_create(panel); - lv_obj_remove_style_all(row); - lv_obj_set_size(row, LV_PCT(100), 36); - lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW); + lv_obj_t *row = box(page, LV_FLEX_FLOW_ROW); + lv_obj_set_size(row, LV_PCT(100), 62); lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_set_style_pad_column(row, 6, 0); - lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_style_pad_column(row, 12, 0); - lv_obj_t *name = lv_label_create(row); - lv_label_set_text(name, r->name); - lv_obj_set_style_text_font(name, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(name, COL_MUTED, 0); - lv_obj_set_width(name, 118); + lv_obj_t *txt = box(row, LV_FLEX_FLOW_COLUMN); + lv_obj_set_height(txt, LV_SIZE_CONTENT); + lv_obj_set_flex_grow(txt, 1); + lv_obj_set_style_pad_row(txt, 2, 0); + label(txt, r->name, &lv_font_montserrat_24, UI_COL_TEXT); + label(txt, r->hint, &lv_font_montserrat_14, UI_COL_MUTED); g_step_ctx[f][0] = {r, -1}; g_step_ctx[f][1] = {r, +1}; - makeStepBtn(row, LV_SYMBOL_MINUS, &g_step_ctx[f][0]); - - r->value_lbl = lv_label_create(row); - lv_label_set_text(r->value_lbl, "--"); - lv_obj_set_style_text_font(r->value_lbl, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(r->value_lbl, COL_TEXT, 0); + makeStepBtn(row, LV_SYMBOL_MINUS, onStep, &g_step_ctx[f][0]); + r->value_lbl = label(row, "--", &lv_font_montserrat_30, UI_COL_TEXT); lv_obj_set_style_text_align(r->value_lbl, LV_TEXT_ALIGN_CENTER, 0); - lv_obj_set_width(r->value_lbl, 82); - - makeStepBtn(row, LV_SYMBOL_PLUS, &g_step_ctx[f][1]); + lv_obj_set_width(r->value_lbl, 190); + makeStepBtn(row, LV_SYMBOL_PLUS, onStep, &g_step_ctx[f][1]); } - static lv_obj_t *makeSwitchRow(lv_obj_t *panel, const char *text, lv_event_cb_t cb, void *user) + static lv_obj_t *makeSwitchRow(lv_obj_t *page, const char *name, const char *hint, lv_event_cb_t cb, void *user) { - lv_obj_t *row = lv_obj_create(panel); - lv_obj_remove_style_all(row); - lv_obj_set_size(row, LV_PCT(100), 36); - lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW); + lv_obj_t *row = box(page, LV_FLEX_FLOW_ROW); + lv_obj_set_size(row, LV_PCT(100), 62); lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE); - - lv_obj_t *l = lv_label_create(row); - lv_label_set_text(l, text); - lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(l, COL_MUTED, 0); - - lv_obj_t *sw = lv_switch_create(row); - lv_obj_set_style_bg_color(sw, COL_ACCENT, (lv_style_selector_t)LV_PART_INDICATOR | (lv_style_selector_t)LV_STATE_CHECKED); - lv_obj_add_event_cb(sw, cb, LV_EVENT_VALUE_CHANGED, user); + lv_obj_t *txt = box(row, LV_FLEX_FLOW_COLUMN); + lv_obj_set_size(txt, LV_SIZE_CONTENT, LV_SIZE_CONTENT); + lv_obj_set_style_pad_row(txt, 2, 0); + label(txt, name, &lv_font_montserrat_24, UI_COL_TEXT); + label(txt, hint, &lv_font_montserrat_14, UI_COL_MUTED); + lv_obj_t *sw = toggle(row, cb, user); + lv_obj_set_style_pad_right(row, 70, 0); // line the switch up under the value column return sw; } - static lv_obj_t *makeSliderRow(lv_obj_t *panel, const char *text, int32_t max, lv_obj_t **readout) + /** Simulation card: title + readout + switch, then [-] slider [+]. */ + static lv_obj_t *makeSimCard(lv_obj_t *page, const char *title, int32_t max, lv_obj_t **sw, lv_obj_t **readout) { - lv_obj_t *head = lv_obj_create(panel); - lv_obj_remove_style_all(head); - lv_obj_set_size(head, LV_PCT(100), 20); - lv_obj_set_flex_flow(head, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(head, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - lv_obj_clear_flag(head, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_t *c = card(page); + lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(c, 14, 0); - lv_obj_t *l = lv_label_create(head); - lv_label_set_text(l, text); - lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(l, COL_MUTED, 0); + lv_obj_t *top = box(c, LV_FLEX_FLOW_ROW); + lv_obj_set_size(top, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_align(top, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_t *t = label(top, title, &lv_font_montserrat_24, UI_COL_TEXT); + lv_obj_set_flex_grow(t, 1); + *readout = label(top, "--", &lv_font_montserrat_30, UI_COL_TEXT); + lv_obj_set_style_pad_right(*readout, 24, 0); + *sw = toggle(top, onOverrideSwitch, NULL); - *readout = lv_label_create(head); - lv_label_set_text(*readout, "--"); - lv_obj_set_style_text_font(*readout, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(*readout, COL_TEXT, 0); - - lv_obj_t *sl = lv_slider_create(panel); - lv_obj_set_width(sl, LV_PCT(96)); + lv_obj_t *bottom = box(c, LV_FLEX_FLOW_ROW); + lv_obj_set_size(bottom, LV_PCT(100), LV_SIZE_CONTENT); + lv_obj_set_flex_align(bottom, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); + lv_obj_set_style_pad_column(bottom, 24, 0); + makeStepBtn(bottom, LV_SYMBOL_MINUS, onSimStep, (void *)(intptr_t)-1); + lv_obj_t *sl = lv_slider_create(bottom); + lv_obj_set_height(sl, 16); + lv_obj_set_flex_grow(sl, 1); lv_slider_set_range(sl, 0, max); - lv_obj_set_style_bg_color(sl, COL_BG, 0); - lv_obj_set_style_bg_color(sl, COL_ACCENT, LV_PART_INDICATOR); - lv_obj_set_style_bg_color(sl, COL_TEXT, LV_PART_KNOB); + lv_obj_set_style_bg_color(sl, UI_COL_PANEL2, 0); + lv_obj_set_style_bg_color(sl, UI_COL_ACCENT, LV_PART_INDICATOR); + lv_obj_set_style_bg_color(sl, UI_COL_TEXT, LV_PART_KNOB); + lv_obj_set_style_pad_all(sl, 12, LV_PART_KNOB); // big knob + lv_obj_set_style_anim_time(sl, 0, 0); + lv_obj_clear_flag(sl, LV_OBJ_FLAG_GESTURE_BUBBLE); // dragging must not change screens lv_obj_add_event_cb(sl, onOverrideSlider, LV_EVENT_VALUE_CHANGED, NULL); lv_obj_add_event_cb(sl, onOverrideSlider, LV_EVENT_RELEASED, NULL); + lv_obj_set_style_pad_ver(bottom, 12, 0); // room for the knob + makeStepBtn(bottom, LV_SYMBOL_PLUS, onSimStep, (void *)(intptr_t)1); return sl; } + static lv_obj_t *makeTabPage() + { + lv_obj_t *p = box(g_screen, LV_FLEX_FLOW_COLUMN); + lv_obj_set_size(p, 1024 - 48, 600 - 150 - 36); + lv_obj_set_pos(p, 24, 150); + lv_obj_set_style_pad_row(p, 6, 0); + return p; + } + static void build() { if (g_screen != NULL) return; - g_screen = lv_obj_create(NULL); - lv_obj_set_style_bg_color(g_screen, COL_BG, 0); - lv_obj_clear_flag(g_screen, LV_OBJ_FLAG_SCROLLABLE); - // No swipe gesture on this screen: dragging the override sliders would - // otherwise change screens. Leave via the Driveline button (top right). + g_screen = screen(); + lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL); + header(g_screen, "GAUGE TUNING", onBack); - lv_obj_t *title = lv_label_create(g_screen); - lv_label_set_text(title, "GAUGE TUNING"); - lv_obj_set_style_text_font(title, &lv_font_montserrat_30, 0); - lv_obj_set_style_text_color(title, COL_TEXT, 0); - lv_obj_align(title, LV_ALIGN_TOP_LEFT, 24, 16); + g_sim_chip = label(g_screen, "SIMULATION ON", &lv_font_montserrat_20, UI_COL_TEXT); + lv_obj_set_style_bg_color(g_sim_chip, UI_COL_WARN, 0); + lv_obj_set_style_bg_opa(g_sim_chip, LV_OPA_COVER, 0); + lv_obj_set_style_radius(g_sim_chip, 8, 0); + lv_obj_set_style_pad_hor(g_sim_chip, 12, 0); + lv_obj_set_style_pad_ver(g_sim_chip, 6, 0); + lv_obj_align(g_sim_chip, LV_ALIGN_TOP_LEFT, 290, 22); + lv_obj_add_flag(g_sim_chip, LV_OBJ_FLAG_HIDDEN); - lv_obj_t *back = lv_btn_create(g_screen); - lv_obj_set_size(back, 150, 36); - lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -24, 18); - lv_obj_set_style_bg_color(back, COL_ACCENT, 0); - lv_obj_add_event_cb(back, onBack, LV_EVENT_CLICKED, NULL); - lv_obj_t *bl = lv_label_create(back); - lv_label_set_text(bl, LV_SYMBOL_HOME " Driveline"); - lv_obj_set_style_text_font(bl, &lv_font_montserrat_14, 0); - lv_obj_center(bl); + g_reset_btn = button(g_screen, LV_SYMBOL_REFRESH " Reset tab", 190, 56, BTN_SECONDARY, onReset, NULL); + lv_obj_align(g_reset_btn, LV_ALIGN_TOP_RIGHT, -16 - 200 - 12, 10); - lv_obj_t *reset = lv_btn_create(g_screen); - lv_obj_set_size(reset, 150, 36); - lv_obj_align(reset, LV_ALIGN_TOP_RIGHT, -24 - 150 - 12, 18); - lv_obj_set_style_bg_color(reset, COL_PANEL, 0); - lv_obj_add_event_cb(reset, onReset, LV_EVENT_CLICKED, NULL); - lv_obj_t *rl = lv_label_create(reset); - lv_label_set_text(rl, LV_SYMBOL_REFRESH " Defaults"); - lv_obj_set_style_text_font(rl, &lv_font_montserrat_14, 0); - lv_obj_center(rl); + // tab bar + for (int i = 0; i < TAB_COUNT; i++) + { + g_tab_btn[i] = button(g_screen, TAB_NAMES[i], 232, 58, BTN_SECONDARY, onTab, (void *)(uintptr_t)i); + lv_obj_set_pos(g_tab_btn[i], 24 + i * (232 + 12), 80); + g_tab_page[i] = makeTabPage(); + } - // Three columns of panels - lv_obj_t *cols = lv_obj_create(g_screen); - lv_obj_remove_style_all(cols); - lv_obj_set_size(cols, 1024 - 48, 600 - 70 - 30); - lv_obj_align(cols, LV_ALIGN_TOP_LEFT, 24, 66); - lv_obj_set_flex_flow(cols, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(cols, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START); - lv_obj_clear_flag(cols, LV_OBJ_FLAG_SCROLLABLE); + // ---- Tachometer ---- + makeRow(g_tab_page[TAB_TACH], F_TACH_PPR); + makeRow(g_tab_page[TAB_TACH], F_TACH_TRIM); + makeRow(g_tab_page[TAB_TACH], F_TACH_MAX_HZ); + g_tach_en_sw = makeSwitchRow(g_tab_page[TAB_TACH], "Tachometer output", "IO7 on Controller B. Off = no signal", + onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH); - const lv_coord_t W = 320; + // ---- Coolant gauge ---- + makeRow(g_tab_page[TAB_COOLANT], F_TEMP_HZ); + makeRow(g_tab_page[TAB_COOLANT], F_TEMP_SLOPE); + makeRow(g_tab_page[TAB_COOLANT], F_TEMP_OFFSET); + makeRow(g_tab_page[TAB_COOLANT], F_TEMP_MIN); + makeRow(g_tab_page[TAB_COOLANT], F_TEMP_DUTY_MAX); + g_temp_en_sw = makeSwitchRow(g_tab_page[TAB_COOLANT], "Coolant gauge output", "IO8 on Controller B. Off = no signal", + onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP); - // ---- column 1: tach + alerts ---- - lv_obj_t *c1 = lv_obj_create(cols); - lv_obj_remove_style_all(c1); - lv_obj_set_size(c1, W, LV_SIZE_CONTENT); - lv_obj_set_flex_flow(c1, LV_FLEX_FLOW_COLUMN); - lv_obj_set_style_pad_row(c1, 12, 0); - lv_obj_clear_flag(c1, LV_OBJ_FLAG_SCROLLABLE); + // ---- Alerts ---- + makeRow(g_tab_page[TAB_ALERTS], F_COOLANT_HOT); + makeRow(g_tab_page[TAB_ALERTS], F_GEARBOX_HOT); + makeRow(g_tab_page[TAB_ALERTS], F_BATT_LOW); - lv_obj_t *tach = makePanel(c1, "TACHOMETER(IO7)", W); - makeRow(tach, F_TACH_PPR); - makeRow(tach, F_TACH_TRIM); - makeRow(tach, F_TACH_MAX_HZ); - g_tach_en_sw = makeSwitchRow(tach, "Output enabled", onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH); + // ---- Simulation ---- + lv_obj_t *sim = g_tab_page[TAB_SIM]; + lv_obj_set_style_pad_row(sim, 14, 0); + lv_obj_t *intro = label(sim, + "Forces fixed values on the gauge outputs so the needles can be calibrated " + "against the cluster. Switch off when done.", + &lv_font_montserrat_20, UI_COL_MUTED); + lv_label_set_long_mode(intro, LV_LABEL_LONG_WRAP); + lv_obj_set_width(intro, LV_PCT(100)); + g_ovr_rpm_sl = makeSimCard(sim, "Force tachometer", RPM_MAX, &g_ovr_rpm_sw, &g_ovr_rpm_lbl); + g_ovr_duty_sl = makeSimCard(sim, "Force coolant gauge", DUTY_MAX, &g_ovr_duty_sw, &g_ovr_duty_lbl); - lv_obj_t *alerts = makePanel(c1, "ALERT THRESHOLDS", W); - makeRow(alerts, F_COOLANT_HOT); - makeRow(alerts, F_GEARBOX_HOT); - makeRow(alerts, F_BATT_LOW); - - // ---- column 2: coolant gauge ---- - lv_obj_t *temp = makePanel(cols, "COOLANT GAUGE(IO8)", W); - makeRow(temp, F_TEMP_HZ); - makeRow(temp, F_TEMP_SLOPE); - makeRow(temp, F_TEMP_OFFSET); - makeRow(temp, F_TEMP_MIN); - makeRow(temp, F_TEMP_DUTY_MAX); - g_temp_en_sw = makeSwitchRow(temp, "Output enabled", onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP); - - // lv_obj_t* note = lv_label_create(temp); - // lv_label_set_text(note, "duty = slope x T + offset\n(defaults: 1.5 x T + 50, from the\nCANNY program)"); - // lv_obj_set_style_text_font(note, &lv_font_montserrat_14, 0); - // lv_obj_set_style_text_color(note, COL_MUTED, 0); - - // ---- column 3: calibration override ---- - lv_obj_t *ovr = makePanel(cols, "SIMULATION", 300); - g_ovr_rpm_sw = makeSwitchRow(ovr, "Force tach rpm", onOverrideSwitch, NULL); - g_ovr_rpm_sl = makeSliderRow(ovr, "RPM", 6000, &g_ovr_rpm_lbl); - g_ovr_duty_sw = makeSwitchRow(ovr, "Force coolant duty", onOverrideSwitch, NULL); - g_ovr_duty_sl = makeSliderRow(ovr, "Duty", 255, &g_ovr_duty_lbl); - - // lv_obj_t* howto = lv_label_create(ovr); - // lv_label_set_text(howto, - // "Tach: force 1000 rpm, fix Pulses/rev until\n" - // "the needle reads 1000; force 3000, fix Trim.\n" - // "Temp: force a duty, note the needle, repeat;\n" - // "derive Slope/Offset from two marks.\n" - // "Switch overrides OFF when done."); - // lv_obj_set_style_text_font(howto, &lv_font_montserrat_14, 0); - // lv_obj_set_style_text_color(howto, COL_MUTED, 0); - - // lv_obj_t *hint = lv_label_create(g_screen); - // lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: back to Driveline"); - // lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0); - // lv_obj_set_style_text_color(hint, COL_MUTED, 0); - // lv_obj_align(hint, LV_ALIGN_BOTTOM_RIGHT, -24, -10); - - g_status_lbl = lv_label_create(g_screen); - lv_label_set_text(g_status_lbl, "config v-"); - lv_obj_set_style_text_font(g_status_lbl, &lv_font_montserrat_14, 0); - lv_obj_set_style_text_color(g_status_lbl, COL_MUTED, 0); - lv_obj_align(g_status_lbl, LV_ALIGN_BOTTOM_RIGHT, -24, -10); + g_save_lbl = label(g_screen, "", &lv_font_montserrat_20, UI_COL_MUTED); + lv_obj_align(g_save_lbl, LV_ALIGN_BOTTOM_LEFT, 24, -8); + selectTab(TAB_TACH); ESP_LOGI("Tuning", "Gauge tuning screen built"); } @@ -585,7 +566,7 @@ namespace TuningScreen { build(); refreshFromTunables(); - lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600 + lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600 } void tick() @@ -596,10 +577,11 @@ namespace TuningScreen if (millis() - last < 500) return; last = millis(); - if (Tunables::version() == g_shown_version) - return; // nothing changed elsewhere lvgl_port_lock(-1); - refreshFromTunables(); + if (Tunables::version() != g_shown_version) + refreshFromTunables(); // changed from the console + else + refreshSaveState(); // "Saving..." -> "saved" after the deferred write lvgl_port_unlock(); } diff --git a/src/modules/tuning_screen.h b/src/modules/tuning_screen.h index 4f6ac76..d1149ca 100644 --- a/src/modules/tuning_screen.h +++ b/src/modules/tuning_screen.h @@ -6,9 +6,10 @@ * bench override (force an rpm / a duty) so the needles can be calibrated * from the touchscreen while watching the cluster. * - * Lives in src/ (never touched by SquareLine exports), like DrivelineScreen. - * Reached by swiping RIGHT on the Driveline screen; the Driveline button (top - * right) goes back. No swipe gesture on this screen (it would fight the sliders). + * Four tabs: Tachometer / Coolant gauge / Alerts / Simulation. + * Reached by swiping RIGHT on the Driveline screen; swipe left or the Driveline + * button (top right) goes back. The Simulation sliders don't bubble gestures, + * so dragging them never changes screens. * Every change goes through Tunables, so it is saved to NVS (overrides * excepted) and pushed to Controller B in the next CONFIG frame. */ diff --git a/src/modules/uart_manager.cpp b/src/modules/uart_manager.cpp index 9414eeb..1953a7b 100644 --- a/src/modules/uart_manager.cpp +++ b/src/modules/uart_manager.cpp @@ -323,15 +323,8 @@ void linkToCANState(bool can_active) { // EVENT HANDLERS // ============================================================================ -void onUARTToggle(lv_event_t *e) +void setEnabled(bool state) { - lv_obj_t *target = lv_event_get_target(e); - if (target == NULL) { - ESP_LOGE("UARTMgr", "ERROR: UART toggle target is NULL!"); - return; - } - - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); ESP_LOGI("UARTMgr", "===== UART Toggle Event ====="); ESP_LOGI("UARTMgr", "UART Toggle State: %s", state ? "ON" : "OFF"); diff --git a/src/modules/uart_manager.h b/src/modules/uart_manager.h index 8d1d99a..98c908c 100644 --- a/src/modules/uart_manager.h +++ b/src/modules/uart_manager.h @@ -116,15 +116,10 @@ void setDebugEnabled(bool enabled); */ void linkToCANState(bool can_active); -// ============================================================================ -// EVENT HANDLERS (Called from SquareLine Studio UI) -// ============================================================================ - /** - * @brief UART toggle event handler - * @param e LVGL event object - * @note This function is registered in SquareLine Studio UI + * @brief Settings-screen switch: start/stop sending to Controller B (UART1 + + * ESP-NOW) and remember the choice in NVS. */ -void onUARTToggle(lv_event_t *e); +void setEnabled(bool enabled); } // namespace UARTManager diff --git a/src/modules/ui_kit.cpp b/src/modules/ui_kit.cpp new file mode 100644 index 0000000..2e8f94d --- /dev/null +++ b/src/modules/ui_kit.cpp @@ -0,0 +1,177 @@ +/* + * UI kit implementation - see ui_kit.h + */ + +#include "ui_kit.h" + +namespace UiKit { + +lv_obj_t* screen() { + lv_obj_t* s = lv_obj_create(NULL); + lv_obj_set_style_bg_color(s, UI_COL_BG, 0); + lv_obj_set_style_bg_opa(s, LV_OPA_COVER, 0); + lv_obj_clear_flag(s, LV_OBJ_FLAG_SCROLLABLE); + return s; +} + +void header(lv_obj_t* scr, const char* title, lv_event_cb_t back_cb) { + lv_obj_t* t = label(scr, title, &lv_font_montserrat_30, UI_COL_TEXT); + lv_obj_align(t, LV_ALIGN_TOP_LEFT, 24, 18); + + lv_obj_t* back = button(scr, LV_SYMBOL_LEFT " Driveline", 200, 56, BTN_SECONDARY, back_cb, NULL); + lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -16, 10); +} + +lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color) { + lv_obj_t* l = lv_label_create(parent); + lv_label_set_text(l, text); + lv_obj_set_style_text_font(l, font, 0); + lv_obj_set_style_text_color(l, color, 0); + return l; +} + +static void styleButton(lv_obj_t* b, btn_style_t style) { + lv_color_t bg = UI_COL_PANEL2, fg = UI_COL_TEXT; + switch (style) { + case BTN_PRIMARY: bg = UI_COL_ACCENT; fg = lv_color_hex(0x0B1620); break; + case BTN_SECONDARY: bg = UI_COL_PANEL2; fg = UI_COL_TEXT; break; + case BTN_DANGER: bg = UI_COL_WARN; fg = UI_COL_TEXT; break; + case BTN_SUCCESS: bg = UI_COL_OK; fg = lv_color_hex(0x0B1620); break; + } + lv_obj_set_style_bg_color(b, bg, 0); + lv_obj_set_style_bg_opa(b, LV_OPA_COVER, 0); + lv_obj_set_style_text_color(b, fg, 0); + lv_obj_set_style_radius(b, 10, 0); + lv_obj_set_style_shadow_width(b, 0, 0); + lv_obj_set_style_bg_color(b, lv_color_hex(0x3A4450), LV_STATE_DISABLED); + lv_obj_set_style_text_color(b, UI_COL_MUTED, LV_STATE_DISABLED); +} + +lv_obj_t* button(lv_obj_t* parent, const char* text, lv_coord_t w, lv_coord_t h, + btn_style_t style, lv_event_cb_t cb, void* user) { + lv_obj_t* b = lv_btn_create(parent); + lv_obj_set_size(b, w, h); + styleButton(b, style); + if (cb) lv_obj_add_event_cb(b, cb, LV_EVENT_CLICKED, user); + lv_obj_t* l = lv_label_create(b); + lv_label_set_text(l, text); + lv_obj_set_style_text_font(l, &lv_font_montserrat_20, 0); + lv_obj_center(l); + return b; +} + +void setButtonText(lv_obj_t* btn, const char* text) { + setText(lv_obj_get_child(btn, 0), text); +} + +lv_obj_t* toggle(lv_obj_t* parent, lv_event_cb_t cb, void* user) { + lv_obj_t* sw = lv_switch_create(parent); + lv_obj_set_size(sw, 92, 48); + lv_obj_set_style_bg_color(sw, UI_COL_PANEL2, 0); + lv_obj_set_style_bg_color(sw, UI_COL_ACCENT, (lv_style_selector_t)LV_PART_INDICATOR | (lv_style_selector_t)LV_STATE_CHECKED); + lv_obj_set_style_anim_time(sw, 0, 0); // no knob slide animation: one redraw per flip + if (cb) lv_obj_add_event_cb(sw, cb, LV_EVENT_VALUE_CHANGED, user); + return sw; +} + +void setChecked(lv_obj_t* obj, bool on) { + if (obj == NULL || lv_obj_has_state(obj, LV_STATE_CHECKED) == on) return; + if (on) lv_obj_add_state(obj, LV_STATE_CHECKED); + else lv_obj_clear_state(obj, LV_STATE_CHECKED); +} + +lv_obj_t* box(lv_obj_t* parent, lv_flex_flow_t flow) { + lv_obj_t* b = lv_obj_create(parent); + lv_obj_remove_style_all(b); + lv_obj_set_flex_flow(b, flow); + lv_obj_clear_flag(b, LV_OBJ_FLAG_SCROLLABLE); + return b; +} + +lv_obj_t* card(lv_obj_t* parent) { + lv_obj_t* c = lv_obj_create(parent); + lv_obj_set_style_bg_color(c, UI_COL_PANEL, 0); + lv_obj_set_style_border_width(c, 0, 0); + lv_obj_set_style_radius(c, 12, 0); + lv_obj_set_style_pad_all(c, 16, 0); + lv_obj_set_style_shadow_width(c, 0, 0); + lv_obj_clear_flag(c, LV_OBJ_FLAG_SCROLLABLE); + return c; +} + +void setText(lv_obj_t* lbl, const char* text) { + if (lbl == NULL) return; + const char* cur = lv_label_get_text(lbl); + if (cur && strcmp(cur, text) == 0) return; + lv_label_set_text(lbl, text); +} + +void setTextColor(lv_obj_t* lbl, lv_color_t c) { + if (lbl == NULL) return; + if (lv_obj_get_style_text_color(lbl, LV_PART_MAIN).full == c.full) return; + lv_obj_set_style_text_color(lbl, c, 0); +} + +void setVisible(lv_obj_t* obj, bool visible) { + if (obj == NULL || lv_obj_has_flag(obj, LV_OBJ_FLAG_HIDDEN) == !visible) return; + if (visible) lv_obj_clear_flag(obj, LV_OBJ_FLAG_HIDDEN); + else lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN); +} + +// ---- confirm dialog -------------------------------------------------------- + +static const char* g_btn_map[3] = {"Cancel", "OK", ""}; +static char g_ok_text[32]; +static void (*g_confirm_cb)(bool, void*) = NULL; +static void* g_confirm_user = NULL; + +static void onConfirm(lv_event_t* e) { + lv_obj_t* mb = lv_event_get_current_target(e); + uint16_t id = lv_msgbox_get_active_btn(mb); + if (id == LV_BTNMATRIX_BTN_NONE) return; + lv_msgbox_close_async(mb); + void (*cb)(bool, void*) = g_confirm_cb; + g_confirm_cb = NULL; + if (cb) cb(id == 1, g_confirm_user); +} + +void confirm(const char* title, const char* text, const char* ok_text, + void (*cb)(bool ok, void* user), void* user) { + snprintf(g_ok_text, sizeof(g_ok_text), "%s", ok_text); + g_btn_map[1] = g_ok_text; + g_confirm_cb = cb; + g_confirm_user = user; + + lv_obj_t* mb = lv_msgbox_create(NULL, title, text, g_btn_map, false); + lv_obj_set_width(mb, 640); + lv_obj_set_style_bg_color(mb, UI_COL_PANEL, 0); + lv_obj_set_style_border_width(mb, 0, 0); + lv_obj_set_style_shadow_width(mb, 0, 0); + lv_obj_set_style_radius(mb, 14, 0); + lv_obj_set_style_pad_all(mb, 24, 0); + lv_obj_set_style_pad_row(mb, 16, 0); + lv_obj_set_style_text_color(mb, UI_COL_TEXT, 0); + lv_obj_set_style_text_font(lv_msgbox_get_title(mb), &lv_font_montserrat_24, 0); + lv_obj_set_style_text_font(lv_msgbox_get_text(mb), &lv_font_montserrat_20, 0); + + lv_obj_t* btns = lv_msgbox_get_btns(mb); + lv_obj_set_size(btns, LV_PCT(100), 64); + lv_obj_set_style_text_font(btns, &lv_font_montserrat_20, 0); + lv_obj_set_style_pad_column(btns, 16, 0); + lv_obj_set_style_bg_color(btns, UI_COL_PANEL2, LV_PART_ITEMS); + lv_obj_set_style_text_color(btns, UI_COL_TEXT, LV_PART_ITEMS); + lv_obj_set_style_radius(btns, 10, LV_PART_ITEMS); + lv_obj_set_style_shadow_width(btns, 0, LV_PART_ITEMS); + lv_btnmatrix_set_btn_ctrl(btns, 1, LV_BTNMATRIX_CTRL_CHECKED); // highlight the action + lv_obj_set_style_bg_color(btns, UI_COL_ACCENT, (lv_style_selector_t)LV_PART_ITEMS | (lv_style_selector_t)LV_STATE_CHECKED); + lv_obj_set_style_text_color(btns, lv_color_hex(0x0B1620), (lv_style_selector_t)LV_PART_ITEMS | (lv_style_selector_t)LV_STATE_CHECKED); + + lv_obj_t* backdrop = lv_obj_get_parent(mb); + lv_obj_set_style_bg_color(backdrop, lv_color_black(), 0); + lv_obj_set_style_bg_opa(backdrop, LV_OPA_70, 0); + + lv_obj_center(mb); + lv_obj_add_event_cb(mb, onConfirm, LV_EVENT_VALUE_CHANGED, NULL); +} + +} // namespace UiKit diff --git a/src/modules/ui_kit.h b/src/modules/ui_kit.h new file mode 100644 index 0000000..cbc0aa8 --- /dev/null +++ b/src/modules/ui_kit.h @@ -0,0 +1,59 @@ +/* + * UI kit - shared look for the hand-coded screens (Settings, Gauge Tuning). + * + * Car-sized touch targets (>= 56 px), 20/24 px body text, no shadows or + * animated transitions (every extra redraw of this 1024x600 PSRAM framebuffer + * costs frame time). All functions need the LVGL lock, like any LVGL call. + */ + +#pragma once + +#include +#include + +#define UI_COL_BG lv_color_hex(0x101418) +#define UI_COL_PANEL lv_color_hex(0x1B2128) +#define UI_COL_PANEL2 lv_color_hex(0x252D36) // pressed / selected rows +#define UI_COL_TEXT lv_color_hex(0xE8EDF2) +#define UI_COL_MUTED lv_color_hex(0x8894A0) +#define UI_COL_ACCENT lv_color_hex(0x3DA9FC) +#define UI_COL_OK lv_color_hex(0x3DD68C) +#define UI_COL_WARN lv_color_hex(0xE5484D) +#define UI_COL_AMBER lv_color_hex(0xF5A524) + +namespace UiKit { + +typedef enum { BTN_PRIMARY, BTN_SECONDARY, BTN_DANGER, BTN_SUCCESS } btn_style_t; + +/** Plain full-screen background object. */ +lv_obj_t* screen(); + +/** Title top-left and a "< Driveline" button top-right that calls back_cb. */ +void header(lv_obj_t* scr, const char* title, lv_event_cb_t back_cb); + +lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color); + +/** Button with a centred label; the label is the button's first child. */ +lv_obj_t* button(lv_obj_t* parent, const char* text, lv_coord_t w, lv_coord_t h, + btn_style_t style, lv_event_cb_t cb, void* user); +void setButtonText(lv_obj_t* btn, const char* text); + +lv_obj_t* toggle(lv_obj_t* parent, lv_event_cb_t cb, void* user); +void setChecked(lv_obj_t* obj, bool on); + +/** Transparent flex row/column container without padding or scrolling. */ +lv_obj_t* box(lv_obj_t* parent, lv_flex_flow_t flow); + +/** Rounded panel (card). */ +lv_obj_t* card(lv_obj_t* parent); + +/** lv_label_set_text only when the text changed - avoids needless redraws. */ +void setText(lv_obj_t* lbl, const char* text); +void setTextColor(lv_obj_t* lbl, lv_color_t c); +void setVisible(lv_obj_t* obj, bool visible); + +/** Modal Cancel / OK dialog; cb(true, user) on OK, cb(false, user) on Cancel. */ +void confirm(const char* title, const char* text, const char* ok_text, + void (*cb)(bool ok, void* user), void* user); + +} // namespace UiKit diff --git a/src/modules/ui_state_manager.cpp b/src/modules/ui_state_manager.cpp index a7d23dd..fb9ff4a 100644 --- a/src/modules/ui_state_manager.cpp +++ b/src/modules/ui_state_manager.cpp @@ -4,19 +4,7 @@ #include "ui_state_manager.h" #include "display/lvgl_v8_port.h" -#include "settings_manager.h" -#include "wifi_manager.h" #include "uart_manager.h" -#include "drivers/can_driver.h" - -// External UI element references (from ui_Settings_Screen.c) -extern "C" { - extern lv_obj_t *uic_Main_Container; - extern lv_obj_t *uic_Toggle_Wifi_Switch; - extern lv_obj_t *uic_Toggle_UART_Switch; - extern lv_obj_t *uic_Toggle_CAN_Bus_Switch; - extern lv_obj_t *uic_Toggle_Debug_Switch; -} namespace UIStateManager { @@ -24,9 +12,6 @@ namespace UIStateManager { // PRIVATE MODULE STATE // ============================================================================ -// Track which screen instance we synced (to prevent redundant syncing) -static lv_obj_t* g_last_synced_screen = NULL; - // Debug mode state static bool g_debug_enabled = false; @@ -36,90 +21,9 @@ static bool g_debug_enabled = false; void init() { Serial.println("[UIStateManager] Initialized"); - g_last_synced_screen = NULL; g_debug_enabled = false; } -void applySavedStatesToUI() { - // Wait for UI widgets to be created - if (uic_Toggle_Wifi_Switch == NULL || uic_Toggle_UART_Switch == NULL || uic_Toggle_CAN_Bus_Switch == NULL) { - // Reset last synced screen when widgets are NULL (screen unloaded) - g_last_synced_screen = NULL; - return; // Settings screen not loaded yet - } - - if (uic_Main_Container == NULL) { - return; // UI not ready - } - - // Get the Settings screen pointer (parent of Main Container) - lv_obj_t* settings_screen = lv_obj_get_parent(uic_Main_Container); - if (settings_screen == NULL) { - return; - } - - // Check if we've already synced this screen instance - if (g_last_synced_screen == settings_screen) { - return; // Already synced this instance - } - - Serial.println("Settings screen detected - syncing toggle states with services..."); - - // Sync UI with the actual running state of services - bool current_wifi_state = WiFiManager::getState() != WiFiManager::WIFI_STATE_OFF; - bool current_uart_state = UARTManager::getState() != UARTManager::UART_STATE_OFF; - bool current_can_state = CANDriver::isActive(); - bool current_debug_state = g_debug_enabled; - - lvgl_port_lock(-1); - - // The SquareLine project ships the WiFi switch with LV_STATE_DISABLED (since - // the first export), which swallows every touch. Wi-Fi is needed to join a - // network for OTA updates, so re-enable it here - survives re-exports. - lv_obj_clear_state(uic_Toggle_Wifi_Switch, LV_STATE_DISABLED); - - // Apply WiFi state - if (current_wifi_state) { - lv_obj_add_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED); - } else { - lv_obj_clear_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED); - } - - // Apply UART state - if (current_uart_state) { - lv_obj_add_state(uic_Toggle_UART_Switch, LV_STATE_CHECKED); - } else { - lv_obj_clear_state(uic_Toggle_UART_Switch, LV_STATE_CHECKED); - } - - // Apply CAN Bus state - if (current_can_state) { - lv_obj_add_state(uic_Toggle_CAN_Bus_Switch, LV_STATE_CHECKED); - } else { - lv_obj_clear_state(uic_Toggle_CAN_Bus_Switch, LV_STATE_CHECKED); - } - - // Apply Debug state - if (uic_Toggle_Debug_Switch != NULL) { - if (current_debug_state) { - lv_obj_add_state(uic_Toggle_Debug_Switch, LV_STATE_CHECKED); - } else { - lv_obj_clear_state(uic_Toggle_Debug_Switch, LV_STATE_CHECKED); - } - } - - lvgl_port_unlock(); - - // Mark this screen instance as synced - g_last_synced_screen = settings_screen; - - Serial.printf("Toggle states synced: WiFi=%s, UART=%s, CAN=%s, Debug=%s\n", - current_wifi_state ? "ON" : "OFF", - current_uart_state ? "ON" : "OFF", - current_can_state ? "ON" : "OFF", - current_debug_state ? "ON" : "OFF"); -} - void setDebugEnabled(bool enabled) { g_debug_enabled = enabled; @@ -154,31 +58,4 @@ bool isDebugEnabled() { return g_debug_enabled; } -// ============================================================================ -// EVENT HANDLERS -// ============================================================================ - -void onDebugToggle(lv_event_t *e) -{ - lv_obj_t *target = lv_event_get_target(e); - - if (target == NULL) { - Serial.println("ERROR: Debug toggle target is NULL!"); - return; - } - - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); - - Serial.printf("===== Debug Toggle Event =====\n"); - Serial.printf("Debug Mode: %s\n", state ? "ON" : "OFF"); - - // Save state to NVS - SettingsManager::saveDebugState(state); - - // Update global state and enable/disable monitors - setDebugEnabled(state); - - Serial.printf("==============================\n"); -} - } // namespace UIStateManager diff --git a/src/modules/ui_state_manager.h b/src/modules/ui_state_manager.h index 4f32dcf..8c64325 100644 --- a/src/modules/ui_state_manager.h +++ b/src/modules/ui_state_manager.h @@ -1,9 +1,9 @@ /* * UI State Manager Module * - * Handles UI state synchronization: - * - Syncs toggle switches with actual service states when screens change - * - Handles SquareLine Studio screen lifecycle (destroy/recreate) + * Holds the debug flag (sent to Controller B, shows LVGL's performance overlay). + * The screen-sync logic for the SquareLine Settings screen went with that + * screen (2026-09-27): the hand-coded Settings screen reads live state itself. */ #pragma once @@ -25,18 +25,6 @@ namespace UIStateManager { */ void init(); -/** - * @brief Apply saved states to UI switches - * - * This function is called continuously in loop() to sync UI toggle switches - * with the actual running state of services when the Settings screen loads. - * It handles the SquareLine Studio screen lifecycle where screens get - * destroyed/recreated when swiping between screens. - * - * @note This function is thread-safe and uses LVGL locks internally - */ -void applySavedStatesToUI(); - /** * @brief Enable or disable debug mode (LVGL performance and memory monitors) * @param enabled True to enable debug monitors, false to disable @@ -49,15 +37,4 @@ void setDebugEnabled(bool enabled); */ bool isDebugEnabled(); -// ============================================================================ -// EVENT HANDLERS (Called from SquareLine Studio UI) -// ============================================================================ - -/** - * @brief Debug toggle event handler - * @param e LVGL event object - * @note This function is registered in SquareLine Studio UI - */ -void onDebugToggle(lv_event_t *e); - } // namespace UIStateManager diff --git a/src/modules/wifi_manager.cpp b/src/modules/wifi_manager.cpp index 10919f9..35b3f25 100644 --- a/src/modules/wifi_manager.cpp +++ b/src/modules/wifi_manager.cpp @@ -1,21 +1,19 @@ /* - * WiFi Manager Module Implementation + * WiFi Manager Module Implementation - see wifi_manager.h for the radio rules. */ #include "wifi_manager.h" #include "espnow_link.h" -#include "display/lvgl_v8_port.h" - -// External UI element references (from ui_Settings_Screen.c) -// MUST be declared outside the namespace to match the global C symbols -extern "C" { - extern lv_obj_t *uic_Select_SSID_BTN; - extern lv_obj_t *uic_Settings_Loading_Container; - extern lv_obj_t *uic_Wifi_Container; - extern lv_obj_t *uic_Toggle_Wifi_Switch; - extern lv_obj_t *uic_Wifi_Passkey_TB; - extern lv_obj_t *uic_Keyboard; -} +#include "settings_manager.h" +#include "serial_lock.h" +#include "protocol/automotive_data.h" // ESPNOW_CHANNEL +#include +#include +#include +#include +#include +#include +#include namespace WiFiManager { @@ -23,772 +21,487 @@ namespace WiFiManager { // PRIVATE MODULE STATE // ============================================================================ -// Global WiFi state variables -static wifi_state_t g_wifi_state = WIFI_STATE_OFF; -static TaskHandle_t g_wifi_task_handle = NULL; -static QueueHandle_t g_wifi_event_queue = NULL; -static SemaphoreHandle_t g_wifi_mutex = NULL; -static wifi_network_t g_scanned_networks[WIFI_SCAN_MAX_NETWORKS]; -static uint8_t g_network_count = 0; -static bool g_wifi_scan_requested = false; -static unsigned long g_last_scan_time = 0; +typedef enum { CMD_ENABLE, CMD_DISABLE, CMD_SCAN, CMD_CONNECT, CMD_CONNECT_SAVED, CMD_FORGET } cmd_type_t; -// Currently selected network for connection -static int8_t g_selected_network_index = -1; +typedef struct { + cmd_type_t type; + char ssid[33]; + char pass[65]; +} cmd_t; -// Dynamic SSID buttons -static lv_obj_t* g_ssid_buttons[WIFI_SCAN_MAX_NETWORKS] = {NULL}; -static uint8_t g_button_count = 0; +static const char* NVS_NAMESPACE = "wifi"; + +static QueueHandle_t g_queue = NULL; +static SemaphoreHandle_t g_mutex = NULL; + +// Guarded by g_mutex +static status_t g_status = {}; +static network_t g_networks[WIFI_SCAN_MAX_NETWORKS]; +static uint8_t g_network_count = 0; + +// Owned by the Wi-Fi task (and init) +static bool g_enabled = false; +static char g_saved_pass[65] = {0}; + +static volatile uint8_t g_disc_reason = 0; // last STA_DISCONNECTED reason (event task) + +static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); } +static void unlock() { xSemaphoreGive(g_mutex); } + +static void print(const char* fmt, ...) { + char buf[160]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + SerialLock::lock(); + Serial.println(buf); + SerialLock::unlock(); +} + +static void copyStr(char* dst, const char* src, size_t n) { + strncpy(dst, src ? src : "", n - 1); + dst[n - 1] = 0; +} + +static void setLink(link_t link, const char* ssid, const char* error = "") { + lock(); + g_status.link = link; + if (ssid) copyStr(g_status.ssid, ssid, sizeof(g_status.ssid)); + copyStr(g_status.error, error, sizeof(g_status.error)); + unlock(); +} + +static link_t currentLink() { + lock(); + link_t l = g_status.link; + unlock(); + return l; +} // ============================================================================ -// PRIVATE HELPER FUNCTIONS +// SAVED NETWORK (NVS) // ============================================================================ -/** - * @brief Get WiFi encryption type as string - */ -static const char* getAuthModeString(wifi_auth_mode_t authmode) { - switch (authmode) { - case WIFI_AUTH_OPEN: return "Open"; - case WIFI_AUTH_WEP: return "WEP"; - case WIFI_AUTH_WPA_PSK: return "WPA"; - case WIFI_AUTH_WPA2_PSK: return "WPA2"; - case WIFI_AUTH_WPA_WPA2_PSK: return "WPA/WPA2"; - case WIFI_AUTH_WPA2_ENTERPRISE: return "WPA2-Ent"; - case WIFI_AUTH_WPA3_PSK: return "WPA3"; - default: return "Unknown"; +static void loadSaved() { + Preferences p; + p.begin(NVS_NAMESPACE, true); + String ssid = p.getString("ssid", ""); + String pass = p.getString("pass", ""); + p.end(); + lock(); + copyStr(g_status.saved_ssid, ssid.c_str(), sizeof(g_status.saved_ssid)); + unlock(); + copyStr(g_saved_pass, pass.c_str(), sizeof(g_saved_pass)); +} + +static void storeSaved(const char* ssid, const char* pass) { + Preferences p; + p.begin(NVS_NAMESPACE, false); + p.putString("ssid", ssid); + p.putString("pass", pass ? pass : ""); + p.end(); + lock(); + copyStr(g_status.saved_ssid, ssid, sizeof(g_status.saved_ssid)); + unlock(); + copyStr(g_saved_pass, pass, sizeof(g_saved_pass)); +} + +static void clearSaved() { + Preferences p; + p.begin(NVS_NAMESPACE, false); + p.clear(); + p.end(); + lock(); + g_status.saved_ssid[0] = 0; + unlock(); + memset(g_saved_pass, 0, sizeof(g_saved_pass)); +} + +// ============================================================================ +// RADIO +// ============================================================================ + +static void onDisconnected(arduino_event_id_t event, arduino_event_info_t info) { + (void)event; + g_disc_reason = info.wifi_sta_disconnected.reason; +} + +/** Leave any AP and park the radio back on the ESP-NOW channel B expects. */ +static void dropToEspNowChannel() { + WiFi.disconnect(); // NOT (true): that powers the radio off and kills ESP-NOW + delay(50); + esp_wifi_set_channel(ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE); +} + +static const char* reasonText(uint8_t r) { + switch (r) { + case WIFI_REASON_AUTH_EXPIRE: + case WIFI_REASON_AUTH_FAIL: + case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: + case WIFI_REASON_HANDSHAKE_TIMEOUT: + case WIFI_REASON_MIC_FAILURE: + return "Wrong password"; + case WIFI_REASON_NO_AP_FOUND: + return "Network not in range"; + case 210: // NO_AP_FOUND_W_COMPATIBLE_SECURITY + case 211: // NO_AP_FOUND_IN_AUTHMODE_THRESHOLD + return "Security type not supported"; + case 212: // NO_AP_FOUND_IN_RSSI_THRESHOLD + return "Signal too weak"; + case WIFI_REASON_ASSOC_FAIL: + return "Network refused the connection"; + default: + return NULL; } } -/** - * @brief Get signal strength indicator - */ -static const char* getSignalStrength(int32_t rssi) { - if (rssi > -50) return "[****]"; // Excellent - else if (rssi > -60) return "[*** ]"; // Good - else if (rssi > -70) return "[** ]"; // Fair - else if (rssi > -80) return "[* ]"; // Weak - else return "[ ]"; // Very weak +static void waitForScanToFinish() { + uint32_t t0 = millis(); + while (WiFi.scanComplete() == WIFI_SCAN_RUNNING && millis() - t0 < 8000) vTaskDelay(pdMS_TO_TICKS(100)); + WiFi.scanDelete(); + lock(); + g_status.scanning = false; + unlock(); } -/** - * @brief Format network name for display in button - */ -static String formatNetworkName(const wifi_network_t& network) { - String formatted = getSignalStrength(network.rssi); - formatted += " "; - formatted += network.ssid; - if (network.ssid.length() == 0) { - formatted += "[Hidden]"; - } - if (network.auth != WIFI_AUTH_OPEN) { - formatted += " [Secured]"; // Text indicator for secured networks - } - return formatted; -} +/** One join attempt, blocking the Wi-Fi task for up to WIFI_CONNECT_TIMEOUT_MS. */ +static bool doConnect(const char* ssid, const char* pass, bool remember, const char* fail_prefix = NULL) { + setLink(LINK_CONNECTING, ssid); + print("[wifi] joining '%s'...", ssid); + waitForScanToFinish(); -/** - * @brief Show connection result to user - * @note Must be called with LVGL lock held OR will acquire lock internally - */ -static void showConnectionResult(bool success, const char* message) { - // 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); + WiFi.disconnect(); + delay(150); // let the leave event land before we watch for failures + g_disc_reason = 0; + WiFi.begin(ssid, (pass && *pass) ? pass : NULL); - // Hide loading spinner - if (uic_Settings_Loading_Container != NULL) { - lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); + uint32_t t0 = millis(), reason_ms = 0; + while (millis() - t0 < WIFI_CONNECT_TIMEOUT_MS) { + if (WiFi.status() == WL_CONNECTED) break; + if (g_disc_reason != 0 && g_disc_reason != WIFI_REASON_ASSOC_LEAVE && reason_ms == 0) reason_ms = millis(); + if (reason_ms && millis() - reason_ms > 1500) break; // one attempt only: autoreconnect is off + vTaskDelay(pdMS_TO_TICKS(200)); } - if (success) { - // Connection successful - Serial.printf("WiFi connected: %s\n", message); - - // Update the roller to show connected status - if (g_selected_network_index >= 0 && g_selected_network_index < g_network_count) { - String connected_text = "[CONNECTED] "; - connected_text += g_scanned_networks[g_selected_network_index].ssid; - - // Update just the selected item in the roller - // Note: This is a simplified approach - in production, you'd want to - // rebuild the entire roller list with the connected indicator - } - - // Optionally show a success message label temporarily - // You could create a temporary label here if needed - - } else { - // Connection failed - show error and return to SSID buttons - Serial.printf("WiFi connection failed: %s\n", message); - - // Show SSID buttons again - for (uint8_t i = 0; i < g_button_count; i++) { - if (g_ssid_buttons[i] != NULL) { - lv_obj_clear_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN); + if (WiFi.status() == WL_CONNECTED) { + setLink(LINK_CONNECTED, ssid); + print("[wifi] connected to '%s', IP %s, %d dBm, channel %d", ssid, + WiFi.localIP().toString().c_str(), (int)WiFi.RSSI(), (int)WiFi.channel()); + if (remember) { + bool same; + lock(); + same = strcmp(g_status.saved_ssid, ssid) == 0; + unlock(); + if (!same || strcmp(g_saved_pass, pass ? pass : "") != 0) { + storeSaved(ssid, pass); + print("[wifi] '%s' remembered - joins automatically at boot", ssid); } } - - // Optionally show an error message label temporarily - // You could create a temporary label here to show the error + return true; } - // Reset selected network index - g_selected_network_index = -1; - - lvgl_port_unlock(); + uint8_t r = g_disc_reason; + const char* why = reasonText(r); + char err[48]; + if (why) snprintf(err, sizeof(err), "%s%s", fail_prefix ? fail_prefix : "", why); + else if (r) snprintf(err, sizeof(err), "%sCouldn't connect (code %u)", fail_prefix ? fail_prefix : "", r); + else snprintf(err, sizeof(err), "%sNo answer from the network", fail_prefix ? fail_prefix : ""); + dropToEspNowChannel(); + setLink(LINK_FAILED, ssid, err); + print("[wifi] '%s' failed: %s", ssid, err); + return false; } -/** - * @brief Reset WiFi UI to initial state (showing SSID list) - */ -static void resetWiFiUI() { - lvgl_port_lock(0); - - // Hide all password entry elements - lv_obj_add_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - - // Clear password field for security - lv_textarea_set_text(uic_Wifi_Passkey_TB, ""); - - // Show SSID buttons - for (uint8_t i = 0; i < g_button_count; i++) { - if (g_ssid_buttons[i] != NULL) { - lv_obj_clear_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN); +static void collectScan(int16_t n) { + network_t tmp[WIFI_SCAN_MAX_NETWORKS]; + uint8_t count = 0; + for (int16_t i = 0; i < n; i++) { + String s = WiFi.SSID(i); + if (s.length() == 0) continue; // hidden + int8_t rssi = (int8_t)WiFi.RSSI(i); + bool secured = WiFi.encryptionType(i) != WIFI_AUTH_OPEN; + int dup = -1; // mesh APs repeat an SSID: keep the strongest + for (uint8_t j = 0; j < count; j++) if (s == tmp[j].ssid) { dup = j; break; } + if (dup >= 0) { + if (rssi > tmp[dup].rssi) tmp[dup].rssi = rssi; + continue; } + if (count >= WIFI_SCAN_MAX_NETWORKS) continue; + copyStr(tmp[count].ssid, s.c_str(), sizeof(tmp[count].ssid)); + tmp[count].rssi = rssi; + tmp[count].secured = secured; + count++; } - - // Reset selected network - g_selected_network_index = -1; - - lvgl_port_unlock(); -} - -/** - * @brief Update WiFi UI state based on state machine - * @note This function MUST be called with lvgl_port_lock held - */ -static void updateWifiUIState(wifi_state_t state) { - // This function MUST be called with lvgl_port_lock held - - if (!uic_Select_SSID_BTN || !uic_Settings_Loading_Container || !uic_Wifi_Container) { - Serial.println("WARNING: UI elements not initialized"); - return; + for (uint8_t i = 1; i < count; i++) { // strongest first + network_t k = tmp[i]; + int j = i - 1; + while (j >= 0 && tmp[j].rssi < k.rssi) { tmp[j + 1] = tmp[j]; j--; } + tmp[j + 1] = k; } + lock(); + memcpy(g_networks, tmp, sizeof(network_t) * count); + g_network_count = count; + g_status.scanning = false; + g_status.scan_gen++; + unlock(); - switch (state) { - case WIFI_STATE_OFF: - // Hide WiFi container and spinner - lv_obj_add_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN); - break; - - case WIFI_STATE_SCANNING: - // Show container and spinner, hide button - lv_obj_clear_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_clear_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN); - break; - - case WIFI_STATE_SCAN_COMPLETE: - // Show button, hide spinner - lv_obj_clear_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_clear_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN); - break; - - case WIFI_STATE_ERROR: - // Show error state (container visible but no spinner or button) - lv_obj_clear_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN); - break; - - default: - break; + print("[wifi] scan: %u networks", count); + for (uint8_t i = 0; i < count; i++) { + print("[wifi] %4d dBm %s%s", tmp[i].rssi, tmp[i].ssid, tmp[i].secured ? "" : " (open)"); } } -/** - * @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; -} +// ============================================================================ +// TASK (Core 0) +// ============================================================================ -static void updateSSIDList() { - // This function MUST be called with lvgl_port_lock held - - if (!uic_Wifi_Container) { - Serial.println("ERROR: uic_Wifi_Container is NULL!"); - return; - } - - // Clean up old buttons - for (uint8_t i = 0; i < g_button_count; i++) { - if (g_ssid_buttons[i] != NULL) { - lv_obj_del(g_ssid_buttons[i]); - g_ssid_buttons[i] = NULL; - } - } - g_button_count = 0; - - if (g_network_count == 0) { - Serial.println("No WiFi networks found"); - return; - } - - Serial.printf("Creating %d SSID buttons:\n", g_network_count); - - // Create a button for each scanned network - for (uint8_t i = 0; i < g_network_count; i++) { - // Create button in the WiFi container - lv_obj_t* btn = lv_btn_create(uic_Wifi_Container); - lv_obj_set_width(btn, 600); // Adjust width as needed - lv_obj_set_height(btn, 60); // Adjust height as needed - - // Create label for the button text - lv_obj_t* label = lv_label_create(btn); - String btnText = formatNetworkName(g_scanned_networks[i]); - lv_label_set_text(label, btnText.c_str()); - lv_obj_center(label); - - // Store network index as user data - lv_obj_set_user_data(btn, (void*)(intptr_t)i); - - // 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; - g_button_count++; - - Serial.printf(" [%d] Created button for: %s\n", i, g_scanned_networks[i].ssid.c_str()); - } - - Serial.printf("Successfully created %d SSID buttons\n", g_button_count); -} - -/** - * @brief Initiate WiFi connection to selected network - */ -static void connectToWiFi(const char* ssid, const char* password) { - if (ssid == NULL) return; - - // Allocate credentials structure - wifi_credentials_t* creds = (wifi_credentials_t*)malloc(sizeof(wifi_credentials_t)); - if (creds == NULL) { - Serial.println("ERROR: Failed to allocate memory for WiFi credentials!"); - showConnectionResult(false, "Memory allocation failed"); - return; - } - - // Copy credentials - strncpy(creds->ssid, ssid, sizeof(creds->ssid) - 1); - creds->ssid[sizeof(creds->ssid) - 1] = '\0'; - - if (password != NULL) { - strncpy(creds->password, password, sizeof(creds->password) - 1); - creds->password[sizeof(creds->password) - 1] = '\0'; - } else { - creds->password[0] = '\0'; // Empty password for open networks - } - - // Send connect event to WiFi task - wifi_queue_event_t evt; - evt.type = WIFI_UI_EVENT_CONNECT; - evt.data = creds; // WiFi task will free this memory - - if (g_wifi_event_queue != NULL) { - if (xQueueSend(g_wifi_event_queue, &evt, pdMS_TO_TICKS(100)) != pdTRUE) { - Serial.println("ERROR: Failed to send connect event to WiFi task!"); - free(creds); - showConnectionResult(false, "Failed to initiate connection"); - } - } else { - Serial.println("ERROR: WiFi event queue not initialized!"); - free(creds); - showConnectionResult(false, "System not ready"); - } -} - -/** - * @brief WiFi task - Runs on Core 0 - * @param parameter Task parameter (unused) - */ static void wifiTask(void* parameter) { - wifi_queue_event_t event; - bool scanning = false; + (void)parameter; + cmd_t cmd; + uint32_t scan_t0 = 0; + uint32_t lost_since = 0; - Serial.println("WiFi task started on Core 0"); + // Boot: join the remembered network once if Wi-Fi is on - after setup() has + // brought ESP-NOW up, so the two don't configure the radio at the same time. + vTaskDelay(pdMS_TO_TICKS(3000)); + if (g_enabled) { + char ssid[33]; + lock(); + copyStr(ssid, g_status.saved_ssid, sizeof(ssid)); + unlock(); + if (ssid[0]) doConnect(ssid, g_saved_pass, false); + } while (true) { - // Check for events from the queue (non-blocking with timeout) - if (xQueueReceive(g_wifi_event_queue, &event, pdMS_TO_TICKS(100)) == pdTRUE) { - switch (event.type) { - case WIFI_UI_EVENT_TOGGLE_ON: - Serial.println("WiFi Task: Enabling WiFi..."); - WiFi.mode(WIFI_STA); - WiFi.disconnect(); // Clear any previous connection - g_wifi_state = WIFI_STATE_SCANNING; - g_wifi_scan_requested = true; + if (xQueueReceive(g_queue, &cmd, pdMS_TO_TICKS(200)) == pdTRUE) { + switch (cmd.type) { + case CMD_ENABLE: { + g_enabled = true; + SettingsManager::saveWiFiState(true); + char ssid[33]; + lock(); + copyStr(ssid, g_status.saved_ssid, sizeof(ssid)); + unlock(); + if (ssid[0]) doConnect(ssid, g_saved_pass, false); + else setLink(LINK_IDLE, ""); + break; + } + case CMD_DISABLE: + g_enabled = false; + SettingsManager::saveWiFiState(false); + waitForScanToFinish(); + dropToEspNowChannel(); + setLink(LINK_OFF, ""); + print("[wifi] off (radio stays up for ESP-NOW)"); break; - case WIFI_UI_EVENT_TOGGLE_OFF: - Serial.println("WiFi Task: Disabling WiFi..."); - WiFi.disconnect(); // NOT (true): that powers the radio off and kills ESP-NOW - // Radio stays in STA mode: the ESP-NOW link to Controller B - // rides on it. "WiFi off" here means scanning/association off. - g_wifi_state = WIFI_STATE_OFF; - g_network_count = 0; - scanning = false; - break; - - case WIFI_UI_EVENT_SCAN_START: - if (g_wifi_state != WIFI_STATE_OFF && !scanning) { - g_wifi_scan_requested = true; + case CMD_SCAN: + if (g_enabled && WiFi.scanComplete() != WIFI_SCAN_RUNNING) { + lock(); + g_status.scanning = true; + unlock(); + WiFi.scanNetworks(true, false); // async, no hidden networks + scan_t0 = millis(); + } else if (!g_enabled) { + lock(); + g_status.scanning = false; // requestScan() raced a switch-off + unlock(); } break; - case WIFI_UI_EVENT_CONNECT: - if (event.data != NULL) { - wifi_credentials_t* creds = (wifi_credentials_t*)event.data; - Serial.printf("WiFi Task: Connecting to %s...\n", creds->ssid); - - // Stop any ongoing scan - WiFi.scanDelete(); - scanning = false; - - // Update state - g_wifi_state = WIFI_STATE_CONNECTED; // Will be updated based on result - - // Attempt connection - WiFi.disconnect(); // Clear any previous connection (radio stays on: ESP-NOW rides on it) - delay(100); - - if (strlen(creds->password) > 0) { - WiFi.begin(creds->ssid, creds->password); - } else { - WiFi.begin(creds->ssid); // Open network - } - - // Wait for connection (with timeout) - int timeout = 20; // 10 seconds timeout - while (WiFi.status() != WL_CONNECTED && timeout > 0) { - delay(500); - Serial.print("."); - timeout--; - } - Serial.println(); - - // Check connection result - if (WiFi.status() == WL_CONNECTED) { - Serial.printf("Connected! IP: %s\n", WiFi.localIP().toString().c_str()); - showConnectionResult(true, WiFi.localIP().toString().c_str()); - g_wifi_state = WIFI_STATE_CONNECTED; - } else { - Serial.println("Connection failed!"); - const char* error_msg = "Connection timeout"; - if (WiFi.status() == WL_CONNECT_FAILED) { - error_msg = "Wrong password"; - } else if (WiFi.status() == WL_NO_SSID_AVAIL) { - error_msg = "Network not found"; - } - showConnectionResult(false, error_msg); - g_wifi_state = WIFI_STATE_SCANNING; - g_wifi_scan_requested = true; // Resume scanning - } - - // Free the credentials memory - free(creds); + case CMD_CONNECT: + if (!g_enabled) { // joining implies switching Wi-Fi on + g_enabled = true; + SettingsManager::saveWiFiState(true); } + doConnect(cmd.ssid, cmd.pass, true); break; - case WIFI_UI_EVENT_DISCONNECT: - Serial.println("WiFi Task: Disconnecting..."); - WiFi.disconnect(); // NOT (true): that powers the radio off and kills ESP-NOW - g_wifi_state = WIFI_STATE_SCANNING; - g_wifi_scan_requested = true; + case CMD_CONNECT_SAVED: { + char ssid[33]; + lock(); + copyStr(ssid, g_status.saved_ssid, sizeof(ssid)); + unlock(); + if (g_enabled && ssid[0]) doConnect(ssid, g_saved_pass, false); break; + } - default: + case CMD_FORGET: + clearSaved(); + dropToEspNowChannel(); + setLink(g_enabled ? LINK_IDLE : LINK_OFF, ""); + print("[wifi] saved network forgotten"); break; } + memset(cmd.pass, 0, sizeof(cmd.pass)); } - // Handle WiFi scanning - if (g_wifi_state != WIFI_STATE_OFF) { - unsigned long current_time = millis(); - - // 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; - g_wifi_scan_requested = false; - g_last_scan_time = current_time; - - // Start async scan - WiFi.scanNetworks(true, false); // async=true, show_hidden=false - - // Only show spinner if list is empty (first scan or after error) - // For periodic rescans, keep the existing list visible - if (g_network_count == 0) { - lvgl_port_lock(-1); - updateWifiUIState(WIFI_STATE_SCANNING); - lvgl_port_unlock(); - Serial.println("Showing loading spinner (list is empty)"); - } else { - Serial.println("Background rescan (keeping list visible)"); - } - } - - // Check if scan is complete - if (scanning) { - int16_t result = WiFi.scanComplete(); - - if (result >= 0) { - // Scan completed successfully - scanning = false; - Serial.printf("WiFi scan complete: %d networks found\n", result); - - // Lock mutex to update shared data - if (xSemaphoreTake(g_wifi_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - g_network_count = min((int)result, WIFI_SCAN_MAX_NETWORKS); - - // Copy scan results to our buffer - for (uint8_t i = 0; i < g_network_count; i++) { - g_scanned_networks[i].ssid = WiFi.SSID(i); - g_scanned_networks[i].rssi = WiFi.RSSI(i); - g_scanned_networks[i].auth = WiFi.encryptionType(i); - - Serial.printf(" [%d] %s (RSSI: %d, Auth: %s)\n", - i, - g_scanned_networks[i].ssid.c_str(), - g_scanned_networks[i].rssi, - getAuthModeString(g_scanned_networks[i].auth)); - } - - xSemaphoreGive(g_wifi_mutex); - - // Update UI with scan results - g_wifi_state = WIFI_STATE_SCAN_COMPLETE; - lvgl_port_lock(-1); - updateSSIDList(); - updateWifiUIState(WIFI_STATE_SCAN_COMPLETE); - lvgl_port_unlock(); - } - - // Delete scan results to free memory - WiFi.scanDelete(); - - } else if (result == WIFI_SCAN_FAILED) { - // Scan failed - scanning = false; - Serial.println("WiFi scan failed!"); - g_wifi_state = WIFI_STATE_ERROR; - - lvgl_port_lock(-1); - updateWifiUIState(WIFI_STATE_ERROR); - lvgl_port_unlock(); - } - // If result == WIFI_SCAN_RUNNING, scan is still in progress + // Scan completion + bool scanning; + lock(); + scanning = g_status.scanning; + unlock(); + if (scanning) { + int16_t r = WiFi.scanComplete(); + if (r >= 0) { + collectScan(r); + WiFi.scanDelete(); + } else if (r == WIFI_SCAN_FAILED || millis() - scan_t0 > 10000) { + WiFi.scanDelete(); + lock(); + g_status.scanning = false; + g_status.scan_gen++; + unlock(); + print("[wifi] scan failed"); } } - // Small delay to prevent task from hogging CPU - vTaskDelay(pdMS_TO_TICKS(50)); - } -} - -// ============================================================================ -// PUBLIC API IMPLEMENTATION -// ============================================================================ - -void init(bool auto_start) { - Serial.println("[WiFiManager] Initializing WiFi subsystem..."); - - // Create mutex for protecting shared WiFi data - g_wifi_mutex = xSemaphoreCreateMutex(); - if (g_wifi_mutex == NULL) { - Serial.println("[WiFiManager] ERROR: Failed to create WiFi mutex!"); - } - - // Create event queue for WiFi task communication - g_wifi_event_queue = xQueueCreate(10, sizeof(wifi_queue_event_t)); - if (g_wifi_event_queue == NULL) { - Serial.println("[WiFiManager] ERROR: Failed to create WiFi event queue!"); - } - - // Create WiFi task on Core 0 - BaseType_t task_created = xTaskCreatePinnedToCore( - wifiTask, // Task function - "WiFi_Task", // Task name - WIFI_TASK_STACK_SIZE, // Stack size - NULL, // Parameters - WIFI_TASK_PRIORITY, // Priority (1) - &g_wifi_task_handle, // Task handle - WIFI_TASK_CORE // Core 0 - ); - - if (task_created != pdPASS) { - Serial.println("[WiFiManager] ERROR: Failed to create WiFi task!"); - } else { - Serial.println("[WiFiManager] WiFi task created successfully on Core 0"); - } - - // Auto-start WiFi if requested - if (auto_start) { - Serial.println("[WiFiManager] Auto-starting WiFi..."); - wifi_queue_event_t evt; - evt.type = WIFI_UI_EVENT_TOGGLE_ON; - evt.data = NULL; - xQueueSend(g_wifi_event_queue, &evt, 0); - } else { - WiFi.mode(WIFI_STA); // radio stays up for the ESP-NOW link (EspNowLink) - Serial.println("[WiFiManager] WiFi initially disabled"); - } -} - -wifi_state_t getState() { - return g_wifi_state; -} - -uint8_t getNetworkCount() { - return g_network_count; -} - -// ============================================================================ -// EVENT HANDLERS -// ============================================================================ - -void onWifiToggle(lv_event_t *e) -{ - // Get the actual widget from the event (safer than global variable) - lv_obj_t *target = lv_event_get_target(e); - - // Verify the widget is valid - if (target == NULL) { - Serial.println("ERROR: WiFi toggle target is NULL!"); - Serial.flush(); - return; - } - - // Check the toggle state - bool state = lv_obj_has_state(target, LV_STATE_CHECKED); - - Serial.printf("WiFi Toggle RELEASED - State: %s\n", state ? "ON" : "OFF"); - Serial.flush(); - - // Send event to WiFi task via queue - wifi_queue_event_t evt; - if (state) { - evt.type = WIFI_UI_EVENT_TOGGLE_ON; - - // Show loading state immediately - updateWifiUIState(WIFI_STATE_SCANNING); - } else { - evt.type = WIFI_UI_EVENT_TOGGLE_OFF; - - // Hide WiFi UI immediately - updateWifiUIState(WIFI_STATE_OFF); - } - evt.data = NULL; - - // Send event to WiFi task (non-blocking) - if (g_wifi_event_queue != NULL) { - xQueueSend(g_wifi_event_queue, &evt, 0); - } else { - Serial.println("ERROR: WiFi event queue not initialized!"); - } -} - -void onSSIDButtonClick(lv_event_t *e) { - lv_obj_t* btn = lv_event_get_target(e); - if (btn == NULL) { - Serial.println("ERROR: Button target is NULL!"); - return; - } - - // Get the network index from user data - int8_t network_idx = (int8_t)(intptr_t)lv_obj_get_user_data(btn); - - if (network_idx < 0 || network_idx >= g_network_count) { - Serial.printf("ERROR: Invalid network index: %d\n", network_idx); - return; - } - - g_selected_network_index = network_idx; - Serial.printf("===== SSID Button Clicked: %s =====\n", - g_scanned_networks[network_idx].ssid.c_str()); - - // Verify UI widgets exist - if (uic_Wifi_Passkey_TB == NULL || uic_Keyboard == NULL) { - Serial.println("ERROR: Password UI widgets are NULL!"); - return; - } - - // Get LVGL lock to update UI - lvgl_port_lock(0); - - // Hide all SSID buttons - for (uint8_t i = 0; i < g_button_count; i++) { - if (g_ssid_buttons[i] != NULL) { - lv_obj_add_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN); - } - } - - // Check if network requires password - if (g_scanned_networks[network_idx].auth == WIFI_AUTH_OPEN) { - // Open network - connect directly without password - Serial.println("Open network - connecting without password..."); - - // Show loading spinner - lv_obj_clear_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - - lvgl_port_unlock(); - - // Connect to open network - connectToWiFi(g_scanned_networks[network_idx].ssid.c_str(), NULL); - - } else { - // Secured network - show password entry - Serial.println("Secured network - showing password entry UI..."); - - // Configure and show password textbox - lv_textarea_set_text(uic_Wifi_Passkey_TB, ""); - lv_textarea_set_placeholder_text(uic_Wifi_Passkey_TB, - g_scanned_networks[network_idx].ssid.c_str()); - lv_textarea_set_password_mode(uic_Wifi_Passkey_TB, true); - lv_textarea_set_one_line(uic_Wifi_Passkey_TB, true); - lv_obj_clear_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN); - - // Configure and show keyboard - lv_keyboard_set_textarea(uic_Keyboard, uic_Wifi_Passkey_TB); - lv_keyboard_set_mode(uic_Keyboard, LV_KEYBOARD_MODE_TEXT_LOWER); - lv_obj_clear_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN); - - // Add event handler for keyboard (if not already added) - static bool keyboard_handler_added = false; - if (!keyboard_handler_added) { - lv_obj_add_event_cb(uic_Keyboard, onKeyboardEvent, LV_EVENT_ALL, NULL); - keyboard_handler_added = true; - Serial.println("Keyboard event handler registered"); - } - - lvgl_port_unlock(); - - Serial.println("Password entry UI shown successfully"); - } -} - -void onKeyboardEvent(lv_event_t *e) { - lv_event_code_t code = lv_event_get_code(e); - lv_obj_t *keyboard = lv_event_get_target(e); - - if (code == LV_EVENT_READY || code == LV_EVENT_CANCEL) { - // Get LVGL lock for UI updates - lvgl_port_lock(0); - - if (code == LV_EVENT_READY) { - // User pressed checkmark/enter - attempt connection - const char *password = lv_textarea_get_text(uic_Wifi_Passkey_TB); - - if (xSemaphoreTake(g_wifi_mutex, pdMS_TO_TICKS(100)) == pdTRUE) { - if (g_selected_network_index >= 0 && g_selected_network_index < g_network_count) { - Serial.printf("Connecting to: %s with password: %s\n", - g_scanned_networks[g_selected_network_index].ssid.c_str(), - password); - - // Hide keyboard and password field - lv_obj_add_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN); - - // Show loading spinner - lv_obj_clear_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN); - - // Trigger WiFi connection - connectToWiFi(g_scanned_networks[g_selected_network_index].ssid.c_str(), password); - - // Clear sensitive password data from text area - lv_textarea_set_text(uic_Wifi_Passkey_TB, ""); - } - xSemaphoreGive(g_wifi_mutex); + // A dropped connection gets one rejoin, then we stay put (an endless + // reconnect would keep hopping channels under the ESP-NOW link). + if (currentLink() == LINK_CONNECTED && WiFi.status() != WL_CONNECTED) { + if (lost_since == 0) lost_since = millis(); + if (millis() - lost_since > 3000) { + lost_since = 0; + char ssid[33]; + lock(); + copyStr(ssid, g_status.ssid, sizeof(ssid)); + unlock(); + print("[wifi] connection to '%s' lost - one retry", ssid); + doConnect(ssid, g_saved_pass, false, "Connection lost: "); } - - } else if (code == LV_EVENT_CANCEL) { - // User pressed X/cancel - go back to SSID list - Serial.println("Password entry cancelled - returning to SSID list"); - - // Hide keyboard and password field - lv_obj_add_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN); - lv_obj_add_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN); - - // Clear password field for security - lv_textarea_set_text(uic_Wifi_Passkey_TB, ""); - - // Show SSID buttons again - for (uint8_t i = 0; i < g_button_count; i++) { - if (g_ssid_buttons[i] != NULL) { - lv_obj_clear_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN); - } - } - - // Reset selected network index - g_selected_network_index = -1; - } - - lvgl_port_unlock(); - } -} - -void onRescanRequest(lv_event_t *e) { - if (g_wifi_state != WIFI_STATE_OFF) { - Serial.println("Manual rescan requested"); - - wifi_queue_event_t evt; - evt.type = WIFI_UI_EVENT_SCAN_START; - evt.data = NULL; - - if (g_wifi_event_queue != NULL) { - xQueueSend(g_wifi_event_queue, &evt, 0); + } else { + lost_since = 0; } } } -void onSelectSSID(lv_event_t *e) { - // This function is called from SquareLine Studio but we now use dynamic buttons - Serial.println("onSelectSSID() called - but dynamic buttons handle clicks now"); +// ============================================================================ +// PUBLIC API +// ============================================================================ + +static void send(cmd_type_t type, const char* ssid = NULL, const char* pass = NULL) { + if (g_queue == NULL) return; + cmd_t c = {}; + c.type = type; + copyStr(c.ssid, ssid, sizeof(c.ssid)); + copyStr(c.pass, pass, sizeof(c.pass)); + if (xQueueSend(g_queue, &c, pdMS_TO_TICKS(50)) != pdTRUE) print("[wifi] busy - request dropped"); + memset(c.pass, 0, sizeof(c.pass)); } +void init(bool enabled) { + g_mutex = xSemaphoreCreateMutex(); + g_queue = xQueueCreate(6, sizeof(cmd_t)); + g_enabled = enabled; + + WiFi.mode(WIFI_STA); // radio stays up for the ESP-NOW link (EspNowLink) + WiFi.persistent(false); // our own NVS copy; don't let the driver write flash on every begin() + WiFi.setAutoReconnect(false); // no endless channel hopping under ESP-NOW + WiFi.onEvent(onDisconnected, ARDUINO_EVENT_WIFI_STA_DISCONNECTED); + + loadSaved(); + lock(); + g_status.link = enabled ? LINK_IDLE : LINK_OFF; + unlock(); + print("[wifi] %s, saved network: %s", enabled ? "on" : "off", + g_status.saved_ssid[0] ? g_status.saved_ssid : "(none)"); + + xTaskCreatePinnedToCore(wifiTask, "WiFi_Task", WIFI_TASK_STACK_SIZE, NULL, + WIFI_TASK_PRIORITY, NULL, WIFI_TASK_CORE); +} + +void setEnabled(bool on) { + // Reflect the switch at once; the task does the (slow) radio work. + if (on) { + lock(); + bool has_saved = g_status.saved_ssid[0] != 0; + if (has_saved) { + g_status.link = LINK_CONNECTING; + copyStr(g_status.ssid, g_status.saved_ssid, sizeof(g_status.ssid)); + } else { + g_status.link = LINK_IDLE; + } + unlock(); + } else { + setLink(LINK_OFF, ""); + } + send(on ? CMD_ENABLE : CMD_DISABLE); +} + +bool isEnabled() { + return currentLink() != LINK_OFF; +} + +void requestScan() { + lock(); + bool busy = g_status.scanning || g_status.link == LINK_OFF; + if (!busy) g_status.scanning = true; // shown at once; the task starts it + unlock(); + if (!busy) send(CMD_SCAN); +} + +void connect(const char* ssid, const char* pass) { + if (ssid == NULL || !*ssid) return; + setLink(LINK_CONNECTING, ssid); + send(CMD_CONNECT, ssid, pass); +} + +void connectSaved() { + lock(); + bool ok = g_status.saved_ssid[0] != 0 && g_status.link != LINK_OFF; + if (ok) { + g_status.link = LINK_CONNECTING; + copyStr(g_status.ssid, g_status.saved_ssid, sizeof(g_status.ssid)); + } + unlock(); + if (ok) send(CMD_CONNECT_SAVED); +} + +void forget() { + send(CMD_FORGET); +} + +status_t getStatus() { + status_t s; + lock(); + s = g_status; + unlock(); + s.ip[0] = 0; + s.rssi = 0; + if (s.link == LINK_CONNECTED && WiFi.status() == WL_CONNECTED) { + copyStr(s.ip, WiFi.localIP().toString().c_str(), sizeof(s.ip)); + s.rssi = WiFi.RSSI(); + } + return s; +} + +uint8_t getNetworks(network_t* out, uint8_t max) { + lock(); + uint8_t n = g_network_count < max ? g_network_count : max; + memcpy(out, g_networks, sizeof(network_t) * n); + unlock(); + return n; +} // ============================================================================ -// CONSOLE (`wifi ...`) - join a network without the Settings screen, e.g. for OTA +// CONSOLE (`wifi ...`) // ============================================================================ +static const char* linkName(link_t l) { + switch (l) { + case LINK_OFF: return "off"; + case LINK_IDLE: return "not connected"; + case LINK_CONNECTING: return "connecting"; + case LINK_CONNECTED: return "connected"; + case LINK_FAILED: return "failed"; + default: return "?"; + } +} + bool handleCommand(const char* line) { char buf[128]; - strncpy(buf, line, sizeof(buf) - 1); - buf[sizeof(buf) - 1] = 0; + copyStr(buf, line, sizeof(buf)); char* argv[4] = {0}; int argc = 0; for (char* t = strtok(buf, " \t"); t && argc < 4; t = strtok(NULL, " \t")) argv[argc++] = t; @@ -796,26 +509,31 @@ bool handleCommand(const char* line) { 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 + connect(argv[2], argc >= 4 ? argv[3] : NULL); // result logged by the Wi-Fi task + } else if (argc == 2 && !strcmp(argv[1], "forget")) { + forget(); + } else if (argc == 2 && !strcmp(argv[1], "on")) { + setEnabled(true); } 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)"); + setEnabled(false); + } else if (argc == 2 && !strcmp(argv[1], "scan")) { + requestScan(); } 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()); + status_t s = getStatus(); + if (s.link == LINK_CONNECTED) { + print("[wifi] connected to '%s', IP %s, RSSI %d dBm, channel %d", s.ssid, s.ip, s.rssi, (int)WiFi.channel()); } else { - Serial.printf("[wifi] not connected (state %d), channel %d\n", (int)g_wifi_state, (int)WiFi.channel()); + print("[wifi] %s%s%s, channel %d", linkName(s.link), s.error[0] ? ": " : "", s.error, (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()); + print("[wifi] saved network: %s", s.saved_ssid[0] ? s.saved_ssid : "(none)"); + print("[wifi] ESP-NOW %s, sent %lu, failed %lu", 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 [pass] join a network (no spaces in the SSID)"); - Serial.println("wifi off stop scanning/association (radio stays on)"); + print("wifi status connection, saved network, ESP-NOW health"); + print("wifi join [pass] join + remember a network (no spaces in the SSID)"); + print("wifi forget drop the remembered network"); + print("wifi scan list networks in range"); + print("wifi on | off Wi-Fi switch (radio stays on for ESP-NOW)"); } return true; } diff --git a/src/modules/wifi_manager.h b/src/modules/wifi_manager.h index f448a0b..945beca 100644 --- a/src/modules/wifi_manager.h +++ b/src/modules/wifi_manager.h @@ -1,160 +1,85 @@ /* * WiFi Manager Module * - * Handles WiFi functionality for the Waveshare ESP32-S3-Touch-LCD-5B: - * - WiFi scanning and network discovery - * - Connection management with password entry - * - Dynamic SSID button generation - * - FreeRTOS task on Core 0 for async WiFi operations - * - Thread-safe UI updates via LVGL lock - * - Auto-restore WiFi state from NVS + * Joins one remembered network (for OTA updates) and scans on request. Owns no + * LVGL objects: the Settings screen polls getStatus()/getNetworks() and calls + * the request functions, so screen lifetimes can never leave dangling pointers + * here. + * + * Radio rules (the ESP-NOW link to Controller B shares the radio): + * - the radio stays in STA mode forever; "off" only stops association/scans. + * Never WiFi.disconnect(true) / WiFi.mode(WIFI_OFF) - that kills ESP-NOW. + * - scans only when asked (each one hops every channel); + * - no endless auto-reconnect: one attempt at boot, one after a drop, then + * idle on ESPNOW_CHANNEL until the user asks again. + * + * The network is remembered in NVS (namespace "wifi") after a successful join. + * The password is never printed. */ #pragma once #include #include -#include -#include -#include -#include namespace WiFiManager { -// ============================================================================ -// CONFIGURATION -// ============================================================================ - #define WIFI_SCAN_MAX_NETWORKS 20 -#define WIFI_SCAN_INTERVAL_MS 10000 // Rescan every 10 seconds when WiFi is ON +#define WIFI_CONNECT_TIMEOUT_MS 15000 #define WIFI_TASK_STACK_SIZE 4096 #define WIFI_TASK_PRIORITY 1 -#define WIFI_TASK_CORE 0 // Run WiFi task on Core 0 (LVGL runs on Core 1) +#define WIFI_TASK_CORE 0 -// ============================================================================ -// PUBLIC TYPES -// ============================================================================ - -/** - * @brief WiFi state machine states - */ typedef enum { - WIFI_STATE_OFF = 0, - WIFI_STATE_SCANNING, - WIFI_STATE_SCAN_COMPLETE, - WIFI_STATE_CONNECTED, - WIFI_STATE_CONNECTING, - WIFI_STATE_ERROR -} wifi_state_t; + LINK_OFF = 0, // Wi-Fi switched off + LINK_IDLE, // on, not connected, not trying + LINK_CONNECTING, + LINK_CONNECTED, + LINK_FAILED // last attempt failed; see status_t::error +} link_t; -/** - * @brief WiFi scan result structure - */ typedef struct { - String ssid; - int32_t rssi; - wifi_auth_mode_t auth; -} wifi_network_t; + link_t link; + char ssid[33]; // network being joined / joined / that failed + char ip[16]; + int rssi; // dBm, when connected + char error[48]; // human-readable reason when LINK_FAILED + char saved_ssid[33]; // remembered network ("" = none) + bool scanning; + uint32_t scan_gen; // bumps each time a scan completes +} status_t; -/** - * @brief WiFi connection credentials - */ typedef struct { - char ssid[32]; - char password[64]; -} wifi_credentials_t; + char ssid[33]; + int8_t rssi; + bool secured; +} network_t; -/** - * @brief WiFi event types for FreeRTOS queue - */ -typedef enum { - WIFI_UI_EVENT_TOGGLE_ON, - WIFI_UI_EVENT_TOGGLE_OFF, - WIFI_UI_EVENT_SCAN_START, - WIFI_UI_EVENT_SCAN_DONE, - WIFI_UI_EVENT_UPDATE_UI, - WIFI_UI_EVENT_CONNECT, - WIFI_UI_EVENT_DISCONNECT -} wifi_ui_event_type_t; +/** Start the Wi-Fi task. If enabled and a network is saved, joins it. */ +void init(bool enabled); -/** - * @brief WiFi queue event structure - */ -typedef struct { - wifi_ui_event_type_t type; - void* data; -} wifi_queue_event_t; +/** Wi-Fi switch: persisted. On joins the saved network; off disconnects. */ +void setEnabled(bool on); +bool isEnabled(); -// ============================================================================ -// PUBLIC API -// ============================================================================ +/** Scan once (ignored while off or already scanning). */ +void requestScan(); -/** - * @brief Initialize the WiFi manager subsystem - * - * This function: - * - Creates FreeRTOS mutex and queue - * - Spawns WiFi task on Core 0 - * - Optionally auto-starts WiFi based on saved state - * - * @param auto_start If true, automatically start WiFi based on NVS saved state - */ -void init(bool auto_start); +/** Join a network; remembered if it works. pass may be NULL/"" for open networks. */ +void connect(const char* ssid, const char* pass); -/** - * @brief Get current WiFi state - * @return Current wifi_state_t value - */ -wifi_state_t getState(); +/** Join the remembered network again. */ +void connectSaved(); -/** - * @brief Get WiFi network count from last scan - * @return Number of networks found - */ -uint8_t getNetworkCount(); +/** Drop the remembered network and disconnect. */ +void forget(); -/** - * @brief Console handler for `wifi status | join [pass] | off`. - * @return false if the line isn't a wifi command - */ +status_t getStatus(); + +/** Copy of the last scan (strongest first, one row per SSID). Returns the count. */ +uint8_t getNetworks(network_t* out, uint8_t max); + +/** Console: `wifi status | join [pass] | forget | on | off`. */ bool handleCommand(const char* line); -// ============================================================================ -// EVENT HANDLERS (Called from SquareLine Studio UI) -// ============================================================================ - -/** - * @brief WiFi toggle event handler - * @param e LVGL event object - * @note This function is registered in SquareLine Studio UI - */ -void onWifiToggle(lv_event_t *e); - -/** - * @brief SSID button click handler - * @param e LVGL event object - * @note Shows password entry for secured networks - */ -void onSSIDButtonClick(lv_event_t *e); - -/** - * @brief Keyboard event handler for password entry - * @param e LVGL event object - * @note Handles READY (connect) and CANCEL events - */ -void onKeyboardEvent(lv_event_t *e); - -/** - * @brief Manual rescan request handler - * @param e LVGL event object - */ -void onRescanRequest(lv_event_t *e); - -/** - * @brief Legacy SquareLine Studio compatibility function - * @param e LVGL event object - * @note Kept for compatibility, but dynamic buttons handle clicks now - */ -void onSelectSSID(lv_event_t *e); - } // namespace WiFiManager