Link protocol v2 receiver, ESP-NOW leg, Patrol gauge outputs, gear pulse

- protocol header v2 copied byte-identical from the 5B repo
- uart_receiver: processFrame() shared by the UART framing task and ESP-NOW,
  version check, dedupe on packet_id+timestamp, per-transport liveness,
  CONFIG cache with sequence number
- espnow_receiver: STA mode, channel hopping while silent, locks on frames
- gauge_outputs: tach on IO7 (LEDC ch2, 14-bit), coolant PWM on IO8 (LEDC
  ch4, 8-bit), config cached in NVS, overrides applied but not saved
- main: gear label from lever + engaged/target (pulses while shifting, red on
  mismatch), icons driven by A's alert bits, gauge update at 5 Hz, link stats
- wiki: temp_stage.cfd (user's old CANNY program) decoded as prior art;
  controller-link, link-redundancy, patrol-gauge-outputs, open-questions
  updated with the bench-verified v2 results and calibration procedure

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-21 19:12:38 +02:00
parent 3613387d41
commit 5fe313b7fa
18 changed files with 1658 additions and 514 deletions
+163 -134
View File
@@ -1,15 +1,17 @@
/**
* ESP32-S3-LCD-1.3 - Controller B
* Phase 2: UART Reception & Data Display
*
* This firmware receives automotive data packets from Controller A via UART
* and displays real-time sensor data on the 1.3" round display (240x240 ST7789VW).
* Receives the v2 link from Controller A on UART1 and ESP-NOW, shows the data
* on the 1.3" round display, and drives the Nissan Patrol cluster's tachometer
* and coolant gauge from it (GaugeOutputs, IO7 / IO8).
*/
#include <Arduino.h>
#include <lvgl.h>
#include "modules/display_init.h"
#include "modules/uart_receiver.h"
#include "modules/espnow_receiver.h"
#include "modules/gauge_outputs.h"
#include "modules/debug_monitor.h"
#include "ui/ui.h"
#include "ui/screens/ui_Home_Screen.h"
@@ -17,51 +19,116 @@
// FreeRTOS task handles
TaskHandle_t lvglTaskHandle = NULL;
// Warning thresholds
#define COOLANT_TEMP_WARNING_C 110 // °C (1100 in 0.1°C units)
#define ENGINE_OIL_TEMP_WARNING_C 130 // °C (1300 in 0.1°C units)
#define GEARBOX_OIL_TEMP_WARNING_C 130 // °C (1300 in 0.1°C units)
#define BATTERY_VOLTAGE_WARNING_V 11.0f // V (1100 in 0.01V units)
// Link is considered lost after this long without an applied DATA frame
#define LINK_TIMEOUT_MS 1000
// A shift pulse is shown for at least this long, so a fast shift still blinks
#define SHIFT_PULSE_MIN_MS 600
/**
* Helper function to update sensor icon position, visibility, and color
*
* @param icon_normal Normal color icon object
* @param icon_red Red/warning color icon object
* @param label_ref Label to position relative to
* @param position_below If true, position icon below label; if false, position above
* @param show If true, show appropriate icon; if false, hide both icons
* @param use_red If true and show=true, show red icon; if false, show normal icon
*/
void update_sensor_icon(lv_obj_t* icon_normal, lv_obj_t* icon_red,
lv_obj_t* label_ref, bool position_below,
bool show, bool use_red) {
if (icon_normal == NULL || icon_red == NULL || label_ref == NULL) {
return; // Safety check
return;
}
if (show) {
// Determine which icon to show
lv_obj_t* icon_to_show = use_red ? icon_red : icon_normal;
lv_obj_t* icon_to_hide = use_red ? icon_normal : icon_red;
// Position the icon relative to the label
if (position_below) {
lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_BOTTOM_MID, 0, 2); // 2px gap below
lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_BOTTOM_MID, 0, 2);
} else {
lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_TOP_MID, 0, -2); // 2px gap above
lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_TOP_MID, 0, -2);
}
// Show appropriate icon, hide the other
lv_obj_clear_flag(icon_to_show, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(icon_to_hide, LV_OBJ_FLAG_HIDDEN);
} else {
// Hide both icons when no data
lv_obj_add_flag(icon_normal, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(icon_red, LV_OBJ_FLAG_HIDDEN);
}
}
// ============================================================================
// GEAR LABEL: pulse while the gearbox is still moving to the target gear
// ============================================================================
static lv_anim_t g_gear_anim;
static bool g_gear_pulsing = false;
static uint32_t g_gear_pulse_started = 0;
static bool g_gear_color_saved = false;
static lv_color_t g_gear_color_default;
static void gearOpaCb(void* obj, int32_t v) {
lv_obj_set_style_opa((lv_obj_t*)obj, (lv_opa_t)v, 0);
}
static void startGearPulse() {
if (g_gear_pulsing || ui_Gear_State_LBL == NULL) return;
lv_anim_init(&g_gear_anim);
lv_anim_set_var(&g_gear_anim, ui_Gear_State_LBL);
lv_anim_set_exec_cb(&g_gear_anim, gearOpaCb);
lv_anim_set_values(&g_gear_anim, 255, 60);
lv_anim_set_time(&g_gear_anim, 300);
lv_anim_set_playback_time(&g_gear_anim, 300);
lv_anim_set_repeat_count(&g_gear_anim, LV_ANIM_REPEAT_INFINITE);
lv_anim_start(&g_gear_anim);
g_gear_pulsing = true;
g_gear_pulse_started = millis();
}
static void stopGearPulse() {
if (!g_gear_pulsing || ui_Gear_State_LBL == NULL) return;
lv_anim_del(ui_Gear_State_LBL, gearOpaCb);
lv_obj_set_style_opa(ui_Gear_State_LBL, LV_OPA_COVER, 0);
g_gear_pulsing = false;
}
/**
* Compose and show the gear label from lever + target/engaged nibbles.
* While target != engaged the TARGET digit is shown and the label pulses;
* once they agree the label goes solid on the engaged gear.
*/
static void updateGearLabel(const automotive_data_t& d, bool valid) {
if (ui_Gear_State_LBL == NULL) return;
if (!g_gear_color_saved) {
g_gear_color_default = lv_obj_get_style_text_color(ui_Gear_State_LBL, 0);
g_gear_color_saved = true;
}
if (!valid) {
stopGearPulse();
lv_label_set_text(ui_Gear_State_LBL, "?");
lv_obj_set_style_text_color(ui_Gear_State_LBL, g_gear_color_default, 0);
return;
}
uint8_t target = gear_target(d.gear_nibbles);
uint8_t engaged = gear_engaged(d.gear_nibbles);
bool shifting = gear_shifting(d.gear_nibbles);
uint8_t number = engaged;
if (shifting || (engaged == 0 && target != 0)) number = target;
char buf[8];
gear_compose(d.gear_lever, number, buf, sizeof(buf));
lv_label_set_text(ui_Gear_State_LBL, buf);
if (shifting) {
startGearPulse();
} else if (g_gear_pulsing && (millis() - g_gear_pulse_started) >= SHIFT_PULSE_MIN_MS) {
stopGearPulse();
}
bool mismatch = (d.valid_flags & VALID_FLAG_ALERTS) && (d.alerts & ALERT_GEAR_MISMATCH);
lv_obj_set_style_text_color(ui_Gear_State_LBL,
mismatch ? lv_color_hex(0xFF3B30) : g_gear_color_default, 0);
}
/**
* LVGL update task (runs on Core 1)
*/
@@ -70,39 +137,32 @@ void lvglTask(void *parameter) {
while (true) {
DisplayInit::update();
vTaskDelay(pdMS_TO_TICKS(5)); // ~200 FPS max, actual will be limited by LVGL
vTaskDelay(pdMS_TO_TICKS(5));
}
}
void setup() {
// Initialize serial (USB CDC on ESP32-S3)
Serial.begin(115200);
// Send immediate boot message (may be lost if monitor not connected yet)
Serial.println("\n[BOOT] ESP32-S3-LCD-1.3 starting...");
// Wait for USB CDC to be ready (important for ESP32-S3)
unsigned long start_wait = millis();
while (!Serial && (millis() - start_wait < 3000)) {
delay(100); // Wait up to 3 seconds for serial
delay(100);
}
delay(500); // Additional stabilization time
delay(500);
Serial.println("[BOOT] Serial communication ready!");
Serial.println("\n\n=================================");
Serial.println("ESP32-S3-LCD-1.3 - Controller B");
Serial.println("Phase 2: UART Reception");
Serial.printf("Link protocol v%u | UART + ESP-NOW | gauge outputs\n", PACKET_VERSION);
Serial.println("=================================\n");
// Display hardware info
Serial.printf("CPU Frequency: %d MHz\n", getCpuFrequencyMhz());
Serial.printf("Free Heap: %d bytes\n", ESP.getFreeHeap());
Serial.printf("PSRAM Size: %d bytes\n", ESP.getPsramSize());
Serial.printf("PSRAM Free: %d bytes\n", ESP.getFreePsram());
// Initialize display hardware
if (!DisplayInit::init()) {
Serial.println("[ERROR] Display initialization failed!");
while (1) {
@@ -110,35 +170,33 @@ void setup() {
}
}
// Initialize SquareLine Studio UI
Serial.println("[UI] Initializing SquareLine Studio UI...");
ui_init();
Serial.println("[UI] SquareLine Studio UI initialized");
// Create LVGL update task on Core 1
xTaskCreatePinnedToCore(
lvglTask,
"LVGL_Task",
8192, // Stack size
NULL,
2, // Priority
&lvglTaskHandle,
1 // Core 1
);
xTaskCreatePinnedToCore(lvglTask, "LVGL_Task", 8192, NULL, 2, &lvglTaskHandle, 1);
// Initialize debug monitor module
Serial.println("\n[Debug] Initializing debug monitor control...");
DebugMonitor::init();
// Initialize UART receiver (creates task on Core 0)
Serial.println("\n[UART] Initializing UART receiver...");
// Gauge outputs before the receivers, so the first CONFIG frame has
// somewhere to land and the pins are already driven low.
Serial.println("\n[Gauges] Initializing Patrol gauge outputs...");
GaugeOutputs::init();
Serial.println("\n[UART] Initializing link receiver...");
if (!UARTReceiver::init()) {
Serial.println("[ERROR] UART receiver initialization failed!");
Serial.println("[ERROR] Link receiver initialization failed!");
while (1) {
delay(1000);
}
}
Serial.println("[UART] UART receiver initialized");
Serial.println("[UART] Link receiver initialized");
Serial.println("\n[EspNow] Initializing ESP-NOW receiver...");
if (!EspNowReceiver::init()) {
Serial.println("[WARN] ESP-NOW receiver failed to start - UART only");
}
Serial.println("\n[Setup] Complete! Starting main loop...\n");
}
@@ -147,153 +205,124 @@ void loop() {
static uint32_t last_stats_print = 0;
static uint32_t last_connection_check = 0;
static uint32_t last_ui_update = 0;
static uint32_t last_cfg_seq = 0;
static bool was_connected = false;
// Print UART statistics every 5 seconds
// Wireless leg housekeeping (channel hopping while silent)
EspNowReceiver::tick();
// Apply a new CONFIG from A. Overrides are a bench tool: applied but not
// persisted, so a reboot never leaves the gauges pinned to a test value.
uint32_t cfg_seq = UARTReceiver::getConfigSeq();
if (cfg_seq != last_cfg_seq) {
last_cfg_seq = cfg_seq;
link_config_t cfg = UARTReceiver::getConfig();
GaugeOutputs::applyConfig(cfg, cfg.override_mode == 0);
}
// Statistics every 5 seconds
if (millis() - last_stats_print > 5000) {
last_stats_print = millis();
UARTReceiver::uart_rx_stats_t stats = UARTReceiver::getStats();
UARTReceiver::uart_rx_stats_t s = UARTReceiver::getStats();
Serial.printf("[Stats] Uptime: %lu s | Free Heap: %d bytes\n",
millis() / 1000,
ESP.getFreeHeap());
Serial.printf("[UART Stats] Packets: %lu | Checksum Errors: %lu | Framing Errors: %lu | Bytes RX: %lu\n",
stats.packets_received,
stats.checksum_errors,
stats.framing_errors,
stats.bytes_received);
if (stats.packets_received > 0) {
uint32_t time_since = UARTReceiver::getTimeSinceLastPacket();
Serial.printf("[UART Stats] Last packet: %lu ms ago\n", time_since);
millis() / 1000, ESP.getFreeHeap());
Serial.printf("[Link] applied=%lu uart=%lu espnow=%lu dup=%lu cfg=%lu | chk=%lu frame=%lu ver=%lu | uart %s, espnow %s (ch %u)\n",
(unsigned long)s.packets_received, (unsigned long)s.packets_uart,
(unsigned long)s.packets_espnow, (unsigned long)s.duplicates,
(unsigned long)s.config_received,
(unsigned long)s.checksum_errors, (unsigned long)s.framing_errors,
(unsigned long)s.version_errors,
UARTReceiver::isSourceAlive(LINK_SOURCE_UART, LINK_TIMEOUT_MS) ? "alive" : "silent",
UARTReceiver::isSourceAlive(LINK_SOURCE_ESPNOW, LINK_TIMEOUT_MS) ? "alive" : "silent",
EspNowReceiver::currentChannel());
if (s.packets_received > 0) {
Serial.printf("[Link] Last packet: %lu ms ago\n", (unsigned long)UARTReceiver::getTimeSinceLastPacket());
}
GaugeOutputs::printStatus();
}
// Check connection status every second
// Connection state changes
if (millis() - last_connection_check > 1000) {
last_connection_check = millis();
bool is_connected = UARTReceiver::isConnected(1000); // 1 second timeout
// Log connection state changes
bool is_connected = UARTReceiver::isConnected(LINK_TIMEOUT_MS);
if (is_connected && !was_connected) {
Serial.println("[UART] Connection ESTABLISHED with Controller A");
automotive_data_t data = UARTReceiver::getLatestData();
char gearbox_buf[16], engine_buf[16], voltage_buf[16];
Serial.printf("[Data] Gear:%s | Gearbox:%s | Engine:%s | Battery:%s | Debug:%s\n",
gear_to_string((gear_position_t)data.gear_position),
format_temperature(data.gearbox_oil_temp, gearbox_buf),
format_temperature(data.engine_oil_temp, engine_buf),
format_voltage(data.battery_voltage, voltage_buf),
data.debug_enabled ? "ON" : "OFF");
Serial.println("[Link] Connection ESTABLISHED with Controller A");
} else if (!is_connected && was_connected) {
Serial.println("[UART] Connection LOST - No data from Controller A");
Serial.println("[Link] Connection LOST - no data from Controller A");
}
was_connected = is_connected;
}
// Update UI labels every 200ms (5Hz, matching UART packet rate)
// UI + gauge outputs at the packet rate (5 Hz)
if (millis() - last_ui_update > 200) {
last_ui_update = millis();
automotive_data_t data = UARTReceiver::getLatestData();
bool is_connected = UARTReceiver::isConnected(1000);
bool is_connected = UARTReceiver::isConnected(LINK_TIMEOUT_MS);
GaugeOutputs::update(data, is_connected);
if (is_connected) {
// Connection active - update labels with real data
// Check valid_flags per protocol requirement (UART_PROTOCOL.md lines 242, 554, 560)
char gearbox_buf[16], engine_buf[16], coolant_buf[16], voltage_buf[16];
bool alerts_valid = (data.valid_flags & VALID_FLAG_ALERTS);
uint16_t alerts = alerts_valid ? data.alerts : 0;
// Update Gearbox Oil Temperature (check VALID_FLAG_GEARBOX_TEMP)
if (data.valid_flags & VALID_FLAG_GEARBOX_TEMP) {
lv_label_set_text(ui_GB_Oil_Temp_LBL, format_temperature(data.gearbox_oil_temp, gearbox_buf));
} else {
lv_label_set_text(ui_GB_Oil_Temp_LBL, "---"); // Invalid per protocol line 560
lv_label_set_text(ui_GB_Oil_Temp_LBL, "---");
}
// Update Engine Oil Temperature (check VALID_FLAG_ENGINE_TEMP)
if (data.valid_flags & VALID_FLAG_ENGINE_TEMP) {
lv_label_set_text(ui_Engine_Oil_Temp_LBL, format_temperature(data.engine_oil_temp, engine_buf));
} else {
lv_label_set_text(ui_Engine_Oil_Temp_LBL, "---");
}
// Update Water/Coolant Temperature (check VALID_FLAG_COOLANT_TEMP)
if (data.valid_flags & VALID_FLAG_COOLANT_TEMP) {
lv_label_set_text(ui_Water_Temp_LBL, format_temperature(data.coolant_temp, coolant_buf));
} else {
lv_label_set_text(ui_Water_Temp_LBL, "---");
}
// Update Battery Voltage (check VALID_FLAG_BATTERY_VOLT)
if (data.valid_flags & VALID_FLAG_BATTERY_VOLT) {
lv_label_set_text(ui_Battery_Voltage_LBL, format_voltage(data.battery_voltage, voltage_buf));
} else {
lv_label_set_text(ui_Battery_Voltage_LBL, "---");
}
// Update Gear Position (check VALID_FLAG_GEAR_POS)
if (ui_Gear_State_LBL != NULL) {
if (data.valid_flags & VALID_FLAG_GEAR_POS) {
lv_label_set_text(ui_Gear_State_LBL, gear_to_string((gear_position_t)data.gear_position));
} else {
lv_label_set_text(ui_Gear_State_LBL, "?");
}
}
updateGearLabel(data, (data.valid_flags & VALID_FLAG_GEAR_POS) != 0);
// Update sensor icons with warning logic
// Icons only shown if data is BOTH connected AND valid (per protocol)
// Temperature values are in 0.1°C units (e.g., 850 = 85.0°C)
// Voltage values are in 0.01V units (e.g., 1250 = 12.50V)
// Top Container Icons (positioned BELOW labels)
// Water/Coolant Temperature - show only if valid, warn if >= 110°C
// Icons: shown when the value is valid, red when A raised the alert.
// Thresholds live on A (Tunables); B only renders the bits.
bool coolant_valid = (data.valid_flags & VALID_FLAG_COOLANT_TEMP);
bool coolant_warning = coolant_valid && (data.coolant_temp >= (COOLANT_TEMP_WARNING_C * 10));
update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red,
ui_Water_Temp_LBL, true, coolant_valid, coolant_warning);
update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red, ui_Water_Temp_LBL, true,
coolant_valid, (alerts & ALERT_COOLANT_HOT) != 0);
// Gearbox Oil Temperature - show only if valid, warn if >= 130°C
bool gearbox_valid = (data.valid_flags & VALID_FLAG_GEARBOX_TEMP);
bool gearbox_warning = gearbox_valid && (data.gearbox_oil_temp >= (GEARBOX_OIL_TEMP_WARNING_C * 10));
update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red,
ui_GB_Oil_Temp_LBL, true, gearbox_valid, gearbox_warning);
update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red, ui_GB_Oil_Temp_LBL, true,
gearbox_valid, (alerts & (ALERT_GEARBOX_HOT | ALERT_GEARBOX_COOLING)) != 0);
// Bottom Container Icons (positioned ABOVE labels)
// Battery Voltage - show only if valid, warn if < threshold
bool battery_valid = (data.valid_flags & VALID_FLAG_BATTERY_VOLT);
bool battery_warning = battery_valid && (data.battery_voltage < (uint16_t)(BATTERY_VOLTAGE_WARNING_V * 100));
update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red,
ui_Battery_Voltage_LBL, false, battery_valid, battery_warning);
update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red, ui_Battery_Voltage_LBL, false,
battery_valid, (alerts & ALERT_BATTERY_LOW) != 0);
// Engine Oil Temperature - show only if valid, warn if >= 130°C
// Engine oil has no sensor on this engine and no alert bit; never red.
bool engine_oil_valid = (data.valid_flags & VALID_FLAG_ENGINE_TEMP);
bool engine_oil_warning = engine_oil_valid && (data.engine_oil_temp >= (ENGINE_OIL_TEMP_WARNING_C * 10));
update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red,
ui_Engine_Oil_Temp_LBL, false, engine_oil_valid, engine_oil_warning);
update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red, ui_Engine_Oil_Temp_LBL, false,
engine_oil_valid, false);
} else {
// No connection - show "N/A" warning and hide all icons
lv_label_set_text(ui_GB_Oil_Temp_LBL, "N/A");
lv_label_set_text(ui_Engine_Oil_Temp_LBL, "N/A");
lv_label_set_text(ui_Water_Temp_LBL, "N/A");
lv_label_set_text(ui_Battery_Voltage_LBL, "N/A");
if (ui_Gear_State_LBL != NULL) {
lv_label_set_text(ui_Gear_State_LBL, "?");
}
updateGearLabel(data, false);
// Hide all sensor icons when disconnected
update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red,
ui_Water_Temp_LBL, true, false, false);
update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red,
ui_GB_Oil_Temp_LBL, true, false, false);
update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red,
ui_Battery_Voltage_LBL, false, false, false);
update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red,
ui_Engine_Oil_Temp_LBL, false, false, false);
update_sensor_icon(ui_Engine_Water, ui_Engine_Water_Red, ui_Water_Temp_LBL, true, false, false);
update_sensor_icon(ui_GearBox_Oil, ui_GearBox_Oil_Red, ui_GB_Oil_Temp_LBL, true, false, false);
update_sensor_icon(ui_Battery_Voltage, ui_Battery_Voltage_Red, ui_Battery_Voltage_LBL, false, false, false);
update_sensor_icon(ui_Engine_Oil, ui_Engine_Oil_Red, ui_Engine_Oil_Temp_LBL, false, false, false);
}
}