Link protocol v2, ESP-NOW leg, gauge tunables + tuning screen; remove Home screen

Protocol v2 (shared header, byte-identical with the 1.3 repo):
- typed DATA/CONFIG frames: 0xAA | ver | type | len | payload | XOR | 0x55
- gear split into lever (P/R/N/D/S/M) + target/engaged nibbles, engine rpm,
  alert bitmap decided here from tunable thresholds, link_config_t tunables
- docs/UART_PROTOCOL.md rewritten for v2

Controller A modules:
- tunables: gauge calibration + alert thresholds in NVS, 'cfg' serial console,
  bench override (never persisted)
- espnow_link: every frame also broadcast on ESP-NOW ch 1; radio stays in STA
  (WiFiManager no longer powers it off)
- uart_manager: DATA at 5 Hz + CONFIG on change/5 s on both transports
- can_driver: publishes gear pieces and rpm, evaluates alerts
- tuning_screen: hand-coded Gauge Tuning page (swipe right from Driveline),
  -/+ rows, enable switches, override sliders, Driveline/Defaults buttons

UI: SquareLine Home screen (3 meters + battery) and meters_manager removed;
Driveline is the boot screen; Settings back-gesture calls app_show_driveline().

tools/fix_penv_deps.ps1: repairs the shared PlatformIO penv after a 1.3 build.
Bench-verified with Controller B: both transports alive, dedupe, override
rpm 2000 -> 133.3 Hz tach output.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-21 19:12:31 +02:00
parent a8f68ebc27
commit f60bdac268
33 changed files with 1743 additions and 2266 deletions
+3 -4
View File
@@ -72,10 +72,9 @@ DisplayObjects init() {
lvgl_port_lock(-1);
ui_init(); // Initialize the SquareLine Studio generated UI
// Note: onSelectSSID event handler is registered in ui_Settings_Screen.c
// Override the boot screen: land on the Driveline data screen, not the
// gauges Home screen. ui_init() loaded Home; swap to Driveline while the
// backlight is still off so there's no visible flash of the wrong screen.
// Home stays reachable by swiping off the Driveline screen.
// Boot screen: the hand-coded Driveline screen. ui_init() only loads an
// empty placeholder now (the SquareLine Home screen was removed 2026-09-21);
// swap while the backlight is still off so there's no flash.
DrivelineScreen::show();
lvgl_port_unlock();
Serial.println("[DisplayInit] Step 13: SquareLine UI loaded successfully!");
+17 -38
View File
@@ -6,6 +6,7 @@
#include "uart_manager.h"
#include "display/lvgl_v8_port.h"
#include "drivers/can_driver.h"
#include "tuning_screen.h"
#include "esp_log.h"
extern "C" {
@@ -48,9 +49,6 @@ static lv_obj_t* g_clutch_chip = NULL;
static lv_obj_t* g_cool_chip = NULL;
static lv_obj_t* g_mismatch_lbl = NULL;
// Home screen instance we've already hooked the right-swipe onto.
static lv_obj_t* g_hooked_home = NULL;
// ============================================================================
// PRIVATE HELPERS
// ============================================================================
@@ -139,32 +137,22 @@ static lv_obj_t* makeStat(lv_obj_t* parent, const char* title,
}
/**
* @brief Gesture handler on OUR screen: swipe right/left goes back to Home.
* @brief Gesture handler on OUR screen: swipe LEFT opens Settings (SquareLine),
* swipe RIGHT continues to the Gauge Tuning screen.
*/
static void onScreenGesture(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_GESTURE) return;
lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
if (dir == LV_DIR_LEFT || dir == LV_DIR_RIGHT) {
if (dir == LV_DIR_LEFT) {
lv_indev_wait_release(lv_indev_get_act());
_ui_screen_change(&ui_Home_Screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0,
&ui_Home_Screen_screen_init);
_ui_screen_change(&ui_Settings_Screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0,
&ui_Settings_Screen_screen_init);
} else if (dir == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act());
TuningScreen::show();
}
}
/**
* @brief Gesture handler we bolt onto the Home screen at runtime.
*
* The generated ui_event_Home_Screen() already claims LEFT (-> Settings). LVGL
* dispatches to every registered callback, so this one coexists with it rather
* than replacing it — which is the whole point: we never edit the generated file.
*/
static void onHomeGesture(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_GESTURE) return;
if (lv_indev_get_gesture_dir(lv_indev_get_act()) != LV_DIR_RIGHT) return;
lv_indev_wait_release(lv_indev_get_act());
show();
}
/**
* @brief Build the screen. Idempotent — returns immediately if already built.
*/
@@ -255,7 +243,7 @@ static void build() {
LV_ALIGN_BOTTOM_MID, 340, -34);
lv_obj_t* hint = lv_label_create(g_screen);
lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe back to Home");
lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: Settings | swipe right: Gauge tuning " LV_SYMBOL_RIGHT);
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(hint, COL_MUTED, 0);
lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -14);
@@ -272,21 +260,6 @@ void show() {
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
}
void attachHomeGesture() {
if (ui_Home_Screen == NULL) {
g_hooked_home = NULL; // screen gone; re-hook when it returns
return;
}
if (g_hooked_home == ui_Home_Screen) return;
lvgl_port_lock(-1);
lv_obj_add_event_cb(ui_Home_Screen, onHomeGesture, LV_EVENT_GESTURE, NULL);
lvgl_port_unlock();
g_hooked_home = ui_Home_Screen;
ESP_LOGI("Driveline", "Right-swipe hooked onto Home screen");
}
void tick() {
// Nothing to do unless we're built AND actually the screen being shown.
if (g_screen == NULL || lv_scr_act() != g_screen) return;
@@ -305,7 +278,7 @@ void tick() {
int16_t coolant = 0, gearbox = 0;
uint8_t flags = 0;
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
gear = UARTManager::g_automotive_data.gear_position;
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;
@@ -417,3 +390,9 @@ void tick() {
}
} // namespace DrivelineScreen
// C entry point used by the SquareLine-generated Settings screen's back gesture.
// Runs inside an LVGL event handler, so the LVGL lock is already held.
extern "C" void app_show_driveline(void) {
DrivelineScreen::show();
}
+6 -11
View File
@@ -9,9 +9,12 @@
* SquareLine Studio owns include/ui/ and overwrites it on every export. Editing
* generated files loses the edit — that is exactly how the CAN toggle's event
* handler went missing. This screen lives entirely in src/, which SquareLine
* never touches, so it cannot be clobbered. It is reached by a right-swipe
* gesture attached to the Home screen AT RUNTIME (see attachHomeGesture) rather
* than by editing ui_Home_Screen.c, for the same reason.
* never touches, so it cannot be clobbered. Since 2026-09-21 it IS the boot
* screen: the SquareLine Home screen was removed, and the generated Settings
* screen's back gesture calls app_show_driveline() (defined at the bottom of
* driveline_screen.cpp) to return here.
*
* Navigation: swipe LEFT -> Settings (SquareLine), swipe RIGHT -> Gauge Tuning.
*
* Signals deliberately NOT shown: engine oil temp (no sensor on this M57N —
* 0x1D0 byte 1 is permanently 0xFF) and battery voltage (0x3B4 publishes the
@@ -38,12 +41,4 @@ void show();
*/
void tick();
/**
* @brief Attach a right-swipe handler to the Home screen so this screen is
* reachable, without touching the SquareLine-generated Home screen code.
* Safe to call every loop — re-attaches only when the Home screen
* instance changes. Takes its own LVGL lock.
*/
void attachHomeGesture();
} // namespace DrivelineScreen
+80
View File
@@ -0,0 +1,80 @@
/*
* ESP-NOW Link Module Implementation (Controller A, transmit only)
*/
#include "espnow_link.h"
#include "protocol/automotive_data.h"
#include <WiFi.h>
#include <esp_wifi.h>
#include <esp_now.h>
#include "esp_log.h"
namespace EspNowLink {
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;
// 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) {
(void)info;
// Broadcast frames are never ACKed, so "success" only means the radio
// transmitted. Failures here mean the radio itself refused the frame.
if (status != ESP_NOW_SEND_SUCCESS) g_fail++;
}
bool init() {
if (g_ready) return true;
// Radio must be up for ESP-NOW. Keep STA regardless of the WiFi toggle.
if (WiFi.getMode() == WIFI_OFF) {
WiFi.mode(WIFI_STA);
}
WiFi.setSleep(false); // modem sleep adds latency/loss to ESP-NOW
// Fixed channel while not associated. If the WiFi manager later joins an
// AP the channel follows the AP; B's receiver hops to find us.
if (WiFi.status() != WL_CONNECTED) {
esp_wifi_set_channel(ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE);
}
if (esp_now_init() != ESP_OK) {
ESP_LOGE("EspNow", "esp_now_init failed");
return false;
}
esp_now_register_send_cb(onSent);
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, BROADCAST_MAC, 6);
peer.channel = 0; // current channel
peer.encrypt = false;
peer.ifidx = WIFI_IF_STA;
if (esp_now_add_peer(&peer) != ESP_OK) {
ESP_LOGE("EspNow", "esp_now_add_peer(broadcast) failed");
return false;
}
g_ready = true;
ESP_LOGI("EspNow", "ESP-NOW ready: STA %s, channel %d, broadcast peer added",
WiFi.macAddress().c_str(), WiFi.channel());
return true;
}
bool send(const uint8_t* frame, size_t len) {
if (!g_ready || len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
esp_err_t err = esp_now_send(BROADCAST_MAC, frame, len);
if (err == ESP_OK) {
g_sent++;
return true;
}
g_fail++;
return false;
}
bool isReady() { return g_ready; }
uint32_t sentCount() { return g_sent; }
uint32_t failCount() { return g_fail; }
} // namespace EspNowLink
+37
View File
@@ -0,0 +1,37 @@
/*
* ESP-NOW Link Module (Controller A side, transmit only)
*
* 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.
*
* 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
* B hops until it finds us.
*/
#pragma once
#include <Arduino.h>
namespace EspNowLink {
/**
* Bring the radio up in STA mode on ESPNOW_CHANNEL and register the
* broadcast peer. Safe to call after WiFiManager::init().
* @return true if ESP-NOW is ready
*/
bool init();
/**
* Broadcast one complete frame (start..end bytes).
* @return true if queued for transmission
*/
bool send(const uint8_t* frame, size_t len);
bool isReady();
uint32_t sentCount();
uint32_t failCount();
} // namespace EspNowLink
-363
View File
@@ -1,363 +0,0 @@
/*
* Meters Manager Module Implementation
*/
#include "meters_manager.h"
#include "esp_log.h"
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
static lv_obj_t *g_coolant_meter = NULL;
static lv_meter_indicator_t *g_coolant_needle = NULL;
static lv_obj_t *g_coolant_label = NULL;
static lv_obj_t *g_engine_oil_meter = NULL;
static lv_meter_indicator_t *g_engine_oil_needle = NULL;
static lv_obj_t *g_engine_oil_label = NULL;
static lv_obj_t *g_gearbox_oil_meter = NULL;
static lv_meter_indicator_t *g_gearbox_oil_needle = NULL;
static lv_obj_t *g_gearbox_oil_label = NULL;
// ============================================================================
// PUBLIC API IMPLEMENTATION
// ============================================================================
void meters_manager_init_coolant(lv_obj_t *container, lv_obj_t *icon)
{
if (container == NULL)
{
ESP_LOGE("MetersMgr", "Container is NULL!");
return;
}
ESP_LOGI("MetersMgr", "Initializing Coolant Temperature meter...");
// Create coolant temperature meter (250x250 pixels)
g_coolant_meter = lv_meter_create(container);
lv_obj_set_size(g_coolant_meter, 250, 250);
lv_obj_center(g_coolant_meter);
// Position icon inside the meter if provided
if (icon != NULL)
{
lv_obj_set_parent(icon, g_coolant_meter); // Reparent icon to meter
lv_obj_align(icon, LV_ALIGN_CENTER, 0, 50); // Center horizontally, 50px below center
lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); // Make visible
ESP_LOGI("MetersMgr", "Icon positioned inside meter (50px below center)");
// Create label below the icon to show temperature reading
g_coolant_label = lv_label_create(g_coolant_meter);
lv_obj_align_to(g_coolant_label, icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
lv_label_set_text(g_coolant_label, "--.-°C");
lv_obj_set_style_text_color(g_coolant_label, lv_color_white(), LV_PART_MAIN);
}
// Add a scale: 0-150°C range
lv_meter_scale_t *scale = lv_meter_add_scale(g_coolant_meter);
lv_meter_set_scale_ticks(g_coolant_meter, scale, 31, 2, 10, lv_palette_main(LV_PALETTE_GREY));
lv_meter_set_scale_major_ticks(g_coolant_meter, scale, 5, 4, 15, lv_color_black(), 15);
lv_meter_set_scale_range(g_coolant_meter, scale, 0, 150, 270, 135); // 0-150°C, 270° arc, start at 135°
// Add blue arc for normal range (0-90°C)
lv_meter_indicator_t *indic_blue = lv_meter_add_arc(g_coolant_meter, scale, 3, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_meter_set_indicator_start_value(g_coolant_meter, indic_blue, 0);
lv_meter_set_indicator_end_value(g_coolant_meter, indic_blue, 90);
// Make tick lines blue in normal range
lv_meter_indicator_t *indic_blue_lines = lv_meter_add_scale_lines(g_coolant_meter, scale,
lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_BLUE), false, 0);
lv_meter_set_indicator_start_value(g_coolant_meter, indic_blue_lines, 0);
lv_meter_set_indicator_end_value(g_coolant_meter, indic_blue_lines, 90);
// Add green arc for warm range (90-105°C)
lv_meter_indicator_t *indic_green = lv_meter_add_arc(g_coolant_meter, scale, 3, lv_palette_main(LV_PALETTE_GREEN), 0);
lv_meter_set_indicator_start_value(g_coolant_meter, indic_green, 90);
lv_meter_set_indicator_end_value(g_coolant_meter, indic_green, 105);
// Make tick lines green in warm range
lv_meter_indicator_t *indic_green_lines = lv_meter_add_scale_lines(g_coolant_meter, scale,
lv_palette_main(LV_PALETTE_GREEN), lv_palette_main(LV_PALETTE_GREEN), false, 0);
lv_meter_set_indicator_start_value(g_coolant_meter, indic_green_lines, 90);
lv_meter_set_indicator_end_value(g_coolant_meter, indic_green_lines, 105);
// Add red arc for high temperature range (105-150°C)
lv_meter_indicator_t *indic_red = lv_meter_add_arc(g_coolant_meter, scale, 3, lv_palette_main(LV_PALETTE_RED), 0);
lv_meter_set_indicator_start_value(g_coolant_meter, indic_red, 105);
lv_meter_set_indicator_end_value(g_coolant_meter, indic_red, 150);
// Make tick lines red in high temperature range
lv_meter_indicator_t *indic_red_lines = lv_meter_add_scale_lines(g_coolant_meter, scale,
lv_palette_main(LV_PALETTE_RED), lv_palette_main(LV_PALETTE_RED), false, 0);
lv_meter_set_indicator_start_value(g_coolant_meter, indic_red_lines, 105);
lv_meter_set_indicator_end_value(g_coolant_meter, indic_red_lines, 150);
// Add needle indicator
g_coolant_needle = lv_meter_add_needle_line(g_coolant_meter, scale, 4, lv_palette_main(LV_PALETTE_GREY), -10);
// Add label below meter to show numeric value
// g_coolant_label = lv_label_create(container);
// lv_obj_align_to(g_coolant_label, g_coolant_meter, LV_ALIGN_OUT_BOTTOM_MID, 0, 10);
// lv_label_set_text(g_coolant_label, "Coolant: --.-°C");
// Set initial value to 0
lv_meter_set_indicator_value(g_coolant_meter, g_coolant_needle, 0);
ESP_LOGI("MetersMgr", "Coolant Temperature meter initialized");
}
void meters_manager_init_engine_oil(lv_obj_t *container, lv_obj_t *icon)
{
if (container == NULL)
{
ESP_LOGE("MetersMgr", "Container is NULL!");
return;
}
ESP_LOGI("MetersMgr", "Initializing Engine Oil Temperature meter...");
// Create engine oil temperature meter (250x250 pixels)
g_engine_oil_meter = lv_meter_create(container);
lv_obj_set_size(g_engine_oil_meter, 250, 250);
lv_obj_center(g_engine_oil_meter);
// Position icon inside the meter if provided
if (icon != NULL)
{
lv_obj_set_parent(icon, g_engine_oil_meter); // Reparent icon to meter
lv_obj_align(icon, LV_ALIGN_CENTER, 0, 50); // Center horizontally, 50px below center
lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); // Make visible
ESP_LOGI("MetersMgr", "Icon positioned inside meter (50px below center)");
// Create label below the icon to show temperature reading
g_engine_oil_label = lv_label_create(g_engine_oil_meter);
lv_obj_align_to(g_engine_oil_label, icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
lv_label_set_text(g_engine_oil_label, "--.-°C");
lv_obj_set_style_text_color(g_engine_oil_label, lv_color_white(), LV_PART_MAIN);
}
// Add a scale: 0-150°C range
lv_meter_scale_t *scale = lv_meter_add_scale(g_engine_oil_meter);
lv_meter_set_scale_ticks(g_engine_oil_meter, scale, 31, 2, 10, lv_palette_main(LV_PALETTE_GREY));
lv_meter_set_scale_major_ticks(g_engine_oil_meter, scale, 5, 4, 15, lv_color_black(), 15);
lv_meter_set_scale_range(g_engine_oil_meter, scale, 0, 150, 270, 135); // 0-150°C, 270° arc, start at 135°
// Add blue arc for normal range (0-90°C)
lv_meter_indicator_t *indic_blue = lv_meter_add_arc(g_engine_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_blue, 0);
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_blue, 90);
// Make tick lines blue in normal range
lv_meter_indicator_t *indic_blue_lines = lv_meter_add_scale_lines(g_engine_oil_meter, scale,
lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_BLUE), false, 0);
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_blue_lines, 0);
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_blue_lines, 90);
// Add green arc for warm range (90-105°C)
lv_meter_indicator_t *indic_green = lv_meter_add_arc(g_engine_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_GREEN), 0);
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_green, 90);
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_green, 105);
// Make tick lines green in warm range
lv_meter_indicator_t *indic_green_lines = lv_meter_add_scale_lines(g_engine_oil_meter, scale,
lv_palette_main(LV_PALETTE_GREEN), lv_palette_main(LV_PALETTE_GREEN), false, 0);
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_green_lines, 90);
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_green_lines, 105);
// Add red arc for high temperature range (105-150°C)
lv_meter_indicator_t *indic_red = lv_meter_add_arc(g_engine_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_RED), 0);
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_red, 105);
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_red, 150);
// Make tick lines red in high temperature range
lv_meter_indicator_t *indic_red_lines = lv_meter_add_scale_lines(g_engine_oil_meter, scale,
lv_palette_main(LV_PALETTE_RED), lv_palette_main(LV_PALETTE_RED), false, 0);
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_red_lines, 105);
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_red_lines, 150);
// Add needle indicator
g_engine_oil_needle = lv_meter_add_needle_line(g_engine_oil_meter, scale, 4, lv_palette_main(LV_PALETTE_GREY), -10);
// Set initial value to 0
lv_meter_set_indicator_value(g_engine_oil_meter, g_engine_oil_needle, 0);
ESP_LOGI("MetersMgr", "Engine Oil Temperature meter initialized");
}
void meters_manager_init_gearbox_oil(lv_obj_t *container, lv_obj_t *icon)
{
if (container == NULL)
{
ESP_LOGE("MetersMgr", "Container is NULL!");
return;
}
ESP_LOGI("MetersMgr", "Initializing Gearbox Oil Temperature meter...");
// Create gearbox oil temperature meter (250x250 pixels)
g_gearbox_oil_meter = lv_meter_create(container);
lv_obj_set_size(g_gearbox_oil_meter, 250, 250);
lv_obj_center(g_gearbox_oil_meter);
// Position icon inside the meter if provided
if (icon != NULL)
{
lv_obj_set_parent(icon, g_gearbox_oil_meter); // Reparent icon to meter
lv_obj_align(icon, LV_ALIGN_CENTER, 0, 50); // Center horizontally, 50px below center
lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); // Make visible
ESP_LOGI("MetersMgr", "Icon positioned inside meter (50px below center)");
// Create label below the icon to show temperature reading
g_gearbox_oil_label = lv_label_create(g_gearbox_oil_meter);
lv_obj_align_to(g_gearbox_oil_label, icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
lv_label_set_text(g_gearbox_oil_label, "--.-°C");
lv_obj_set_style_text_color(g_gearbox_oil_label, lv_color_white(), LV_PART_MAIN);
}
// Add a scale: 0-150°C range
lv_meter_scale_t *scale = lv_meter_add_scale(g_gearbox_oil_meter);
lv_meter_set_scale_ticks(g_gearbox_oil_meter, scale, 31, 2, 10, lv_palette_main(LV_PALETTE_GREY));
lv_meter_set_scale_major_ticks(g_gearbox_oil_meter, scale, 5, 4, 15, lv_color_black(), 15);
lv_meter_set_scale_range(g_gearbox_oil_meter, scale, 0, 150, 270, 135); // 0-150°C, 270° arc, start at 135°
// Add blue arc for normal range (0-90°C)
lv_meter_indicator_t *indic_blue = lv_meter_add_arc(g_gearbox_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_BLUE), 0);
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_blue, 0);
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_blue, 90);
// Make tick lines blue in normal range
lv_meter_indicator_t *indic_blue_lines = lv_meter_add_scale_lines(g_gearbox_oil_meter, scale,
lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_BLUE), false, 0);
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_blue_lines, 0);
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_blue_lines, 90);
// Add green arc for warm range (90-105°C)
lv_meter_indicator_t *indic_green = lv_meter_add_arc(g_gearbox_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_GREEN), 0);
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_green, 90);
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_green, 105);
// Make tick lines green in warm range
lv_meter_indicator_t *indic_green_lines = lv_meter_add_scale_lines(g_gearbox_oil_meter, scale,
lv_palette_main(LV_PALETTE_GREEN), lv_palette_main(LV_PALETTE_GREEN), false, 0);
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_green_lines, 90);
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_green_lines, 105);
// Add red arc for high temperature range (105-150°C)
lv_meter_indicator_t *indic_red = lv_meter_add_arc(g_gearbox_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_RED), 0);
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_red, 105);
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_red, 150);
// Make tick lines red in high temperature range
lv_meter_indicator_t *indic_red_lines = lv_meter_add_scale_lines(g_gearbox_oil_meter, scale,
lv_palette_main(LV_PALETTE_RED), lv_palette_main(LV_PALETTE_RED), false, 0);
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_red_lines, 105);
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_red_lines, 150);
// Add needle indicator
g_gearbox_oil_needle = lv_meter_add_needle_line(g_gearbox_oil_meter, scale, 4, lv_palette_main(LV_PALETTE_GREY), -10);
// Set initial value to 0
lv_meter_set_indicator_value(g_gearbox_oil_meter, g_gearbox_oil_needle, 0);
ESP_LOGI("MetersMgr", "Gearbox Oil Temperature meter initialized");
}
void meters_manager_update_coolant_temp(int16_t temp_x10)
{
if (g_coolant_meter == NULL || g_coolant_needle == NULL)
{
return; // Not initialized yet
}
// Convert temp_x10 to whole degrees for meter (e.g., 890 -> 89)
int16_t temp_degrees = temp_x10 / 10;
// Clamp to meter range (0-150°C)
if (temp_degrees < 0)
temp_degrees = 0;
if (temp_degrees > 150)
temp_degrees = 150;
// Update needle position
lv_meter_set_indicator_value(g_coolant_meter, g_coolant_needle, temp_degrees);
// Update label with precise value (with decimal)
if (g_coolant_label != NULL)
{
char buf[16];
snprintf(buf, sizeof(buf), "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
lv_label_set_text(g_coolant_label, buf);
}
}
void meters_manager_update_engine_oil_temp(int16_t temp_x10)
{
if (g_engine_oil_meter == NULL || g_engine_oil_needle == NULL)
{
return; // Not initialized yet
}
// Convert temp_x10 to whole degrees for meter (e.g., 920 -> 92)
int16_t temp_degrees = temp_x10 / 10;
// Clamp to meter range (0-150°C)
if (temp_degrees < 0)
temp_degrees = 0;
if (temp_degrees > 150)
temp_degrees = 150;
// Update needle position
lv_meter_set_indicator_value(g_engine_oil_meter, g_engine_oil_needle, temp_degrees);
// Update label with precise value (with decimal)
if (g_engine_oil_label != NULL)
{
char buf[16];
snprintf(buf, sizeof(buf), "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
lv_label_set_text(g_engine_oil_label, buf);
}
}
void meters_manager_update_gearbox_oil_temp(int16_t temp_x10)
{
if (g_gearbox_oil_meter == NULL || g_gearbox_oil_needle == NULL)
{
return; // Not initialized yet
}
// Convert temp_x10 to whole degrees for meter (e.g., 850 -> 85)
int16_t temp_degrees = temp_x10 / 10;
// Clamp to meter range (0-150°C)
if (temp_degrees < 0)
temp_degrees = 0;
if (temp_degrees > 150)
temp_degrees = 150;
// Update needle position
lv_meter_set_indicator_value(g_gearbox_oil_meter, g_gearbox_oil_needle, temp_degrees);
// Update label with precise value (with decimal)
if (g_gearbox_oil_label != NULL)
{
char buf[16];
snprintf(buf, sizeof(buf), "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
lv_label_set_text(g_gearbox_oil_label, buf);
}
}
void meters_manager_cleanup(void)
{
g_coolant_meter = NULL;
g_coolant_needle = NULL;
g_coolant_label = NULL;
g_engine_oil_meter = NULL;
g_engine_oil_needle = NULL;
g_engine_oil_label = NULL;
g_gearbox_oil_meter = NULL;
g_gearbox_oil_needle = NULL;
g_gearbox_oil_label = NULL;
ESP_LOGI("MetersMgr", "Meters cleaned up");
}
-70
View File
@@ -1,70 +0,0 @@
/*
* Meters Manager Module
*
* Handles LVGL meter widgets for displaying automotive sensor data
* Currently implements: Coolant Temperature gauge
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
#ifdef __cplusplus
extern "C" {
#endif
// ============================================================================
// PUBLIC API
// ============================================================================
/**
* @brief Initialize the coolant temperature meter
* @param container Parent container to add meter to (uic_Home_Loading_Container)
* @param icon Optional icon to place inside the meter (can be NULL)
* @note Creates coolant temperature meter widget with icon and label
*/
void meters_manager_init_coolant(lv_obj_t* container, lv_obj_t* icon);
/**
* @brief Initialize the engine oil temperature meter
* @param container Parent container to add meter to (uic_Home_Loading_Container)
* @param icon Optional icon to place inside the meter (can be NULL)
* @note Creates engine oil temperature meter widget with icon and label
*/
void meters_manager_init_engine_oil(lv_obj_t* container, lv_obj_t* icon);
/**
* @brief Initialize the gearbox oil temperature meter
* @param container Parent container to add meter to (uic_Home_Loading_Container)
* @param icon Optional icon to place inside the meter (can be NULL)
* @note Creates gearbox oil temperature meter widget with icon and label
*/
void meters_manager_init_gearbox_oil(lv_obj_t* container, lv_obj_t* icon);
/**
* @brief Update coolant temperature meter value
* @param temp_x10 Temperature in 0.1°C (e.g., 890 = 89.0°C)
*/
void meters_manager_update_coolant_temp(int16_t temp_x10);
/**
* @brief Update engine oil temperature meter value
* @param temp_x10 Temperature in 0.1°C (e.g., 920 = 92.0°C)
*/
void meters_manager_update_engine_oil_temp(int16_t temp_x10);
/**
* @brief Update gearbox oil temperature meter value
* @param temp_x10 Temperature in 0.1°C (e.g., 850 = 85.0°C)
*/
void meters_manager_update_gearbox_oil_temp(int16_t temp_x10);
/**
* @brief Cleanup meters when screen is destroyed
*/
void meters_manager_cleanup(void);
#ifdef __cplusplus
}
#endif
+263
View File
@@ -0,0 +1,263 @@
/*
* Tunables Module Implementation
*/
#include "tunables.h"
#include "serial_lock.h"
#include <Preferences.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
namespace Tunables {
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
static const char* NVS_NAMESPACE = "tunables";
static const char* NVS_KEY_BLOB = "cfg";
static link_config_t g_cfg;
static SemaphoreHandle_t g_mutex = NULL;
static char g_line[96];
static size_t g_line_len = 0;
// ============================================================================
// PRIVATE HELPERS
// ============================================================================
static void lock() { if (g_mutex) xSemaphoreTake(g_mutex, portMAX_DELAY); }
static void unlock() { if (g_mutex) xSemaphoreGive(g_mutex); }
static void save() {
// Never persist a bench override: a reboot must come up with real data.
link_config_t c = g_cfg;
c.override_mode = 0;
c.override_rpm = 0;
c.override_duty = 0;
Preferences prefs;
prefs.begin(NVS_NAMESPACE, false);
prefs.putBytes(NVS_KEY_BLOB, &c, sizeof(c));
prefs.end();
}
static bool load() {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, true);
size_t n = prefs.getBytesLength(NVS_KEY_BLOB);
bool ok = false;
if (n == sizeof(link_config_t)) {
prefs.getBytes(NVS_KEY_BLOB, &g_cfg, sizeof(g_cfg));
ok = true;
}
prefs.end();
return ok;
}
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 void show() {
link_config_t c = get();
print("[cfg] version %u", c.cfg_version);
print("[cfg] tach: ppr=%u trim=%d%% min_hz=%u max_hz=%u enable=%d",
c.tach_ppr, c.tach_trim_pct, c.tach_min_hz, c.tach_max_hz,
(c.out_enable & OUT_ENABLE_TACH) ? 1 : 0);
print("[cfg] temp: pwm_hz=%u slope=%u.%02u duty/C offset=%d min_c=%d duty_max=%u enable=%d",
c.temp_pwm_hz, c.temp_slope_x100 / 100, c.temp_slope_x100 % 100,
c.temp_offset, c.temp_min_c, c.temp_duty_max,
(c.out_enable & OUT_ENABLE_TEMP) ? 1 : 0);
print("[cfg] override: mode=%u rpm=%u duty=%u", c.override_mode, c.override_rpm, c.override_duty);
print("[cfg] alerts: coolant_hot=%dC gearbox_hot=%dC battery_low=%u.%02uV",
c.coolant_hot_c, c.gearbox_hot_c, c.battery_low_x100 / 100, c.battery_low_x100 % 100);
}
static void help() {
print("cfg show print current tunables");
print("cfg set <name> <value> names: tach_ppr tach_trim tach_min_hz tach_max_hz");
print(" temp_hz temp_slope(x100) temp_offset temp_min temp_duty_max");
print(" tach_en temp_en coolant_hot gearbox_hot batt_low(x100)");
print("cfg override off | rpm <n> | duty <n> | both <rpm> <duty>");
print("cfg reset back to defaults");
}
static bool setField(const char* name, long v) {
lock();
bool ok = true;
if (!strcmp(name, "tach_ppr")) g_cfg.tach_ppr = (uint8_t)constrain(v, 1, 32);
else if (!strcmp(name, "tach_trim")) g_cfg.tach_trim_pct = (int8_t)constrain(v, -50, 50);
else if (!strcmp(name, "tach_min_hz")) g_cfg.tach_min_hz = (uint16_t)constrain(v, 0, 5000);
else if (!strcmp(name, "tach_max_hz")) g_cfg.tach_max_hz = (uint16_t)constrain(v, 0, 5000);
else if (!strcmp(name, "temp_hz")) g_cfg.temp_pwm_hz = (uint16_t)constrain(v, 20, 20000);
else if (!strcmp(name, "temp_slope")) g_cfg.temp_slope_x100 = (uint16_t)constrain(v, 0, 5000);
else if (!strcmp(name, "temp_offset")) g_cfg.temp_offset = (int16_t)constrain(v, -1000, 1000);
else if (!strcmp(name, "temp_min")) g_cfg.temp_min_c = (int16_t)constrain(v, -50, 200);
else if (!strcmp(name, "temp_duty_max")) g_cfg.temp_duty_max = (uint8_t)constrain(v, 0, 255);
else if (!strcmp(name, "tach_en")) g_cfg.out_enable = v ? (g_cfg.out_enable | OUT_ENABLE_TACH) : (g_cfg.out_enable & ~OUT_ENABLE_TACH);
else if (!strcmp(name, "temp_en")) g_cfg.out_enable = v ? (g_cfg.out_enable | OUT_ENABLE_TEMP) : (g_cfg.out_enable & ~OUT_ENABLE_TEMP);
else if (!strcmp(name, "coolant_hot")) g_cfg.coolant_hot_c = (int16_t)constrain(v, 0, 200);
else if (!strcmp(name, "gearbox_hot")) g_cfg.gearbox_hot_c = (int16_t)constrain(v, 0, 200);
else if (!strcmp(name, "batt_low")) g_cfg.battery_low_x100 = (uint16_t)constrain(v, 0, 3000);
else ok = false;
if (ok) {
g_cfg.cfg_version++;
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
save();
}
unlock();
return ok;
}
// ============================================================================
// PUBLIC API
// ============================================================================
void init() {
if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex();
lock();
if (!load()) {
link_config_defaults(&g_cfg);
save();
unlock();
print("[Tunables] No saved config (or size changed) - defaults written to NVS");
} else {
unlock();
print("[Tunables] Loaded config version %u from NVS", g_cfg.cfg_version);
}
show();
print("[Tunables] Type 'cfg help' on this console to tune the Patrol gauges");
}
link_config_t get() {
link_config_t c;
lock();
c = g_cfg;
unlock();
return c;
}
uint8_t version() {
lock();
uint8_t v = g_cfg.cfg_version;
unlock();
return v;
}
void set(const link_config_t& cfg) {
lock();
uint8_t v = g_cfg.cfg_version + 1;
g_cfg = cfg;
g_cfg.cfg_version = v ? v : 1;
save();
unlock();
}
void resetDefaults() {
lock();
uint8_t v = g_cfg.cfg_version + 1;
link_config_defaults(&g_cfg);
g_cfg.cfg_version = v ? v : 1;
save();
unlock();
}
void setOverride(uint8_t mode, uint16_t rpm, uint8_t duty) {
lock();
g_cfg.override_mode = mode & (OVERRIDE_TACH | OVERRIDE_TEMP);
g_cfg.override_rpm = rpm;
g_cfg.override_duty = duty;
g_cfg.cfg_version++;
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
unlock();
print("[cfg] override mode=%u rpm=%u duty=%u (not saved)", mode, rpm, duty);
}
bool handleCommand(const char* line) {
char buf[96];
strncpy(buf, line, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
char* argv[5] = {0};
int argc = 0;
for (char* tok = strtok(buf, " \t"); tok && argc < 5; tok = strtok(NULL, " \t")) {
argv[argc++] = tok;
}
if (argc == 0) return false;
if (strcmp(argv[0], "cfg") != 0 && strcmp(argv[0], "help") != 0) return false;
if (argc == 1 || !strcmp(argv[1], "help") || !strcmp(argv[0], "help")) { help(); return true; }
if (!strcmp(argv[1], "show")) { show(); return true; }
if (!strcmp(argv[1], "reset")) { resetDefaults(); print("[cfg] reset to defaults"); show(); return true; }
if (!strcmp(argv[1], "set") && argc == 4) {
long v = strtol(argv[3], NULL, 0);
if (setField(argv[2], v)) {
print("[cfg] %s = %ld (version %u, saved)", argv[2], v, version());
} else {
print("[cfg] unknown field '%s'", argv[2]);
help();
}
return true;
}
if (!strcmp(argv[1], "override") && argc >= 3) {
lock();
if (!strcmp(argv[2], "off")) {
g_cfg.override_mode = 0;
} else if (!strcmp(argv[2], "rpm") && argc == 4) {
g_cfg.override_mode = OVERRIDE_TACH;
g_cfg.override_rpm = (uint16_t)constrain(strtol(argv[3], NULL, 0), 0, 10000);
} else if (!strcmp(argv[2], "duty") && argc == 4) {
g_cfg.override_mode = OVERRIDE_TEMP;
g_cfg.override_duty = (uint8_t)constrain(strtol(argv[3], NULL, 0), 0, 255);
} else if (!strcmp(argv[2], "both") && argc == 5) {
g_cfg.override_mode = OVERRIDE_TACH | OVERRIDE_TEMP;
g_cfg.override_rpm = (uint16_t)constrain(strtol(argv[3], NULL, 0), 0, 10000);
g_cfg.override_duty = (uint8_t)constrain(strtol(argv[4], NULL, 0), 0, 255);
} else {
unlock();
help();
return true;
}
g_cfg.cfg_version++;
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
// Overrides are a bench tool: pushed to B immediately but NOT persisted,
// so a reboot never leaves the gauges pinned to a test value.
unlock();
print("[cfg] override mode=%u rpm=%u duty=%u (not saved)", g_cfg.override_mode, g_cfg.override_rpm, g_cfg.override_duty);
return true;
}
help();
return true;
}
void pollSerial() {
while (Serial.available()) {
char c = (char)Serial.read();
if (c == '\r' || c == '\n') {
if (g_line_len > 0) {
g_line[g_line_len] = 0;
if (!handleCommand(g_line)) {
print("[console] unknown command '%s' (try 'cfg help')", g_line);
}
g_line_len = 0;
}
} else if (g_line_len < sizeof(g_line) - 1) {
g_line[g_line_len++] = c;
} else {
g_line_len = 0; // overflow: drop the line
}
}
}
} // namespace Tunables
+61
View File
@@ -0,0 +1,61 @@
/*
* Tunables Module
*
* Owns the link_config_t that Controller A pushes to Controller B: 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.
*/
#pragma once
#include <Arduino.h>
#include "protocol/automotive_data.h"
namespace Tunables {
/**
* Load from NVS (or defaults if absent / size mismatch). Call after Serial.begin().
*/
void init();
/**
* Snapshot of the current configuration (thread-safe copy).
*/
link_config_t get();
/**
* Current cfg_version. Increments on every change; the UART manager re-sends
* a CONFIG frame when it sees a new value.
*/
uint8_t version();
/**
* Replace the whole configuration (bumps cfg_version, saves to NVS).
*/
void set(const link_config_t& cfg);
/**
* Reset to link_config_defaults() and save.
*/
void resetDefaults();
/**
* Set the bench override (bumps cfg_version so it is pushed to B, but NEVER
* saved to NVS - a reboot must not leave the gauges pinned to a test value).
*/
void setOverride(uint8_t mode, uint16_t rpm, uint8_t duty);
/**
* Execute one console command line ("cfg show", "cfg set tach_ppr 4", ...).
* @return true if the line was a recognised command
*/
bool handleCommand(const char* line);
/**
* Non-blocking: read pending bytes from Serial, dispatch complete lines to
* handleCommand(). Call from loop().
*/
void pollSerial();
} // namespace Tunables
+605
View File
@@ -0,0 +1,605 @@
/*
* Gauge Tuning Screen Module Implementation
*/
#include "tuning_screen.h"
#include "tunables.h"
#include "driveline_screen.h"
#include "display/lvgl_v8_port.h"
#include "esp_log.h"
extern "C"
{
#include "ui.h"
}
namespace TuningScreen
{
// ============================================================================
// THEME
// ============================================================================
#define COL_BG lv_color_hex(0x101418)
#define COL_PANEL lv_color_hex(0x1B2128)
#define COL_TEXT lv_color_hex(0xE8EDF2)
#define COL_MUTED lv_color_hex(0x6E7B88)
#define COL_ACCENT lv_color_hex(0x3DA9FC)
#define COL_OK lv_color_hex(0x3DD68C)
#define COL_WARN lv_color_hex(0xE5484D)
// ============================================================================
// FIELD TABLE — one row per numeric tunable
// ============================================================================
typedef enum
{
F_TACH_PPR,
F_TACH_TRIM,
F_TACH_MAX_HZ,
F_TEMP_HZ,
F_TEMP_SLOPE,
F_TEMP_OFFSET,
F_TEMP_MIN,
F_TEMP_DUTY_MAX,
F_COOLANT_HOT,
F_GEARBOX_HOT,
F_BATT_LOW,
F_COUNT
} field_t;
typedef struct
{
field_t id;
const char *name;
const char *unit;
int32_t step;
int32_t min;
int32_t max;
lv_obj_t *value_lbl;
} row_t;
static row_t g_rows[F_COUNT] = {
{F_TACH_PPR, "Pulses / rev", "", 1, 1, 32, NULL},
{F_TACH_TRIM, "Trim", "%", 1, -50, 50, NULL},
{F_TACH_MAX_HZ, "Max output", "Hz", 10, 0, 5000, NULL},
{F_TEMP_HZ, "PWM frequency", "Hz", 50, 20, 20000, NULL},
{F_TEMP_SLOPE, "Slope", "x100", 5, 0, 5000, NULL},
{F_TEMP_OFFSET, "Offset", "", 1, -1000, 1000, NULL},
{F_TEMP_MIN, "Min temp", "C", 1, -50, 200, NULL},
{F_TEMP_DUTY_MAX, "Duty clamp", "", 5, 0, 255, NULL},
{F_COOLANT_HOT, "Coolant hot", "C", 1, 0, 200, NULL},
{F_GEARBOX_HOT, "Gearbox hot", "C", 1, 0, 200, NULL},
{F_BATT_LOW, "Battery low", "x0.01V", 10, 0, 3000, NULL},
};
static int32_t getField(const link_config_t &c, field_t f)
{
switch (f)
{
case F_TACH_PPR:
return c.tach_ppr;
case F_TACH_TRIM:
return c.tach_trim_pct;
case F_TACH_MAX_HZ:
return c.tach_max_hz;
case F_TEMP_HZ:
return c.temp_pwm_hz;
case F_TEMP_SLOPE:
return c.temp_slope_x100;
case F_TEMP_OFFSET:
return c.temp_offset;
case F_TEMP_MIN:
return c.temp_min_c;
case F_TEMP_DUTY_MAX:
return c.temp_duty_max;
case F_COOLANT_HOT:
return c.coolant_hot_c;
case F_GEARBOX_HOT:
return c.gearbox_hot_c;
case F_BATT_LOW:
return c.battery_low_x100;
default:
return 0;
}
}
static void setField(link_config_t &c, field_t f, int32_t v)
{
switch (f)
{
case F_TACH_PPR:
c.tach_ppr = (uint8_t)v;
break;
case F_TACH_TRIM:
c.tach_trim_pct = (int8_t)v;
break;
case F_TACH_MAX_HZ:
c.tach_max_hz = (uint16_t)v;
break;
case F_TEMP_HZ:
c.temp_pwm_hz = (uint16_t)v;
break;
case F_TEMP_SLOPE:
c.temp_slope_x100 = (uint16_t)v;
break;
case F_TEMP_OFFSET:
c.temp_offset = (int16_t)v;
break;
case F_TEMP_MIN:
c.temp_min_c = (int16_t)v;
break;
case F_TEMP_DUTY_MAX:
c.temp_duty_max = (uint8_t)v;
break;
case F_COOLANT_HOT:
c.coolant_hot_c = (int16_t)v;
break;
case F_GEARBOX_HOT:
c.gearbox_hot_c = (int16_t)v;
break;
case F_BATT_LOW:
c.battery_low_x100 = (uint16_t)v;
break;
default:
break;
}
}
// ============================================================================
// MODULE STATE
// ============================================================================
static lv_obj_t *g_screen = NULL;
static lv_obj_t *g_tach_en_sw = NULL;
static lv_obj_t *g_temp_en_sw = NULL;
static lv_obj_t *g_ovr_rpm_sw = NULL;
static lv_obj_t *g_ovr_duty_sw = NULL;
static lv_obj_t *g_ovr_rpm_sl = NULL;
static lv_obj_t *g_ovr_duty_sl = NULL;
static lv_obj_t *g_ovr_rpm_lbl = NULL;
static lv_obj_t *g_ovr_duty_lbl = NULL;
static lv_obj_t *g_status_lbl = NULL;
static uint8_t g_shown_version = 0;
static bool g_refreshing = false; // suppress event handlers while we set widget values
// ============================================================================
// HELPERS
// ============================================================================
static void formatValue(const row_t &r, int32_t v, char *out, size_t n)
{
if (r.id == F_TEMP_SLOPE)
{
snprintf(out, n, "%ld.%02ld", (long)(v / 100), (long)labs(v % 100));
}
else if (r.id == F_BATT_LOW)
{
snprintf(out, n, "%ld.%02ld V", (long)(v / 100), (long)(v % 100));
}
else if (r.unit[0])
{
snprintf(out, n, "%ld %s", (long)v, r.unit);
}
else
{
snprintf(out, n, "%ld", (long)v);
}
}
static void refreshFromTunables()
{
link_config_t c = Tunables::get();
g_refreshing = true;
char buf[24];
for (int i = 0; i < F_COUNT; i++)
{
if (g_rows[i].value_lbl == NULL)
continue;
formatValue(g_rows[i], getField(c, g_rows[i].id), buf, sizeof(buf));
lv_label_set_text(g_rows[i].value_lbl, buf);
}
auto setSw = [](lv_obj_t *sw, bool on)
{
if (sw == NULL)
return;
if (on)
lv_obj_add_state(sw, LV_STATE_CHECKED);
else
lv_obj_clear_state(sw, LV_STATE_CHECKED);
};
setSw(g_tach_en_sw, c.out_enable & OUT_ENABLE_TACH);
setSw(g_temp_en_sw, c.out_enable & OUT_ENABLE_TEMP);
setSw(g_ovr_rpm_sw, c.override_mode & OVERRIDE_TACH);
setSw(g_ovr_duty_sw, c.override_mode & OVERRIDE_TEMP);
if (g_ovr_rpm_sl)
lv_slider_set_value(g_ovr_rpm_sl, c.override_rpm, LV_ANIM_OFF);
if (g_ovr_duty_sl)
lv_slider_set_value(g_ovr_duty_sl, c.override_duty, LV_ANIM_OFF);
if (g_ovr_rpm_lbl)
{
snprintf(buf, sizeof(buf), "%u rpm", c.override_rpm);
lv_label_set_text(g_ovr_rpm_lbl, buf);
}
if (g_ovr_duty_lbl)
{
snprintf(buf, sizeof(buf), "%u / 255", c.override_duty);
lv_label_set_text(g_ovr_duty_lbl, buf);
}
if (g_status_lbl)
{
snprintf(buf, sizeof(buf), "config v%u", c.cfg_version);
lv_label_set_text(g_status_lbl, buf);
lv_obj_set_style_text_color(g_status_lbl, c.override_mode ? COL_WARN : COL_MUTED, 0);
}
g_shown_version = c.cfg_version;
g_refreshing = false;
}
// ---- event handlers --------------------------------------------------------
// user_data = row pointer; the button's own user data (+1/-1) is in lv_event_get_user_data
typedef struct
{
row_t *row;
int dir;
} step_ctx_t;
static step_ctx_t g_step_ctx[F_COUNT][2];
static void onStep(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
if (code != LV_EVENT_CLICKED && code != LV_EVENT_LONG_PRESSED_REPEAT)
return;
step_ctx_t *ctx = (step_ctx_t *)lv_event_get_user_data(e);
link_config_t c = Tunables::get();
int32_t v = getField(c, ctx->row->id) + ctx->dir * ctx->row->step;
if (v < ctx->row->min)
v = ctx->row->min;
if (v > ctx->row->max)
v = ctx->row->max;
setField(c, ctx->row->id, v);
Tunables::set(c); // saves + bumps version -> CONFIG frame goes out
refreshFromTunables();
}
static void onEnableSwitch(lv_event_t *e)
{
if (g_refreshing || lv_event_get_code(e) != LV_EVENT_VALUE_CHANGED)
return;
lv_obj_t *sw = lv_event_get_target(e);
bool on = lv_obj_has_state(sw, LV_STATE_CHECKED);
uint8_t bit = (uint8_t)(uintptr_t)lv_event_get_user_data(e);
link_config_t c = Tunables::get();
c.out_enable = on ? (c.out_enable | bit) : (c.out_enable & ~bit);
Tunables::set(c);
refreshFromTunables();
}
static void pushOverride()
{
link_config_t c = Tunables::get();
uint8_t mode = 0;
if (g_ovr_rpm_sw && lv_obj_has_state(g_ovr_rpm_sw, LV_STATE_CHECKED))
mode |= OVERRIDE_TACH;
if (g_ovr_duty_sw && lv_obj_has_state(g_ovr_duty_sw, LV_STATE_CHECKED))
mode |= OVERRIDE_TEMP;
uint16_t rpm = g_ovr_rpm_sl ? (uint16_t)lv_slider_get_value(g_ovr_rpm_sl) : c.override_rpm;
uint8_t duty = g_ovr_duty_sl ? (uint8_t)lv_slider_get_value(g_ovr_duty_sl) : c.override_duty;
Tunables::setOverride(mode, rpm, duty); // pushed to B, never saved
refreshFromTunables();
}
static void onOverrideSwitch(lv_event_t *e)
{
if (g_refreshing || lv_event_get_code(e) != LV_EVENT_VALUE_CHANGED)
return;
pushOverride();
}
static void onOverrideSlider(lv_event_t *e)
{
if (g_refreshing)
return;
lv_event_code_t code = lv_event_get_code(e);
// Update the readout while dragging; push to B on release so we don't
// flood the link with CONFIG frames at touch rate.
if (code == LV_EVENT_VALUE_CHANGED)
{
char buf[24];
lv_obj_t *sl = lv_event_get_target(e);
if (sl == g_ovr_rpm_sl && g_ovr_rpm_lbl)
{
snprintf(buf, sizeof(buf), "%d rpm", (int)lv_slider_get_value(sl));
lv_label_set_text(g_ovr_rpm_lbl, buf);
}
else if (sl == g_ovr_duty_sl && g_ovr_duty_lbl)
{
snprintf(buf, sizeof(buf), "%d / 255", (int)lv_slider_get_value(sl));
lv_label_set_text(g_ovr_duty_lbl, buf);
}
}
else if (code == LV_EVENT_RELEASED)
{
pushOverride();
}
}
static void onBack(lv_event_t *e)
{
if (lv_event_get_code(e) != LV_EVENT_CLICKED)
return;
DrivelineScreen::show();
}
static void onReset(lv_event_t *e)
{
if (lv_event_get_code(e) != LV_EVENT_CLICKED)
return;
Tunables::resetDefaults();
refreshFromTunables();
}
// ---- builders --------------------------------------------------------------
static lv_obj_t *makePanel(lv_obj_t *parent, const char *title, lv_coord_t w)
{
lv_obj_t *p = lv_obj_create(parent);
lv_obj_set_size(p, w, LV_SIZE_CONTENT);
lv_obj_set_style_bg_color(p, COL_PANEL, 0);
lv_obj_set_style_border_width(p, 0, 0);
lv_obj_set_style_radius(p, 12, 0);
lv_obj_set_style_pad_all(p, 12, 0);
lv_obj_set_style_pad_row(p, 6, 0);
lv_obj_set_flex_flow(p, LV_FLEX_FLOW_COLUMN);
lv_obj_clear_flag(p, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *t = lv_label_create(p);
lv_label_set_text(t, title);
lv_obj_set_style_text_font(t, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(t, COL_ACCENT, 0);
lv_obj_set_style_pad_bottom(t, 4, 0);
return p;
}
static lv_obj_t *makeStepBtn(lv_obj_t *parent, const char *txt, step_ctx_t *ctx)
{
lv_obj_t *b = lv_btn_create(parent);
lv_obj_set_size(b, 44, 36);
lv_obj_set_style_bg_color(b, COL_BG, 0);
lv_obj_set_style_radius(b, 8, 0);
lv_obj_add_event_cb(b, onStep, LV_EVENT_CLICKED, ctx);
lv_obj_add_event_cb(b, onStep, LV_EVENT_LONG_PRESSED_REPEAT, ctx);
lv_obj_t *l = lv_label_create(b);
lv_label_set_text(l, txt);
lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0);
lv_obj_center(l);
return b;
}
static void makeRow(lv_obj_t *panel, field_t f)
{
row_t *r = &g_rows[f];
lv_obj_t *row = lv_obj_create(panel);
lv_obj_remove_style_all(row);
lv_obj_set_size(row, LV_PCT(100), 36);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(row, 6, 0);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *name = lv_label_create(row);
lv_label_set_text(name, r->name);
lv_obj_set_style_text_font(name, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(name, COL_MUTED, 0);
lv_obj_set_width(name, 118);
g_step_ctx[f][0] = {r, -1};
g_step_ctx[f][1] = {r, +1};
makeStepBtn(row, LV_SYMBOL_MINUS, &g_step_ctx[f][0]);
r->value_lbl = lv_label_create(row);
lv_label_set_text(r->value_lbl, "--");
lv_obj_set_style_text_font(r->value_lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(r->value_lbl, COL_TEXT, 0);
lv_obj_set_style_text_align(r->value_lbl, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(r->value_lbl, 82);
makeStepBtn(row, LV_SYMBOL_PLUS, &g_step_ctx[f][1]);
}
static lv_obj_t *makeSwitchRow(lv_obj_t *panel, const char *text, lv_event_cb_t cb, void *user)
{
lv_obj_t *row = lv_obj_create(panel);
lv_obj_remove_style_all(row);
lv_obj_set_size(row, LV_PCT(100), 36);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *l = lv_label_create(row);
lv_label_set_text(l, text);
lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(l, COL_MUTED, 0);
lv_obj_t *sw = lv_switch_create(row);
lv_obj_set_style_bg_color(sw, COL_ACCENT, (lv_style_selector_t)LV_PART_INDICATOR | (lv_style_selector_t)LV_STATE_CHECKED);
lv_obj_add_event_cb(sw, cb, LV_EVENT_VALUE_CHANGED, user);
return sw;
}
static lv_obj_t *makeSliderRow(lv_obj_t *panel, const char *text, int32_t max, lv_obj_t **readout)
{
lv_obj_t *head = lv_obj_create(panel);
lv_obj_remove_style_all(head);
lv_obj_set_size(head, LV_PCT(100), 20);
lv_obj_set_flex_flow(head, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(head, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(head, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *l = lv_label_create(head);
lv_label_set_text(l, text);
lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(l, COL_MUTED, 0);
*readout = lv_label_create(head);
lv_label_set_text(*readout, "--");
lv_obj_set_style_text_font(*readout, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(*readout, COL_TEXT, 0);
lv_obj_t *sl = lv_slider_create(panel);
lv_obj_set_width(sl, LV_PCT(96));
lv_slider_set_range(sl, 0, max);
lv_obj_set_style_bg_color(sl, COL_BG, 0);
lv_obj_set_style_bg_color(sl, COL_ACCENT, LV_PART_INDICATOR);
lv_obj_set_style_bg_color(sl, COL_TEXT, LV_PART_KNOB);
lv_obj_add_event_cb(sl, onOverrideSlider, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_add_event_cb(sl, onOverrideSlider, LV_EVENT_RELEASED, NULL);
return sl;
}
static void build()
{
if (g_screen != NULL)
return;
g_screen = lv_obj_create(NULL);
lv_obj_set_style_bg_color(g_screen, COL_BG, 0);
lv_obj_clear_flag(g_screen, LV_OBJ_FLAG_SCROLLABLE);
// No swipe gesture on this screen: dragging the override sliders would
// otherwise change screens. Leave via the Driveline button (top right).
lv_obj_t *title = lv_label_create(g_screen);
lv_label_set_text(title, "GAUGE TUNING");
lv_obj_set_style_text_font(title, &lv_font_montserrat_30, 0);
lv_obj_set_style_text_color(title, COL_TEXT, 0);
lv_obj_align(title, LV_ALIGN_TOP_LEFT, 24, 16);
lv_obj_t *back = lv_btn_create(g_screen);
lv_obj_set_size(back, 150, 36);
lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -24, 18);
lv_obj_set_style_bg_color(back, COL_ACCENT, 0);
lv_obj_add_event_cb(back, onBack, LV_EVENT_CLICKED, NULL);
lv_obj_t *bl = lv_label_create(back);
lv_label_set_text(bl, LV_SYMBOL_HOME " Driveline");
lv_obj_set_style_text_font(bl, &lv_font_montserrat_14, 0);
lv_obj_center(bl);
lv_obj_t *reset = lv_btn_create(g_screen);
lv_obj_set_size(reset, 150, 36);
lv_obj_align(reset, LV_ALIGN_TOP_RIGHT, -24 - 150 - 12, 18);
lv_obj_set_style_bg_color(reset, COL_PANEL, 0);
lv_obj_add_event_cb(reset, onReset, LV_EVENT_CLICKED, NULL);
lv_obj_t *rl = lv_label_create(reset);
lv_label_set_text(rl, LV_SYMBOL_REFRESH " Defaults");
lv_obj_set_style_text_font(rl, &lv_font_montserrat_14, 0);
lv_obj_center(rl);
// Three columns of panels
lv_obj_t *cols = lv_obj_create(g_screen);
lv_obj_remove_style_all(cols);
lv_obj_set_size(cols, 1024 - 48, 600 - 70 - 30);
lv_obj_align(cols, LV_ALIGN_TOP_LEFT, 24, 66);
lv_obj_set_flex_flow(cols, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(cols, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_clear_flag(cols, LV_OBJ_FLAG_SCROLLABLE);
const lv_coord_t W = 320;
// ---- column 1: tach + alerts ----
lv_obj_t *c1 = lv_obj_create(cols);
lv_obj_remove_style_all(c1);
lv_obj_set_size(c1, W, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(c1, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(c1, 12, 0);
lv_obj_clear_flag(c1, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *tach = makePanel(c1, "TACHOMETER(IO7)", W);
makeRow(tach, F_TACH_PPR);
makeRow(tach, F_TACH_TRIM);
makeRow(tach, F_TACH_MAX_HZ);
g_tach_en_sw = makeSwitchRow(tach, "Output enabled", onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH);
lv_obj_t *alerts = makePanel(c1, "ALERT THRESHOLDS", W);
makeRow(alerts, F_COOLANT_HOT);
makeRow(alerts, F_GEARBOX_HOT);
makeRow(alerts, F_BATT_LOW);
// ---- column 2: coolant gauge ----
lv_obj_t *temp = makePanel(cols, "COOLANT GAUGE(IO8)", W);
makeRow(temp, F_TEMP_HZ);
makeRow(temp, F_TEMP_SLOPE);
makeRow(temp, F_TEMP_OFFSET);
makeRow(temp, F_TEMP_MIN);
makeRow(temp, F_TEMP_DUTY_MAX);
g_temp_en_sw = makeSwitchRow(temp, "Output enabled", onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP);
// lv_obj_t* note = lv_label_create(temp);
// lv_label_set_text(note, "duty = slope x T + offset\n(defaults: 1.5 x T + 50, from the\nCANNY program)");
// lv_obj_set_style_text_font(note, &lv_font_montserrat_14, 0);
// lv_obj_set_style_text_color(note, COL_MUTED, 0);
// ---- column 3: calibration override ----
lv_obj_t *ovr = makePanel(cols, "SIMULATION", 300);
g_ovr_rpm_sw = makeSwitchRow(ovr, "Force tach rpm", onOverrideSwitch, NULL);
g_ovr_rpm_sl = makeSliderRow(ovr, "RPM", 6000, &g_ovr_rpm_lbl);
g_ovr_duty_sw = makeSwitchRow(ovr, "Force coolant duty", onOverrideSwitch, NULL);
g_ovr_duty_sl = makeSliderRow(ovr, "Duty", 255, &g_ovr_duty_lbl);
// lv_obj_t* howto = lv_label_create(ovr);
// lv_label_set_text(howto,
// "Tach: force 1000 rpm, fix Pulses/rev until\n"
// "the needle reads 1000; force 3000, fix Trim.\n"
// "Temp: force a duty, note the needle, repeat;\n"
// "derive Slope/Offset from two marks.\n"
// "Switch overrides OFF when done.");
// lv_obj_set_style_text_font(howto, &lv_font_montserrat_14, 0);
// lv_obj_set_style_text_color(howto, COL_MUTED, 0);
// lv_obj_t *hint = lv_label_create(g_screen);
// lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: back to Driveline");
// lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
// lv_obj_set_style_text_color(hint, COL_MUTED, 0);
// lv_obj_align(hint, LV_ALIGN_BOTTOM_RIGHT, -24, -10);
g_status_lbl = lv_label_create(g_screen);
lv_label_set_text(g_status_lbl, "config v-");
lv_obj_set_style_text_font(g_status_lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_status_lbl, COL_MUTED, 0);
lv_obj_align(g_status_lbl, LV_ALIGN_BOTTOM_RIGHT, -24, -10);
ESP_LOGI("Tuning", "Gauge tuning screen built");
}
// ============================================================================
// PUBLIC API
// ============================================================================
void show()
{
build();
refreshFromTunables();
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
}
void tick()
{
if (g_screen == NULL || lv_scr_act() != g_screen)
return;
static uint32_t last = 0;
if (millis() - last < 500)
return;
last = millis();
if (Tunables::version() == g_shown_version)
return; // nothing changed elsewhere
lvgl_port_lock(-1);
refreshFromTunables();
lvgl_port_unlock();
}
} // namespace TuningScreen
+36
View File
@@ -0,0 +1,36 @@
/*
* Gauge Tuning Screen Module
*
* Hand-coded LVGL screen for the Patrol gauge tunables (link_config_t):
* tach pulses/rev + trim, coolant PWM law, alert thresholds, enables, and a
* bench override (force an rpm / a duty) so the needles can be calibrated
* from the touchscreen while watching the cluster.
*
* Lives in src/ (never touched by SquareLine exports), like DrivelineScreen.
* Reached by swiping RIGHT on the Driveline screen; the Driveline button (top
* right) goes back. No swipe gesture on this screen (it would fight the sliders).
* Every change goes through Tunables, so it is saved to NVS (overrides
* excepted) and pushed to Controller B in the next CONFIG frame.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
namespace TuningScreen {
/**
* @brief Build the screen (idempotent), refresh it from Tunables, and load it.
* @note Caller must hold the LVGL lock.
*/
void show();
/**
* @brief Refresh displayed values if the tunables changed elsewhere (console).
* Cheap no-op unless the screen exists and is on display. Call from
* loop(); takes its own lock.
*/
void tick();
} // namespace TuningScreen
+110 -105
View File
@@ -1,10 +1,16 @@
/*
* UART Manager Module Implementation
*
* 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.
*/
#include "uart_manager.h"
#include "settings_manager.h"
#include "serial_lock.h"
#include "tunables.h"
#include "espnow_link.h"
namespace UARTManager {
@@ -12,65 +18,67 @@ namespace UARTManager {
// UART HARDWARE CONFIGURATION
// ============================================================================
// Controller A specific UART pins (using GPIO headers for direct TTL connection)
// Note: RS485 terminal uses differential signaling and requires RS485-to-TTL converter
// For direct UART connection, use GPIO pin headers instead
#define UART_TX_PIN 44 // GPIO 44 - Connect to Controller B RX (IO1)
#define UART_RX_PIN 43 // GPIO 43 - Not used (TX-only mode)
// GPIO 44 is UART1 TX. On the 5B it does not reach a header: it feeds the
// SP3485 whose A/B pair is on the terminal block. On the bench, 485_A straight
// into B's IO1 works (unterminated, biased high); in the car use a transceiver
// on B or rely on the ESP-NOW leg. See ESP32-S3-LCD-1.3/wiki/pages/controller-link.md
#define UART_TX_PIN 44
#define UART_RX_PIN 43 // unused (TX-only link)
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
// Global UART state variables
static uart_state_t g_uart_state = UART_STATE_OFF;
static TaskHandle_t g_uart_task_handle = NULL;
static QueueHandle_t g_uart_event_queue = NULL;
// Shared automotive data (accessible by CAN driver)
// Shared automotive data (written by the CAN driver)
SemaphoreHandle_t g_data_mutex = NULL;
automotive_data_t g_automotive_data = {0};
static uint8_t g_packet_id = 0;
// UART statistics for debugging
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;
// ============================================================================
// PRIVATE HELPER FUNCTIONS
// ============================================================================
/**
* @brief Initialize default automotive data values
* @note Provides reasonable starting values until CAN bus updates them
* @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.
*/
static void initializeDefaultData() {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
// Set default values (will be overwritten by CAN driver)
g_automotive_data.gear_position = GEAR_PARK;
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.fault_codes = DEFAULT_FAULT_CODES;
g_automotive_data.alerts = DEFAULT_ALERTS;
// Mark all data as valid for now
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_FAULT_CODES;
VALID_FLAG_ALERTS;
// Initialize debug flag (will be updated from UI state manager)
g_automotive_data.debug_enabled = 0;
xSemaphoreGive(g_data_mutex);
}
}
/**
* @brief Update packet metadata (timestamp and ID) without modifying sensor data
* @note Sensor values are updated by CAN driver, we only update transmission metadata
* @brief Update packet metadata (timestamp and ID) without touching sensor data
*/
static void updatePacketMetadata() {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
@@ -81,65 +89,80 @@ static void updatePacketMetadata() {
}
/**
* @brief Send automotive data packet over UART
* @return true if successful, false on error
* @brief Send one already-built frame on both transports.
* @return true if the UART write completed (ESP-NOW is best-effort)
*/
static bool sendUARTPacket() {
uart_packet_t packet;
static bool sendFrame(const uint8_t* frame, size_t len) {
size_t written = Serial1.write(frame, len);
EspNowLink::send(frame, len); // best effort; counted inside the module
return written == len;
}
// Get latest data with mutex protection
/**
* @brief Build and send the DATA frame
*/
static bool sendDataFrame() {
automotive_data_t snapshot;
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) != pdTRUE) {
ESP_LOGE("UARTTask", "Failed to acquire data mutex");
return false;
}
// Build packet
packet.start_byte = PACKET_START_BYTE;
packet.version = PACKET_VERSION;
packet.length = sizeof(automotive_data_t);
memcpy(&packet.data, &g_automotive_data, sizeof(automotive_data_t));
snapshot = g_automotive_data;
xSemaphoreGive(g_data_mutex);
// Calculate checksum (version + length + data)
uint8_t* checksum_start = (uint8_t*)&packet.version;
size_t checksum_size = 2 + packet.length; // version(1) + length(1) + data
packet.checksum = calculate_checksum(checksum_start, checksum_size);
packet.end_byte = PACKET_END_BYTE;
uint8_t frame[PACKET_MAX_SIZE];
size_t len = frame_build(PACKET_TYPE_DATA, &snapshot, sizeof(snapshot), frame);
if (len == 0) return false;
// Send packet over UART1
size_t bytes_written = Serial1.write((uint8_t*)&packet, sizeof(packet));
if (bytes_written == sizeof(packet)) {
if (sendFrame(frame, len)) {
g_uart_stats.packets_sent++;
g_uart_stats.last_send_time = millis();
// Debug output - first 5 packets, then every 10
if (g_uart_stats.packets_sent <= 5 || g_uart_stats.packets_sent % 10 == 0) {
// Hold the serial lock so this line can't splice into a CANRAW frame
// Debug output - first 5 packets, then every 25
if (g_uart_stats.packets_sent <= 5 || g_uart_stats.packets_sent % 25 == 0) {
char gear[8];
gear_compose(snapshot.gear_lever, gear_engaged(snapshot.gear_nibbles), gear, sizeof(gear));
SerialLock::lock();
ESP_LOGI("UARTTask", "✓ TX Packet #%d (Gear:%s, Temps:%d.%d/%d.%d/%d.%d°C, Batt:%d.%02dV, Debug:%s) [%d bytes on GPIO%d]",
packet.data.packet_id,
gear_to_string((gear_position_t)packet.data.gear_position),
packet.data.gearbox_oil_temp / 10, abs(packet.data.gearbox_oil_temp % 10),
packet.data.engine_oil_temp / 10, abs(packet.data.engine_oil_temp % 10),
packet.data.coolant_temp / 10, abs(packet.data.coolant_temp % 10),
packet.data.battery_voltage / 100, packet.data.battery_voltage % 100,
packet.data.debug_enabled ? "ON" : "OFF",
bytes_written, UART_TX_PIN);
ESP_LOGI("UARTTask", "TX #%u gear=%s(t%u/e%u) rpm=%u cool=%d.%d gb=%d.%d batt=%u.%02u alerts=0x%02X valid=0x%02X [%u B uart+espnow, espnow tx=%lu fail=%lu]",
snapshot.packet_id, gear,
gear_target(snapshot.gear_nibbles), gear_engaged(snapshot.gear_nibbles),
snapshot.engine_rpm,
snapshot.coolant_temp / 10, abs(snapshot.coolant_temp % 10),
snapshot.gearbox_oil_temp / 10, abs(snapshot.gearbox_oil_temp % 10),
snapshot.battery_voltage / 100, snapshot.battery_voltage % 100,
snapshot.alerts, snapshot.valid_flags,
(unsigned)len,
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount());
SerialLock::unlock();
}
return true;
} else {
g_uart_stats.send_errors++;
ESP_LOGE("UARTTask", "Send error! Only wrote %d of %d bytes", bytes_written, sizeof(packet));
return false;
}
g_uart_stats.send_errors++;
ESP_LOGE("UARTTask", "UART send error");
return false;
}
/**
* @brief Build and send the CONFIG frame
*/
static void sendConfigFrame(const char* why) {
link_config_t cfg = Tunables::get();
uint8_t frame[PACKET_MAX_SIZE];
size_t len = frame_build(PACKET_TYPE_CONFIG, &cfg, sizeof(cfg), frame);
if (len == 0) return;
sendFrame(frame, len);
g_last_cfg_version_sent = cfg.cfg_version;
g_last_cfg_send_time = millis();
SerialLock::lock();
ESP_LOGI("UARTTask", "TX CONFIG v%u (%s): ppr=%u trim=%d temp_hz=%u slope=%u offset=%d min=%d override=%u",
cfg.cfg_version, why, cfg.tach_ppr, cfg.tach_trim_pct, cfg.temp_pwm_hz,
cfg.temp_slope_x100, cfg.temp_offset, cfg.temp_min_c, cfg.override_mode);
SerialLock::unlock();
}
/**
* @brief UART task - Runs on Core 0
* @param parameter Task parameter (unused)
*/
static void uartTask(void* parameter) {
uart_queue_event_t event;
@@ -148,17 +171,14 @@ static void uartTask(void* parameter) {
ESP_LOGI("UARTTask", "UART task started on Core 0");
// Initialize UART1 hardware
Serial1.setRxBufferSize(256); // Set receive buffer size BEFORE begin()
Serial1.setRxBufferSize(256);
Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d, RX=GPIO%d",
UART_BAUD_RATE, UART_TX_PIN, UART_RX_PIN);
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u",
UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION);
// Initialize default values (will be overwritten by CAN driver when active)
initializeDefaultData();
while (true) {
// Check for control events from the queue
if (xQueueReceive(g_uart_event_queue, &event, pdMS_TO_TICKS(10)) == pdTRUE) {
switch (event.type) {
case UART_EVENT_START:
@@ -167,23 +187,21 @@ static void uartTask(void* parameter) {
g_uart_state = UART_STATE_TRANSMITTING;
g_uart_stats.packets_sent = 0;
g_uart_stats.send_errors = 0;
sendConfigFrame("start");
break;
case UART_EVENT_STOP:
ESP_LOGI("UARTTask", "Stopping transmission...");
transmitting = false;
g_uart_state = UART_STATE_OFF;
// Print final statistics
ESP_LOGI("UARTTask", "Stats: %d packets sent, %d errors",
g_uart_stats.packets_sent, g_uart_stats.send_errors);
break;
case UART_EVENT_SEND_DATA:
// Manual send trigger (not used in periodic mode)
if (transmitting) {
updatePacketMetadata();
sendUARTPacket();
sendDataFrame();
}
break;
@@ -192,18 +210,23 @@ static void uartTask(void* parameter) {
}
}
// Handle periodic transmission at 5Hz (200ms intervals)
if (transmitting) {
unsigned long current_time = millis();
if (current_time - last_transmit_time >= UART_UPDATE_RATE_MS) {
last_transmit_time = current_time;
unsigned long now = millis();
// Update packet metadata (CAN driver updates sensor values)
// CONFIG: on every tunables change, and periodically as a safety net
// (B may have rebooted, or missed the change on both transports).
uint8_t v = Tunables::version();
if (v != g_last_cfg_version_sent) {
sendConfigFrame("changed");
} else if (now - g_last_cfg_send_time >= CONFIG_RESEND_MS) {
sendConfigFrame("periodic");
}
// DATA at 5 Hz
if (now - last_transmit_time >= UART_UPDATE_RATE_MS) {
last_transmit_time = now;
updatePacketMetadata();
// Send packet
if (!sendUARTPacket()) {
// Handle send error
if (!sendDataFrame()) {
if (g_uart_stats.send_errors > 10) {
ESP_LOGE("UARTTask", "Too many send errors, entering error state");
g_uart_state = UART_STATE_ERROR;
@@ -213,8 +236,7 @@ static void uartTask(void* parameter) {
}
}
// Small delay to prevent task from hogging CPU
vTaskDelay(pdMS_TO_TICKS(50));
vTaskDelay(pdMS_TO_TICKS(20));
}
}
@@ -225,27 +247,24 @@ static void uartTask(void* parameter) {
void init(bool auto_start) {
ESP_LOGI("UARTMgr", "Initializing UART subsystem...");
// Create mutex for protecting automotive data
g_data_mutex = xSemaphoreCreateMutex();
if (g_data_mutex == NULL) {
ESP_LOGE("UARTMgr", "ERROR: Failed to create UART data mutex!");
}
// Create event queue for UART task communication
g_uart_event_queue = xQueueCreate(10, sizeof(uart_queue_event_t));
if (g_uart_event_queue == NULL) {
ESP_LOGE("UARTMgr", "ERROR: Failed to create UART event queue!");
}
// Create UART task on Core 0
BaseType_t uart_task_created = xTaskCreatePinnedToCore(
uartTask, // Task function
"UART_Task", // Task name
UART_TASK_STACK_SIZE, // Stack size
NULL, // Parameters
UART_TASK_PRIORITY, // Priority (1)
&g_uart_task_handle, // Task handle
UART_TASK_CORE // Core 0
uartTask,
"UART_Task",
UART_TASK_STACK_SIZE,
NULL,
UART_TASK_PRIORITY,
&g_uart_task_handle,
UART_TASK_CORE
);
if (uart_task_created != pdPASS) {
@@ -254,11 +273,10 @@ void init(bool auto_start) {
ESP_LOGI("UARTMgr", "UART task created successfully on Core 0");
}
// Auto-start UART if requested
if (auto_start) {
ESP_LOGI("UARTMgr", "========================================");
ESP_LOGI("UARTMgr", " AUTO-STARTING UART TRANSMISSION");
ESP_LOGI("UARTMgr", " Baud: %d | TX: GPIO%d | RX: GPIO%d", UART_BAUD_RATE, UART_TX_PIN, UART_RX_PIN);
ESP_LOGI("UARTMgr", " AUTO-STARTING LINK TRANSMISSION");
ESP_LOGI("UARTMgr", " Baud: %d | TX: GPIO%d | + ESP-NOW", UART_BAUD_RATE, UART_TX_PIN);
ESP_LOGI("UARTMgr", "========================================");
uart_queue_event_t evt;
evt.type = UART_EVENT_START;
@@ -266,7 +284,7 @@ void init(bool auto_start) {
xQueueSend(g_uart_event_queue, &evt, 0);
} else {
ESP_LOGI("UARTMgr", "========================================");
ESP_LOGI("UARTMgr", " UART INITIALLY DISABLED");
ESP_LOGI("UARTMgr", " LINK INITIALLY DISABLED");
ESP_LOGI("UARTMgr", " Enable via Settings screen toggle");
ESP_LOGI("UARTMgr", "========================================");
}
@@ -307,38 +325,26 @@ void linkToCANState(bool can_active) {
void onUARTToggle(lv_event_t *e)
{
// Get the actual widget from the event
lv_obj_t *target = lv_event_get_target(e);
// Verify the widget is valid
if (target == NULL) {
ESP_LOGE("UARTMgr", "ERROR: UART toggle target is NULL!");
return;
}
// Check the toggle state
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
ESP_LOGI("UARTMgr", "===== UART Toggle Event =====");
ESP_LOGI("UARTMgr", "UART Toggle State: %s", state ? "ON" : "OFF");
// Save state to NVS for persistence across power cycles
SettingsManager::saveUARTState(state);
// Send event to UART task via queue
uart_queue_event_t evt;
evt.type = state ? UART_EVENT_START : UART_EVENT_STOP;
evt.data = NULL;
// Send event to UART task (non-blocking)
if (g_uart_event_queue != NULL) {
if (xQueueSend(g_uart_event_queue, &evt, pdMS_TO_TICKS(100)) == pdTRUE) {
ESP_LOGI("UARTMgr", "Command sent to task (%s)", state ? "START" : "STOP");
// Optional: Update UI to show UART status
// For now, we'll just update a label if we add one later
// Could show "UART: ON" or "UART: OFF" somewhere on the screen
} else {
ESP_LOGE("UARTMgr", "ERROR: Failed to send command to UART task!");
}
@@ -346,7 +352,6 @@ void onUARTToggle(lv_event_t *e)
ESP_LOGE("UARTMgr", "ERROR: UART event queue not initialized!");
}
// Print current UART statistics if turning off
if (!state && g_uart_state != UART_STATE_OFF) {
ESP_LOGI("UARTMgr", "UART Statistics:");
ESP_LOGI("UARTMgr", " Packets sent: %d", g_uart_stats.packets_sent);
+3 -2
View File
@@ -332,7 +332,8 @@ static void wifiTask(void* parameter) {
case WIFI_UI_EVENT_TOGGLE_OFF:
Serial.println("WiFi Task: Disabling WiFi...");
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
// Radio stays in STA mode: the ESP-NOW link to Controller B
// rides on it. "WiFi off" here means scanning/association off.
g_wifi_state = WIFI_STATE_OFF;
g_network_count = 0;
scanning = false;
@@ -540,7 +541,7 @@ void init(bool auto_start) {
evt.data = NULL;
xQueueSend(g_wifi_event_queue, &evt, 0);
} else {
WiFi.mode(WIFI_OFF);
WiFi.mode(WIFI_STA); // radio stays up for the ESP-NOW link (EspNowLink)
Serial.println("[WiFiManager] WiFi initially disabled");
}
}