refactor #12

Merged
stephen merged 4 commits from refactor into main 2025-07-10 09:10:15 -06:00
9 changed files with 2114 additions and 744 deletions

View File

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

124
main/config.h Normal file
View File

@ -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

File diff suppressed because it is too large Load Diff

411
main/motor_control.c Normal file
View File

@ -0,0 +1,411 @@
#include "motor_control.h"
#include "config.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#include <string.h>
// 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;
}

166
main/motor_control.h Normal file
View File

@ -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 <stdbool.h>
// 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

437
main/state_manager.c Normal file
View File

@ -0,0 +1,437 @@
#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 <string.h>
#include <stdio.h>
// 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();
// 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, "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 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)speed_to_save);
}
// 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);
}

126
main/state_manager.h Normal file
View File

@ -0,0 +1,126 @@
#ifndef STATE_MANAGER_H
#define STATE_MANAGER_H
#include "esp_err.h"
#include "motor_control.h"
#include <stdbool.h>
/**
* @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

436
main/wifi_manager.c Normal file
View File

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

193
main/wifi_manager.h Normal file
View File

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