refactor #12

Merged
stephen merged 4 commits from refactor into main 2025-07-10 09:10:15 -06:00
9 changed files with 2114 additions and 744 deletions
Showing only changes of commit 504003e2ba - Show all commits

View File

@ -1,2 +1,2 @@
idf_component_register(SRCS "maxxfan-controller.c" "motor_control.c" "state_manager.c" idf_component_register(SRCS "maxxfan-controller.c" "motor_control.c" "state_manager.c" "wifi_manager.c"
INCLUDE_DIRS ".") INCLUDE_DIRS ".")

View File

@ -2,10 +2,7 @@
#include <string.h> #include <string.h>
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h" #include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h" #include "esp_log.h"
#include "esp_http_server.h" #include "esp_http_server.h"
#include "esp_task_wdt.h" #include "esp_task_wdt.h"
@ -16,10 +13,7 @@
#include "config.h" #include "config.h"
#include "motor_control.h" #include "motor_control.h"
#include "state_manager.h" #include "state_manager.h"
#include "wifi_manager.h"
// WiFi event group
static EventGroupHandle_t s_wifi_event_group;
static int s_retry_num = 0;
// HTTP server handle // HTTP server handle
static httpd_handle_t server = NULL; static httpd_handle_t server = NULL;
@ -112,29 +106,6 @@ void feed_watchdog(void) {
} }
} }
// WiFi event handler
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
if (s_retry_num < WIFI_MAXIMUM_RETRY) {
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(SYSTEM_TAG, "retry to connect to the AP");
} else {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(SYSTEM_TAG, "connect to the AP fail");
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(SYSTEM_TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
// Helper function to set CORS headers // Helper function to set CORS headers
static void set_cors_headers(httpd_req_t *req) { static void set_cors_headers(httpd_req_t *req) {
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
@ -164,9 +135,16 @@ static esp_err_t status_get_handler(httpd_req_t *req)
int last_on_speed; int last_on_speed;
motor_get_last_on_state(&last_on_mode, &last_on_speed); motor_get_last_on_state(&last_on_mode, &last_on_speed);
ESP_LOGI(SYSTEM_TAG, "Status request - Mode: %s, Current: %d%%, Target: %d%%, State: %s, Ramping: %s", // Get WiFi information
wifi_info_t wifi_info;
wifi_manager_get_info(&wifi_info);
char ip_str[16];
wifi_manager_get_ip_string(ip_str, sizeof(ip_str));
ESP_LOGI(SYSTEM_TAG, "Status request - Mode: %s, Current: %d%%, Target: %d%%, State: %s, Ramping: %s, WiFi: %s (%s)",
motor_mode_to_string(state->mode), state->current_speed, state->target_speed, motor_mode_to_string(state->mode), state->current_speed, state->target_speed,
motor_state_to_string(state->state), state->ramping ? "YES" : "NO"); motor_state_to_string(state->state), state->ramping ? "YES" : "NO",
wifi_manager_status_to_string(wifi_info.status), ip_str);
set_cors_headers(req); set_cors_headers(req);
httpd_resp_set_type(req, "application/json"); httpd_resp_set_type(req, "application/json");
@ -189,6 +167,7 @@ static esp_err_t status_get_handler(httpd_req_t *req)
const char* last_on_mode_str = "exhaust"; const char* last_on_mode_str = "exhaust";
if (last_on_mode == MOTOR_INTAKE) last_on_mode_str = "intake"; if (last_on_mode == MOTOR_INTAKE) last_on_mode_str = "intake";
// Motor status
cJSON_AddStringToObject(json, "mode", mode_str); cJSON_AddStringToObject(json, "mode", mode_str);
cJSON_AddNumberToObject(json, "current_speed", state->current_speed); cJSON_AddNumberToObject(json, "current_speed", state->current_speed);
cJSON_AddNumberToObject(json, "target_speed", state->target_speed); cJSON_AddNumberToObject(json, "target_speed", state->target_speed);
@ -198,6 +177,15 @@ static esp_err_t status_get_handler(httpd_req_t *req)
cJSON_AddStringToObject(json, "last_on_mode", last_on_mode_str); cJSON_AddStringToObject(json, "last_on_mode", last_on_mode_str);
cJSON_AddNumberToObject(json, "last_on_speed", last_on_speed); cJSON_AddNumberToObject(json, "last_on_speed", last_on_speed);
// WiFi status
cJSON *wifi_json = cJSON_CreateObject();
cJSON_AddStringToObject(wifi_json, "status", wifi_manager_status_to_string(wifi_info.status));
cJSON_AddStringToObject(wifi_json, "ssid", wifi_info.ssid);
cJSON_AddStringToObject(wifi_json, "ip", ip_str);
cJSON_AddNumberToObject(wifi_json, "rssi", wifi_info.rssi);
cJSON_AddBoolToObject(wifi_json, "connected", wifi_manager_is_connected());
cJSON_AddItemToObject(json, "wifi", wifi_json);
// Add pending command info if in cooldown // Add pending command info if in cooldown
if (state->state == MOTOR_STATE_COOLDOWN) { if (state->state == MOTOR_STATE_COOLDOWN) {
const char* pending_mode_str = "off"; const char* pending_mode_str = "off";
@ -382,62 +370,6 @@ static httpd_handle_t start_webserver(void)
return NULL; return NULL;
} }
void wifi_init_sta(void)
{
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
&event_handler,
NULL,
&instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
IP_EVENT_STA_GOT_IP,
&event_handler,
NULL,
&instance_got_ip));
wifi_config_t wifi_config = {
.sta = {
.ssid = WIFI_SSID,
.password = WIFI_PASS,
.threshold.authmode = WIFI_AUTH_WPA2_PSK,
.pmf_cfg = {
.capable = true,
.required = false
},
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(SYSTEM_TAG, "wifi_init_sta finished.");
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE,
pdFALSE,
portMAX_DELAY);
if (bits & WIFI_CONNECTED_BIT) {
ESP_LOGI(SYSTEM_TAG, "connected to ap SSID:%s", WIFI_SSID);
} else if (bits & WIFI_FAIL_BIT) {
ESP_LOGI(SYSTEM_TAG, "Failed to connect to SSID:%s", WIFI_SSID);
} else {
ESP_LOGE(SYSTEM_TAG, "UNEXPECTED EVENT");
}
}
void app_main(void) void app_main(void)
{ {
ESP_LOGI(SYSTEM_TAG, "Starting Maxxfan HTTP Controller with State Preservation!"); ESP_LOGI(SYSTEM_TAG, "Starting Maxxfan HTTP Controller with State Preservation!");
@ -472,18 +404,63 @@ void app_main(void)
ESP_LOGW(SYSTEM_TAG, "⚠️ Failed to load state: %s", esp_err_to_name(load_result)); ESP_LOGW(SYSTEM_TAG, "⚠️ Failed to load state: %s", esp_err_to_name(load_result));
} }
ESP_LOGI(SYSTEM_TAG, "Connecting to WiFi network: %s", WIFI_SSID); // Initialize WiFi manager
wifi_init_sta(); ESP_LOGI(SYSTEM_TAG, "Initializing WiFi manager...");
ret = wifi_manager_init();
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to initialize WiFi manager: %s", esp_err_to_name(ret));
return;
}
// Start HTTP server // Connect to WiFi using default credentials
start_webserver(); ESP_LOGI(SYSTEM_TAG, "Connecting to WiFi network: %s", WIFI_SSID);
ret = wifi_manager_connect_default();
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to start WiFi connection: %s", esp_err_to_name(ret));
return;
}
// Wait for WiFi connection (with timeout)
ESP_LOGI(SYSTEM_TAG, "Waiting for WiFi connection...");
esp_err_t wifi_result = wifi_manager_wait_for_connection(30000); // 30 second timeout
if (wifi_result == ESP_OK) {
char ip_str[16];
wifi_manager_get_ip_string(ip_str, sizeof(ip_str));
wifi_info_t wifi_info;
wifi_manager_get_info(&wifi_info);
ESP_LOGI(SYSTEM_TAG, "✓ WiFi connected successfully!");
ESP_LOGI(SYSTEM_TAG, " SSID: %s", wifi_info.ssid);
ESP_LOGI(SYSTEM_TAG, " IP Address: %s", ip_str);
ESP_LOGI(SYSTEM_TAG, " Signal Strength: %d dBm", wifi_info.rssi);
} else if (wifi_result == ESP_ERR_TIMEOUT) {
ESP_LOGW(SYSTEM_TAG, "⚠️ WiFi connection timeout - continuing with limited functionality");
} else {
ESP_LOGW(SYSTEM_TAG, "⚠️ WiFi connection failed - continuing with limited functionality");
}
// Start HTTP server (even if WiFi failed, for debugging)
ESP_LOGI(SYSTEM_TAG, "Starting web server...");
httpd_handle_t web_server = start_webserver();
if (web_server) {
ESP_LOGI(SYSTEM_TAG, "✓ Web server started successfully");
} else {
ESP_LOGE(SYSTEM_TAG, "✗ Failed to start web server");
}
// Report final system state after initialization // Report final system state after initialization
const motor_state_t* final_state = motor_get_state(); const motor_state_t* final_state = motor_get_state();
wifi_info_t final_wifi_info;
wifi_manager_get_info(&final_wifi_info);
char final_ip_str[16];
wifi_manager_get_ip_string(final_ip_str, sizeof(final_ip_str));
ESP_LOGI(SYSTEM_TAG, "=== SYSTEM INITIALIZATION COMPLETE ==="); ESP_LOGI(SYSTEM_TAG, "=== SYSTEM INITIALIZATION COMPLETE ===");
ESP_LOGI(SYSTEM_TAG, "Reset Reason: %s", state_manager_get_reset_reason_string()); ESP_LOGI(SYSTEM_TAG, "Reset Reason: %s", state_manager_get_reset_reason_string());
ESP_LOGI(SYSTEM_TAG, "Watchdog Reset: %s", state_manager_was_watchdog_reset() ? "YES" : "NO"); ESP_LOGI(SYSTEM_TAG, "Watchdog Reset: %s", state_manager_was_watchdog_reset() ? "YES" : "NO");
ESP_LOGI(SYSTEM_TAG, "Final motor state: mode=%s, target=%d%%, current=%d%%, state=%s",
// Motor status
ESP_LOGI(SYSTEM_TAG, "Motor: mode=%s, target=%d%%, current=%d%%, state=%s",
motor_mode_to_string(final_state->mode), final_state->target_speed, motor_mode_to_string(final_state->mode), final_state->target_speed,
final_state->current_speed, motor_state_to_string(final_state->state)); final_state->current_speed, motor_state_to_string(final_state->state));
@ -500,6 +477,18 @@ void app_main(void)
ESP_LOGI(SYSTEM_TAG, "Last ON state: %s @ %d%%", ESP_LOGI(SYSTEM_TAG, "Last ON state: %s @ %d%%",
motor_mode_to_string(last_on_mode), last_on_speed); motor_mode_to_string(last_on_mode), last_on_speed);
ESP_LOGI(SYSTEM_TAG, "User turned off: %s", motor_get_user_turned_off() ? "YES" : "NO"); ESP_LOGI(SYSTEM_TAG, "User turned off: %s", motor_get_user_turned_off() ? "YES" : "NO");
// WiFi status
ESP_LOGI(SYSTEM_TAG, "WiFi: status=%s, SSID=%s, IP=%s, RSSI=%d dBm",
wifi_manager_status_to_string(final_wifi_info.status),
final_wifi_info.ssid, final_ip_str, final_wifi_info.rssi);
// Connection statistics
uint32_t total_attempts, successful_connections;
esp_err_t last_wifi_error;
wifi_manager_get_stats(&total_attempts, &successful_connections, &last_wifi_error);
ESP_LOGI(SYSTEM_TAG, "WiFi Stats: %lu attempts, %lu successful", total_attempts, successful_connections);
ESP_LOGI(SYSTEM_TAG, "Saved state exists: %s", state_manager_has_saved_state() ? "YES" : "NO"); ESP_LOGI(SYSTEM_TAG, "Saved state exists: %s", state_manager_has_saved_state() ? "YES" : "NO");
ESP_LOGI(SYSTEM_TAG, "====================================="); ESP_LOGI(SYSTEM_TAG, "=====================================");
@ -507,17 +496,31 @@ void app_main(void)
ESP_LOGI(SYSTEM_TAG, "Features: State Preservation, Direction Safety, Motor Ramping, ON Button"); ESP_LOGI(SYSTEM_TAG, "Features: State Preservation, Direction Safety, Motor Ramping, ON Button");
ESP_LOGI(SYSTEM_TAG, "Safety: %d-second cooldown for direction changes", DIRECTION_CHANGE_COOLDOWN_MS / 1000); ESP_LOGI(SYSTEM_TAG, "Safety: %d-second cooldown for direction changes", DIRECTION_CHANGE_COOLDOWN_MS / 1000);
ESP_LOGI(SYSTEM_TAG, "Memory: Remembers settings after power loss (except watchdog resets)"); ESP_LOGI(SYSTEM_TAG, "Memory: Remembers settings after power loss (except watchdog resets)");
ESP_LOGI(SYSTEM_TAG, "WiFi: Enhanced connection management with auto-reconnect");
ESP_LOGI(SYSTEM_TAG, "State Manager: Enhanced NVS operations with validation and recovery"); ESP_LOGI(SYSTEM_TAG, "State Manager: Enhanced NVS operations with validation and recovery");
ESP_LOGI(SYSTEM_TAG, "Open your browser and go to: http://[ESP32_IP_ADDRESS]");
ESP_LOGI(SYSTEM_TAG, "Check the monitor output above for your IP address"); if (wifi_manager_is_connected()) {
ESP_LOGI(SYSTEM_TAG, "🌐 Open your browser and go to: http://%s", final_ip_str);
} else {
ESP_LOGI(SYSTEM_TAG, "⚠️ WiFi not connected - check network settings");
}
// Main loop - reset watchdog periodically and update motor cooldown // Main loop - reset watchdog periodically and update motor cooldown
uint32_t loop_count = 0;
while (1) { while (1) {
feed_watchdog(); feed_watchdog();
// Update motor cooldown time for status reporting // Update motor cooldown time for status reporting
motor_update_cooldown_time(); motor_update_cooldown_time();
// Periodic WiFi status logging (every 30 seconds)
if (++loop_count % 10 == 0) {
wifi_status_t current_status = wifi_manager_get_status();
if (current_status != WIFI_STATUS_CONNECTED) {
ESP_LOGW(SYSTEM_TAG, "WiFi status: %s", wifi_manager_status_to_string(current_status));
}
}
vTaskDelay(pdMS_TO_TICKS(WATCHDOG_FEED_INTERVAL_MS)); vTaskDelay(pdMS_TO_TICKS(WATCHDOG_FEED_INTERVAL_MS));
} }
} }

View File

@ -123,16 +123,31 @@ esp_err_t state_manager_save(void) {
motor_get_last_on_state(&last_on_mode, &last_on_speed); motor_get_last_on_state(&last_on_mode, &last_on_speed);
bool user_turned_off = motor_get_user_turned_off(); bool user_turned_off = motor_get_user_turned_off();
// Determine the actual state to save
motor_mode_t mode_to_save = state->mode;
int speed_to_save = state->target_speed;
// If we're in cooldown, save the pending state instead of the current OFF state
if (state->state == MOTOR_STATE_COOLDOWN && state->pending_mode != MOTOR_OFF) {
mode_to_save = state->pending_mode;
speed_to_save = state->pending_speed;
ESP_LOGI(SYSTEM_TAG, "Motor in cooldown - saving pending state instead: %s @ %d%%",
motor_mode_to_string(mode_to_save), speed_to_save);
}
ESP_LOGI(SYSTEM_TAG, "=== SAVING STATE TO NVS ==="); ESP_LOGI(SYSTEM_TAG, "=== SAVING STATE TO NVS ===");
ESP_LOGI(SYSTEM_TAG, "Mode: %s, Speed: %d%%, Last ON: %s@%d%%, User OFF: %s", ESP_LOGI(SYSTEM_TAG, "Current: %s @ %d%%, State: %s",
motor_mode_to_string(state->mode), state->target_speed, motor_mode_to_string(state->mode), state->target_speed,
motor_state_to_string(state->state));
ESP_LOGI(SYSTEM_TAG, "Saving: %s @ %d%%, Last ON: %s@%d%%, User OFF: %s",
motor_mode_to_string(mode_to_save), speed_to_save,
motor_mode_to_string(last_on_mode), last_on_speed, motor_mode_to_string(last_on_mode), last_on_speed,
user_turned_off ? "YES" : "NO"); user_turned_off ? "YES" : "NO");
// Save current motor state // Save the determined motor state (actual or pending)
err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)state->mode); err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)mode_to_save);
if (err == ESP_OK) { if (err == ESP_OK) {
err = nvs_set_u8(nvs_handle, NVS_KEY_SPEED, (uint8_t)state->target_speed); err = nvs_set_u8(nvs_handle, NVS_KEY_SPEED, (uint8_t)speed_to_save);
} }
// Save last ON state // Save last ON state

436
main/wifi_manager.c Normal file
View File

@ -0,0 +1,436 @@
#include "wifi_manager.h"
#include "config.h"
#include "esp_log.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include <string.h>
#include <stdio.h>
// Private state
static struct {
wifi_status_t status;
EventGroupHandle_t event_group;
esp_netif_t* netif;
char current_ssid[33];
char current_password[65];
uint8_t max_retries;
uint8_t retry_count;
uint32_t connect_start_time;
bool auto_reconnect;
bool initialized;
// Statistics
uint32_t total_attempts;
uint32_t successful_connections;
esp_err_t last_error;
} wifi_state = {
.status = WIFI_STATUS_DISCONNECTED,
.event_group = NULL,
.netif = NULL,
.current_ssid = "",
.current_password = "",
.max_retries = WIFI_MAXIMUM_RETRY,
.retry_count = 0,
.connect_start_time = 0,
.auto_reconnect = true,
.initialized = false,
.total_attempts = 0,
.successful_connections = 0,
.last_error = ESP_OK
};
// Private function declarations
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
static esp_err_t start_connection_attempt(void);
// Private function implementations
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
if (event_base == WIFI_EVENT) {
switch (event_id) {
case WIFI_EVENT_STA_START:
ESP_LOGI(SYSTEM_TAG, "WiFi station started");
break;
case WIFI_EVENT_STA_CONNECTED:
ESP_LOGI(SYSTEM_TAG, "Connected to WiFi network: %s", wifi_state.current_ssid);
wifi_state.status = WIFI_STATUS_CONNECTED;
break;
case WIFI_EVENT_STA_DISCONNECTED: {
wifi_event_sta_disconnected_t* disconnected = (wifi_event_sta_disconnected_t*) event_data;
ESP_LOGW(SYSTEM_TAG, "WiFi disconnected, reason: %d", disconnected->reason);
if (wifi_state.status == WIFI_STATUS_CONNECTED) {
// We were connected, so this is a disconnection
if (wifi_state.auto_reconnect) {
wifi_state.status = WIFI_STATUS_RECONNECTING;
wifi_state.retry_count = 0;
ESP_LOGI(SYSTEM_TAG, "Auto-reconnect enabled, attempting to reconnect...");
esp_wifi_connect();
} else {
wifi_state.status = WIFI_STATUS_DISCONNECTED;
}
} else {
// Connection attempt failed
wifi_state.retry_count++;
wifi_state.last_error = ESP_ERR_WIFI_NOT_CONNECT;
if (wifi_state.max_retries == 0 || wifi_state.retry_count < wifi_state.max_retries) {
wifi_state.status = WIFI_STATUS_CONNECTING;
ESP_LOGI(SYSTEM_TAG, "Retry %d/%d connecting to WiFi...",
wifi_state.retry_count, wifi_state.max_retries);
esp_wifi_connect();
} else {
wifi_state.status = WIFI_STATUS_FAILED;
ESP_LOGE(SYSTEM_TAG, "Failed to connect to WiFi after %d attempts", wifi_state.retry_count);
xEventGroupSetBits(wifi_state.event_group, WIFI_FAIL_BIT);
}
}
break;
}
default:
break;
}
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(SYSTEM_TAG, "Got IP address: " IPSTR, IP2STR(&event->ip_info.ip));
wifi_state.status = WIFI_STATUS_CONNECTED;
wifi_state.successful_connections++;
wifi_state.retry_count = 0;
wifi_state.last_error = ESP_OK;
xEventGroupSetBits(wifi_state.event_group, WIFI_CONNECTED_BIT);
}
}
static void update_connection_time(void) {
if (wifi_state.connect_start_time > 0) {
wifi_state.connect_start_time = xTaskGetTickCount() * portTICK_PERIOD_MS;
}
}
static esp_err_t start_connection_attempt(void) {
wifi_state.total_attempts++;
wifi_state.connect_start_time = xTaskGetTickCount() * portTICK_PERIOD_MS;
wifi_state.retry_count = 0;
wifi_state.status = WIFI_STATUS_CONNECTING;
// Clear event bits
xEventGroupClearBits(wifi_state.event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT);
return esp_wifi_connect();
}
// Public API implementation
esp_err_t wifi_manager_init(void) {
if (wifi_state.initialized) {
ESP_LOGW(SYSTEM_TAG, "WiFi manager already initialized");
return ESP_OK;
}
ESP_LOGI(SYSTEM_TAG, "Initializing WiFi manager...");
// Create event group
wifi_state.event_group = xEventGroupCreate();
if (!wifi_state.event_group) {
ESP_LOGE(SYSTEM_TAG, "Failed to create WiFi event group");
return ESP_FAIL;
}
// Initialize network interface
esp_err_t ret = esp_netif_init();
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to initialize netif: %s", esp_err_to_name(ret));
return ret;
}
ret = esp_event_loop_create_default();
if (ret != ESP_OK && ret != ESP_ERR_INVALID_STATE) {
ESP_LOGE(SYSTEM_TAG, "Failed to create event loop: %s", esp_err_to_name(ret));
return ret;
}
wifi_state.netif = esp_netif_create_default_wifi_sta();
if (!wifi_state.netif) {
ESP_LOGE(SYSTEM_TAG, "Failed to create default WiFi STA netif");
return ESP_FAIL;
}
// Initialize WiFi
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ret = esp_wifi_init(&cfg);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to initialize WiFi: %s", esp_err_to_name(ret));
return ret;
}
// Register event handlers
ret = esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
&wifi_event_handler, NULL, NULL);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register WiFi event handler: %s", esp_err_to_name(ret));
return ret;
}
ret = esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
&wifi_event_handler, NULL, NULL);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register IP event handler: %s", esp_err_to_name(ret));
return ret;
}
// Set WiFi mode
ret = esp_wifi_set_mode(WIFI_MODE_STA);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to set WiFi mode: %s", esp_err_to_name(ret));
return ret;
}
// Start WiFi
ret = esp_wifi_start();
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to start WiFi: %s", esp_err_to_name(ret));
return ret;
}
wifi_state.initialized = true;
wifi_state.status = WIFI_STATUS_DISCONNECTED;
ESP_LOGI(SYSTEM_TAG, "WiFi manager initialized successfully");
return ESP_OK;
}
esp_err_t wifi_manager_connect(const char* ssid, const char* password, uint8_t max_retries) {
if (!wifi_state.initialized) {
ESP_LOGE(SYSTEM_TAG, "WiFi manager not initialized");
return ESP_FAIL;
}
if (!ssid || strlen(ssid) == 0 || strlen(ssid) > 32) {
ESP_LOGE(SYSTEM_TAG, "Invalid SSID");
return ESP_ERR_INVALID_ARG;
}
if (!password || strlen(password) > 64) {
ESP_LOGE(SYSTEM_TAG, "Invalid password");
return ESP_ERR_INVALID_ARG;
}
// Store connection parameters
strncpy(wifi_state.current_ssid, ssid, sizeof(wifi_state.current_ssid) - 1);
wifi_state.current_ssid[sizeof(wifi_state.current_ssid) - 1] = '\0';
strncpy(wifi_state.current_password, password, sizeof(wifi_state.current_password) - 1);
wifi_state.current_password[sizeof(wifi_state.current_password) - 1] = '\0';
wifi_state.max_retries = max_retries;
// Configure WiFi
wifi_config_t wifi_config = {0};
strncpy((char*)wifi_config.sta.ssid, ssid, sizeof(wifi_config.sta.ssid) - 1);
strncpy((char*)wifi_config.sta.password, password, sizeof(wifi_config.sta.password) - 1);
wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
wifi_config.sta.pmf_cfg.capable = true;
wifi_config.sta.pmf_cfg.required = false;
esp_err_t ret = esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to set WiFi config: %s", esp_err_to_name(ret));
return ret;
}
ESP_LOGI(SYSTEM_TAG, "Connecting to WiFi SSID: %s", ssid);
return start_connection_attempt();
}
esp_err_t wifi_manager_connect_default(void) {
return wifi_manager_connect(WIFI_SSID, WIFI_PASS, WIFI_MAXIMUM_RETRY);
}
esp_err_t wifi_manager_disconnect(void) {
if (!wifi_state.initialized) {
return ESP_FAIL;
}
wifi_state.auto_reconnect = false;
wifi_state.status = WIFI_STATUS_DISCONNECTED;
esp_err_t ret = esp_wifi_disconnect();
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to disconnect WiFi: %s", esp_err_to_name(ret));
}
return ret;
}
wifi_status_t wifi_manager_get_status(void) {
return wifi_state.status;
}
esp_err_t wifi_manager_get_info(wifi_info_t* info) {
if (!info) {
return ESP_ERR_INVALID_ARG;
}
info->status = wifi_state.status;
strncpy(info->ssid, wifi_state.current_ssid, sizeof(info->ssid) - 1);
info->ssid[sizeof(info->ssid) - 1] = '\0';
info->ip_address = wifi_manager_get_ip();
info->rssi = wifi_manager_get_rssi();
info->retry_count = wifi_state.retry_count;
info->auto_reconnect = wifi_state.auto_reconnect;
if (wifi_state.connect_start_time > 0) {
uint32_t current_time = xTaskGetTickCount() * portTICK_PERIOD_MS;
info->connect_time_ms = current_time - wifi_state.connect_start_time;
} else {
info->connect_time_ms = 0;
}
return ESP_OK;
}
bool wifi_manager_is_connected(void) {
return wifi_state.status == WIFI_STATUS_CONNECTED;
}
uint32_t wifi_manager_get_ip(void) {
if (!wifi_state.initialized || !wifi_manager_is_connected()) {
return 0;
}
esp_netif_ip_info_t ip_info;
if (esp_netif_get_ip_info(wifi_state.netif, &ip_info) == ESP_OK) {
return ip_info.ip.addr;
}
return 0;
}
esp_err_t wifi_manager_get_ip_string(char* ip_str, size_t max_len) {
if (!ip_str || max_len < 16) {
return ESP_ERR_INVALID_ARG;
}
uint32_t ip = wifi_manager_get_ip();
if (ip == 0) {
strncpy(ip_str, "0.0.0.0", max_len - 1);
ip_str[max_len - 1] = '\0';
return ESP_FAIL;
}
// Convert uint32_t IP to string manually
uint8_t* ip_bytes = (uint8_t*)&ip;
snprintf(ip_str, max_len, "%d.%d.%d.%d",
ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]);
return ESP_OK;
}
int8_t wifi_manager_get_rssi(void) {
if (!wifi_state.initialized || !wifi_manager_is_connected()) {
return 0;
}
wifi_ap_record_t ap_info;
if (esp_wifi_sta_get_ap_info(&ap_info) == ESP_OK) {
return ap_info.rssi;
}
return 0;
}
esp_err_t wifi_manager_set_auto_reconnect(bool enable) {
wifi_state.auto_reconnect = enable;
ESP_LOGI(SYSTEM_TAG, "Auto-reconnect %s", enable ? "enabled" : "disabled");
return ESP_OK;
}
esp_err_t wifi_manager_wait_for_connection(uint32_t timeout_ms) {
if (!wifi_state.initialized) {
return ESP_FAIL;
}
if (wifi_manager_is_connected()) {
return ESP_OK;
}
TickType_t timeout_ticks = (timeout_ms == 0) ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms);
EventBits_t bits = xEventGroupWaitBits(wifi_state.event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
pdFALSE, pdFALSE, timeout_ticks);
if (bits & WIFI_CONNECTED_BIT) {
return ESP_OK;
} else if (bits & WIFI_FAIL_BIT) {
return ESP_FAIL;
} else {
return ESP_ERR_TIMEOUT;
}
}
const char* wifi_manager_status_to_string(wifi_status_t status) {
switch (status) {
case WIFI_STATUS_DISCONNECTED: return "DISCONNECTED";
case WIFI_STATUS_CONNECTING: return "CONNECTING";
case WIFI_STATUS_CONNECTED: return "CONNECTED";
case WIFI_STATUS_FAILED: return "FAILED";
case WIFI_STATUS_RECONNECTING: return "RECONNECTING";
default: return "UNKNOWN";
}
}
esp_err_t wifi_manager_start_scan(void) {
if (!wifi_state.initialized) {
return ESP_FAIL;
}
wifi_scan_config_t scan_config = {
.ssid = NULL,
.bssid = NULL,
.channel = 0,
.show_hidden = false,
.scan_type = WIFI_SCAN_TYPE_ACTIVE,
.scan_time.active.min = 100,
.scan_time.active.max = 300
};
return esp_wifi_scan_start(&scan_config, false);
}
esp_err_t wifi_manager_get_scan_results(wifi_ap_record_t* ap_info, uint16_t max_aps, uint16_t* num_aps) {
if (!ap_info || !num_aps) {
return ESP_ERR_INVALID_ARG;
}
return esp_wifi_scan_get_ap_records(&max_aps, ap_info);
}
esp_err_t wifi_manager_reconnect(void) {
if (!wifi_state.initialized) {
return ESP_FAIL;
}
ESP_LOGI(SYSTEM_TAG, "Forcing WiFi reconnection...");
wifi_state.retry_count = 0;
return start_connection_attempt();
}
esp_err_t wifi_manager_get_stats(uint32_t* total_attempts, uint32_t* successful_connections, esp_err_t* last_error) {
if (total_attempts) *total_attempts = wifi_state.total_attempts;
if (successful_connections) *successful_connections = wifi_state.successful_connections;
if (last_error) *last_error = wifi_state.last_error;
return ESP_OK;
}
esp_err_t wifi_manager_reset_stats(void) {
wifi_state.total_attempts = 0;
wifi_state.successful_connections = 0;
wifi_state.last_error = ESP_OK;
ESP_LOGI(SYSTEM_TAG, "WiFi statistics reset");
return ESP_OK;
}

193
main/wifi_manager.h Normal file
View File

@ -0,0 +1,193 @@
#ifndef WIFI_MANAGER_H
#define WIFI_MANAGER_H
#include "esp_err.h"
#include "esp_wifi.h"
#include "esp_netif.h"
#include <stdbool.h>
#include <stdint.h>
// WiFi connection status
typedef enum {
WIFI_STATUS_DISCONNECTED,
WIFI_STATUS_CONNECTING,
WIFI_STATUS_CONNECTED,
WIFI_STATUS_FAILED,
WIFI_STATUS_RECONNECTING
} wifi_status_t;
// WiFi connection information
typedef struct {
wifi_status_t status;
char ssid[33]; // WiFi SSID (max 32 chars + null terminator)
uint32_t ip_address; // IP address (0 if not connected)
int8_t rssi; // Signal strength in dBm
uint8_t retry_count; // Current retry attempt
uint32_t connect_time_ms; // Time since connection started
bool auto_reconnect; // Whether auto-reconnect is enabled
} wifi_info_t;
/**
* @brief Initialize the WiFi manager
*
* Sets up WiFi in station mode and prepares for connection.
* Must be called before any other WiFi manager functions.
*
* @return ESP_OK on success, ESP_FAIL on error
*/
esp_err_t wifi_manager_init(void);
/**
* @brief Connect to WiFi network with specified credentials
*
* Attempts to connect to the specified WiFi network. This function
* returns immediately and connection happens asynchronously.
*
* @param ssid WiFi network name (max 32 characters)
* @param password WiFi password (max 64 characters)
* @param max_retries Maximum number of connection attempts (0 = infinite)
* @return ESP_OK if connection attempt started, ESP_FAIL on error
*/
esp_err_t wifi_manager_connect(const char* ssid, const char* password, uint8_t max_retries);
/**
* @brief Connect using credentials from config.h
*
* Convenience function that uses WIFI_SSID and WIFI_PASS from config.h
* with WIFI_MAXIMUM_RETRY attempts.
*
* @return ESP_OK if connection attempt started, ESP_FAIL on error
*/
esp_err_t wifi_manager_connect_default(void);
/**
* @brief Disconnect from WiFi network
*
* @return ESP_OK on success, ESP_FAIL on error
*/
esp_err_t wifi_manager_disconnect(void);
/**
* @brief Get current WiFi connection status
*
* @return Current WiFi status
*/
wifi_status_t wifi_manager_get_status(void);
/**
* @brief Get comprehensive WiFi information
*
* @param info Pointer to wifi_info_t structure to fill
* @return ESP_OK on success, ESP_ERR_INVALID_ARG if info is NULL
*/
esp_err_t wifi_manager_get_info(wifi_info_t* info);
/**
* @brief Check if WiFi is connected
*
* @return true if connected, false otherwise
*/
bool wifi_manager_is_connected(void);
/**
* @brief Get current IP address
*
* @return IP address as uint32_t (0 if not connected)
*/
uint32_t wifi_manager_get_ip(void);
/**
* @brief Get current IP address as string
*
* @param ip_str Buffer to store IP string (minimum 16 bytes)
* @param max_len Maximum length of buffer
* @return ESP_OK on success, ESP_ERR_INVALID_ARG on error
*/
esp_err_t wifi_manager_get_ip_string(char* ip_str, size_t max_len);
/**
* @brief Get signal strength (RSSI)
*
* @return Signal strength in dBm (0 if not connected)
*/
int8_t wifi_manager_get_rssi(void);
/**
* @brief Enable or disable auto-reconnect
*
* When enabled, the WiFi manager will automatically attempt to reconnect
* if the connection is lost.
*
* @param enable true to enable auto-reconnect, false to disable
* @return ESP_OK on success
*/
esp_err_t wifi_manager_set_auto_reconnect(bool enable);
/**
* @brief Wait for WiFi connection to complete
*
* Blocks until WiFi connection succeeds or fails. Useful for synchronous
* operation during initialization.
*
* @param timeout_ms Maximum time to wait in milliseconds (0 = wait forever)
* @return ESP_OK if connected, ESP_ERR_TIMEOUT if timeout, ESP_FAIL if connection failed
*/
esp_err_t wifi_manager_wait_for_connection(uint32_t timeout_ms);
/**
* @brief Get WiFi status as string
*
* @param status WiFi status enum value
* @return String representation of the status
*/
const char* wifi_manager_status_to_string(wifi_status_t status);
/**
* @brief Scan for available WiFi networks
*
* Initiates a WiFi scan. Results can be retrieved with wifi_manager_get_scan_results().
*
* @return ESP_OK if scan started, ESP_FAIL on error
*/
esp_err_t wifi_manager_start_scan(void);
/**
* @brief Get WiFi scan results
*
* @param ap_info Array to store access point information
* @param max_aps Maximum number of APs to return
* @param num_aps Pointer to store actual number of APs found
* @return ESP_OK on success, ESP_FAIL on error
*/
esp_err_t wifi_manager_get_scan_results(wifi_ap_record_t* ap_info, uint16_t max_aps, uint16_t* num_aps);
/**
* @brief Force immediate reconnection attempt
*
* Useful for testing or when you want to retry connection immediately
* instead of waiting for the automatic retry.
*
* @return ESP_OK if reconnection attempt started, ESP_FAIL on error
*/
esp_err_t wifi_manager_reconnect(void);
/**
* @brief Get detailed connection statistics
*
* Provides information about connection attempts, success rate, etc.
*
* @param total_attempts Pointer to store total connection attempts
* @param successful_connections Pointer to store successful connections
* @param last_error Pointer to store last connection error
* @return ESP_OK on success
*/
esp_err_t wifi_manager_get_stats(uint32_t* total_attempts, uint32_t* successful_connections, esp_err_t* last_error);
/**
* @brief Reset WiFi manager statistics
*
* @return ESP_OK on success
*/
esp_err_t wifi_manager_reset_stats(void);
#endif // WIFI_MANAGER_H