refactored webserver code

This commit is contained in:
Emanuele Trabattoni
2026-04-09 14:42:13 +02:00
parent 1e068476af
commit 155f58a347
4 changed files with 143 additions and 99 deletions

View File

@@ -7,18 +7,14 @@
#include <SPI.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
// Definitions
#include <tasks.h>
#include <devices.h>
#include <datasave.h>
#include <webserver.h>
#include <ui.h>
static File uploadFile;
static bool uploadFailed = false;
// FreeRTOS directives
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
@@ -29,20 +25,6 @@ static bool uploadFailed = false;
#define WIFI_SSID "AstroRotaxMonitor"
#define WIFI_PASSWORD "maledettirotax"
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client,
AwsEventType type, void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WS client IP[%s]-ID[%u] CONNECTED\r\n", client->remoteIP().toString().c_str(), client->id());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WS client ID[%u] DISCONNECTED\r\n", client->remoteIP().toString().c_str(), client->id());
break;
}
}
void setup()
{
Serial.begin(921600);
@@ -201,7 +183,7 @@ void loop()
RT_TASK_PRIORITY,
&trigA_TaskHandle,
CORE_0);
delay(100);
delay(100); // give some time to the thread to start
// Ignition B on Core 1
auto ignB_task_success = pdPASS;
@@ -214,7 +196,7 @@ void loop()
RT_TASK_PRIORITY, // priorità leggermente più alta
&trigB_TaskHandle,
CORE_1);
delay(100);
delay(100); // give some time to the thread to start
#endif
if (ignA_task_success != pdPASS || ignB_task_success != pdPASS)
@@ -234,78 +216,7 @@ void loop()
ignitionBoxStatus ign_info;
ignitionBoxStatusAverage ign_info_avg(filter_k);
LITTLEFSGuard fsGuard;
// Initialize Web page
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
ws.onEvent(onWsEvent);
server.addHandler(&ws);
server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
server.on("/upload", HTTP_POST,
[](AsyncWebServerRequest *request) {
if (uploadFailed)
{
request->send(500, "text/plain", "Upload failed");
}
else
{
request->send(200, "text/plain", "Upload successful");
}
},
[](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) {
if (index == 0)
{
uploadFailed = false;
String safeName = filename;
int slashIndex = safeName.lastIndexOf('/');
if (slashIndex >= 0)
{
safeName = safeName.substring(slashIndex + 1);
}
if (safeName.length() == 0)
{
uploadFailed = true;
return;
}
String filePath = "/" + safeName;
if (LittleFS.exists(filePath))
{
LittleFS.remove(filePath);
}
uploadFile = LittleFS.open(filePath, FILE_WRITE);
if (!uploadFile)
{
uploadFailed = true;
LOG_ERROR("Failed to open upload file:", filePath);
return;
}
}
if (!uploadFailed && uploadFile)
{
if (uploadFile.write(data, len) != len)
{
uploadFailed = true;
}
}
if (final && uploadFile)
{
uploadFile.close();
if (!uploadFailed)
{
LOG_INFO("Uploaded file to LittleFS:", filename);
}
}
});
server.begin();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/plain", "OK"); });
WebPage webPage(80, LittleFS); // Initialize webserver and Websocket
while (running)
{
@@ -328,14 +239,12 @@ void loop()
auto &hist = *active_history;
hist[counter++ % active_history->size()] = ign_info;
ign_info_avg.update(ign_info); // update moving average with latest ignition status
Serial.print("\033[2K Data Received: " + String(counter) + "/" + String(hist.size()) + '\r');
if (ws.count() > 0 && counter % filter_k == 0) // send data every 10 samples
Serial.printf("\033[2K Data Received: %d/%d\r", counter, hist.size());
if ( counter % filter_k == 0) // send data every 10 samples
{
Serial.println();
LOG_DEBUG("Sending average ignition status to websocket clients...");
auto msg = ign_info_avg.toJson().as<String>();
ws.textAll(msg);
webPage.sendWsData(ign_info_avg.toJson().as<String>());
}
}
else