This commit is contained in:
2026-09-21 10:28:35 +02:00
commit b6fb01ba73
54 changed files with 33982 additions and 0 deletions
+301
View File
@@ -0,0 +1,301 @@
/**
* 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).
*/
#include <Arduino.h>
#include <lvgl.h>
#include "modules/display_init.h"
#include "modules/uart_receiver.h"
#include "modules/debug_monitor.h"
#include "ui/ui.h"
#include "ui/screens/ui_Home_Screen.h"
// 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)
/**
* 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
}
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
} else {
lv_obj_align_to(icon_to_show, label_ref, LV_ALIGN_OUT_TOP_MID, 0, -2); // 2px gap above
}
// 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);
}
}
/**
* LVGL update task (runs on Core 1)
*/
void lvglTask(void *parameter) {
Serial.println("[LVGL Task] Started on Core 1");
while (true) {
DisplayInit::update();
vTaskDelay(pdMS_TO_TICKS(5)); // ~200 FPS max, actual will be limited by LVGL
}
}
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(500); // Additional stabilization time
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.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) {
delay(1000);
}
}
// 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
);
// 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...");
if (!UARTReceiver::init()) {
Serial.println("[ERROR] UART receiver initialization failed!");
while (1) {
delay(1000);
}
}
Serial.println("[UART] UART receiver initialized");
Serial.println("\n[Setup] Complete! Starting main loop...\n");
}
void loop() {
static uint32_t last_stats_print = 0;
static uint32_t last_connection_check = 0;
static uint32_t last_ui_update = 0;
static bool was_connected = false;
// Print UART statistics every 5 seconds
if (millis() - last_stats_print > 5000) {
last_stats_print = millis();
UARTReceiver::uart_rx_stats_t stats = 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);
}
}
// Check connection status every second
if (millis() - last_connection_check > 1000) {
last_connection_check = millis();
bool is_connected = UARTReceiver::isConnected(1000); // 1 second timeout
// Log connection state changes
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");
} else if (!is_connected && was_connected) {
Serial.println("[UART] Connection LOST - No data from Controller A");
}
was_connected = is_connected;
}
// Update UI labels every 200ms (5Hz, matching UART packet rate)
if (millis() - last_ui_update > 200) {
last_ui_update = millis();
automotive_data_t data = UARTReceiver::getLatestData();
bool is_connected = UARTReceiver::isConnected(1000);
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];
// 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
}
// 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, "?");
}
}
// 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
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);
// 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);
// 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);
// Engine Oil Temperature - show only if valid, warn if >= 130°C
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);
} 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, "?");
}
// 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);
}
}
delay(10);
}
+72
View File
@@ -0,0 +1,72 @@
/**
* Debug Monitor Module Implementation
*
* Controls LVGL performance and memory monitor visibility at runtime
* based on debug_enabled flag from Controller A.
*/
#include "modules/debug_monitor.h"
#include <lvgl.h>
namespace DebugMonitor {
static bool g_monitors_visible = true; // Default: visible (matches lv_conf.h settings)
static bool g_initialized = false;
void init() {
if (g_initialized) {
Serial.println("[DebugMonitor] Already initialized");
return;
}
Serial.println("[DebugMonitor] Initializing debug monitor control...");
// Monitors are enabled by default in lv_conf.h (LV_USE_PERF_MONITOR=1, LV_USE_MEM_MONITOR=1)
// They will be visible on boot
g_monitors_visible = true;
g_initialized = true;
Serial.println("[DebugMonitor] Debug monitors are VISIBLE (default state)");
Serial.println("[DebugMonitor] Waiting for debug_enabled flag from Controller A...");
}
void setVisible(bool enabled) {
if (!g_initialized) {
Serial.println("[DebugMonitor] ERROR: Not initialized, call init() first");
return;
}
// Only update if state changes
if (g_monitors_visible == enabled) {
return; // Already in correct state
}
g_monitors_visible = enabled;
#if LV_USE_PERF_MONITOR || LV_USE_MEM_MONITOR
// Get the system layer where performance and memory monitors are rendered
lv_obj_t* sys_layer = lv_disp_get_layer_sys(NULL);
if (sys_layer != NULL) {
if (enabled) {
// Show monitors by clearing the hidden flag
lv_obj_clear_flag(sys_layer, LV_OBJ_FLAG_HIDDEN);
Serial.println("[DebugMonitor] Debug monitors SHOWN (FPS, CPU, Memory visible)");
} else {
// Hide monitors by setting the hidden flag
lv_obj_add_flag(sys_layer, LV_OBJ_FLAG_HIDDEN);
Serial.println("[DebugMonitor] Debug monitors HIDDEN (FPS, CPU, Memory hidden)");
}
} else {
Serial.println("[DebugMonitor] WARNING: Could not access system layer");
}
#else
Serial.println("[DebugMonitor] Debug monitors are disabled at compile-time in lv_conf.h");
#endif
}
bool isVisible() {
return g_monitors_visible;
}
} // namespace DebugMonitor
+164
View File
@@ -0,0 +1,164 @@
#include "modules/display_init.h"
namespace DisplayInit {
// LovyanGFX display configuration for ESP32-S3-LCD-1.3
class LGFX : public lgfx::LGFX_Device {
lgfx::Panel_ST7789 _panel_instance;
lgfx::Bus_SPI _bus_instance;
lgfx::Light_PWM _light_instance;
public:
LGFX(void) {
// Configure SPI bus
{
auto cfg = _bus_instance.config();
cfg.spi_host = SPI2_HOST;
cfg.spi_mode = 0;
cfg.freq_write = 80000000; // 80MHz SPI
cfg.freq_read = 16000000;
// Pin assignments from Waveshare ESP32-S3-LCD-1.3 official demo
// Source: ESP32-S3-LCD-1.3-Demo/Arduino/libraries/TFT_eSPI/User_Setup.h
cfg.pin_sclk = 40; // SPI Clock (SCLK)
cfg.pin_mosi = 41; // SPI MOSI (Data Out)
cfg.pin_miso = -1; // SPI MISO (not used by display)
cfg.pin_dc = 38; // Data/Command (DC)
cfg.spi_3wire = false;
cfg.use_lock = true;
cfg.dma_channel = SPI_DMA_CH_AUTO;
_bus_instance.config(cfg);
_panel_instance.setBus(&_bus_instance);
}
// Configure ST7789 panel
{
auto cfg = _panel_instance.config();
cfg.pin_cs = 39; // Chip Select (CS)
cfg.pin_rst = 42; // Reset (RST)
cfg.pin_busy = -1; // Not used
cfg.panel_width = DISPLAY_WIDTH;
cfg.panel_height = DISPLAY_HEIGHT;
cfg.offset_x = 0;
cfg.offset_y = 0;
cfg.offset_rotation = 0;
cfg.dummy_read_pixel = 8;
cfg.dummy_read_bits = 1;
cfg.readable = false;
cfg.invert = true;
cfg.rgb_order = false;
cfg.dlen_16bit = false;
cfg.bus_shared = false;
_panel_instance.config(cfg);
}
// Configure backlight
{
auto cfg = _light_instance.config();
cfg.pin_bl = 20; // Backlight pin (from demo: LCD_BL = GPIO 20)
cfg.invert = false;
cfg.freq = 44100;
cfg.pwm_channel = 1;
_light_instance.config(cfg);
_panel_instance.setLight(&_light_instance);
}
setPanel(&_panel_instance);
}
};
// Static instances
static LGFX display;
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf1[DISPLAY_WIDTH * 40]; // Buffer for 40 lines
static lv_color_t buf2[DISPLAY_WIDTH * 40]; // Double buffering
static lv_disp_drv_t disp_drv;
// Timer for LVGL tick
static uint32_t last_tick_ms = 0;
// Current brightness level
static uint8_t current_brightness = 128;
// Flush callback for LVGL
void lvgl_flush_cb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p) {
uint32_t w = (area->x2 - area->x1 + 1);
uint32_t h = (area->y2 - area->y1 + 1);
display.startWrite();
display.setAddrWindow(area->x1, area->y1, w, h);
display.writePixels((lgfx::rgb565_t *)&color_p->full, w * h);
display.endWrite();
lv_disp_flush_ready(disp);
}
bool init() {
Serial.println("[DisplayInit] Initializing display...");
// Initialize LovyanGFX
display.init();
display.setRotation(0); // Adjust as needed for your mounting
display.setBrightness(current_brightness); // Set initial brightness
display.fillScreen(TFT_BLACK);
Serial.printf("[DisplayInit] Display initialized: %dx%d\n", DISPLAY_WIDTH, DISPLAY_HEIGHT);
// Initialize LVGL
lv_init();
// Initialize LVGL tick timer
last_tick_ms = millis();
// Set up LVGL display buffers
lv_disp_draw_buf_init(&draw_buf, buf1, buf2, DISPLAY_WIDTH * 40);
// Initialize display driver
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = DISPLAY_WIDTH;
disp_drv.ver_res = DISPLAY_HEIGHT;
disp_drv.flush_cb = lvgl_flush_cb;
disp_drv.draw_buf = &draw_buf;
lv_disp_drv_register(&disp_drv);
Serial.println("[DisplayInit] LVGL initialized");
Serial.println("[DisplayInit] Display hardware ready for UI");
return true;
}
LGFX* getDisplay() {
return &display;
}
void update() {
// Update LVGL tick (required for animations and timers)
uint32_t current_ms = millis();
uint32_t elapsed_ms = current_ms - last_tick_ms;
if (elapsed_ms > 0) {
lv_tick_inc(elapsed_ms);
last_tick_ms = current_ms;
}
// Handle LVGL tasks
lv_timer_handler();
}
void setBrightness(uint8_t brightness) {
current_brightness = brightness;
display.setBrightness(brightness);
}
uint8_t getBrightness() {
return current_brightness;
}
} // namespace DisplayInit
+33
View File
@@ -0,0 +1,33 @@
#ifndef DISPLAY_INIT_H
#define DISPLAY_INIT_H
#include <Arduino.h>
#include <lvgl.h>
#include <LovyanGFX.hpp>
// Display configuration
#define DISPLAY_WIDTH 240
#define DISPLAY_HEIGHT 240
#define DISPLAY_RADIUS 120 // For circular mask
namespace DisplayInit {
// Initialize display hardware and LVGL
bool init();
// Get display instance
class LGFX* getDisplay();
// LVGL flush callback
void lvgl_flush_cb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p);
// Update display (call in loop)
void update();
// Brightness control (0-255, where 0=off, 255=max brightness)
void setBrightness(uint8_t brightness);
uint8_t getBrightness();
} // namespace DisplayInit
#endif // DISPLAY_INIT_H
+313
View File
@@ -0,0 +1,313 @@
/**
* UART Receiver Module Implementation
*
* Receives automotive data packets from Controller A via UART1.
* Uses state machine for robust packet parsing and framing.
*/
#include "modules/uart_receiver.h"
#include "modules/debug_monitor.h"
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/semphr.h>
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
// Packet framing state machine states
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)
} rx_state_t;
// Private state variables
static automotive_data_t g_latest_data = {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;
/**
* @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
*/
static void uartRxTask(void* parameter) {
uint8_t rx_buffer[sizeof(uart_packet_t)];
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");
while (true) {
// Check if data available
if (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);
}
switch (state) {
case STATE_WAIT_START:
if (byte == PACKET_START_BYTE) {
rx_buffer[0] = byte;
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);
}
}
break;
case STATE_READ_VERSION:
rx_buffer[bytes_read++] = byte;
state = STATE_READ_LENGTH;
break;
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));
state = STATE_WAIT_START;
bytes_read = 0;
if (xSemaphoreTake(g_data_mutex, 0) == pdTRUE) {
g_rx_stats.framing_errors++;
xSemaphoreGive(g_data_mutex);
}
} else {
state = STATE_READ_DATA;
}
break;
case STATE_READ_DATA:
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)) {
state = STATE_READ_CHECKSUM;
}
break;
case STATE_READ_CHECKSUM:
rx_buffer[bytes_read++] = byte;
state = STATE_READ_END;
break;
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
state = STATE_WAIT_START;
bytes_read = 0;
break;
}
}
// Small delay to prevent CPU hogging
vTaskDelay(pdMS_TO_TICKS(1));
}
}
bool init() {
if (g_initialized) {
Serial.println("[UARTReceiver] Already initialized");
return true;
}
Serial.println("[UARTReceiver] Initializing UART receiver...");
// 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
);
if (result != pdPASS) {
Serial.println("[UARTReceiver] ERROR: Failed to create task");
return false;
}
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);
}
}
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);
}
}
return stats;
}
bool isConnected(uint32_t timeout_ms) {
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);
}
}
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);
}
}
Serial.println("[UARTReceiver] Statistics reset");
}
uint32_t getTimeSinceLastPacket() {
if (!g_initialized) {
return UINT32_MAX;
}
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;
}
} // namespace UARTReceiver