808 lines
30 KiB
C
Executable File
808 lines
30 KiB
C
Executable File
#include <stdio.h>
|
|
#include <string.h>
|
|
#include "freertos/FreeRTOS.h"
|
|
#include "freertos/task.h"
|
|
#include "freertos/event_groups.h"
|
|
#include "freertos/timers.h"
|
|
#include "esp_system.h"
|
|
#include "esp_wifi.h"
|
|
#include "esp_event.h"
|
|
#include "esp_log.h"
|
|
#include "esp_http_server.h"
|
|
#include "esp_task_wdt.h"
|
|
#include "nvs_flash.h"
|
|
#include "driver/gpio.h"
|
|
#include "driver/ledc.h"
|
|
#include "cJSON.h"
|
|
|
|
// WiFi credentials - CHANGE THESE TO YOUR NETWORK
|
|
#define WIFI_SSID "GL-AXT1800-0c2"
|
|
#define WIFI_PASS "CR7W25FM8S"
|
|
#define WIFI_MAXIMUM_RETRY 5
|
|
|
|
// Pin definitions
|
|
#define LED_PIN GPIO_NUM_13
|
|
#define MOTOR_R_EN GPIO_NUM_18
|
|
#define MOTOR_L_EN GPIO_NUM_19
|
|
#define PWM_R_PIN GPIO_NUM_21
|
|
#define PWM_L_PIN GPIO_NUM_22
|
|
|
|
// PWM configuration
|
|
#define PWM_FREQUENCY 20000
|
|
#define PWM_RESOLUTION LEDC_TIMER_8_BIT
|
|
#define PWM_R_CHANNEL LEDC_CHANNEL_0
|
|
#define PWM_L_CHANNEL LEDC_CHANNEL_1
|
|
|
|
// Motor ramping configuration
|
|
#define RAMP_STEP_MS 200 // Time between ramp steps (milliseconds)
|
|
#define RAMP_STEP_SIZE 2 // 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
|
|
|
|
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;
|
|
|
|
typedef enum {
|
|
MOTOR_STATE_IDLE, // Motor is off or running normally
|
|
MOTOR_STATE_RAMPING, // Motor is ramping up/down
|
|
MOTOR_STATE_STOPPING, // Motor is stopping for direction change
|
|
MOTOR_STATE_COOLDOWN, // Motor is in cooldown period
|
|
MOTOR_STATE_RESTARTING // Motor is restarting after cooldown
|
|
} motor_state_enum_t;
|
|
|
|
typedef struct {
|
|
motor_mode_t mode;
|
|
motor_mode_t pending_mode; // Mode to switch to after cooldown
|
|
int target_speed;
|
|
int pending_speed; // Speed to set after cooldown
|
|
int current_speed;
|
|
motor_state_enum_t state;
|
|
bool ramping;
|
|
TimerHandle_t ramp_timer;
|
|
TimerHandle_t cooldown_timer;
|
|
uint32_t cooldown_remaining_ms; // For status reporting
|
|
} motor_state_t;
|
|
|
|
static motor_state_t motor_state = {
|
|
.mode = MOTOR_OFF,
|
|
.pending_mode = MOTOR_OFF,
|
|
.target_speed = 0,
|
|
.pending_speed = 0,
|
|
.current_speed = 0,
|
|
.state = MOTOR_STATE_IDLE,
|
|
.ramping = false,
|
|
.ramp_timer = NULL,
|
|
.cooldown_timer = NULL,
|
|
.cooldown_remaining_ms = 0
|
|
};
|
|
|
|
// HTTP server handle
|
|
static httpd_handle_t server = NULL;
|
|
|
|
// Task handles for watchdog
|
|
static TaskHandle_t main_task_handle = NULL;
|
|
|
|
// 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}"
|
|
".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>"
|
|
"<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=\"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){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();"
|
|
"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
|
|
static void motor_ramp_timer_callback(TimerHandle_t xTimer);
|
|
static void motor_cooldown_timer_callback(TimerHandle_t xTimer);
|
|
static void apply_motor_pwm(int speed_percent);
|
|
static void start_motor_operation(motor_mode_t mode, int speed_percent);
|
|
|
|
// Initialize watchdog timer
|
|
void init_watchdog(void) {
|
|
ESP_LOGI(TAG, "Setting up watchdog monitoring...");
|
|
|
|
// Get current task handle and add to watchdog
|
|
main_task_handle = xTaskGetCurrentTaskHandle();
|
|
esp_err_t result = esp_task_wdt_add(main_task_handle);
|
|
|
|
if (result == ESP_OK) {
|
|
ESP_LOGI(TAG, "Main task added to watchdog monitoring");
|
|
} else if (result == ESP_ERR_INVALID_ARG) {
|
|
ESP_LOGI(TAG, "Task already monitored by watchdog");
|
|
} else {
|
|
ESP_LOGW(TAG, "Watchdog not available: %s", esp_err_to_name(result));
|
|
main_task_handle = NULL; // Disable watchdog feeding
|
|
}
|
|
}
|
|
|
|
// Feed the watchdog
|
|
void feed_watchdog(void) {
|
|
if (main_task_handle != NULL) {
|
|
esp_err_t result = esp_task_wdt_reset();
|
|
if (result != ESP_OK) {
|
|
ESP_LOGD(TAG, "Watchdog reset failed: %s", esp_err_to_name(result));
|
|
}
|
|
}
|
|
}
|
|
|
|
// WiFi event handler
|
|
static void event_handler(void* arg, esp_event_base_t event_base,
|
|
int32_t event_id, void* event_data)
|
|
{
|
|
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
|
|
esp_wifi_connect();
|
|
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
|
if (s_retry_num < WIFI_MAXIMUM_RETRY) {
|
|
esp_wifi_connect();
|
|
s_retry_num++;
|
|
ESP_LOGI(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...");
|
|
|
|
uint64_t pin_mask = (1ULL << LED_PIN) |
|
|
(1ULL << MOTOR_R_EN) |
|
|
(1ULL << MOTOR_L_EN);
|
|
|
|
gpio_config_t io_conf = {
|
|
.pin_bit_mask = pin_mask,
|
|
.mode = GPIO_MODE_OUTPUT,
|
|
.pull_up_en = GPIO_PULLUP_DISABLE,
|
|
.pull_down_en = GPIO_PULLDOWN_DISABLE,
|
|
.intr_type = GPIO_INTR_DISABLE
|
|
};
|
|
|
|
gpio_config(&io_conf);
|
|
|
|
gpio_set_level(LED_PIN, 0);
|
|
gpio_set_level(MOTOR_R_EN, 0);
|
|
gpio_set_level(MOTOR_L_EN, 0);
|
|
|
|
ESP_LOGI(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");
|
|
}
|
|
|
|
// Apply PWM to motor based on current mode and speed
|
|
static void apply_motor_pwm(int speed_percent) {
|
|
if (speed_percent < 0) speed_percent = 0;
|
|
if (speed_percent > 100) speed_percent = 100;
|
|
|
|
uint32_t duty = (speed_percent * 255) / 100;
|
|
|
|
if (motor_state.mode == MOTOR_OFF || speed_percent == 0) {
|
|
gpio_set_level(LED_PIN, 0);
|
|
gpio_set_level(MOTOR_R_EN, 0);
|
|
gpio_set_level(MOTOR_L_EN, 0);
|
|
ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL, 0);
|
|
ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL, 0);
|
|
ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL);
|
|
ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL);
|
|
|
|
} else if (motor_state.mode == MOTOR_EXHAUST) {
|
|
gpio_set_level(LED_PIN, 1);
|
|
gpio_set_level(MOTOR_R_EN, 1);
|
|
gpio_set_level(MOTOR_L_EN, 1);
|
|
ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL, duty);
|
|
ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL, 0);
|
|
ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL);
|
|
ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL);
|
|
|
|
} else if (motor_state.mode == MOTOR_INTAKE) {
|
|
gpio_set_level(LED_PIN, 1);
|
|
gpio_set_level(MOTOR_R_EN, 1);
|
|
gpio_set_level(MOTOR_L_EN, 1);
|
|
ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL, 0);
|
|
ledc_set_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL, duty);
|
|
ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_R_CHANNEL);
|
|
ledc_update_duty(LEDC_LOW_SPEED_MODE, PWM_L_CHANNEL);
|
|
}
|
|
}
|
|
|
|
// 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(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;
|
|
}
|
|
|
|
ESP_LOGD(TAG, "Ramping: %d%% (target: %d%%)", motor_state.current_speed, motor_state.target_speed);
|
|
}
|
|
|
|
apply_motor_pwm(motor_state.current_speed);
|
|
}
|
|
|
|
// Motor cooldown timer callback
|
|
static void motor_cooldown_timer_callback(TimerHandle_t xTimer) {
|
|
ESP_LOGI(TAG, "Cooldown complete - Starting motor in %s mode at %d%%",
|
|
motor_state.pending_mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE",
|
|
motor_state.pending_speed);
|
|
|
|
// Reset cooldown tracking
|
|
motor_state.cooldown_remaining_ms = 0;
|
|
|
|
// Start the motor in the pending mode
|
|
start_motor_operation(motor_state.pending_mode, motor_state.pending_speed);
|
|
}
|
|
|
|
// Update cooldown remaining time (called periodically)
|
|
static void update_cooldown_time(void) {
|
|
if (motor_state.state == MOTOR_STATE_COOLDOWN && motor_state.cooldown_remaining_ms > 0) {
|
|
if (motor_state.cooldown_remaining_ms >= 1000) {
|
|
motor_state.cooldown_remaining_ms -= 1000;
|
|
} else {
|
|
motor_state.cooldown_remaining_ms = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Start motor operation (internal function)
|
|
static void start_motor_operation(motor_mode_t mode, int 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(TAG, "Motor stopped immediately");
|
|
} else {
|
|
// 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(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;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Initialize motor ramping system
|
|
void init_motor_ramping(void) {
|
|
motor_state.ramp_timer = xTimerCreate(
|
|
"MotorRampTimer", // Timer name
|
|
pdMS_TO_TICKS(RAMP_STEP_MS), // Timer period
|
|
pdTRUE, // Auto-reload
|
|
(void*)0, // Timer ID
|
|
motor_ramp_timer_callback // Callback function
|
|
);
|
|
|
|
motor_state.cooldown_timer = xTimerCreate(
|
|
"MotorCooldownTimer", // Timer name
|
|
pdMS_TO_TICKS(DIRECTION_CHANGE_COOLDOWN_MS), // Timer period
|
|
pdFALSE, // One-shot
|
|
(void*)0, // Timer ID
|
|
motor_cooldown_timer_callback // Callback function
|
|
);
|
|
|
|
if (motor_state.ramp_timer == NULL || motor_state.cooldown_timer == NULL) {
|
|
ESP_LOGE(TAG, "Failed to create motor timers");
|
|
} else {
|
|
ESP_LOGI(TAG, "Motor control system initialized with direction change safety");
|
|
}
|
|
}
|
|
|
|
void set_motor_speed(motor_mode_t mode, int speed_percent)
|
|
{
|
|
if (speed_percent < 0) speed_percent = 0;
|
|
if (speed_percent > 100) speed_percent = 100;
|
|
|
|
ESP_LOGI(TAG, "Motor command: %s - Speed: %d%% (Current mode: %s, Current speed: %d%%, State: %d)",
|
|
mode == MOTOR_OFF ? "OFF" : (mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE"),
|
|
speed_percent,
|
|
motor_state.mode == MOTOR_OFF ? "OFF" : (motor_state.mode == MOTOR_EXHAUST ? "EXHAUST" : "INTAKE"),
|
|
motor_state.current_speed,
|
|
motor_state.state);
|
|
|
|
// If we're in cooldown, update the pending command
|
|
if (motor_state.state == MOTOR_STATE_COOLDOWN) {
|
|
motor_state.pending_mode = mode;
|
|
motor_state.pending_speed = speed_percent;
|
|
ESP_LOGI(TAG, "Motor in cooldown - command queued for execution");
|
|
return;
|
|
}
|
|
|
|
// Check if this is a direction change that requires cooldown
|
|
bool requires_cooldown = false;
|
|
if (motor_state.current_speed > 0 && motor_state.mode != MOTOR_OFF) {
|
|
if ((motor_state.mode == MOTOR_EXHAUST && mode == MOTOR_INTAKE) ||
|
|
(motor_state.mode == MOTOR_INTAKE && mode == MOTOR_EXHAUST)) {
|
|
requires_cooldown = true;
|
|
}
|
|
}
|
|
|
|
if (requires_cooldown) {
|
|
ESP_LOGI(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(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);
|
|
}
|
|
}
|
|
|
|
// 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");
|
|
}
|
|
|
|
// HTTP handler for the main web page
|
|
static esp_err_t root_get_handler(httpd_req_t *req)
|
|
{
|
|
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 cooldown time before reporting
|
|
update_cooldown_time();
|
|
|
|
ESP_LOGI(TAG, "Status request - Mode: %d, Current: %d%%, Target: %d%%, State: %d, Ramping: %s",
|
|
motor_state.mode, motor_state.current_speed, motor_state.target_speed,
|
|
motor_state.state, motor_state.ramping ? "YES" : "NO");
|
|
|
|
set_cors_headers(req);
|
|
httpd_resp_set_type(req, "application/json");
|
|
|
|
cJSON *json = cJSON_CreateObject();
|
|
|
|
const char* mode_str = "off";
|
|
if (motor_state.mode == MOTOR_EXHAUST) mode_str = "exhaust";
|
|
else if (motor_state.mode == MOTOR_INTAKE) mode_str = "intake";
|
|
|
|
const char* state_str = "idle";
|
|
switch (motor_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;
|
|
}
|
|
|
|
cJSON_AddStringToObject(json, "mode", mode_str);
|
|
cJSON_AddNumberToObject(json, "current_speed", motor_state.current_speed);
|
|
cJSON_AddNumberToObject(json, "target_speed", motor_state.target_speed);
|
|
cJSON_AddStringToObject(json, "state", state_str);
|
|
cJSON_AddBoolToObject(json, "ramping", motor_state.ramping);
|
|
cJSON_AddNumberToObject(json, "cooldown_remaining", motor_state.cooldown_remaining_ms);
|
|
|
|
// Add pending command info if in cooldown
|
|
if (motor_state.state == MOTOR_STATE_COOLDOWN) {
|
|
const char* pending_mode_str = "off";
|
|
if (motor_state.pending_mode == MOTOR_EXHAUST) pending_mode_str = "exhaust";
|
|
else if (motor_state.pending_mode == MOTOR_INTAKE) pending_mode_str = "intake";
|
|
|
|
cJSON_AddStringToObject(json, "pending_mode", pending_mode_str);
|
|
cJSON_AddNumberToObject(json, "pending_speed", motor_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)
|
|
{
|
|
char buf[200];
|
|
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(TAG, "Received POST data: %s", buf);
|
|
|
|
cJSON *json = cJSON_Parse(buf);
|
|
if (json == NULL) {
|
|
ESP_LOGE(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(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;
|
|
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 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)
|
|
{
|
|
set_cors_headers(req);
|
|
httpd_resp_set_status(req, "200 OK");
|
|
httpd_resp_send(req, NULL, 0);
|
|
return ESP_OK;
|
|
}
|
|
|
|
// Start HTTP server
|
|
static httpd_handle_t start_webserver(void)
|
|
{
|
|
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
|
config.max_uri_handlers = 15;
|
|
config.recv_wait_timeout = 10;
|
|
config.send_wait_timeout = 10;
|
|
|
|
ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
|
|
if (httpd_start(&server, &config) == ESP_OK) {
|
|
ESP_LOGI(TAG, "Registering URI handlers");
|
|
|
|
// Root handler
|
|
httpd_uri_t root = {
|
|
.uri = "/",
|
|
.method = HTTP_GET,
|
|
.handler = root_get_handler,
|
|
.user_ctx = NULL
|
|
};
|
|
httpd_register_uri_handler(server, &root);
|
|
|
|
// Status handler
|
|
httpd_uri_t status = {
|
|
.uri = "/status",
|
|
.method = HTTP_GET,
|
|
.handler = status_get_handler,
|
|
.user_ctx = NULL
|
|
};
|
|
httpd_register_uri_handler(server, &status);
|
|
|
|
// Fan control handler
|
|
httpd_uri_t fan = {
|
|
.uri = "/fan",
|
|
.method = HTTP_POST,
|
|
.handler = fan_post_handler,
|
|
.user_ctx = NULL
|
|
};
|
|
httpd_register_uri_handler(server, &fan);
|
|
|
|
// OPTIONS handler for CORS preflight
|
|
httpd_uri_t options_status = {
|
|
.uri = "/status",
|
|
.method = HTTP_OPTIONS,
|
|
.handler = options_handler,
|
|
.user_ctx = NULL
|
|
};
|
|
httpd_register_uri_handler(server, &options_status);
|
|
|
|
httpd_uri_t options_fan = {
|
|
.uri = "/fan",
|
|
.method = HTTP_OPTIONS,
|
|
.handler = options_handler,
|
|
.user_ctx = NULL
|
|
};
|
|
httpd_register_uri_handler(server, &options_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");
|
|
}
|
|
}
|
|
|
|
// Main application task with watchdog feeding
|
|
void main_task(void *pvParameters) {
|
|
ESP_LOGI(TAG, "Main task started");
|
|
|
|
while (1) {
|
|
feed_watchdog();
|
|
vTaskDelay(pdMS_TO_TICKS(5000)); // Feed watchdog every 5 seconds
|
|
}
|
|
}
|
|
|
|
void app_main(void)
|
|
{
|
|
ESP_LOGI(TAG, "Starting Maxxfan HTTP Controller with Direction Change Safety!");
|
|
|
|
// 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();
|
|
}
|
|
ESP_ERROR_CHECK(ret);
|
|
|
|
// Initialize watchdog timer
|
|
init_watchdog();
|
|
|
|
// Configure hardware
|
|
configure_gpio_pins();
|
|
configure_pwm();
|
|
|
|
// Initialize motor ramping system
|
|
init_motor_ramping();
|
|
|
|
ESP_LOGI(TAG, "Connecting to WiFi network: %s", WIFI_SSID);
|
|
wifi_init_sta();
|
|
|
|
// Start HTTP server
|
|
start_webserver();
|
|
|
|
ESP_LOGI(TAG, "=== Enhanced Maxxfan Controller Ready! ===");
|
|
ESP_LOGI(TAG, "Features: Motor Ramping, Direction Change Safety, Real-time Updates");
|
|
ESP_LOGI(TAG, "Safety: 10-second cooldown for direction changes");
|
|
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");
|
|
|
|
// Main loop - reset watchdog periodically
|
|
while (1) {
|
|
feed_watchdog();
|
|
vTaskDelay(pdMS_TO_TICKS(3000)); // Feed every 3 seconds (system default is usually 5s timeout)
|
|
}
|
|
} |