Init new era, with wiki integrated.

This commit is contained in:
2026-07-15 12:17:06 +02:00
commit 37f98a241f
67 changed files with 10396 additions and 0 deletions
+92
View File
@@ -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
+46
View File
@@ -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
+363
View File
@@ -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");
}
+70
View File
@@ -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
+92
View File
@@ -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
+69
View File
@@ -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
+356
View File
@@ -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
+130
View File
@@ -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
+179
View File
@@ -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
+63
View File
@@ -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
+759
View File
@@ -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
+154
View File
@@ -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