Compare commits

...

15 Commits

12 changed files with 2962 additions and 479 deletions

380
README.md Normal file
View File

@ -0,0 +1,380 @@
# Maxxfan Smart Controller
A WiFi-enabled smart controller for the Maxxfan Deluxe 6401K using ESP32 and BTS7960 motor driver. Transform your manual RV fan into a remotely controllable smart device with variable speed control, bidirectional operation, and smooth motor ramping.
## 🌟 Features
- **WiFi Remote Control** - Control your fan from anywhere on your network
- **Variable Speed Control** - 0-100% speed adjustment via web interface
- **Bidirectional Operation** - Switch between exhaust and intake modes
- **Smooth Motor Ramping** - Gradual speed changes prevent mechanical stress
- **Real-time Status** - Live updates of fan mode, current speed, and target speed
- **Ramping Visualization** - See when speed changes are in progress
- **Mobile-Friendly Interface** - Responsive web design works on phones and tablets
- **Enhanced Error Handling** - Visual connection status and error messages
- **CORS Support** - Cross-origin requests properly handled
- **Compact Design** - Optimized for ESP32 memory constraints
- **Connection Status** - Shows "Connected", "Connecting", or "Error" status
- **REST API** - Enhanced JSON API for integration with home automation systems
- **Watchdog Protection** - Automatic system recovery from crashes
- **Homebridge Compatible** - Easy integration with HomeKit
## 🔧 Hardware Requirements
### Main Components
- **ESP32 Development Board** (tested with SparkFun ESP32 Thing Plus)
- **BTS7960 Motor Driver Module** (43A high-power motor driver)
- **Maxxfan Deluxe 6401K** (or compatible 12V DC fan)
- **12V Power Supply** (adequate for your fan's current draw)
### Wiring Connections
```
ESP32 GPIO → BTS7960 Pin
GPIO 18 → R_EN (Right Enable)
GPIO 19 → L_EN (Left Enable)
GPIO 21 → R_PWM (Right PWM)
GPIO 22 → L_PWM (Left PWM)
GPIO 13 → LED (Status Indicator)
3.3V → VCC (Logic Power)
GND → GND
BTS7960 → Fan Motor
B+ → Fan Positive
B- → Fan Negative
Power Supply
12V → BTS7960 Motor Power + Fan Power Input
GND → Common Ground
```
## 🚀 Quick Start
### Prerequisites
- Docker installed on Ubuntu (recommended) or Mac
- ESP32 connected via USB
- WiFi network credentials
### 1. Set Up Development Environment
```bash
# Create project directory
mkdir ~/maxxfan-controller
cd ~/maxxfan-controller
# Pull official ESP-IDF Docker image (v5.x recommended)
docker pull espressif/idf:latest
# Create new ESP-IDF project
docker run --rm -v $PWD:/project -w /project -it espressif/idf:latest
idf.py create-project maxxfan-controller
exit
```
### 2. Configure WiFi Credentials
Edit the WiFi credentials in `main/maxxfan-controller.c`:
```c
#define WIFI_SSID "YOUR_WIFI_NAME"
#define WIFI_PASS "YOUR_WIFI_PASSWORD"
```
### 3. Build and Flash
```bash
cd maxxfan-controller
# Build
docker run --rm -v $PWD:/project -w /project -it espressif/idf:latest idf.py build
# Flash (replace /dev/ttyUSB0 with your device)
docker run --rm -v $PWD:/project -w /project --device=/dev/ttyUSB0 -it espressif/idf:latest idf.py flash -p /dev/ttyUSB0
# Monitor serial output
docker run --rm -v $PWD:/project -w /project --device=/dev/ttyUSB0 -it espressif/idf:latest idf.py monitor -p /dev/ttyUSB0
```
### 4. Access Web Interface
1. Note the IP address from serial monitor output:
```
I (xxx) HTTP_MOTOR: got ip:192.168.1.123
```
2. Open your browser and navigate to: `http://192.168.1.123`
## 🌐 Enhanced Web Interface
The improved web interface provides:
- **Real-time Status Display** - Current fan mode, speed, and target speed
- **Ramping Indicator** - Visual feedback when speed changes are in progress
- **Quick Controls** - One-click buttons for common operations
- **Speed Slider** - Precise speed adjustment (0-100%)
- **Real-time Updates** - Status refreshes every 1 second for live ramping visualization
- **Error Handling** - Visual connection status and network error feedback
- **Persistent State** - Settings maintained across page reloads
- **Memory Optimized** - Compact HTML (~2KB) ensures reliable loading
### Controls Available
- **Turn OFF** - Stops the fan completely
- **Exhaust (50%)** - Sets exhaust mode at 50% speed with smooth ramping
- **Intake (50%)** - Sets intake mode at 50% speed with smooth ramping
- **Custom Speed** - Use slider + "Set Exhaust/Intake Speed" buttons
### Motor Ramping Features
- **Smooth Startup** - Motors start at minimum speed (10%) then ramp to target
- **Gradual Changes** - Speed changes in 5% increments every 50ms
- **Direction Changes** - Proper sequencing prevents mechanical stress
- **Visual Feedback** - Ramping indicator shows when changes are in progress
## 📡 Enhanced REST API
### Get Status
```bash
GET /status
```
Enhanced Response:
```json
{
"mode": "exhaust",
"current_speed": 65,
"target_speed": 80,
"ramping": true
}
```
### Control Fan
```bash
POST /fan
Content-Type: application/json
{
"mode": "exhaust", // "off", "exhaust", or "intake"
"speed": 75 // 0-100
}
```
### Example cURL Commands
```bash
# Turn fan off (immediate stop)
curl -X POST http://192.168.1.123/fan -H "Content-Type: application/json" -d '{"mode":"off","speed":0}'
# Set exhaust mode at 80% (with ramping)
curl -X POST http://192.168.1.123/fan -H "Content-Type: application/json" -d '{"mode":"exhaust","speed":80}'
# Set intake mode at 60% (with ramping)
curl -X POST http://192.168.1.123/fan -H "Content-Type: application/json" -d '{"mode":"intake","speed":60}'
# Get current status (includes ramping state)
curl http://192.168.1.123/status
```
## 🏠 Homebridge Integration
Add to your Homebridge `config.json`:
```json
{
"accessories": [
{
"accessory": "HTTP-FAN",
"name": "Maxxfan",
"getUrl": "http://192.168.1.123/status",
"setUrl": "http://192.168.1.123/fan",
"on": {
"setOn": "http://192.168.1.123/fan",
"setOff": "http://192.168.1.123/fan"
},
"speed": {
"setSpeed": "http://192.168.1.123/fan"
}
},
{
"accessory": "HTTP-SWITCH",
"name": "Maxxfan Direction",
"getUrl": "http://192.168.1.123/status",
"setUrl": "http://192.168.1.123/fan",
"mapOn": "intake",
"mapOff": "exhaust"
}
]
}
```
Requires: `npm install -g homebridge-http-accessory`
## 🔧 Technical Details
### Enhanced Motor Control Logic
The BTS7960 is a dual H-bridge motor driver with improved control sequencing:
- **Exhaust Mode**: R_EN=HIGH, L_EN=LOW, PWM on R_PWM pin
- **Intake Mode**: R_EN=LOW, L_EN=HIGH, PWM on L_PWM pin
- **Off Mode**: Both enables LOW, PWM stopped
- **Ramping**: Gradual speed changes using FreeRTOS timers
### Motor Ramping Configuration
```c
#define RAMP_STEP_MS 50 // Time between ramp steps (50ms)
#define RAMP_STEP_SIZE 5 // PWM duty change per step (~2% speed)
#define MIN_MOTOR_SPEED 10 // Minimum speed to overcome inertia
```
### PWM Configuration
- **Frequency**: 1kHz (optimal for motor control)
- **Resolution**: 8-bit (256 levels of speed control)
- **Speed Range**: 0-100% mapped to 0-255 PWM duty cycle
### Memory Optimization
The web interface HTML has been optimized to ~2KB (down from ~8KB) to ensure:
- Complete page loading without truncation
- Reliable JavaScript execution
- Proper function definitions and event handling
- Stable operation on ESP32's limited memory
### Safety & Reliability Features
- **Watchdog Timer**: Automatic system recovery from crashes
- **Enable Sequencing**: Enable pins activated before PWM signals
- **Direction Switching**: Proper delays prevent shoot-through current
- **Error Handling**: Robust JSON parsing and HTTP error responses
- **CORS Headers**: Cross-origin support for web integrations
- **Compact HTML**: Optimized web interface for ESP32 memory constraints
- **Real-time Updates**: 1-second polling for live status updates
- **Visual Feedback**: Connection status and ramping progress indicators
## 🛠️ Development
### Project Structure
```
maxxfan-controller/
├── main/
│ ├── maxxfan-controller.c # Enhanced application code
│ └── CMakeLists.txt # Build configuration
├── CMakeLists.txt # Project configuration
└── sdkconfig # ESP-IDF configuration
```
### Key Components
- **GPIO Control**: Direct hardware pin management
- **LEDC PWM**: Hardware PWM generation for speed control
- **FreeRTOS Timers**: Motor ramping control
- **Task Watchdog**: System reliability monitoring
- **WiFi Station**: Connect to existing network
- **HTTP Server**: Built-in ESP-IDF web server with CORS support
- **JSON Parsing**: cJSON library for enhanced API requests
### Building from Source
The project uses ESP-IDF v5.x with these main dependencies:
- `driver/gpio.h` - GPIO control
- `driver/ledc.h` - PWM generation
- `esp_http_server.h` - Web server
- `esp_task_wdt.h` - Watchdog timer
- `freertos/timers.h` - Motor ramping timers
- `cJSON.h` - JSON parsing
- `esp_wifi.h` - WiFi connectivity
## 📋 Troubleshooting
### Common Boot Messages (Normal)
```
W (501) spi_flash: Detected size(16384k) larger than the size in the binary image header(2048k)
```
This warning is normal - your ESP32 has more flash than the project uses.
### WiFi Connection Issues
- Verify SSID and password in code
- Check 2.4GHz network (ESP32 doesn't support 5GHz)
- Monitor serial output for connection status
### Motor Not Responding
- Check all wiring connections
- Verify 12V power supply to BTS7960
- Ensure common ground between ESP32 and motor circuit
- Test with multimeter on enable pins (should show 3.3V when active)
- Check for ramping messages in serial output
### Web Interface Issues
- Confirm IP address from serial monitor
- Check browser developer console (F12) for JavaScript errors
- Look for CORS or network errors
- Try different browser or incognito mode
### JavaScript Console Errors
If you see "Unexpected end of script" or "Can't find variable" errors:
- These indicate HTML truncation due to memory constraints
- The current compact HTML should resolve these issues
- Check browser developer console (F12) for specific errors
- Verify complete page load by viewing page source
- If errors persist, try clearing browser cache and refreshing
### Connection Status Issues
If the web interface shows "Connection Error":
- Check that ESP32 is connected to WiFi (serial monitor should show IP)
- Verify you're accessing the correct IP address
- Check that both devices are on the same network
- Try accessing `/status` endpoint directly: `http://[ESP32_IP]/status`
- Look for CORS-related errors in browser console
### Watchdog Timer Messages
If you see watchdog errors, check:
- Main loop is running (should see periodic status updates)
- No infinite loops in code
- Adequate task stack sizes
### Serial Port Issues (Ubuntu)
```bash
# Add user to dialout group
sudo usermod -a -G dialout $USER
# Check available ports
ls /dev/tty* | grep -E "(USB|ACM)"
# Fix permissions if needed
sudo chmod 666 /dev/ttyUSB0
```
### Flash Size Warning Fix (Optional)
To use full 16MB flash and eliminate warning:
```bash
idf.py menuconfig
# Navigate to: Serial flasher config → Flash size → 16MB
```
## 🔒 Security Considerations
### Current Implementation
- **Open Access**: No authentication required
- **Local Network Only**: Not accessible from internet
- **HTTP Only**: Unencrypted communication
- **CORS Enabled**: Allows cross-origin requests
### Recommended Improvements for Production
- **Network Isolation**: Use dedicated IoT VLAN
- **Basic Authentication**: Add username/password protection
- **HTTPS**: Enable SSL/TLS encryption
- **Firewall Rules**: Restrict access to specific devices
## 📄 License
This project is open source. Use at your own risk. Always follow electrical safety practices when working with 12V systems.
## 🤝 Contributing
Feel free to submit issues, feature requests, or pull requests to improve this project.
## ⚠️ Disclaimer
This project involves working with electrical systems and motor control. Always:
- Follow proper electrical safety practices
- Use appropriate fuses and circuit protection
- Test thoroughly before permanent installation
- Ensure adequate ventilation and mounting
- Check local electrical codes and regulations
The authors are not responsible for any damage or injury resulting from the use of this project.

View File

@ -1,2 +1,2 @@
idf_component_register(SRCS "maxxfan-controller.c"
INCLUDE_DIRS ".")
idf_component_register(SRCS "maxxfan-controller.c" "motor_control.c" "state_manager.c" "wifi_manager.c" "http_server.c"
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

442
main/http_server.c Normal file
View File

@ -0,0 +1,442 @@
#include "http_server.h"
#include "config.h"
#include "motor_control.h"
#include "state_manager.h"
#include "wifi_manager.h"
#include "esp_log.h"
#include "esp_http_server.h"
#include "cJSON.h"
#include <string.h>
#include <stdio.h>
// Private state
static struct {
httpd_handle_t server;
bool running;
uint32_t total_requests;
uint32_t active_connections;
uint32_t last_request_time;
} server_state = {
.server = NULL,
.running = false,
.total_requests = 0,
.active_connections = 0,
.last_request_time = 0
};
// Compact HTML web page for control
static const char* html_page =
"<!DOCTYPE html><html><head><title>Maxxfan</title><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><style>"
"body{font-family:Arial;margin:20px;background:#f0f0f0}.container{max-width:500px;margin:0 auto;background:white;padding:20px;border-radius:8px}"
"h1{color:#333;text-align:center;margin:0 0 20px}button{padding:12px 20px;margin:5px;border:none;border-radius:4px;cursor:pointer;font-size:14px}"
".off{background:#f44336;color:white}.exhaust{background:#ff9800;color:white}.intake{background:#4CAF50;color:white}.on{background:#2196F3;color:white}"
".status{background:#e3f2fd;padding:15px;border-radius:4px;margin:15px 0}.ramping{background:#fff3e0;padding:8px;margin:8px 0;display:none}"
".cooldown{background:#ffebee;padding:8px;margin:8px 0;color:#c62828;display:none}"
".error{background:#ffebee;padding:8px;margin:8px 0;color:#c62828;display:none}.slider{width:100%;height:30px;margin:10px 0}"
"</style></head><body><div class=\"container\"><h1>Maxxfan Controller</h1>"
"<div class=\"status\"><h4>Status</h4><p>Mode: <span id=\"mode\">OFF</span></p><p>Speed: <span id=\"speed\">0</span>%</p>"
"<p>Target: <span id=\"target\">0</span>%</p><p>State: <span id=\"state\">IDLE</span></p>"
"<p>Last ON: <span id=\"lastOn\">EXHAUST @ 50%</span></p>"
"<div id=\"rampStatus\" class=\"ramping\">Ramping...</div>"
"<div id=\"cooldownStatus\" class=\"cooldown\">Direction change cooldown: <span id=\"cooldownTime\">0</span>s</div>"
"<div id=\"errorStatus\" class=\"error\">Error</div><small id=\"connectionStatus\">Connecting...</small></div>"
"<div><h3>Fan Control</h3><button class=\"off\" onclick=\"setFan('off',0)\">OFF</button>"
"<button class=\"on\" onclick=\"setFan('on',0)\">ON (Resume Last)</button>"
"<button class=\"exhaust\" onclick=\"setFan('exhaust',50)\">Exhaust 50%</button>"
"<button class=\"intake\" onclick=\"setFan('intake',50)\">Intake 50%</button></div>"
"<div><h3>Speed Control</h3><label>Speed: <span id=\"speedValue\">50</span>%</label>"
"<input type=\"range\" id=\"speedSlider\" class=\"slider\" min=\"0\" max=\"100\" value=\"50\" oninput=\"updateSpeed(this.value)\">"
"<button class=\"exhaust\" onclick=\"setFanSpeed('exhaust')\">Set Exhaust</button>"
"<button class=\"intake\" onclick=\"setFanSpeed('intake')\">Set Intake</button></div></div>"
"<script>let currentSpeed=50,updateInterval=null,errorCount=0;"
"function updateSpeed(v){currentSpeed=parseInt(v);document.getElementById('speedValue').textContent=v}"
"function showError(m){document.getElementById('errorStatus').innerHTML='Error: '+m;document.getElementById('errorStatus').style.display='block';"
"document.getElementById('connectionStatus').textContent='Error'}"
"function hideError(){document.getElementById('errorStatus').style.display='none';"
"document.getElementById('connectionStatus').textContent='Connected';errorCount=0}"
"function setFan(mode,speed){if(mode==='on'){fetch('/fan',{method:'POST',headers:{'Content-Type':'application/json'},"
"body:JSON.stringify({mode:'on',speed:0})})"
".then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json()})"
".then(d=>{updateStatus(d);hideError()}).catch(e=>{console.error(e);showError(e.message)});return;}"
"currentSpeed=speed;document.getElementById('speedSlider').value=speed;"
"document.getElementById('speedValue').textContent=speed;fetch('/fan',{method:'POST',"
"headers:{'Content-Type':'application/json'},body:JSON.stringify({mode:mode,speed:parseInt(speed)})})"
".then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json()})"
".then(d=>{updateStatus(d);hideError()}).catch(e=>{console.error(e);showError(e.message)})}"
"function setFanSpeed(mode){fetch('/fan',{method:'POST',headers:{'Content-Type':'application/json'},"
"body:JSON.stringify({mode:mode,speed:parseInt(currentSpeed)})})"
".then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json()})"
".then(d=>{updateStatus(d);hideError()}).catch(e=>{console.error(e);showError(e.message)})}"
"function updateStatus(data){document.getElementById('mode').textContent=data.mode.toUpperCase();"
"document.getElementById('speed').textContent=data.current_speed;"
"document.getElementById('target').textContent=data.target_speed;"
"document.getElementById('state').textContent=data.state.toUpperCase();"
"if(data.last_on_mode&&data.last_on_speed){document.getElementById('lastOn').textContent=data.last_on_mode.toUpperCase()+' @ '+data.last_on_speed+'%';}"
"document.getElementById('rampStatus').style.display=data.ramping?'block':'none';"
"let cooldownDiv=document.getElementById('cooldownStatus');"
"if(data.cooldown_remaining>0){cooldownDiv.style.display='block';"
"document.getElementById('cooldownTime').textContent=Math.ceil(data.cooldown_remaining/1000);}else{cooldownDiv.style.display='none';}}"
"function getStatus(){fetch('/status').then(r=>{if(!r.ok)throw new Error('HTTP '+r.status);return r.json()})"
".then(d=>{updateStatus(d);hideError()}).catch(e=>{errorCount++;if(errorCount>=3)showError('Connection lost')})}"
"function startUpdates(){if(updateInterval)clearInterval(updateInterval);updateInterval=setInterval(getStatus,1000)}"
"document.addEventListener('DOMContentLoaded',function(){getStatus();startUpdates()})</script></body></html>";
// Forward declarations for handler functions
static esp_err_t root_get_handler(httpd_req_t *req);
static esp_err_t status_get_handler(httpd_req_t *req);
static esp_err_t fan_post_handler(httpd_req_t *req);
static esp_err_t options_handler(httpd_req_t *req);
// Helper functions
static void set_cors_headers(httpd_req_t *req);
static void update_request_stats(void);
// Helper function to set CORS headers
static void set_cors_headers(httpd_req_t *req) {
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "GET, POST, OPTIONS");
httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "Content-Type, Accept");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
}
// Helper function to update request statistics
static void update_request_stats(void) {
server_state.total_requests++;
server_state.last_request_time = xTaskGetTickCount() * portTICK_PERIOD_MS;
}
// HTTP handler for the main web page
static esp_err_t root_get_handler(httpd_req_t *req) {
update_request_stats();
set_cors_headers(req);
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, html_page, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
// HTTP handler for fan status (GET /status)
static esp_err_t status_get_handler(httpd_req_t *req) {
update_request_stats();
// Update cooldown time before reporting
motor_update_cooldown_time();
// 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);
// 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",
wifi_manager_status_to_string(wifi_info.status), ip_str);
set_cors_headers(req);
httpd_resp_set_type(req, "application/json");
cJSON *json = cJSON_CreateObject();
const char* mode_str = "off";
if (state->mode == MOTOR_EXHAUST) mode_str = "exhaust";
else if (state->mode == MOTOR_INTAKE) mode_str = "intake";
const char* state_str = "idle";
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;
case MOTOR_STATE_RESTARTING: state_str = "restarting"; break;
default: state_str = "idle"; break;
}
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);
cJSON_AddStringToObject(json, "state", state_str);
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", 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";
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", state->pending_speed);
}
char *json_string = cJSON_Print(json);
if (json_string) {
httpd_resp_send(req, json_string, strlen(json_string));
free(json_string);
} else {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "JSON creation failed");
}
cJSON_Delete(json);
return ESP_OK;
}
// HTTP handler for fan control (POST /fan)
static esp_err_t fan_post_handler(httpd_req_t *req) {
update_request_stats();
char buf[MAX_JSON_BUFFER_SIZE];
int ret, remaining = req->content_len;
if (remaining >= sizeof(buf)) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too long");
return ESP_FAIL;
}
ret = httpd_req_recv(req, buf, remaining);
if (ret <= 0) {
if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "Request timeout");
}
return ESP_FAIL;
}
buf[ret] = '\0';
ESP_LOGI(SYSTEM_TAG, "Received POST data: %s", buf);
cJSON *json = cJSON_Parse(buf);
if (json == NULL) {
ESP_LOGE(SYSTEM_TAG, "JSON parsing failed");
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
return ESP_FAIL;
}
cJSON *mode_json = cJSON_GetObjectItem(json, "mode");
cJSON *speed_json = cJSON_GetObjectItem(json, "speed");
if (!cJSON_IsString(mode_json) || (!cJSON_IsNumber(speed_json) && !cJSON_IsString(speed_json))) {
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);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing mode or speed");
return ESP_FAIL;
}
const char* mode_str = mode_json->valuestring;
int speed;
// Handle both number and string speed values
if (cJSON_IsNumber(speed_json)) {
speed = (int)speed_json->valuedouble;
} else if (cJSON_IsString(speed_json)) {
speed = atoi(speed_json->valuestring);
} else {
speed = 0;
}
motor_mode_t mode = MOTOR_OFF;
// Handle special "ON" command - resume last settings
if (strcmp(mode_str, "on") == 0) {
ESP_LOGI(SYSTEM_TAG, "ON button pressed - resuming last state");
motor_resume_last_state();
// 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);
} else if (strcmp(mode_str, "exhaust") == 0) {
mode = MOTOR_EXHAUST;
} else if (strcmp(mode_str, "intake") == 0) {
mode = MOTOR_INTAKE;
}
ESP_LOGI(SYSTEM_TAG, "HTTP Request: mode=%s, speed=%d", mode_str, speed);
motor_set_speed(mode, speed);
// 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);
// Send response with updated status
return status_get_handler(req);
}
// HTTP handler for OPTIONS requests (CORS preflight)
static esp_err_t options_handler(httpd_req_t *req) {
update_request_stats();
set_cors_headers(req);
httpd_resp_set_status(req, "200 OK");
httpd_resp_send(req, NULL, 0);
return ESP_OK;
}
// Public API Implementation
esp_err_t http_server_init(void) {
if (server_state.running) {
ESP_LOGW(SYSTEM_TAG, "HTTP server already running");
return ESP_OK;
}
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
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(SYSTEM_TAG, "Starting HTTP server on port: '%d'", config.server_port);
esp_err_t ret = httpd_start(&server_state.server, &config);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to start HTTP server: %s", esp_err_to_name(ret));
return ret;
}
ESP_LOGI(SYSTEM_TAG, "Registering URI handlers");
// Root handler
httpd_uri_t root = {
.uri = "/",
.method = HTTP_GET,
.handler = root_get_handler,
.user_ctx = NULL
};
ret = httpd_register_uri_handler(server_state.server, &root);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register root handler: %s", esp_err_to_name(ret));
goto cleanup;
}
// Status handler
httpd_uri_t status = {
.uri = "/status",
.method = HTTP_GET,
.handler = status_get_handler,
.user_ctx = NULL
};
ret = httpd_register_uri_handler(server_state.server, &status);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register status handler: %s", esp_err_to_name(ret));
goto cleanup;
}
// Fan control handler
httpd_uri_t fan = {
.uri = "/fan",
.method = HTTP_POST,
.handler = fan_post_handler,
.user_ctx = NULL
};
ret = httpd_register_uri_handler(server_state.server, &fan);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register fan handler: %s", esp_err_to_name(ret));
goto cleanup;
}
// OPTIONS handler for CORS preflight
httpd_uri_t options_status = {
.uri = "/status",
.method = HTTP_OPTIONS,
.handler = options_handler,
.user_ctx = NULL
};
ret = httpd_register_uri_handler(server_state.server, &options_status);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register OPTIONS status handler: %s", esp_err_to_name(ret));
goto cleanup;
}
httpd_uri_t options_fan = {
.uri = "/fan",
.method = HTTP_OPTIONS,
.handler = options_handler,
.user_ctx = NULL
};
ret = httpd_register_uri_handler(server_state.server, &options_fan);
if (ret != ESP_OK) {
ESP_LOGE(SYSTEM_TAG, "Failed to register OPTIONS fan handler: %s", esp_err_to_name(ret));
goto cleanup;
}
server_state.running = true;
ESP_LOGI(SYSTEM_TAG, "HTTP server started successfully with %d handlers", HTTP_MAX_URI_HANDLERS);
return ESP_OK;
cleanup:
httpd_stop(server_state.server);
server_state.server = NULL;
return ret;
}
esp_err_t http_server_stop(void) {
if (!server_state.running || !server_state.server) {
ESP_LOGW(SYSTEM_TAG, "HTTP server not running");
return ESP_OK;
}
ESP_LOGI(SYSTEM_TAG, "Stopping HTTP server...");
esp_err_t ret = httpd_stop(server_state.server);
if (ret == ESP_OK) {
server_state.server = NULL;
server_state.running = false;
server_state.active_connections = 0;
ESP_LOGI(SYSTEM_TAG, "HTTP server stopped successfully");
} else {
ESP_LOGE(SYSTEM_TAG, "Failed to stop HTTP server: %s", esp_err_to_name(ret));
}
return ret;
}
bool http_server_is_running(void) {
return server_state.running;
}
httpd_handle_t http_server_get_handle(void) {
return server_state.running ? server_state.server : NULL;
}
esp_err_t http_server_get_stats(uint32_t* total_requests, uint32_t* active_connections, uint32_t* last_request_time) {
if (total_requests) *total_requests = server_state.total_requests;
if (active_connections) *active_connections = server_state.active_connections;
if (last_request_time) *last_request_time = server_state.last_request_time;
return ESP_OK;
}
esp_err_t http_server_reset_stats(void) {
server_state.total_requests = 0;
server_state.active_connections = 0;
server_state.last_request_time = 0;
ESP_LOGI(SYSTEM_TAG, "HTTP server statistics reset");
return ESP_OK;
}

64
main/http_server.h Normal file
View File

@ -0,0 +1,64 @@
#ifndef HTTP_SERVER_H
#define HTTP_SERVER_H
#include "esp_err.h"
#include "esp_http_server.h"
/**
* @brief Initialize and start the HTTP server
*
* Sets up all URI handlers and starts the web server on the configured port.
* Provides a REST API for motor control and a web interface.
*
* @return ESP_OK on success, ESP_FAIL on error
*/
esp_err_t http_server_init(void);
/**
* @brief Stop the HTTP server
*
* Gracefully shuts down the HTTP server and frees resources.
*
* @return ESP_OK on success, ESP_FAIL on error
*/
esp_err_t http_server_stop(void);
/**
* @brief Check if HTTP server is running
*
* @return true if server is running, false otherwise
*/
bool http_server_is_running(void);
/**
* @brief Get the HTTP server handle
*
* Returns the internal server handle for advanced operations.
* Can return NULL if server is not running.
*
* @return HTTP server handle or NULL
*/
httpd_handle_t http_server_get_handle(void);
/**
* @brief Get server statistics
*
* Provides information about server performance and usage.
*
* @param total_requests Pointer to store total request count
* @param active_connections Pointer to store current active connections
* @param last_request_time Pointer to store timestamp of last request
* @return ESP_OK on success, ESP_ERR_INVALID_ARG if pointers are NULL
*/
esp_err_t http_server_get_stats(uint32_t* total_requests, uint32_t* active_connections, uint32_t* last_request_time);
/**
* @brief Reset server statistics
*
* Resets all server statistics counters to zero.
*
* @return ESP_OK on success
*/
esp_err_t http_server_reset_stats(void);
#endif // HTTP_SERVER_H

View File

@ -2,503 +2,207 @@
#include <string.h>
#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 "nvs_flash.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#include "cJSON.h"
#include "esp_task_wdt.h"
#include "nvs.h"
// WiFi credentials - CHANGE THESE TO YOUR NETWORK
#define WIFI_SSID "GL-AXT1800-0c2"
#define WIFI_PASS "CR7W25FM8S"
#define WIFI_MAXIMUM_RETRY 5
// Project modules
#include "config.h"
#include "motor_control.h"
#include "state_manager.h"
#include "wifi_manager.h"
#include "http_server.h"
// 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
// Task handles for watchdog
static TaskHandle_t main_task_handle = NULL;
// PWM configuration
#define PWM_FREQUENCY 1000
#define PWM_RESOLUTION LEDC_TIMER_8_BIT
#define PWM_R_CHANNEL LEDC_CHANNEL_0
#define PWM_L_CHANNEL LEDC_CHANNEL_1
static const char* TAG = "HTTP_MOTOR";
// 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
typedef enum {
MOTOR_OFF,
MOTOR_EXHAUST,
MOTOR_INTAKE
} motor_mode_t;
static motor_mode_t current_mode = MOTOR_OFF;
static int current_speed = 0;
// HTTP server handle
static httpd_handle_t server = NULL;
// HTML web page for control
static const char* html_page =
"<!DOCTYPE html>"
"<html>"
"<head>"
" <title>Maxxfan Controller</title>"
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
" <style>"
" body { font-family: Arial, sans-serif; margin: 40px; background: #f0f0f0; }"
" .container { max-width: 500px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }"
" h1 { color: #333; text-align: center; }"
" .control-group { margin: 20px 0; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }"
" .control-group h3 { margin-top: 0; color: #555; }"
" button { padding: 15px 25px; margin: 5px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }"
" .btn-off { background: #f44336; color: white; }"
" .btn-exhaust { background: #ff9800; color: white; }"
" .btn-intake { background: #4CAF50; color: white; }"
" .btn-off:hover { background: #d32f2f; }"
" .btn-exhaust:hover { background: #f57c00; }"
" .btn-intake:hover { background: #388e3c; }"
" .speed-control { margin: 20px 0; }"
" .speed-slider { width: 100%; height: 40px; }"
" .status { background: #e3f2fd; padding: 15px; border-radius: 5px; margin: 20px 0; }"
" .status h4 { margin: 0 0 10px 0; color: #1976d2; }"
" </style>"
"</head>"
"<body>"
" <div class=\"container\">"
" <h1>Maxxfan Controller</h1>"
" "
" <div class=\"status\">"
" <h4>Current Status</h4>"
" <p><strong>Mode:</strong> <span id=\"mode\">OFF</span></p>"
" <p><strong>Speed:</strong> <span id=\"speed\">0</span>%</p>"
" </div>"
" "
" <div class=\"control-group\">"
" <h3>Fan Control</h3>"
" <button class=\"btn-off\" onclick=\"setFan('off', 0)\">Turn OFF</button>"
" <button class=\"btn-exhaust\" onclick=\"setFan('exhaust', 50)\">Exhaust (50%)</button>"
" <button class=\"btn-intake\" onclick=\"setFan('intake', 50)\">Intake (50%)</button>"
" </div>"
" "
" <div class=\"control-group\">"
" <h3>Speed Control</h3>"
" <div class=\"speed-control\">"
" <label for=\"speedSlider\">Speed: <span id=\"speedValue\">50</span>%</label><br>"
" <input type=\"range\" id=\"speedSlider\" class=\"speed-slider\" min=\"0\" max=\"100\" value=\"50\" oninput=\"updateSpeed(this.value)\">"
" </div>"
" <button class=\"btn-exhaust\" onclick=\"setFanSpeed('exhaust')\">Set Exhaust Speed</button>"
" <button class=\"btn-intake\" onclick=\"setFanSpeed('intake')\">Set Intake Speed</button>"
" </div>"
" </div>"
""
" <script>"
" let currentSpeed = 50;"
" "
" function updateSpeed(value) {"
" currentSpeed = parseInt(value);"
" document.getElementById('speedValue').textContent = value;"
" }"
" "
" function setFan(mode, speed) {"
" currentSpeed = speed;"
" document.getElementById('speedSlider').value = speed;"
" document.getElementById('speedValue').textContent = speed;"
" "
" fetch('/fan', {"
" method: 'POST',"
" headers: { 'Content-Type': 'application/json' },"
" body: JSON.stringify({ mode: mode, speed: parseInt(speed) })"
" })"
" .then(response => response.json())"
" .then(data => updateStatus(data))"
" .catch(error => console.error('Error:', error));"
" }"
" "
" function setFanSpeed(mode) {"
" fetch('/fan', {"
" method: 'POST',"
" headers: { 'Content-Type': 'application/json' },"
" body: JSON.stringify({ mode: mode, speed: parseInt(currentSpeed) })"
" })"
" .then(response => response.json())"
" .then(data => updateStatus(data))"
" .catch(error => console.error('Error:', error));"
" }"
" "
" function updateStatus(data) {"
" document.getElementById('mode').textContent = data.mode.toUpperCase();"
" document.getElementById('speed').textContent = data.speed;"
" }"
" "
" function getStatus() {"
" fetch('/status')"
" .then(response => response.json())"
" .then(data => updateStatus(data))"
" .catch(error => console.error('Error:', error));"
" }"
" "
" // Update status every 2 seconds"
" setInterval(getStatus, 2000);"
" "
" // Get initial status"
" getStatus();"
" </script>"
"</body>"
"</html>";
// WiFi event handler (same as before)
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(TAG, "retry to connect to the AP");
} else {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(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));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void configure_gpio_pins(void)
{
ESP_LOGI(TAG, "Configuring GPIO pins...");
// Initialize watchdog timer
void init_watchdog(void) {
ESP_LOGI(SYSTEM_TAG, "Setting up watchdog monitoring...");
uint64_t pin_mask = (1ULL << LED_PIN) |
(1ULL << MOTOR_R_EN) |
(1ULL << MOTOR_L_EN);
// Get current task handle and add to watchdog
main_task_handle = xTaskGetCurrentTaskHandle();
esp_err_t result = esp_task_wdt_add(main_task_handle);
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(TAG, "GPIO pins configured");
}
void configure_pwm(void)
{
ESP_LOGI(TAG, "Configuring PWM...");
ledc_timer_config_t timer_conf = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.timer_num = LEDC_TIMER_0,
.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 = LEDC_LOW_SPEED_MODE,
.hpoint = 0,
.timer_sel = LEDC_TIMER_0
};
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(TAG, "PWM configured");
}
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;
current_mode = mode;
current_speed = speed_percent;
uint32_t duty = (speed_percent * 255) / 100;
if (mode == MOTOR_OFF || speed_percent == 0) {
ESP_LOGI(TAG, "Motor OFF");
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);
} else if (mode == MOTOR_EXHAUST) {
ESP_LOGI(TAG, "Motor EXHAUST - Speed: %d%%", speed_percent);
gpio_set_level(LED_PIN, 1);
gpio_set_level(MOTOR_R_EN, 1);
gpio_set_level(MOTOR_L_EN, 0);
vTaskDelay(pdMS_TO_TICKS(10));
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);
} else if (mode == MOTOR_INTAKE) {
ESP_LOGI(TAG, "Motor INTAKE - Speed: %d%%", speed_percent);
gpio_set_level(LED_PIN, 1);
gpio_set_level(MOTOR_R_EN, 0);
gpio_set_level(MOTOR_L_EN, 1);
vTaskDelay(pdMS_TO_TICKS(10));
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);
}
}
// HTTP handler for the main web page
static esp_err_t root_get_handler(httpd_req_t *req)
{
httpd_resp_set_type(req, "text/html");
httpd_resp_send(req, html_page, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
// HTTP handler for fan status (GET /status)
static esp_err_t status_get_handler(httpd_req_t *req)
{
cJSON *json = cJSON_CreateObject();
const char* mode_str = "off";
if (current_mode == MOTOR_EXHAUST) mode_str = "exhaust";
else if (current_mode == MOTOR_INTAKE) mode_str = "intake";
cJSON_AddStringToObject(json, "mode", mode_str);
cJSON_AddNumberToObject(json, "speed", current_speed);
char *json_string = cJSON_Print(json);
httpd_resp_set_type(req, "application/json");
httpd_resp_send(req, json_string, strlen(json_string));
free(json_string);
cJSON_Delete(json);
return ESP_OK;
}
// HTTP handler for fan control (POST /fan)
static esp_err_t fan_post_handler(httpd_req_t *req)
{
char buf[100];
int ret, remaining = req->content_len;
if (remaining >= sizeof(buf)) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too long");
return ESP_FAIL;
}
ret = httpd_req_recv(req, buf, remaining);
if (ret <= 0) {
if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "Request timeout");
}
return ESP_FAIL;
}
buf[ret] = '\0';
cJSON *json = cJSON_Parse(buf);
if (json == NULL) {
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Invalid JSON");
return ESP_FAIL;
}
cJSON *mode_json = cJSON_GetObjectItem(json, "mode");
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",
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);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing mode or speed");
return ESP_FAIL;
}
const char* mode_str = mode_json->valuestring;
int speed;
// Handle both number and string speed values
if (cJSON_IsNumber(speed_json)) {
speed = (int)speed_json->valuedouble;
} else if (cJSON_IsString(speed_json)) {
speed = atoi(speed_json->valuestring);
if (result == ESP_OK) {
ESP_LOGI(SYSTEM_TAG, "Main task added to watchdog monitoring");
} else if (result == ESP_ERR_INVALID_ARG) {
ESP_LOGI(SYSTEM_TAG, "Task already monitored by watchdog");
} else {
speed = 0;
ESP_LOGW(SYSTEM_TAG, "Watchdog not available: %s", esp_err_to_name(result));
main_task_handle = NULL; // Disable watchdog feeding
}
motor_mode_t mode = MOTOR_OFF;
if (strcmp(mode_str, "exhaust") == 0) {
mode = MOTOR_EXHAUST;
} else if (strcmp(mode_str, "intake") == 0) {
mode = MOTOR_INTAKE;
}
ESP_LOGI(TAG, "HTTP Request: mode=%s, speed=%d", mode_str, speed);
set_motor_speed(mode, speed);
cJSON_Delete(json);
// Send response
return status_get_handler(req);
}
// Start HTTP server
static httpd_handle_t start_webserver(void)
{
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.max_uri_handlers = 10;
ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
if (httpd_start(&server, &config) == ESP_OK) {
ESP_LOGI(TAG, "Registering URI handlers");
httpd_uri_t root = {
.uri = "/",
.method = HTTP_GET,
.handler = root_get_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &root);
httpd_uri_t status = {
.uri = "/status",
.method = HTTP_GET,
.handler = status_get_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &status);
httpd_uri_t fan = {
.uri = "/fan",
.method = HTTP_POST,
.handler = fan_post_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &fan);
return server;
}
ESP_LOGI(TAG, "Error starting server!");
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(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(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);
} else {
ESP_LOGE(TAG, "UNEXPECTED EVENT");
// Feed the watchdog
void feed_watchdog(void) {
if (main_task_handle != NULL) {
esp_err_t result = esp_task_wdt_reset();
if (result != ESP_OK) {
MOTOR_LOGD(SYSTEM_TAG, "Watchdog reset failed: %s", esp_err_to_name(result));
}
}
}
void app_main(void)
{
ESP_LOGI(TAG, "Starting Maxxfan HTTP Controller!");
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);
// Configure hardware
configure_gpio_pins();
configure_pwm();
// Initialize watchdog timer
init_watchdog();
ESP_LOGI(TAG, "Connecting to WiFi network: %s", WIFI_SSID);
wifi_init_sta();
// 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;
}
// Start HTTP server
start_webserver();
// 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(TAG, "=== Maxxfan Controller Ready! ===");
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");
// 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;
}
// 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...");
ret = http_server_init();
if (ret == ESP_OK) {
ESP_LOGI(SYSTEM_TAG, "✓ Web server started successfully");
} else {
ESP_LOGE(SYSTEM_TAG, "✗ Failed to start web server: %s", esp_err_to_name(ret));
}
// 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");
// 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));
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, "⏸️ Motor remains OFF");
}
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");
// 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);
// HTTP server statistics
uint32_t total_requests, active_connections, last_request_time;
http_server_get_stats(&total_requests, &active_connections, &last_request_time);
ESP_LOGI(SYSTEM_TAG, "HTTP Server: running=%s, requests=%lu",
http_server_is_running() ? "YES" : "NO", total_requests);
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, "WiFi: Enhanced connection management with auto-reconnect");
ESP_LOGI(SYSTEM_TAG, "State Manager: Enhanced NVS operations with validation and recovery");
ESP_LOGI(SYSTEM_TAG, "HTTP Server: Modular web server with comprehensive API");
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));
}
}

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