Init new era, with wiki integrated.
This commit is contained in:
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* can_driver.cpp
|
||||
*
|
||||
* CAN Bus driver implementation for BMW vehicle data reception
|
||||
* Based on Waveshare TWAI receive example
|
||||
*/
|
||||
|
||||
#include "drivers/can_driver.h"
|
||||
#include "modules/uart_manager.h"
|
||||
#include "modules/settings_manager.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
// Import shared data from UARTManager namespace
|
||||
using UARTManager::g_data_mutex;
|
||||
using UARTManager::g_automotive_data;
|
||||
|
||||
namespace CANDriver {
|
||||
|
||||
// ============================================================================
|
||||
// CONFIGURATION
|
||||
// ============================================================================
|
||||
|
||||
// CAN timeout threshold - stop UART if no messages received for this duration
|
||||
#define CAN_TIMEOUT_MS 2000 // 2 seconds (for 5Hz expected rate, this is 10 missed messages)
|
||||
|
||||
// ============================================================================
|
||||
// MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
static bool g_can_active = false;
|
||||
static TaskHandle_t g_can_task_handle = NULL;
|
||||
static QueueHandle_t g_can_event_queue = NULL;
|
||||
static can_stats_t g_can_stats = {0};
|
||||
static bool g_uart_auto_stopped = false; // Track if UART was auto-stopped due to CAN timeout
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Parse BMW-specific CAN message and update automotive data
|
||||
* @param message Received TWAI message
|
||||
* @return true if message was parsed, false if unknown ID
|
||||
*/
|
||||
static bool parseCANMessage(const twai_message_t& message) {
|
||||
bool parsed = false;
|
||||
uint32_t id = message.identifier;
|
||||
const uint8_t* data = message.data;
|
||||
|
||||
// Acquire mutex to update shared data (10ms timeout to prevent blocking)
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) != pdTRUE) {
|
||||
ESP_LOGE("CANDrv", "Failed to acquire data mutex");
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (id) {
|
||||
case CAN_ID_COOLANT_TEMP:
|
||||
// Engine coolant temperature (byte 0)
|
||||
if (message.data_length_code > CAN_BYTE_COOLANT_TEMP) {
|
||||
g_automotive_data.coolant_temp = can_to_temperature(data[CAN_BYTE_COOLANT_TEMP]);
|
||||
g_automotive_data.valid_flags |= VALID_FLAG_COOLANT_TEMP;
|
||||
parsed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case CAN_ID_ENGINE_OIL_TEMP:
|
||||
// Engine oil temperature (byte 7)
|
||||
if (message.data_length_code > CAN_BYTE_ENGINE_OIL_TEMP) {
|
||||
g_automotive_data.engine_oil_temp = can_to_temperature(data[CAN_BYTE_ENGINE_OIL_TEMP]);
|
||||
g_automotive_data.valid_flags |= VALID_FLAG_ENGINE_TEMP;
|
||||
parsed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case CAN_ID_GEARBOX_TEMP:
|
||||
// Gearbox oil temperature (byte 3)
|
||||
if (message.data_length_code > CAN_BYTE_GEARBOX_TEMP) {
|
||||
g_automotive_data.gearbox_oil_temp = can_to_temperature(data[CAN_BYTE_GEARBOX_TEMP]);
|
||||
g_automotive_data.valid_flags |= VALID_FLAG_GEARBOX_TEMP;
|
||||
parsed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case CAN_ID_GEARBOX_DATA:
|
||||
// Gearbox position and current gear (bytes 0 and 1)
|
||||
if (message.data_length_code > CAN_BYTE_CURRENT_GEAR) {
|
||||
// Byte 0: Gear position (P/R/N/D/S/M)
|
||||
g_automotive_data.gear_position = data[CAN_BYTE_GEAR_POS];
|
||||
|
||||
// Byte 1: Current gear number (1-8) - stored for future use
|
||||
// Could be displayed alongside position for manual modes
|
||||
|
||||
g_automotive_data.valid_flags |= VALID_FLAG_GEAR_POS;
|
||||
parsed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case CAN_ID_BATTERY_VOLTAGE:
|
||||
// Battery voltage (bytes 0-1, 16-bit value)
|
||||
if (message.data_length_code > CAN_BYTE_BATTERY_VOLT_L) {
|
||||
// Combine high and low bytes (assuming big-endian)
|
||||
uint16_t raw_voltage = (data[CAN_BYTE_BATTERY_VOLT_H] << 8) | data[CAN_BYTE_BATTERY_VOLT_L];
|
||||
|
||||
// Convert to internal format (0.01V units)
|
||||
// Assuming CAN sends in 0.1V units, multiply by 10
|
||||
g_automotive_data.battery_voltage = raw_voltage * 10;
|
||||
|
||||
g_automotive_data.valid_flags |= VALID_FLAG_BATTERY_VOLT;
|
||||
parsed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Unknown CAN ID - ignore
|
||||
break;
|
||||
}
|
||||
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Handle received CAN message
|
||||
* @param message TWAI message structure
|
||||
*/
|
||||
static void handleRxMessage(twai_message_t& message) {
|
||||
g_can_stats.messages_received++;
|
||||
g_can_stats.last_receive_time = millis();
|
||||
|
||||
// Auto-restart UART if it was stopped due to CAN timeout
|
||||
if (g_uart_auto_stopped) {
|
||||
ESP_LOGI("CANDrv", "✓ CAN messages resumed, auto-restarting UART");
|
||||
UARTManager::linkToCANState(true);
|
||||
g_uart_auto_stopped = false;
|
||||
}
|
||||
|
||||
// Parse the message
|
||||
if (parseCANMessage(message)) {
|
||||
g_can_stats.messages_parsed++;
|
||||
|
||||
// DETAILED LOGGING (TEMPORARY FOR DEBUGGING)
|
||||
// Log EVERY parsed message with actual values
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
ESP_LOGI("CANDrv", "✓ RX CAN ID=0x%X → Coolant:%d.%d°C, Oil:%d.%d°C, Gearbox:%d.%d°C, Batt:%d.%02dV, Gear:%d [%d/%d]",
|
||||
message.identifier,
|
||||
g_automotive_data.coolant_temp / 10, abs(g_automotive_data.coolant_temp % 10),
|
||||
g_automotive_data.engine_oil_temp / 10, abs(g_automotive_data.engine_oil_temp % 10),
|
||||
g_automotive_data.gearbox_oil_temp / 10, abs(g_automotive_data.gearbox_oil_temp % 10),
|
||||
g_automotive_data.battery_voltage / 100, g_automotive_data.battery_voltage % 100,
|
||||
g_automotive_data.gear_position,
|
||||
g_can_stats.messages_parsed,
|
||||
g_can_stats.messages_received);
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
} else {
|
||||
// Unknown message ID - log ALL unknown messages for debugging
|
||||
ESP_LOGW("CANDrv", "⚠ Unknown CAN ID=0x%X (DLC=%d) [%d total]",
|
||||
message.identifier,
|
||||
message.data_length_code,
|
||||
g_can_stats.messages_received);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Initialize TWAI driver
|
||||
* @return true if successful
|
||||
*/
|
||||
static bool initTWAI() {
|
||||
// General config - NORMAL mode (can send ACK to prevent retransmissions)
|
||||
// Note: LISTEN_ONLY mode cannot ACK, causing transmitters to flood the bus with retries
|
||||
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(
|
||||
(gpio_num_t)CAN_TX_PIN,
|
||||
(gpio_num_t)CAN_RX_PIN,
|
||||
TWAI_MODE_NORMAL // Required to send ACK bits - prevents message flooding
|
||||
);
|
||||
|
||||
// Increase RX queue from default 5 to 20 to handle burst traffic
|
||||
// At 25 msg/sec, this provides 800ms buffer (20/25 = 0.8s)
|
||||
g_config.rx_queue_len = 20;
|
||||
|
||||
// Timing config - 500 Kbps for BMW
|
||||
twai_timing_config_t t_config = CAN_BAUD_RATE;
|
||||
|
||||
// Filter config - accept all messages (we'll filter in software)
|
||||
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
|
||||
|
||||
// Install TWAI driver
|
||||
if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
|
||||
ESP_LOGE("CANDrv", "Failed to install TWAI driver");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI("CANDrv", "TWAI driver installed (GPIO%d/GPIO%d, 500Kbps, LISTEN_ONLY)",
|
||||
CAN_TX_PIN, CAN_RX_PIN);
|
||||
|
||||
// Start TWAI driver
|
||||
if (twai_start() != ESP_OK) {
|
||||
ESP_LOGE("CANDrv", "Failed to start TWAI driver");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI("CANDrv", "TWAI driver started");
|
||||
|
||||
// Configure alerts
|
||||
uint32_t alerts_to_enable = TWAI_ALERT_RX_DATA |
|
||||
TWAI_ALERT_ERR_PASS |
|
||||
TWAI_ALERT_BUS_ERROR |
|
||||
TWAI_ALERT_RX_QUEUE_FULL;
|
||||
|
||||
if (twai_reconfigure_alerts(alerts_to_enable, NULL) != ESP_OK) {
|
||||
ESP_LOGE("CANDrv", "Failed to reconfigure alerts");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI("CANDrv", "CAN alerts configured");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Stop and uninstall TWAI driver
|
||||
*/
|
||||
static void deinitTWAI() {
|
||||
twai_stop();
|
||||
twai_driver_uninstall();
|
||||
ESP_LOGI("CANDrv", "TWAI driver stopped and uninstalled");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief CAN reception task (runs on Core 0)
|
||||
* @param parameter Unused
|
||||
*/
|
||||
static void canTask(void* parameter) {
|
||||
ESP_LOGI("CANTask", "CAN task started on Core 0");
|
||||
|
||||
while (true) {
|
||||
// Check for queue events (start/stop commands)
|
||||
// Use shorter timeout when CAN active for faster message processing
|
||||
uint32_t queue_timeout = g_can_active ? 1 : 10;
|
||||
can_queue_event_t event;
|
||||
if (xQueueReceive(g_can_event_queue, &event, pdMS_TO_TICKS(queue_timeout)) == pdTRUE) {
|
||||
switch (event.type) {
|
||||
case CAN_EVENT_START:
|
||||
if (!g_can_active) {
|
||||
ESP_LOGI("CANTask", "Starting CAN reception...");
|
||||
if (initTWAI()) {
|
||||
g_can_active = true;
|
||||
memset(&g_can_stats, 0, sizeof(g_can_stats));
|
||||
ESP_LOGI("CANTask", "CAN reception active");
|
||||
|
||||
// Auto-start UART transmission (CAN drives UART)
|
||||
UARTManager::linkToCANState(true);
|
||||
} else {
|
||||
ESP_LOGE("CANTask", "Failed to start CAN reception");
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case CAN_EVENT_STOP:
|
||||
if (g_can_active) {
|
||||
ESP_LOGI("CANTask", "Stopping CAN reception...");
|
||||
deinitTWAI();
|
||||
g_can_active = false;
|
||||
g_uart_auto_stopped = false; // Reset auto-stop flag
|
||||
|
||||
// Auto-stop UART transmission (CAN drives UART)
|
||||
UARTManager::linkToCANState(false);
|
||||
|
||||
ESP_LOGI("CANTask", "CAN stopped. Stats: %d msgs received, %d parsed",
|
||||
g_can_stats.messages_received,
|
||||
g_can_stats.messages_parsed);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If CAN is active, poll for messages
|
||||
if (g_can_active) {
|
||||
uint32_t alerts_triggered;
|
||||
// Use 0 timeout (non-blocking) for faster polling
|
||||
twai_read_alerts(&alerts_triggered, 0);
|
||||
|
||||
// Handle error alerts
|
||||
if (alerts_triggered & TWAI_ALERT_ERR_PASS) {
|
||||
ESP_LOGW("CANTask", "TWAI controller has become error passive");
|
||||
}
|
||||
if (alerts_triggered & TWAI_ALERT_BUS_ERROR) {
|
||||
twai_status_info_t status;
|
||||
twai_get_status_info(&status);
|
||||
ESP_LOGW("CANTask", "Bus error detected (count: %d)", status.bus_error_count);
|
||||
g_can_stats.parse_errors++;
|
||||
}
|
||||
if (alerts_triggered & TWAI_ALERT_RX_QUEUE_FULL) {
|
||||
twai_status_info_t status;
|
||||
twai_get_status_info(&status);
|
||||
ESP_LOGW("CANTask", "RX queue full! Missed: %d, Overrun: %d, Queue: %d",
|
||||
status.rx_missed_count, status.rx_overrun_count, status.msgs_to_rx);
|
||||
g_can_stats.parse_errors++; // Track overflow events
|
||||
}
|
||||
|
||||
// Periodic queue depth monitoring (every 1000 messages)
|
||||
if (g_can_stats.messages_received % 1000 == 0 && g_can_stats.messages_received > 0) {
|
||||
twai_status_info_t status;
|
||||
twai_get_status_info(&status);
|
||||
ESP_LOGI("CANTask", "Queue health: %d msgs pending (max 20)", status.msgs_to_rx);
|
||||
}
|
||||
|
||||
// Handle received messages
|
||||
if (alerts_triggered & TWAI_ALERT_RX_DATA) {
|
||||
twai_message_t message;
|
||||
while (twai_receive(&message, 0) == ESP_OK) {
|
||||
handleRxMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for CAN timeout - stop UART if no messages received recently
|
||||
if (g_can_stats.messages_received > 0) { // Only check if we've received at least one message
|
||||
uint32_t time_since_last_rx = millis() - g_can_stats.last_receive_time;
|
||||
|
||||
if (time_since_last_rx > CAN_TIMEOUT_MS && !g_uart_auto_stopped) {
|
||||
// CAN data is stale - auto-stop UART to prevent transmitting stale data
|
||||
ESP_LOGW("CANTask", "⚠ CAN timeout (%dms since last message), auto-stopping UART", time_since_last_rx);
|
||||
UARTManager::linkToCANState(false);
|
||||
g_uart_auto_stopped = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// CAN inactive, sleep longer to save CPU
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
void init(bool auto_start) {
|
||||
ESP_LOGI("CANDrv", "Initializing CAN subsystem...");
|
||||
|
||||
// Create event queue
|
||||
g_can_event_queue = xQueueCreate(10, sizeof(can_queue_event_t));
|
||||
if (g_can_event_queue == NULL) {
|
||||
ESP_LOGE("CANDrv", "ERROR: Failed to create CAN event queue!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create CAN task on Core 0
|
||||
BaseType_t task_created = xTaskCreatePinnedToCore(
|
||||
canTask,
|
||||
"CAN_Task",
|
||||
CAN_TASK_STACK_SIZE,
|
||||
NULL,
|
||||
CAN_TASK_PRIORITY,
|
||||
&g_can_task_handle,
|
||||
CAN_TASK_CORE
|
||||
);
|
||||
|
||||
if (task_created != pdPASS) {
|
||||
ESP_LOGE("CANDrv", "ERROR: Failed to create CAN task!");
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI("CANDrv", "CAN task created successfully on Core 0");
|
||||
|
||||
// Auto-start if requested
|
||||
if (auto_start) {
|
||||
ESP_LOGI("CANDrv", "Auto-starting CAN...");
|
||||
start();
|
||||
} else {
|
||||
ESP_LOGI("CANDrv", "CAN initially disabled");
|
||||
}
|
||||
}
|
||||
|
||||
void start() {
|
||||
can_queue_event_t evt;
|
||||
evt.type = CAN_EVENT_START;
|
||||
xQueueSend(g_can_event_queue, &evt, 0);
|
||||
}
|
||||
|
||||
void stop() {
|
||||
can_queue_event_t evt;
|
||||
evt.type = CAN_EVENT_STOP;
|
||||
xQueueSend(g_can_event_queue, &evt, 0);
|
||||
}
|
||||
|
||||
can_stats_t getStats() {
|
||||
return g_can_stats;
|
||||
}
|
||||
|
||||
bool isActive() {
|
||||
return g_can_active;
|
||||
}
|
||||
|
||||
void onCANToggle(lv_event_t *e) {
|
||||
lv_obj_t *target = lv_event_get_target(e);
|
||||
if (target == NULL) {
|
||||
ESP_LOGE("CANDrv", "ERROR: CAN toggle target is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
||||
ESP_LOGI("CANDrv", "===== CAN Toggle Event =====");
|
||||
ESP_LOGI("CANDrv", "CAN Toggle State: %s", state ? "ON" : "OFF");
|
||||
|
||||
// Save state to NVS
|
||||
SettingsManager::saveCANState(state);
|
||||
|
||||
// Send command to CAN task
|
||||
if (state) {
|
||||
start();
|
||||
ESP_LOGI("CANDrv", "CAN START command sent to task");
|
||||
} else {
|
||||
stop();
|
||||
ESP_LOGI("CANDrv", "CAN STOP command sent to task");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace CANDriver
|
||||
@@ -0,0 +1,2 @@
|
||||
dependencies:
|
||||
idf: '>=5.1'
|
||||
@@ -0,0 +1,2 @@
|
||||
dependencies:
|
||||
idf: '>=5.1'
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
#include <Arduino.h>
|
||||
#include <lvgl.h>
|
||||
#include "display/lvgl_v8_port.h" // LVGL port layer (for lvgl_port_lock/unlock)
|
||||
#include "modules/display_init.h" // Display initialization module
|
||||
#include "modules/wifi_manager.h" // WiFi manager module
|
||||
#include "modules/uart_manager.h" // UART manager module
|
||||
#include "drivers/can_driver.h" // CAN Bus driver module
|
||||
#include "modules/settings_manager.h" // Settings manager module
|
||||
#include "modules/ui_state_manager.h" // UI state manager module
|
||||
#include "modules/meters_manager.h" // Meters display manager module
|
||||
|
||||
// ============================================================================
|
||||
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
|
||||
// ============================================================================
|
||||
// This is a minimal setup with:
|
||||
// - LVGL display and touch initialization
|
||||
// - SquareLine Studio UI (Home Screen + Settings Screen)
|
||||
// - WiFi module with async scanning (managed by WiFiManager)
|
||||
// - UART data transmission at 5Hz (managed by UARTManager)
|
||||
// - UI state synchronization (managed by UIStateManager)
|
||||
// - Persistent settings storage (managed by SettingsManager)
|
||||
// ============================================================================
|
||||
|
||||
// External UI element references (from ui_Settings_Screen.c)
|
||||
extern "C" {
|
||||
extern lv_obj_t *uic_Main_Container;
|
||||
extern lv_obj_t *uic_Toggle_Wifi_Switch;
|
||||
extern lv_obj_t *uic_Toggle_UART_Switch;
|
||||
extern lv_obj_t *uic_Toggle_CAN_Bus_Switch;
|
||||
}
|
||||
|
||||
// External UI element references (from ui_Home_Screen.c)
|
||||
extern "C" {
|
||||
extern lv_obj_t *uic_Home_Loading_Container;
|
||||
extern lv_obj_t *uic_Engine_Temp_Icon;
|
||||
extern lv_obj_t *uic_Engine_Oil_Temp_Icon;
|
||||
extern lv_obj_t *uic_GearBox_Oil_Temp;
|
||||
extern lv_obj_t *uic_Batery_Values_LBL;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS (C linkage for SquareLine Studio UI callbacks)
|
||||
// ============================================================================
|
||||
|
||||
extern "C" {
|
||||
|
||||
// WiFi-related event handlers (delegated to WiFiManager)
|
||||
void onSelectSSID(lv_event_t *e) {
|
||||
WiFiManager::onSelectSSID(e);
|
||||
}
|
||||
|
||||
// WiFi toggle event handler - delegates to WiFiManager module
|
||||
void onWifiToggle(lv_event_t *e)
|
||||
{
|
||||
// Get the actual widget from the event (safer than global variable)
|
||||
lv_obj_t *target = lv_event_get_target(e);
|
||||
|
||||
// Verify the widget is valid
|
||||
if (target == NULL) {
|
||||
Serial.println("ERROR: WiFi toggle target is NULL!");
|
||||
Serial.flush();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the toggle state
|
||||
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
||||
|
||||
Serial.printf("WiFi Toggle RELEASED - State: %s\n", state ? "ON" : "OFF");
|
||||
Serial.flush();
|
||||
|
||||
// Save state to NVS for persistence across power cycles
|
||||
SettingsManager::saveWiFiState(state);
|
||||
|
||||
// Delegate to WiFiManager module
|
||||
WiFiManager::onWifiToggle(e);
|
||||
}
|
||||
|
||||
// UART toggle event handler - delegates to UARTManager module
|
||||
void onUARTToggle(lv_event_t *e)
|
||||
{
|
||||
// Get the actual widget from the event (safer than global variable)
|
||||
lv_obj_t *target = lv_event_get_target(e);
|
||||
|
||||
// Verify the widget is valid
|
||||
if (target == NULL) {
|
||||
Serial.println("ERROR: UART toggle target is NULL!");
|
||||
Serial.flush();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the toggle state
|
||||
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
||||
|
||||
Serial.printf("UART Toggle RELEASED - State: %s\n", state ? "ON" : "OFF");
|
||||
Serial.flush();
|
||||
|
||||
// Save state to NVS for persistence across power cycles
|
||||
SettingsManager::saveUARTState(state);
|
||||
|
||||
// Delegate to UARTManager module
|
||||
UARTManager::onUARTToggle(e);
|
||||
}
|
||||
|
||||
// CAN Bus toggle event handler - delegates to CANDriver module
|
||||
void onCANBusToggle(lv_event_t *e)
|
||||
{
|
||||
CANDriver::onCANToggle(e);
|
||||
}
|
||||
|
||||
// Debug toggle event handler - delegates to UIStateManager module
|
||||
void onDebugToggle(lv_event_t *e)
|
||||
{
|
||||
UIStateManager::onDebugToggle(e);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
// ============================================================================
|
||||
// HOME SCREEN METER INITIALIZATION
|
||||
// ============================================================================
|
||||
|
||||
// Track which Home screen instance has meters initialized
|
||||
static lv_obj_t* g_last_home_screen = NULL;
|
||||
|
||||
/**
|
||||
* @brief Initialize meters when Home screen loads
|
||||
* @note Uses screen instance tracking to prevent re-initialization
|
||||
* This survives SquareLine Studio regeneration since it's in main.cpp
|
||||
*/
|
||||
void initializeHomeScreenMeters() {
|
||||
// Wait for Home screen UI widgets to be created
|
||||
if (uic_Home_Loading_Container == NULL) {
|
||||
// Reset when screen is unloaded
|
||||
g_last_home_screen = NULL;
|
||||
return; // Home screen not loaded yet
|
||||
}
|
||||
|
||||
// Get the Home screen pointer
|
||||
lv_obj_t* home_screen = lv_obj_get_parent(uic_Home_Loading_Container);
|
||||
if (home_screen == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we've already initialized this screen instance
|
||||
if (g_last_home_screen == home_screen) {
|
||||
return; // Already initialized this instance
|
||||
}
|
||||
|
||||
ESP_LOGI("MAIN", "Home screen detected - initializing meters...");
|
||||
|
||||
// Initialize meters (LVGL lock required for thread safety)
|
||||
lvgl_port_lock(-1);
|
||||
meters_manager_init_coolant(uic_Home_Loading_Container, uic_Engine_Temp_Icon);
|
||||
meters_manager_init_engine_oil(uic_Home_Loading_Container, uic_Engine_Oil_Temp_Icon);
|
||||
meters_manager_init_gearbox_oil(uic_Home_Loading_Container, uic_GearBox_Oil_Temp);
|
||||
lvgl_port_unlock();
|
||||
|
||||
// Mark this screen instance as initialized
|
||||
g_last_home_screen = home_screen;
|
||||
|
||||
ESP_LOGI("MAIN", "Meters initialized for Home screen");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// SETUP - Initialize hardware and UI
|
||||
// ============================================================================
|
||||
void setup()
|
||||
{
|
||||
Serial.begin(115200);
|
||||
delay(2000); // Longer delay for serial to stabilize
|
||||
|
||||
// Use ESP_LOG instead of Serial.println to match library output
|
||||
ESP_LOGI("MAIN", "=== ESP32-S3-LCD-5B Minimal Setup ===");
|
||||
ESP_LOGI("MAIN", "Firmware compiled: %s %s", __DATE__, __TIME__);
|
||||
|
||||
// Initialize display hardware and UI
|
||||
ESP_LOGI("MAIN", "Initializing display and UI...");
|
||||
DisplayInit::init();
|
||||
ESP_LOGI("MAIN", "Display init COMPLETED!");
|
||||
|
||||
// Initialize Settings Manager
|
||||
ESP_LOGI("MAIN", "Initializing Settings Manager...");
|
||||
SettingsManager::init();
|
||||
|
||||
// Load saved switch states from NVS
|
||||
ESP_LOGI("MAIN", "Loading saved switch states from NVS...");
|
||||
bool saved_wifi_state = SettingsManager::loadWiFiState();
|
||||
bool saved_uart_state = SettingsManager::loadUARTState();
|
||||
bool saved_can_state = SettingsManager::loadCANState();
|
||||
bool saved_debug_state = SettingsManager::loadDebugState();
|
||||
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
|
||||
|
||||
// Initialize UI State Manager
|
||||
ESP_LOGI("MAIN", "Initializing UI State Manager...");
|
||||
UIStateManager::init();
|
||||
|
||||
// Initialize WiFi subsystem using WiFiManager module
|
||||
ESP_LOGI("MAIN", "Initializing WiFi subsystem...");
|
||||
WiFiManager::init(saved_wifi_state);
|
||||
|
||||
// Initialize UART subsystem using UARTManager module
|
||||
ESP_LOGI("MAIN", "Initializing UART subsystem...");
|
||||
UARTManager::init(saved_uart_state);
|
||||
|
||||
// Initialize CAN Bus subsystem using CANDriver module
|
||||
ESP_LOGI("MAIN", "Initializing CAN Bus subsystem...");
|
||||
CANDriver::init(saved_can_state);
|
||||
|
||||
// Set debug state AFTER all subsystems are initialized
|
||||
UIStateManager::setDebugEnabled(saved_debug_state);
|
||||
|
||||
ESP_LOGI("MAIN", "");
|
||||
ESP_LOGI("MAIN", "=== System Ready ===");
|
||||
ESP_LOGI("MAIN", "- LVGL task: UI rendering (Core 1, Priority 2)");
|
||||
ESP_LOGI("MAIN", "- WiFi task: Network scanning (Core 0, Priority 1)");
|
||||
ESP_LOGI("MAIN", "- UART task: Data transmission (Core 0, Priority 1)");
|
||||
ESP_LOGI("MAIN", "- Screen: 1024x600");
|
||||
ESP_LOGI("MAIN", "- UART: 115200 baud on GPIO 43/44 (RS485 terminal)");
|
||||
ESP_LOGI("MAIN", "- Swipe left/right to navigate between screens");
|
||||
ESP_LOGI("MAIN", "- Settings screen has WiFi and UART toggles");
|
||||
ESP_LOGI("MAIN", "- WiFi scan updates every 10 seconds when enabled");
|
||||
ESP_LOGI("MAIN", "- UART transmits at 5Hz (200ms) when enabled");
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
static uint32_t last_print = 0;
|
||||
static uint32_t last_meter_update = 0;
|
||||
|
||||
// Debug: Print heartbeat every 5 seconds
|
||||
if (millis() - last_print > 5000) {
|
||||
ESP_LOGI("LOOP", "Heartbeat - system running");
|
||||
last_print = millis();
|
||||
}
|
||||
|
||||
// LVGL task runs automatically in separate task
|
||||
// Keep loop() minimal and empty to avoid interfering with LVGL rendering
|
||||
|
||||
// Continuously sync UI switches with actual service states
|
||||
// (Settings screen gets destroyed/recreated when swiping)
|
||||
UIStateManager::applySavedStatesToUI();
|
||||
|
||||
// Initialize Home screen meters when screen loads
|
||||
// (This survives SquareLine Studio regeneration)
|
||||
initializeHomeScreenMeters();
|
||||
|
||||
// Update meter values from CAN data every 200ms (5Hz)
|
||||
if (millis() - last_meter_update >= 200) {
|
||||
last_meter_update = millis();
|
||||
|
||||
// Read sensor data from automotive data (thread-safe)
|
||||
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
int16_t coolant_temp = UARTManager::g_automotive_data.coolant_temp;
|
||||
int16_t engine_oil_temp = UARTManager::g_automotive_data.engine_oil_temp;
|
||||
int16_t gearbox_oil_temp = UARTManager::g_automotive_data.gearbox_oil_temp;
|
||||
uint16_t battery_voltage = UARTManager::g_automotive_data.battery_voltage;
|
||||
xSemaphoreGive(UARTManager::g_data_mutex);
|
||||
|
||||
// Update meters and labels (LVGL port lock required for thread safety)
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
// Update temperature meters
|
||||
meters_manager_update_coolant_temp(coolant_temp);
|
||||
meters_manager_update_engine_oil_temp(engine_oil_temp);
|
||||
meters_manager_update_gearbox_oil_temp(gearbox_oil_temp);
|
||||
|
||||
// Update battery voltage label (format: "12.45V")
|
||||
if (uic_Batery_Values_LBL != NULL) {
|
||||
char battery_buf[16];
|
||||
snprintf(battery_buf, sizeof(battery_buf), "%d.%02d",
|
||||
battery_voltage / 100, battery_voltage % 100);
|
||||
lv_label_set_text(uic_Batery_Values_LBL, battery_buf);
|
||||
}
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
}
|
||||
|
||||
delay(100); // Check frequently to catch screen changes quickly
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Display Initialization Module Implementation
|
||||
*/
|
||||
|
||||
#include "display_init.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include "ui/ui.h"
|
||||
|
||||
namespace DisplayInit {
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
DisplayObjects init() {
|
||||
Serial.println("[DisplayInit] Starting display initialization...");
|
||||
|
||||
// Step 1-3: Create and initialize board
|
||||
Serial.println("[DisplayInit] Step 1: Creating Board object...");
|
||||
Board *board = new Board();
|
||||
|
||||
Serial.println("[DisplayInit] Step 2: Calling board->init()...");
|
||||
board->init();
|
||||
Serial.println("[DisplayInit] Step 3: Board init completed");
|
||||
|
||||
// Step 4-5: Configure framebuffers (if avoid-tearing mode is enabled)
|
||||
#if LVGL_PORT_AVOID_TEARING_MODE
|
||||
Serial.println("[DisplayInit] Step 4: Configuring LCD frame buffers...");
|
||||
auto lcd = board->getLCD();
|
||||
lcd->configFrameBufferNumber(LVGL_PORT_DISP_BUFFER_NUM);
|
||||
|
||||
#if ESP_PANEL_DRIVERS_BUS_ENABLE_RGB && CONFIG_IDF_TARGET_ESP32S3
|
||||
auto lcd_bus = lcd->getBus();
|
||||
if (lcd_bus->getBasicAttributes().type == ESP_PANEL_BUS_TYPE_RGB) {
|
||||
Serial.println("[DisplayInit] Step 5: Configuring bounce buffer...");
|
||||
static_cast<BusRGB *>(lcd_bus)->configRGB_BounceBufferSize(lcd->getFrameWidth() * 10);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Step 6: Get backlight object (before board->begin() to control it manually)
|
||||
Serial.println("[DisplayInit] Step 6: Getting backlight control...");
|
||||
auto backlight = board->getBacklight();
|
||||
|
||||
// Step 7-8: Start the board
|
||||
Serial.println("[DisplayInit] Step 7: Calling board->begin()...");
|
||||
if (!board->begin()) {
|
||||
Serial.println("[DisplayInit] ERROR: board->begin() failed!");
|
||||
Serial.println("[DisplayInit] System halted.");
|
||||
while (1) {
|
||||
delay(1000);
|
||||
}
|
||||
}
|
||||
Serial.println("[DisplayInit] Step 8: Board initialized successfully!");
|
||||
|
||||
// Step 9: Turn OFF backlight to prevent white flash
|
||||
Serial.println("[DisplayInit] Step 9: Turning off backlight to prevent white flash...");
|
||||
if (backlight != nullptr) {
|
||||
backlight->off();
|
||||
}
|
||||
|
||||
// Step 10-11: Initialize LVGL
|
||||
Serial.println("[DisplayInit] Step 10: Initializing LVGL...");
|
||||
Serial.flush();
|
||||
lvgl_port_init(board->getLCD(), board->getTouch());
|
||||
Serial.println("[DisplayInit] Step 11: LVGL initialized successfully!");
|
||||
Serial.flush();
|
||||
|
||||
// Step 12-13: Load SquareLine Studio UI
|
||||
Serial.println("[DisplayInit] Step 12: Loading SquareLine Studio UI...");
|
||||
lvgl_port_lock(-1);
|
||||
ui_init(); // Initialize the SquareLine Studio generated UI
|
||||
// Note: onSelectSSID event handler is registered in ui_Settings_Screen.c
|
||||
lvgl_port_unlock();
|
||||
Serial.println("[DisplayInit] Step 13: SquareLine UI loaded successfully!");
|
||||
|
||||
// Small delay to ensure UI is rendered
|
||||
delay(100);
|
||||
|
||||
// Step 14: NOW turn on backlight - UI is ready!
|
||||
Serial.println("[DisplayInit] Step 14: Turning on backlight...");
|
||||
if (backlight != nullptr) {
|
||||
backlight->on();
|
||||
}
|
||||
Serial.println("[DisplayInit] Backlight on - no white flash!");
|
||||
Serial.println("[DisplayInit] Display initialization complete!");
|
||||
|
||||
// Return board and backlight objects for later use
|
||||
return {board, backlight};
|
||||
}
|
||||
|
||||
} // namespace DisplayInit
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Display Initialization Module
|
||||
*
|
||||
* Handles hardware-specific initialization for the Waveshare ESP32-S3-Touch-LCD-5B:
|
||||
* - Board initialization (LCD panel, touch controller)
|
||||
* - LVGL initialization and configuration
|
||||
* - SquareLine Studio UI loading
|
||||
* - Backlight control to prevent white flash during startup
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <esp_display_panel.hpp>
|
||||
|
||||
using namespace esp_panel::drivers;
|
||||
using namespace esp_panel::board;
|
||||
|
||||
namespace DisplayInit {
|
||||
|
||||
/**
|
||||
* @brief Display hardware objects returned by initialization
|
||||
*/
|
||||
struct DisplayObjects {
|
||||
Board* board; // ESP32 Display Panel board object
|
||||
Backlight* backlight; // Backlight controller
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Initialize the display hardware and LVGL
|
||||
*
|
||||
* This function performs the complete display initialization sequence:
|
||||
* 1. Create and initialize the display board object
|
||||
* 2. Configure framebuffers (if avoid-tearing mode is enabled)
|
||||
* 3. Initialize backlight (off initially to prevent white flash)
|
||||
* 4. Start the board
|
||||
* 5. Initialize LVGL porting layer
|
||||
* 6. Load SquareLine Studio UI
|
||||
* 7. Turn on backlight after UI is ready
|
||||
*
|
||||
* @return DisplayObjects containing board and backlight pointers
|
||||
* @note This function will halt in an infinite loop if board initialization fails
|
||||
*/
|
||||
DisplayObjects init();
|
||||
|
||||
} // namespace DisplayInit
|
||||
@@ -0,0 +1,363 @@
|
||||
/*
|
||||
* Meters Manager Module Implementation
|
||||
*/
|
||||
|
||||
#include "meters_manager.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
static lv_obj_t *g_coolant_meter = NULL;
|
||||
static lv_meter_indicator_t *g_coolant_needle = NULL;
|
||||
static lv_obj_t *g_coolant_label = NULL;
|
||||
|
||||
static lv_obj_t *g_engine_oil_meter = NULL;
|
||||
static lv_meter_indicator_t *g_engine_oil_needle = NULL;
|
||||
static lv_obj_t *g_engine_oil_label = NULL;
|
||||
|
||||
static lv_obj_t *g_gearbox_oil_meter = NULL;
|
||||
static lv_meter_indicator_t *g_gearbox_oil_needle = NULL;
|
||||
static lv_obj_t *g_gearbox_oil_label = NULL;
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
void meters_manager_init_coolant(lv_obj_t *container, lv_obj_t *icon)
|
||||
{
|
||||
if (container == NULL)
|
||||
{
|
||||
ESP_LOGE("MetersMgr", "Container is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI("MetersMgr", "Initializing Coolant Temperature meter...");
|
||||
|
||||
// Create coolant temperature meter (250x250 pixels)
|
||||
g_coolant_meter = lv_meter_create(container);
|
||||
lv_obj_set_size(g_coolant_meter, 250, 250);
|
||||
lv_obj_center(g_coolant_meter);
|
||||
|
||||
// Position icon inside the meter if provided
|
||||
if (icon != NULL)
|
||||
{
|
||||
lv_obj_set_parent(icon, g_coolant_meter); // Reparent icon to meter
|
||||
lv_obj_align(icon, LV_ALIGN_CENTER, 0, 50); // Center horizontally, 50px below center
|
||||
lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); // Make visible
|
||||
ESP_LOGI("MetersMgr", "Icon positioned inside meter (50px below center)");
|
||||
|
||||
// Create label below the icon to show temperature reading
|
||||
g_coolant_label = lv_label_create(g_coolant_meter);
|
||||
lv_obj_align_to(g_coolant_label, icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
|
||||
lv_label_set_text(g_coolant_label, "--.-°C");
|
||||
lv_obj_set_style_text_color(g_coolant_label, lv_color_white(), LV_PART_MAIN);
|
||||
}
|
||||
|
||||
// Add a scale: 0-150°C range
|
||||
lv_meter_scale_t *scale = lv_meter_add_scale(g_coolant_meter);
|
||||
lv_meter_set_scale_ticks(g_coolant_meter, scale, 31, 2, 10, lv_palette_main(LV_PALETTE_GREY));
|
||||
lv_meter_set_scale_major_ticks(g_coolant_meter, scale, 5, 4, 15, lv_color_black(), 15);
|
||||
lv_meter_set_scale_range(g_coolant_meter, scale, 0, 150, 270, 135); // 0-150°C, 270° arc, start at 135°
|
||||
|
||||
// Add blue arc for normal range (0-90°C)
|
||||
lv_meter_indicator_t *indic_blue = lv_meter_add_arc(g_coolant_meter, scale, 3, lv_palette_main(LV_PALETTE_BLUE), 0);
|
||||
lv_meter_set_indicator_start_value(g_coolant_meter, indic_blue, 0);
|
||||
lv_meter_set_indicator_end_value(g_coolant_meter, indic_blue, 90);
|
||||
|
||||
// Make tick lines blue in normal range
|
||||
lv_meter_indicator_t *indic_blue_lines = lv_meter_add_scale_lines(g_coolant_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_BLUE), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_coolant_meter, indic_blue_lines, 0);
|
||||
lv_meter_set_indicator_end_value(g_coolant_meter, indic_blue_lines, 90);
|
||||
|
||||
// Add green arc for warm range (90-105°C)
|
||||
lv_meter_indicator_t *indic_green = lv_meter_add_arc(g_coolant_meter, scale, 3, lv_palette_main(LV_PALETTE_GREEN), 0);
|
||||
lv_meter_set_indicator_start_value(g_coolant_meter, indic_green, 90);
|
||||
lv_meter_set_indicator_end_value(g_coolant_meter, indic_green, 105);
|
||||
|
||||
// Make tick lines green in warm range
|
||||
lv_meter_indicator_t *indic_green_lines = lv_meter_add_scale_lines(g_coolant_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_GREEN), lv_palette_main(LV_PALETTE_GREEN), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_coolant_meter, indic_green_lines, 90);
|
||||
lv_meter_set_indicator_end_value(g_coolant_meter, indic_green_lines, 105);
|
||||
|
||||
// Add red arc for high temperature range (105-150°C)
|
||||
lv_meter_indicator_t *indic_red = lv_meter_add_arc(g_coolant_meter, scale, 3, lv_palette_main(LV_PALETTE_RED), 0);
|
||||
lv_meter_set_indicator_start_value(g_coolant_meter, indic_red, 105);
|
||||
lv_meter_set_indicator_end_value(g_coolant_meter, indic_red, 150);
|
||||
|
||||
// Make tick lines red in high temperature range
|
||||
lv_meter_indicator_t *indic_red_lines = lv_meter_add_scale_lines(g_coolant_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_RED), lv_palette_main(LV_PALETTE_RED), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_coolant_meter, indic_red_lines, 105);
|
||||
lv_meter_set_indicator_end_value(g_coolant_meter, indic_red_lines, 150);
|
||||
|
||||
// Add needle indicator
|
||||
g_coolant_needle = lv_meter_add_needle_line(g_coolant_meter, scale, 4, lv_palette_main(LV_PALETTE_GREY), -10);
|
||||
|
||||
// Add label below meter to show numeric value
|
||||
// g_coolant_label = lv_label_create(container);
|
||||
// lv_obj_align_to(g_coolant_label, g_coolant_meter, LV_ALIGN_OUT_BOTTOM_MID, 0, 10);
|
||||
// lv_label_set_text(g_coolant_label, "Coolant: --.-°C");
|
||||
|
||||
// Set initial value to 0
|
||||
lv_meter_set_indicator_value(g_coolant_meter, g_coolant_needle, 0);
|
||||
|
||||
ESP_LOGI("MetersMgr", "Coolant Temperature meter initialized");
|
||||
}
|
||||
|
||||
void meters_manager_init_engine_oil(lv_obj_t *container, lv_obj_t *icon)
|
||||
{
|
||||
if (container == NULL)
|
||||
{
|
||||
ESP_LOGE("MetersMgr", "Container is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI("MetersMgr", "Initializing Engine Oil Temperature meter...");
|
||||
|
||||
// Create engine oil temperature meter (250x250 pixels)
|
||||
g_engine_oil_meter = lv_meter_create(container);
|
||||
lv_obj_set_size(g_engine_oil_meter, 250, 250);
|
||||
lv_obj_center(g_engine_oil_meter);
|
||||
|
||||
// Position icon inside the meter if provided
|
||||
if (icon != NULL)
|
||||
{
|
||||
lv_obj_set_parent(icon, g_engine_oil_meter); // Reparent icon to meter
|
||||
lv_obj_align(icon, LV_ALIGN_CENTER, 0, 50); // Center horizontally, 50px below center
|
||||
lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); // Make visible
|
||||
ESP_LOGI("MetersMgr", "Icon positioned inside meter (50px below center)");
|
||||
|
||||
// Create label below the icon to show temperature reading
|
||||
g_engine_oil_label = lv_label_create(g_engine_oil_meter);
|
||||
lv_obj_align_to(g_engine_oil_label, icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
|
||||
lv_label_set_text(g_engine_oil_label, "--.-°C");
|
||||
lv_obj_set_style_text_color(g_engine_oil_label, lv_color_white(), LV_PART_MAIN);
|
||||
}
|
||||
|
||||
// Add a scale: 0-150°C range
|
||||
lv_meter_scale_t *scale = lv_meter_add_scale(g_engine_oil_meter);
|
||||
lv_meter_set_scale_ticks(g_engine_oil_meter, scale, 31, 2, 10, lv_palette_main(LV_PALETTE_GREY));
|
||||
lv_meter_set_scale_major_ticks(g_engine_oil_meter, scale, 5, 4, 15, lv_color_black(), 15);
|
||||
lv_meter_set_scale_range(g_engine_oil_meter, scale, 0, 150, 270, 135); // 0-150°C, 270° arc, start at 135°
|
||||
|
||||
// Add blue arc for normal range (0-90°C)
|
||||
lv_meter_indicator_t *indic_blue = lv_meter_add_arc(g_engine_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_BLUE), 0);
|
||||
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_blue, 0);
|
||||
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_blue, 90);
|
||||
|
||||
// Make tick lines blue in normal range
|
||||
lv_meter_indicator_t *indic_blue_lines = lv_meter_add_scale_lines(g_engine_oil_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_BLUE), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_blue_lines, 0);
|
||||
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_blue_lines, 90);
|
||||
|
||||
// Add green arc for warm range (90-105°C)
|
||||
lv_meter_indicator_t *indic_green = lv_meter_add_arc(g_engine_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_GREEN), 0);
|
||||
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_green, 90);
|
||||
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_green, 105);
|
||||
|
||||
// Make tick lines green in warm range
|
||||
lv_meter_indicator_t *indic_green_lines = lv_meter_add_scale_lines(g_engine_oil_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_GREEN), lv_palette_main(LV_PALETTE_GREEN), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_green_lines, 90);
|
||||
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_green_lines, 105);
|
||||
|
||||
// Add red arc for high temperature range (105-150°C)
|
||||
lv_meter_indicator_t *indic_red = lv_meter_add_arc(g_engine_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_RED), 0);
|
||||
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_red, 105);
|
||||
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_red, 150);
|
||||
|
||||
// Make tick lines red in high temperature range
|
||||
lv_meter_indicator_t *indic_red_lines = lv_meter_add_scale_lines(g_engine_oil_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_RED), lv_palette_main(LV_PALETTE_RED), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_engine_oil_meter, indic_red_lines, 105);
|
||||
lv_meter_set_indicator_end_value(g_engine_oil_meter, indic_red_lines, 150);
|
||||
|
||||
// Add needle indicator
|
||||
g_engine_oil_needle = lv_meter_add_needle_line(g_engine_oil_meter, scale, 4, lv_palette_main(LV_PALETTE_GREY), -10);
|
||||
|
||||
// Set initial value to 0
|
||||
lv_meter_set_indicator_value(g_engine_oil_meter, g_engine_oil_needle, 0);
|
||||
|
||||
ESP_LOGI("MetersMgr", "Engine Oil Temperature meter initialized");
|
||||
}
|
||||
|
||||
void meters_manager_init_gearbox_oil(lv_obj_t *container, lv_obj_t *icon)
|
||||
{
|
||||
if (container == NULL)
|
||||
{
|
||||
ESP_LOGE("MetersMgr", "Container is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI("MetersMgr", "Initializing Gearbox Oil Temperature meter...");
|
||||
|
||||
// Create gearbox oil temperature meter (250x250 pixels)
|
||||
g_gearbox_oil_meter = lv_meter_create(container);
|
||||
lv_obj_set_size(g_gearbox_oil_meter, 250, 250);
|
||||
lv_obj_center(g_gearbox_oil_meter);
|
||||
|
||||
// Position icon inside the meter if provided
|
||||
if (icon != NULL)
|
||||
{
|
||||
lv_obj_set_parent(icon, g_gearbox_oil_meter); // Reparent icon to meter
|
||||
lv_obj_align(icon, LV_ALIGN_CENTER, 0, 50); // Center horizontally, 50px below center
|
||||
lv_obj_clear_flag(icon, LV_OBJ_FLAG_HIDDEN); // Make visible
|
||||
ESP_LOGI("MetersMgr", "Icon positioned inside meter (50px below center)");
|
||||
|
||||
// Create label below the icon to show temperature reading
|
||||
g_gearbox_oil_label = lv_label_create(g_gearbox_oil_meter);
|
||||
lv_obj_align_to(g_gearbox_oil_label, icon, LV_ALIGN_OUT_BOTTOM_MID, 0, 5);
|
||||
lv_label_set_text(g_gearbox_oil_label, "--.-°C");
|
||||
lv_obj_set_style_text_color(g_gearbox_oil_label, lv_color_white(), LV_PART_MAIN);
|
||||
}
|
||||
|
||||
// Add a scale: 0-150°C range
|
||||
lv_meter_scale_t *scale = lv_meter_add_scale(g_gearbox_oil_meter);
|
||||
lv_meter_set_scale_ticks(g_gearbox_oil_meter, scale, 31, 2, 10, lv_palette_main(LV_PALETTE_GREY));
|
||||
lv_meter_set_scale_major_ticks(g_gearbox_oil_meter, scale, 5, 4, 15, lv_color_black(), 15);
|
||||
lv_meter_set_scale_range(g_gearbox_oil_meter, scale, 0, 150, 270, 135); // 0-150°C, 270° arc, start at 135°
|
||||
|
||||
// Add blue arc for normal range (0-90°C)
|
||||
lv_meter_indicator_t *indic_blue = lv_meter_add_arc(g_gearbox_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_BLUE), 0);
|
||||
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_blue, 0);
|
||||
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_blue, 90);
|
||||
|
||||
// Make tick lines blue in normal range
|
||||
lv_meter_indicator_t *indic_blue_lines = lv_meter_add_scale_lines(g_gearbox_oil_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_BLUE), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_blue_lines, 0);
|
||||
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_blue_lines, 90);
|
||||
|
||||
// Add green arc for warm range (90-105°C)
|
||||
lv_meter_indicator_t *indic_green = lv_meter_add_arc(g_gearbox_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_GREEN), 0);
|
||||
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_green, 90);
|
||||
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_green, 105);
|
||||
|
||||
// Make tick lines green in warm range
|
||||
lv_meter_indicator_t *indic_green_lines = lv_meter_add_scale_lines(g_gearbox_oil_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_GREEN), lv_palette_main(LV_PALETTE_GREEN), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_green_lines, 90);
|
||||
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_green_lines, 105);
|
||||
|
||||
// Add red arc for high temperature range (105-150°C)
|
||||
lv_meter_indicator_t *indic_red = lv_meter_add_arc(g_gearbox_oil_meter, scale, 3, lv_palette_main(LV_PALETTE_RED), 0);
|
||||
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_red, 105);
|
||||
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_red, 150);
|
||||
|
||||
// Make tick lines red in high temperature range
|
||||
lv_meter_indicator_t *indic_red_lines = lv_meter_add_scale_lines(g_gearbox_oil_meter, scale,
|
||||
lv_palette_main(LV_PALETTE_RED), lv_palette_main(LV_PALETTE_RED), false, 0);
|
||||
lv_meter_set_indicator_start_value(g_gearbox_oil_meter, indic_red_lines, 105);
|
||||
lv_meter_set_indicator_end_value(g_gearbox_oil_meter, indic_red_lines, 150);
|
||||
|
||||
// Add needle indicator
|
||||
g_gearbox_oil_needle = lv_meter_add_needle_line(g_gearbox_oil_meter, scale, 4, lv_palette_main(LV_PALETTE_GREY), -10);
|
||||
|
||||
// Set initial value to 0
|
||||
lv_meter_set_indicator_value(g_gearbox_oil_meter, g_gearbox_oil_needle, 0);
|
||||
|
||||
ESP_LOGI("MetersMgr", "Gearbox Oil Temperature meter initialized");
|
||||
}
|
||||
|
||||
void meters_manager_update_coolant_temp(int16_t temp_x10)
|
||||
{
|
||||
if (g_coolant_meter == NULL || g_coolant_needle == NULL)
|
||||
{
|
||||
return; // Not initialized yet
|
||||
}
|
||||
|
||||
// Convert temp_x10 to whole degrees for meter (e.g., 890 -> 89)
|
||||
int16_t temp_degrees = temp_x10 / 10;
|
||||
|
||||
// Clamp to meter range (0-150°C)
|
||||
if (temp_degrees < 0)
|
||||
temp_degrees = 0;
|
||||
if (temp_degrees > 150)
|
||||
temp_degrees = 150;
|
||||
|
||||
// Update needle position
|
||||
lv_meter_set_indicator_value(g_coolant_meter, g_coolant_needle, temp_degrees);
|
||||
|
||||
// Update label with precise value (with decimal)
|
||||
if (g_coolant_label != NULL)
|
||||
{
|
||||
char buf[16];
|
||||
snprintf(buf, sizeof(buf), "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
|
||||
lv_label_set_text(g_coolant_label, buf);
|
||||
}
|
||||
}
|
||||
|
||||
void meters_manager_update_engine_oil_temp(int16_t temp_x10)
|
||||
{
|
||||
if (g_engine_oil_meter == NULL || g_engine_oil_needle == NULL)
|
||||
{
|
||||
return; // Not initialized yet
|
||||
}
|
||||
|
||||
// Convert temp_x10 to whole degrees for meter (e.g., 920 -> 92)
|
||||
int16_t temp_degrees = temp_x10 / 10;
|
||||
|
||||
// Clamp to meter range (0-150°C)
|
||||
if (temp_degrees < 0)
|
||||
temp_degrees = 0;
|
||||
if (temp_degrees > 150)
|
||||
temp_degrees = 150;
|
||||
|
||||
// Update needle position
|
||||
lv_meter_set_indicator_value(g_engine_oil_meter, g_engine_oil_needle, temp_degrees);
|
||||
|
||||
// Update label with precise value (with decimal)
|
||||
if (g_engine_oil_label != NULL)
|
||||
{
|
||||
char buf[16];
|
||||
snprintf(buf, sizeof(buf), "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
|
||||
lv_label_set_text(g_engine_oil_label, buf);
|
||||
}
|
||||
}
|
||||
|
||||
void meters_manager_update_gearbox_oil_temp(int16_t temp_x10)
|
||||
{
|
||||
if (g_gearbox_oil_meter == NULL || g_gearbox_oil_needle == NULL)
|
||||
{
|
||||
return; // Not initialized yet
|
||||
}
|
||||
|
||||
// Convert temp_x10 to whole degrees for meter (e.g., 850 -> 85)
|
||||
int16_t temp_degrees = temp_x10 / 10;
|
||||
|
||||
// Clamp to meter range (0-150°C)
|
||||
if (temp_degrees < 0)
|
||||
temp_degrees = 0;
|
||||
if (temp_degrees > 150)
|
||||
temp_degrees = 150;
|
||||
|
||||
// Update needle position
|
||||
lv_meter_set_indicator_value(g_gearbox_oil_meter, g_gearbox_oil_needle, temp_degrees);
|
||||
|
||||
// Update label with precise value (with decimal)
|
||||
if (g_gearbox_oil_label != NULL)
|
||||
{
|
||||
char buf[16];
|
||||
snprintf(buf, sizeof(buf), "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
|
||||
lv_label_set_text(g_gearbox_oil_label, buf);
|
||||
}
|
||||
}
|
||||
|
||||
void meters_manager_cleanup(void)
|
||||
{
|
||||
g_coolant_meter = NULL;
|
||||
g_coolant_needle = NULL;
|
||||
g_coolant_label = NULL;
|
||||
g_engine_oil_meter = NULL;
|
||||
g_engine_oil_needle = NULL;
|
||||
g_engine_oil_label = NULL;
|
||||
g_gearbox_oil_meter = NULL;
|
||||
g_gearbox_oil_needle = NULL;
|
||||
g_gearbox_oil_label = NULL;
|
||||
ESP_LOGI("MetersMgr", "Meters cleaned up");
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Meters Manager Module
|
||||
*
|
||||
* Handles LVGL meter widgets for displaying automotive sensor data
|
||||
* Currently implements: Coolant Temperature gauge
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <lvgl.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Initialize the coolant temperature meter
|
||||
* @param container Parent container to add meter to (uic_Home_Loading_Container)
|
||||
* @param icon Optional icon to place inside the meter (can be NULL)
|
||||
* @note Creates coolant temperature meter widget with icon and label
|
||||
*/
|
||||
void meters_manager_init_coolant(lv_obj_t* container, lv_obj_t* icon);
|
||||
|
||||
/**
|
||||
* @brief Initialize the engine oil temperature meter
|
||||
* @param container Parent container to add meter to (uic_Home_Loading_Container)
|
||||
* @param icon Optional icon to place inside the meter (can be NULL)
|
||||
* @note Creates engine oil temperature meter widget with icon and label
|
||||
*/
|
||||
void meters_manager_init_engine_oil(lv_obj_t* container, lv_obj_t* icon);
|
||||
|
||||
/**
|
||||
* @brief Initialize the gearbox oil temperature meter
|
||||
* @param container Parent container to add meter to (uic_Home_Loading_Container)
|
||||
* @param icon Optional icon to place inside the meter (can be NULL)
|
||||
* @note Creates gearbox oil temperature meter widget with icon and label
|
||||
*/
|
||||
void meters_manager_init_gearbox_oil(lv_obj_t* container, lv_obj_t* icon);
|
||||
|
||||
/**
|
||||
* @brief Update coolant temperature meter value
|
||||
* @param temp_x10 Temperature in 0.1°C (e.g., 890 = 89.0°C)
|
||||
*/
|
||||
void meters_manager_update_coolant_temp(int16_t temp_x10);
|
||||
|
||||
/**
|
||||
* @brief Update engine oil temperature meter value
|
||||
* @param temp_x10 Temperature in 0.1°C (e.g., 920 = 92.0°C)
|
||||
*/
|
||||
void meters_manager_update_engine_oil_temp(int16_t temp_x10);
|
||||
|
||||
/**
|
||||
* @brief Update gearbox oil temperature meter value
|
||||
* @param temp_x10 Temperature in 0.1°C (e.g., 850 = 85.0°C)
|
||||
*/
|
||||
void meters_manager_update_gearbox_oil_temp(int16_t temp_x10);
|
||||
|
||||
/**
|
||||
* @brief Cleanup meters when screen is destroyed
|
||||
*/
|
||||
void meters_manager_cleanup(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Settings Manager Module Implementation
|
||||
*/
|
||||
|
||||
#include "settings_manager.h"
|
||||
#include <Preferences.h>
|
||||
|
||||
namespace SettingsManager {
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
static Preferences preferences; // NVS storage object
|
||||
|
||||
// NVS namespace and keys
|
||||
static const char* NVS_NAMESPACE = "settings";
|
||||
static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
|
||||
static const char* NVS_KEY_UART_ENABLED = "uart_en";
|
||||
static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
|
||||
static const char* NVS_KEY_CAN_ENABLED = "can_en";
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
void init() {
|
||||
// NVS initialization is handled automatically by ESP32 Preferences library
|
||||
Serial.println("[SettingsManager] Initialized");
|
||||
}
|
||||
|
||||
void saveWiFiState(bool enabled) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_WIFI_ENABLED, enabled);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved WiFi state = %s\n", enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
bool loadWiFiState() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool enabled = preferences.getBool(NVS_KEY_WIFI_ENABLED, false); // default: OFF
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Loaded WiFi state = %s\n", enabled ? "ON" : "OFF");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void saveUARTState(bool enabled) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_UART_ENABLED, enabled);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved UART state = %s\n", enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
bool loadUARTState() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool enabled = preferences.getBool(NVS_KEY_UART_ENABLED, false); // default: OFF
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Loaded UART state = %s\n", enabled ? "ON" : "OFF");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void saveDebugState(bool enabled) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_DEBUG_ENABLED, enabled);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved Debug state = %s\n", enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
bool loadDebugState() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool enabled = preferences.getBool(NVS_KEY_DEBUG_ENABLED, false); // default: OFF
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Loaded Debug state = %s\n", enabled ? "ON" : "OFF");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void saveCANState(bool enabled) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_CAN_ENABLED, enabled);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved CAN state = %s\n", enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
bool loadCANState() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool enabled = preferences.getBool(NVS_KEY_CAN_ENABLED, false); // default: OFF
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Loaded CAN state = %s\n", enabled ? "ON" : "OFF");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
} // namespace SettingsManager
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* Settings Manager Module
|
||||
*
|
||||
* Manages persistent storage of application settings using ESP32 NVS (Non-Volatile Storage).
|
||||
* Provides save/load functionality for WiFi and UART states.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace SettingsManager {
|
||||
|
||||
/**
|
||||
* @brief Initialize the settings manager
|
||||
*
|
||||
* Must be called once during system startup before any save/load operations.
|
||||
*/
|
||||
void init();
|
||||
|
||||
/**
|
||||
* @brief Save WiFi enabled state to NVS
|
||||
* @param enabled true if WiFi should be enabled, false otherwise
|
||||
*/
|
||||
void saveWiFiState(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Load WiFi enabled state from NVS
|
||||
* @return bool true if WiFi was enabled, false otherwise (default: false)
|
||||
*/
|
||||
bool loadWiFiState();
|
||||
|
||||
/**
|
||||
* @brief Save UART enabled state to NVS
|
||||
* @param enabled true if UART should be enabled, false otherwise
|
||||
*/
|
||||
void saveUARTState(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Load UART enabled state from NVS
|
||||
* @return bool true if UART was enabled, false otherwise (default: false)
|
||||
*/
|
||||
bool loadUARTState();
|
||||
|
||||
/**
|
||||
* @brief Save Debug mode enabled state to NVS
|
||||
* @param enabled true if Debug mode should be enabled, false otherwise
|
||||
*/
|
||||
void saveDebugState(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Load Debug mode enabled state from NVS
|
||||
* @return bool true if Debug mode was enabled, false otherwise (default: false)
|
||||
*/
|
||||
bool loadDebugState();
|
||||
|
||||
/**
|
||||
* @brief Save CAN Bus enabled state to NVS
|
||||
* @param enabled true if CAN Bus should be enabled, false otherwise
|
||||
*/
|
||||
void saveCANState(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Load CAN Bus enabled state from NVS
|
||||
* @return bool true if CAN Bus was enabled, false otherwise (default: false)
|
||||
*/
|
||||
bool loadCANState();
|
||||
|
||||
} // namespace SettingsManager
|
||||
@@ -0,0 +1,356 @@
|
||||
/*
|
||||
* UART Manager Module Implementation
|
||||
*/
|
||||
|
||||
#include "uart_manager.h"
|
||||
#include "settings_manager.h"
|
||||
|
||||
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)
|
||||
|
||||
// ============================================================================
|
||||
// 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)
|
||||
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};
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPER FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Initialize default automotive data values
|
||||
* @note Provides reasonable starting values until CAN bus updates them
|
||||
*/
|
||||
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.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;
|
||||
|
||||
// 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;
|
||||
|
||||
// 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
|
||||
*/
|
||||
static void updatePacketMetadata() {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
g_automotive_data.timestamp_ms = millis();
|
||||
g_automotive_data.packet_id = g_packet_id++;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Send automotive data packet over UART
|
||||
* @return true if successful, false on error
|
||||
*/
|
||||
static bool sendUARTPacket() {
|
||||
uart_packet_t packet;
|
||||
|
||||
// Get latest data with mutex protection
|
||||
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));
|
||||
|
||||
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;
|
||||
|
||||
// Send packet over UART1
|
||||
size_t bytes_written = Serial1.write((uint8_t*)&packet, sizeof(packet));
|
||||
|
||||
if (bytes_written == sizeof(packet)) {
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief UART task - Runs on Core 0
|
||||
* @param parameter Task parameter (unused)
|
||||
*/
|
||||
static void uartTask(void* parameter) {
|
||||
uart_queue_event_t event;
|
||||
bool transmitting = false;
|
||||
unsigned long last_transmit_time = 0;
|
||||
|
||||
ESP_LOGI("UARTTask", "UART task started on Core 0");
|
||||
|
||||
// Initialize UART1 hardware
|
||||
Serial1.setRxBufferSize(256); // Set receive buffer size BEFORE begin()
|
||||
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);
|
||||
|
||||
// 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:
|
||||
ESP_LOGI("UARTTask", "Starting transmission...");
|
||||
transmitting = true;
|
||||
g_uart_state = UART_STATE_TRANSMITTING;
|
||||
g_uart_stats.packets_sent = 0;
|
||||
g_uart_stats.send_errors = 0;
|
||||
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();
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
// Update packet metadata (CAN driver updates sensor values)
|
||||
updatePacketMetadata();
|
||||
|
||||
// Send packet
|
||||
if (!sendUARTPacket()) {
|
||||
// Handle send error
|
||||
if (g_uart_stats.send_errors > 10) {
|
||||
ESP_LOGE("UARTTask", "Too many send errors, entering error state");
|
||||
g_uart_state = UART_STATE_ERROR;
|
||||
transmitting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay to prevent task from hogging CPU
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
if (uart_task_created != pdPASS) {
|
||||
ESP_LOGE("UARTMgr", "ERROR: Failed to create UART task!");
|
||||
} else {
|
||||
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", "========================================");
|
||||
uart_queue_event_t evt;
|
||||
evt.type = UART_EVENT_START;
|
||||
evt.data = NULL;
|
||||
xQueueSend(g_uart_event_queue, &evt, 0);
|
||||
} else {
|
||||
ESP_LOGI("UARTMgr", "========================================");
|
||||
ESP_LOGI("UARTMgr", " UART INITIALLY DISABLED");
|
||||
ESP_LOGI("UARTMgr", " Enable via Settings screen toggle");
|
||||
ESP_LOGI("UARTMgr", "========================================");
|
||||
}
|
||||
}
|
||||
|
||||
uart_state_t getState() {
|
||||
return g_uart_state;
|
||||
}
|
||||
|
||||
uart_stats_t getStats() {
|
||||
return g_uart_stats;
|
||||
}
|
||||
|
||||
void setDebugEnabled(bool enabled) {
|
||||
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
g_automotive_data.debug_enabled = enabled ? 1 : 0;
|
||||
xSemaphoreGive(g_data_mutex);
|
||||
ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Controller B)",
|
||||
enabled ? "ENABLED" : "DISABLED");
|
||||
}
|
||||
}
|
||||
|
||||
void linkToCANState(bool can_active) {
|
||||
uart_queue_event_t evt;
|
||||
evt.type = can_active ? UART_EVENT_START : UART_EVENT_STOP;
|
||||
evt.data = NULL;
|
||||
|
||||
if (g_uart_event_queue != NULL) {
|
||||
if (xQueueSend(g_uart_event_queue, &evt, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
ESP_LOGI("UARTMgr", "UART %s (triggered by CAN state)", can_active ? "STARTED" : "STOPPED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS
|
||||
// ============================================================================
|
||||
|
||||
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!");
|
||||
}
|
||||
} else {
|
||||
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);
|
||||
ESP_LOGI("UARTMgr", " Send errors: %d", g_uart_stats.send_errors);
|
||||
ESP_LOGI("UARTMgr", " Last send time: %dms ago", millis() - g_uart_stats.last_send_time);
|
||||
}
|
||||
|
||||
ESP_LOGI("UARTMgr", "=============================");
|
||||
}
|
||||
|
||||
} // namespace UARTManager
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* UART Manager Module
|
||||
*
|
||||
* Handles UART communication for the Waveshare ESP32-S3-Touch-LCD-5B:
|
||||
* - Periodic automotive data transmission @ 5Hz
|
||||
* - FreeRTOS task on Core 0 for async UART operations
|
||||
* - Automotive data packet framing and checksums
|
||||
* - Default data initialization
|
||||
* - CAN bus integration - UART transmits only when CAN is active
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <lvgl.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <freertos/queue.h>
|
||||
#include "protocol/automotive_data.h"
|
||||
|
||||
namespace UARTManager {
|
||||
|
||||
// ============================================================================
|
||||
// CONFIGURATION
|
||||
// ============================================================================
|
||||
|
||||
#define UART_TASK_STACK_SIZE 4096
|
||||
#define UART_TASK_PRIORITY 1
|
||||
#define UART_TASK_CORE 0 // Run UART task on Core 0 (same as WiFi)
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC TYPES
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief UART state machine states
|
||||
*/
|
||||
typedef enum {
|
||||
UART_STATE_OFF = 0,
|
||||
UART_STATE_TRANSMITTING,
|
||||
UART_STATE_ERROR
|
||||
} uart_state_t;
|
||||
|
||||
/**
|
||||
* @brief UART event types for FreeRTOS queue
|
||||
*/
|
||||
typedef enum {
|
||||
UART_EVENT_START,
|
||||
UART_EVENT_STOP,
|
||||
UART_EVENT_SEND_DATA
|
||||
} uart_event_type_t;
|
||||
|
||||
/**
|
||||
* @brief UART queue event structure
|
||||
*/
|
||||
typedef struct {
|
||||
uart_event_type_t type;
|
||||
void* data;
|
||||
} uart_queue_event_t;
|
||||
|
||||
/**
|
||||
* @brief UART statistics structure
|
||||
*/
|
||||
typedef struct {
|
||||
uint32_t packets_sent;
|
||||
uint32_t send_errors;
|
||||
uint32_t last_send_time;
|
||||
} uart_stats_t;
|
||||
|
||||
// ============================================================================
|
||||
// SHARED DATA (Accessible by CAN driver)
|
||||
// ============================================================================
|
||||
|
||||
// External declarations for shared automotive data
|
||||
extern SemaphoreHandle_t g_data_mutex;
|
||||
extern automotive_data_t g_automotive_data;
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Initialize the UART manager subsystem
|
||||
*
|
||||
* This function:
|
||||
* - Creates FreeRTOS mutex and queue
|
||||
* - Spawns UART task on Core 0
|
||||
* - Optionally auto-starts UART based on saved state
|
||||
*
|
||||
* @param auto_start If true, automatically start UART based on NVS saved state
|
||||
*/
|
||||
void init(bool auto_start);
|
||||
|
||||
/**
|
||||
* @brief Get current UART state
|
||||
* @return Current uart_state_t value
|
||||
*/
|
||||
uart_state_t getState();
|
||||
|
||||
/**
|
||||
* @brief Get UART statistics
|
||||
* @return Current uart_stats_t structure
|
||||
*/
|
||||
uart_stats_t getStats();
|
||||
|
||||
/**
|
||||
* @brief Set debug mode flag in transmitted packets
|
||||
* @param enabled True to enable debug mode on receiver, false to disable
|
||||
*/
|
||||
void setDebugEnabled(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Link UART transmission state to CAN driver state
|
||||
* @param can_active True when CAN starts, false when CAN stops
|
||||
* @note Called by CAN driver to automatically start/stop UART
|
||||
*/
|
||||
void linkToCANState(bool can_active);
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS (Called from SquareLine Studio UI)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief UART toggle event handler
|
||||
* @param e LVGL event object
|
||||
* @note This function is registered in SquareLine Studio UI
|
||||
*/
|
||||
void onUARTToggle(lv_event_t *e);
|
||||
|
||||
} // namespace UARTManager
|
||||
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* UI State Manager Module Implementation
|
||||
*/
|
||||
|
||||
#include "ui_state_manager.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include "settings_manager.h"
|
||||
#include "wifi_manager.h"
|
||||
#include "uart_manager.h"
|
||||
#include "drivers/can_driver.h"
|
||||
|
||||
// External UI element references (from ui_Settings_Screen.c)
|
||||
extern "C" {
|
||||
extern lv_obj_t *uic_Main_Container;
|
||||
extern lv_obj_t *uic_Toggle_Wifi_Switch;
|
||||
extern lv_obj_t *uic_Toggle_UART_Switch;
|
||||
extern lv_obj_t *uic_Toggle_CAN_Bus_Switch;
|
||||
extern lv_obj_t *uic_Toggle_Debug_Switch;
|
||||
}
|
||||
|
||||
namespace UIStateManager {
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
// Track which screen instance we synced (to prevent redundant syncing)
|
||||
static lv_obj_t* g_last_synced_screen = NULL;
|
||||
|
||||
// Debug mode state
|
||||
static bool g_debug_enabled = false;
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
void init() {
|
||||
Serial.println("[UIStateManager] Initialized");
|
||||
g_last_synced_screen = NULL;
|
||||
g_debug_enabled = false;
|
||||
}
|
||||
|
||||
void applySavedStatesToUI() {
|
||||
// Wait for UI widgets to be created
|
||||
if (uic_Toggle_Wifi_Switch == NULL || uic_Toggle_UART_Switch == NULL || uic_Toggle_CAN_Bus_Switch == NULL) {
|
||||
// Reset last synced screen when widgets are NULL (screen unloaded)
|
||||
g_last_synced_screen = NULL;
|
||||
return; // Settings screen not loaded yet
|
||||
}
|
||||
|
||||
if (uic_Main_Container == NULL) {
|
||||
return; // UI not ready
|
||||
}
|
||||
|
||||
// Get the Settings screen pointer (parent of Main Container)
|
||||
lv_obj_t* settings_screen = lv_obj_get_parent(uic_Main_Container);
|
||||
if (settings_screen == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we've already synced this screen instance
|
||||
if (g_last_synced_screen == settings_screen) {
|
||||
return; // Already synced this instance
|
||||
}
|
||||
|
||||
Serial.println("Settings screen detected - syncing toggle states with services...");
|
||||
|
||||
// Sync UI with the actual running state of services
|
||||
bool current_wifi_state = WiFiManager::getState() != WiFiManager::WIFI_STATE_OFF;
|
||||
bool current_uart_state = UARTManager::getState() != UARTManager::UART_STATE_OFF;
|
||||
bool current_can_state = CANDriver::isActive();
|
||||
bool current_debug_state = g_debug_enabled;
|
||||
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
// Apply WiFi state
|
||||
if (current_wifi_state) {
|
||||
lv_obj_add_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
|
||||
} else {
|
||||
lv_obj_clear_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
|
||||
}
|
||||
|
||||
// Apply UART state
|
||||
if (current_uart_state) {
|
||||
lv_obj_add_state(uic_Toggle_UART_Switch, LV_STATE_CHECKED);
|
||||
} else {
|
||||
lv_obj_clear_state(uic_Toggle_UART_Switch, LV_STATE_CHECKED);
|
||||
}
|
||||
|
||||
// Apply CAN Bus state
|
||||
if (current_can_state) {
|
||||
lv_obj_add_state(uic_Toggle_CAN_Bus_Switch, LV_STATE_CHECKED);
|
||||
} else {
|
||||
lv_obj_clear_state(uic_Toggle_CAN_Bus_Switch, LV_STATE_CHECKED);
|
||||
}
|
||||
|
||||
// Apply Debug state
|
||||
if (uic_Toggle_Debug_Switch != NULL) {
|
||||
if (current_debug_state) {
|
||||
lv_obj_add_state(uic_Toggle_Debug_Switch, LV_STATE_CHECKED);
|
||||
} else {
|
||||
lv_obj_clear_state(uic_Toggle_Debug_Switch, LV_STATE_CHECKED);
|
||||
}
|
||||
}
|
||||
|
||||
lvgl_port_unlock();
|
||||
|
||||
// Mark this screen instance as synced
|
||||
g_last_synced_screen = settings_screen;
|
||||
|
||||
Serial.printf("Toggle states synced: WiFi=%s, UART=%s, CAN=%s, Debug=%s\n",
|
||||
current_wifi_state ? "ON" : "OFF",
|
||||
current_uart_state ? "ON" : "OFF",
|
||||
current_can_state ? "ON" : "OFF",
|
||||
current_debug_state ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
void setDebugEnabled(bool enabled) {
|
||||
g_debug_enabled = enabled;
|
||||
|
||||
Serial.printf("[UIStateManager] Debug mode %s\n", enabled ? "ENABLED" : "DISABLED");
|
||||
|
||||
// Notify UART manager to include debug flag in transmitted packets
|
||||
UARTManager::setDebugEnabled(enabled);
|
||||
|
||||
lvgl_port_lock(-1);
|
||||
|
||||
#if LV_USE_PERF_MONITOR
|
||||
// Enable/disable LVGL performance monitor (FPS, CPU)
|
||||
lv_obj_t* perf_monitor = lv_disp_get_layer_sys(NULL);
|
||||
if (perf_monitor) {
|
||||
if (enabled) {
|
||||
lv_obj_clear_flag(perf_monitor, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag(perf_monitor, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if LV_USE_MEM_MONITOR
|
||||
// Enable/disable LVGL memory monitor
|
||||
// Note: Memory monitor visibility is controlled by the same mechanism
|
||||
#endif
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
bool isDebugEnabled() {
|
||||
return g_debug_enabled;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS
|
||||
// ============================================================================
|
||||
|
||||
void onDebugToggle(lv_event_t *e)
|
||||
{
|
||||
lv_obj_t *target = lv_event_get_target(e);
|
||||
|
||||
if (target == NULL) {
|
||||
Serial.println("ERROR: Debug toggle target is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
||||
|
||||
Serial.printf("===== Debug Toggle Event =====\n");
|
||||
Serial.printf("Debug Mode: %s\n", state ? "ON" : "OFF");
|
||||
|
||||
// Save state to NVS
|
||||
SettingsManager::saveDebugState(state);
|
||||
|
||||
// Update global state and enable/disable monitors
|
||||
setDebugEnabled(state);
|
||||
|
||||
Serial.printf("==============================\n");
|
||||
}
|
||||
|
||||
} // namespace UIStateManager
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* UI State Manager Module
|
||||
*
|
||||
* Handles UI state synchronization:
|
||||
* - Syncs toggle switches with actual service states when screens change
|
||||
* - Handles SquareLine Studio screen lifecycle (destroy/recreate)
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <lvgl.h>
|
||||
|
||||
namespace UIStateManager {
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Initialize the UI State Manager
|
||||
*
|
||||
* This function:
|
||||
* - Initializes internal state tracking variables
|
||||
*/
|
||||
void init();
|
||||
|
||||
/**
|
||||
* @brief Apply saved states to UI switches
|
||||
*
|
||||
* This function is called continuously in loop() to sync UI toggle switches
|
||||
* with the actual running state of services when the Settings screen loads.
|
||||
* It handles the SquareLine Studio screen lifecycle where screens get
|
||||
* destroyed/recreated when swiping between screens.
|
||||
*
|
||||
* @note This function is thread-safe and uses LVGL locks internally
|
||||
*/
|
||||
void applySavedStatesToUI();
|
||||
|
||||
/**
|
||||
* @brief Enable or disable debug mode (LVGL performance and memory monitors)
|
||||
* @param enabled True to enable debug monitors, false to disable
|
||||
*/
|
||||
void setDebugEnabled(bool enabled);
|
||||
|
||||
/**
|
||||
* @brief Get current debug mode state
|
||||
* @return True if debug mode is enabled, false otherwise
|
||||
*/
|
||||
bool isDebugEnabled();
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS (Called from SquareLine Studio UI)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Debug toggle event handler
|
||||
* @param e LVGL event object
|
||||
* @note This function is registered in SquareLine Studio UI
|
||||
*/
|
||||
void onDebugToggle(lv_event_t *e);
|
||||
|
||||
} // namespace UIStateManager
|
||||
@@ -0,0 +1,759 @@
|
||||
/*
|
||||
* WiFi Manager Module Implementation
|
||||
*/
|
||||
|
||||
#include "wifi_manager.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
|
||||
// External UI element references (from ui_Settings_Screen.c)
|
||||
// MUST be declared outside the namespace to match the global C symbols
|
||||
extern "C" {
|
||||
extern lv_obj_t *uic_Select_SSID_BTN;
|
||||
extern lv_obj_t *uic_Settings_Loading_Container;
|
||||
extern lv_obj_t *uic_Wifi_Container;
|
||||
extern lv_obj_t *uic_Toggle_Wifi_Switch;
|
||||
extern lv_obj_t *uic_Wifi_Passkey_TB;
|
||||
extern lv_obj_t *uic_Keyboard;
|
||||
}
|
||||
|
||||
namespace WiFiManager {
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
// Global WiFi state variables
|
||||
static wifi_state_t g_wifi_state = WIFI_STATE_OFF;
|
||||
static TaskHandle_t g_wifi_task_handle = NULL;
|
||||
static QueueHandle_t g_wifi_event_queue = NULL;
|
||||
static SemaphoreHandle_t g_wifi_mutex = NULL;
|
||||
static wifi_network_t g_scanned_networks[WIFI_SCAN_MAX_NETWORKS];
|
||||
static uint8_t g_network_count = 0;
|
||||
static bool g_wifi_scan_requested = false;
|
||||
static unsigned long g_last_scan_time = 0;
|
||||
|
||||
// Currently selected network for connection
|
||||
static int8_t g_selected_network_index = -1;
|
||||
|
||||
// Dynamic SSID buttons
|
||||
static lv_obj_t* g_ssid_buttons[WIFI_SCAN_MAX_NETWORKS] = {NULL};
|
||||
static uint8_t g_button_count = 0;
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPER FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Get WiFi encryption type as string
|
||||
*/
|
||||
static const char* getAuthModeString(wifi_auth_mode_t authmode) {
|
||||
switch (authmode) {
|
||||
case WIFI_AUTH_OPEN: return "Open";
|
||||
case WIFI_AUTH_WEP: return "WEP";
|
||||
case WIFI_AUTH_WPA_PSK: return "WPA";
|
||||
case WIFI_AUTH_WPA2_PSK: return "WPA2";
|
||||
case WIFI_AUTH_WPA_WPA2_PSK: return "WPA/WPA2";
|
||||
case WIFI_AUTH_WPA2_ENTERPRISE: return "WPA2-Ent";
|
||||
case WIFI_AUTH_WPA3_PSK: return "WPA3";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get signal strength indicator
|
||||
*/
|
||||
static const char* getSignalStrength(int32_t rssi) {
|
||||
if (rssi > -50) return "[****]"; // Excellent
|
||||
else if (rssi > -60) return "[*** ]"; // Good
|
||||
else if (rssi > -70) return "[** ]"; // Fair
|
||||
else if (rssi > -80) return "[* ]"; // Weak
|
||||
else return "[ ]"; // Very weak
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Format network name for display in button
|
||||
*/
|
||||
static String formatNetworkName(const wifi_network_t& network) {
|
||||
String formatted = getSignalStrength(network.rssi);
|
||||
formatted += " ";
|
||||
formatted += network.ssid;
|
||||
if (network.ssid.length() == 0) {
|
||||
formatted += "[Hidden]";
|
||||
}
|
||||
if (network.auth != WIFI_AUTH_OPEN) {
|
||||
formatted += " [Secured]"; // Text indicator for secured networks
|
||||
}
|
||||
return formatted;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Show connection result to user
|
||||
* @note Must be called with LVGL lock held OR will acquire lock internally
|
||||
*/
|
||||
static void showConnectionResult(bool success, const char* message) {
|
||||
lvgl_port_lock(0);
|
||||
|
||||
// Hide loading spinner
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
if (success) {
|
||||
// Connection successful
|
||||
Serial.printf("WiFi connected: %s\n", message);
|
||||
|
||||
// Update the roller to show connected status
|
||||
if (g_selected_network_index >= 0 && g_selected_network_index < g_network_count) {
|
||||
String connected_text = "[CONNECTED] ";
|
||||
connected_text += g_scanned_networks[g_selected_network_index].ssid;
|
||||
|
||||
// Update just the selected item in the roller
|
||||
// Note: This is a simplified approach - in production, you'd want to
|
||||
// rebuild the entire roller list with the connected indicator
|
||||
}
|
||||
|
||||
// Optionally show a success message label temporarily
|
||||
// You could create a temporary label here if needed
|
||||
|
||||
} else {
|
||||
// Connection failed - show error and return to SSID buttons
|
||||
Serial.printf("WiFi connection failed: %s\n", message);
|
||||
|
||||
// Show SSID buttons again
|
||||
for (uint8_t i = 0; i < g_button_count; i++) {
|
||||
if (g_ssid_buttons[i] != NULL) {
|
||||
lv_obj_clear_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
// Optionally show an error message label temporarily
|
||||
// You could create a temporary label here to show the error
|
||||
}
|
||||
|
||||
// Reset selected network index
|
||||
g_selected_network_index = -1;
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Reset WiFi UI to initial state (showing SSID list)
|
||||
*/
|
||||
static void resetWiFiUI() {
|
||||
lvgl_port_lock(0);
|
||||
|
||||
// Hide all password entry elements
|
||||
lv_obj_add_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
// Clear password field for security
|
||||
lv_textarea_set_text(uic_Wifi_Passkey_TB, "");
|
||||
|
||||
// Show SSID buttons
|
||||
for (uint8_t i = 0; i < g_button_count; i++) {
|
||||
if (g_ssid_buttons[i] != NULL) {
|
||||
lv_obj_clear_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
// Reset selected network
|
||||
g_selected_network_index = -1;
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Update WiFi UI state based on state machine
|
||||
* @note This function MUST be called with lvgl_port_lock held
|
||||
*/
|
||||
static void updateWifiUIState(wifi_state_t state) {
|
||||
// This function MUST be called with lvgl_port_lock held
|
||||
|
||||
if (!uic_Select_SSID_BTN || !uic_Settings_Loading_Container || !uic_Wifi_Container) {
|
||||
Serial.println("WARNING: UI elements not initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (state) {
|
||||
case WIFI_STATE_OFF:
|
||||
// Hide WiFi container and spinner
|
||||
lv_obj_add_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN);
|
||||
break;
|
||||
|
||||
case WIFI_STATE_SCANNING:
|
||||
// Show container and spinner, hide button
|
||||
lv_obj_clear_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN);
|
||||
break;
|
||||
|
||||
case WIFI_STATE_SCAN_COMPLETE:
|
||||
// Show button, hide spinner
|
||||
lv_obj_clear_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_clear_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN);
|
||||
break;
|
||||
|
||||
case WIFI_STATE_ERROR:
|
||||
// Show error state (container visible but no spinner or button)
|
||||
lv_obj_clear_flag(uic_Wifi_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Update SSID list with dynamic buttons
|
||||
* @note This function MUST be called with lvgl_port_lock held
|
||||
*/
|
||||
static void updateSSIDList() {
|
||||
// This function MUST be called with lvgl_port_lock held
|
||||
|
||||
if (!uic_Wifi_Container) {
|
||||
Serial.println("ERROR: uic_Wifi_Container is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Clean up old buttons
|
||||
for (uint8_t i = 0; i < g_button_count; i++) {
|
||||
if (g_ssid_buttons[i] != NULL) {
|
||||
lv_obj_del(g_ssid_buttons[i]);
|
||||
g_ssid_buttons[i] = NULL;
|
||||
}
|
||||
}
|
||||
g_button_count = 0;
|
||||
|
||||
if (g_network_count == 0) {
|
||||
Serial.println("No WiFi networks found");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.printf("Creating %d SSID buttons:\n", g_network_count);
|
||||
|
||||
// Create a button for each scanned network
|
||||
for (uint8_t i = 0; i < g_network_count; i++) {
|
||||
// Create button in the WiFi container
|
||||
lv_obj_t* btn = lv_btn_create(uic_Wifi_Container);
|
||||
lv_obj_set_width(btn, 600); // Adjust width as needed
|
||||
lv_obj_set_height(btn, 60); // Adjust height as needed
|
||||
|
||||
// Create label for the button text
|
||||
lv_obj_t* label = lv_label_create(btn);
|
||||
String btnText = formatNetworkName(g_scanned_networks[i]);
|
||||
lv_label_set_text(label, btnText.c_str());
|
||||
lv_obj_center(label);
|
||||
|
||||
// Store network index as user data
|
||||
lv_obj_set_user_data(btn, (void*)(intptr_t)i);
|
||||
|
||||
// Add click event handler
|
||||
lv_obj_add_event_cb(btn, onSSIDButtonClick, LV_EVENT_CLICKED, NULL);
|
||||
|
||||
// Store button reference
|
||||
g_ssid_buttons[i] = btn;
|
||||
g_button_count++;
|
||||
|
||||
Serial.printf(" [%d] Created button for: %s\n", i, g_scanned_networks[i].ssid.c_str());
|
||||
}
|
||||
|
||||
Serial.printf("Successfully created %d SSID buttons\n", g_button_count);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Initiate WiFi connection to selected network
|
||||
*/
|
||||
static void connectToWiFi(const char* ssid, const char* password) {
|
||||
if (ssid == NULL) return;
|
||||
|
||||
// Allocate credentials structure
|
||||
wifi_credentials_t* creds = (wifi_credentials_t*)malloc(sizeof(wifi_credentials_t));
|
||||
if (creds == NULL) {
|
||||
Serial.println("ERROR: Failed to allocate memory for WiFi credentials!");
|
||||
showConnectionResult(false, "Memory allocation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy credentials
|
||||
strncpy(creds->ssid, ssid, sizeof(creds->ssid) - 1);
|
||||
creds->ssid[sizeof(creds->ssid) - 1] = '\0';
|
||||
|
||||
if (password != NULL) {
|
||||
strncpy(creds->password, password, sizeof(creds->password) - 1);
|
||||
creds->password[sizeof(creds->password) - 1] = '\0';
|
||||
} else {
|
||||
creds->password[0] = '\0'; // Empty password for open networks
|
||||
}
|
||||
|
||||
// Send connect event to WiFi task
|
||||
wifi_queue_event_t evt;
|
||||
evt.type = WIFI_UI_EVENT_CONNECT;
|
||||
evt.data = creds; // WiFi task will free this memory
|
||||
|
||||
if (g_wifi_event_queue != NULL) {
|
||||
if (xQueueSend(g_wifi_event_queue, &evt, pdMS_TO_TICKS(100)) != pdTRUE) {
|
||||
Serial.println("ERROR: Failed to send connect event to WiFi task!");
|
||||
free(creds);
|
||||
showConnectionResult(false, "Failed to initiate connection");
|
||||
}
|
||||
} else {
|
||||
Serial.println("ERROR: WiFi event queue not initialized!");
|
||||
free(creds);
|
||||
showConnectionResult(false, "System not ready");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief WiFi task - Runs on Core 0
|
||||
* @param parameter Task parameter (unused)
|
||||
*/
|
||||
static void wifiTask(void* parameter) {
|
||||
wifi_queue_event_t event;
|
||||
bool scanning = false;
|
||||
|
||||
Serial.println("WiFi task started on Core 0");
|
||||
|
||||
while (true) {
|
||||
// Check for events from the queue (non-blocking with timeout)
|
||||
if (xQueueReceive(g_wifi_event_queue, &event, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
switch (event.type) {
|
||||
case WIFI_UI_EVENT_TOGGLE_ON:
|
||||
Serial.println("WiFi Task: Enabling WiFi...");
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.disconnect(); // Clear any previous connection
|
||||
g_wifi_state = WIFI_STATE_SCANNING;
|
||||
g_wifi_scan_requested = true;
|
||||
break;
|
||||
|
||||
case WIFI_UI_EVENT_TOGGLE_OFF:
|
||||
Serial.println("WiFi Task: Disabling WiFi...");
|
||||
WiFi.disconnect(true);
|
||||
WiFi.mode(WIFI_OFF);
|
||||
g_wifi_state = WIFI_STATE_OFF;
|
||||
g_network_count = 0;
|
||||
scanning = false;
|
||||
break;
|
||||
|
||||
case WIFI_UI_EVENT_SCAN_START:
|
||||
if (g_wifi_state != WIFI_STATE_OFF && !scanning) {
|
||||
g_wifi_scan_requested = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case WIFI_UI_EVENT_CONNECT:
|
||||
if (event.data != NULL) {
|
||||
wifi_credentials_t* creds = (wifi_credentials_t*)event.data;
|
||||
Serial.printf("WiFi Task: Connecting to %s...\n", creds->ssid);
|
||||
|
||||
// Stop any ongoing scan
|
||||
WiFi.scanDelete();
|
||||
scanning = false;
|
||||
|
||||
// Update state
|
||||
g_wifi_state = WIFI_STATE_CONNECTED; // Will be updated based on result
|
||||
|
||||
// Attempt connection
|
||||
WiFi.disconnect(true); // Clear any previous connection
|
||||
delay(100);
|
||||
|
||||
if (strlen(creds->password) > 0) {
|
||||
WiFi.begin(creds->ssid, creds->password);
|
||||
} else {
|
||||
WiFi.begin(creds->ssid); // Open network
|
||||
}
|
||||
|
||||
// Wait for connection (with timeout)
|
||||
int timeout = 20; // 10 seconds timeout
|
||||
while (WiFi.status() != WL_CONNECTED && timeout > 0) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
timeout--;
|
||||
}
|
||||
Serial.println();
|
||||
|
||||
// Check connection result
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.printf("Connected! IP: %s\n", WiFi.localIP().toString().c_str());
|
||||
showConnectionResult(true, WiFi.localIP().toString().c_str());
|
||||
g_wifi_state = WIFI_STATE_CONNECTED;
|
||||
} else {
|
||||
Serial.println("Connection failed!");
|
||||
const char* error_msg = "Connection timeout";
|
||||
if (WiFi.status() == WL_CONNECT_FAILED) {
|
||||
error_msg = "Wrong password";
|
||||
} else if (WiFi.status() == WL_NO_SSID_AVAIL) {
|
||||
error_msg = "Network not found";
|
||||
}
|
||||
showConnectionResult(false, error_msg);
|
||||
g_wifi_state = WIFI_STATE_SCANNING;
|
||||
g_wifi_scan_requested = true; // Resume scanning
|
||||
}
|
||||
|
||||
// Free the credentials memory
|
||||
free(creds);
|
||||
}
|
||||
break;
|
||||
|
||||
case WIFI_UI_EVENT_DISCONNECT:
|
||||
Serial.println("WiFi Task: Disconnecting...");
|
||||
WiFi.disconnect(true);
|
||||
g_wifi_state = WIFI_STATE_SCANNING;
|
||||
g_wifi_scan_requested = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle WiFi scanning
|
||||
if (g_wifi_state != WIFI_STATE_OFF) {
|
||||
unsigned long current_time = millis();
|
||||
|
||||
// Start scan if requested or periodic scan is due
|
||||
if (g_wifi_scan_requested ||
|
||||
(current_time - g_last_scan_time > WIFI_SCAN_INTERVAL_MS && !scanning)) {
|
||||
|
||||
Serial.println("Starting WiFi scan...");
|
||||
scanning = true;
|
||||
g_wifi_scan_requested = false;
|
||||
g_last_scan_time = current_time;
|
||||
|
||||
// Start async scan
|
||||
WiFi.scanNetworks(true, false); // async=true, show_hidden=false
|
||||
|
||||
// Only show spinner if list is empty (first scan or after error)
|
||||
// For periodic rescans, keep the existing list visible
|
||||
if (g_network_count == 0) {
|
||||
lvgl_port_lock(-1);
|
||||
updateWifiUIState(WIFI_STATE_SCANNING);
|
||||
lvgl_port_unlock();
|
||||
Serial.println("Showing loading spinner (list is empty)");
|
||||
} else {
|
||||
Serial.println("Background rescan (keeping list visible)");
|
||||
}
|
||||
}
|
||||
|
||||
// Check if scan is complete
|
||||
if (scanning) {
|
||||
int16_t result = WiFi.scanComplete();
|
||||
|
||||
if (result >= 0) {
|
||||
// Scan completed successfully
|
||||
scanning = false;
|
||||
Serial.printf("WiFi scan complete: %d networks found\n", result);
|
||||
|
||||
// Lock mutex to update shared data
|
||||
if (xSemaphoreTake(g_wifi_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
g_network_count = min((int)result, WIFI_SCAN_MAX_NETWORKS);
|
||||
|
||||
// Copy scan results to our buffer
|
||||
for (uint8_t i = 0; i < g_network_count; i++) {
|
||||
g_scanned_networks[i].ssid = WiFi.SSID(i);
|
||||
g_scanned_networks[i].rssi = WiFi.RSSI(i);
|
||||
g_scanned_networks[i].auth = WiFi.encryptionType(i);
|
||||
|
||||
Serial.printf(" [%d] %s (RSSI: %d, Auth: %s)\n",
|
||||
i,
|
||||
g_scanned_networks[i].ssid.c_str(),
|
||||
g_scanned_networks[i].rssi,
|
||||
getAuthModeString(g_scanned_networks[i].auth));
|
||||
}
|
||||
|
||||
xSemaphoreGive(g_wifi_mutex);
|
||||
|
||||
// Update UI with scan results
|
||||
g_wifi_state = WIFI_STATE_SCAN_COMPLETE;
|
||||
lvgl_port_lock(-1);
|
||||
updateSSIDList();
|
||||
updateWifiUIState(WIFI_STATE_SCAN_COMPLETE);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
// Delete scan results to free memory
|
||||
WiFi.scanDelete();
|
||||
|
||||
} else if (result == WIFI_SCAN_FAILED) {
|
||||
// Scan failed
|
||||
scanning = false;
|
||||
Serial.println("WiFi scan failed!");
|
||||
g_wifi_state = WIFI_STATE_ERROR;
|
||||
|
||||
lvgl_port_lock(-1);
|
||||
updateWifiUIState(WIFI_STATE_ERROR);
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
// If result == WIFI_SCAN_RUNNING, scan is still in progress
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay to prevent task from hogging CPU
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
// ============================================================================
|
||||
|
||||
void init(bool auto_start) {
|
||||
Serial.println("[WiFiManager] Initializing WiFi subsystem...");
|
||||
|
||||
// Create mutex for protecting shared WiFi data
|
||||
g_wifi_mutex = xSemaphoreCreateMutex();
|
||||
if (g_wifi_mutex == NULL) {
|
||||
Serial.println("[WiFiManager] ERROR: Failed to create WiFi mutex!");
|
||||
}
|
||||
|
||||
// Create event queue for WiFi task communication
|
||||
g_wifi_event_queue = xQueueCreate(10, sizeof(wifi_queue_event_t));
|
||||
if (g_wifi_event_queue == NULL) {
|
||||
Serial.println("[WiFiManager] ERROR: Failed to create WiFi event queue!");
|
||||
}
|
||||
|
||||
// Create WiFi task on Core 0
|
||||
BaseType_t task_created = xTaskCreatePinnedToCore(
|
||||
wifiTask, // Task function
|
||||
"WiFi_Task", // Task name
|
||||
WIFI_TASK_STACK_SIZE, // Stack size
|
||||
NULL, // Parameters
|
||||
WIFI_TASK_PRIORITY, // Priority (1)
|
||||
&g_wifi_task_handle, // Task handle
|
||||
WIFI_TASK_CORE // Core 0
|
||||
);
|
||||
|
||||
if (task_created != pdPASS) {
|
||||
Serial.println("[WiFiManager] ERROR: Failed to create WiFi task!");
|
||||
} else {
|
||||
Serial.println("[WiFiManager] WiFi task created successfully on Core 0");
|
||||
}
|
||||
|
||||
// Auto-start WiFi if requested
|
||||
if (auto_start) {
|
||||
Serial.println("[WiFiManager] Auto-starting WiFi...");
|
||||
wifi_queue_event_t evt;
|
||||
evt.type = WIFI_UI_EVENT_TOGGLE_ON;
|
||||
evt.data = NULL;
|
||||
xQueueSend(g_wifi_event_queue, &evt, 0);
|
||||
} else {
|
||||
WiFi.mode(WIFI_OFF);
|
||||
Serial.println("[WiFiManager] WiFi initially disabled");
|
||||
}
|
||||
}
|
||||
|
||||
wifi_state_t getState() {
|
||||
return g_wifi_state;
|
||||
}
|
||||
|
||||
uint8_t getNetworkCount() {
|
||||
return g_network_count;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS
|
||||
// ============================================================================
|
||||
|
||||
void onWifiToggle(lv_event_t *e)
|
||||
{
|
||||
// Get the actual widget from the event (safer than global variable)
|
||||
lv_obj_t *target = lv_event_get_target(e);
|
||||
|
||||
// Verify the widget is valid
|
||||
if (target == NULL) {
|
||||
Serial.println("ERROR: WiFi toggle target is NULL!");
|
||||
Serial.flush();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the toggle state
|
||||
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
||||
|
||||
Serial.printf("WiFi Toggle RELEASED - State: %s\n", state ? "ON" : "OFF");
|
||||
Serial.flush();
|
||||
|
||||
// Send event to WiFi task via queue
|
||||
wifi_queue_event_t evt;
|
||||
if (state) {
|
||||
evt.type = WIFI_UI_EVENT_TOGGLE_ON;
|
||||
|
||||
// Show loading state immediately
|
||||
updateWifiUIState(WIFI_STATE_SCANNING);
|
||||
} else {
|
||||
evt.type = WIFI_UI_EVENT_TOGGLE_OFF;
|
||||
|
||||
// Hide WiFi UI immediately
|
||||
updateWifiUIState(WIFI_STATE_OFF);
|
||||
}
|
||||
evt.data = NULL;
|
||||
|
||||
// Send event to WiFi task (non-blocking)
|
||||
if (g_wifi_event_queue != NULL) {
|
||||
xQueueSend(g_wifi_event_queue, &evt, 0);
|
||||
} else {
|
||||
Serial.println("ERROR: WiFi event queue not initialized!");
|
||||
}
|
||||
}
|
||||
|
||||
void onSSIDButtonClick(lv_event_t *e) {
|
||||
lv_obj_t* btn = lv_event_get_target(e);
|
||||
if (btn == NULL) {
|
||||
Serial.println("ERROR: Button target is NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the network index from user data
|
||||
int8_t network_idx = (int8_t)(intptr_t)lv_obj_get_user_data(btn);
|
||||
|
||||
if (network_idx < 0 || network_idx >= g_network_count) {
|
||||
Serial.printf("ERROR: Invalid network index: %d\n", network_idx);
|
||||
return;
|
||||
}
|
||||
|
||||
g_selected_network_index = network_idx;
|
||||
Serial.printf("===== SSID Button Clicked: %s =====\n",
|
||||
g_scanned_networks[network_idx].ssid.c_str());
|
||||
|
||||
// Verify UI widgets exist
|
||||
if (uic_Wifi_Passkey_TB == NULL || uic_Keyboard == NULL) {
|
||||
Serial.println("ERROR: Password UI widgets are NULL!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get LVGL lock to update UI
|
||||
lvgl_port_lock(0);
|
||||
|
||||
// Hide all SSID buttons
|
||||
for (uint8_t i = 0; i < g_button_count; i++) {
|
||||
if (g_ssid_buttons[i] != NULL) {
|
||||
lv_obj_add_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if network requires password
|
||||
if (g_scanned_networks[network_idx].auth == WIFI_AUTH_OPEN) {
|
||||
// Open network - connect directly without password
|
||||
Serial.println("Open network - connecting without password...");
|
||||
|
||||
// Show loading spinner
|
||||
lv_obj_clear_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
lvgl_port_unlock();
|
||||
|
||||
// Connect to open network
|
||||
connectToWiFi(g_scanned_networks[network_idx].ssid.c_str(), NULL);
|
||||
|
||||
} else {
|
||||
// Secured network - show password entry
|
||||
Serial.println("Secured network - showing password entry UI...");
|
||||
|
||||
// Configure and show password textbox
|
||||
lv_textarea_set_text(uic_Wifi_Passkey_TB, "");
|
||||
lv_textarea_set_placeholder_text(uic_Wifi_Passkey_TB,
|
||||
g_scanned_networks[network_idx].ssid.c_str());
|
||||
lv_textarea_set_password_mode(uic_Wifi_Passkey_TB, true);
|
||||
lv_textarea_set_one_line(uic_Wifi_Passkey_TB, true);
|
||||
lv_obj_clear_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
// Configure and show keyboard
|
||||
lv_keyboard_set_textarea(uic_Keyboard, uic_Wifi_Passkey_TB);
|
||||
lv_keyboard_set_mode(uic_Keyboard, LV_KEYBOARD_MODE_TEXT_LOWER);
|
||||
lv_obj_clear_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
// Add event handler for keyboard (if not already added)
|
||||
static bool keyboard_handler_added = false;
|
||||
if (!keyboard_handler_added) {
|
||||
lv_obj_add_event_cb(uic_Keyboard, onKeyboardEvent, LV_EVENT_ALL, NULL);
|
||||
keyboard_handler_added = true;
|
||||
Serial.println("Keyboard event handler registered");
|
||||
}
|
||||
|
||||
lvgl_port_unlock();
|
||||
|
||||
Serial.println("Password entry UI shown successfully");
|
||||
}
|
||||
}
|
||||
|
||||
void onKeyboardEvent(lv_event_t *e) {
|
||||
lv_event_code_t code = lv_event_get_code(e);
|
||||
lv_obj_t *keyboard = lv_event_get_target(e);
|
||||
|
||||
if (code == LV_EVENT_READY || code == LV_EVENT_CANCEL) {
|
||||
// Get LVGL lock for UI updates
|
||||
lvgl_port_lock(0);
|
||||
|
||||
if (code == LV_EVENT_READY) {
|
||||
// User pressed checkmark/enter - attempt connection
|
||||
const char *password = lv_textarea_get_text(uic_Wifi_Passkey_TB);
|
||||
|
||||
if (xSemaphoreTake(g_wifi_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
if (g_selected_network_index >= 0 && g_selected_network_index < g_network_count) {
|
||||
Serial.printf("Connecting to: %s with password: %s\n",
|
||||
g_scanned_networks[g_selected_network_index].ssid.c_str(),
|
||||
password);
|
||||
|
||||
// Hide keyboard and password field
|
||||
lv_obj_add_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
// Show loading spinner
|
||||
lv_obj_clear_flag(uic_Settings_Loading_Container, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
// Trigger WiFi connection
|
||||
connectToWiFi(g_scanned_networks[g_selected_network_index].ssid.c_str(), password);
|
||||
|
||||
// Clear sensitive password data from text area
|
||||
lv_textarea_set_text(uic_Wifi_Passkey_TB, "");
|
||||
}
|
||||
xSemaphoreGive(g_wifi_mutex);
|
||||
}
|
||||
|
||||
} else if (code == LV_EVENT_CANCEL) {
|
||||
// User pressed X/cancel - go back to SSID list
|
||||
Serial.println("Password entry cancelled - returning to SSID list");
|
||||
|
||||
// Hide keyboard and password field
|
||||
lv_obj_add_flag(uic_Keyboard, LV_OBJ_FLAG_HIDDEN);
|
||||
lv_obj_add_flag(uic_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN);
|
||||
|
||||
// Clear password field for security
|
||||
lv_textarea_set_text(uic_Wifi_Passkey_TB, "");
|
||||
|
||||
// Show SSID buttons again
|
||||
for (uint8_t i = 0; i < g_button_count; i++) {
|
||||
if (g_ssid_buttons[i] != NULL) {
|
||||
lv_obj_clear_flag(g_ssid_buttons[i], LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
// Reset selected network index
|
||||
g_selected_network_index = -1;
|
||||
}
|
||||
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
}
|
||||
|
||||
void onRescanRequest(lv_event_t *e) {
|
||||
if (g_wifi_state != WIFI_STATE_OFF) {
|
||||
Serial.println("Manual rescan requested");
|
||||
|
||||
wifi_queue_event_t evt;
|
||||
evt.type = WIFI_UI_EVENT_SCAN_START;
|
||||
evt.data = NULL;
|
||||
|
||||
if (g_wifi_event_queue != NULL) {
|
||||
xQueueSend(g_wifi_event_queue, &evt, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void onSelectSSID(lv_event_t *e) {
|
||||
// This function is called from SquareLine Studio but we now use dynamic buttons
|
||||
Serial.println("onSelectSSID() called - but dynamic buttons handle clicks now");
|
||||
}
|
||||
|
||||
} // namespace WiFiManager
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* WiFi Manager Module
|
||||
*
|
||||
* Handles WiFi functionality for the Waveshare ESP32-S3-Touch-LCD-5B:
|
||||
* - WiFi scanning and network discovery
|
||||
* - Connection management with password entry
|
||||
* - Dynamic SSID button generation
|
||||
* - FreeRTOS task on Core 0 for async WiFi operations
|
||||
* - Thread-safe UI updates via LVGL lock
|
||||
* - Auto-restore WiFi state from NVS
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <lvgl.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <freertos/queue.h>
|
||||
|
||||
namespace WiFiManager {
|
||||
|
||||
// ============================================================================
|
||||
// CONFIGURATION
|
||||
// ============================================================================
|
||||
|
||||
#define WIFI_SCAN_MAX_NETWORKS 20
|
||||
#define WIFI_SCAN_INTERVAL_MS 10000 // Rescan every 10 seconds when WiFi is ON
|
||||
#define WIFI_TASK_STACK_SIZE 4096
|
||||
#define WIFI_TASK_PRIORITY 1
|
||||
#define WIFI_TASK_CORE 0 // Run WiFi task on Core 0 (LVGL runs on Core 1)
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC TYPES
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief WiFi state machine states
|
||||
*/
|
||||
typedef enum {
|
||||
WIFI_STATE_OFF = 0,
|
||||
WIFI_STATE_SCANNING,
|
||||
WIFI_STATE_SCAN_COMPLETE,
|
||||
WIFI_STATE_CONNECTED,
|
||||
WIFI_STATE_CONNECTING,
|
||||
WIFI_STATE_ERROR
|
||||
} wifi_state_t;
|
||||
|
||||
/**
|
||||
* @brief WiFi scan result structure
|
||||
*/
|
||||
typedef struct {
|
||||
String ssid;
|
||||
int32_t rssi;
|
||||
wifi_auth_mode_t auth;
|
||||
} wifi_network_t;
|
||||
|
||||
/**
|
||||
* @brief WiFi connection credentials
|
||||
*/
|
||||
typedef struct {
|
||||
char ssid[32];
|
||||
char password[64];
|
||||
} wifi_credentials_t;
|
||||
|
||||
/**
|
||||
* @brief WiFi event types for FreeRTOS queue
|
||||
*/
|
||||
typedef enum {
|
||||
WIFI_UI_EVENT_TOGGLE_ON,
|
||||
WIFI_UI_EVENT_TOGGLE_OFF,
|
||||
WIFI_UI_EVENT_SCAN_START,
|
||||
WIFI_UI_EVENT_SCAN_DONE,
|
||||
WIFI_UI_EVENT_UPDATE_UI,
|
||||
WIFI_UI_EVENT_CONNECT,
|
||||
WIFI_UI_EVENT_DISCONNECT
|
||||
} wifi_ui_event_type_t;
|
||||
|
||||
/**
|
||||
* @brief WiFi queue event structure
|
||||
*/
|
||||
typedef struct {
|
||||
wifi_ui_event_type_t type;
|
||||
void* data;
|
||||
} wifi_queue_event_t;
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief Initialize the WiFi manager subsystem
|
||||
*
|
||||
* This function:
|
||||
* - Creates FreeRTOS mutex and queue
|
||||
* - Spawns WiFi task on Core 0
|
||||
* - Optionally auto-starts WiFi based on saved state
|
||||
*
|
||||
* @param auto_start If true, automatically start WiFi based on NVS saved state
|
||||
*/
|
||||
void init(bool auto_start);
|
||||
|
||||
/**
|
||||
* @brief Get current WiFi state
|
||||
* @return Current wifi_state_t value
|
||||
*/
|
||||
wifi_state_t getState();
|
||||
|
||||
/**
|
||||
* @brief Get WiFi network count from last scan
|
||||
* @return Number of networks found
|
||||
*/
|
||||
uint8_t getNetworkCount();
|
||||
|
||||
// ============================================================================
|
||||
// EVENT HANDLERS (Called from SquareLine Studio UI)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief WiFi toggle event handler
|
||||
* @param e LVGL event object
|
||||
* @note This function is registered in SquareLine Studio UI
|
||||
*/
|
||||
void onWifiToggle(lv_event_t *e);
|
||||
|
||||
/**
|
||||
* @brief SSID button click handler
|
||||
* @param e LVGL event object
|
||||
* @note Shows password entry for secured networks
|
||||
*/
|
||||
void onSSIDButtonClick(lv_event_t *e);
|
||||
|
||||
/**
|
||||
* @brief Keyboard event handler for password entry
|
||||
* @param e LVGL event object
|
||||
* @note Handles READY (connect) and CANCEL events
|
||||
*/
|
||||
void onKeyboardEvent(lv_event_t *e);
|
||||
|
||||
/**
|
||||
* @brief Manual rescan request handler
|
||||
* @param e LVGL event object
|
||||
*/
|
||||
void onRescanRequest(lv_event_t *e);
|
||||
|
||||
/**
|
||||
* @brief Legacy SquareLine Studio compatibility function
|
||||
* @param e LVGL event object
|
||||
* @note Kept for compatibility, but dynamic buttons handle clicks now
|
||||
*/
|
||||
void onSelectSSID(lv_event_t *e);
|
||||
|
||||
} // namespace WiFiManager
|
||||
Reference in New Issue
Block a user