Link protocol v2, ESP-NOW leg, gauge tunables + tuning screen; remove Home screen
Protocol v2 (shared header, byte-identical with the 1.3 repo): - typed DATA/CONFIG frames: 0xAA | ver | type | len | payload | XOR | 0x55 - gear split into lever (P/R/N/D/S/M) + target/engaged nibbles, engine rpm, alert bitmap decided here from tunable thresholds, link_config_t tunables - docs/UART_PROTOCOL.md rewritten for v2 Controller A modules: - tunables: gauge calibration + alert thresholds in NVS, 'cfg' serial console, bench override (never persisted) - espnow_link: every frame also broadcast on ESP-NOW ch 1; radio stays in STA (WiFiManager no longer powers it off) - uart_manager: DATA at 5 Hz + CONFIG on change/5 s on both transports - can_driver: publishes gear pieces and rpm, evaluates alerts - tuning_screen: hand-coded Gauge Tuning page (swipe right from Driveline), -/+ rows, enable switches, override sliders, Driveline/Defaults buttons UI: SquareLine Home screen (3 meters + battery) and meters_manager removed; Driveline is the boot screen; Settings back-gesture calls app_show_driveline(). tools/fix_penv_deps.ps1: repairs the shared PlatformIO penv after a 1.3 build. Bench-verified with Controller B: both transports alive, dedupe, override rpm 2000 -> 133.3 Hz tach output. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+110
-105
@@ -1,10 +1,16 @@
|
||||
/*
|
||||
* UART Manager Module Implementation
|
||||
*
|
||||
* Builds the v2 frames (DATA at 5 Hz, CONFIG on change + every CONFIG_RESEND_MS)
|
||||
* and sends each one on BOTH transports: UART1 (GPIO 44 -> SP3485 -> 485_A/B)
|
||||
* and ESP-NOW broadcast. Controller B dedupes on packet_id.
|
||||
*/
|
||||
|
||||
#include "uart_manager.h"
|
||||
#include "settings_manager.h"
|
||||
#include "serial_lock.h"
|
||||
#include "tunables.h"
|
||||
#include "espnow_link.h"
|
||||
|
||||
namespace UARTManager {
|
||||
|
||||
@@ -12,65 +18,67 @@ namespace UARTManager {
|
||||
// UART HARDWARE CONFIGURATION
|
||||
// ============================================================================
|
||||
|
||||
// Controller A specific UART pins (using GPIO headers for direct TTL connection)
|
||||
// Note: RS485 terminal uses differential signaling and requires RS485-to-TTL converter
|
||||
// For direct UART connection, use GPIO pin headers instead
|
||||
#define UART_TX_PIN 44 // GPIO 44 - Connect to Controller B RX (IO1)
|
||||
#define UART_RX_PIN 43 // GPIO 43 - Not used (TX-only mode)
|
||||
// GPIO 44 is UART1 TX. On the 5B it does not reach a header: it feeds the
|
||||
// SP3485 whose A/B pair is on the terminal block. On the bench, 485_A straight
|
||||
// into B's IO1 works (unterminated, biased high); in the car use a transceiver
|
||||
// on B or rely on the ESP-NOW leg. See ESP32-S3-LCD-1.3/wiki/pages/controller-link.md
|
||||
#define UART_TX_PIN 44
|
||||
#define UART_RX_PIN 43 // unused (TX-only link)
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
// Global UART state variables
|
||||
static uart_state_t g_uart_state = UART_STATE_OFF;
|
||||
static TaskHandle_t g_uart_task_handle = NULL;
|
||||
static QueueHandle_t g_uart_event_queue = NULL;
|
||||
|
||||
// Shared automotive data (accessible by CAN driver)
|
||||
// Shared automotive data (written by the CAN driver)
|
||||
SemaphoreHandle_t g_data_mutex = NULL;
|
||||
automotive_data_t g_automotive_data = {0};
|
||||
static uint8_t g_packet_id = 0;
|
||||
|
||||
// UART statistics for debugging
|
||||
static uart_stats_t g_uart_stats = {0};
|
||||
|
||||
// CONFIG frame scheduling
|
||||
static uint8_t g_last_cfg_version_sent = 0;
|
||||
static uint32_t g_last_cfg_send_time = 0;
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPER FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Initialize default automotive data values
|
||||
* @note Provides reasonable starting values until CAN bus updates them
|
||||
* @brief Seed the shared structure until CAN data arrives.
|
||||
* @note The temperatures/voltage are marked valid so a bench without CAN still
|
||||
* exercises B's display. RPM and gear nibbles are NOT marked valid: the
|
||||
* tach output must never run on invented data.
|
||||
*/
|
||||
static void initializeDefaultData() {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
// Set default values (will be overwritten by CAN driver)
|
||||
g_automotive_data.gear_position = GEAR_PARK;
|
||||
g_automotive_data.gear_lever = DEFAULT_GEAR_LEVER;
|
||||
g_automotive_data.gear_nibbles = 0;
|
||||
g_automotive_data.engine_rpm = 0;
|
||||
g_automotive_data.gearbox_oil_temp = DEFAULT_GEARBOX_TEMP;
|
||||
g_automotive_data.engine_oil_temp = DEFAULT_ENGINE_OIL_TEMP;
|
||||
g_automotive_data.coolant_temp = DEFAULT_COOLANT_TEMP;
|
||||
g_automotive_data.battery_voltage = DEFAULT_BATTERY_VOLTAGE;
|
||||
g_automotive_data.fault_codes = DEFAULT_FAULT_CODES;
|
||||
g_automotive_data.alerts = DEFAULT_ALERTS;
|
||||
|
||||
// Mark all data as valid for now
|
||||
g_automotive_data.valid_flags = VALID_FLAG_GEAR_POS |
|
||||
VALID_FLAG_GEARBOX_TEMP |
|
||||
VALID_FLAG_ENGINE_TEMP |
|
||||
VALID_FLAG_COOLANT_TEMP |
|
||||
VALID_FLAG_BATTERY_VOLT |
|
||||
VALID_FLAG_FAULT_CODES;
|
||||
VALID_FLAG_ALERTS;
|
||||
|
||||
// Initialize debug flag (will be updated from UI state manager)
|
||||
g_automotive_data.debug_enabled = 0;
|
||||
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Update packet metadata (timestamp and ID) without modifying sensor data
|
||||
* @note Sensor values are updated by CAN driver, we only update transmission metadata
|
||||
* @brief Update packet metadata (timestamp and ID) without touching sensor data
|
||||
*/
|
||||
static void updatePacketMetadata() {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
@@ -81,65 +89,80 @@ static void updatePacketMetadata() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Send automotive data packet over UART
|
||||
* @return true if successful, false on error
|
||||
* @brief Send one already-built frame on both transports.
|
||||
* @return true if the UART write completed (ESP-NOW is best-effort)
|
||||
*/
|
||||
static bool sendUARTPacket() {
|
||||
uart_packet_t packet;
|
||||
static bool sendFrame(const uint8_t* frame, size_t len) {
|
||||
size_t written = Serial1.write(frame, len);
|
||||
EspNowLink::send(frame, len); // best effort; counted inside the module
|
||||
return written == len;
|
||||
}
|
||||
|
||||
// Get latest data with mutex protection
|
||||
/**
|
||||
* @brief Build and send the DATA frame
|
||||
*/
|
||||
static bool sendDataFrame() {
|
||||
automotive_data_t snapshot;
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) != pdTRUE) {
|
||||
ESP_LOGE("UARTTask", "Failed to acquire data mutex");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Build packet
|
||||
packet.start_byte = PACKET_START_BYTE;
|
||||
packet.version = PACKET_VERSION;
|
||||
packet.length = sizeof(automotive_data_t);
|
||||
memcpy(&packet.data, &g_automotive_data, sizeof(automotive_data_t));
|
||||
|
||||
snapshot = g_automotive_data;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
|
||||
// Calculate checksum (version + length + data)
|
||||
uint8_t* checksum_start = (uint8_t*)&packet.version;
|
||||
size_t checksum_size = 2 + packet.length; // version(1) + length(1) + data
|
||||
packet.checksum = calculate_checksum(checksum_start, checksum_size);
|
||||
packet.end_byte = PACKET_END_BYTE;
|
||||
uint8_t frame[PACKET_MAX_SIZE];
|
||||
size_t len = frame_build(PACKET_TYPE_DATA, &snapshot, sizeof(snapshot), frame);
|
||||
if (len == 0) return false;
|
||||
|
||||
// Send packet over UART1
|
||||
size_t bytes_written = Serial1.write((uint8_t*)&packet, sizeof(packet));
|
||||
|
||||
if (bytes_written == sizeof(packet)) {
|
||||
if (sendFrame(frame, len)) {
|
||||
g_uart_stats.packets_sent++;
|
||||
g_uart_stats.last_send_time = millis();
|
||||
|
||||
// Debug output - first 5 packets, then every 10
|
||||
if (g_uart_stats.packets_sent <= 5 || g_uart_stats.packets_sent % 10 == 0) {
|
||||
// Hold the serial lock so this line can't splice into a CANRAW frame
|
||||
// Debug output - first 5 packets, then every 25
|
||||
if (g_uart_stats.packets_sent <= 5 || g_uart_stats.packets_sent % 25 == 0) {
|
||||
char gear[8];
|
||||
gear_compose(snapshot.gear_lever, gear_engaged(snapshot.gear_nibbles), gear, sizeof(gear));
|
||||
SerialLock::lock();
|
||||
ESP_LOGI("UARTTask", "✓ TX Packet #%d (Gear:%s, Temps:%d.%d/%d.%d/%d.%d°C, Batt:%d.%02dV, Debug:%s) [%d bytes on GPIO%d]",
|
||||
packet.data.packet_id,
|
||||
gear_to_string((gear_position_t)packet.data.gear_position),
|
||||
packet.data.gearbox_oil_temp / 10, abs(packet.data.gearbox_oil_temp % 10),
|
||||
packet.data.engine_oil_temp / 10, abs(packet.data.engine_oil_temp % 10),
|
||||
packet.data.coolant_temp / 10, abs(packet.data.coolant_temp % 10),
|
||||
packet.data.battery_voltage / 100, packet.data.battery_voltage % 100,
|
||||
packet.data.debug_enabled ? "ON" : "OFF",
|
||||
bytes_written, UART_TX_PIN);
|
||||
ESP_LOGI("UARTTask", "TX #%u gear=%s(t%u/e%u) rpm=%u cool=%d.%d gb=%d.%d batt=%u.%02u alerts=0x%02X valid=0x%02X [%u B uart+espnow, espnow tx=%lu fail=%lu]",
|
||||
snapshot.packet_id, gear,
|
||||
gear_target(snapshot.gear_nibbles), gear_engaged(snapshot.gear_nibbles),
|
||||
snapshot.engine_rpm,
|
||||
snapshot.coolant_temp / 10, abs(snapshot.coolant_temp % 10),
|
||||
snapshot.gearbox_oil_temp / 10, abs(snapshot.gearbox_oil_temp % 10),
|
||||
snapshot.battery_voltage / 100, snapshot.battery_voltage % 100,
|
||||
snapshot.alerts, snapshot.valid_flags,
|
||||
(unsigned)len,
|
||||
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount());
|
||||
SerialLock::unlock();
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
g_uart_stats.send_errors++;
|
||||
ESP_LOGE("UARTTask", "Send error! Only wrote %d of %d bytes", bytes_written, sizeof(packet));
|
||||
return false;
|
||||
}
|
||||
|
||||
g_uart_stats.send_errors++;
|
||||
ESP_LOGE("UARTTask", "UART send error");
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Build and send the CONFIG frame
|
||||
*/
|
||||
static void sendConfigFrame(const char* why) {
|
||||
link_config_t cfg = Tunables::get();
|
||||
uint8_t frame[PACKET_MAX_SIZE];
|
||||
size_t len = frame_build(PACKET_TYPE_CONFIG, &cfg, sizeof(cfg), frame);
|
||||
if (len == 0) return;
|
||||
sendFrame(frame, len);
|
||||
g_last_cfg_version_sent = cfg.cfg_version;
|
||||
g_last_cfg_send_time = millis();
|
||||
SerialLock::lock();
|
||||
ESP_LOGI("UARTTask", "TX CONFIG v%u (%s): ppr=%u trim=%d temp_hz=%u slope=%u offset=%d min=%d override=%u",
|
||||
cfg.cfg_version, why, cfg.tach_ppr, cfg.tach_trim_pct, cfg.temp_pwm_hz,
|
||||
cfg.temp_slope_x100, cfg.temp_offset, cfg.temp_min_c, cfg.override_mode);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief UART task - Runs on Core 0
|
||||
* @param parameter Task parameter (unused)
|
||||
*/
|
||||
static void uartTask(void* parameter) {
|
||||
uart_queue_event_t event;
|
||||
@@ -148,17 +171,14 @@ static void uartTask(void* parameter) {
|
||||
|
||||
ESP_LOGI("UARTTask", "UART task started on Core 0");
|
||||
|
||||
// Initialize UART1 hardware
|
||||
Serial1.setRxBufferSize(256); // Set receive buffer size BEFORE begin()
|
||||
Serial1.setRxBufferSize(256);
|
||||
Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
|
||||
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d, RX=GPIO%d",
|
||||
UART_BAUD_RATE, UART_TX_PIN, UART_RX_PIN);
|
||||
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u",
|
||||
UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION);
|
||||
|
||||
// Initialize default values (will be overwritten by CAN driver when active)
|
||||
initializeDefaultData();
|
||||
|
||||
while (true) {
|
||||
// Check for control events from the queue
|
||||
if (xQueueReceive(g_uart_event_queue, &event, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
switch (event.type) {
|
||||
case UART_EVENT_START:
|
||||
@@ -167,23 +187,21 @@ static void uartTask(void* parameter) {
|
||||
g_uart_state = UART_STATE_TRANSMITTING;
|
||||
g_uart_stats.packets_sent = 0;
|
||||
g_uart_stats.send_errors = 0;
|
||||
sendConfigFrame("start");
|
||||
break;
|
||||
|
||||
case UART_EVENT_STOP:
|
||||
ESP_LOGI("UARTTask", "Stopping transmission...");
|
||||
transmitting = false;
|
||||
g_uart_state = UART_STATE_OFF;
|
||||
|
||||
// Print final statistics
|
||||
ESP_LOGI("UARTTask", "Stats: %d packets sent, %d errors",
|
||||
g_uart_stats.packets_sent, g_uart_stats.send_errors);
|
||||
break;
|
||||
|
||||
case UART_EVENT_SEND_DATA:
|
||||
// Manual send trigger (not used in periodic mode)
|
||||
if (transmitting) {
|
||||
updatePacketMetadata();
|
||||
sendUARTPacket();
|
||||
sendDataFrame();
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -192,18 +210,23 @@ static void uartTask(void* parameter) {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle periodic transmission at 5Hz (200ms intervals)
|
||||
if (transmitting) {
|
||||
unsigned long current_time = millis();
|
||||
if (current_time - last_transmit_time >= UART_UPDATE_RATE_MS) {
|
||||
last_transmit_time = current_time;
|
||||
unsigned long now = millis();
|
||||
|
||||
// Update packet metadata (CAN driver updates sensor values)
|
||||
// CONFIG: on every tunables change, and periodically as a safety net
|
||||
// (B may have rebooted, or missed the change on both transports).
|
||||
uint8_t v = Tunables::version();
|
||||
if (v != g_last_cfg_version_sent) {
|
||||
sendConfigFrame("changed");
|
||||
} else if (now - g_last_cfg_send_time >= CONFIG_RESEND_MS) {
|
||||
sendConfigFrame("periodic");
|
||||
}
|
||||
|
||||
// DATA at 5 Hz
|
||||
if (now - last_transmit_time >= UART_UPDATE_RATE_MS) {
|
||||
last_transmit_time = now;
|
||||
updatePacketMetadata();
|
||||
|
||||
// Send packet
|
||||
if (!sendUARTPacket()) {
|
||||
// Handle send error
|
||||
if (!sendDataFrame()) {
|
||||
if (g_uart_stats.send_errors > 10) {
|
||||
ESP_LOGE("UARTTask", "Too many send errors, entering error state");
|
||||
g_uart_state = UART_STATE_ERROR;
|
||||
@@ -213,8 +236,7 @@ static void uartTask(void* parameter) {
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay to prevent task from hogging CPU
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,27 +247,24 @@ static void uartTask(void* parameter) {
|
||||
void init(bool auto_start) {
|
||||
ESP_LOGI("UARTMgr", "Initializing UART subsystem...");
|
||||
|
||||
// Create mutex for protecting automotive data
|
||||
g_data_mutex = xSemaphoreCreateMutex();
|
||||
if (g_data_mutex == NULL) {
|
||||
ESP_LOGE("UARTMgr", "ERROR: Failed to create UART data mutex!");
|
||||
}
|
||||
|
||||
// Create event queue for UART task communication
|
||||
g_uart_event_queue = xQueueCreate(10, sizeof(uart_queue_event_t));
|
||||
if (g_uart_event_queue == NULL) {
|
||||
ESP_LOGE("UARTMgr", "ERROR: Failed to create UART event queue!");
|
||||
}
|
||||
|
||||
// Create UART task on Core 0
|
||||
BaseType_t uart_task_created = xTaskCreatePinnedToCore(
|
||||
uartTask, // Task function
|
||||
"UART_Task", // Task name
|
||||
UART_TASK_STACK_SIZE, // Stack size
|
||||
NULL, // Parameters
|
||||
UART_TASK_PRIORITY, // Priority (1)
|
||||
&g_uart_task_handle, // Task handle
|
||||
UART_TASK_CORE // Core 0
|
||||
uartTask,
|
||||
"UART_Task",
|
||||
UART_TASK_STACK_SIZE,
|
||||
NULL,
|
||||
UART_TASK_PRIORITY,
|
||||
&g_uart_task_handle,
|
||||
UART_TASK_CORE
|
||||
);
|
||||
|
||||
if (uart_task_created != pdPASS) {
|
||||
@@ -254,11 +273,10 @@ void init(bool auto_start) {
|
||||
ESP_LOGI("UARTMgr", "UART task created successfully on Core 0");
|
||||
}
|
||||
|
||||
// Auto-start UART if requested
|
||||
if (auto_start) {
|
||||
ESP_LOGI("UARTMgr", "========================================");
|
||||
ESP_LOGI("UARTMgr", " AUTO-STARTING UART TRANSMISSION");
|
||||
ESP_LOGI("UARTMgr", " Baud: %d | TX: GPIO%d | RX: GPIO%d", UART_BAUD_RATE, UART_TX_PIN, UART_RX_PIN);
|
||||
ESP_LOGI("UARTMgr", " AUTO-STARTING LINK TRANSMISSION");
|
||||
ESP_LOGI("UARTMgr", " Baud: %d | TX: GPIO%d | + ESP-NOW", UART_BAUD_RATE, UART_TX_PIN);
|
||||
ESP_LOGI("UARTMgr", "========================================");
|
||||
uart_queue_event_t evt;
|
||||
evt.type = UART_EVENT_START;
|
||||
@@ -266,7 +284,7 @@ void init(bool auto_start) {
|
||||
xQueueSend(g_uart_event_queue, &evt, 0);
|
||||
} else {
|
||||
ESP_LOGI("UARTMgr", "========================================");
|
||||
ESP_LOGI("UARTMgr", " UART INITIALLY DISABLED");
|
||||
ESP_LOGI("UARTMgr", " LINK INITIALLY DISABLED");
|
||||
ESP_LOGI("UARTMgr", " Enable via Settings screen toggle");
|
||||
ESP_LOGI("UARTMgr", "========================================");
|
||||
}
|
||||
@@ -307,38 +325,26 @@ void linkToCANState(bool can_active) {
|
||||
|
||||
void onUARTToggle(lv_event_t *e)
|
||||
{
|
||||
// Get the actual widget from the event
|
||||
lv_obj_t *target = lv_event_get_target(e);
|
||||
|
||||
// Verify the widget is valid
|
||||
if (target == NULL) {
|
||||
ESP_LOGE("UARTMgr", "ERROR: UART toggle target is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the toggle state
|
||||
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
||||
|
||||
ESP_LOGI("UARTMgr", "===== UART Toggle Event =====");
|
||||
ESP_LOGI("UARTMgr", "UART Toggle State: %s", state ? "ON" : "OFF");
|
||||
|
||||
// Save state to NVS for persistence across power cycles
|
||||
SettingsManager::saveUARTState(state);
|
||||
|
||||
// Send event to UART task via queue
|
||||
uart_queue_event_t evt;
|
||||
evt.type = state ? UART_EVENT_START : UART_EVENT_STOP;
|
||||
evt.data = NULL;
|
||||
|
||||
// Send event to UART task (non-blocking)
|
||||
if (g_uart_event_queue != NULL) {
|
||||
if (xQueueSend(g_uart_event_queue, &evt, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
ESP_LOGI("UARTMgr", "Command sent to task (%s)", state ? "START" : "STOP");
|
||||
|
||||
// Optional: Update UI to show UART status
|
||||
// For now, we'll just update a label if we add one later
|
||||
// Could show "UART: ON" or "UART: OFF" somewhere on the screen
|
||||
|
||||
} else {
|
||||
ESP_LOGE("UARTMgr", "ERROR: Failed to send command to UART task!");
|
||||
}
|
||||
@@ -346,7 +352,6 @@ void onUARTToggle(lv_event_t *e)
|
||||
ESP_LOGE("UARTMgr", "ERROR: UART event queue not initialized!");
|
||||
}
|
||||
|
||||
// Print current UART statistics if turning off
|
||||
if (!state && g_uart_state != UART_STATE_OFF) {
|
||||
ESP_LOGI("UARTMgr", "UART Statistics:");
|
||||
ESP_LOGI("UARTMgr", " Packets sent: %d", g_uart_stats.packets_sent);
|
||||
|
||||
Reference in New Issue
Block a user