From 15f8d41656beb28d13ceb654dcc7a6a6085326ab Mon Sep 17 00:00:00 2001 From: Stephen Minakian Date: Wed, 9 Jul 2025 17:10:51 -0600 Subject: [PATCH 1/4] Refactored out config and macros --- main/config.h | 124 ++++++++++++++++++ main/maxxfan-controller.c | 266 ++++++++++++++++---------------------- 2 files changed, 239 insertions(+), 151 deletions(-) create mode 100644 main/config.h diff --git a/main/config.h b/main/config.h new file mode 100644 index 0000000..90fc402 --- /dev/null +++ b/main/config.h @@ -0,0 +1,124 @@ +#ifndef CONFIG_H +#define CONFIG_H + +#include "driver/gpio.h" +#include "driver/ledc.h" + +// ================================ +// WiFi Configuration +// ================================ +#define WIFI_SSID "GL-AXT1800-0c2" +#define WIFI_PASS "CR7W25FM8S" +#define WIFI_MAXIMUM_RETRY 5 + +// WiFi event group bits +#define WIFI_CONNECTED_BIT BIT0 +#define WIFI_FAIL_BIT BIT1 + +// ================================ +// GPIO Pin Definitions +// ================================ +#define LED_PIN GPIO_NUM_13 +#define MOTOR_R_EN GPIO_NUM_18 +#define MOTOR_L_EN GPIO_NUM_19 +#define PWM_R_PIN GPIO_NUM_21 +#define PWM_L_PIN GPIO_NUM_22 + +// ================================ +// PWM Configuration +// ================================ +#define PWM_FREQUENCY 20000 +#define PWM_RESOLUTION LEDC_TIMER_8_BIT +#define PWM_R_CHANNEL LEDC_CHANNEL_0 +#define PWM_L_CHANNEL LEDC_CHANNEL_1 +#define PWM_TIMER LEDC_TIMER_0 +#define PWM_SPEED_MODE LEDC_LOW_SPEED_MODE + +// ================================ +// Motor Control Configuration +// ================================ +#define RAMP_STEP_MS 150 // Time between ramp steps (milliseconds) +#define RAMP_STEP_SIZE 5 // PWM duty change per step (0-255) +#define MIN_MOTOR_SPEED 10 // Minimum speed to overcome motor inertia +#define DIRECTION_CHANGE_COOLDOWN_MS 10000 // 10 seconds cooldown for direction changes + +// ================================ +// Watchdog Configuration +// ================================ +#define WATCHDOG_TIMEOUT_S 10 // Watchdog timeout in seconds +#define WATCHDOG_FEED_INTERVAL_MS 3000 // Feed watchdog every 3 seconds + +// ================================ +// State Preservation Configuration +// ================================ +#define NVS_NAMESPACE "fan_state" +#define NVS_KEY_MODE "mode" +#define NVS_KEY_SPEED "speed" +#define NVS_KEY_LAST_ON_MODE "last_mode" +#define NVS_KEY_LAST_ON_SPEED "last_speed" +#define NVS_KEY_POWER_STATE "power_state" + +// ================================ +// HTTP Server Configuration +// ================================ +#define HTTP_SERVER_PORT 80 +#define HTTP_MAX_URI_HANDLERS 15 +#define HTTP_RECV_TIMEOUT_SEC 10 +#define HTTP_SEND_TIMEOUT_SEC 10 + +// ================================ +// Status Update Configuration +// ================================ +#define STATUS_UPDATE_INTERVAL_MS 1000 // Web interface status update interval + +// ================================ +// System Configuration +// ================================ +#define SYSTEM_TAG "HTTP_MOTOR" // Main logging tag + +// ================================ +// Safety Limits +// ================================ +#define MAX_SPEED_PERCENT 100 +#define MIN_SPEED_PERCENT 0 +#define MAX_JSON_BUFFER_SIZE 200 + +// ================================ +// Motor PWM Calculation Macros +// ================================ +#define SPEED_TO_DUTY(speed_percent) ((speed_percent * 255) / 100) +#define DUTY_TO_SPEED(duty) ((duty * 100) / 255) + +// ================================ +// Validation Macros +// ================================ +#define CLAMP_SPEED(speed) ((speed) < MIN_SPEED_PERCENT ? MIN_SPEED_PERCENT : \ + (speed) > MAX_SPEED_PERCENT ? MAX_SPEED_PERCENT : (speed)) + +// For unsigned types (uint8_t), we only need to check the upper bound since MIN_SPEED_PERCENT is 0 +#define IS_VALID_SPEED(speed) ((speed) <= MAX_SPEED_PERCENT) + +// For signed types or when MIN_SPEED_PERCENT might be > 0, use this version: +#define IS_VALID_SPEED_FULL(speed) ((speed) >= MIN_SPEED_PERCENT && (speed) <= MAX_SPEED_PERCENT) + +#define IS_DIRECTION_CHANGE(old_mode, new_mode) \ + (((old_mode) == MOTOR_EXHAUST && (new_mode) == MOTOR_INTAKE) || \ + ((old_mode) == MOTOR_INTAKE && (new_mode) == MOTOR_EXHAUST)) + +// ================================ +// Debug Configuration +// ================================ +#ifdef CONFIG_LOG_DEFAULT_LEVEL_DEBUG +#define MOTOR_DEBUG_ENABLED 1 +#else +#define MOTOR_DEBUG_ENABLED 0 +#endif + +// Debug logging macro +#if MOTOR_DEBUG_ENABLED +#define MOTOR_LOGD(tag, format, ...) ESP_LOGD(tag, format, ##__VA_ARGS__) +#else +#define MOTOR_LOGD(tag, format, ...) +#endif + +#endif // CONFIG_H \ No newline at end of file diff --git a/main/maxxfan-controller.c b/main/maxxfan-controller.c index 0af619b..ca94ed3 100755 --- a/main/maxxfan-controller.c +++ b/main/maxxfan-controller.c @@ -16,48 +16,11 @@ #include "driver/ledc.h" #include "cJSON.h" -// WiFi credentials - CHANGE THESE TO YOUR NETWORK -#define WIFI_SSID "GL-AXT1800-0c2" -#define WIFI_PASS "CR7W25FM8S" -#define WIFI_MAXIMUM_RETRY 5 - -// Pin definitions -#define LED_PIN GPIO_NUM_13 -#define MOTOR_R_EN GPIO_NUM_18 -#define MOTOR_L_EN GPIO_NUM_19 -#define PWM_R_PIN GPIO_NUM_21 -#define PWM_L_PIN GPIO_NUM_22 - -// PWM configuration -#define PWM_FREQUENCY 20000 -#define PWM_RESOLUTION LEDC_TIMER_8_BIT -#define PWM_R_CHANNEL LEDC_CHANNEL_0 -#define PWM_L_CHANNEL LEDC_CHANNEL_1 - -// Motor ramping configuration -#define RAMP_STEP_MS 150 // Time between ramp steps (milliseconds) -#define RAMP_STEP_SIZE 5 // PWM duty change per step (0-255) -#define MIN_MOTOR_SPEED 10 // Minimum speed to overcome motor inertia -#define DIRECTION_CHANGE_COOLDOWN_MS 10000 // 10 seconds cooldown for direction changes - -// Watchdog configuration -#define WATCHDOG_TIMEOUT_S 10 // Watchdog timeout in seconds - -// State preservation configuration -#define NVS_NAMESPACE "fan_state" -#define NVS_KEY_MODE "mode" -#define NVS_KEY_SPEED "speed" -#define NVS_KEY_LAST_ON_MODE "last_mode" -#define NVS_KEY_LAST_ON_SPEED "last_speed" -#define NVS_KEY_POWER_STATE "power_state" - -static const char* TAG = "HTTP_MOTOR"; +// Project configuration +#include "config.h" // WiFi event group static EventGroupHandle_t s_wifi_event_group; -#define WIFI_CONNECTED_BIT BIT0 -#define WIFI_FAIL_BIT BIT1 - static int s_retry_num = 0; // Motor control @@ -184,18 +147,18 @@ static void save_last_on_state(motor_mode_t mode, int speed); // Initialize watchdog timer void init_watchdog(void) { - ESP_LOGI(TAG, "Setting up watchdog monitoring..."); + ESP_LOGI(SYSTEM_TAG, "Setting up watchdog monitoring..."); // Get current task handle and add to watchdog main_task_handle = xTaskGetCurrentTaskHandle(); esp_err_t result = esp_task_wdt_add(main_task_handle); if (result == ESP_OK) { - ESP_LOGI(TAG, "Main task added to watchdog monitoring"); + ESP_LOGI(SYSTEM_TAG, "Main task added to watchdog monitoring"); } else if (result == ESP_ERR_INVALID_ARG) { - ESP_LOGI(TAG, "Task already monitored by watchdog"); + ESP_LOGI(SYSTEM_TAG, "Task already monitored by watchdog"); } else { - ESP_LOGW(TAG, "Watchdog not available: %s", esp_err_to_name(result)); + ESP_LOGW(SYSTEM_TAG, "Watchdog not available: %s", esp_err_to_name(result)); main_task_handle = NULL; // Disable watchdog feeding } } @@ -205,7 +168,7 @@ void feed_watchdog(void) { if (main_task_handle != NULL) { esp_err_t result = esp_task_wdt_reset(); if (result != ESP_OK) { - ESP_LOGD(TAG, "Watchdog reset failed: %s", esp_err_to_name(result)); + MOTOR_LOGD(SYSTEM_TAG, "Watchdog reset failed: %s", esp_err_to_name(result)); } } } @@ -227,12 +190,12 @@ static esp_err_t save_motor_state_to_nvs(void) { err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle); if (err != ESP_OK) { - ESP_LOGE(TAG, "Error opening NVS handle: %s", esp_err_to_name(err)); + ESP_LOGE(SYSTEM_TAG, "Error opening NVS handle: %s", esp_err_to_name(err)); return err; } - ESP_LOGI(TAG, "=== SAVING STATE TO NVS ==="); - ESP_LOGI(TAG, "Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", + ESP_LOGI(SYSTEM_TAG, "=== SAVING STATE TO NVS ==="); + ESP_LOGI(SYSTEM_TAG, "Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", motor_state.mode, motor_state.target_speed, motor_state.last_on_mode, motor_state.last_on_speed, motor_state.user_turned_off ? "YES" : "NO"); @@ -259,14 +222,14 @@ static esp_err_t save_motor_state_to_nvs(void) { if (err == ESP_OK) { err = nvs_commit(nvs_handle); if (err == ESP_OK) { - ESP_LOGI(TAG, "✓ Motor state successfully saved to NVS"); + ESP_LOGI(SYSTEM_TAG, "✓ Motor state successfully saved to NVS"); } else { - ESP_LOGE(TAG, "✗ NVS commit failed: %s", esp_err_to_name(err)); + ESP_LOGE(SYSTEM_TAG, "✗ NVS commit failed: %s", esp_err_to_name(err)); } } else { - ESP_LOGE(TAG, "✗ Error saving to NVS: %s", esp_err_to_name(err)); + ESP_LOGE(SYSTEM_TAG, "✗ Error saving to NVS: %s", esp_err_to_name(err)); } - ESP_LOGI(TAG, "==========================="); + ESP_LOGI(SYSTEM_TAG, "==========================="); nvs_close(nvs_handle); return err; @@ -279,7 +242,7 @@ static esp_err_t load_motor_state_from_nvs(void) { err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle); if (err != ESP_OK) { - ESP_LOGI(TAG, "NVS not found, using default state"); + ESP_LOGI(SYSTEM_TAG, "NVS not found, using default state"); return ESP_ERR_NVS_NOT_FOUND; } @@ -297,27 +260,27 @@ static esp_err_t load_motor_state_from_nvs(void) { nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, &stored_last_speed); nvs_get_u8(nvs_handle, NVS_KEY_POWER_STATE, &stored_power_state); - // Validate ranges + // Validate ranges using config macros if (stored_mode > MOTOR_INTAKE) stored_mode = MOTOR_OFF; - if (stored_speed > 100) stored_speed = 0; + if (!IS_VALID_SPEED(stored_speed)) stored_speed = 0; if (stored_last_mode < MOTOR_EXHAUST || stored_last_mode > MOTOR_INTAKE) stored_last_mode = MOTOR_EXHAUST; - if (stored_last_speed > 100) stored_last_speed = 50; + if (!IS_VALID_SPEED(stored_last_speed)) stored_last_speed = 50; motor_state.last_on_mode = (motor_mode_t)stored_last_mode; motor_state.last_on_speed = stored_last_speed; motor_state.user_turned_off = (stored_power_state == 1); - ESP_LOGI(TAG, "Loaded state from NVS - Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", + ESP_LOGI(SYSTEM_TAG, "Loaded state from NVS - Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", stored_mode, stored_speed, motor_state.last_on_mode, motor_state.last_on_speed, motor_state.user_turned_off ? "YES" : "NO"); - // Check reset reason to decide whether to restore state + // Check reset reason to decide whether to restore state bool was_watchdog_reset = is_watchdog_reset(); esp_reset_reason_t reset_reason = esp_reset_reason(); - ESP_LOGI(TAG, "=== RESET ANALYSIS ==="); - ESP_LOGI(TAG, "Reset reason: %d", reset_reason); - ESP_LOGI(TAG, "Reset reason name: %s", + ESP_LOGI(SYSTEM_TAG, "=== RESET ANALYSIS ==="); + ESP_LOGI(SYSTEM_TAG, "Reset reason: %d", reset_reason); + ESP_LOGI(SYSTEM_TAG, "Reset reason name: %s", reset_reason == ESP_RST_POWERON ? "POWERON" : reset_reason == ESP_RST_EXT ? "EXTERNAL" : reset_reason == ESP_RST_SW ? "SOFTWARE" : @@ -328,39 +291,39 @@ static esp_err_t load_motor_state_from_nvs(void) { reset_reason == ESP_RST_DEEPSLEEP ? "DEEPSLEEP" : reset_reason == ESP_RST_BROWNOUT ? "BROWNOUT" : reset_reason == ESP_RST_SDIO ? "SDIO" : "UNKNOWN"); - ESP_LOGI(TAG, "Watchdog reset: %s", was_watchdog_reset ? "YES" : "NO"); - ESP_LOGI(TAG, "Stored mode: %d, speed: %d", stored_mode, stored_speed); - ESP_LOGI(TAG, "User turned off: %s", motor_state.user_turned_off ? "YES" : "NO"); - ESP_LOGI(TAG, "===================="); + ESP_LOGI(SYSTEM_TAG, "Watchdog reset: %s", was_watchdog_reset ? "YES" : "NO"); + ESP_LOGI(SYSTEM_TAG, "Stored mode: %d, speed: %d", stored_mode, stored_speed); + ESP_LOGI(SYSTEM_TAG, "User turned off: %s", motor_state.user_turned_off ? "YES" : "NO"); + ESP_LOGI(SYSTEM_TAG, "===================="); if (was_watchdog_reset) { // True watchdog reset (TASK_WDT or INT_WDT) - don't restore state, start fresh - ESP_LOGI(TAG, "⚠️ TRUE watchdog reset detected - starting in OFF state for safety"); + ESP_LOGI(SYSTEM_TAG, "⚠️ TRUE watchdog reset detected - starting in OFF state for safety"); motor_state.mode = MOTOR_OFF; motor_state.target_speed = 0; motor_state.current_speed = 0; motor_state.user_turned_off = false; // Reset user off flag } else if (motor_state.user_turned_off) { // User manually turned off - stay off - ESP_LOGI(TAG, "🔒 User had turned off manually - staying OFF"); + ESP_LOGI(SYSTEM_TAG, "🔒 User had turned off manually - staying OFF"); motor_state.mode = MOTOR_OFF; motor_state.target_speed = 0; motor_state.current_speed = 0; } else if (stored_mode != MOTOR_OFF && stored_speed > 0) { // Normal power loss or general WDT (which can be power-related) - restore previous state - ESP_LOGI(TAG, "🔋 Power restored - will resume previous state: %s @ %d%%", + ESP_LOGI(SYSTEM_TAG, "🔋 Power restored - will resume previous state: %s @ %d%%", stored_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", stored_speed); motor_state.mode = (motor_mode_t)stored_mode; motor_state.target_speed = stored_speed; motor_state.current_speed = 0; // Always start ramping from 0 } else { - ESP_LOGI(TAG, "❌ No valid state to restore (mode=%d, speed=%d)", stored_mode, stored_speed); + ESP_LOGI(SYSTEM_TAG, "❌ No valid state to restore (mode=%d, speed=%d)", stored_mode, stored_speed); motor_state.mode = MOTOR_OFF; motor_state.target_speed = 0; motor_state.current_speed = 0; } } else { - ESP_LOGI(TAG, "No saved state found, using defaults"); + ESP_LOGI(SYSTEM_TAG, "No saved state found, using defaults"); err = ESP_ERR_NVS_NOT_FOUND; } @@ -373,7 +336,7 @@ static void save_last_on_state(motor_mode_t mode, int speed) { if (mode != MOTOR_OFF && speed > 0) { motor_state.last_on_mode = mode; motor_state.last_on_speed = speed; - ESP_LOGI(TAG, "Last ON state updated: %s @ %d%%", + ESP_LOGI(SYSTEM_TAG, "Last ON state updated: %s @ %d%%", mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", speed); } } @@ -388,14 +351,14 @@ static void event_handler(void* arg, esp_event_base_t event_base, if (s_retry_num < WIFI_MAXIMUM_RETRY) { esp_wifi_connect(); s_retry_num++; - ESP_LOGI(TAG, "retry to connect to the AP"); + ESP_LOGI(SYSTEM_TAG, "retry to connect to the AP"); } else { xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); } - ESP_LOGI(TAG, "connect to the AP fail"); + 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(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip)); + ESP_LOGI(SYSTEM_TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip)); s_retry_num = 0; xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); } @@ -403,7 +366,7 @@ static void event_handler(void* arg, esp_event_base_t event_base, void configure_gpio_pins(void) { - ESP_LOGI(TAG, "Configuring GPIO pins..."); + ESP_LOGI(SYSTEM_TAG, "Configuring GPIO pins..."); uint64_t pin_mask = (1ULL << LED_PIN) | (1ULL << MOTOR_R_EN) | @@ -423,16 +386,16 @@ void configure_gpio_pins(void) gpio_set_level(MOTOR_R_EN, 0); gpio_set_level(MOTOR_L_EN, 0); - ESP_LOGI(TAG, "GPIO pins configured"); + ESP_LOGI(SYSTEM_TAG, "GPIO pins configured"); } void configure_pwm(void) { - ESP_LOGI(TAG, "Configuring PWM..."); + ESP_LOGI(SYSTEM_TAG, "Configuring PWM..."); ledc_timer_config_t timer_conf = { - .speed_mode = LEDC_LOW_SPEED_MODE, - .timer_num = LEDC_TIMER_0, + .speed_mode = PWM_SPEED_MODE, + .timer_num = PWM_TIMER, .duty_resolution = PWM_RESOLUTION, .freq_hz = PWM_FREQUENCY, .clk_cfg = LEDC_AUTO_CLK @@ -443,9 +406,9 @@ void configure_pwm(void) .channel = PWM_R_CHANNEL, .duty = 0, .gpio_num = PWM_R_PIN, - .speed_mode = LEDC_LOW_SPEED_MODE, + .speed_mode = PWM_SPEED_MODE, .hpoint = 0, - .timer_sel = LEDC_TIMER_0 + .timer_sel = PWM_TIMER }; ledc_channel_config(&channel_conf); @@ -453,42 +416,42 @@ void configure_pwm(void) channel_conf.gpio_num = PWM_L_PIN; ledc_channel_config(&channel_conf); - ESP_LOGI(TAG, "PWM configured"); + ESP_LOGI(SYSTEM_TAG, "PWM configured"); } // Apply PWM to motor based on current mode and speed static void apply_motor_pwm(int speed_percent) { - if (speed_percent < 0) speed_percent = 0; - if (speed_percent > 100) speed_percent = 100; + // Clamp speed to valid range using config macro + speed_percent = CLAMP_SPEED(speed_percent); - uint32_t duty = (speed_percent * 255) / 100; + uint32_t duty = SPEED_TO_DUTY(speed_percent); if (motor_state.mode == MOTOR_OFF || speed_percent == 0) { gpio_set_level(LED_PIN, 0); gpio_set_level(MOTOR_R_EN, 0); gpio_set_level(MOTOR_L_EN, 0); - ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL, 0); - ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL, 0); - ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL); - ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL); + ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, 0); + ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, 0); + ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); + ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); } else if (motor_state.mode == MOTOR_EXHAUST) { gpio_set_level(LED_PIN, 1); gpio_set_level(MOTOR_R_EN, 1); gpio_set_level(MOTOR_L_EN, 1); - ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL, duty); - ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL, 0); - ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL); - ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL); + ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, duty); + ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, 0); + ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); + ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); } else if (motor_state.mode == MOTOR_INTAKE) { gpio_set_level(LED_PIN, 1); gpio_set_level(MOTOR_R_EN, 1); gpio_set_level(MOTOR_L_EN, 1); - ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL, 0); - ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL, duty); - ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL); - ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL); + ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, 0); + ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, duty); + ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); + ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); } } @@ -509,7 +472,7 @@ static void motor_ramp_timer_callback(TimerHandle_t xTimer) { // Stop the timer xTimerStop(motor_state.ramp_timer, 0); - ESP_LOGI(TAG, "Ramping complete - Final speed: %d%%", motor_state.current_speed); + ESP_LOGI(SYSTEM_TAG, "Ramping complete - Final speed: %d%%", motor_state.current_speed); } else { // Continue ramping if (speed_diff > 0) { @@ -518,7 +481,7 @@ static void motor_ramp_timer_callback(TimerHandle_t xTimer) { motor_state.current_speed -= RAMP_STEP_SIZE; } - ESP_LOGD(TAG, "Ramping: %d%% (target: %d%%)", motor_state.current_speed, motor_state.target_speed); + MOTOR_LOGD(SYSTEM_TAG, "Ramping: %d%% (target: %d%%)", motor_state.current_speed, motor_state.target_speed); } apply_motor_pwm(motor_state.current_speed); @@ -526,7 +489,7 @@ static void motor_ramp_timer_callback(TimerHandle_t xTimer) { // Motor cooldown timer callback static void motor_cooldown_timer_callback(TimerHandle_t xTimer) { - ESP_LOGI(TAG, "Cooldown complete - Starting motor in %s mode at %d%%", + ESP_LOGI(SYSTEM_TAG, "Cooldown complete - Starting motor in %s mode at %d%%", motor_state.pending_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", motor_state.pending_speed); @@ -540,8 +503,8 @@ static void motor_cooldown_timer_callback(TimerHandle_t xTimer) { // Update cooldown remaining time (called periodically) static void update_cooldown_time(void) { if (motor_state.state == MOTOR_STATE_COOLDOWN && motor_state.cooldown_remaining_ms > 0) { - if (motor_state.cooldown_remaining_ms >= 1000) { - motor_state.cooldown_remaining_ms -= 1000; + if (motor_state.cooldown_remaining_ms >= STATUS_UPDATE_INTERVAL_MS) { + motor_state.cooldown_remaining_ms -= STATUS_UPDATE_INTERVAL_MS; } else { motor_state.cooldown_remaining_ms = 0; } @@ -550,6 +513,9 @@ static void update_cooldown_time(void) { // Start motor operation (internal function) static void start_motor_operation(motor_mode_t mode, int speed_percent) { + // Clamp speed using config macro + speed_percent = CLAMP_SPEED(speed_percent); + motor_state.mode = mode; motor_state.target_speed = speed_percent; motor_state.state = MOTOR_STATE_RAMPING; @@ -562,7 +528,7 @@ static void start_motor_operation(motor_mode_t mode, int speed_percent) { motor_state.state = MOTOR_STATE_IDLE; motor_state.ramping = false; apply_motor_pwm(0); - ESP_LOGI(TAG, "Motor stopped immediately"); + ESP_LOGI(SYSTEM_TAG, "Motor stopped immediately"); } else { // Save last ON state for future ON button use save_last_on_state(mode, speed_percent); @@ -572,7 +538,7 @@ static void start_motor_operation(motor_mode_t mode, int speed_percent) { int start_speed = (speed_percent < MIN_MOTOR_SPEED) ? speed_percent : MIN_MOTOR_SPEED; motor_state.current_speed = start_speed; apply_motor_pwm(start_speed); - ESP_LOGI(TAG, "Motor starting at %d%%, ramping to %d%%", start_speed, speed_percent); + ESP_LOGI(SYSTEM_TAG, "Motor starting at %d%%, ramping to %d%%", start_speed, speed_percent); } // Start ramping if needed @@ -607,18 +573,18 @@ void init_motor_ramping(void) { ); if (motor_state.ramp_timer == NULL || motor_state.cooldown_timer == NULL) { - ESP_LOGE(TAG, "Failed to create motor timers"); + ESP_LOGE(SYSTEM_TAG, "Failed to create motor timers"); } else { - ESP_LOGI(TAG, "Motor control system initialized with direction change safety"); + ESP_LOGI(SYSTEM_TAG, "Motor control system initialized with direction change safety"); } } void set_motor_speed(motor_mode_t mode, int speed_percent) { - if (speed_percent < 0) speed_percent = 0; - if (speed_percent > 100) speed_percent = 100; + // Clamp speed to valid range using config macro + speed_percent = CLAMP_SPEED(speed_percent); - ESP_LOGI(TAG, "Motor command: %s - Speed: %d%% (Current mode: %s, Current speed: %d%%, State: %d)", + ESP_LOGI(SYSTEM_TAG, "Motor command: %s - Speed: %d%% (Current mode: %s, Current speed: %d%%, State: %d)", mode == MOTOR_OFF ? "OFF" : (mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE"), speed_percent, motor_state.mode == MOTOR_OFF ? "OFF" : (motor_state.mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE"), @@ -628,32 +594,29 @@ void set_motor_speed(motor_mode_t mode, int speed_percent) // Track if user manually turned off if (mode == MOTOR_OFF && motor_state.mode != MOTOR_OFF) { motor_state.user_turned_off = true; - ESP_LOGI(TAG, "User manually turned OFF - will stay off after restart"); + ESP_LOGI(SYSTEM_TAG, "User manually turned OFF - will stay off after restart"); } else if (mode != MOTOR_OFF) { motor_state.user_turned_off = false; - ESP_LOGI(TAG, "Motor turned ON - will resume after power loss"); + ESP_LOGI(SYSTEM_TAG, "Motor turned ON - will resume after power loss"); } // If we're in cooldown, update the pending command if (motor_state.state == MOTOR_STATE_COOLDOWN) { motor_state.pending_mode = mode; motor_state.pending_speed = speed_percent; - ESP_LOGI(TAG, "Motor in cooldown - command queued for execution"); + ESP_LOGI(SYSTEM_TAG, "Motor in cooldown - command queued for execution"); save_motor_state_to_nvs(); // Save the pending state return; } - // Check if this is a direction change that requires cooldown + // Check if this is a direction change that requires cooldown using config macro bool requires_cooldown = false; if (motor_state.current_speed > 0 && motor_state.mode != MOTOR_OFF) { - if ((motor_state.mode == MOTOR_EXHAUST && mode == MOTOR_INTAKE) || - (motor_state.mode == MOTOR_INTAKE && mode == MOTOR_EXHAUST)) { - requires_cooldown = true; - } + requires_cooldown = IS_DIRECTION_CHANGE(motor_state.mode, mode); } if (requires_cooldown) { - ESP_LOGI(TAG, "Direction change detected - initiating safety cooldown sequence"); + ESP_LOGI(SYSTEM_TAG, "Direction change detected - initiating safety cooldown sequence"); // Stop any current ramping if (motor_state.ramping) { @@ -676,7 +639,7 @@ void set_motor_speed(motor_mode_t mode, int speed_percent) // Start cooldown timer xTimerStart(motor_state.cooldown_timer, 0); - ESP_LOGI(TAG, "Motor stopped for direction change - %d second cooldown started", + ESP_LOGI(SYSTEM_TAG, "Motor stopped for direction change - %d second cooldown started", DIRECTION_CHANGE_COOLDOWN_MS / 1000); // Save state including pending command @@ -723,7 +686,7 @@ static esp_err_t status_get_handler(httpd_req_t *req) // Update cooldown time before reporting update_cooldown_time(); - ESP_LOGI(TAG, "Status request - Mode: %d, Current: %d%%, Target: %d%%, State: %d, Ramping: %s", + ESP_LOGI(SYSTEM_TAG, "Status request - Mode: %d, Current: %d%%, Target: %d%%, State: %d, Ramping: %s", motor_state.mode, motor_state.current_speed, motor_state.target_speed, motor_state.state, motor_state.ramping ? "YES" : "NO"); @@ -782,7 +745,7 @@ static esp_err_t status_get_handler(httpd_req_t *req) // HTTP handler for fan control (POST /fan) static esp_err_t fan_post_handler(httpd_req_t *req) { - char buf[200]; + char buf[MAX_JSON_BUFFER_SIZE]; int ret, remaining = req->content_len; if (remaining >= sizeof(buf)) { @@ -799,11 +762,11 @@ static esp_err_t fan_post_handler(httpd_req_t *req) } buf[ret] = '\0'; - ESP_LOGI(TAG, "Received POST data: %s", buf); + ESP_LOGI(SYSTEM_TAG, "Received POST data: %s", buf); cJSON *json = cJSON_Parse(buf); if (json == NULL) { - ESP_LOGE(TAG, "JSON parsing failed"); + ESP_LOGE(SYSTEM_TAG, "JSON parsing failed"); httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON"); return ESP_FAIL; } @@ -812,7 +775,7 @@ static esp_err_t fan_post_handler(httpd_req_t *req) cJSON *speed_json = cJSON_GetObjectItem(json, "speed"); if (!cJSON_IsString(mode_json) || (!cJSON_IsNumber(speed_json) && !cJSON_IsString(speed_json))) { - ESP_LOGE(TAG, "JSON parsing failed - mode: %s, speed: %s", + ESP_LOGE(SYSTEM_TAG, "JSON parsing failed - mode: %s, speed: %s", mode_json ? (cJSON_IsString(mode_json) ? mode_json->valuestring : "not_string") : "null", speed_json ? (cJSON_IsNumber(speed_json) ? "number" : (cJSON_IsString(speed_json) ? speed_json->valuestring : "not_number_or_string")) : "null"); cJSON_Delete(json); @@ -838,7 +801,7 @@ static esp_err_t fan_post_handler(httpd_req_t *req) if (strcmp(mode_str, "on") == 0) { mode = motor_state.last_on_mode; speed = motor_state.last_on_speed; - ESP_LOGI(TAG, "ON button pressed - resuming %s @ %d%%", + ESP_LOGI(SYSTEM_TAG, "ON button pressed - resuming %s @ %d%%", mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", speed); } else if (strcmp(mode_str, "exhaust") == 0) { mode = MOTOR_EXHAUST; @@ -846,7 +809,7 @@ static esp_err_t fan_post_handler(httpd_req_t *req) mode = MOTOR_INTAKE; } - ESP_LOGI(TAG, "HTTP Request: mode=%s, speed=%d", mode_str, speed); + ESP_LOGI(SYSTEM_TAG, "HTTP Request: mode=%s, speed=%d", mode_str, speed); set_motor_speed(mode, speed); cJSON_Delete(json); @@ -868,13 +831,14 @@ static esp_err_t options_handler(httpd_req_t *req) static httpd_handle_t start_webserver(void) { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); - config.max_uri_handlers = 15; - config.recv_wait_timeout = 10; - config.send_wait_timeout = 10; + config.server_port = HTTP_SERVER_PORT; + config.max_uri_handlers = HTTP_MAX_URI_HANDLERS; + config.recv_wait_timeout = HTTP_RECV_TIMEOUT_SEC; + config.send_wait_timeout = HTTP_SEND_TIMEOUT_SEC; - ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port); + ESP_LOGI(SYSTEM_TAG, "Starting server on port: '%d'", config.server_port); if (httpd_start(&server, &config) == ESP_OK) { - ESP_LOGI(TAG, "Registering URI handlers"); + ESP_LOGI(SYSTEM_TAG, "Registering URI handlers"); // Root handler httpd_uri_t root = { @@ -923,7 +887,7 @@ static httpd_handle_t start_webserver(void) return server; } - ESP_LOGI(TAG, "Error starting server!"); + ESP_LOGI(SYSTEM_TAG, "Error starting server!"); return NULL; } @@ -966,7 +930,7 @@ void wifi_init_sta(void) ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); ESP_ERROR_CHECK(esp_wifi_start()); - ESP_LOGI(TAG, "wifi_init_sta finished."); + ESP_LOGI(SYSTEM_TAG, "wifi_init_sta finished."); EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, @@ -975,17 +939,17 @@ void wifi_init_sta(void) portMAX_DELAY); if (bits & WIFI_CONNECTED_BIT) { - ESP_LOGI(TAG, "connected to ap SSID:%s", WIFI_SSID); + ESP_LOGI(SYSTEM_TAG, "connected to ap SSID:%s", WIFI_SSID); } else if (bits & WIFI_FAIL_BIT) { - ESP_LOGI(TAG, "Failed to connect to SSID:%s", WIFI_SSID); + ESP_LOGI(SYSTEM_TAG, "Failed to connect to SSID:%s", WIFI_SSID); } else { - ESP_LOGE(TAG, "UNEXPECTED EVENT"); + ESP_LOGE(SYSTEM_TAG, "UNEXPECTED EVENT"); } } void app_main(void) { - ESP_LOGI(TAG, "Starting Maxxfan HTTP Controller with State Preservation!"); + ESP_LOGI(SYSTEM_TAG, "Starting Maxxfan HTTP Controller with State Preservation!"); // Initialize NVS esp_err_t ret = nvs_flash_init(); @@ -1006,44 +970,44 @@ void app_main(void) init_motor_ramping(); // Load saved state from NVS - ESP_LOGI(TAG, "Loading saved state..."); + ESP_LOGI(SYSTEM_TAG, "Loading saved state..."); load_motor_state_from_nvs(); - ESP_LOGI(TAG, "Connecting to WiFi network: %s", WIFI_SSID); + ESP_LOGI(SYSTEM_TAG, "Connecting to WiFi network: %s", WIFI_SSID); wifi_init_sta(); // Start HTTP server start_webserver(); // Restore motor state if needed (after WiFi is connected and server is running) - ESP_LOGI(TAG, "=== MOTOR STATE RESTORATION ==="); - ESP_LOGI(TAG, "Current motor state: mode=%d, target=%d%%, current=%d%%", + ESP_LOGI(SYSTEM_TAG, "=== MOTOR STATE RESTORATION ==="); + ESP_LOGI(SYSTEM_TAG, "Current motor state: mode=%d, target=%d%%, current=%d%%", motor_state.mode, motor_state.target_speed, motor_state.current_speed); if (motor_state.mode != MOTOR_OFF && motor_state.target_speed > 0) { - ESP_LOGI(TAG, "Restoring motor state: %s @ %d%%", + ESP_LOGI(SYSTEM_TAG, "Restoring motor state: %s @ %d%%", motor_state.mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", motor_state.target_speed); // Start the motor with current settings motor_state.current_speed = 0; // Start from 0 and ramp up start_motor_operation(motor_state.mode, motor_state.target_speed); - ESP_LOGI(TAG, "Motor restoration initiated"); + ESP_LOGI(SYSTEM_TAG, "Motor restoration initiated"); } else { - ESP_LOGI(TAG, "No motor state to restore - staying OFF"); + ESP_LOGI(SYSTEM_TAG, "No motor state to restore - staying OFF"); } - ESP_LOGI(TAG, "==============================="); + ESP_LOGI(SYSTEM_TAG, "==============================="); - ESP_LOGI(TAG, "=== Enhanced Maxxfan Controller Ready! ==="); - ESP_LOGI(TAG, "Features: State Preservation, Direction Safety, Motor Ramping, ON Button"); - ESP_LOGI(TAG, "Safety: 10-second cooldown for direction changes"); - ESP_LOGI(TAG, "Memory: Remembers settings after power loss (except watchdog resets)"); - ESP_LOGI(TAG, "Open your browser and go to: http://[ESP32_IP_ADDRESS]"); - ESP_LOGI(TAG, "Check the monitor output above for your IP address"); + ESP_LOGI(SYSTEM_TAG, "=== Enhanced Maxxfan Controller Ready! ==="); + ESP_LOGI(SYSTEM_TAG, "Features: State Preservation, Direction Safety, Motor Ramping, ON Button"); + ESP_LOGI(SYSTEM_TAG, "Safety: 10-second cooldown for direction changes"); + ESP_LOGI(SYSTEM_TAG, "Memory: Remembers settings after power loss (except watchdog resets)"); + 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"); // Main loop - reset watchdog periodically while (1) { feed_watchdog(); - vTaskDelay(pdMS_TO_TICKS(3000)); // Feed every 3 seconds (system default is usually 5s timeout) + vTaskDelay(pdMS_TO_TICKS(WATCHDOG_FEED_INTERVAL_MS)); } } \ No newline at end of file From f3fb4f4ac86d89a4ce8a88ea0f1f5cca78eab103 Mon Sep 17 00:00:00 2001 From: Stephen Minakian Date: Wed, 9 Jul 2025 17:29:27 -0600 Subject: [PATCH 2/4] Refactor motor control --- main/CMakeLists.txt | 4 +- main/maxxfan-controller.c | 532 +++++++------------------------------- main/motor_control.c | 411 +++++++++++++++++++++++++++++ main/motor_control.h | 166 ++++++++++++ 4 files changed, 670 insertions(+), 443 deletions(-) create mode 100644 main/motor_control.c create mode 100644 main/motor_control.h diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 436a1be..b02e8fd 100755 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,2 +1,2 @@ -idf_component_register(SRCS "maxxfan-controller.c" - INCLUDE_DIRS ".") +idf_component_register(SRCS "maxxfan-controller.c" "motor_control.c" + INCLUDE_DIRS ".") \ No newline at end of file diff --git a/main/maxxfan-controller.c b/main/maxxfan-controller.c index ca94ed3..cd23629 100755 --- a/main/maxxfan-controller.c +++ b/main/maxxfan-controller.c @@ -3,7 +3,6 @@ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" -#include "freertos/timers.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" @@ -12,66 +11,16 @@ #include "esp_task_wdt.h" #include "nvs_flash.h" #include "nvs.h" -#include "driver/gpio.h" -#include "driver/ledc.h" #include "cJSON.h" -// Project configuration +// Project modules #include "config.h" +#include "motor_control.h" // WiFi event group static EventGroupHandle_t s_wifi_event_group; static int s_retry_num = 0; -// Motor control -typedef enum { - MOTOR_OFF, - MOTOR_EXHAUST, - MOTOR_INTAKE -} motor_mode_t; - -typedef enum { - MOTOR_STATE_IDLE, // Motor is off or running normally - MOTOR_STATE_RAMPING, // Motor is ramping up/down - MOTOR_STATE_STOPPING, // Motor is stopping for direction change - MOTOR_STATE_COOLDOWN, // Motor is in cooldown period - MOTOR_STATE_RESTARTING // Motor is restarting after cooldown -} motor_state_enum_t; - -typedef struct { - motor_mode_t mode; - motor_mode_t pending_mode; // Mode to switch to after cooldown - int target_speed; - int pending_speed; // Speed to set after cooldown - int current_speed; - motor_state_enum_t state; - bool ramping; - TimerHandle_t ramp_timer; - TimerHandle_t cooldown_timer; - uint32_t cooldown_remaining_ms; // For status reporting - - // State preservation - motor_mode_t last_on_mode; // Last non-OFF mode for ON button - int last_on_speed; // Last non-zero speed for ON button - bool user_turned_off; // Track if user manually turned off -} motor_state_t; - -static motor_state_t motor_state = { - .mode = MOTOR_OFF, - .pending_mode = MOTOR_OFF, - .target_speed = 0, - .pending_speed = 0, - .current_speed = 0, - .state = MOTOR_STATE_IDLE, - .ramping = false, - .ramp_timer = NULL, - .cooldown_timer = NULL, - .cooldown_remaining_ms = 0, - .last_on_mode = MOTOR_EXHAUST, // Default to exhaust for ON button - .last_on_speed = 50, // Default to 50% for ON button - .user_turned_off = false -}; - // HTTP server handle static httpd_handle_t server = NULL; @@ -136,14 +85,9 @@ static const char* html_page = "document.addEventListener('DOMContentLoaded',function(){getStatus();startUpdates()})"; // Forward declarations -static void motor_ramp_timer_callback(TimerHandle_t xTimer); -static void motor_cooldown_timer_callback(TimerHandle_t xTimer); -static void apply_motor_pwm(int speed_percent); -static void start_motor_operation(motor_mode_t mode, int speed_percent); static esp_err_t save_motor_state_to_nvs(void); static esp_err_t load_motor_state_from_nvs(void); static bool is_watchdog_reset(void); -static void save_last_on_state(motor_mode_t mode, int speed); // Initialize watchdog timer void init_watchdog(void) { @@ -194,29 +138,36 @@ static esp_err_t save_motor_state_to_nvs(void) { return err; } + // Get current motor state + const motor_state_t* state = motor_get_state(); + motor_mode_t last_on_mode; + int last_on_speed; + motor_get_last_on_state(&last_on_mode, &last_on_speed); + bool user_turned_off = motor_get_user_turned_off(); + ESP_LOGI(SYSTEM_TAG, "=== SAVING STATE TO NVS ==="); ESP_LOGI(SYSTEM_TAG, "Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", - motor_state.mode, motor_state.target_speed, - motor_state.last_on_mode, motor_state.last_on_speed, - motor_state.user_turned_off ? "YES" : "NO"); + state->mode, state->target_speed, + last_on_mode, last_on_speed, + user_turned_off ? "YES" : "NO"); // Save current motor state - err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)motor_state.mode); + err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)state->mode); if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_SPEED, (uint8_t)motor_state.target_speed); + err = nvs_set_u8(nvs_handle, NVS_KEY_SPEED, (uint8_t)state->target_speed); } // Save last ON state if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, (uint8_t)motor_state.last_on_mode); + err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, (uint8_t)last_on_mode); } if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, (uint8_t)motor_state.last_on_speed); + err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, (uint8_t)last_on_speed); } // Save power state (whether user turned off manually) if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_POWER_STATE, motor_state.user_turned_off ? 1 : 0); + err = nvs_set_u8(nvs_handle, NVS_KEY_POWER_STATE, user_turned_off ? 1 : 0); } if (err == ESP_OK) { @@ -266,13 +217,13 @@ static esp_err_t load_motor_state_from_nvs(void) { if (stored_last_mode < MOTOR_EXHAUST || stored_last_mode > MOTOR_INTAKE) stored_last_mode = MOTOR_EXHAUST; if (!IS_VALID_SPEED(stored_last_speed)) stored_last_speed = 50; - motor_state.last_on_mode = (motor_mode_t)stored_last_mode; - motor_state.last_on_speed = stored_last_speed; - motor_state.user_turned_off = (stored_power_state == 1); + // Set the last ON state in motor control module + motor_set_last_on_state((motor_mode_t)stored_last_mode, stored_last_speed); + motor_set_user_turned_off(stored_power_state == 1); ESP_LOGI(SYSTEM_TAG, "Loaded state from NVS - Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", - stored_mode, stored_speed, motor_state.last_on_mode, motor_state.last_on_speed, - motor_state.user_turned_off ? "YES" : "NO"); + stored_mode, stored_speed, stored_last_mode, stored_last_speed, + stored_power_state ? "YES" : "NO"); // Check reset reason to decide whether to restore state bool was_watchdog_reset = is_watchdog_reset(); @@ -293,34 +244,28 @@ static esp_err_t load_motor_state_from_nvs(void) { reset_reason == ESP_RST_SDIO ? "SDIO" : "UNKNOWN"); ESP_LOGI(SYSTEM_TAG, "Watchdog reset: %s", was_watchdog_reset ? "YES" : "NO"); ESP_LOGI(SYSTEM_TAG, "Stored mode: %d, speed: %d", stored_mode, stored_speed); - ESP_LOGI(SYSTEM_TAG, "User turned off: %s", motor_state.user_turned_off ? "YES" : "NO"); + ESP_LOGI(SYSTEM_TAG, "User turned off: %s", stored_power_state ? "YES" : "NO"); ESP_LOGI(SYSTEM_TAG, "===================="); + // Store the restored state for potential motor restoration if (was_watchdog_reset) { // True watchdog reset (TASK_WDT or INT_WDT) - don't restore state, start fresh ESP_LOGI(SYSTEM_TAG, "⚠️ TRUE watchdog reset detected - starting in OFF state for safety"); - motor_state.mode = MOTOR_OFF; - motor_state.target_speed = 0; - motor_state.current_speed = 0; - motor_state.user_turned_off = false; // Reset user off flag - } else if (motor_state.user_turned_off) { + // Motor module is already initialized in OFF state, no action needed + } else if (stored_power_state) { // User manually turned off - stay off ESP_LOGI(SYSTEM_TAG, "🔒 User had turned off manually - staying OFF"); - motor_state.mode = MOTOR_OFF; - motor_state.target_speed = 0; - motor_state.current_speed = 0; + // Motor module is already initialized in OFF state, no action needed } else if (stored_mode != MOTOR_OFF && stored_speed > 0) { // Normal power loss or general WDT (which can be power-related) - restore previous state ESP_LOGI(SYSTEM_TAG, "🔋 Power restored - will resume previous state: %s @ %d%%", stored_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", stored_speed); - motor_state.mode = (motor_mode_t)stored_mode; - motor_state.target_speed = stored_speed; - motor_state.current_speed = 0; // Always start ramping from 0 + + // Set the motor to the restored state (will be applied after initialization) + motor_set_speed((motor_mode_t)stored_mode, stored_speed); } else { ESP_LOGI(SYSTEM_TAG, "❌ No valid state to restore (mode=%d, speed=%d)", stored_mode, stored_speed); - motor_state.mode = MOTOR_OFF; - motor_state.target_speed = 0; - motor_state.current_speed = 0; + // Motor module is already initialized in OFF state, no action needed } } else { ESP_LOGI(SYSTEM_TAG, "No saved state found, using defaults"); @@ -331,16 +276,6 @@ static esp_err_t load_motor_state_from_nvs(void) { return err; } -// Save the last ON state (for ON button functionality) -static void save_last_on_state(motor_mode_t mode, int speed) { - if (mode != MOTOR_OFF && speed > 0) { - motor_state.last_on_mode = mode; - motor_state.last_on_speed = speed; - ESP_LOGI(SYSTEM_TAG, "Last ON state updated: %s @ %d%%", - mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", speed); - } -} - // WiFi event handler static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) @@ -364,305 +299,6 @@ static void event_handler(void* arg, esp_event_base_t event_base, } } -void configure_gpio_pins(void) -{ - ESP_LOGI(SYSTEM_TAG, "Configuring GPIO pins..."); - - uint64_t pin_mask = (1ULL << LED_PIN) | - (1ULL << MOTOR_R_EN) | - (1ULL << MOTOR_L_EN); - - gpio_config_t io_conf = { - .pin_bit_mask = pin_mask, - .mode = GPIO_MODE_OUTPUT, - .pull_up_en = GPIO_PULLUP_DISABLE, - .pull_down_en = GPIO_PULLDOWN_DISABLE, - .intr_type = GPIO_INTR_DISABLE - }; - - gpio_config(&io_conf); - - gpio_set_level(LED_PIN, 0); - gpio_set_level(MOTOR_R_EN, 0); - gpio_set_level(MOTOR_L_EN, 0); - - ESP_LOGI(SYSTEM_TAG, "GPIO pins configured"); -} - -void configure_pwm(void) -{ - ESP_LOGI(SYSTEM_TAG, "Configuring PWM..."); - - ledc_timer_config_t timer_conf = { - .speed_mode = PWM_SPEED_MODE, - .timer_num = PWM_TIMER, - .duty_resolution = PWM_RESOLUTION, - .freq_hz = PWM_FREQUENCY, - .clk_cfg = LEDC_AUTO_CLK - }; - ledc_timer_config(&timer_conf); - - ledc_channel_config_t channel_conf = { - .channel = PWM_R_CHANNEL, - .duty = 0, - .gpio_num = PWM_R_PIN, - .speed_mode = PWM_SPEED_MODE, - .hpoint = 0, - .timer_sel = PWM_TIMER - }; - ledc_channel_config(&channel_conf); - - channel_conf.channel = PWM_L_CHANNEL; - channel_conf.gpio_num = PWM_L_PIN; - ledc_channel_config(&channel_conf); - - ESP_LOGI(SYSTEM_TAG, "PWM configured"); -} - -// Apply PWM to motor based on current mode and speed -static void apply_motor_pwm(int speed_percent) { - // Clamp speed to valid range using config macro - speed_percent = CLAMP_SPEED(speed_percent); - - uint32_t duty = SPEED_TO_DUTY(speed_percent); - - if (motor_state.mode == MOTOR_OFF || speed_percent == 0) { - gpio_set_level(LED_PIN, 0); - gpio_set_level(MOTOR_R_EN, 0); - gpio_set_level(MOTOR_L_EN, 0); - ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, 0); - ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, 0); - ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); - ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); - - } else if (motor_state.mode == MOTOR_EXHAUST) { - gpio_set_level(LED_PIN, 1); - gpio_set_level(MOTOR_R_EN, 1); - gpio_set_level(MOTOR_L_EN, 1); - ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, duty); - ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, 0); - ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); - ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); - - } else if (motor_state.mode == MOTOR_INTAKE) { - gpio_set_level(LED_PIN, 1); - gpio_set_level(MOTOR_R_EN, 1); - gpio_set_level(MOTOR_L_EN, 1); - ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, 0); - ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, duty); - ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); - ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); - } -} - -// Motor ramp timer callback -static void motor_ramp_timer_callback(TimerHandle_t xTimer) { - if (motor_state.state != MOTOR_STATE_RAMPING) { - return; - } - - int speed_diff = motor_state.target_speed - motor_state.current_speed; - - if (abs(speed_diff) <= RAMP_STEP_SIZE) { - // Close enough to target, finish ramping - motor_state.current_speed = motor_state.target_speed; - motor_state.ramping = false; - motor_state.state = MOTOR_STATE_IDLE; - - // Stop the timer - xTimerStop(motor_state.ramp_timer, 0); - - ESP_LOGI(SYSTEM_TAG, "Ramping complete - Final speed: %d%%", motor_state.current_speed); - } else { - // Continue ramping - if (speed_diff > 0) { - motor_state.current_speed += RAMP_STEP_SIZE; - } else { - motor_state.current_speed -= RAMP_STEP_SIZE; - } - - MOTOR_LOGD(SYSTEM_TAG, "Ramping: %d%% (target: %d%%)", motor_state.current_speed, motor_state.target_speed); - } - - apply_motor_pwm(motor_state.current_speed); -} - -// Motor cooldown timer callback -static void motor_cooldown_timer_callback(TimerHandle_t xTimer) { - ESP_LOGI(SYSTEM_TAG, "Cooldown complete - Starting motor in %s mode at %d%%", - motor_state.pending_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", - motor_state.pending_speed); - - // Reset cooldown tracking - motor_state.cooldown_remaining_ms = 0; - - // Start the motor in the pending mode - start_motor_operation(motor_state.pending_mode, motor_state.pending_speed); -} - -// Update cooldown remaining time (called periodically) -static void update_cooldown_time(void) { - if (motor_state.state == MOTOR_STATE_COOLDOWN && motor_state.cooldown_remaining_ms > 0) { - if (motor_state.cooldown_remaining_ms >= STATUS_UPDATE_INTERVAL_MS) { - motor_state.cooldown_remaining_ms -= STATUS_UPDATE_INTERVAL_MS; - } else { - motor_state.cooldown_remaining_ms = 0; - } - } -} - -// Start motor operation (internal function) -static void start_motor_operation(motor_mode_t mode, int speed_percent) { - // Clamp speed using config macro - speed_percent = CLAMP_SPEED(speed_percent); - - motor_state.mode = mode; - motor_state.target_speed = speed_percent; - motor_state.state = MOTOR_STATE_RAMPING; - motor_state.ramping = true; - - if (mode == MOTOR_OFF || speed_percent == 0) { - // Immediate stop - motor_state.current_speed = 0; - motor_state.target_speed = 0; - motor_state.state = MOTOR_STATE_IDLE; - motor_state.ramping = false; - apply_motor_pwm(0); - ESP_LOGI(SYSTEM_TAG, "Motor stopped immediately"); - } else { - // Save last ON state for future ON button use - save_last_on_state(mode, speed_percent); - - // Start from minimum speed if currently off - if (motor_state.current_speed == 0) { - int start_speed = (speed_percent < MIN_MOTOR_SPEED) ? speed_percent : MIN_MOTOR_SPEED; - motor_state.current_speed = start_speed; - apply_motor_pwm(start_speed); - ESP_LOGI(SYSTEM_TAG, "Motor starting at %d%%, ramping to %d%%", start_speed, speed_percent); - } - - // Start ramping if needed - if (motor_state.current_speed != motor_state.target_speed) { - xTimerStart(motor_state.ramp_timer, 0); - } else { - motor_state.state = MOTOR_STATE_IDLE; - motor_state.ramping = false; - } - } - - // Save state to NVS after any change - save_motor_state_to_nvs(); -} - -// Initialize motor ramping system -void init_motor_ramping(void) { - motor_state.ramp_timer = xTimerCreate( - "MotorRampTimer", // Timer name - pdMS_TO_TICKS(RAMP_STEP_MS), // Timer period - pdTRUE, // Auto-reload - (void*)0, // Timer ID - motor_ramp_timer_callback // Callback function - ); - - motor_state.cooldown_timer = xTimerCreate( - "MotorCooldownTimer", // Timer name - pdMS_TO_TICKS(DIRECTION_CHANGE_COOLDOWN_MS), // Timer period - pdFALSE, // One-shot - (void*)0, // Timer ID - motor_cooldown_timer_callback // Callback function - ); - - if (motor_state.ramp_timer == NULL || motor_state.cooldown_timer == NULL) { - ESP_LOGE(SYSTEM_TAG, "Failed to create motor timers"); - } else { - ESP_LOGI(SYSTEM_TAG, "Motor control system initialized with direction change safety"); - } -} - -void set_motor_speed(motor_mode_t mode, int speed_percent) -{ - // Clamp speed to valid range using config macro - speed_percent = CLAMP_SPEED(speed_percent); - - ESP_LOGI(SYSTEM_TAG, "Motor command: %s - Speed: %d%% (Current mode: %s, Current speed: %d%%, State: %d)", - mode == MOTOR_OFF ? "OFF" : (mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE"), - speed_percent, - motor_state.mode == MOTOR_OFF ? "OFF" : (motor_state.mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE"), - motor_state.current_speed, - motor_state.state); - - // Track if user manually turned off - if (mode == MOTOR_OFF && motor_state.mode != MOTOR_OFF) { - motor_state.user_turned_off = true; - ESP_LOGI(SYSTEM_TAG, "User manually turned OFF - will stay off after restart"); - } else if (mode != MOTOR_OFF) { - motor_state.user_turned_off = false; - ESP_LOGI(SYSTEM_TAG, "Motor turned ON - will resume after power loss"); - } - - // If we're in cooldown, update the pending command - if (motor_state.state == MOTOR_STATE_COOLDOWN) { - motor_state.pending_mode = mode; - motor_state.pending_speed = speed_percent; - ESP_LOGI(SYSTEM_TAG, "Motor in cooldown - command queued for execution"); - save_motor_state_to_nvs(); // Save the pending state - return; - } - - // Check if this is a direction change that requires cooldown using config macro - bool requires_cooldown = false; - if (motor_state.current_speed > 0 && motor_state.mode != MOTOR_OFF) { - requires_cooldown = IS_DIRECTION_CHANGE(motor_state.mode, mode); - } - - if (requires_cooldown) { - ESP_LOGI(SYSTEM_TAG, "Direction change detected - initiating safety cooldown sequence"); - - // Stop any current ramping - if (motor_state.ramping) { - xTimerStop(motor_state.ramp_timer, 0); - motor_state.ramping = false; - } - - // Stop the motor immediately - motor_state.mode = MOTOR_OFF; - motor_state.current_speed = 0; - motor_state.target_speed = 0; - motor_state.state = MOTOR_STATE_COOLDOWN; - motor_state.cooldown_remaining_ms = DIRECTION_CHANGE_COOLDOWN_MS; - apply_motor_pwm(0); - - // Store the pending command - motor_state.pending_mode = mode; - motor_state.pending_speed = speed_percent; - - // Start cooldown timer - xTimerStart(motor_state.cooldown_timer, 0); - - ESP_LOGI(SYSTEM_TAG, "Motor stopped for direction change - %d second cooldown started", - DIRECTION_CHANGE_COOLDOWN_MS / 1000); - - // Save state including pending command - save_motor_state_to_nvs(); - } else { - // No direction change required, proceed normally - - // Stop any current ramping - if (motor_state.ramping) { - xTimerStop(motor_state.ramp_timer, 0); - motor_state.ramping = false; - } - - // Stop cooldown timer if running - if (motor_state.state == MOTOR_STATE_COOLDOWN) { - xTimerStop(motor_state.cooldown_timer, 0); - motor_state.cooldown_remaining_ms = 0; - } - - start_motor_operation(mode, speed_percent); - } -} - // Helper function to set CORS headers static void set_cors_headers(httpd_req_t *req) { httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); @@ -684,11 +320,17 @@ static esp_err_t root_get_handler(httpd_req_t *req) static esp_err_t status_get_handler(httpd_req_t *req) { // Update cooldown time before reporting - update_cooldown_time(); + motor_update_cooldown_time(); - ESP_LOGI(SYSTEM_TAG, "Status request - Mode: %d, Current: %d%%, Target: %d%%, State: %d, Ramping: %s", - motor_state.mode, motor_state.current_speed, motor_state.target_speed, - motor_state.state, motor_state.ramping ? "YES" : "NO"); + // Get current motor state + const motor_state_t* state = motor_get_state(); + motor_mode_t last_on_mode; + int 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", + motor_mode_to_string(state->mode), state->current_speed, state->target_speed, + motor_state_to_string(state->state), state->ramping ? "YES" : "NO"); set_cors_headers(req); httpd_resp_set_type(req, "application/json"); @@ -696,11 +338,11 @@ static esp_err_t status_get_handler(httpd_req_t *req) cJSON *json = cJSON_CreateObject(); const char* mode_str = "off"; - if (motor_state.mode == MOTOR_EXHAUST) mode_str = "exhaust"; - else if (motor_state.mode == MOTOR_INTAKE) mode_str = "intake"; + if (state->mode == MOTOR_EXHAUST) mode_str = "exhaust"; + else if (state->mode == MOTOR_INTAKE) mode_str = "intake"; const char* state_str = "idle"; - switch (motor_state.state) { + switch (state->state) { case MOTOR_STATE_RAMPING: state_str = "ramping"; break; case MOTOR_STATE_STOPPING: state_str = "stopping"; break; case MOTOR_STATE_COOLDOWN: state_str = "cooldown"; break; @@ -709,25 +351,25 @@ static esp_err_t status_get_handler(httpd_req_t *req) } const char* last_on_mode_str = "exhaust"; - if (motor_state.last_on_mode == MOTOR_INTAKE) last_on_mode_str = "intake"; + if (last_on_mode == MOTOR_INTAKE) last_on_mode_str = "intake"; cJSON_AddStringToObject(json, "mode", mode_str); - cJSON_AddNumberToObject(json, "current_speed", motor_state.current_speed); - cJSON_AddNumberToObject(json, "target_speed", motor_state.target_speed); + cJSON_AddNumberToObject(json, "current_speed", state->current_speed); + cJSON_AddNumberToObject(json, "target_speed", state->target_speed); cJSON_AddStringToObject(json, "state", state_str); - cJSON_AddBoolToObject(json, "ramping", motor_state.ramping); - cJSON_AddNumberToObject(json, "cooldown_remaining", motor_state.cooldown_remaining_ms); + cJSON_AddBoolToObject(json, "ramping", state->ramping); + cJSON_AddNumberToObject(json, "cooldown_remaining", state->cooldown_remaining_ms); cJSON_AddStringToObject(json, "last_on_mode", last_on_mode_str); - cJSON_AddNumberToObject(json, "last_on_speed", motor_state.last_on_speed); + cJSON_AddNumberToObject(json, "last_on_speed", last_on_speed); // Add pending command info if in cooldown - if (motor_state.state == MOTOR_STATE_COOLDOWN) { + if (state->state == MOTOR_STATE_COOLDOWN) { const char* pending_mode_str = "off"; - if (motor_state.pending_mode == MOTOR_EXHAUST) pending_mode_str = "exhaust"; - else if (motor_state.pending_mode == MOTOR_INTAKE) pending_mode_str = "intake"; + if (state->pending_mode == MOTOR_EXHAUST) pending_mode_str = "exhaust"; + else if (state->pending_mode == MOTOR_INTAKE) pending_mode_str = "intake"; cJSON_AddStringToObject(json, "pending_mode", pending_mode_str); - cJSON_AddNumberToObject(json, "pending_speed", motor_state.pending_speed); + cJSON_AddNumberToObject(json, "pending_speed", state->pending_speed); } char *json_string = cJSON_Print(json); @@ -799,10 +441,14 @@ static esp_err_t fan_post_handler(httpd_req_t *req) // Handle special "ON" command - resume last settings if (strcmp(mode_str, "on") == 0) { - mode = motor_state.last_on_mode; - speed = motor_state.last_on_speed; - ESP_LOGI(SYSTEM_TAG, "ON button pressed - resuming %s @ %d%%", - mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", speed); + ESP_LOGI(SYSTEM_TAG, "ON button pressed - resuming last state"); + motor_resume_last_state(); + + // Save state after ON button + save_motor_state_to_nvs(); + + cJSON_Delete(json); + return status_get_handler(req); } else if (strcmp(mode_str, "exhaust") == 0) { mode = MOTOR_EXHAUST; } else if (strcmp(mode_str, "intake") == 0) { @@ -810,7 +456,10 @@ static esp_err_t fan_post_handler(httpd_req_t *req) } ESP_LOGI(SYSTEM_TAG, "HTTP Request: mode=%s, speed=%d", mode_str, speed); - set_motor_speed(mode, speed); + motor_set_speed(mode, speed); + + // Save state after any motor command + save_motor_state_to_nvs(); cJSON_Delete(json); @@ -962,14 +611,15 @@ void app_main(void) // Initialize watchdog timer init_watchdog(); - // Configure hardware - configure_gpio_pins(); - configure_pwm(); + // Initialize motor control system + ESP_LOGI(SYSTEM_TAG, "Initializing motor control system..."); + ret = motor_control_init(); + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to initialize motor control: %s", esp_err_to_name(ret)); + return; + } - // Initialize motor ramping system - init_motor_ramping(); - - // Load saved state from NVS + // Load saved state from NVS and potentially restore motor state ESP_LOGI(SYSTEM_TAG, "Loading saved state..."); load_motor_state_from_nvs(); @@ -979,35 +629,35 @@ void app_main(void) // Start HTTP server start_webserver(); - // Restore motor state if needed (after WiFi is connected and server is running) - ESP_LOGI(SYSTEM_TAG, "=== MOTOR STATE RESTORATION ==="); - ESP_LOGI(SYSTEM_TAG, "Current motor state: mode=%d, target=%d%%, current=%d%%", - motor_state.mode, motor_state.target_speed, motor_state.current_speed); + // Report final motor state after initialization + const motor_state_t* final_state = motor_get_state(); + ESP_LOGI(SYSTEM_TAG, "=== MOTOR STATE AFTER INITIALIZATION ==="); + ESP_LOGI(SYSTEM_TAG, "Final motor state: mode=%s, target=%d%%, current=%d%%, state=%s", + motor_mode_to_string(final_state->mode), final_state->target_speed, + final_state->current_speed, motor_state_to_string(final_state->state)); - if (motor_state.mode != MOTOR_OFF && motor_state.target_speed > 0) { - ESP_LOGI(SYSTEM_TAG, "Restoring motor state: %s @ %d%%", - motor_state.mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", - motor_state.target_speed); - - // Start the motor with current settings - motor_state.current_speed = 0; // Start from 0 and ramp up - start_motor_operation(motor_state.mode, motor_state.target_speed); - ESP_LOGI(SYSTEM_TAG, "Motor restoration initiated"); + if (final_state->mode != MOTOR_OFF && final_state->target_speed > 0) { + ESP_LOGI(SYSTEM_TAG, "Motor restored to: %s @ %d%%", + motor_mode_to_string(final_state->mode), final_state->target_speed); } else { - ESP_LOGI(SYSTEM_TAG, "No motor state to restore - staying OFF"); + ESP_LOGI(SYSTEM_TAG, "Motor remains OFF"); } - ESP_LOGI(SYSTEM_TAG, "==============================="); + ESP_LOGI(SYSTEM_TAG, "======================================="); ESP_LOGI(SYSTEM_TAG, "=== Enhanced Maxxfan Controller Ready! ==="); ESP_LOGI(SYSTEM_TAG, "Features: State Preservation, Direction Safety, Motor Ramping, ON Button"); - ESP_LOGI(SYSTEM_TAG, "Safety: 10-second cooldown for direction changes"); + 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, "Open your browser and go to: http://[ESP32_IP_ADDRESS]"); ESP_LOGI(SYSTEM_TAG, "Check the monitor output above for your IP address"); - // Main loop - reset watchdog periodically + // Main loop - reset watchdog periodically and update motor cooldown while (1) { feed_watchdog(); + + // Update motor cooldown time for status reporting + motor_update_cooldown_time(); + vTaskDelay(pdMS_TO_TICKS(WATCHDOG_FEED_INTERVAL_MS)); } } \ No newline at end of file diff --git a/main/motor_control.c b/main/motor_control.c new file mode 100644 index 0000000..5226b8c --- /dev/null +++ b/main/motor_control.c @@ -0,0 +1,411 @@ +#include "motor_control.h" +#include "config.h" +#include "esp_log.h" +#include "driver/gpio.h" +#include "driver/ledc.h" +#include + +// Private variables +static motor_state_t motor_state = { + .mode = MOTOR_OFF, + .pending_mode = MOTOR_OFF, + .target_speed = 0, + .pending_speed = 0, + .current_speed = 0, + .state = MOTOR_STATE_IDLE, + .ramping = false, + .ramp_timer = NULL, + .cooldown_timer = NULL, + .cooldown_remaining_ms = 0, + .last_on_mode = MOTOR_EXHAUST, // Default to exhaust for ON button + .last_on_speed = 50, // Default to 50% for ON button + .user_turned_off = false +}; + +// Forward declarations for private functions +static void apply_motor_pwm(int speed_percent); +static void start_motor_operation(motor_mode_t mode, int speed_percent); +static void save_last_on_state(motor_mode_t mode, int speed); +static void motor_ramp_timer_callback(TimerHandle_t xTimer); +static void motor_cooldown_timer_callback(TimerHandle_t xTimer); + +// Private function: Apply PWM to motor based on current mode and speed +static void apply_motor_pwm(int speed_percent) { + // Clamp speed to valid range using config macro + speed_percent = CLAMP_SPEED(speed_percent); + + uint32_t duty = SPEED_TO_DUTY(speed_percent); + + if (motor_state.mode == MOTOR_OFF || speed_percent == 0) { + gpio_set_level(LED_PIN, 0); + gpio_set_level(MOTOR_R_EN, 0); + gpio_set_level(MOTOR_L_EN, 0); + ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, 0); + ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, 0); + ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); + ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); + + } else if (motor_state.mode == MOTOR_EXHAUST) { + gpio_set_level(LED_PIN, 1); + gpio_set_level(MOTOR_R_EN, 1); + gpio_set_level(MOTOR_L_EN, 1); + ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, duty); + ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, 0); + ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); + ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); + + } else if (motor_state.mode == MOTOR_INTAKE) { + gpio_set_level(LED_PIN, 1); + gpio_set_level(MOTOR_R_EN, 1); + gpio_set_level(MOTOR_L_EN, 1); + ledc_set_duty(PWM_SPEED_MODE, PWM_R_CHANNEL, 0); + ledc_set_duty(PWM_SPEED_MODE, PWM_L_CHANNEL, duty); + ledc_update_duty(PWM_SPEED_MODE, PWM_R_CHANNEL); + ledc_update_duty(PWM_SPEED_MODE, PWM_L_CHANNEL); + } +} + +// Private function: Motor ramp timer callback +static void motor_ramp_timer_callback(TimerHandle_t xTimer) { + if (motor_state.state != MOTOR_STATE_RAMPING) { + return; + } + + int speed_diff = motor_state.target_speed - motor_state.current_speed; + + if (abs(speed_diff) <= RAMP_STEP_SIZE) { + // Close enough to target, finish ramping + motor_state.current_speed = motor_state.target_speed; + motor_state.ramping = false; + motor_state.state = MOTOR_STATE_IDLE; + + // Stop the timer + xTimerStop(motor_state.ramp_timer, 0); + + ESP_LOGI(SYSTEM_TAG, "Ramping complete - Final speed: %d%%", motor_state.current_speed); + } else { + // Continue ramping + if (speed_diff > 0) { + motor_state.current_speed += RAMP_STEP_SIZE; + } else { + motor_state.current_speed -= RAMP_STEP_SIZE; + } + + MOTOR_LOGD(SYSTEM_TAG, "Ramping: %d%% (target: %d%%)", motor_state.current_speed, motor_state.target_speed); + } + + apply_motor_pwm(motor_state.current_speed); +} + +// Private function: Motor cooldown timer callback +static void motor_cooldown_timer_callback(TimerHandle_t xTimer) { + ESP_LOGI(SYSTEM_TAG, "Cooldown complete - Starting motor in %s mode at %d%%", + motor_state.pending_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", + motor_state.pending_speed); + + // Reset cooldown tracking + motor_state.cooldown_remaining_ms = 0; + + // Start the motor in the pending mode + start_motor_operation(motor_state.pending_mode, motor_state.pending_speed); +} + +// Private function: Save the last ON state (for ON button functionality) +static void save_last_on_state(motor_mode_t mode, int speed) { + if (mode != MOTOR_OFF && speed > 0) { + motor_state.last_on_mode = mode; + motor_state.last_on_speed = speed; + ESP_LOGI(SYSTEM_TAG, "Last ON state updated: %s @ %d%%", + mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", speed); + } +} + +// Private function: Start motor operation (internal function) +static void start_motor_operation(motor_mode_t mode, int speed_percent) { + // Clamp speed using config macro + speed_percent = CLAMP_SPEED(speed_percent); + + motor_state.mode = mode; + motor_state.target_speed = speed_percent; + motor_state.state = MOTOR_STATE_RAMPING; + motor_state.ramping = true; + + if (mode == MOTOR_OFF || speed_percent == 0) { + // Immediate stop + motor_state.current_speed = 0; + motor_state.target_speed = 0; + motor_state.state = MOTOR_STATE_IDLE; + motor_state.ramping = false; + apply_motor_pwm(0); + ESP_LOGI(SYSTEM_TAG, "Motor stopped immediately"); + } else { + // Save last ON state for future ON button use + save_last_on_state(mode, speed_percent); + + // Start from minimum speed if currently off + if (motor_state.current_speed == 0) { + int start_speed = (speed_percent < MIN_MOTOR_SPEED) ? speed_percent : MIN_MOTOR_SPEED; + motor_state.current_speed = start_speed; + apply_motor_pwm(start_speed); + ESP_LOGI(SYSTEM_TAG, "Motor starting at %d%%, ramping to %d%%", start_speed, speed_percent); + } + + // Start ramping if needed + if (motor_state.current_speed != motor_state.target_speed) { + xTimerStart(motor_state.ramp_timer, 0); + } else { + motor_state.state = MOTOR_STATE_IDLE; + motor_state.ramping = false; + } + } +} + +// Public API Implementation + +esp_err_t motor_control_init(void) { + ESP_LOGI(SYSTEM_TAG, "Initializing motor control system..."); + + // Configure GPIO pins + ESP_LOGI(SYSTEM_TAG, "Configuring GPIO pins..."); + + uint64_t pin_mask = (1ULL << LED_PIN) | + (1ULL << MOTOR_R_EN) | + (1ULL << MOTOR_L_EN); + + gpio_config_t io_conf = { + .pin_bit_mask = pin_mask, + .mode = GPIO_MODE_OUTPUT, + .pull_up_en = GPIO_PULLUP_DISABLE, + .pull_down_en = GPIO_PULLDOWN_DISABLE, + .intr_type = GPIO_INTR_DISABLE + }; + + esp_err_t ret = gpio_config(&io_conf); + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to configure GPIO pins: %s", esp_err_to_name(ret)); + return ret; + } + + // Set initial pin states + gpio_set_level(LED_PIN, 0); + gpio_set_level(MOTOR_R_EN, 0); + gpio_set_level(MOTOR_L_EN, 0); + + ESP_LOGI(SYSTEM_TAG, "GPIO pins configured"); + + // Configure PWM + ESP_LOGI(SYSTEM_TAG, "Configuring PWM..."); + + ledc_timer_config_t timer_conf = { + .speed_mode = PWM_SPEED_MODE, + .timer_num = PWM_TIMER, + .duty_resolution = PWM_RESOLUTION, + .freq_hz = PWM_FREQUENCY, + .clk_cfg = LEDC_AUTO_CLK + }; + ret = ledc_timer_config(&timer_conf); + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to configure PWM timer: %s", esp_err_to_name(ret)); + return ret; + } + + ledc_channel_config_t channel_conf = { + .channel = PWM_R_CHANNEL, + .duty = 0, + .gpio_num = PWM_R_PIN, + .speed_mode = PWM_SPEED_MODE, + .hpoint = 0, + .timer_sel = PWM_TIMER + }; + ret = ledc_channel_config(&channel_conf); + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to configure PWM right channel: %s", esp_err_to_name(ret)); + return ret; + } + + channel_conf.channel = PWM_L_CHANNEL; + channel_conf.gpio_num = PWM_L_PIN; + ret = ledc_channel_config(&channel_conf); + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to configure PWM left channel: %s", esp_err_to_name(ret)); + return ret; + } + + ESP_LOGI(SYSTEM_TAG, "PWM configured"); + + // Create timers + motor_state.ramp_timer = xTimerCreate( + "MotorRampTimer", // Timer name + pdMS_TO_TICKS(RAMP_STEP_MS), // Timer period + pdTRUE, // Auto-reload + (void*)0, // Timer ID + motor_ramp_timer_callback // Callback function + ); + + motor_state.cooldown_timer = xTimerCreate( + "MotorCooldownTimer", // Timer name + pdMS_TO_TICKS(DIRECTION_CHANGE_COOLDOWN_MS), // Timer period + pdFALSE, // One-shot + (void*)0, // Timer ID + motor_cooldown_timer_callback // Callback function + ); + + if (motor_state.ramp_timer == NULL || motor_state.cooldown_timer == NULL) { + ESP_LOGE(SYSTEM_TAG, "Failed to create motor timers"); + return ESP_FAIL; + } + + ESP_LOGI(SYSTEM_TAG, "Motor control system initialized with direction change safety"); + return ESP_OK; +} + +void motor_set_speed(motor_mode_t mode, int speed_percent) { + // Clamp speed to valid range using config macro + speed_percent = CLAMP_SPEED(speed_percent); + + ESP_LOGI(SYSTEM_TAG, "Motor command: %s - Speed: %d%% (Current mode: %s, Current speed: %d%%, State: %s)", + motor_mode_to_string(mode), speed_percent, + motor_mode_to_string(motor_state.mode), motor_state.current_speed, + motor_state_to_string(motor_state.state)); + + // Track if user manually turned off + if (mode == MOTOR_OFF && motor_state.mode != MOTOR_OFF) { + motor_state.user_turned_off = true; + ESP_LOGI(SYSTEM_TAG, "User manually turned OFF - will stay off after restart"); + } else if (mode != MOTOR_OFF) { + motor_state.user_turned_off = false; + ESP_LOGI(SYSTEM_TAG, "Motor turned ON - will resume after power loss"); + } + + // If we're in cooldown, update the pending command + if (motor_state.state == MOTOR_STATE_COOLDOWN) { + motor_state.pending_mode = mode; + motor_state.pending_speed = speed_percent; + ESP_LOGI(SYSTEM_TAG, "Motor in cooldown - command queued for execution"); + return; + } + + // Check if this is a direction change that requires cooldown using config macro + bool requires_cooldown = false; + if (motor_state.current_speed > 0 && motor_state.mode != MOTOR_OFF) { + requires_cooldown = IS_DIRECTION_CHANGE(motor_state.mode, mode); + } + + if (requires_cooldown) { + ESP_LOGI(SYSTEM_TAG, "Direction change detected - initiating safety cooldown sequence"); + + // Stop any current ramping + if (motor_state.ramping) { + xTimerStop(motor_state.ramp_timer, 0); + motor_state.ramping = false; + } + + // Stop the motor immediately + motor_state.mode = MOTOR_OFF; + motor_state.current_speed = 0; + motor_state.target_speed = 0; + motor_state.state = MOTOR_STATE_COOLDOWN; + motor_state.cooldown_remaining_ms = DIRECTION_CHANGE_COOLDOWN_MS; + apply_motor_pwm(0); + + // Store the pending command + motor_state.pending_mode = mode; + motor_state.pending_speed = speed_percent; + + // Start cooldown timer + xTimerStart(motor_state.cooldown_timer, 0); + + ESP_LOGI(SYSTEM_TAG, "Motor stopped for direction change - %d second cooldown started", + DIRECTION_CHANGE_COOLDOWN_MS / 1000); + } else { + // No direction change required, proceed normally + + // Stop any current ramping + if (motor_state.ramping) { + xTimerStop(motor_state.ramp_timer, 0); + motor_state.ramping = false; + } + + // Stop cooldown timer if running + if (motor_state.state == MOTOR_STATE_COOLDOWN) { + xTimerStop(motor_state.cooldown_timer, 0); + motor_state.cooldown_remaining_ms = 0; + } + + start_motor_operation(mode, speed_percent); + } +} + +const motor_state_t* motor_get_state(void) { + return &motor_state; +} + +void motor_update_cooldown_time(void) { + if (motor_state.state == MOTOR_STATE_COOLDOWN && motor_state.cooldown_remaining_ms > 0) { + if (motor_state.cooldown_remaining_ms >= STATUS_UPDATE_INTERVAL_MS) { + motor_state.cooldown_remaining_ms -= STATUS_UPDATE_INTERVAL_MS; + } else { + motor_state.cooldown_remaining_ms = 0; + } + } +} + +const char* motor_mode_to_string(motor_mode_t mode) { + switch (mode) { + case MOTOR_OFF: return "OFF"; + case MOTOR_EXHAUST: return "EXHAUST"; + case MOTOR_INTAKE: return "INTAKE"; + default: return "UNKNOWN"; + } +} + +const char* motor_state_to_string(motor_state_enum_t state) { + switch (state) { + case MOTOR_STATE_IDLE: return "IDLE"; + case MOTOR_STATE_RAMPING: return "RAMPING"; + case MOTOR_STATE_STOPPING: return "STOPPING"; + case MOTOR_STATE_COOLDOWN: return "COOLDOWN"; + case MOTOR_STATE_RESTARTING: return "RESTARTING"; + default: return "UNKNOWN"; + } +} + +bool motor_is_ramping(void) { + return motor_state.ramping; +} + +bool motor_is_in_cooldown(void) { + return motor_state.state == MOTOR_STATE_COOLDOWN; +} + +uint32_t motor_get_cooldown_remaining(void) { + return motor_state.cooldown_remaining_ms; +} + +void motor_set_last_on_state(motor_mode_t mode, int speed) { + if (mode != MOTOR_OFF && IS_VALID_SPEED(speed) && speed > 0) { + motor_state.last_on_mode = mode; + motor_state.last_on_speed = speed; + ESP_LOGI(SYSTEM_TAG, "Last ON state set: %s @ %d%%", + motor_mode_to_string(mode), speed); + } +} + +void motor_get_last_on_state(motor_mode_t* mode, int* speed) { + if (mode) *mode = motor_state.last_on_mode; + if (speed) *speed = motor_state.last_on_speed; +} + +void motor_resume_last_state(void) { + ESP_LOGI(SYSTEM_TAG, "Resuming last state: %s @ %d%%", + motor_mode_to_string(motor_state.last_on_mode), motor_state.last_on_speed); + motor_set_speed(motor_state.last_on_mode, motor_state.last_on_speed); +} + +void motor_set_user_turned_off(bool turned_off) { + motor_state.user_turned_off = turned_off; +} + +bool motor_get_user_turned_off(void) { + return motor_state.user_turned_off; +} \ No newline at end of file diff --git a/main/motor_control.h b/main/motor_control.h new file mode 100644 index 0000000..3573c47 --- /dev/null +++ b/main/motor_control.h @@ -0,0 +1,166 @@ +#ifndef MOTOR_CONTROL_H +#define MOTOR_CONTROL_H + +#include "freertos/FreeRTOS.h" +#include "freertos/timers.h" +#include "esp_err.h" +#include + +// Motor mode enumeration +typedef enum { + MOTOR_OFF, + MOTOR_EXHAUST, + MOTOR_INTAKE +} motor_mode_t; + +// Motor state enumeration +typedef enum { + MOTOR_STATE_IDLE, // Motor is off or running normally + MOTOR_STATE_RAMPING, // Motor is ramping up/down + MOTOR_STATE_STOPPING, // Motor is stopping for direction change + MOTOR_STATE_COOLDOWN, // Motor is in cooldown period + MOTOR_STATE_RESTARTING // Motor is restarting after cooldown +} motor_state_enum_t; + +// Motor state structure +typedef struct { + motor_mode_t mode; + motor_mode_t pending_mode; // Mode to switch to after cooldown + int target_speed; + int pending_speed; // Speed to set after cooldown + int current_speed; + motor_state_enum_t state; + bool ramping; + TimerHandle_t ramp_timer; + TimerHandle_t cooldown_timer; + uint32_t cooldown_remaining_ms; // For status reporting + + // State preservation + motor_mode_t last_on_mode; // Last non-OFF mode for ON button + int last_on_speed; // Last non-zero speed for ON button + bool user_turned_off; // Track if user manually turned off +} motor_state_t; + +// Public API functions + +/** + * @brief Initialize the motor control system + * + * Sets up GPIO pins, PWM channels, and creates FreeRTOS timers for ramping and cooldown. + * Must be called before any other motor control functions. + * + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t motor_control_init(void); + +/** + * @brief Set motor speed and mode + * + * Controls the motor with automatic ramping and direction change safety. + * Handles cooldown periods when changing directions to prevent mechanical stress. + * + * @param mode Motor mode (MOTOR_OFF, MOTOR_EXHAUST, MOTOR_INTAKE) + * @param speed_percent Speed percentage (0-100) + */ +void motor_set_speed(motor_mode_t mode, int speed_percent); + +/** + * @brief Get current motor state + * + * Returns a pointer to the current motor state structure for status reporting. + * The returned pointer should not be modified directly. + * + * @return Pointer to motor_state_t structure + */ +const motor_state_t* motor_get_state(void); + +/** + * @brief Update cooldown time tracking + * + * Should be called periodically (e.g., every 1 second) to update the + * cooldown_remaining_ms field for status reporting. + */ +void motor_update_cooldown_time(void); + +/** + * @brief Get motor mode as string + * + * @param mode Motor mode enum value + * @return String representation of the mode + */ +const char* motor_mode_to_string(motor_mode_t mode); + +/** + * @brief Get motor state as string + * + * @param state Motor state enum value + * @return String representation of the state + */ +const char* motor_state_to_string(motor_state_enum_t state); + +/** + * @brief Check if motor is currently ramping + * + * @return true if motor is ramping, false otherwise + */ +bool motor_is_ramping(void); + +/** + * @brief Check if motor is in cooldown + * + * @return true if motor is in cooldown, false otherwise + */ +bool motor_is_in_cooldown(void); + +/** + * @brief Get cooldown remaining time in milliseconds + * + * @return Remaining cooldown time in milliseconds, 0 if not in cooldown + */ +uint32_t motor_get_cooldown_remaining(void); + +/** + * @brief Set the "last on" state for the ON button functionality + * + * This is called automatically when the motor is turned on, but can be + * called manually to set the default state for the ON button. + * + * @param mode Motor mode (should be MOTOR_EXHAUST or MOTOR_INTAKE) + * @param speed Speed percentage (1-100) + */ +void motor_set_last_on_state(motor_mode_t mode, int speed); + +/** + * @brief Get the "last on" state + * + * @param mode Pointer to store the last on mode + * @param speed Pointer to store the last on speed + */ +void motor_get_last_on_state(motor_mode_t* mode, int* speed); + +/** + * @brief Resume last motor state (ON button functionality) + * + * Sets the motor to the last known good state (mode and speed). + * This is typically called when the user presses an "ON" button. + */ +void motor_resume_last_state(void); + +/** + * @brief Set user turned off flag + * + * Tracks whether the user manually turned off the motor. + * This affects state restoration behavior after power loss. + * + * @param turned_off true if user manually turned off, false otherwise + */ +void motor_set_user_turned_off(bool turned_off); + +/** + * @brief Get user turned off flag + * + * @return true if user manually turned off, false otherwise + */ +bool motor_get_user_turned_off(void); + +#endif // MOTOR_CONTROL_H \ No newline at end of file From c3bbba4a24fc07a36effba47e4c592c3b4c041d1 Mon Sep 17 00:00:00 2001 From: Stephen Minakian Date: Wed, 9 Jul 2025 22:55:35 -0600 Subject: [PATCH 3/4] Refactor, state manager --- main/CMakeLists.txt | 2 +- main/maxxfan-controller.c | 226 ++++---------------- main/state_manager.c | 422 ++++++++++++++++++++++++++++++++++++++ main/state_manager.h | 126 ++++++++++++ 4 files changed, 592 insertions(+), 184 deletions(-) create mode 100644 main/state_manager.c create mode 100644 main/state_manager.h diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index b02e8fd..2270210 100755 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,2 +1,2 @@ -idf_component_register(SRCS "maxxfan-controller.c" "motor_control.c" +idf_component_register(SRCS "maxxfan-controller.c" "motor_control.c" "state_manager.c" INCLUDE_DIRS ".") \ No newline at end of file diff --git a/main/maxxfan-controller.c b/main/maxxfan-controller.c index cd23629..18ec64a 100755 --- a/main/maxxfan-controller.c +++ b/main/maxxfan-controller.c @@ -9,13 +9,13 @@ #include "esp_log.h" #include "esp_http_server.h" #include "esp_task_wdt.h" -#include "nvs_flash.h" #include "nvs.h" #include "cJSON.h" // Project modules #include "config.h" #include "motor_control.h" +#include "state_manager.h" // WiFi event group static EventGroupHandle_t s_wifi_event_group; @@ -84,11 +84,6 @@ static const char* html_page = "function startUpdates(){if(updateInterval)clearInterval(updateInterval);updateInterval=setInterval(getStatus,1000)}" "document.addEventListener('DOMContentLoaded',function(){getStatus();startUpdates()})"; -// Forward declarations -static esp_err_t save_motor_state_to_nvs(void); -static esp_err_t load_motor_state_from_nvs(void); -static bool is_watchdog_reset(void); - // Initialize watchdog timer void init_watchdog(void) { ESP_LOGI(SYSTEM_TAG, "Setting up watchdog monitoring..."); @@ -117,165 +112,6 @@ void feed_watchdog(void) { } } -// Check if this was a watchdog reset -static bool is_watchdog_reset(void) { - esp_reset_reason_t reset_reason = esp_reset_reason(); - - // Only consider TASK_WDT and INT_WDT as true watchdog resets - // ESP_RST_WDT can be triggered by power disconnection, so we exclude it - return (reset_reason == ESP_RST_TASK_WDT || - reset_reason == ESP_RST_INT_WDT); -} - -// Save motor state to NVS -static esp_err_t save_motor_state_to_nvs(void) { - nvs_handle_t nvs_handle; - esp_err_t err; - - err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle); - if (err != ESP_OK) { - ESP_LOGE(SYSTEM_TAG, "Error opening NVS handle: %s", esp_err_to_name(err)); - return err; - } - - // Get current motor state - const motor_state_t* state = motor_get_state(); - motor_mode_t last_on_mode; - int last_on_speed; - motor_get_last_on_state(&last_on_mode, &last_on_speed); - bool user_turned_off = motor_get_user_turned_off(); - - ESP_LOGI(SYSTEM_TAG, "=== SAVING STATE TO NVS ==="); - ESP_LOGI(SYSTEM_TAG, "Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", - state->mode, state->target_speed, - last_on_mode, last_on_speed, - user_turned_off ? "YES" : "NO"); - - // Save current motor state - err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)state->mode); - if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_SPEED, (uint8_t)state->target_speed); - } - - // Save last ON state - if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, (uint8_t)last_on_mode); - } - if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, (uint8_t)last_on_speed); - } - - // Save power state (whether user turned off manually) - if (err == ESP_OK) { - err = nvs_set_u8(nvs_handle, NVS_KEY_POWER_STATE, user_turned_off ? 1 : 0); - } - - if (err == ESP_OK) { - err = nvs_commit(nvs_handle); - if (err == ESP_OK) { - ESP_LOGI(SYSTEM_TAG, "✓ Motor state successfully saved to NVS"); - } else { - ESP_LOGE(SYSTEM_TAG, "✗ NVS commit failed: %s", esp_err_to_name(err)); - } - } else { - ESP_LOGE(SYSTEM_TAG, "✗ Error saving to NVS: %s", esp_err_to_name(err)); - } - ESP_LOGI(SYSTEM_TAG, "==========================="); - - nvs_close(nvs_handle); - return err; -} - -// Load motor state from NVS -static esp_err_t load_motor_state_from_nvs(void) { - nvs_handle_t nvs_handle; - esp_err_t err; - - err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle); - if (err != ESP_OK) { - ESP_LOGI(SYSTEM_TAG, "NVS not found, using default state"); - return ESP_ERR_NVS_NOT_FOUND; - } - - uint8_t stored_mode = 0; - uint8_t stored_speed = 0; - uint8_t stored_last_mode = 1; // Default to MOTOR_EXHAUST - uint8_t stored_last_speed = 50; - uint8_t stored_power_state = 0; - - // Load current motor state - err = nvs_get_u8(nvs_handle, NVS_KEY_MODE, &stored_mode); - if (err == ESP_OK) { - nvs_get_u8(nvs_handle, NVS_KEY_SPEED, &stored_speed); - nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, &stored_last_mode); - nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, &stored_last_speed); - nvs_get_u8(nvs_handle, NVS_KEY_POWER_STATE, &stored_power_state); - - // Validate ranges using config macros - if (stored_mode > MOTOR_INTAKE) stored_mode = MOTOR_OFF; - if (!IS_VALID_SPEED(stored_speed)) stored_speed = 0; - if (stored_last_mode < MOTOR_EXHAUST || stored_last_mode > MOTOR_INTAKE) stored_last_mode = MOTOR_EXHAUST; - if (!IS_VALID_SPEED(stored_last_speed)) stored_last_speed = 50; - - // Set the last ON state in motor control module - motor_set_last_on_state((motor_mode_t)stored_last_mode, stored_last_speed); - motor_set_user_turned_off(stored_power_state == 1); - - ESP_LOGI(SYSTEM_TAG, "Loaded state from NVS - Mode: %d, Speed: %d%%, Last ON: %d@%d%%, User OFF: %s", - stored_mode, stored_speed, stored_last_mode, stored_last_speed, - stored_power_state ? "YES" : "NO"); - - // Check reset reason to decide whether to restore state - bool was_watchdog_reset = is_watchdog_reset(); - esp_reset_reason_t reset_reason = esp_reset_reason(); - - ESP_LOGI(SYSTEM_TAG, "=== RESET ANALYSIS ==="); - ESP_LOGI(SYSTEM_TAG, "Reset reason: %d", reset_reason); - ESP_LOGI(SYSTEM_TAG, "Reset reason name: %s", - reset_reason == ESP_RST_POWERON ? "POWERON" : - reset_reason == ESP_RST_EXT ? "EXTERNAL" : - reset_reason == ESP_RST_SW ? "SOFTWARE" : - reset_reason == ESP_RST_PANIC ? "PANIC" : - reset_reason == ESP_RST_INT_WDT ? "INT_WDT" : - reset_reason == ESP_RST_TASK_WDT ? "TASK_WDT" : - reset_reason == ESP_RST_WDT ? "WDT" : - reset_reason == ESP_RST_DEEPSLEEP ? "DEEPSLEEP" : - reset_reason == ESP_RST_BROWNOUT ? "BROWNOUT" : - reset_reason == ESP_RST_SDIO ? "SDIO" : "UNKNOWN"); - ESP_LOGI(SYSTEM_TAG, "Watchdog reset: %s", was_watchdog_reset ? "YES" : "NO"); - ESP_LOGI(SYSTEM_TAG, "Stored mode: %d, speed: %d", stored_mode, stored_speed); - ESP_LOGI(SYSTEM_TAG, "User turned off: %s", stored_power_state ? "YES" : "NO"); - ESP_LOGI(SYSTEM_TAG, "===================="); - - // Store the restored state for potential motor restoration - if (was_watchdog_reset) { - // True watchdog reset (TASK_WDT or INT_WDT) - don't restore state, start fresh - ESP_LOGI(SYSTEM_TAG, "⚠️ TRUE watchdog reset detected - starting in OFF state for safety"); - // Motor module is already initialized in OFF state, no action needed - } else if (stored_power_state) { - // User manually turned off - stay off - ESP_LOGI(SYSTEM_TAG, "🔒 User had turned off manually - staying OFF"); - // Motor module is already initialized in OFF state, no action needed - } else if (stored_mode != MOTOR_OFF && stored_speed > 0) { - // Normal power loss or general WDT (which can be power-related) - restore previous state - ESP_LOGI(SYSTEM_TAG, "🔋 Power restored - will resume previous state: %s @ %d%%", - stored_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE", stored_speed); - - // Set the motor to the restored state (will be applied after initialization) - motor_set_speed((motor_mode_t)stored_mode, stored_speed); - } else { - ESP_LOGI(SYSTEM_TAG, "❌ No valid state to restore (mode=%d, speed=%d)", stored_mode, stored_speed); - // Motor module is already initialized in OFF state, no action needed - } - } else { - ESP_LOGI(SYSTEM_TAG, "No saved state found, using defaults"); - err = ESP_ERR_NVS_NOT_FOUND; - } - - nvs_close(nvs_handle); - return err; -} - // WiFi event handler static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) @@ -444,8 +280,11 @@ static esp_err_t fan_post_handler(httpd_req_t *req) ESP_LOGI(SYSTEM_TAG, "ON button pressed - resuming last state"); motor_resume_last_state(); - // Save state after ON button - save_motor_state_to_nvs(); + // Save state after ON button using state manager + esp_err_t save_result = state_manager_save(); + if (save_result != ESP_OK) { + ESP_LOGW(SYSTEM_TAG, "Failed to save state after ON button: %s", esp_err_to_name(save_result)); + } cJSON_Delete(json); return status_get_handler(req); @@ -458,8 +297,11 @@ static esp_err_t fan_post_handler(httpd_req_t *req) ESP_LOGI(SYSTEM_TAG, "HTTP Request: mode=%s, speed=%d", mode_str, speed); motor_set_speed(mode, speed); - // Save state after any motor command - save_motor_state_to_nvs(); + // Save state after any motor command using state manager + esp_err_t save_result = state_manager_save(); + if (save_result != ESP_OK) { + ESP_LOGW(SYSTEM_TAG, "Failed to save state after motor command: %s", esp_err_to_name(save_result)); + } cJSON_Delete(json); @@ -600,13 +442,13 @@ void app_main(void) { ESP_LOGI(SYSTEM_TAG, "Starting Maxxfan HTTP Controller with State Preservation!"); - // Initialize NVS - esp_err_t ret = nvs_flash_init(); - if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { - ESP_ERROR_CHECK(nvs_flash_erase()); - ret = nvs_flash_init(); + // Initialize state manager (includes NVS initialization) + ESP_LOGI(SYSTEM_TAG, "Initializing state manager..."); + esp_err_t ret = state_manager_init(); + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to initialize state manager: %s", esp_err_to_name(ret)); + return; } - ESP_ERROR_CHECK(ret); // Initialize watchdog timer init_watchdog(); @@ -619,9 +461,16 @@ void app_main(void) return; } - // Load saved state from NVS and potentially restore motor state - ESP_LOGI(SYSTEM_TAG, "Loading saved state..."); - load_motor_state_from_nvs(); + // Load saved state and restore motor if appropriate + ESP_LOGI(SYSTEM_TAG, "Loading saved state and applying restoration logic..."); + esp_err_t load_result = state_manager_load_and_restore(); + if (load_result == ESP_OK) { + ESP_LOGI(SYSTEM_TAG, "✓ State loaded and restoration logic applied"); + } else if (load_result == ESP_ERR_NVS_NOT_FOUND) { + ESP_LOGI(SYSTEM_TAG, "ℹ️ No saved state found, using defaults"); + } else { + 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); wifi_init_sta(); @@ -629,25 +478,36 @@ void app_main(void) // Start HTTP server start_webserver(); - // Report final motor state after initialization + // Report final system state after initialization const motor_state_t* final_state = motor_get_state(); - ESP_LOGI(SYSTEM_TAG, "=== MOTOR STATE AFTER INITIALIZATION ==="); + ESP_LOGI(SYSTEM_TAG, "=== SYSTEM INITIALIZATION COMPLETE ==="); + 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, "Final motor state: mode=%s, target=%d%%, current=%d%%, state=%s", motor_mode_to_string(final_state->mode), final_state->target_speed, final_state->current_speed, motor_state_to_string(final_state->state)); if (final_state->mode != MOTOR_OFF && final_state->target_speed > 0) { - ESP_LOGI(SYSTEM_TAG, "Motor restored to: %s @ %d%%", + ESP_LOGI(SYSTEM_TAG, "🔄 Motor restored to: %s @ %d%%", motor_mode_to_string(final_state->mode), final_state->target_speed); } else { - ESP_LOGI(SYSTEM_TAG, "Motor remains OFF"); + ESP_LOGI(SYSTEM_TAG, "⏸️ Motor remains OFF"); } - ESP_LOGI(SYSTEM_TAG, "======================================="); + + motor_mode_t last_on_mode; + int last_on_speed; + motor_get_last_on_state(&last_on_mode, &last_on_speed); + ESP_LOGI(SYSTEM_TAG, "Last ON state: %s @ %d%%", + 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, "Saved state exists: %s", state_manager_has_saved_state() ? "YES" : "NO"); + ESP_LOGI(SYSTEM_TAG, "====================================="); ESP_LOGI(SYSTEM_TAG, "=== Enhanced Maxxfan Controller Ready! ==="); 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, "Memory: Remembers settings after power loss (except watchdog resets)"); + 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"); diff --git a/main/state_manager.c b/main/state_manager.c new file mode 100644 index 0000000..7ef0fbc --- /dev/null +++ b/main/state_manager.c @@ -0,0 +1,422 @@ +#include "state_manager.h" +#include "config.h" +#include "motor_control.h" +#include "esp_log.h" +#include "esp_system.h" +#include "nvs_flash.h" +#include "nvs.h" +#include +#include + +// Private functions +static esp_err_t validate_and_clamp_values(uint8_t* mode, uint8_t* speed, uint8_t* last_mode, uint8_t* last_speed); +static void log_reset_analysis(void); +static esp_err_t should_restore_state(bool* should_restore, motor_mode_t stored_mode, int stored_speed); + +// Validate and clamp loaded values to safe ranges +static esp_err_t validate_and_clamp_values(uint8_t* mode, uint8_t* speed, uint8_t* last_mode, uint8_t* last_speed) { + // Validate and clamp motor mode + if (*mode > MOTOR_INTAKE) { + ESP_LOGW(SYSTEM_TAG, "Invalid stored mode %d, clamping to OFF", *mode); + *mode = MOTOR_OFF; + } + + // Validate and clamp speed + if (!IS_VALID_SPEED(*speed)) { + ESP_LOGW(SYSTEM_TAG, "Invalid stored speed %d, clamping to 0", *speed); + *speed = 0; + } + + // Validate and clamp last ON mode + if (*last_mode < MOTOR_EXHAUST || *last_mode > MOTOR_INTAKE) { + ESP_LOGW(SYSTEM_TAG, "Invalid stored last mode %d, defaulting to EXHAUST", *last_mode); + *last_mode = MOTOR_EXHAUST; + } + + // Validate and clamp last ON speed + if (!IS_VALID_SPEED(*last_speed) || *last_speed == 0) { + ESP_LOGW(SYSTEM_TAG, "Invalid stored last speed %d, defaulting to 50", *last_speed); + *last_speed = 50; + } + + return ESP_OK; +} + +// Log detailed reset analysis +static void log_reset_analysis(void) { + esp_reset_reason_t reset_reason = esp_reset_reason(); + bool was_watchdog = state_manager_was_watchdog_reset(); + + ESP_LOGI(SYSTEM_TAG, "=== RESET ANALYSIS ==="); + ESP_LOGI(SYSTEM_TAG, "Reset reason code: %d", reset_reason); + ESP_LOGI(SYSTEM_TAG, "Reset reason: %s", state_manager_get_reset_reason_string()); + ESP_LOGI(SYSTEM_TAG, "Watchdog reset: %s", was_watchdog ? "YES" : "NO"); + ESP_LOGI(SYSTEM_TAG, "===================="); +} + +// Determine if state should be restored based on reset reason and user preferences +static esp_err_t should_restore_state(bool* should_restore, motor_mode_t stored_mode, int stored_speed) { + if (!should_restore) return ESP_ERR_INVALID_ARG; + + *should_restore = false; + + bool was_watchdog = state_manager_was_watchdog_reset(); + bool user_turned_off = motor_get_user_turned_off(); + + if (was_watchdog) { + ESP_LOGI(SYSTEM_TAG, "⚠️ TRUE watchdog reset detected - starting in OFF state for safety"); + return ESP_OK; + } + + if (user_turned_off) { + ESP_LOGI(SYSTEM_TAG, "🔒 User had turned off manually - staying OFF"); + return ESP_OK; + } + + if (stored_mode != MOTOR_OFF && stored_speed > 0) { + ESP_LOGI(SYSTEM_TAG, "🔋 Power restored - will resume previous state: %s @ %d%%", + motor_mode_to_string(stored_mode), stored_speed); + *should_restore = true; + return ESP_OK; + } + + ESP_LOGI(SYSTEM_TAG, "❌ No valid state to restore (mode=%s, speed=%d)", + motor_mode_to_string(stored_mode), stored_speed); + return ESP_OK; +} + +// Public API Implementation + +esp_err_t state_manager_init(void) { + ESP_LOGI(SYSTEM_TAG, "Initializing state manager..."); + + esp_err_t ret = nvs_flash_init(); + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_LOGW(SYSTEM_TAG, "NVS partition was truncated, erasing..."); + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + + if (ret != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Failed to initialize NVS: %s", esp_err_to_name(ret)); + return ret; + } + + ESP_LOGI(SYSTEM_TAG, "State manager initialized successfully"); + return ESP_OK; +} + +esp_err_t state_manager_save(void) { + nvs_handle_t nvs_handle; + esp_err_t err; + + err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle); + if (err != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Error opening NVS handle: %s", esp_err_to_name(err)); + return err; + } + + // Get current motor state + const motor_state_t* state = motor_get_state(); + motor_mode_t last_on_mode; + int last_on_speed; + motor_get_last_on_state(&last_on_mode, &last_on_speed); + bool user_turned_off = motor_get_user_turned_off(); + + ESP_LOGI(SYSTEM_TAG, "=== SAVING STATE TO NVS ==="); + ESP_LOGI(SYSTEM_TAG, "Mode: %s, Speed: %d%%, Last ON: %s@%d%%, User OFF: %s", + motor_mode_to_string(state->mode), state->target_speed, + motor_mode_to_string(last_on_mode), last_on_speed, + user_turned_off ? "YES" : "NO"); + + // Save current motor state + err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)state->mode); + if (err == ESP_OK) { + err = nvs_set_u8(nvs_handle, NVS_KEY_SPEED, (uint8_t)state->target_speed); + } + + // Save last ON state + if (err == ESP_OK) { + err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, (uint8_t)last_on_mode); + } + if (err == ESP_OK) { + err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, (uint8_t)last_on_speed); + } + + // Save power state (whether user turned off manually) + if (err == ESP_OK) { + err = nvs_set_u8(nvs_handle, NVS_KEY_POWER_STATE, user_turned_off ? 1 : 0); + } + + if (err == ESP_OK) { + err = nvs_commit(nvs_handle); + if (err == ESP_OK) { + ESP_LOGI(SYSTEM_TAG, "✓ Motor state successfully saved to NVS"); + } else { + ESP_LOGE(SYSTEM_TAG, "✗ NVS commit failed: %s", esp_err_to_name(err)); + } + } else { + ESP_LOGE(SYSTEM_TAG, "✗ Error saving to NVS: %s", esp_err_to_name(err)); + } + ESP_LOGI(SYSTEM_TAG, "==========================="); + + nvs_close(nvs_handle); + return err; +} + +esp_err_t state_manager_load_and_restore(void) { + nvs_handle_t nvs_handle; + esp_err_t err; + + err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle); + if (err != ESP_OK) { + ESP_LOGI(SYSTEM_TAG, "NVS not found, using default state"); + return ESP_ERR_NVS_NOT_FOUND; + } + + uint8_t stored_mode = 0; + uint8_t stored_speed = 0; + uint8_t stored_last_mode = MOTOR_EXHAUST; // Default to MOTOR_EXHAUST + uint8_t stored_last_speed = 50; + uint8_t stored_power_state = 0; + + // Load current motor state + err = nvs_get_u8(nvs_handle, NVS_KEY_MODE, &stored_mode); + if (err == ESP_OK) { + nvs_get_u8(nvs_handle, NVS_KEY_SPEED, &stored_speed); + nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, &stored_last_mode); + nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, &stored_last_speed); + nvs_get_u8(nvs_handle, NVS_KEY_POWER_STATE, &stored_power_state); + + // Validate and clamp all values + validate_and_clamp_values(&stored_mode, &stored_speed, &stored_last_mode, &stored_last_speed); + + // Set the loaded state in motor control module + motor_set_last_on_state((motor_mode_t)stored_last_mode, stored_last_speed); + motor_set_user_turned_off(stored_power_state == 1); + + ESP_LOGI(SYSTEM_TAG, "Loaded state from NVS - Mode: %s, Speed: %d%%, Last ON: %s@%d%%, User OFF: %s", + motor_mode_to_string((motor_mode_t)stored_mode), stored_speed, + motor_mode_to_string((motor_mode_t)stored_last_mode), stored_last_speed, + stored_power_state ? "YES" : "NO"); + + // Log reset analysis + log_reset_analysis(); + + // Determine if we should restore the motor state + bool should_restore = false; + should_restore_state(&should_restore, (motor_mode_t)stored_mode, stored_speed); + + if (should_restore) { + // Restore the motor to its previous state + motor_set_speed((motor_mode_t)stored_mode, stored_speed); + } + // Note: If should_restore is false, motor remains in default OFF state + + } else { + ESP_LOGI(SYSTEM_TAG, "No saved state found, using defaults"); + err = ESP_ERR_NVS_NOT_FOUND; + } + + nvs_close(nvs_handle); + return err; +} + +bool state_manager_was_watchdog_reset(void) { + esp_reset_reason_t reset_reason = esp_reset_reason(); + + // Only consider TASK_WDT and INT_WDT as true watchdog resets + // ESP_RST_WDT can be triggered by power disconnection, so we exclude it + return (reset_reason == ESP_RST_TASK_WDT || + reset_reason == ESP_RST_INT_WDT); +} + +const char* state_manager_get_reset_reason_string(void) { + esp_reset_reason_t reset_reason = esp_reset_reason(); + + switch (reset_reason) { + case ESP_RST_POWERON: return "POWER_ON"; + case ESP_RST_EXT: return "EXTERNAL"; + case ESP_RST_SW: return "SOFTWARE"; + case ESP_RST_PANIC: return "PANIC"; + case ESP_RST_INT_WDT: return "INT_WDT"; + case ESP_RST_TASK_WDT: return "TASK_WDT"; + case ESP_RST_WDT: return "WDT"; + case ESP_RST_DEEPSLEEP: return "DEEPSLEEP"; + case ESP_RST_BROWNOUT: return "BROWNOUT"; + case ESP_RST_SDIO: return "SDIO"; + default: return "UNKNOWN"; + } +} + +esp_err_t state_manager_clear_all(void) { + nvs_handle_t nvs_handle; + esp_err_t err; + + err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle); + if (err != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Error opening NVS handle for clear: %s", esp_err_to_name(err)); + return err; + } + + ESP_LOGI(SYSTEM_TAG, "Clearing all saved state from NVS..."); + + err = nvs_erase_all(nvs_handle); + if (err == ESP_OK) { + err = nvs_commit(nvs_handle); + if (err == ESP_OK) { + ESP_LOGI(SYSTEM_TAG, "✓ All state cleared from NVS"); + } else { + ESP_LOGE(SYSTEM_TAG, "✗ Failed to commit NVS clear: %s", esp_err_to_name(err)); + } + } else { + ESP_LOGE(SYSTEM_TAG, "✗ Failed to clear NVS: %s", esp_err_to_name(err)); + } + + nvs_close(nvs_handle); + return err; +} + +esp_err_t state_manager_save_last_on_state(motor_mode_t mode, int speed) { + if (mode == MOTOR_OFF || !IS_VALID_SPEED(speed) || speed == 0) { + ESP_LOGW(SYSTEM_TAG, "Invalid last ON state: mode=%s, speed=%d", + motor_mode_to_string(mode), speed); + return ESP_ERR_INVALID_ARG; + } + + nvs_handle_t nvs_handle; + esp_err_t err; + + err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle); + if (err != ESP_OK) { + ESP_LOGE(SYSTEM_TAG, "Error opening NVS handle: %s", esp_err_to_name(err)); + return err; + } + + // Save only the last ON state + err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, (uint8_t)mode); + if (err == ESP_OK) { + err = nvs_set_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, (uint8_t)speed); + } + + if (err == ESP_OK) { + err = nvs_commit(nvs_handle); + } + + nvs_close(nvs_handle); + + if (err == ESP_OK) { + ESP_LOGI(SYSTEM_TAG, "Last ON state saved: %s @ %d%%", + motor_mode_to_string(mode), speed); + } else { + ESP_LOGE(SYSTEM_TAG, "Failed to save last ON state: %s", esp_err_to_name(err)); + } + + return err; +} + +esp_err_t state_manager_load_last_on_state(motor_mode_t* mode, int* speed) { + if (!mode || !speed) return ESP_ERR_INVALID_ARG; + + nvs_handle_t nvs_handle; + esp_err_t err; + + err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle); + if (err != ESP_OK) { + return ESP_ERR_NVS_NOT_FOUND; + } + + uint8_t stored_mode = MOTOR_EXHAUST; + uint8_t stored_speed = 50; + + err = nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_MODE, &stored_mode); + if (err == ESP_OK) { + nvs_get_u8(nvs_handle, NVS_KEY_LAST_ON_SPEED, &stored_speed); + + // Validate values + if (stored_mode < MOTOR_EXHAUST || stored_mode > MOTOR_INTAKE) { + stored_mode = MOTOR_EXHAUST; + } + if (!IS_VALID_SPEED(stored_speed) || stored_speed == 0) { + stored_speed = 50; + } + + *mode = (motor_mode_t)stored_mode; + *speed = stored_speed; + } + + nvs_close(nvs_handle); + return err; +} + +bool state_manager_get_user_turned_off(void) { + return motor_get_user_turned_off(); +} + +esp_err_t state_manager_set_user_turned_off(bool turned_off) { + motor_set_user_turned_off(turned_off); + + // Save just this flag to NVS + nvs_handle_t nvs_handle; + esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle); + if (err != ESP_OK) { + return err; + } + + err = nvs_set_u8(nvs_handle, NVS_KEY_POWER_STATE, turned_off ? 1 : 0); + if (err == ESP_OK) { + err = nvs_commit(nvs_handle); + } + + nvs_close(nvs_handle); + return err; +} + +esp_err_t state_manager_get_debug_info(char* info_buffer, size_t buffer_size) { + if (!info_buffer || buffer_size == 0) return ESP_ERR_INVALID_ARG; + + const motor_state_t* state = motor_get_state(); + motor_mode_t last_on_mode; + int last_on_speed; + motor_get_last_on_state(&last_on_mode, &last_on_speed); + + int written = snprintf(info_buffer, buffer_size, + "=== STATE MANAGER DEBUG INFO ===\n" + "Reset Reason: %s\n" + "Watchdog Reset: %s\n" + "Current Mode: %s\n" + "Current Speed: %d%%\n" + "Target Speed: %d%%\n" + "Motor State: %s\n" + "Last ON: %s @ %d%%\n" + "User Turned Off: %s\n" + "Has Saved State: %s\n" + "===============================", + state_manager_get_reset_reason_string(), + state_manager_was_watchdog_reset() ? "YES" : "NO", + motor_mode_to_string(state->mode), + state->current_speed, + state->target_speed, + motor_state_to_string(state->state), + motor_mode_to_string(last_on_mode), + last_on_speed, + motor_get_user_turned_off() ? "YES" : "NO", + state_manager_has_saved_state() ? "YES" : "NO" + ); + + return (written < buffer_size) ? ESP_OK : ESP_ERR_INVALID_SIZE; +} + +bool state_manager_has_saved_state(void) { + nvs_handle_t nvs_handle; + esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle); + if (err != ESP_OK) { + return false; + } + + uint8_t dummy; + err = nvs_get_u8(nvs_handle, NVS_KEY_MODE, &dummy); + nvs_close(nvs_handle); + + return (err == ESP_OK); +} \ No newline at end of file diff --git a/main/state_manager.h b/main/state_manager.h new file mode 100644 index 0000000..a1c5e4a --- /dev/null +++ b/main/state_manager.h @@ -0,0 +1,126 @@ +#ifndef STATE_MANAGER_H +#define STATE_MANAGER_H + +#include "esp_err.h" +#include "motor_control.h" +#include + +/** + * @brief Initialize the state manager + * + * Sets up NVS flash and prepares for state operations. + * Must be called before any other state manager functions. + * + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t state_manager_init(void); + +/** + * @brief Save current motor state to NVS + * + * Saves the current motor mode, speed, last ON state, and user preferences + * to non-volatile storage for persistence across power cycles. + * + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t state_manager_save(void); + +/** + * @brief Load motor state from NVS and apply restoration logic + * + * Loads saved state from NVS and determines whether to restore the motor + * based on reset reason and user preferences. Handles: + * - Power loss recovery + * - Watchdog reset detection + * - User manual shutoff preference + * + * @return ESP_OK if state was loaded and applied, ESP_ERR_NVS_NOT_FOUND if no saved state + */ +esp_err_t state_manager_load_and_restore(void); + +/** + * @brief Check if the last reset was due to a watchdog timeout + * + * Distinguishes between true watchdog resets (software issues) and + * other resets like power loss or external reset. + * + * @return true if reset was due to watchdog timeout, false otherwise + */ +bool state_manager_was_watchdog_reset(void); + +/** + * @brief Get human-readable reset reason string + * + * @return String describing the reset reason + */ +const char* state_manager_get_reset_reason_string(void); + +/** + * @brief Clear all saved state from NVS + * + * Removes all motor state data from NVS. Useful for factory reset + * or debugging purposes. + * + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t state_manager_clear_all(void); + +/** + * @brief Save only the "last ON" state to NVS + * + * Saves just the last known good motor state for the ON button functionality. + * This is lighter weight than saving the full state. + * + * @param mode Motor mode (MOTOR_EXHAUST or MOTOR_INTAKE) + * @param speed Speed percentage (1-100) + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t state_manager_save_last_on_state(motor_mode_t mode, int speed); + +/** + * @brief Load only the "last ON" state from NVS + * + * @param mode Pointer to store the loaded mode + * @param speed Pointer to store the loaded speed + * @return ESP_OK if loaded successfully, ESP_ERR_NVS_NOT_FOUND if not found + */ +esp_err_t state_manager_load_last_on_state(motor_mode_t* mode, int* speed); + +/** + * @brief Check if user manually turned off the motor + * + * Used to determine restoration behavior - if user manually turned off, + * the motor should stay off after power restoration. + * + * @return true if user manually turned off, false otherwise + */ +bool state_manager_get_user_turned_off(void); + +/** + * @brief Set the user turned off flag + * + * @param turned_off true if user manually turned off, false otherwise + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t state_manager_set_user_turned_off(bool turned_off); + +/** + * @brief Get detailed state information for debugging + * + * Provides comprehensive information about the saved state and + * reset conditions for troubleshooting. + * + * @param info_buffer Buffer to store the information string + * @param buffer_size Size of the info buffer + * @return ESP_OK on success, ESP_FAIL on error + */ +esp_err_t state_manager_get_debug_info(char* info_buffer, size_t buffer_size); + +/** + * @brief Check if NVS contains any saved motor state + * + * @return true if saved state exists, false otherwise + */ +bool state_manager_has_saved_state(void); + +#endif // STATE_MANAGER_H \ No newline at end of file From 504003e2ba66a5887d9ace0345d30b3f4bf49072 Mon Sep 17 00:00:00 2001 From: Stephen Minakian Date: Wed, 9 Jul 2025 23:25:08 -0600 Subject: [PATCH 4/4] Refactor WiFi Manager --- main/CMakeLists.txt | 2 +- main/maxxfan-controller.c | 193 ++++++++--------- main/state_manager.c | 23 +- main/wifi_manager.c | 436 ++++++++++++++++++++++++++++++++++++++ main/wifi_manager.h | 193 +++++++++++++++++ 5 files changed, 747 insertions(+), 100 deletions(-) create mode 100644 main/wifi_manager.c create mode 100644 main/wifi_manager.h diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 2270210..440169e 100755 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -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 ".") \ No newline at end of file diff --git a/main/maxxfan-controller.c b/main/maxxfan-controller.c index 18ec64a..8183c97 100755 --- a/main/maxxfan-controller.c +++ b/main/maxxfan-controller.c @@ -2,10 +2,7 @@ #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" -#include "freertos/event_groups.h" #include "esp_system.h" -#include "esp_wifi.h" -#include "esp_event.h" #include "esp_log.h" #include "esp_http_server.h" #include "esp_task_wdt.h" @@ -16,10 +13,7 @@ #include "config.h" #include "motor_control.h" #include "state_manager.h" - -// WiFi event group -static EventGroupHandle_t s_wifi_event_group; -static int s_retry_num = 0; +#include "wifi_manager.h" // HTTP server handle 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 static void set_cors_headers(httpd_req_t *req) { 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; 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_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); 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"; if (last_on_mode == MOTOR_INTAKE) last_on_mode_str = "intake"; + // Motor status cJSON_AddStringToObject(json, "mode", mode_str); cJSON_AddNumberToObject(json, "current_speed", state->current_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_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 if (state->state == MOTOR_STATE_COOLDOWN) { const char* pending_mode_str = "off"; @@ -382,62 +370,6 @@ static httpd_handle_t start_webserver(void) 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) { 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_LOGI(SYSTEM_TAG, "Connecting to WiFi network: %s", WIFI_SSID); - wifi_init_sta(); + // Initialize WiFi manager + 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 - start_webserver(); + // Connect to WiFi using default credentials + 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 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, "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, "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, 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%%", 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"); + + // 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, "====================================="); @@ -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, "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, "WiFi: Enhanced connection management with auto-reconnect"); 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 + uint32_t loop_count = 0; while (1) { feed_watchdog(); // Update motor cooldown time for status reporting 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)); } } \ No newline at end of file diff --git a/main/state_manager.c b/main/state_manager.c index 7ef0fbc..ae918af 100644 --- a/main/state_manager.c +++ b/main/state_manager.c @@ -123,16 +123,31 @@ esp_err_t state_manager_save(void) { motor_get_last_on_state(&last_on_mode, &last_on_speed); 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, "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_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, user_turned_off ? "YES" : "NO"); - // Save current motor state - err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)state->mode); + // Save the determined motor state (actual or pending) + err = nvs_set_u8(nvs_handle, NVS_KEY_MODE, (uint8_t)mode_to_save); 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 diff --git a/main/wifi_manager.c b/main/wifi_manager.c new file mode 100644 index 0000000..f70d00e --- /dev/null +++ b/main/wifi_manager.c @@ -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 +#include + +// 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; +} \ No newline at end of file diff --git a/main/wifi_manager.h b/main/wifi_manager.h new file mode 100644 index 0000000..ac1348c --- /dev/null +++ b/main/wifi_manager.h @@ -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 +#include + +// 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 \ No newline at end of file