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:
+163
-134
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* ESP-NOW Receiver Module Implementation (Controller B)
|
||||
*/
|
||||
|
||||
#include "modules/espnow_receiver.h"
|
||||
#include "modules/uart_receiver.h"
|
||||
#include "protocol/automotive_data.h"
|
||||
#include <WiFi.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <esp_now.h>
|
||||
|
||||
namespace EspNowReceiver {
|
||||
|
||||
#define HOP_SILENCE_MS 1500 // no frame for this long -> start hopping
|
||||
#define HOP_DWELL_MS 400 // time spent on each channel while hopping
|
||||
#define CHANNEL_MAX 13
|
||||
|
||||
static bool g_ready = false;
|
||||
static volatile uint32_t g_frames = 0;
|
||||
static volatile uint32_t g_last_frame_ms = 0;
|
||||
static uint8_t g_channel = ESPNOW_CHANNEL;
|
||||
static uint32_t g_last_hop_ms = 0;
|
||||
static bool g_locked = false;
|
||||
|
||||
static void onReceive(const uint8_t* mac, const uint8_t* data, int len) {
|
||||
(void)mac;
|
||||
if (len <= 0) return;
|
||||
g_frames++;
|
||||
g_last_frame_ms = millis();
|
||||
UARTReceiver::processFrame(data, (size_t)len, LINK_SOURCE_ESPNOW);
|
||||
}
|
||||
|
||||
static void setChannel(uint8_t ch) {
|
||||
esp_wifi_set_channel(ch, WIFI_SECOND_CHAN_NONE);
|
||||
g_channel = ch;
|
||||
}
|
||||
|
||||
bool init() {
|
||||
if (g_ready) return true;
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.disconnect();
|
||||
WiFi.setSleep(false);
|
||||
setChannel(ESPNOW_CHANNEL);
|
||||
|
||||
if (esp_now_init() != ESP_OK) {
|
||||
Serial.println("[EspNow] esp_now_init failed");
|
||||
return false;
|
||||
}
|
||||
esp_now_register_recv_cb(onReceive);
|
||||
|
||||
g_ready = true;
|
||||
g_last_hop_ms = millis();
|
||||
Serial.printf("[EspNow] Listening: STA %s, channel %u (will hop if silent)\n",
|
||||
WiFi.macAddress().c_str(), g_channel);
|
||||
return true;
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (!g_ready) return;
|
||||
uint32_t now = millis();
|
||||
uint32_t since = now - g_last_frame_ms;
|
||||
|
||||
if (g_frames > 0 && since < HOP_SILENCE_MS) {
|
||||
if (!g_locked) {
|
||||
g_locked = true;
|
||||
Serial.printf("[EspNow] Locked on channel %u\n", g_channel);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Silent: hop. Start from the configured channel so the common case
|
||||
// (A not on an AP) is found without a full sweep.
|
||||
if (now - g_last_hop_ms >= HOP_DWELL_MS) {
|
||||
g_last_hop_ms = now;
|
||||
if (g_locked) {
|
||||
g_locked = false;
|
||||
Serial.printf("[EspNow] Silent for %lu ms - hopping\n", (unsigned long)since);
|
||||
}
|
||||
uint8_t next = g_channel + 1;
|
||||
if (next > CHANNEL_MAX) next = 1;
|
||||
setChannel(next);
|
||||
}
|
||||
}
|
||||
|
||||
bool isReady() { return g_ready; }
|
||||
uint8_t currentChannel() { return g_channel; }
|
||||
uint32_t framesReceived() { return g_frames; }
|
||||
|
||||
} // namespace EspNowReceiver
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* Gauge Outputs Module Implementation (Controller B)
|
||||
*
|
||||
* LEDC channel plan (Arduino-ESP32 2.x: timer = channel / 2):
|
||||
* channel 1 -> timer 0 : LovyanGFX backlight (display_init.cpp, 44.1 kHz)
|
||||
* channel 2 -> timer 1 : tachometer (frequency varies with rpm)
|
||||
* channel 4 -> timer 2 : coolant PWM (fixed frequency, duty varies)
|
||||
* The two gauge channels sit on their own timers so changing the tach
|
||||
* frequency never disturbs the backlight or the coolant PWM.
|
||||
*/
|
||||
|
||||
#include "modules/gauge_outputs.h"
|
||||
#include <Preferences.h>
|
||||
#include <math.h>
|
||||
|
||||
namespace GaugeOutputs {
|
||||
|
||||
#define TACH_CHANNEL 2
|
||||
#define TEMP_CHANNEL 4
|
||||
#define TEMP_RESOLUTION 8 // bits; duty 0..255 (matches the config's 8-bit law)
|
||||
// The tach runs from ~5 Hz to a few hundred Hz. The LEDC divider only reaches
|
||||
// low frequencies with a high duty resolution (f_min ~= 80 MHz / (2^res * 1024)),
|
||||
// so the tach timer uses 14 bits: ~4.8 Hz .. ~4.9 kHz.
|
||||
#define TACH_RESOLUTION 14
|
||||
#define TACH_DUTY (1 << (TACH_RESOLUTION - 1)) // 50 %
|
||||
#define TACH_MIN_HZ 5.0
|
||||
|
||||
static const char* NVS_NAMESPACE = "gaugecfg";
|
||||
static const char* NVS_KEY_BLOB = "cfg";
|
||||
|
||||
static link_config_t g_cfg;
|
||||
static bool g_initialized = false;
|
||||
|
||||
// Live output state, for status and change detection
|
||||
static bool g_tach_on = false;
|
||||
static double g_tach_hz = 0.0;
|
||||
static bool g_temp_on = false;
|
||||
static uint8_t g_temp_duty = 0;
|
||||
static uint16_t g_temp_hz_setup = 0;
|
||||
static const char* g_tach_src = "off";
|
||||
static const char* g_temp_src = "off";
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPERS
|
||||
// ============================================================================
|
||||
|
||||
static void saveConfig() {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, false);
|
||||
prefs.putBytes(NVS_KEY_BLOB, &g_cfg, sizeof(g_cfg));
|
||||
prefs.end();
|
||||
}
|
||||
|
||||
static bool loadConfig() {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, true);
|
||||
bool ok = false;
|
||||
if (prefs.getBytesLength(NVS_KEY_BLOB) == sizeof(link_config_t)) {
|
||||
prefs.getBytes(NVS_KEY_BLOB, &g_cfg, sizeof(g_cfg));
|
||||
ok = true;
|
||||
}
|
||||
prefs.end();
|
||||
return ok;
|
||||
}
|
||||
|
||||
static void tachOff() {
|
||||
if (g_tach_on) {
|
||||
ledcWrite(TACH_CHANNEL, 0);
|
||||
g_tach_on = false;
|
||||
}
|
||||
g_tach_hz = 0.0;
|
||||
}
|
||||
|
||||
static void tachSet(double hz) {
|
||||
// Only touch the timer when the frequency actually moved; every change
|
||||
// restarts the period and would jitter the needle if done each frame.
|
||||
if (!g_tach_on || fabs(hz - g_tach_hz) > 0.25) {
|
||||
double got = ledcChangeFrequency(TACH_CHANNEL, hz, TACH_RESOLUTION);
|
||||
if (got <= 0.0) {
|
||||
tachOff();
|
||||
return;
|
||||
}
|
||||
g_tach_hz = hz;
|
||||
}
|
||||
if (!g_tach_on) {
|
||||
ledcWrite(TACH_CHANNEL, TACH_DUTY);
|
||||
g_tach_on = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void tempSetupFrequency(uint16_t hz) {
|
||||
if (hz < 20) hz = 20;
|
||||
if (hz == g_temp_hz_setup) return;
|
||||
ledcSetup(TEMP_CHANNEL, hz, TEMP_RESOLUTION);
|
||||
ledcAttachPin(GAUGE_TEMP_PIN, TEMP_CHANNEL);
|
||||
ledcWrite(TEMP_CHANNEL, g_temp_on ? g_temp_duty : 0);
|
||||
g_temp_hz_setup = hz;
|
||||
}
|
||||
|
||||
static void tempSet(uint8_t duty) {
|
||||
if (!g_temp_on || duty != g_temp_duty) {
|
||||
ledcWrite(TEMP_CHANNEL, duty);
|
||||
g_temp_duty = duty;
|
||||
g_temp_on = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void tempOff() {
|
||||
if (g_temp_on) {
|
||||
ledcWrite(TEMP_CHANNEL, 0);
|
||||
g_temp_on = false;
|
||||
}
|
||||
g_temp_duty = 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
void init() {
|
||||
if (g_initialized) return;
|
||||
|
||||
if (!loadConfig()) {
|
||||
link_config_defaults(&g_cfg);
|
||||
Serial.println("[Gauges] No cached config - using defaults until A sends one");
|
||||
} else {
|
||||
Serial.printf("[Gauges] Cached config v%u loaded from NVS\n", g_cfg.cfg_version);
|
||||
}
|
||||
|
||||
// Tach: set up at a nominal frequency, output low until data arrives.
|
||||
ledcSetup(TACH_CHANNEL, 100, TACH_RESOLUTION);
|
||||
ledcAttachPin(GAUGE_TACH_PIN, TACH_CHANNEL);
|
||||
ledcWrite(TACH_CHANNEL, 0);
|
||||
|
||||
// Temp: fixed frequency from config, duty 0.
|
||||
tempSetupFrequency(g_cfg.temp_pwm_hz);
|
||||
ledcWrite(TEMP_CHANNEL, 0);
|
||||
|
||||
g_initialized = true;
|
||||
Serial.printf("[Gauges] Outputs ready: tach IO%d (LEDC ch%d), temp IO%d (LEDC ch%d @ %u Hz)\n",
|
||||
GAUGE_TACH_PIN, TACH_CHANNEL, GAUGE_TEMP_PIN, TEMP_CHANNEL, g_cfg.temp_pwm_hz);
|
||||
}
|
||||
|
||||
void applyConfig(const link_config_t& cfg, bool persist) {
|
||||
g_cfg = cfg;
|
||||
tempSetupFrequency(g_cfg.temp_pwm_hz);
|
||||
// Force the tach to re-evaluate its frequency on the next update().
|
||||
g_tach_hz = -1.0;
|
||||
if (persist) saveConfig();
|
||||
Serial.printf("[Gauges] Config v%u applied%s: ppr=%u trim=%d%% temp=%uHz slope=%u.%02u offset=%d min=%dC override=%u\n",
|
||||
g_cfg.cfg_version, persist ? " (saved)" : "",
|
||||
g_cfg.tach_ppr, g_cfg.tach_trim_pct, g_cfg.temp_pwm_hz,
|
||||
g_cfg.temp_slope_x100 / 100, g_cfg.temp_slope_x100 % 100,
|
||||
g_cfg.temp_offset, g_cfg.temp_min_c, g_cfg.override_mode);
|
||||
}
|
||||
|
||||
link_config_t getConfig() {
|
||||
return g_cfg;
|
||||
}
|
||||
|
||||
void update(const automotive_data_t& d, bool link_ok) {
|
||||
if (!g_initialized) return;
|
||||
|
||||
// ---------------- tachometer ----------------
|
||||
{
|
||||
bool have = false;
|
||||
uint32_t rpm = 0;
|
||||
if (g_cfg.override_mode & OVERRIDE_TACH) {
|
||||
have = true; rpm = g_cfg.override_rpm; g_tach_src = "override";
|
||||
} else if (link_ok && (d.valid_flags & VALID_FLAG_RPM)) {
|
||||
have = true; rpm = d.engine_rpm; g_tach_src = "can";
|
||||
} else {
|
||||
g_tach_src = link_ok ? "no-rpm" : "no-link";
|
||||
}
|
||||
|
||||
if (!(g_cfg.out_enable & OUT_ENABLE_TACH)) { have = false; g_tach_src = "disabled"; }
|
||||
|
||||
if (have && rpm > 0 && g_cfg.tach_ppr > 0) {
|
||||
double hz = (double)rpm * g_cfg.tach_ppr / 60.0;
|
||||
hz *= (1.0 + g_cfg.tach_trim_pct / 100.0);
|
||||
if (g_cfg.tach_min_hz && hz < g_cfg.tach_min_hz) hz = g_cfg.tach_min_hz;
|
||||
if (g_cfg.tach_max_hz && hz > g_cfg.tach_max_hz) hz = g_cfg.tach_max_hz;
|
||||
if (hz >= TACH_MIN_HZ) tachSet(hz); else tachOff();
|
||||
} else {
|
||||
tachOff();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- coolant gauge ----------------
|
||||
{
|
||||
bool have = false;
|
||||
int32_t duty = 0;
|
||||
if (g_cfg.override_mode & OVERRIDE_TEMP) {
|
||||
have = true; duty = g_cfg.override_duty; g_temp_src = "override";
|
||||
} else if (link_ok && (d.valid_flags & VALID_FLAG_COOLANT_TEMP)) {
|
||||
int32_t t_c = d.coolant_temp / 10; // 0.1 degC -> degC
|
||||
if (t_c >= g_cfg.temp_min_c) {
|
||||
have = true;
|
||||
duty = ((int32_t)g_cfg.temp_slope_x100 * t_c) / 100 + g_cfg.temp_offset;
|
||||
g_temp_src = "can";
|
||||
} else {
|
||||
g_temp_src = "below-min";
|
||||
}
|
||||
} else {
|
||||
g_temp_src = link_ok ? "no-temp" : "no-link";
|
||||
}
|
||||
|
||||
if (!(g_cfg.out_enable & OUT_ENABLE_TEMP)) { have = false; g_temp_src = "disabled"; }
|
||||
|
||||
if (have) {
|
||||
if (duty < 0) duty = 0;
|
||||
if (duty > g_cfg.temp_duty_max) duty = g_cfg.temp_duty_max;
|
||||
tempSet((uint8_t)duty);
|
||||
} else {
|
||||
tempOff();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void printStatus() {
|
||||
Serial.printf("[Gauges] tach: %s %.1f Hz (%s) | temp: %s duty %u/255 @ %u Hz (%s) | cfg v%u\n",
|
||||
g_tach_on ? "ON " : "off", g_tach_hz > 0 ? g_tach_hz : 0.0, g_tach_src,
|
||||
g_temp_on ? "ON " : "off", g_temp_duty, g_temp_hz_setup, g_temp_src,
|
||||
g_cfg.cfg_version);
|
||||
}
|
||||
|
||||
} // namespace GaugeOutputs
|
||||
+208
-178
@@ -1,8 +1,5 @@
|
||||
/**
|
||||
* UART Receiver Module Implementation
|
||||
*
|
||||
* Receives automotive data packets from Controller A via UART1.
|
||||
* Uses state machine for robust packet parsing and framing.
|
||||
* Link Receiver Module Implementation (Controller B)
|
||||
*/
|
||||
|
||||
#include "modules/uart_receiver.h"
|
||||
@@ -13,65 +10,159 @@
|
||||
|
||||
namespace UARTReceiver {
|
||||
|
||||
// UART Configuration
|
||||
// Note: UART_RX_PIN, UART_TX_PIN, and UART_BAUD_RATE are defined in platformio.ini
|
||||
#define UART_SERIAL_PORT Serial1 // Hardware UART1
|
||||
#define UART_RX_BUFFER_SIZE 256 // Receive buffer size
|
||||
#define UART_SERIAL_PORT Serial1
|
||||
#define UART_RX_BUFFER_SIZE 256
|
||||
|
||||
// Packet framing state machine states
|
||||
// UART framing state machine
|
||||
typedef enum {
|
||||
STATE_WAIT_START, // Waiting for start byte (0xAA)
|
||||
STATE_READ_VERSION, // Reading protocol version
|
||||
STATE_READ_LENGTH, // Reading data length
|
||||
STATE_READ_DATA, // Reading data payload
|
||||
STATE_READ_CHECKSUM, // Reading checksum byte
|
||||
STATE_READ_END // Reading end byte (0x55)
|
||||
STATE_WAIT_START,
|
||||
STATE_READ_VERSION,
|
||||
STATE_READ_TYPE,
|
||||
STATE_READ_LENGTH,
|
||||
STATE_READ_PAYLOAD,
|
||||
STATE_READ_CHECKSUM,
|
||||
STATE_READ_END
|
||||
} rx_state_t;
|
||||
|
||||
// Private state variables
|
||||
static automotive_data_t g_latest_data = {0};
|
||||
static link_config_t g_config;
|
||||
static uint32_t g_config_seq = 0;
|
||||
static uart_rx_stats_t g_rx_stats = {0};
|
||||
static SemaphoreHandle_t g_data_mutex = NULL;
|
||||
static TaskHandle_t g_uart_task_handle = NULL;
|
||||
static bool g_initialized = false;
|
||||
|
||||
// Dedupe key of the last applied DATA frame
|
||||
static bool g_have_last = false;
|
||||
static uint8_t g_last_id = 0;
|
||||
static uint32_t g_last_ts = 0;
|
||||
|
||||
static const char* sourceName(link_source_t s) {
|
||||
switch (s) {
|
||||
case LINK_SOURCE_UART: return "uart";
|
||||
case LINK_SOURCE_ESPNOW: return "espnow";
|
||||
default: return "none";
|
||||
}
|
||||
}
|
||||
|
||||
static void bump(uint32_t* counter) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
(*counter)++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
void processFrame(const uint8_t* frame, size_t len, link_source_t source) {
|
||||
uint8_t type = 0, plen = 0;
|
||||
const uint8_t* payload = NULL;
|
||||
frame_status_t st = frame_parse(frame, len, &type, &payload, &plen);
|
||||
|
||||
if (st != FRAME_OK) {
|
||||
switch (st) {
|
||||
case FRAME_ERR_VERSION:
|
||||
bump(&g_rx_stats.version_errors);
|
||||
if (g_rx_stats.version_errors <= 3 || g_rx_stats.version_errors % 50 == 0) {
|
||||
Serial.printf("[Link] Version mismatch on %s: got v%u, this firmware speaks v%u (%lu so far)\n",
|
||||
sourceName(source), frame[1], PACKET_VERSION,
|
||||
(unsigned long)g_rx_stats.version_errors);
|
||||
}
|
||||
break;
|
||||
case FRAME_ERR_CHECKSUM:
|
||||
bump(&g_rx_stats.checksum_errors);
|
||||
Serial.printf("[Link] Checksum error on %s\n", sourceName(source));
|
||||
break;
|
||||
default:
|
||||
bump(&g_rx_stats.framing_errors);
|
||||
Serial.printf("[Link] Framing error %d on %s (len %u)\n", (int)st, sourceName(source), (unsigned)len);
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
|
||||
if (type == PACKET_TYPE_CONFIG) {
|
||||
link_config_t cfg;
|
||||
memcpy(&cfg, payload, sizeof(cfg));
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
bool changed = (g_config_seq == 0) || (cfg.cfg_version != g_config.cfg_version);
|
||||
if (changed) {
|
||||
g_config = cfg;
|
||||
g_config_seq++;
|
||||
}
|
||||
g_rx_stats.config_received++;
|
||||
if (source == LINK_SOURCE_UART) g_rx_stats.last_uart_time = now;
|
||||
else if (source == LINK_SOURCE_ESPNOW) g_rx_stats.last_espnow_time = now;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
if (changed) {
|
||||
Serial.printf("[Link] CONFIG v%u received on %s\n", cfg.cfg_version, sourceName(source));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// DATA
|
||||
automotive_data_t d;
|
||||
memcpy(&d, payload, sizeof(d));
|
||||
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(50)) != pdTRUE) return;
|
||||
|
||||
if (source == LINK_SOURCE_UART) { g_rx_stats.packets_uart++; g_rx_stats.last_uart_time = now; }
|
||||
else if (source == LINK_SOURCE_ESPNOW) { g_rx_stats.packets_espnow++; g_rx_stats.last_espnow_time = now; }
|
||||
|
||||
bool dup = g_have_last && d.packet_id == g_last_id && d.timestamp_ms == g_last_ts;
|
||||
if (dup) {
|
||||
g_rx_stats.duplicates++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
return;
|
||||
}
|
||||
|
||||
g_have_last = true;
|
||||
g_last_id = d.packet_id;
|
||||
g_last_ts = d.timestamp_ms;
|
||||
g_latest_data = d;
|
||||
g_rx_stats.packets_received++;
|
||||
g_rx_stats.last_packet_time = now;
|
||||
g_rx_stats.last_source = source;
|
||||
uint32_t n = g_rx_stats.packets_received;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
|
||||
DebugMonitor::setVisible(d.debug_enabled != 0);
|
||||
|
||||
if (n % 25 == 0) {
|
||||
char gear[8], gearbox_buf[16], coolant_buf[16], voltage_buf[16];
|
||||
gear_compose(d.gear_lever, gear_engaged(d.gear_nibbles), gear, sizeof(gear));
|
||||
Serial.printf("[Link] RX #%u via %s | Gear:%s (t%u/e%u) | RPM:%u | GB:%s | Cool:%s | Batt:%s | Alerts:0x%02X | Valid:0x%02X\n",
|
||||
d.packet_id, sourceName(source), gear,
|
||||
gear_target(d.gear_nibbles), gear_engaged(d.gear_nibbles),
|
||||
d.engine_rpm,
|
||||
format_temperature(d.gearbox_oil_temp, gearbox_buf),
|
||||
format_temperature(d.coolant_temp, coolant_buf),
|
||||
format_voltage(d.battery_voltage, voltage_buf),
|
||||
d.alerts, d.valid_flags);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief UART reception task - runs on Core 0
|
||||
*
|
||||
* Implements state machine for packet parsing:
|
||||
* 1. Wait for start byte (0xAA)
|
||||
* 2. Read version and length
|
||||
* 3. Read data payload
|
||||
* 4. Read checksum
|
||||
* 5. Read end byte (0x55)
|
||||
* 6. Validate packet
|
||||
* 7. Update shared data structure
|
||||
* UART1 byte-stream framing task (Core 0)
|
||||
*/
|
||||
static void uartRxTask(void* parameter) {
|
||||
uint8_t rx_buffer[sizeof(uart_packet_t)];
|
||||
uint8_t rx_buffer[PACKET_MAX_SIZE];
|
||||
rx_state_t state = STATE_WAIT_START;
|
||||
size_t bytes_read = 0;
|
||||
uint8_t expected_length = 0;
|
||||
|
||||
Serial.println("[UARTReceiver] Task started on Core 0");
|
||||
|
||||
// Initialize UART1 hardware
|
||||
UART_SERIAL_PORT.setRxBufferSize(UART_RX_BUFFER_SIZE);
|
||||
UART_SERIAL_PORT.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
|
||||
|
||||
Serial.printf("[UARTReceiver] UART1 initialized: %d baud, RX=GPIO%d, TX=GPIO%d\n",
|
||||
UART_BAUD_RATE, UART_RX_PIN, UART_TX_PIN);
|
||||
Serial.printf("[UARTReceiver] Waiting for packets from Controller A...\n");
|
||||
Serial.printf("[UARTReceiver] UART1 initialized: %d baud, RX=GPIO%d, protocol v%u\n",
|
||||
UART_BAUD_RATE, UART_RX_PIN, PACKET_VERSION);
|
||||
|
||||
while (true) {
|
||||
// Check if data available
|
||||
if (UART_SERIAL_PORT.available()) {
|
||||
while (UART_SERIAL_PORT.available()) {
|
||||
uint8_t byte = UART_SERIAL_PORT.read();
|
||||
|
||||
if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) {
|
||||
g_rx_stats.bytes_received++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
g_rx_stats.bytes_received++; // statistic only; a torn read is harmless
|
||||
|
||||
switch (state) {
|
||||
case STATE_WAIT_START:
|
||||
@@ -80,15 +171,16 @@ static void uartRxTask(void* parameter) {
|
||||
bytes_read = 1;
|
||||
state = STATE_READ_VERSION;
|
||||
} else {
|
||||
// Ignore byte, still waiting for start
|
||||
if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) {
|
||||
g_rx_stats.framing_errors++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
bump(&g_rx_stats.framing_errors);
|
||||
}
|
||||
break;
|
||||
|
||||
case STATE_READ_VERSION:
|
||||
rx_buffer[bytes_read++] = byte;
|
||||
state = STATE_READ_TYPE;
|
||||
break;
|
||||
|
||||
case STATE_READ_TYPE:
|
||||
rx_buffer[bytes_read++] = byte;
|
||||
state = STATE_READ_LENGTH;
|
||||
break;
|
||||
@@ -96,29 +188,20 @@ static void uartRxTask(void* parameter) {
|
||||
case STATE_READ_LENGTH:
|
||||
rx_buffer[bytes_read++] = byte;
|
||||
expected_length = byte;
|
||||
|
||||
// Validate length is reasonable
|
||||
if (expected_length > sizeof(automotive_data_t)) {
|
||||
// Invalid length, reset to wait for start
|
||||
Serial.printf("[UARTReceiver] ERROR: Invalid length %d (max: %d)\n",
|
||||
expected_length, sizeof(automotive_data_t));
|
||||
if (expected_length > PACKET_MAX_PAYLOAD) {
|
||||
bump(&g_rx_stats.framing_errors);
|
||||
state = STATE_WAIT_START;
|
||||
bytes_read = 0;
|
||||
if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) {
|
||||
g_rx_stats.framing_errors++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
} else if (expected_length == 0) {
|
||||
state = STATE_READ_CHECKSUM;
|
||||
} else {
|
||||
state = STATE_READ_DATA;
|
||||
state = STATE_READ_PAYLOAD;
|
||||
}
|
||||
break;
|
||||
|
||||
case STATE_READ_DATA:
|
||||
case STATE_READ_PAYLOAD:
|
||||
rx_buffer[bytes_read++] = byte;
|
||||
|
||||
// Check if we've read all data bytes
|
||||
// Packet structure: start(1) + version(1) + length(1) + data(expected_length)
|
||||
if (bytes_read >= (3 + expected_length)) {
|
||||
if (bytes_read >= (size_t)(PACKET_HEADER_SIZE + expected_length)) {
|
||||
state = STATE_READ_CHECKSUM;
|
||||
}
|
||||
break;
|
||||
@@ -130,63 +213,13 @@ static void uartRxTask(void* parameter) {
|
||||
|
||||
case STATE_READ_END:
|
||||
rx_buffer[bytes_read++] = byte;
|
||||
|
||||
if (byte == PACKET_END_BYTE) {
|
||||
// Complete packet received - validate it
|
||||
uart_packet_t* packet = (uart_packet_t*)rx_buffer;
|
||||
|
||||
if (validate_packet(packet)) {
|
||||
// Valid packet - update latest data
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
memcpy(&g_latest_data, &packet->data, sizeof(automotive_data_t));
|
||||
g_rx_stats.packets_received++;
|
||||
g_rx_stats.last_packet_time = millis();
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
|
||||
// Update debug monitor visibility based on received flag
|
||||
DebugMonitor::setVisible(packet->data.debug_enabled != 0);
|
||||
|
||||
// Debug output every 20 packets
|
||||
if (g_rx_stats.packets_received % 20 == 0) {
|
||||
char gearbox_buf[16], engine_buf[16], coolant_buf[16], voltage_buf[16];
|
||||
Serial.printf("[UARTReceiver] RX #%d | Gear:%s | GB:%s | Eng:%s | Cool:%s | Batt:%s | Valid:0x%02X | Debug:%s\n",
|
||||
packet->data.packet_id,
|
||||
gear_to_string((gear_position_t)packet->data.gear_position),
|
||||
format_temperature(packet->data.gearbox_oil_temp, gearbox_buf),
|
||||
format_temperature(packet->data.engine_oil_temp, engine_buf),
|
||||
format_temperature(packet->data.coolant_temp, coolant_buf),
|
||||
format_voltage(packet->data.battery_voltage, voltage_buf),
|
||||
packet->data.valid_flags,
|
||||
packet->data.debug_enabled ? "ON" : "OFF");
|
||||
}
|
||||
} else {
|
||||
// Invalid checksum
|
||||
if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) {
|
||||
g_rx_stats.checksum_errors++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
Serial.printf("[UARTReceiver] Checksum error (packet #%d)\n",
|
||||
((uart_packet_t*)rx_buffer)->data.packet_id);
|
||||
}
|
||||
} else {
|
||||
// Invalid end byte
|
||||
if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) {
|
||||
g_rx_stats.framing_errors++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
Serial.printf("[UARTReceiver] Framing error: End byte 0x%02X (expected 0x55)\n", byte);
|
||||
}
|
||||
|
||||
// Reset to wait for next packet
|
||||
processFrame(rx_buffer, bytes_read, LINK_SOURCE_UART);
|
||||
state = STATE_WAIT_START;
|
||||
bytes_read = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay to prevent CPU hogging
|
||||
vTaskDelay(pdMS_TO_TICKS(1));
|
||||
vTaskDelay(pdMS_TO_TICKS(2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,26 +229,18 @@ bool init() {
|
||||
return true;
|
||||
}
|
||||
|
||||
Serial.println("[UARTReceiver] Initializing UART receiver...");
|
||||
Serial.println("[UARTReceiver] Initializing link receiver...");
|
||||
|
||||
link_config_defaults(&g_config);
|
||||
|
||||
// Create mutex for thread-safe data access
|
||||
g_data_mutex = xSemaphoreCreateMutex();
|
||||
if (g_data_mutex == NULL) {
|
||||
Serial.println("[UARTReceiver] ERROR: Failed to create mutex");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create UART reception task on Core 0
|
||||
BaseType_t result = xTaskCreatePinnedToCore(
|
||||
uartRxTask,
|
||||
"UART_RX_Task",
|
||||
4096, // Stack size
|
||||
NULL, // Parameters
|
||||
1, // Priority (lower than LVGL task)
|
||||
&g_uart_task_handle,
|
||||
0 // Core 0
|
||||
);
|
||||
|
||||
uartRxTask, "UART_RX_Task", 4096, NULL, 1, &g_uart_task_handle, 0);
|
||||
if (result != pdPASS) {
|
||||
Serial.println("[UARTReceiver] ERROR: Failed to create task");
|
||||
return false;
|
||||
@@ -223,91 +248,96 @@ bool init() {
|
||||
|
||||
g_initialized = true;
|
||||
Serial.println("[UARTReceiver] Initialization complete");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
automotive_data_t getLatestData() {
|
||||
automotive_data_t data;
|
||||
memset(&data, 0, sizeof(data));
|
||||
|
||||
if (g_data_mutex != NULL) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
memcpy(&data, &g_latest_data, sizeof(automotive_data_t));
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
data = g_latest_data;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
uart_rx_stats_t getStats() {
|
||||
uart_rx_stats_t stats;
|
||||
memset(&stats, 0, sizeof(stats));
|
||||
|
||||
if (g_data_mutex != NULL) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
memcpy(&stats, &g_rx_stats, sizeof(uart_rx_stats_t));
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
stats = g_rx_stats;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
bool isConnected(uint32_t timeout_ms) {
|
||||
if (!g_initialized) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!g_initialized) return false;
|
||||
bool connected = false;
|
||||
|
||||
if (g_data_mutex != NULL) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
if (g_rx_stats.packets_received > 0) {
|
||||
uint32_t time_since_last = millis() - g_rx_stats.last_packet_time;
|
||||
connected = (time_since_last < timeout_ms);
|
||||
}
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
if (g_rx_stats.packets_received > 0) {
|
||||
connected = (millis() - g_rx_stats.last_packet_time) < timeout_ms;
|
||||
}
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
|
||||
return connected;
|
||||
}
|
||||
|
||||
void resetStats() {
|
||||
if (g_data_mutex != NULL) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
g_rx_stats.packets_received = 0;
|
||||
g_rx_stats.checksum_errors = 0;
|
||||
g_rx_stats.framing_errors = 0;
|
||||
g_rx_stats.timeout_errors = 0;
|
||||
g_rx_stats.bytes_received = 0;
|
||||
// Keep last_packet_time
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
bool isSourceAlive(link_source_t source, uint32_t timeout_ms) {
|
||||
if (!g_initialized) return false;
|
||||
bool alive = false;
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
uint32_t t = (source == LINK_SOURCE_UART) ? g_rx_stats.last_uart_time
|
||||
: (source == LINK_SOURCE_ESPNOW) ? g_rx_stats.last_espnow_time : 0;
|
||||
alive = (t != 0) && ((millis() - t) < timeout_ms);
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
return alive;
|
||||
}
|
||||
|
||||
link_config_t getConfig() {
|
||||
link_config_t c;
|
||||
link_config_defaults(&c);
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
c = g_config;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
uint32_t getConfigSeq() {
|
||||
uint32_t s = 0;
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
s = g_config_seq;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void resetStats() {
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
uint32_t keep_last = g_rx_stats.last_packet_time;
|
||||
uint32_t keep_uart = g_rx_stats.last_uart_time;
|
||||
uint32_t keep_espnow = g_rx_stats.last_espnow_time;
|
||||
link_source_t keep_src = g_rx_stats.last_source;
|
||||
memset(&g_rx_stats, 0, sizeof(g_rx_stats));
|
||||
g_rx_stats.last_packet_time = keep_last;
|
||||
g_rx_stats.last_uart_time = keep_uart;
|
||||
g_rx_stats.last_espnow_time = keep_espnow;
|
||||
g_rx_stats.last_source = keep_src;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
Serial.println("[UARTReceiver] Statistics reset");
|
||||
}
|
||||
|
||||
uint32_t getTimeSinceLastPacket() {
|
||||
if (!g_initialized) {
|
||||
return UINT32_MAX;
|
||||
if (!g_initialized) return UINT32_MAX;
|
||||
uint32_t t = UINT32_MAX;
|
||||
if (g_data_mutex && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
if (g_rx_stats.packets_received > 0) t = millis() - g_rx_stats.last_packet_time;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
|
||||
uint32_t time_since = UINT32_MAX;
|
||||
|
||||
if (g_data_mutex != NULL) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
if (g_rx_stats.packets_received > 0) {
|
||||
time_since = millis() - g_rx_stats.last_packet_time;
|
||||
}
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
return time_since;
|
||||
return t;
|
||||
}
|
||||
|
||||
} // namespace UARTReceiver
|
||||
|
||||
Reference in New Issue
Block a user