Merge origin/main (27 commits from the other machine) with the Engine data screen
Firmware / build (push) Successful in 7m2s
Firmware / build (push) Successful in 7m2s
All incoming changes kept as they were. Conflicts resolved by adding the Engine-data pieces next to them: - main.cpp: StatusOverlay::tick() and EngineScreen::tick() - driveline_screen.cpp: both include sets; the old mismatch label stays removed (overlay owns it); the Engine data button moves to y 60, left of the diff-lock drawing, clear of the overlay band - CLAUDE.md: Engine data bullet added; DiagProbe paragraph keeps its text plus the live-mode sentence - wiki: all incoming log entries kept, the 2026-10-07 entry appended; open-questions #12 keeps the renamed line plus the 2026-10-07 update Built clean locally (custom_sdkconfig core rebuild). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -42,6 +42,7 @@ static QueueHandle_t g_can_event_queue = NULL;
|
||||
static can_stats_t g_can_stats = {0};
|
||||
static bool g_uart_auto_stopped = false; // Track if UART was auto-stopped due to CAN timeout
|
||||
|
||||
|
||||
// Raw frame logging: capture EVERY frame (candump-style) for offline CAN ID
|
||||
// discovery. Default ON since discovery is the current priority.
|
||||
static bool g_raw_logging = true;
|
||||
@@ -53,6 +54,22 @@ static bool g_verbose_decode = false;
|
||||
// Guarded by g_data_mutex along with g_automotive_data.
|
||||
static driveline_t g_driveline = {0};
|
||||
|
||||
/**
|
||||
* Forget every CAN-derived value: nothing may be shown or sent that the bus
|
||||
* did not say recently. Called when CAN stops and when the bus goes silent.
|
||||
*/
|
||||
static void clearSharedData() {
|
||||
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
uint8_t dbg = UARTManager::g_automotive_data.debug_enabled;
|
||||
memset(&UARTManager::g_automotive_data, 0, sizeof(UARTManager::g_automotive_data));
|
||||
UARTManager::g_automotive_data.gear_lever = LEVER_UNKNOWN;
|
||||
UARTManager::g_automotive_data.debug_enabled = dbg;
|
||||
xSemaphoreGive(UARTManager::g_data_mutex);
|
||||
}
|
||||
memset(&g_driveline, 0, sizeof(g_driveline));
|
||||
g_driveline.lever = GEAR_UNKNOWN;
|
||||
}
|
||||
|
||||
// Last gear LEVER code seen on 0x1D2, for the lever-vs-gearbox cross-check.
|
||||
static gear_position_t g_last_lever = GEAR_UNKNOWN;
|
||||
// When the current disagreement started (0 = currently in agreement).
|
||||
@@ -523,6 +540,7 @@ static void canTask(void* parameter) {
|
||||
deinitTWAI();
|
||||
g_can_active = false;
|
||||
g_uart_auto_stopped = false; // Reset auto-stop flag
|
||||
clearSharedData();
|
||||
|
||||
// Auto-stop UART transmission (CAN drives UART)
|
||||
UARTManager::linkToCANState(false);
|
||||
@@ -595,6 +613,7 @@ static void canTask(void* parameter) {
|
||||
// CAN data is stale - auto-stop UART to prevent transmitting stale data
|
||||
ESP_LOGW("CANTask", "⚠ CAN timeout (%dms since last message), auto-stopping UART", time_since_last_rx);
|
||||
UARTManager::linkToCANState(false);
|
||||
clearSharedData(); // stale values must not come back as "valid" later
|
||||
g_uart_auto_stopped = true;
|
||||
}
|
||||
}
|
||||
|
||||
+17
-3
@@ -14,9 +14,13 @@
|
||||
#include "modules/engine_screen.h" // Live DDE values (Engine data button on 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
|
||||
#include "modules/perf_monitor.h" // `perf` console: render fps, flush cost, CPU idle, heap
|
||||
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Inst. Cluster
|
||||
#include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter
|
||||
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
|
||||
#include "modules/link_peer.h" // Inst. Cluster status, pairing, credential handoff, B updates (`link` console)
|
||||
#include "modules/status_overlay.h" // Every screen: Wi-Fi chip top-right, blinking alert banner top-centre
|
||||
#include "modules/diff_locks.h" // Diff-lock inputs DI0 rear / DI1 front via the CH422G (`difflock` console)
|
||||
|
||||
// ============================================================================
|
||||
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
|
||||
@@ -55,10 +59,12 @@ static bool memCommand(const char* line) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem.
|
||||
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem, link, difflock.
|
||||
static bool consoleExtraCommand(const char* line) {
|
||||
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
|
||||
WiFiManager::handleCommand(line) || memCommand(line);
|
||||
WiFiManager::handleCommand(line) || memCommand(line) ||
|
||||
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
|
||||
DiffLocks::handleCommand(line);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -86,6 +92,7 @@ void setup()
|
||||
ESP_LOGI("MAIN", "Initializing display and UI...");
|
||||
DisplayInit::init();
|
||||
ESP_LOGI("MAIN", "Display init COMPLETED!");
|
||||
StatusOverlay::init(); // Wi-Fi chip + alert banner on lv_layer_top(), above every screen
|
||||
|
||||
// Initialize Settings Manager
|
||||
ESP_LOGI("MAIN", "Initializing Settings Manager...");
|
||||
@@ -95,6 +102,7 @@ void setup()
|
||||
Tunables::init();
|
||||
DiagProbe::init();
|
||||
Tunables::setExtraCommandHandler(consoleExtraCommand);
|
||||
PerfMon::init();
|
||||
|
||||
// Load saved switch states from NVS
|
||||
ESP_LOGI("MAIN", "Loading saved switch states from NVS...");
|
||||
@@ -102,6 +110,7 @@ void setup()
|
||||
bool saved_uart_state = SettingsManager::loadUARTState();
|
||||
bool saved_can_state = SettingsManager::loadCANState();
|
||||
bool saved_debug_state = SettingsManager::loadDebugState();
|
||||
DiffLocks::init(SettingsManager::loadDiffLockState(), SettingsManager::loadDiffLockInvert()); // CH422G bus is up since DisplayInit
|
||||
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
|
||||
|
||||
// Initialize UI State Manager
|
||||
@@ -115,6 +124,7 @@ void setup()
|
||||
// ESP-NOW transmit leg (needs the radio in STA mode, which WiFiManager keeps)
|
||||
ESP_LOGI("MAIN", "Initializing ESP-NOW link...");
|
||||
EspNowLink::init();
|
||||
LinkPeer::init(); // B's STATUS frames, pairing key, credential handoff
|
||||
|
||||
// Initialize UART subsystem using UARTManager module
|
||||
ESP_LOGI("MAIN", "Initializing UART subsystem...");
|
||||
@@ -155,12 +165,16 @@ void loop()
|
||||
// LVGL renders in its own task; the screen ticks below only refresh values.
|
||||
// Serial console: gauge tunables (cfg ...), diagnostic probe (diag ...), updates (ota ...)
|
||||
Tunables::pollSerial();
|
||||
PerfMon::tick();
|
||||
DiagProbe::tick();
|
||||
Ota::tick(); // confirms a freshly installed image after healthy uptime
|
||||
LinkPeer::tick(); // Inst. Cluster heard/lost, credential sync
|
||||
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
|
||||
|
||||
DrivelineScreen::tick();
|
||||
TuningScreen::tick();
|
||||
SettingsScreen::tick();
|
||||
StatusOverlay::tick();
|
||||
EngineScreen::tick();
|
||||
|
||||
delay(100); // Check frequently to catch screen changes quickly
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Differential lock inputs - see diff_locks.h
|
||||
*
|
||||
* Schematic (V1.2, sheet 1): DINx -> PC814 LED -> 3.6 kOhm -> DI_COM. The
|
||||
* optocoupler's transistor pulls DIx (4.7 kOhm to 3V3) LOW while current flows,
|
||||
* so a LOCKED diff reads 0 on its EXIO bit. The PC814 LED is bidirectional:
|
||||
* +12 V on DINx with DI_COM on ground is the "PNP / high-level" wiring.
|
||||
*/
|
||||
|
||||
#include "diff_locks.h"
|
||||
#include "settings_manager.h"
|
||||
#include "serial_lock.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include <driver/i2c.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
namespace DiffLocks {
|
||||
|
||||
// CH422G on the panel library's I2C host 0. Its "registers" are I2C addresses.
|
||||
static const i2c_port_t CH422G_PORT = I2C_NUM_0;
|
||||
static const uint8_t ADDR_WR_SET = 0x24; // system parameter byte
|
||||
static const uint8_t ADDR_RD_IO = 0x26; // IO0-7 pin levels
|
||||
// WR_SET as the board config leaves it (ESP_PANEL_BOARD_EXPANDER_POST_BEGIN_FUNCTION:
|
||||
// enableAllIO_Output -> IO_OE only; OC push-pull, no sleep). Input = IO_OE cleared.
|
||||
static const uint8_t WR_SET_OUTPUT = 0x01;
|
||||
static const uint8_t WR_SET_INPUT = 0x00;
|
||||
|
||||
static const uint8_t BIT_REAR = 1 << 0; // DI0 = EXIO0
|
||||
static const uint8_t BIT_FRONT = 1 << 5; // DI1 = EXIO5
|
||||
|
||||
static const uint32_t POLL_MS = 250;
|
||||
static const uint8_t FAULT_AFTER = 3; // failed reads in a row
|
||||
|
||||
static bool g_enabled = false;
|
||||
static bool g_inverted = false;
|
||||
static bool g_rear = false, g_front = false; // debounced
|
||||
static bool g_have_state = false;
|
||||
static uint8_t g_last_raw = 0xFF;
|
||||
static bool g_have_raw = false;
|
||||
static uint8_t g_fail_run = 0;
|
||||
static uint32_t g_reads = 0, g_fails = 0;
|
||||
static uint32_t g_last_poll = 0;
|
||||
|
||||
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 esp_err_t writeSet(uint8_t v) {
|
||||
return i2c_master_write_to_device(CH422G_PORT, ADDR_WR_SET, &v, 1, pdMS_TO_TICKS(10));
|
||||
}
|
||||
|
||||
/**
|
||||
* One raw read of IO0-7. The bank is an input only between the two WR_SET
|
||||
* writes (three short I2C transactions); the output is restored even when the
|
||||
* read fails, and retried, because touch reset, backlight and LCD reset live on
|
||||
* the same bank. The caller holds the LVGL lock, so no touch read (same bus)
|
||||
* can land in the middle.
|
||||
*/
|
||||
static bool readBank(uint8_t* out) {
|
||||
if (writeSet(WR_SET_INPUT) != ESP_OK) {
|
||||
writeSet(WR_SET_OUTPUT); // a half-done write: make sure we are back
|
||||
return false;
|
||||
}
|
||||
esp_err_t r = i2c_master_read_from_device(CH422G_PORT, ADDR_RD_IO, out, 1, pdMS_TO_TICKS(10));
|
||||
for (int i = 0; i < 3 && writeSet(WR_SET_OUTPUT) != ESP_OK; i++) {}
|
||||
return r == ESP_OK;
|
||||
}
|
||||
|
||||
void init(bool enabled, bool inverted) {
|
||||
g_enabled = enabled;
|
||||
g_inverted = inverted;
|
||||
print("[difflock] %s (DI0 = rear, DI1 = front, %s)", enabled ? "ON" : "OFF - Settings > System to enable",
|
||||
inverted ? "INVERTED: no current = locked" : "current = locked");
|
||||
}
|
||||
|
||||
void setEnabled(bool enabled) {
|
||||
if (enabled == g_enabled) return;
|
||||
g_enabled = enabled;
|
||||
g_have_state = g_have_raw = false;
|
||||
g_rear = g_front = false;
|
||||
g_fail_run = 0;
|
||||
SettingsManager::saveDiffLockState(enabled);
|
||||
}
|
||||
|
||||
void setInverted(bool inverted) {
|
||||
if (inverted == g_inverted) return;
|
||||
g_inverted = inverted;
|
||||
g_have_state = g_have_raw = false; // re-evaluate from the next two reads
|
||||
SettingsManager::saveDiffLockInvert(inverted);
|
||||
}
|
||||
|
||||
bool isInverted() { return g_inverted; }
|
||||
bool isEnabled() { return g_enabled; }
|
||||
bool isValid() { return g_enabled && g_have_state && g_fail_run < FAULT_AFTER; }
|
||||
bool rearLocked() { return isValid() && g_rear; }
|
||||
bool frontLocked() { return isValid() && g_front; }
|
||||
|
||||
void tick() {
|
||||
if (!g_enabled || millis() - g_last_poll < POLL_MS) return;
|
||||
g_last_poll = millis();
|
||||
|
||||
if (!lvgl_port_lock(100)) return; // UI busy: try again next poll
|
||||
uint8_t raw = 0xFF;
|
||||
bool ok = readBank(&raw);
|
||||
lvgl_port_unlock();
|
||||
|
||||
g_reads++;
|
||||
if (!ok) {
|
||||
g_fails++;
|
||||
if (g_fail_run < 255) g_fail_run++;
|
||||
if (g_fail_run == FAULT_AFTER) print("[difflock] CH422G read failing - lock states unknown");
|
||||
return;
|
||||
}
|
||||
g_fail_run = 0;
|
||||
|
||||
// Accept a state only when two reads in a row agree (<= 0.5 s latency).
|
||||
uint8_t bits = raw & (BIT_REAR | BIT_FRONT);
|
||||
if (g_have_raw && bits == (g_last_raw & (BIT_REAR | BIT_FRONT))) {
|
||||
// opto conducting = pin low; that is "locked" unless the polarity is inverted
|
||||
bool rear = !(bits & BIT_REAR) != g_inverted;
|
||||
bool front = !(bits & BIT_FRONT) != g_inverted;
|
||||
if (!g_have_state || rear != g_rear || front != g_front) {
|
||||
g_rear = rear;
|
||||
g_front = front;
|
||||
g_have_state = true;
|
||||
print("[difflock] rear %s, front %s%s", rear ? "LOCKED" : "open", front ? "LOCKED" : "open",
|
||||
(front && !rear) ? " (front without rear - check the DI0 wiring)" : "");
|
||||
}
|
||||
}
|
||||
g_last_raw = raw;
|
||||
g_have_raw = true;
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
if (strncmp(line, "difflock", 8) != 0 || (line[8] != 0 && line[8] != ' ')) return false;
|
||||
const char* a = line + 8;
|
||||
while (*a == ' ') a++;
|
||||
|
||||
if (!strcmp(a, "on")) { setEnabled(true); print("[difflock] ON (saved)"); return true; }
|
||||
if (!strcmp(a, "off")) { setEnabled(false); print("[difflock] OFF (saved)"); return true; }
|
||||
if (!strcmp(a, "invert on")) { setInverted(true); print("[difflock] INVERTED: no current = locked (saved)"); return true; }
|
||||
if (!strcmp(a, "invert off")) { setInverted(false); print("[difflock] normal: current (+12 V) = locked (saved)"); return true; }
|
||||
if (!*a || !strcmp(a, "status")) {
|
||||
if (!g_enabled) { print("[difflock] OFF - inputs not read ('difflock on' or Settings > System)"); return true; }
|
||||
print("[difflock] rear %s, front %s | %s | raw IO0-7 0x%02X | %lu reads, %lu failed%s",
|
||||
!isValid() ? "?" : g_rear ? "LOCKED" : "open",
|
||||
!isValid() ? "?" : g_front ? "LOCKED" : "open",
|
||||
g_inverted ? "inverted" : "normal", g_last_raw, (unsigned long)g_reads, (unsigned long)g_fails,
|
||||
g_fail_run >= FAULT_AFTER ? " | READ FAULT" : "");
|
||||
return true;
|
||||
}
|
||||
print("[difflock] usage: difflock status | on | off | invert on|off (DI0 = rear, DI1 = front)");
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace DiffLocks
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Differential lock inputs - DI0 = rear, DI1 = front
|
||||
*
|
||||
* The Patrol's lock switches put +12 V on a wire while a diff is locked. Those
|
||||
* wires go to the board's isolated inputs (PC814 optocouplers, 5-36 V, DI_COM to
|
||||
* vehicle ground). The inputs reach the ESP32 only through the CH422G expander
|
||||
* (DI0 = EXIO0, DI1 = EXIO5), whose IO0-7 are all-in or all-out as ONE bank - and
|
||||
* the same bank drives touch reset, backlight enable and LCD reset. So each read
|
||||
* switches the bank to input for ~0.1 ms and straight back (output latches are
|
||||
* kept by the chip). That is why the whole feature sits behind a Settings switch,
|
||||
* default OFF: a board without diff-lock wiring never touches the bank.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace DiffLocks {
|
||||
|
||||
/** Call once after DisplayInit (the CH422G's I2C bus is installed by the panel library). */
|
||||
void init(bool enabled, bool inverted);
|
||||
|
||||
/** Settings switch / `difflock on|off`. Saved to NVS (SettingsManager). */
|
||||
void setEnabled(bool enabled);
|
||||
bool isEnabled();
|
||||
|
||||
/**
|
||||
* Polarity. Normal: current through the input (+12 V on DINx) = locked.
|
||||
* Inverted: NO current = locked - the Patrol's ground-switched lock lamps give
|
||||
* 12 V through the lamp while unlocked and 0 V once the diff switch closes
|
||||
* (seen in the car, 2026-09-29). Saved to NVS.
|
||||
*/
|
||||
void setInverted(bool inverted);
|
||||
bool isInverted();
|
||||
|
||||
/** Poll the inputs (4 Hz, debounced over two reads). Call from loop(). */
|
||||
void tick();
|
||||
|
||||
/** Enabled AND the last reads succeeded - otherwise the lock states mean nothing. */
|
||||
bool isValid();
|
||||
bool rearLocked();
|
||||
bool frontLocked();
|
||||
|
||||
/** `difflock status | on | off | invert on|off`. Returns true if the line was ours. */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
} // namespace DiffLocks
|
||||
@@ -4,10 +4,13 @@
|
||||
|
||||
#include "driveline_screen.h"
|
||||
#include "uart_manager.h"
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include "drivers/can_driver.h"
|
||||
#include "tuning_screen.h"
|
||||
#include "settings_screen.h"
|
||||
#include "diff_locks.h"
|
||||
#include "engine_screen.h"
|
||||
#include "ui_kit.h"
|
||||
#include "esp_log.h"
|
||||
@@ -25,6 +28,8 @@ namespace DrivelineScreen {
|
||||
#define COL_ACCENT lv_color_hex(0x3DA9FC)
|
||||
#define COL_OK lv_color_hex(0x3DD68C)
|
||||
#define COL_WARN lv_color_hex(0xE5484D)
|
||||
#define COL_ALERT lv_color_hex(0xFF3B30) // threshold crossed: value + title
|
||||
#define COL_AMBER lv_color_hex(0xF5A524)
|
||||
|
||||
#define RPM_MAX 5000 // M57N redline is ~4500; a little headroom
|
||||
|
||||
@@ -37,6 +42,8 @@ static lv_obj_t* g_gear_lbl = NULL;
|
||||
static lv_obj_t* g_gear_ring = NULL;
|
||||
static lv_obj_t* g_coolant_lbl = NULL;
|
||||
static lv_obj_t* g_gearbox_lbl = NULL;
|
||||
static lv_obj_t* g_coolant_title = NULL;
|
||||
static lv_obj_t* g_gearbox_title = NULL;
|
||||
static lv_obj_t* g_rpm_bar = NULL;
|
||||
static lv_obj_t* g_rpm_lbl = NULL;
|
||||
static lv_obj_t* g_torque_lbl = NULL;
|
||||
@@ -46,7 +53,7 @@ static lv_obj_t* g_ign_chip = NULL;
|
||||
static lv_obj_t* g_eng_chip = NULL;
|
||||
static lv_obj_t* g_clutch_chip = NULL;
|
||||
static lv_obj_t* g_cool_chip = NULL;
|
||||
static lv_obj_t* g_mismatch_lbl = NULL;
|
||||
static lv_obj_t* g_diff_box = NULL; // top-right: chassis top view, locked axles lit
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPERS
|
||||
@@ -69,12 +76,180 @@ static lv_obj_t* makeChip(lv_obj_t* parent, const char* text) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set a chip's text and colour in one go.
|
||||
* @brief lv_label_set_text() only if the text differs. lv_label_set_text()
|
||||
* re-lays-out and invalidates the label even when the string is the
|
||||
* same, and this screen refreshes at 10 Hz - with constant data that was
|
||||
* ~40 kpx redrawn 10x a second for nothing, a third of core 1 and 50 ms/s
|
||||
* of PSRAM writes (perf baseline 2026-09-27).
|
||||
*/
|
||||
static void setText(lv_obj_t* lbl, const char* text) {
|
||||
if (lbl == NULL) return;
|
||||
const char* cur = lv_label_get_text(lbl);
|
||||
if (cur != NULL && strcmp(cur, text) == 0) return;
|
||||
lv_label_set_text(lbl, text);
|
||||
}
|
||||
|
||||
/** Text colour, written only on change (a style write invalidates regardless). */
|
||||
static void setColour(lv_obj_t* o, lv_color_t colour) {
|
||||
if (o == NULL) return;
|
||||
if (lv_color_to32(lv_obj_get_style_text_color(o, 0)) != lv_color_to32(colour)) {
|
||||
lv_obj_set_style_text_color(o, colour, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Ring border colour, written only on change. */
|
||||
static void setRing(lv_color_t colour) {
|
||||
if (lv_color_to32(lv_obj_get_style_border_color(g_gear_ring, 0)) != lv_color_to32(colour)) {
|
||||
lv_obj_set_style_border_color(g_gear_ring, colour, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set a chip's text and colour, touching the object only on a change
|
||||
* (a style write invalidates the object even for an identical value).
|
||||
*/
|
||||
static void setChip(lv_obj_t* chip, const char* text, lv_color_t colour) {
|
||||
if (chip == NULL) return;
|
||||
lv_label_set_text(chip, text);
|
||||
lv_obj_set_style_text_color(chip, colour, 0);
|
||||
setText(chip, text);
|
||||
if (lv_color_to32(lv_obj_get_style_text_color(chip, 0)) != lv_color_to32(colour)) {
|
||||
lv_obj_set_style_text_color(chip, colour, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- diff-lock drawing ------------------------------------------------------
|
||||
// A top view of the chassis, after the user's sketch (front up): steered front
|
||||
// tyres on the front axle, prop shaft, rear axle on straight tyres. All four
|
||||
// tyres are the same square-cornered 24 x 76 rectangle. A locked axle lights up:
|
||||
// axle, tyres filled, and an X on its diff. Geometry is in sketch pixels, scaled
|
||||
// by DL_S. Wheelbase 151 = the sketch's 189 shortened by 20 % (user, 2026-09-29).
|
||||
|
||||
static const float DL_S = 0.46f; // sketch -> screen
|
||||
static const lv_coord_t DL_BOX_W = 110; // hugs the drawing (dl(DL_W) = 98)
|
||||
static const float DL_W = 212; // sketch width the drawing is centred in
|
||||
static const float DL_SHAFT_X = 106;
|
||||
static const float DL_FRONT_Y = 45;
|
||||
static const float DL_REAR_Y = DL_FRONT_Y + 151;
|
||||
static const float DL_TRACK_L = 45, DL_TRACK_R = 167; // tyre centres, symmetric about the shaft
|
||||
static const float DL_TYRE_W = 24, DL_TYRE_L = 76;
|
||||
static const float DL_STEER = 25; // front tyres, degrees, top leaning right
|
||||
|
||||
static lv_coord_t dl(float v) { return (lv_coord_t)lroundf(v * DL_S); }
|
||||
|
||||
/** Sketch point -> box point (drawing centred horizontally in the box). */
|
||||
static lv_point_t dlPoint(float x, float y) {
|
||||
lv_point_t pt;
|
||||
pt.x = (DL_BOX_W - dl(DL_W)) / 2 + dl(x);
|
||||
pt.y = dl(y) + 2;
|
||||
return pt;
|
||||
}
|
||||
|
||||
struct TyreView {
|
||||
lv_obj_t* outline;
|
||||
lv_obj_t* fill; // shown only while the axle is locked
|
||||
};
|
||||
|
||||
struct AxleView {
|
||||
lv_obj_t* axle;
|
||||
TyreView tyre[2];
|
||||
lv_obj_t* cross[2]; // the X on the diff, shown only while locked
|
||||
};
|
||||
static AxleView g_front_axle, g_rear_axle;
|
||||
|
||||
// lv_line keeps a pointer to its points: they must outlive the objects.
|
||||
static lv_point_t g_pts_shaft[2];
|
||||
static lv_point_t g_pts_axle[2][2]; // [front, rear][end]
|
||||
static lv_point_t g_pts_tyre[2][2][5]; // [front, rear][left, right] closed outline
|
||||
static lv_point_t g_pts_fill[2][2][2]; // [front, rear][left, right] centre line of the fill
|
||||
static lv_point_t g_pts_cross[2][2][2]; // [front, rear][stroke][end]
|
||||
|
||||
static lv_obj_t* makeLine(lv_obj_t* parent, lv_point_t* pts, uint16_t n, lv_coord_t width, bool rounded) {
|
||||
lv_obj_t* l = lv_line_create(parent);
|
||||
lv_line_set_points(l, pts, n);
|
||||
lv_obj_set_style_line_width(l, width, 0);
|
||||
lv_obj_set_style_line_rounded(l, rounded, 0);
|
||||
lv_obj_set_style_line_color(l, COL_MUTED, 0);
|
||||
lv_obj_clear_flag(l, LV_OBJ_FLAG_CLICKABLE);
|
||||
return l;
|
||||
}
|
||||
|
||||
/**
|
||||
* A tyre centred on (cx, cy), `steer` degrees from straight (top leaning right).
|
||||
* The fill is ONE line as wide as the tyre with square ends, which is exactly
|
||||
* the filled rectangle, rotated or not (LVGL 8 cannot rotate a plain box).
|
||||
*/
|
||||
static TyreView makeTyre(lv_obj_t* parent, lv_point_t* outline, lv_point_t* fill,
|
||||
float cx, float cy, float steer) {
|
||||
const float a = DL_TYRE_W / 2, b = DL_TYRE_L / 2, t = steer * (float)M_PI / 180.0f;
|
||||
const float ux = sinf(t), uy = -cosf(t); // long axis, towards the top
|
||||
const float vx = cosf(t), vy = sinf(t); // short axis
|
||||
const float k[4][2] = {{b, a}, {b, -a}, {-b, -a}, {-b, a}};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
outline[i] = dlPoint(cx + k[i][0] * ux + k[i][1] * vx, cy + k[i][0] * uy + k[i][1] * vy);
|
||||
}
|
||||
outline[4] = outline[0];
|
||||
fill[0] = dlPoint(cx + b * ux, cy + b * uy);
|
||||
fill[1] = dlPoint(cx - b * ux, cy - b * uy);
|
||||
|
||||
TyreView v;
|
||||
v.fill = makeLine(parent, fill, 2, dl(DL_TYRE_W), false);
|
||||
lv_obj_add_flag(v.fill, LV_OBJ_FLAG_HIDDEN);
|
||||
v.outline = makeLine(parent, outline, 5, 2, true); // 2 px rounded joins read as square corners
|
||||
return v;
|
||||
}
|
||||
|
||||
/** The X on a diff at (cx, cy); idx 0 = front, 1 = rear. */
|
||||
static void diffCross(lv_obj_t* parent, AxleView& a, int idx, float cx, float cy) {
|
||||
const float r = 16;
|
||||
g_pts_cross[idx][0][0] = dlPoint(cx - r, cy - r); g_pts_cross[idx][0][1] = dlPoint(cx + r, cy + r);
|
||||
g_pts_cross[idx][1][0] = dlPoint(cx + r, cy - r); g_pts_cross[idx][1][1] = dlPoint(cx - r, cy + r);
|
||||
for (int k = 0; k < 2; k++) {
|
||||
a.cross[k] = makeLine(parent, g_pts_cross[idx][k], 2, 4, true);
|
||||
lv_obj_add_flag(a.cross[k], LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
/** Line colour, written only on change. */
|
||||
static void setPartColour(lv_obj_t* o, lv_color_t c) {
|
||||
if (lv_color_to32(lv_obj_get_style_line_color(o, 0)) != lv_color_to32(c)) {
|
||||
lv_obj_set_style_line_color(o, c, 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void setHidden(lv_obj_t* o, bool hidden) {
|
||||
if (lv_obj_has_flag(o, LV_OBJ_FLAG_HIDDEN) == hidden) return;
|
||||
if (hidden) lv_obj_add_flag(o, LV_OBJ_FLAG_HIDDEN);
|
||||
else lv_obj_clear_flag(o, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
|
||||
static void setAxle(AxleView& a, bool locked, lv_color_t colour) {
|
||||
lv_color_t c = locked ? colour : COL_MUTED;
|
||||
setPartColour(a.axle, c);
|
||||
for (int i = 0; i < 2; i++) {
|
||||
setPartColour(a.tyre[i].outline, c);
|
||||
setPartColour(a.tyre[i].fill, c);
|
||||
setHidden(a.tyre[i].fill, !locked);
|
||||
setPartColour(a.cross[i], c);
|
||||
setHidden(a.cross[i], !locked);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Diff locks, from the isolated inputs (not CAN - shown with CAN off too).
|
||||
* Locked axle = amber. The front can only lock after the rear, so FRONT
|
||||
* without REAR is a wiring/switch fault and shows red.
|
||||
*/
|
||||
static void refreshDiffLocks() {
|
||||
bool on = DiffLocks::isEnabled();
|
||||
setHidden(g_diff_box, !on);
|
||||
if (!on) return;
|
||||
if (!DiffLocks::isValid()) {
|
||||
setAxle(g_front_axle, false, COL_MUTED);
|
||||
setAxle(g_rear_axle, false, COL_MUTED);
|
||||
return;
|
||||
}
|
||||
bool rear = DiffLocks::rearLocked(), front = DiffLocks::frontLocked();
|
||||
setAxle(g_rear_axle, rear, COL_AMBER);
|
||||
setAxle(g_front_axle, front, rear ? COL_AMBER : COL_ALERT); // no caption: the drawing says it all (user)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -173,26 +348,54 @@ static void build() {
|
||||
lv_obj_set_size(bar, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_flow(bar, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_style_pad_column(bar, 8, 0);
|
||||
lv_obj_align(bar, LV_ALIGN_TOP_LEFT, 24, 18);
|
||||
// y 60: the top 56 px belong to the StatusOverlay (alert banner centre, Wi-Fi chip right)
|
||||
lv_obj_align(bar, LV_ALIGN_TOP_LEFT, 24, 60);
|
||||
lv_obj_clear_flag(bar, LV_OBJ_FLAG_SCROLLABLE);
|
||||
|
||||
g_ign_chip = makeChip(bar, "IGN --");
|
||||
g_eng_chip = makeChip(bar, "ENG --");
|
||||
g_clutch_chip = makeChip(bar, "CLUTCH --");
|
||||
g_cool_chip = makeChip(bar, "COOLING --");
|
||||
// Gear mismatch: the ring and the gear letter turn red, and the overlay banner says so.
|
||||
|
||||
g_mismatch_lbl = lv_label_create(g_screen);
|
||||
lv_label_set_text(g_mismatch_lbl, LV_SYMBOL_WARNING " GEAR MISMATCH");
|
||||
lv_obj_set_style_text_font(g_mismatch_lbl, &lv_font_montserrat_14, 0);
|
||||
lv_obj_set_style_text_color(g_mismatch_lbl, COL_WARN, 0);
|
||||
lv_obj_align(g_mismatch_lbl, LV_ALIGN_TOP_RIGHT, -240, 24);
|
||||
// ---- diff locks, top-right under the overlay's Wi-Fi chip (hidden until enabled).
|
||||
// Box bottom stays above the GEARBOX OIL stat (its top is at y ~227).
|
||||
g_diff_box = lv_obj_create(g_screen);
|
||||
lv_obj_remove_style_all(g_diff_box);
|
||||
lv_obj_set_size(g_diff_box, DL_BOX_W, dl(DL_REAR_Y + DL_TYRE_L / 2) + 6); // drawing only, no caption
|
||||
lv_obj_align(g_diff_box, LV_ALIGN_TOP_RIGHT, -16, 60);
|
||||
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_SCROLLABLE);
|
||||
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_CLICKABLE); // swipes pass through to the screen
|
||||
lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
g_pts_shaft[0] = dlPoint(DL_SHAFT_X, DL_FRONT_Y);
|
||||
g_pts_shaft[1] = dlPoint(DL_SHAFT_X, DL_REAR_Y);
|
||||
makeLine(g_diff_box, g_pts_shaft, 2, 3, true);
|
||||
|
||||
// axles run between the tyres' inner edges (a steered tyre's edge sits a little further out)
|
||||
const float half = DL_TYRE_W / 2;
|
||||
const float half_steered = half / cosf(DL_STEER * (float)M_PI / 180.0f);
|
||||
g_pts_axle[0][0] = dlPoint(DL_TRACK_L + half_steered, DL_FRONT_Y);
|
||||
g_pts_axle[0][1] = dlPoint(DL_TRACK_R - half_steered, DL_FRONT_Y);
|
||||
g_pts_axle[1][0] = dlPoint(DL_TRACK_L + half, DL_REAR_Y);
|
||||
g_pts_axle[1][1] = dlPoint(DL_TRACK_R - half, DL_REAR_Y);
|
||||
g_front_axle.axle = makeLine(g_diff_box, g_pts_axle[0], 2, 3, true);
|
||||
g_rear_axle.axle = makeLine(g_diff_box, g_pts_axle[1], 2, 3, true);
|
||||
|
||||
g_front_axle.tyre[0] = makeTyre(g_diff_box, g_pts_tyre[0][0], g_pts_fill[0][0], DL_TRACK_L, DL_FRONT_Y, DL_STEER);
|
||||
g_front_axle.tyre[1] = makeTyre(g_diff_box, g_pts_tyre[0][1], g_pts_fill[0][1], DL_TRACK_R, DL_FRONT_Y, DL_STEER);
|
||||
g_rear_axle.tyre[0] = makeTyre(g_diff_box, g_pts_tyre[1][0], g_pts_fill[1][0], DL_TRACK_L, DL_REAR_Y, 0);
|
||||
g_rear_axle.tyre[1] = makeTyre(g_diff_box, g_pts_tyre[1][1], g_pts_fill[1][1], DL_TRACK_R, DL_REAR_Y, 0);
|
||||
|
||||
diffCross(g_diff_box, g_front_axle, 0, DL_SHAFT_X, DL_FRONT_Y);
|
||||
diffCross(g_diff_box, g_rear_axle, 1, DL_SHAFT_X, DL_REAR_Y);
|
||||
|
||||
// Live DDE values (rail, boost, charge-air temp, battery). A button, not a
|
||||
// swipe, so polling the engine ECU never starts by accident.
|
||||
lv_obj_t* eng = UiKit::button(g_screen, LV_SYMBOL_CHARGE " Engine data", 210, 56,
|
||||
// swipe, so polling the engine ECU never starts by accident. Below the
|
||||
// overlay band (y 60, like the chips), left of the diff-lock drawing.
|
||||
lv_obj_t* eng = UiKit::button(g_screen, LV_SYMBOL_CHARGE " Engine data", 200, 56,
|
||||
UiKit::BTN_SECONDARY, onEngineData, NULL);
|
||||
lv_obj_align(eng, LV_ALIGN_TOP_RIGHT, -16, 10);
|
||||
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_align(eng, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16, 60);
|
||||
|
||||
// ---- gear hero -------------------------------------------------------
|
||||
g_gear_ring = lv_obj_create(g_screen);
|
||||
@@ -215,6 +418,8 @@ static void build() {
|
||||
LV_ALIGN_LEFT_MID, 110, -40);
|
||||
g_gearbox_lbl = makeStat(g_screen, "GEARBOX OIL", &lv_font_montserrat_40,
|
||||
LV_ALIGN_RIGHT_MID, -110, -40);
|
||||
g_coolant_title = lv_obj_get_child(lv_obj_get_parent(g_coolant_lbl), 0);
|
||||
g_gearbox_title = lv_obj_get_child(lv_obj_get_parent(g_gearbox_lbl), 0);
|
||||
|
||||
// ---- RPM bar ---------------------------------------------------------
|
||||
lv_obj_t* rpm_title = lv_label_create(g_screen);
|
||||
@@ -286,11 +491,13 @@ void tick() {
|
||||
uint8_t gear = GEAR_UNKNOWN;
|
||||
int16_t coolant = 0, gearbox = 0;
|
||||
uint8_t flags = 0;
|
||||
uint16_t alerts = 0;
|
||||
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
gear = UARTManager::g_automotive_data.gear_lever;
|
||||
coolant = UARTManager::g_automotive_data.coolant_temp;
|
||||
gearbox = UARTManager::g_automotive_data.gearbox_oil_temp;
|
||||
flags = UARTManager::g_automotive_data.valid_flags;
|
||||
alerts = UARTManager::g_automotive_data.alerts;
|
||||
xSemaphoreGive(UARTManager::g_data_mutex);
|
||||
} else {
|
||||
return; // couldn't read; leave the last frame on screen
|
||||
@@ -300,20 +507,25 @@ void tick() {
|
||||
(void)gear; // gear now comes from the driveline pieces, not the UART enum
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
refreshDiffLocks(); // hard-wired inputs: live even with CAN or the key off
|
||||
|
||||
// Blank every readout when there's nothing live to show: CAN off, or the key
|
||||
// is off. The user asked for a full reset on ignition-off so the screen goes
|
||||
// quiet with the car rather than freezing the last frame. 0x3B4 sends its
|
||||
// ignition nibble on-change, so this reset is effectively instant.
|
||||
if (!can_up || !dl.ignition_on) {
|
||||
lv_label_set_text(g_gear_lbl, "--");
|
||||
lv_label_set_text(g_coolant_lbl, "--");
|
||||
lv_label_set_text(g_gearbox_lbl, "--");
|
||||
lv_label_set_text(g_rpm_lbl, "----");
|
||||
lv_label_set_text(g_torque_lbl, "--");
|
||||
lv_label_set_text(g_pedal_lbl, "--");
|
||||
lv_label_set_text(g_shaft_lbl, "--");
|
||||
setText(g_gear_lbl, "--");
|
||||
setText(g_coolant_lbl, "--");
|
||||
setText(g_gearbox_lbl, "--");
|
||||
setText(g_rpm_lbl, "----");
|
||||
setText(g_torque_lbl, "--");
|
||||
setText(g_pedal_lbl, "--");
|
||||
setText(g_shaft_lbl, "--");
|
||||
lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF);
|
||||
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
|
||||
setRing(COL_ACCENT);
|
||||
setColour(g_gear_lbl, COL_TEXT);
|
||||
setColour(g_coolant_lbl, COL_TEXT); setColour(g_coolant_title, COL_MUTED);
|
||||
setColour(g_gearbox_lbl, COL_TEXT); setColour(g_gearbox_title, COL_MUTED);
|
||||
// Leave the ignition chip telling the truth; mute the rest, since their
|
||||
// values are meaningless with the key out (or absent with CAN off).
|
||||
if (!can_up) {
|
||||
@@ -332,37 +544,48 @@ void tick() {
|
||||
// ---- gear (composed: P/R/N, or D/S/M + engaged number) ---------------
|
||||
if ((gear_position_t)dl.lever != GEAR_UNKNOWN) {
|
||||
composeGear(dl, buf, sizeof(buf));
|
||||
lv_label_set_text(g_gear_lbl, buf);
|
||||
setText(g_gear_lbl, buf);
|
||||
} else {
|
||||
lv_label_set_text(g_gear_lbl, "--");
|
||||
setText(g_gear_lbl, "--");
|
||||
}
|
||||
|
||||
// ---- temperatures (only when the signal is real) ---------------------
|
||||
if (flags & VALID_FLAG_COOLANT_TEMP) {
|
||||
snprintf(buf, sizeof(buf), "%d.%d°C", coolant / 10, abs(coolant % 10));
|
||||
lv_label_set_text(g_coolant_lbl, buf);
|
||||
setText(g_coolant_lbl, buf);
|
||||
}
|
||||
if (flags & VALID_FLAG_GEARBOX_TEMP) {
|
||||
snprintf(buf, sizeof(buf), "%d.%d°C", gearbox / 10, abs(gearbox % 10));
|
||||
lv_label_set_text(g_gearbox_lbl, buf);
|
||||
setText(g_gearbox_lbl, buf);
|
||||
}
|
||||
|
||||
// ---- thresholds crossed: the value AND its title go red (amber while the
|
||||
// box only asks for cooling); the overlay banner blinks on top of it all.
|
||||
if (!(flags & VALID_FLAG_ALERTS)) alerts = 0;
|
||||
bool cool_hot = (alerts & ALERT_COOLANT_HOT) != 0;
|
||||
bool gb_hot = (alerts & ALERT_GEARBOX_HOT) != 0;
|
||||
bool gb_cool = (alerts & ALERT_GEARBOX_COOLING) != 0;
|
||||
setColour(g_coolant_lbl, cool_hot ? COL_ALERT : COL_TEXT);
|
||||
setColour(g_coolant_title, cool_hot ? COL_ALERT : COL_MUTED);
|
||||
setColour(g_gearbox_lbl, gb_hot ? COL_ALERT : gb_cool ? COL_AMBER : COL_TEXT);
|
||||
setColour(g_gearbox_title, gb_hot ? COL_ALERT : gb_cool ? COL_AMBER : COL_MUTED);
|
||||
|
||||
// ---- speeds ----------------------------------------------------------
|
||||
snprintf(buf, sizeof(buf), "%u", dl.engine_rpm);
|
||||
lv_label_set_text(g_rpm_lbl, buf);
|
||||
setText(g_rpm_lbl, buf);
|
||||
lv_bar_set_value(g_rpm_bar, dl.engine_rpm > RPM_MAX ? RPM_MAX : dl.engine_rpm, LV_ANIM_OFF);
|
||||
|
||||
// Torque is signed (negative under overrun/braking); one decimal, matching
|
||||
// the 0.5 Nm resolution of the field.
|
||||
snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10));
|
||||
lv_label_set_text(g_torque_lbl, buf);
|
||||
setText(g_torque_lbl, buf);
|
||||
|
||||
snprintf(buf, sizeof(buf), "%u", dl.pedal_percent);
|
||||
lv_label_set_text(g_pedal_lbl, buf);
|
||||
setText(g_pedal_lbl, buf);
|
||||
|
||||
// Provisional rpm from the single-point Launch factor (see automotive_data.h).
|
||||
snprintf(buf, sizeof(buf), "%u", can_output_shaft_rpm(dl.output_shaft_raw));
|
||||
lv_label_set_text(g_shaft_lbl, buf);
|
||||
setText(g_shaft_lbl, buf);
|
||||
|
||||
// ---- status chips ----------------------------------------------------
|
||||
setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF",
|
||||
@@ -389,11 +612,9 @@ void tick() {
|
||||
default: setChip(g_cool_chip, "COOLING ?", COL_MUTED); break;
|
||||
}
|
||||
|
||||
if (dl.gear_mismatch) {
|
||||
lv_obj_clear_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
// Gear mismatch: the hero ring and the gear letter turn red.
|
||||
setRing(dl.gear_mismatch ? COL_ALERT : COL_ACCENT);
|
||||
setColour(g_gear_lbl, dl.gear_mismatch ? COL_ALERT : COL_TEXT);
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* ESP-NOW Link Module Implementation (Controller A, transmit only)
|
||||
* ESP-NOW Link Module Implementation (Main CTRL, transmit only)
|
||||
*/
|
||||
|
||||
#include "espnow_link.h"
|
||||
@@ -16,6 +16,13 @@ static const uint8_t BROADCAST_MAC[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
|
||||
static bool g_ready = false;
|
||||
static uint32_t g_sent = 0;
|
||||
static uint32_t g_fail = 0;
|
||||
static receive_handler_t g_rx_handler = NULL;
|
||||
|
||||
// IDF 5.x receive callback: sender MAC is in the info struct.
|
||||
static void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len) {
|
||||
if (g_rx_handler == NULL || info == NULL || len <= 0) return;
|
||||
g_rx_handler(info->src_addr, data, (size_t)len);
|
||||
}
|
||||
|
||||
// IDF 5.5 (pioarduino / Arduino 3.3) passes wifi_tx_info_t*; older cores passed the MAC.
|
||||
static void onSent(const wifi_tx_info_t* info, esp_now_send_status_t status) {
|
||||
@@ -45,6 +52,7 @@ bool init() {
|
||||
return false;
|
||||
}
|
||||
esp_now_register_send_cb(onSent);
|
||||
esp_now_register_recv_cb(onReceive);
|
||||
|
||||
esp_now_peer_info_t peer = {};
|
||||
memcpy(peer.peer_addr, BROADCAST_MAC, 6);
|
||||
@@ -93,4 +101,26 @@ bool isReady() { return g_ready; }
|
||||
uint32_t sentCount() { return g_sent; }
|
||||
uint32_t failCount() { return g_fail; }
|
||||
|
||||
void setReceiveHandler(receive_handler_t handler) { g_rx_handler = handler; }
|
||||
|
||||
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len) {
|
||||
if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
|
||||
if (!g_ready) {
|
||||
reinitIfDue();
|
||||
if (!g_ready) return false;
|
||||
}
|
||||
if (!esp_now_is_peer_exist(mac)) {
|
||||
esp_now_peer_info_t peer = {};
|
||||
memcpy(peer.peer_addr, mac, 6);
|
||||
peer.channel = 0; // current channel
|
||||
peer.encrypt = false; // SECURE frames carry their own encryption
|
||||
peer.ifidx = WIFI_IF_STA;
|
||||
if (esp_now_add_peer(&peer) != ESP_OK) {
|
||||
ESP_LOGE("EspNow", "esp_now_add_peer(B) failed");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return esp_now_send(mac, frame, len) == ESP_OK;
|
||||
}
|
||||
|
||||
} // namespace EspNowLink
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
/*
|
||||
* ESP-NOW Link Module (Controller A side, transmit only)
|
||||
* ESP-NOW Link Module (Main CTRL side)
|
||||
*
|
||||
* Second transport for the A -> B link: every frame the UART manager builds
|
||||
* is also broadcast over ESP-NOW, so B keeps receiving if the wire is lost.
|
||||
* B dedupes on packet_id, so both paths may be live at once.
|
||||
*
|
||||
* Since 2026-09-27 the radio also listens: B unicasts STATUS frames back and
|
||||
* A unicasts SECURE frames to B (LinkPeer). Frames received are handed to the
|
||||
* handler set with setReceiveHandler(); sendTo() unicasts to one MAC.
|
||||
*
|
||||
* Radio policy: the Wi-Fi radio stays in STA mode permanently (the WiFi
|
||||
* manager's "off" only stops scanning). A transmits on ESPNOW_CHANNEL unless
|
||||
* associated to an access point, in which case the AP's channel is used and
|
||||
@@ -34,4 +38,11 @@ bool isReady();
|
||||
uint32_t sentCount();
|
||||
uint32_t failCount();
|
||||
|
||||
/** Frames received from any sender (runs in the Wi-Fi task - copy and return). */
|
||||
typedef void (*receive_handler_t)(const uint8_t mac[6], const uint8_t* frame, size_t len);
|
||||
void setReceiveHandler(receive_handler_t handler);
|
||||
|
||||
/** Unicast one complete frame to a MAC (peer added on first use, unencrypted). */
|
||||
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len);
|
||||
|
||||
} // namespace EspNowLink
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
/*
|
||||
* Link Peer Module Implementation (Main CTRL)
|
||||
*
|
||||
* Threading: onFrame() runs in the Wi-Fi task and only copies the STATUS into
|
||||
* g_peer under a mutex. Everything else (NVS, sending, console) is the loop task.
|
||||
*/
|
||||
|
||||
#include "link_peer.h"
|
||||
#include "espnow_link.h"
|
||||
#include "uart_manager.h"
|
||||
#include "wifi_manager.h"
|
||||
#include "ota_update.h"
|
||||
#include "serial_lock.h"
|
||||
#include "protocol/link_secure.h"
|
||||
#include <Preferences.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
|
||||
namespace LinkPeer {
|
||||
|
||||
static const char* NVS_LINK = "linkpeer"; // key (32 B)
|
||||
#define CREDS_PUSH_MIN_MS 15000 // never push credentials more often than this
|
||||
#define PAIR_REPEATS 3 // PAIR is sent this many times over the wire
|
||||
|
||||
static bool g_paired = false;
|
||||
static uint8_t g_key[LINK_KEY_LEN];
|
||||
static uint16_t g_key_fp = 0;
|
||||
|
||||
// last STATUS from B (written by the Wi-Fi task)
|
||||
static SemaphoreHandle_t g_mutex = NULL;
|
||||
static link_status_t g_st = {};
|
||||
static uint8_t g_b_mac[6] = {0};
|
||||
static uint32_t g_last_status_ms = 0;
|
||||
static bool g_ever_heard = false;
|
||||
static uint32_t g_status_count = 0, g_secure_sent = 0, g_secure_fail = 0;
|
||||
|
||||
// credential sync
|
||||
static uint32_t g_pushed_hash = 0;
|
||||
static uint32_t g_last_push_ms = 0;
|
||||
|
||||
static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); }
|
||||
static void unlock() { xSemaphoreGive(g_mutex); }
|
||||
|
||||
static void print(const char* fmt, ...) {
|
||||
char buf[200];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
static const char* phaseName(uint8_t p) {
|
||||
switch (p) {
|
||||
case LINK_OTA_CHECKING: return "checking";
|
||||
case LINK_OTA_UP_TO_DATE: return "up to date";
|
||||
case LINK_OTA_AVAILABLE: return "update available";
|
||||
case LINK_OTA_INSTALLING: return "installing";
|
||||
case LINK_OTA_FAILED: return "failed";
|
||||
default: return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
// ---- NVS --------------------------------------------------------------------
|
||||
static void loadKey() {
|
||||
Preferences p;
|
||||
p.begin(NVS_LINK, true);
|
||||
g_paired = p.getBytesLength("key") == LINK_KEY_LEN;
|
||||
if (g_paired) p.getBytes("key", g_key, LINK_KEY_LEN);
|
||||
p.end();
|
||||
g_key_fp = g_paired ? link_key_fingerprint(g_key) : 0;
|
||||
}
|
||||
|
||||
static void storeKey() {
|
||||
Preferences p;
|
||||
p.begin(NVS_LINK, false);
|
||||
p.putBytes("key", g_key, LINK_KEY_LEN);
|
||||
p.end();
|
||||
}
|
||||
|
||||
static void clearKey() {
|
||||
Preferences p;
|
||||
p.begin(NVS_LINK, false);
|
||||
p.clear();
|
||||
p.end();
|
||||
g_paired = false;
|
||||
g_key_fp = 0;
|
||||
memset(g_key, 0, sizeof(g_key));
|
||||
}
|
||||
|
||||
// ---- inbound (Wi-Fi task) ---------------------------------------------------
|
||||
static void onFrame(const uint8_t mac[6], const uint8_t* frame, size_t len) {
|
||||
uint8_t type = 0, plen = 0;
|
||||
const uint8_t* payload = NULL;
|
||||
if (frame_parse(frame, len, &type, &payload, &plen) != FRAME_OK) return;
|
||||
if (type != PACKET_TYPE_STATUS) return;
|
||||
if (xSemaphoreTake(g_mutex, pdMS_TO_TICKS(10)) != pdTRUE) return;
|
||||
memcpy(&g_st, payload, sizeof(g_st));
|
||||
g_st.version[sizeof(g_st.version) - 1] = 0;
|
||||
g_st.latest[sizeof(g_st.latest) - 1] = 0;
|
||||
g_st.message[sizeof(g_st.message) - 1] = 0;
|
||||
memcpy(g_b_mac, mac, 6);
|
||||
g_last_status_ms = millis();
|
||||
g_ever_heard = true;
|
||||
g_status_count++;
|
||||
xSemaphoreGive(g_mutex);
|
||||
}
|
||||
|
||||
// ---- public: status ---------------------------------------------------------
|
||||
peer_status_t getStatus() {
|
||||
peer_status_t p = {};
|
||||
lock();
|
||||
p.st = g_st;
|
||||
memcpy(p.mac, g_b_mac, 6);
|
||||
uint32_t last = g_last_status_ms;
|
||||
bool ever = g_ever_heard;
|
||||
unlock();
|
||||
p.age_ms = ever ? millis() - last : 0xFFFFFFFF;
|
||||
p.heard = ever && p.age_ms < LINK_STATUS_TIMEOUT_MS;
|
||||
p.paired = g_paired;
|
||||
p.key_fp = g_key_fp;
|
||||
p.key_match = g_paired && p.st.key_fp == g_key_fp;
|
||||
return p;
|
||||
}
|
||||
|
||||
// ---- outbound ---------------------------------------------------------------
|
||||
static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) {
|
||||
peer_status_t p = getStatus();
|
||||
if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard"); return false; }
|
||||
if (!p.paired) { snprintf(why, n, "not paired - run `link pair` with the wire connected"); return false; }
|
||||
if (!p.key_match) { snprintf(why, n, "Inst. Cluster holds a different key - run `link pair` again"); return false; }
|
||||
|
||||
uint8_t payload[PACKET_MAX_PAYLOAD], frame[PACKET_MAX_SIZE];
|
||||
size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload);
|
||||
if (!plen) { snprintf(why, n, "encryption failed"); return false; }
|
||||
size_t flen = frame_build(PACKET_TYPE_SECURE, payload, (uint8_t)plen, frame);
|
||||
if (!flen || !EspNowLink::sendTo(p.mac, frame, flen)) {
|
||||
g_secure_fail++;
|
||||
snprintf(why, n, "ESP-NOW send failed");
|
||||
return false;
|
||||
}
|
||||
g_secure_sent++;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool sendOtaCmd(uint8_t cmd, uint8_t flags, char* why, size_t n) {
|
||||
link_ota_cmd_t c = {};
|
||||
c.cmd = cmd;
|
||||
c.flags = flags;
|
||||
c.nonce = esp_random();
|
||||
return sendSecure(LINK_INNER_OTA_CMD, &c, sizeof(c), why, n);
|
||||
}
|
||||
|
||||
static uint32_t hashStr(uint32_t h, const char* s) {
|
||||
for (; *s; s++) h = (h ^ (uint8_t)*s) * 16777619u; // FNV-1a
|
||||
return h;
|
||||
}
|
||||
|
||||
/** Push A's remembered network (or a FORGET) to B. */
|
||||
static bool pushCredentials(char* why, size_t n, bool log) {
|
||||
link_wifi_creds_t c = {};
|
||||
char pass[65];
|
||||
bool have = WiFiManager::getSavedCredentials(c.ssid, sizeof(c.ssid), pass, sizeof(pass));
|
||||
if (have) {
|
||||
c.action = LINK_WIFI_SET;
|
||||
strlcpy(c.pass, pass, sizeof(c.pass));
|
||||
} else {
|
||||
c.action = LINK_WIFI_FORGET;
|
||||
}
|
||||
bool ok = sendSecure(LINK_INNER_WIFI_CREDS, &c, sizeof(c), why, n);
|
||||
memset(pass, 0, sizeof(pass));
|
||||
if (ok) {
|
||||
g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1;
|
||||
g_last_push_ms = millis();
|
||||
if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Inst. Cluster (encrypted)"
|
||||
: "[link] told Inst. Cluster to forget its Wi-Fi credentials", c.ssid);
|
||||
}
|
||||
memset(&c, 0, sizeof(c));
|
||||
return ok;
|
||||
}
|
||||
|
||||
// B lacks credentials A has, or A's changed, or A forgot them while B still has them.
|
||||
static void syncCredentials() {
|
||||
peer_status_t p = getStatus();
|
||||
if (!p.heard || !p.paired || !p.key_match) return;
|
||||
if (millis() - g_last_push_ms < CREDS_PUSH_MIN_MS && g_last_push_ms != 0) return;
|
||||
|
||||
char ssid[33], pass[65];
|
||||
bool have = WiFiManager::getSavedCredentials(ssid, sizeof(ssid), pass, sizeof(pass));
|
||||
uint32_t h = have ? hashStr(hashStr(2166136261u, ssid), pass) : 1;
|
||||
memset(pass, 0, sizeof(pass));
|
||||
bool b_has = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0;
|
||||
|
||||
bool need = have ? (!b_has || h != g_pushed_hash)
|
||||
: (b_has && g_pushed_hash != 1);
|
||||
if (!need) return;
|
||||
char why[64];
|
||||
pushCredentials(why, sizeof(why), true);
|
||||
}
|
||||
|
||||
// ---- pairing ----------------------------------------------------------------
|
||||
static bool pair(char* why, size_t n) {
|
||||
if (UARTManager::getState() == UARTManager::UART_STATE_OFF) {
|
||||
snprintf(why, n, "link is off - enable 'Send to Inst. Cluster' in Settings first");
|
||||
return false;
|
||||
}
|
||||
link_pair_t pk = {};
|
||||
pk.magic = LINK_PAIR_MAGIC;
|
||||
esp_fill_random(pk.key, LINK_KEY_LEN);
|
||||
esp_wifi_get_mac(WIFI_IF_STA, pk.a_mac);
|
||||
|
||||
uint8_t frame[PACKET_MAX_SIZE];
|
||||
size_t flen = frame_build(PACKET_TYPE_PAIR, &pk, sizeof(pk), frame);
|
||||
int sent = 0;
|
||||
for (int i = 0; i < PAIR_REPEATS; i++) {
|
||||
if (UARTManager::sendWire(frame, flen)) sent++;
|
||||
delay(40);
|
||||
}
|
||||
if (!sent) { snprintf(why, n, "UART write failed"); memset(&pk, 0, sizeof(pk)); return false; }
|
||||
|
||||
memcpy(g_key, pk.key, LINK_KEY_LEN);
|
||||
memset(&pk, 0, sizeof(pk));
|
||||
g_paired = true;
|
||||
g_key_fp = link_key_fingerprint(g_key);
|
||||
storeKey();
|
||||
g_pushed_hash = 0; // re-send the credentials under the new key
|
||||
g_last_push_ms = 0;
|
||||
print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. "
|
||||
"Inst. Cluster confirms in its next STATUS (`link status`).", sent, g_key_fp);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- public: requests (UI) --------------------------------------------------
|
||||
static bool bReady(char* why, size_t n, bool need_parked) {
|
||||
peer_status_t p = getStatus();
|
||||
if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard - is it powered?"); return false; }
|
||||
if (!p.paired || !p.key_match) {
|
||||
snprintf(why, n, "Inst. Cluster is not paired with this controller (console: link pair, wire connected)");
|
||||
return false;
|
||||
}
|
||||
if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) {
|
||||
snprintf(why, n, "Inst. Cluster has no Wi-Fi credentials yet - join a network on this screen first");
|
||||
return false;
|
||||
}
|
||||
if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) {
|
||||
snprintf(why, n, "Inst. Cluster is busy (%s)", phaseName(p.st.ota_phase));
|
||||
return false;
|
||||
}
|
||||
if (need_parked && !Ota::isParked(why, n)) return false;
|
||||
// Same network as B => same radio channel, so B's STATUS frames (progress)
|
||||
// keep reaching this screen while B is joined.
|
||||
if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) {
|
||||
snprintf(why, n, "join Wi-Fi on this controller first, so Inst. Cluster's progress can be followed");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool requestCheck(char* why, size_t n) {
|
||||
if (!bReady(why, n, false)) { print("[link] check refused: %s", why); return false; }
|
||||
return sendOtaCmd(LINK_OTA_CMD_CHECK, 0, why, n);
|
||||
}
|
||||
|
||||
bool requestInstall(char* why, size_t n) {
|
||||
if (!bReady(why, n, true)) { print("[link] install refused: %s", why); return false; }
|
||||
return sendOtaCmd(LINK_OTA_CMD_INSTALL, 0, why, n);
|
||||
}
|
||||
|
||||
// ---- lifecycle --------------------------------------------------------------
|
||||
void init() {
|
||||
if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex();
|
||||
loadKey();
|
||||
EspNowLink::setReceiveHandler(onFrame);
|
||||
print("[link] Inst. Cluster: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected");
|
||||
}
|
||||
|
||||
void tick() {
|
||||
static uint32_t last = 0;
|
||||
static bool was_heard = false;
|
||||
static uint8_t last_phase = 0xFF;
|
||||
static bool was_match = false;
|
||||
if (millis() - last < 1000) return;
|
||||
last = millis();
|
||||
|
||||
peer_status_t p = getStatus();
|
||||
if (p.heard != was_heard) {
|
||||
was_heard = p.heard;
|
||||
if (p.heard) print("[link] Inst. Cluster heard: %s, %s, %lu s up", p.st.version,
|
||||
p.key_match ? "paired" : (p.st.key_fp ? "paired with ANOTHER key" : "unpaired"),
|
||||
(unsigned long)p.st.uptime_s);
|
||||
else print("[link] Inst. Cluster silent for %lu s", (unsigned long)(p.age_ms / 1000));
|
||||
}
|
||||
if (p.heard && p.key_match && !was_match) {
|
||||
print("[link] Inst. Cluster confirmed pairing (fingerprint %04X)", p.st.key_fp);
|
||||
}
|
||||
was_match = p.heard && p.key_match;
|
||||
if (p.heard && p.st.ota_phase != last_phase) {
|
||||
if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE)
|
||||
print("[link] Inst. Cluster update: %s%s%s%s%s", phaseName(p.st.ota_phase),
|
||||
p.st.latest[0] ? ", latest " : "", p.st.latest,
|
||||
p.st.ota_phase == LINK_OTA_FAILED ? " - " : "",
|
||||
p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : "");
|
||||
last_phase = p.st.ota_phase;
|
||||
}
|
||||
syncCredentials();
|
||||
}
|
||||
|
||||
// ---- console ----------------------------------------------------------------
|
||||
static void help() {
|
||||
print("link status Inst. Cluster: version, pairing, update phase");
|
||||
print("link pair new shared key -> B over the UART wire (bench, wire connected)");
|
||||
print("link unpair forget the key here (B keeps its own until re-paired)");
|
||||
print("link creds send the remembered Wi-Fi network to B now");
|
||||
print("link ota check|install [force]|rollback drive B's updater");
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
if (strncmp(line, "link", 4) != 0 || (line[4] != 0 && line[4] != ' ')) return false;
|
||||
const char* a = line + 4;
|
||||
while (*a == ' ') a++;
|
||||
char why[96] = "";
|
||||
|
||||
if (!*a || !strcmp(a, "help")) { help(); return true; }
|
||||
if (!strcmp(a, "status")) {
|
||||
peer_status_t p = getStatus();
|
||||
print("[link] this side: %s (fingerprint %04X) | STATUS frames %lu | SECURE sent %lu, failed %lu",
|
||||
p.paired ? "paired" : "NOT paired", p.key_fp, (unsigned long)g_status_count,
|
||||
(unsigned long)g_secure_sent, (unsigned long)g_secure_fail);
|
||||
if (!g_ever_heard) { print("[link] Inst. Cluster never heard"); return true; }
|
||||
print("[link] Inst. Cluster %02X:%02X:%02X:%02X:%02X:%02X, %s (%lu s ago)",
|
||||
p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5],
|
||||
p.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000));
|
||||
print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s",
|
||||
p.st.version, p.st.key_fp, p.key_match ? "matches" : p.st.key_fp ? "DIFFERENT" : "none",
|
||||
(p.st.flags & LINK_STATUS_HAVE_WIFI) ? "yes" : "no",
|
||||
(p.st.flags & LINK_STATUS_WIFI_JOINED) ? ", joined" : "",
|
||||
(p.st.flags & LINK_STATUS_PENDING_VERIFY) ? " | fresh image, unconfirmed" : "");
|
||||
print("[link] update: %s%s%s%s%s | up %lu s | heap %lu",
|
||||
phaseName(p.st.ota_phase),
|
||||
p.st.latest[0] ? ", latest " : "", p.st.latest,
|
||||
p.st.message[0] ? " - " : "", p.st.message,
|
||||
(unsigned long)p.st.uptime_s, (unsigned long)p.st.free_heap);
|
||||
return true;
|
||||
}
|
||||
if (!strcmp(a, "pair")) { if (!pair(why, sizeof(why))) print("[link] pair refused: %s", why); return true; }
|
||||
if (!strcmp(a, "unpair")) { clearKey(); print("[link] pairing key removed here"); return true; }
|
||||
if (!strcmp(a, "creds")) {
|
||||
if (!pushCredentials(why, sizeof(why), true)) print("[link] creds refused: %s", why);
|
||||
return true;
|
||||
}
|
||||
if (!strncmp(a, "ota", 3)) {
|
||||
const char* b = a + 3;
|
||||
while (*b == ' ') b++;
|
||||
bool ok = false;
|
||||
if (!strcmp(b, "check")) ok = requestCheck(why, sizeof(why));
|
||||
else if (!strcmp(b, "install")) ok = requestInstall(why, sizeof(why));
|
||||
else if (!strcmp(b, "install force")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_INSTALL, LINK_OTA_FORCE, why, sizeof(why));
|
||||
else if (!strcmp(b, "rollback")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_ROLLBACK, 0, why, sizeof(why));
|
||||
else { help(); return true; }
|
||||
print(ok ? "[link] command sent to Inst. Cluster - watch `link status`" : "[link] refused: %s", why);
|
||||
return true;
|
||||
}
|
||||
help();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace LinkPeer
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Link Peer Module (Main CTRL) - what A knows about Inst. Cluster, and the
|
||||
* maintenance traffic that keeps B updatable. See
|
||||
* ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md (B's wiki).
|
||||
*
|
||||
* STATUS B -> A ESP-NOW unicast every 5 s: B's version, OTA phase, uptime.
|
||||
* Shown on Settings -> Updates as the "Inst. Cluster" card.
|
||||
* PAIR A -> B `link pair` on the console, UART WIRE ONLY: a fresh random
|
||||
* key, kept in NVS on both sides. Both repos are public, so
|
||||
* this is the only secret and it never travels by radio.
|
||||
* SECURE A -> B ESP-NOW unicast, AES-256-GCM under the pairing key:
|
||||
* the remembered Wi-Fi credentials (pushed automatically
|
||||
* whenever B lacks them or they change) and OTA commands.
|
||||
*
|
||||
* Console: link status | pair | unpair | creds | ota check | ota install [force] | ota rollback
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "protocol/automotive_data.h"
|
||||
|
||||
namespace LinkPeer {
|
||||
|
||||
/** Load the pairing key, hook the ESP-NOW receive path. After EspNowLink::init(). */
|
||||
void init();
|
||||
|
||||
/** Credential sync + logging. Call from loop(). */
|
||||
void tick();
|
||||
|
||||
typedef struct {
|
||||
bool heard; // STATUS within LINK_STATUS_TIMEOUT_MS
|
||||
uint32_t age_ms; // since the last STATUS
|
||||
uint8_t mac[6]; // B's STA MAC
|
||||
link_status_t st; // last STATUS as received
|
||||
bool paired; // this controller holds a pairing key
|
||||
bool key_match; // B reports the fingerprint of OUR key
|
||||
uint16_t key_fp; // our key's fingerprint (0 = none)
|
||||
} peer_status_t;
|
||||
|
||||
peer_status_t getStatus();
|
||||
|
||||
/** Ask B to check / install (behind the same parking gate as A's own update). */
|
||||
bool requestCheck(char* why, size_t n);
|
||||
bool requestInstall(char* why, size_t n);
|
||||
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
} // namespace LinkPeer
|
||||
+74
-11
@@ -40,6 +40,8 @@ extern "C" bool verifyRollbackLater() { return true; }
|
||||
|
||||
namespace Ota {
|
||||
|
||||
static void setNoticeProgress(int pct); // defined with the full-screen notice below
|
||||
|
||||
#define OTA_CONFIRM_S 30 // healthy uptime before a new image is kept
|
||||
#define TOSTR_(x) #x
|
||||
#define TOSTR(x) TOSTR_(x)
|
||||
@@ -142,7 +144,7 @@ static const char* stateName(esp_ota_img_states_t s) {
|
||||
|
||||
/**
|
||||
* The vehicle must be parked to update: installing ends in a reboot that blanks
|
||||
* Controller B's gauges. A silent bus (ignition off, or the bench) counts as
|
||||
* Inst. Cluster's gauges. A silent bus (ignition off, or the bench) counts as
|
||||
* parked. Lever UNKNOWN is allowed so a missing gear frame can't block a bench
|
||||
* update; engine and output shaft are the checks that matter.
|
||||
*/
|
||||
@@ -382,7 +384,9 @@ static bool writeImage(const manifest_t& m, const esp_partition_t* part) {
|
||||
err = esp_ota_write(h, buf, r);
|
||||
if (err != ESP_OK) { print("[ota] flash write: %s", esp_err_to_name(err)); ok = false; break; }
|
||||
got += r;
|
||||
int decile = (int)((uint64_t)got * 10 / m.size);
|
||||
int pct = (int)((uint64_t)got * 100 / m.size);
|
||||
setNoticeProgress(pct);
|
||||
int decile = pct / 10;
|
||||
if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; }
|
||||
}
|
||||
http.end();
|
||||
@@ -407,10 +411,18 @@ static bool writeImage(const manifest_t& m, const esp_partition_t* part) {
|
||||
}
|
||||
|
||||
// ---- Full-screen notice on lv_layer_top() (above every screen) ----------------
|
||||
// Since the core runs with XIP from PSRAM and an IRAM-safe RGB refill ISR
|
||||
// (2026-09-27), flash writes no longer blank the panel, so the screen stays ON
|
||||
// during the download and shows a progress bar. The user must see that the
|
||||
// update is alive; a dark screen invited switching the ignition off mid-write.
|
||||
static lv_obj_t* g_notice = NULL;
|
||||
static lv_obj_t* g_notice_lbl = NULL;
|
||||
static lv_obj_t* g_notice_bar = NULL;
|
||||
static lv_obj_t* g_notice_pct = NULL;
|
||||
static lv_obj_t* g_notice_warn = NULL;
|
||||
static int g_notice_last_pct = -1;
|
||||
|
||||
static void showNotice(const char* text) {
|
||||
static void showNotice(const char* text, bool with_progress = false) {
|
||||
lvgl_port_lock(-1);
|
||||
if (g_notice == NULL) {
|
||||
g_notice = lv_obj_create(lv_layer_top());
|
||||
@@ -419,17 +431,69 @@ static void showNotice(const char* text) {
|
||||
lv_obj_set_style_bg_color(g_notice, lv_color_black(), 0);
|
||||
lv_obj_set_style_bg_opa(g_notice, LV_OPA_COVER, 0);
|
||||
lv_obj_add_flag(g_notice, LV_OBJ_FLAG_CLICKABLE); // swallow touches while shown
|
||||
|
||||
g_notice_lbl = lv_label_create(g_notice);
|
||||
lv_obj_set_style_text_font(g_notice_lbl, &lv_font_montserrat_30, 0);
|
||||
lv_obj_set_style_text_color(g_notice_lbl, lv_color_white(), 0);
|
||||
lv_obj_set_style_text_align(g_notice_lbl, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_center(g_notice_lbl);
|
||||
lv_obj_align(g_notice_lbl, LV_ALIGN_CENTER, 0, -90);
|
||||
|
||||
g_notice_bar = lv_bar_create(g_notice);
|
||||
lv_obj_set_size(g_notice_bar, 640, 28);
|
||||
lv_obj_align(g_notice_bar, LV_ALIGN_CENTER, 0, 10);
|
||||
lv_bar_set_range(g_notice_bar, 0, 100);
|
||||
lv_bar_set_value(g_notice_bar, 0, LV_ANIM_OFF);
|
||||
lv_obj_set_style_bg_color(g_notice_bar, lv_color_hex(0x252D36), LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_opa(g_notice_bar, LV_OPA_COVER, LV_PART_MAIN);
|
||||
lv_obj_set_style_radius(g_notice_bar, 14, LV_PART_MAIN);
|
||||
lv_obj_set_style_bg_color(g_notice_bar, lv_color_hex(0x3DA9FC), LV_PART_INDICATOR);
|
||||
lv_obj_set_style_bg_opa(g_notice_bar, LV_OPA_COVER, LV_PART_INDICATOR);
|
||||
lv_obj_set_style_radius(g_notice_bar, 14, LV_PART_INDICATOR);
|
||||
|
||||
g_notice_pct = lv_label_create(g_notice);
|
||||
lv_obj_set_style_text_font(g_notice_pct, &lv_font_montserrat_24, 0);
|
||||
lv_obj_set_style_text_color(g_notice_pct, lv_color_white(), 0);
|
||||
lv_label_set_text(g_notice_pct, "0%");
|
||||
lv_obj_align_to(g_notice_pct, g_notice_bar, LV_ALIGN_OUT_BOTTOM_MID, 0, 12);
|
||||
|
||||
g_notice_warn = lv_label_create(g_notice);
|
||||
lv_obj_set_style_text_font(g_notice_warn, &lv_font_montserrat_24, 0);
|
||||
lv_obj_set_style_text_color(g_notice_warn, lv_color_hex(0xF5A524), 0);
|
||||
lv_obj_set_style_text_align(g_notice_warn, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_label_set_text(g_notice_warn, LV_SYMBOL_WARNING " Do not switch off the ignition");
|
||||
lv_obj_align(g_notice_warn, LV_ALIGN_CENTER, 0, 130);
|
||||
}
|
||||
lv_label_set_text(g_notice_lbl, text);
|
||||
if (with_progress) {
|
||||
lv_bar_set_value(g_notice_bar, 0, LV_ANIM_OFF);
|
||||
lv_label_set_text(g_notice_pct, "0%");
|
||||
lv_obj_clear_flag(g_notice_bar, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(g_notice_pct, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(g_notice_warn, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag(g_notice_bar, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(g_notice_pct, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(g_notice_warn, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
g_notice_last_pct = -1;
|
||||
lv_obj_clear_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
/** Progress bar update from the download loop (loop task). Cheap: one bar + label. */
|
||||
static void setNoticeProgress(int pct) {
|
||||
if (pct < 0) pct = 0;
|
||||
if (pct > 100) pct = 100;
|
||||
if (pct == g_notice_last_pct || g_notice_bar == NULL) return;
|
||||
g_notice_last_pct = pct;
|
||||
char t[8];
|
||||
snprintf(t, sizeof(t), "%d%%", pct);
|
||||
if (!lvgl_port_lock(50)) return; // never stall the download on the UI lock
|
||||
lv_bar_set_value(g_notice_bar, pct, LV_ANIM_OFF);
|
||||
lv_label_set_text(g_notice_pct, t);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
static void hideNotice() {
|
||||
lvgl_port_lock(-1);
|
||||
if (g_notice) lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
|
||||
@@ -457,15 +521,13 @@ static void install(bool force) {
|
||||
|
||||
print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size);
|
||||
|
||||
// Flash writes stall the PSRAM-fed RGB panel (flicker), so the screen is
|
||||
// dark while the image is written, with a notice before and after.
|
||||
// The screen stays on: with XIP from PSRAM + an IRAM-safe RGB refill ISR the
|
||||
// flash writes no longer starve the panel (verified 2026-09-27: 24 frames/s
|
||||
// for the whole download). The bar is driven from the download loop.
|
||||
char msg[160];
|
||||
snprintf(msg, sizeof(msg), "Updating to %s\n\nThe screen goes dark for about a minute.\nDo not switch off.", m.version);
|
||||
showNotice(msg);
|
||||
delay(3000); // time to read it; LVGL renders on its own task
|
||||
DisplayInit::setBacklight(false);
|
||||
snprintf(msg, sizeof(msg), "Updating to %s", m.version);
|
||||
showNotice(msg, true);
|
||||
bool ok = writeImage(m, part);
|
||||
DisplayInit::setBacklight(true);
|
||||
|
||||
// The download took a while - the driver may have started the engine since.
|
||||
if (ok && !gate(false)) {
|
||||
@@ -623,6 +685,7 @@ ui_status_t getStatus() {
|
||||
|
||||
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); }
|
||||
bool isParked(char* why, size_t n) { return parked(why, n); }
|
||||
|
||||
void init() {
|
||||
const esp_partition_t* run = esp_ota_get_running_partition();
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
* or crash before that makes the bootloader fall back to the old slot.
|
||||
*
|
||||
* Needs Wi-Fi joined to a network with internet (Settings screen). Joining an
|
||||
* AP moves the radio channel; the ESP-NOW link to Controller B follows it.
|
||||
* AP moves the radio channel; the ESP-NOW link to Inst. Cluster follows it.
|
||||
* See wiki/pages/ota-updates.md.
|
||||
*/
|
||||
|
||||
@@ -66,6 +66,9 @@ ui_status_t getStatus();
|
||||
bool requestCheck(char* why, size_t n);
|
||||
bool requestInstall(char* why, size_t n);
|
||||
|
||||
/** The parking gate on its own (Inst. Cluster's install is guarded by it too). */
|
||||
bool isParked(char* why, size_t n);
|
||||
|
||||
} // namespace Ota
|
||||
|
||||
#endif // OTA_UPDATE_H
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* Performance Monitor implementation. See perf_monitor.h.
|
||||
*
|
||||
* onFrame()/onFlush() run in the LVGL task; everything else in loop(). The
|
||||
* counters are plain 32-bit words read under a short critical section, so the
|
||||
* hooks cost nothing measurable.
|
||||
*/
|
||||
|
||||
#include "perf_monitor.h"
|
||||
#include "serial_lock.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include <lvgl.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <esp_heap_caps.h>
|
||||
#include <esp_timer.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace PerfMon {
|
||||
|
||||
// ---- accumulators (LVGL task writes, loop reads) ---------------------------
|
||||
static portMUX_TYPE g_mux = portMUX_INITIALIZER_UNLOCKED;
|
||||
static uint32_t g_frames = 0;
|
||||
static uint32_t g_frame_ms_sum = 0;
|
||||
static uint32_t g_frame_ms_max = 0;
|
||||
static uint32_t g_frame_px_sum = 0;
|
||||
static uint32_t g_flushes = 0;
|
||||
static uint32_t g_flush_us_sum = 0;
|
||||
static uint32_t g_flush_px_sum = 0;
|
||||
|
||||
// vsync counters: written from the panel ISR, read from the reporter. 32-bit
|
||||
// aligned loads/stores are atomic on this core; no lock in the ISR.
|
||||
static volatile uint32_t g_vsync_count = 0;
|
||||
static volatile uint32_t g_vsync_gap_max_us = 0;
|
||||
static volatile uint32_t g_vsync_last_us = 0;
|
||||
|
||||
static esp_timer_handle_t g_timer = NULL;
|
||||
|
||||
// ---- window bookkeeping (loop) --------------------------------------------
|
||||
static int64_t g_window_start_us = 0;
|
||||
static uint64_t g_idle_start[2] = {0, 0};
|
||||
static bool g_periodic = false;
|
||||
static uint32_t g_period_ms = 1000;
|
||||
static uint32_t g_last_report_ms = 0;
|
||||
|
||||
static void print(const char* fmt, ...) {
|
||||
char buf[240];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
static uint64_t idleCounter(int core) {
|
||||
#if CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
|
||||
// Run-time counter unit is microseconds (esp_timer) on ESP-IDF.
|
||||
return (uint64_t)ulTaskGetIdleRunTimeCounterForCore(core);
|
||||
#else
|
||||
(void)core;
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void timerCallback(void* arg);
|
||||
|
||||
static void resetWindow() {
|
||||
portENTER_CRITICAL(&g_mux);
|
||||
g_frames = g_frame_ms_sum = g_frame_ms_max = g_frame_px_sum = 0;
|
||||
g_flushes = g_flush_us_sum = g_flush_px_sum = 0;
|
||||
portEXIT_CRITICAL(&g_mux);
|
||||
g_vsync_count = 0;
|
||||
g_vsync_gap_max_us = 0;
|
||||
g_window_start_us = esp_timer_get_time();
|
||||
g_idle_start[0] = idleCounter(0);
|
||||
g_idle_start[1] = idleCounter(1);
|
||||
}
|
||||
|
||||
void init() {
|
||||
resetWindow();
|
||||
if (!g_timer) {
|
||||
esp_timer_create_args_t a = {};
|
||||
a.callback = timerCallback;
|
||||
a.arg = NULL;
|
||||
a.dispatch_method = ESP_TIMER_TASK;
|
||||
a.name = "perf";
|
||||
esp_timer_create(&a, &g_timer);
|
||||
}
|
||||
}
|
||||
|
||||
void onFrame(uint32_t time_ms, uint32_t px) {
|
||||
portENTER_CRITICAL(&g_mux);
|
||||
g_frames++;
|
||||
g_frame_ms_sum += time_ms;
|
||||
if (time_ms > g_frame_ms_max) g_frame_ms_max = time_ms;
|
||||
g_frame_px_sum += px;
|
||||
portEXIT_CRITICAL(&g_mux);
|
||||
}
|
||||
|
||||
void onFlush(uint32_t time_us, uint32_t px) {
|
||||
portENTER_CRITICAL(&g_mux);
|
||||
g_flushes++;
|
||||
g_flush_us_sum += time_us;
|
||||
g_flush_px_sum += px;
|
||||
portEXIT_CRITICAL(&g_mux);
|
||||
}
|
||||
|
||||
void IRAM_ATTR onVsync() {
|
||||
uint32_t now = (uint32_t)esp_timer_get_time();
|
||||
uint32_t last = g_vsync_last_us;
|
||||
g_vsync_last_us = now;
|
||||
g_vsync_count = g_vsync_count + 1;
|
||||
if (last != 0) {
|
||||
uint32_t gap = now - last;
|
||||
if (gap > g_vsync_gap_max_us) g_vsync_gap_max_us = gap;
|
||||
}
|
||||
}
|
||||
|
||||
/** Emit one PERF line for the window since the last reset, then reset. */
|
||||
static void report() {
|
||||
int64_t now_us = esp_timer_get_time();
|
||||
uint64_t win_us = (uint64_t)(now_us - g_window_start_us);
|
||||
if (win_us < 1000) win_us = 1000;
|
||||
|
||||
uint32_t frames, ms_sum, ms_max, px_sum, flushes, fl_us, fl_px;
|
||||
portENTER_CRITICAL(&g_mux);
|
||||
frames = g_frames; ms_sum = g_frame_ms_sum; ms_max = g_frame_ms_max; px_sum = g_frame_px_sum;
|
||||
flushes = g_flushes; fl_us = g_flush_us_sum; fl_px = g_flush_px_sum;
|
||||
portEXIT_CRITICAL(&g_mux);
|
||||
|
||||
uint32_t vsyncs = g_vsync_count;
|
||||
uint32_t vgap = g_vsync_gap_max_us;
|
||||
unsigned vsync_per_s = (unsigned)((uint64_t)vsyncs * 1000000ULL / win_us);
|
||||
|
||||
uint64_t idle0 = idleCounter(0) - g_idle_start[0];
|
||||
uint64_t idle1 = idleCounter(1) - g_idle_start[1];
|
||||
unsigned idle0_pct = (unsigned)((idle0 * 100) / win_us);
|
||||
unsigned idle1_pct = (unsigned)((idle1 * 100) / win_us);
|
||||
if (idle0_pct > 100) idle0_pct = 100;
|
||||
if (idle1_pct > 100) idle1_pct = 100;
|
||||
|
||||
// fps x10 for one decimal without floats in the format
|
||||
unsigned fps10 = (unsigned)((uint64_t)frames * 10000000ULL / win_us);
|
||||
unsigned avg_ms10 = frames ? (ms_sum * 10) / frames : 0;
|
||||
unsigned kpx = frames ? (px_sum / frames) / 1000 : 0;
|
||||
unsigned flush_ms_per_s = (unsigned)(((uint64_t)fl_us * 1000ULL) / win_us); // ms of copying per second
|
||||
|
||||
unsigned lv_idle = 0;
|
||||
if (lvgl_port_lock_available()) {
|
||||
lv_idle = lv_timer_get_idle();
|
||||
}
|
||||
|
||||
print("PERF,%lu,%u.%u,%u.%u,%lu,%u,%u,%u,%u,%u,%u,%u,%u,%u,%lu",
|
||||
(unsigned long)millis(),
|
||||
fps10 / 10, fps10 % 10,
|
||||
avg_ms10 / 10, avg_ms10 % 10,
|
||||
(unsigned long)ms_max,
|
||||
kpx,
|
||||
flush_ms_per_s,
|
||||
lv_idle,
|
||||
idle0_pct, idle1_pct,
|
||||
(unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
|
||||
(unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
|
||||
(unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM),
|
||||
vsync_per_s, (unsigned long)vgap);
|
||||
(void)flushes; (void)fl_px;
|
||||
resetWindow();
|
||||
}
|
||||
|
||||
static void help() {
|
||||
print("perf one PERF line for the window since the last report");
|
||||
print("perf on [sec] PERF line every <sec> seconds (default 1) while you provoke symptoms");
|
||||
print("perf off");
|
||||
print("PERF,ts,fps,avg_ms,max_ms,kpx/frame,flush_ms/s,lvgl_idle%%,idle0%%,idle1%%,int_free,int_largest,psram_free,vsync/s,vsync_gap_max_us");
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
char buf[48];
|
||||
strncpy(buf, line, sizeof(buf) - 1);
|
||||
buf[sizeof(buf) - 1] = 0;
|
||||
char* argv[3] = {0};
|
||||
int argc = 0;
|
||||
for (char* tok = strtok(buf, " \t"); tok && argc < 3; tok = strtok(NULL, " \t")) argv[argc++] = tok;
|
||||
if (argc == 0 || strcmp(argv[0], "perf") != 0) return false;
|
||||
|
||||
if (argc == 1) { report(); return true; }
|
||||
if (!strcmp(argv[1], "help")) { help(); return true; }
|
||||
if (!strcmp(argv[1], "on")) {
|
||||
long s = (argc == 3) ? strtol(argv[2], NULL, 10) : 1;
|
||||
if (s < 1) s = 1;
|
||||
if (s > 60) s = 60;
|
||||
g_period_ms = (uint32_t)s * 1000;
|
||||
g_periodic = true;
|
||||
g_last_report_ms = millis();
|
||||
resetWindow();
|
||||
// esp_timer, not loop(): the OTA job blocks loop() for the whole download
|
||||
// and that is exactly when we want to see the panel counters.
|
||||
if (g_timer) esp_timer_stop(g_timer);
|
||||
if (g_timer) esp_timer_start_periodic(g_timer, (uint64_t)g_period_ms * 1000ULL);
|
||||
print("[perf] periodic every %ld s (columns: ts,fps,avg_ms,max_ms,kpx,flush_ms/s,lv_idle,idle0,idle1,int_free,int_largest,psram,vsync/s,vsync_gap_max_us)", s);
|
||||
return true;
|
||||
}
|
||||
if (!strcmp(argv[1], "off")) {
|
||||
g_periodic = false;
|
||||
if (g_timer) esp_timer_stop(g_timer);
|
||||
print("[perf] periodic off");
|
||||
return true;
|
||||
}
|
||||
help();
|
||||
return true;
|
||||
}
|
||||
|
||||
static void timerCallback(void* arg) {
|
||||
(void)arg;
|
||||
if (g_periodic) report();
|
||||
}
|
||||
|
||||
void tick() {
|
||||
// Reporting moved to the esp_timer (see handleCommand "on").
|
||||
}
|
||||
|
||||
} // namespace PerfMon
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Performance Monitor
|
||||
*
|
||||
* Measures what the display pipeline actually does, so display experiments
|
||||
* (bounce buffers, draw-buffer size, XIP from PSRAM - wiki open question #13)
|
||||
* can be compared with numbers instead of impressions:
|
||||
*
|
||||
* - render frames/s and ms per frame (LVGL's monitor_cb: render + flush)
|
||||
* - time spent copying pixels into the PSRAM framebuffer (flush_cb)
|
||||
* - LVGL task idle % (lv_timer_get_idle)
|
||||
* - CPU idle % per core (FreeRTOS run-time stats)
|
||||
* - internal heap, largest block, PSRAM free
|
||||
*
|
||||
* Console:
|
||||
* perf one line for the last window
|
||||
* perf on [sec] print a PERF, line every <sec> s (default 1) - use while
|
||||
* provoking symptoms (Wi-Fi scan, tuning save, OTA)
|
||||
* perf off
|
||||
*
|
||||
* PERF line (CSV, greppable like CANRAW):
|
||||
* PERF,<ts_ms>,<fps>,<avg_ms>,<max_ms>,<kpx/frame>,<flush_ms/s>,
|
||||
* <lvgl_idle%>,<idle0%>,<idle1%>,<int_free>,<int_largest>,<psram_free>,
|
||||
* <vsync/s>,<vsync_gap_max_us>
|
||||
* vsync/s is the panel's own refresh rate (constant when healthy);
|
||||
* vsync_gap_max_us is the longest interval between two refreshes in the
|
||||
* window - a DMA underrun/restart stretches it.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace PerfMon {
|
||||
|
||||
/** Call once in setup(), before the LVGL port starts. */
|
||||
void init();
|
||||
|
||||
/** Hook for lv_disp_drv_t::monitor_cb - one rendered frame (ms, pixels). */
|
||||
void onFrame(uint32_t time_ms, uint32_t px);
|
||||
|
||||
/** Hook for the flush callback - one pixel copy into the framebuffer. */
|
||||
void onFlush(uint32_t time_us, uint32_t px);
|
||||
|
||||
/**
|
||||
* Hook for the RGB panel's refresh-finished (vsync) interrupt. ISR context:
|
||||
* counts frames the panel actually completed and the longest gap between two,
|
||||
* which is where a DMA underrun / restart (flicker, dots) shows up.
|
||||
*/
|
||||
void onVsync();
|
||||
|
||||
/** Console line beginning with "perf". */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
/**
|
||||
* Kept for compatibility; periodic reporting now runs from an esp_timer so it
|
||||
* survives a blocked loop() (the OTA job). Safe to call, does nothing.
|
||||
*/
|
||||
void tick();
|
||||
|
||||
} // namespace PerfMon
|
||||
@@ -19,6 +19,8 @@ static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
|
||||
static const char* NVS_KEY_UART_ENABLED = "uart_en";
|
||||
static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
|
||||
static const char* NVS_KEY_CAN_ENABLED = "can_en";
|
||||
static const char* NVS_KEY_DIFFLOCK_ENABLED = "difflock_en";
|
||||
static const char* NVS_KEY_DIFFLOCK_INVERT = "difflock_inv";
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
@@ -89,4 +91,32 @@ bool loadCANState() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void saveDiffLockState(bool enabled) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_DIFFLOCK_ENABLED, enabled);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved DiffLock state = %s\n", enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
bool loadDiffLockState() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool enabled = preferences.getBool(NVS_KEY_DIFFLOCK_ENABLED, false); // default: OFF
|
||||
preferences.end();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void saveDiffLockInvert(bool inverted) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_DIFFLOCK_INVERT, inverted);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved DiffLock polarity = %s\n", inverted ? "INVERTED" : "normal");
|
||||
}
|
||||
|
||||
bool loadDiffLockInvert() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool inverted = preferences.getBool(NVS_KEY_DIFFLOCK_INVERT, false); // default: current = locked
|
||||
preferences.end();
|
||||
return inverted;
|
||||
}
|
||||
|
||||
} // namespace SettingsManager
|
||||
|
||||
@@ -66,4 +66,12 @@ void saveCANState(bool enabled);
|
||||
*/
|
||||
bool loadCANState();
|
||||
|
||||
/** Diff-lock inputs DI0/DI1 read (DiffLocks). Default OFF. */
|
||||
void saveDiffLockState(bool enabled);
|
||||
bool loadDiffLockState();
|
||||
|
||||
/** Diff-lock polarity: true = no current means locked. Default false. */
|
||||
void saveDiffLockInvert(bool inverted);
|
||||
bool loadDiffLockInvert();
|
||||
|
||||
} // namespace SettingsManager
|
||||
|
||||
+199
-44
@@ -7,6 +7,8 @@
|
||||
#include "driveline_screen.h"
|
||||
#include "wifi_manager.h"
|
||||
#include "ota_update.h"
|
||||
#include "link_peer.h"
|
||||
#include "diff_locks.h"
|
||||
#include "uart_manager.h"
|
||||
#include "espnow_link.h"
|
||||
#include "settings_manager.h"
|
||||
@@ -81,6 +83,9 @@ static Ota::phase_t g_upd_refusal_phase = Ota::PHASE_IDLE;
|
||||
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_diff = NULL;
|
||||
static lv_obj_t* g_sys_diff_inv = NULL; // polarity: no current = locked
|
||||
static lv_obj_t* g_sys_diff_sub = NULL; // sub-line of the diff-lock row: live state
|
||||
static lv_obj_t* g_sys_info = NULL; // values column; keys are static
|
||||
|
||||
static void refresh(bool force);
|
||||
@@ -207,7 +212,7 @@ 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);
|
||||
snprintf(text, sizeof(text), "Main CTRL will no longer join \"%s\" by itself.", s.saved_ssid);
|
||||
confirm("Forget this network?", text, "Forget", onForgetConfirmed, NULL);
|
||||
}
|
||||
|
||||
@@ -402,7 +407,7 @@ static void buildWifiPage(lv_obj_t* page) {
|
||||
|
||||
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.",
|
||||
"The link to Inst. Cluster 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));
|
||||
@@ -510,9 +515,17 @@ static void buildPasswordOverlay() {
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// UPDATES PAGE
|
||||
// UPDATES PAGE - Main CTRL (this board) and Inst. Cluster (over the link)
|
||||
// ============================================================================
|
||||
|
||||
static lv_obj_t* g_b_installed = NULL;
|
||||
static lv_obj_t* g_b_latest = NULL;
|
||||
static lv_obj_t* g_b_state = NULL;
|
||||
static lv_obj_t* g_b_check = NULL;
|
||||
static lv_obj_t* g_b_install = NULL;
|
||||
static char g_b_refusal[96] = "";
|
||||
static uint8_t g_b_refusal_phase = LINK_OTA_IDLE;
|
||||
|
||||
static void onInstallConfirmed(bool ok, void* user) {
|
||||
(void)user;
|
||||
if (!ok) return;
|
||||
@@ -528,9 +541,8 @@ static void onInstall(lv_event_t* e) {
|
||||
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.",
|
||||
"This Controller will restart after successful update.\n\nInstrument Cluster's gauges will drop out for a few seconds.\n\n"
|
||||
"DO NOT SWITCH OFF THE IGNITION!\n\nOnly while parked with the engine off!",
|
||||
"Install", onInstallConfirmed, NULL);
|
||||
}
|
||||
|
||||
@@ -547,7 +559,36 @@ static void onGoWifi(lv_event_t* e) {
|
||||
selectPage(PAGE_WIFI);
|
||||
}
|
||||
|
||||
static void refreshUpdates() {
|
||||
static void onBInstallConfirmed(bool ok, void* user) {
|
||||
(void)user;
|
||||
if (!ok) return;
|
||||
uint8_t before = LinkPeer::getStatus().st.ota_phase;
|
||||
if (!LinkPeer::requestInstall(g_b_refusal, sizeof(g_b_refusal))) g_b_refusal_phase = before;
|
||||
else g_b_refusal[0] = 0;
|
||||
refresh(true);
|
||||
}
|
||||
|
||||
static void onBInstall(lv_event_t* e) {
|
||||
(void)e;
|
||||
LinkPeer::peer_status_t p = LinkPeer::getStatus();
|
||||
char title[64];
|
||||
snprintf(title, sizeof(title), "Install %s on Inst. Cluster?", p.st.latest);
|
||||
confirm(title,
|
||||
"Inst. Cluster joins the Wi-Fi network, downloads its new firmware and restarts; "
|
||||
"its gauges hold still meanwhile and this card shows the progress.\n\n"
|
||||
"Only while parked with the engine off.",
|
||||
"Install", onBInstallConfirmed, NULL);
|
||||
}
|
||||
|
||||
static void onBCheck(lv_event_t* e) {
|
||||
(void)e;
|
||||
uint8_t before = LinkPeer::getStatus().st.ota_phase;
|
||||
if (!LinkPeer::requestCheck(g_b_refusal, sizeof(g_b_refusal))) g_b_refusal_phase = before;
|
||||
else g_b_refusal[0] = 0;
|
||||
refresh(true);
|
||||
}
|
||||
|
||||
static void refreshUpdatesA() {
|
||||
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
|
||||
@@ -570,7 +611,7 @@ static void refreshUpdates() {
|
||||
} 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.");
|
||||
snprintf(msg + n, sizeof(msg) - n, " Connect to Wi-Fi to check again.");
|
||||
}
|
||||
setText(g_upd_state, msg);
|
||||
setTextColor(g_upd_state, col);
|
||||
@@ -590,45 +631,124 @@ static void refreshUpdates() {
|
||||
setVisible(g_upd_wifi, !wifi_ok);
|
||||
}
|
||||
|
||||
static void refreshUpdatesB() {
|
||||
LinkPeer::peer_status_t p = LinkPeer::getStatus();
|
||||
if (g_b_refusal[0] && p.st.ota_phase != g_b_refusal_phase) g_b_refusal[0] = 0;
|
||||
|
||||
bool has_wifi = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0;
|
||||
bool ready = p.heard && p.paired && p.key_match && has_wifi;
|
||||
char msg[160];
|
||||
lv_color_t col = UI_COL_MUTED;
|
||||
if (!p.heard) {
|
||||
snprintf(msg, sizeof(msg), "Inst. Cluster not heard.%s",
|
||||
p.paired ? "" : " Not paired yet: connect the wire and run 'link pair' on the console.");
|
||||
} else if (!p.paired || !p.key_match) {
|
||||
snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " Not paired with this controller. "
|
||||
"Connect the wire and run 'link pair' on the console.");
|
||||
col = UI_COL_AMBER;
|
||||
} else if (!has_wifi) {
|
||||
snprintf(msg, sizeof(msg), "Inst. Cluster has no Wi-Fi credentials yet. Join a network here; "
|
||||
"they are passed on by themselves.");
|
||||
} else {
|
||||
switch (p.st.ota_phase) {
|
||||
case LINK_OTA_CHECKING: snprintf(msg, sizeof(msg), "Inst. Cluster is checking..."); break;
|
||||
case LINK_OTA_INSTALLING: snprintf(msg, sizeof(msg), "Installing %s on Inst. Cluster... %u %%",
|
||||
p.st.latest, p.st.ota_progress); col = UI_COL_ACCENT; break;
|
||||
case LINK_OTA_UP_TO_DATE: snprintf(msg, sizeof(msg), LV_SYMBOL_OK " Inst. Cluster is up to date."); col = UI_COL_OK; break;
|
||||
case LINK_OTA_AVAILABLE: snprintf(msg, sizeof(msg), "Version %s is available for Inst. Cluster.", p.st.latest); col = UI_COL_ACCENT; break;
|
||||
case LINK_OTA_FAILED: snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", p.st.message); col = UI_COL_WARN; break;
|
||||
default: snprintf(msg, sizeof(msg), "Tap Check to look for a new version"); break;
|
||||
}
|
||||
if (p.st.flags & LINK_STATUS_PENDING_VERIFY) {
|
||||
size_t n = strlen(msg);
|
||||
snprintf(msg + n, sizeof(msg) - n, " (new firmware, confirming...)");
|
||||
}
|
||||
}
|
||||
if (g_b_refusal[0]) {
|
||||
snprintf(msg, sizeof(msg), LV_SYMBOL_WARNING " %s", g_b_refusal);
|
||||
col = UI_COL_WARN;
|
||||
}
|
||||
setText(g_b_state, msg);
|
||||
setTextColor(g_b_state, col);
|
||||
setText(g_b_installed, p.heard ? p.st.version : "-");
|
||||
setText(g_b_latest, (p.heard && p.st.latest[0]) ? p.st.latest : "-");
|
||||
|
||||
bool busy = p.heard && (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING);
|
||||
setButtonText(g_b_check, busy ? "Working..." : LV_SYMBOL_REFRESH " Check for updates");
|
||||
if (busy || !ready) lv_obj_add_state(g_b_check, LV_STATE_DISABLED);
|
||||
else lv_obj_clear_state(g_b_check, LV_STATE_DISABLED);
|
||||
|
||||
bool can_install = ready && p.st.ota_phase == LINK_OTA_AVAILABLE;
|
||||
char inst[48];
|
||||
snprintf(inst, sizeof(inst), LV_SYMBOL_DOWNLOAD " Install %s", p.st.latest);
|
||||
setButtonText(g_b_install, inst);
|
||||
setVisible(g_b_install, can_install);
|
||||
}
|
||||
|
||||
static void refreshUpdates() {
|
||||
refreshUpdatesA();
|
||||
refreshUpdatesB();
|
||||
}
|
||||
|
||||
/** One controller's card: "Name Installed vX Latest vY", a status line, a button row. */
|
||||
static lv_obj_t* controllerCard(lv_obj_t* page, const char* name, const char* installed,
|
||||
lv_obj_t** installed_lbl, lv_obj_t** latest_lbl, lv_obj_t** state_lbl) {
|
||||
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, 8, 0);
|
||||
|
||||
lv_obj_t* row = box(c, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
|
||||
lv_obj_set_style_pad_column(row, 36, 0);
|
||||
lv_obj_t* title = label(row, name, &lv_font_montserrat_24, UI_COL_TEXT);
|
||||
lv_obj_set_width(title, 190);
|
||||
|
||||
lv_obj_t* a = box(row, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(a, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_align(a, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
|
||||
lv_obj_set_style_pad_column(a, 10, 0);
|
||||
label(a, "Installed", &lv_font_montserrat_20, UI_COL_MUTED);
|
||||
*installed_lbl = label(a, installed, &lv_font_montserrat_24, UI_COL_TEXT);
|
||||
|
||||
lv_obj_t* b = box(row, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(b, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_align(b, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
|
||||
lv_obj_set_style_pad_column(b, 10, 0);
|
||||
label(b, "Latest", &lv_font_montserrat_20, UI_COL_MUTED);
|
||||
*latest_lbl = label(b, "-", &lv_font_montserrat_24, UI_COL_TEXT);
|
||||
|
||||
*state_lbl = label(c, "", &lv_font_montserrat_20, UI_COL_MUTED);
|
||||
lv_label_set_long_mode(*state_lbl, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_width(*state_lbl, LV_PCT(100));
|
||||
return c;
|
||||
}
|
||||
|
||||
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_t* installed_a = NULL;
|
||||
lv_obj_t* a = controllerCard(page, "Main CTRL", FW_VERSION, &installed_a, &g_upd_latest, &g_upd_state);
|
||||
lv_obj_t* btns = box(a, 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);
|
||||
g_upd_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 56, BTN_PRIMARY, onCheck, NULL);
|
||||
g_upd_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onInstall, NULL);
|
||||
g_upd_wifi = button(btns, LV_SYMBOL_WIFI " Wi-Fi settings", 260, 56, BTN_SECONDARY, onGoWifi, NULL);
|
||||
|
||||
lv_obj_t* b = controllerCard(page, "Inst. Cluster", "-", &g_b_installed, &g_b_latest, &g_b_state);
|
||||
btns = box(b, 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_b_check = button(btns, LV_SYMBOL_REFRESH " Check for updates", 300, 56, BTN_PRIMARY, onBCheck, NULL);
|
||||
g_b_install = button(btns, "Install", 280, 56, BTN_SUCCESS, onBInstall, 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.",
|
||||
"Each controller restarts after updating. DO NOT TURN OFF THE IGNITION DURING THE UPDATE",
|
||||
&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);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -652,10 +772,30 @@ static void onDebugSwitch(lv_event_t* e) {
|
||||
UIStateManager::setDebugEnabled(on);
|
||||
}
|
||||
|
||||
static void onDiffSwitch(lv_event_t* e) {
|
||||
if (g_refreshing) return;
|
||||
DiffLocks::setEnabled(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED));
|
||||
}
|
||||
|
||||
static void onDiffInvertSwitch(lv_event_t* e) {
|
||||
if (g_refreshing) return;
|
||||
DiffLocks::setInverted(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED));
|
||||
}
|
||||
|
||||
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());
|
||||
setChecked(g_sys_diff, DiffLocks::isEnabled());
|
||||
setChecked(g_sys_diff_inv, DiffLocks::isInverted());
|
||||
// live state in the sub-line, so the wiring can be tested from this page
|
||||
if (!DiffLocks::isEnabled()) setText(g_sys_diff_sub, DiffLocks::isInverted()
|
||||
? "DI0 rear, DI1 front - 0 V = locked"
|
||||
: "DI0 rear, DI1 front - 12 V = locked");
|
||||
else if (!DiffLocks::isValid()) setText(g_sys_diff_sub, "Now: reading...");
|
||||
else setText(g_sys_diff_sub, DiffLocks::frontLocked()
|
||||
? (DiffLocks::rearLocked() ? "Now: rear LOCKED, front LOCKED" : "Now: FRONT only - check DI0 wiring")
|
||||
: (DiffLocks::rearLocked() ? "Now: rear LOCKED, front open" : "Now: both open"));
|
||||
|
||||
static uint32_t last = 0; // the figures below change slowly; 1 Hz is plenty
|
||||
if (!force && millis() - last < 1000) return;
|
||||
@@ -666,18 +806,17 @@ static void refreshSystem(bool force) {
|
||||
uint32_t up = millis() / 1000;
|
||||
char buf[400];
|
||||
snprintf(buf, sizeof(buf),
|
||||
"%s (slot %s)\n"
|
||||
"%s (slot %s), up %lu h %02lu min\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",
|
||||
"%u KB internal free, %u KB PSRAM free",
|
||||
FW_VERSION, run ? run->label : "?",
|
||||
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60),
|
||||
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));
|
||||
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
|
||||
setText(g_sys_info, buf);
|
||||
}
|
||||
|
||||
@@ -690,17 +829,33 @@ static void buildSystemPage(lv_obj_t* page) {
|
||||
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);
|
||||
makeSettingRow(c, "Send to Inst. Cluster", "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);
|
||||
lv_obj_t* diff_row = makeSettingRow(c, "Diff lock inputs", "DI0 rear, DI1 front - 12 V = locked", &right);
|
||||
g_sys_diff_sub = lv_obj_get_child(lv_obj_get_child(diff_row, 0), 1);
|
||||
// two switches on the right: polarity ("Inverted") and on/off; the page has no room for a fifth row
|
||||
lv_obj_t* diff_right = box(right, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(diff_right, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
// START, not END: with END, LVGL 8's content-size pass measures only the last child
|
||||
// (the earlier ones sit at negative x) and clips "Inverted" away - seen on the board.
|
||||
// The row's SPACE_BETWEEN already pushes this box to the right edge.
|
||||
lv_obj_set_flex_align(diff_right, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
|
||||
lv_obj_set_style_pad_column(diff_right, 12, 0);
|
||||
label(diff_right, "Inverted", &lv_font_montserrat_20, UI_COL_MUTED);
|
||||
g_sys_diff_inv = toggle(diff_right, onDiffInvertSwitch, NULL);
|
||||
lv_obj_t* gap = box(diff_right, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(gap, 12, 1);
|
||||
g_sys_diff = toggle(diff_right, onDiffSwitch, 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);
|
||||
// Uptime shares the firmware line: a fourth switch row leaves no room for a fifth line (484 px page)
|
||||
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory", &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);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* 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,
|
||||
* System - CAN bus / link to Inst. Cluster / performance overlay switches,
|
||||
* live link and memory figures
|
||||
*
|
||||
* Reached by swiping LEFT on the Driveline screen; swipe right or the
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Status Overlay implementation. See status_overlay.h.
|
||||
*/
|
||||
|
||||
#include "status_overlay.h"
|
||||
#include "wifi_manager.h"
|
||||
#include "uart_manager.h"
|
||||
#include "ui_kit.h"
|
||||
#include "drivers/can_driver.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include "protocol/automotive_data.h"
|
||||
#include <lvgl.h>
|
||||
|
||||
namespace StatusOverlay {
|
||||
|
||||
#define BLINK_MS 500
|
||||
|
||||
static lv_obj_t* g_wifi = NULL;
|
||||
static lv_obj_t* g_banner = NULL;
|
||||
static bool g_banner_shown = false;
|
||||
|
||||
static const lv_color_t COL_RED_HI = lv_color_hex(0xFF3B30);
|
||||
static const lv_color_t COL_RED_LO = lv_color_hex(0x8F1A14);
|
||||
|
||||
static void setText(lv_obj_t* lbl, const char* text) {
|
||||
const char* cur = lv_label_get_text(lbl);
|
||||
if (cur != NULL && strcmp(cur, text) == 0) return;
|
||||
lv_label_set_text(lbl, text);
|
||||
}
|
||||
|
||||
static void setTextColour(lv_obj_t* o, lv_color_t c) {
|
||||
if (lv_color_to32(lv_obj_get_style_text_color(o, 0)) != lv_color_to32(c)) lv_obj_set_style_text_color(o, c, 0);
|
||||
}
|
||||
|
||||
static void setBgColour(lv_obj_t* o, lv_color_t c) {
|
||||
if (lv_color_to32(lv_obj_get_style_bg_color(o, 0)) != lv_color_to32(c)) lv_obj_set_style_bg_color(o, c, 0);
|
||||
}
|
||||
|
||||
void init() {
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
// Wi-Fi chip, fixed width so the header layout never moves
|
||||
g_wifi = lv_label_create(lv_layer_top());
|
||||
lv_obj_set_width(g_wifi, 150);
|
||||
lv_label_set_long_mode(g_wifi, LV_LABEL_LONG_DOT);
|
||||
lv_label_set_text(g_wifi, LV_SYMBOL_WIFI " --");
|
||||
lv_obj_set_style_text_font(g_wifi, &lv_font_montserrat_14, 0);
|
||||
lv_obj_set_style_text_color(g_wifi, UI_COL_MUTED, 0);
|
||||
lv_obj_set_style_bg_color(g_wifi, UI_COL_PANEL, 0);
|
||||
lv_obj_set_style_bg_opa(g_wifi, LV_OPA_COVER, 0);
|
||||
lv_obj_set_style_radius(g_wifi, 13, 0);
|
||||
lv_obj_set_style_pad_hor(g_wifi, 10, 0);
|
||||
lv_obj_set_style_pad_ver(g_wifi, 5, 0);
|
||||
lv_obj_align(g_wifi, LV_ALIGN_TOP_RIGHT, -16, 25);
|
||||
|
||||
// Alert banner, top centre
|
||||
g_banner = lv_label_create(lv_layer_top());
|
||||
lv_label_set_text(g_banner, "");
|
||||
lv_obj_set_style_text_font(g_banner, &lv_font_montserrat_20, 0);
|
||||
lv_obj_set_style_text_color(g_banner, lv_color_white(), 0);
|
||||
lv_obj_set_style_bg_color(g_banner, COL_RED_HI, 0);
|
||||
lv_obj_set_style_bg_opa(g_banner, LV_OPA_COVER, 0);
|
||||
lv_obj_set_style_radius(g_banner, 10, 0);
|
||||
lv_obj_set_style_pad_hor(g_banner, 18, 0);
|
||||
lv_obj_set_style_pad_ver(g_banner, 8, 0);
|
||||
lv_obj_align(g_banner, LV_ALIGN_TOP_MID, -20, 10);
|
||||
lv_obj_add_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
static void refreshWifi() {
|
||||
WiFiManager::status_t w = WiFiManager::getStatus();
|
||||
char txt[64];
|
||||
lv_color_t col = UI_COL_MUTED;
|
||||
switch (w.link) {
|
||||
case WiFiManager::LINK_CONNECTED: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " %s", w.ssid); col = UI_COL_TEXT; break;
|
||||
case WiFiManager::LINK_CONNECTING: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " joining..."); col = UI_COL_ACCENT; break;
|
||||
case WiFiManager::LINK_FAILED: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " failed"); col = UI_COL_AMBER; break;
|
||||
case WiFiManager::LINK_OFF: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " off"); break;
|
||||
default: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " not connected"); break;
|
||||
}
|
||||
setText(g_wifi, txt);
|
||||
setTextColour(g_wifi, col);
|
||||
}
|
||||
|
||||
static void refreshAlerts() {
|
||||
bool can_up = CANDriver::isActive();
|
||||
driveline_t dl = CANDriver::getDriveline();
|
||||
|
||||
uint16_t alerts = 0;
|
||||
uint8_t flags = 0;
|
||||
int16_t coolant = 0, gearbox = 0;
|
||||
uint16_t batt = 0;
|
||||
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
alerts = UARTManager::g_automotive_data.alerts;
|
||||
flags = UARTManager::g_automotive_data.valid_flags;
|
||||
coolant = UARTManager::g_automotive_data.coolant_temp;
|
||||
gearbox = UARTManager::g_automotive_data.gearbox_oil_temp;
|
||||
batt = UARTManager::g_automotive_data.battery_voltage;
|
||||
xSemaphoreGive(UARTManager::g_data_mutex);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
bool live = can_up && dl.ignition_on && (flags & VALID_FLAG_ALERTS);
|
||||
bool red = live && (alerts & ALERTS_RED);
|
||||
bool amber = live && !red && (alerts & ALERTS_AMBER);
|
||||
bool show = red || amber;
|
||||
|
||||
if (show != g_banner_shown) {
|
||||
g_banner_shown = show;
|
||||
if (show) lv_obj_clear_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
|
||||
else lv_obj_add_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
if (!show) return;
|
||||
|
||||
char txt[64];
|
||||
if (alerts & ALERT_COOLANT_HOT) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " COOLANT %d °C HOT", coolant / 10);
|
||||
else if (alerts & ALERT_GEARBOX_HOT) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEARBOX OIL %d °C HOT", gearbox / 10);
|
||||
else if (alerts & ALERT_GEAR_MISMATCH) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEAR MISMATCH");
|
||||
else if (alerts & ALERT_BATTERY_LOW) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " BATTERY %d.%02d V LOW", batt / 100, batt % 100);
|
||||
else snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEARBOX COOLING");
|
||||
setText(g_banner, txt);
|
||||
|
||||
if (red) {
|
||||
bool hi = (millis() / BLINK_MS) & 1;
|
||||
setBgColour(g_banner, hi ? COL_RED_HI : COL_RED_LO);
|
||||
setTextColour(g_banner, lv_color_white());
|
||||
} else {
|
||||
setBgColour(g_banner, UI_COL_AMBER);
|
||||
setTextColour(g_banner, lv_color_hex(0x1A1200));
|
||||
}
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (g_wifi == NULL) return;
|
||||
static uint32_t last = 0;
|
||||
if (millis() - last < 250) return;
|
||||
last = millis();
|
||||
lvgl_port_lock(-1);
|
||||
refreshWifi();
|
||||
refreshAlerts();
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
} // namespace StatusOverlay
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Status Overlay - what every screen shows, on lv_layer_top():
|
||||
*
|
||||
* top-right Wi-Fi chip: off / not connected / joining / <network>
|
||||
* top-centre ALERT BANNER: red and blinking (2 Hz) while any red alert from
|
||||
* Tunables' thresholds is on (coolant hot, gearbox oil hot,
|
||||
* gear mismatch, battery low), steady amber while the gearbox
|
||||
* asks for cooling. Hidden with CAN off or ignition off.
|
||||
*
|
||||
* Both are labels, so they never take touches from the screen below. tick()
|
||||
* runs from loop() and only touches an object when its text/colour changes.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace StatusOverlay {
|
||||
|
||||
/** Build the two labels. Call after DisplayInit::init(), before the screens tick. */
|
||||
void init();
|
||||
|
||||
/** Refresh from WiFiManager / the shared automotive data. Call from loop(). */
|
||||
void tick();
|
||||
|
||||
} // namespace StatusOverlay
|
||||
@@ -102,6 +102,7 @@ static void help() {
|
||||
print("cfg override off | rpm <n> | duty <n> | both <rpm> <duty>");
|
||||
print("cfg reset back to defaults");
|
||||
print("diag help OBD-II diagnostic probe (transmits on the bus)");
|
||||
print("link help Inst. Cluster: pairing, credentials, its updates");
|
||||
}
|
||||
|
||||
static bool setField(const char* name, long v) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
* Tunables Module
|
||||
*
|
||||
* Owns the link_config_t that Controller A pushes to Controller B: Patrol gauge
|
||||
* Owns the link_config_t that Main CTRL pushes to Inst. Cluster: Patrol gauge
|
||||
* calibration (tach pulses/rev, coolant PWM law) and the alert thresholds A
|
||||
* evaluates. Persisted in NVS. Editable at runtime over the USB serial console
|
||||
* ("cfg help") until a settings-screen UI exists.
|
||||
|
||||
@@ -61,9 +61,9 @@ namespace TuningScreen
|
||||
{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},
|
||||
{F_COOLANT_HOT, TAB_ALERTS, "Coolant too hot", "Alarm on Inst. Cluster at or above this temperature", 1, 0, 200, NULL},
|
||||
{F_GEARBOX_HOT, TAB_ALERTS, "Gearbox oil too hot", "Alarm on Inst. Cluster at or above this temperature", 1, 0, 200, NULL},
|
||||
{F_BATT_LOW, TAB_ALERTS, "Battery low", "Alarm on Inst. Cluster below this voltage", 10, 0, 3000, NULL},
|
||||
};
|
||||
|
||||
static const char *TAB_NAMES[TAB_COUNT] = {"Tachometer", "Coolant gauge", "Alerts", "Simulation"};
|
||||
@@ -522,7 +522,7 @@ namespace TuningScreen
|
||||
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",
|
||||
g_tach_en_sw = makeSwitchRow(g_tab_page[TAB_TACH], "Tachometer output", "IO7 on Inst. Cluster. Off = no signal",
|
||||
onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH);
|
||||
|
||||
// ---- Coolant gauge ----
|
||||
@@ -531,7 +531,7 @@ namespace TuningScreen
|
||||
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",
|
||||
g_temp_en_sw = makeSwitchRow(g_tab_page[TAB_COOLANT], "Coolant gauge output", "IO8 on Inst. Cluster. Off = no signal",
|
||||
onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP);
|
||||
|
||||
// ---- Alerts ----
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* 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.
|
||||
* excepted) and pushed to Inst. Cluster in the next CONFIG frame.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* Builds the v2 frames (DATA at 5 Hz, CONFIG on change + every CONFIG_RESEND_MS)
|
||||
* and sends each one on BOTH transports: UART1 (GPIO 44 -> SP3485 -> 485_A/B)
|
||||
* and ESP-NOW broadcast. Controller B dedupes on packet_id.
|
||||
* and ESP-NOW broadcast. Inst. Cluster dedupes on packet_id.
|
||||
*/
|
||||
|
||||
#include "uart_manager.h"
|
||||
@@ -43,36 +43,24 @@ static uart_stats_t g_uart_stats = {0};
|
||||
// CONFIG frame scheduling
|
||||
static uint8_t g_last_cfg_version_sent = 0;
|
||||
static uint32_t g_last_cfg_send_time = 0;
|
||||
static volatile bool g_port_ready = false; // Serial1.begin() done (in the task)
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPER FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Seed the shared structure until CAN data arrives.
|
||||
* @note The temperatures/voltage are marked valid so a bench without CAN still
|
||||
* exercises B's display. RPM and gear nibbles are NOT marked valid: the
|
||||
* tach output must never run on invented data.
|
||||
* @brief Start from NOTHING valid. Until a CAN frame fills a field, its valid
|
||||
* flag stays clear and B shows no value for it (user decision
|
||||
* 2026-09-28: no invented numbers, ever - the old bench defaults of
|
||||
* 89 / 85 degC and 12.45 V looked like real readings).
|
||||
*/
|
||||
static void initializeDefaultData() {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
g_automotive_data.gear_lever = DEFAULT_GEAR_LEVER;
|
||||
g_automotive_data.gear_nibbles = 0;
|
||||
g_automotive_data.engine_rpm = 0;
|
||||
g_automotive_data.gearbox_oil_temp = DEFAULT_GEARBOX_TEMP;
|
||||
g_automotive_data.engine_oil_temp = DEFAULT_ENGINE_OIL_TEMP;
|
||||
g_automotive_data.coolant_temp = DEFAULT_COOLANT_TEMP;
|
||||
g_automotive_data.battery_voltage = DEFAULT_BATTERY_VOLTAGE;
|
||||
g_automotive_data.alerts = DEFAULT_ALERTS;
|
||||
|
||||
g_automotive_data.valid_flags = VALID_FLAG_GEAR_POS |
|
||||
VALID_FLAG_GEARBOX_TEMP |
|
||||
VALID_FLAG_ENGINE_TEMP |
|
||||
VALID_FLAG_COOLANT_TEMP |
|
||||
VALID_FLAG_BATTERY_VOLT |
|
||||
VALID_FLAG_ALERTS;
|
||||
|
||||
g_automotive_data.debug_enabled = 0;
|
||||
uint8_t dbg = g_automotive_data.debug_enabled;
|
||||
memset(&g_automotive_data, 0, sizeof(g_automotive_data));
|
||||
g_automotive_data.gear_lever = LEVER_UNKNOWN;
|
||||
g_automotive_data.debug_enabled = dbg;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
}
|
||||
@@ -173,6 +161,7 @@ static void uartTask(void* parameter) {
|
||||
|
||||
Serial1.setRxBufferSize(256);
|
||||
Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
|
||||
g_port_ready = true;
|
||||
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u",
|
||||
UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION);
|
||||
|
||||
@@ -302,7 +291,7 @@ void setDebugEnabled(bool enabled) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
g_automotive_data.debug_enabled = enabled ? 1 : 0;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Controller B)",
|
||||
ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Inst. Cluster)",
|
||||
enabled ? "ENABLED" : "DISABLED");
|
||||
}
|
||||
}
|
||||
@@ -355,4 +344,10 @@ void setEnabled(bool state)
|
||||
ESP_LOGI("UARTMgr", "=============================");
|
||||
}
|
||||
|
||||
bool sendWire(const uint8_t* frame, size_t len) {
|
||||
if (!g_port_ready || len == 0) return false;
|
||||
return Serial1.write(frame, len) == len;
|
||||
}
|
||||
|
||||
} // namespace UARTManager
|
||||
|
||||
|
||||
@@ -117,9 +117,17 @@ void setDebugEnabled(bool enabled);
|
||||
void linkToCANState(bool can_active);
|
||||
|
||||
/**
|
||||
* @brief Settings-screen switch: start/stop sending to Controller B (UART1 +
|
||||
* @brief Settings-screen switch: start/stop sending to Inst. Cluster (UART1 +
|
||||
* ESP-NOW) and remember the choice in NVS.
|
||||
*/
|
||||
void setEnabled(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Send one complete frame on the UART wire ONLY (never ESP-NOW).
|
||||
* Used for the PAIR frame, which must not go over the air. One write
|
||||
* call, so it cannot interleave with the task's own frames.
|
||||
* @return true if the port is up and every byte was written
|
||||
*/
|
||||
bool sendWire(const uint8_t* frame, size_t len);
|
||||
|
||||
} // namespace UARTManager
|
||||
|
||||
@@ -18,8 +18,9 @@ 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);
|
||||
|
||||
// -176: the StatusOverlay Wi-Fi chip owns the last 150 px of the top-right corner
|
||||
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_align(back, LV_ALIGN_TOP_RIGHT, -176, 10);
|
||||
}
|
||||
|
||||
lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
* UI State Manager Module
|
||||
*
|
||||
* Holds the debug flag (sent to Controller B, shows LVGL's performance overlay).
|
||||
* Holds the debug flag (sent to Inst. Cluster, shows LVGL's performance overlay).
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
@@ -95,6 +95,14 @@ static void loadSaved() {
|
||||
copyStr(g_saved_pass, pass.c_str(), sizeof(g_saved_pass));
|
||||
}
|
||||
|
||||
bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n) {
|
||||
lock();
|
||||
copyStr(ssid, g_status.saved_ssid, ssid_n);
|
||||
unlock();
|
||||
copyStr(pass, g_saved_pass, pass_n);
|
||||
return ssid[0] != 0;
|
||||
}
|
||||
|
||||
static void storeSaved(const char* ssid, const char* pass) {
|
||||
Preferences p;
|
||||
p.begin(NVS_NAMESPACE, false);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* the request functions, so screen lifetimes can never leave dangling pointers
|
||||
* here.
|
||||
*
|
||||
* Radio rules (the ESP-NOW link to Controller B shares the radio):
|
||||
* Radio rules (the ESP-NOW link to Inst. Cluster 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);
|
||||
@@ -82,4 +82,11 @@ uint8_t getNetworks(network_t* out, uint8_t max);
|
||||
/** Console: `wifi status | join <ssid> [pass] | forget | on | off`. */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
/**
|
||||
* The remembered network, password included - for LinkPeer, which hands it to
|
||||
* Inst. Cluster inside an encrypted frame. Never print the password.
|
||||
* @return false if no network is saved
|
||||
*/
|
||||
bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n);
|
||||
|
||||
} // namespace WiFiManager
|
||||
|
||||
Reference in New Issue
Block a user