Working UI with updates

This commit is contained in:
2025-07-09 11:12:10 -06:00
parent a4fa347557
commit 2febf4f902

View File

@ -79,127 +79,48 @@ static httpd_handle_t server = NULL;
// Task handles for watchdog
static TaskHandle_t main_task_handle = NULL;
// HTML web page for control (same as before)
// Compact 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; }"
" .ramping { background: #fff3e0; border-left: 4px solid #ff9800; padding: 10px; margin: 10px 0; }"
" </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>"
" <p><strong>Target:</strong> <span id=\"target\">0</span>%</p>"
" <div id=\"rampStatus\" class=\"ramping\" style=\"display: none;\">"
" <strong>Ramping in progress...</strong>"
" </div>"
" </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.current_speed;"
" document.getElementById('target').textContent = data.target_speed;"
" "
" const rampStatus = document.getElementById('rampStatus');"
" if (data.ramping) {"
" rampStatus.style.display = 'block';"
" } else {"
" rampStatus.style.display = 'none';"
" }"
" }"
" "
" function getStatus() {"
" fetch('/status')"
" .then(response => response.json())"
" .then(data => updateStatus(data))"
" .catch(error => console.error('Error:', error));"
" }"
" "
" // Update status every 1 second (faster to show ramping)"
" setInterval(getStatus, 1000);"
" "
" // Get initial status"
" getStatus();"
" </script>"
"</body>"
"</html>";
"<!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}"
".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><div id=\"rampStatus\" class=\"ramping\">Ramping...</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('rampStatus').style.display=data.ramping?'block':'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);
@ -458,9 +379,18 @@ void set_motor_speed(motor_mode_t mode, int 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;
@ -469,6 +399,13 @@ static esp_err_t root_get_handler(httpd_req_t *req)
// HTTP handler for fan status (GET /status)
static esp_err_t status_get_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "Status request - Mode: %d, Current: %d%%, Target: %d%%, Ramping: %s",
motor_state.mode, motor_state.current_speed, motor_state.target_speed,
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";
@ -481,10 +418,13 @@ static esp_err_t status_get_handler(httpd_req_t *req)
cJSON_AddBoolToObject(json, "ramping", motor_state.ramping);
char *json_string = cJSON_Print(json);
httpd_resp_set_type(req, "application/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;
}
@ -492,7 +432,7 @@ static esp_err_t status_get_handler(httpd_req_t *req)
// HTTP handler for fan control (POST /fan)
static esp_err_t fan_post_handler(httpd_req_t *req)
{
char buf[100];
char buf[200];
int ret, remaining = req->content_len;
if (remaining >= sizeof(buf)) {
@ -509,8 +449,11 @@ static esp_err_t fan_post_handler(httpd_req_t *req)
}
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;
}
@ -551,20 +494,32 @@ static esp_err_t fan_post_handler(httpd_req_t *req)
cJSON_Delete(json);
// Send response
// 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 = 10;
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,
@ -573,6 +528,7 @@ static httpd_handle_t start_webserver(void)
};
httpd_register_uri_handler(server, &root);
// Status handler
httpd_uri_t status = {
.uri = "/status",
.method = HTTP_GET,
@ -581,6 +537,7 @@ static httpd_handle_t start_webserver(void)
};
httpd_register_uri_handler(server, &status);
// Fan control handler
httpd_uri_t fan = {
.uri = "/fan",
.method = HTTP_POST,
@ -589,6 +546,23 @@ static httpd_handle_t start_webserver(void)
};
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;
}
@ -691,7 +665,7 @@ void app_main(void)
start_webserver();
ESP_LOGI(TAG, "=== Enhanced Maxxfan Controller Ready! ===");
ESP_LOGI(TAG, "Features: Motor Ramping, Optimized Performance");
ESP_LOGI(TAG, "Features: Motor Ramping, Optimized Performance, Real-time Updates");
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");