Sporttafel-old/src/core/http.cpp
2025-01-10 12:14:02 +01:00

136 lines
2.9 KiB
C++

#include "http.h"
#include <ESPAsyncWebServer.h>
#include <app/App.h>
#include "log.h"
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
auto websocketStarted = false;
void httpActionLeft(AsyncWebServerRequest *request) {
if (app != nullptr) {
app->left();
}
request->send(200);
}
void httpActionUp(AsyncWebServerRequest *request) {
if (app != nullptr) {
app->up();
}
request->send(200);
}
void httpActionDown(AsyncWebServerRequest *request) {
if (app != nullptr) {
app->down();
}
request->send(200);
}
void httpActionRight(AsyncWebServerRequest *request) {
if (app != nullptr) {
app->right();
}
request->send(200);
}
void httpActionCancel(AsyncWebServerRequest *request) {
if (app != nullptr) {
app->cancel();
}
request->send(200);
}
void httpActionConfirm(AsyncWebServerRequest *request) {
if (app != nullptr) {
app->confirm();
}
request->send(200);
}
void httpAppConfig(AsyncWebServerRequest *request) {
if (!request->hasArg("key")) {
error("missing parameter 'key'");
request->send(400);
return;
}
if (!request->hasArg("value")) {
error("missing parameter 'value'");
request->send(400);
return;
}
if (app != nullptr) {
if (app->setConfig(request->arg("key"), request->arg("value"))) {
request->send(200);
return;
}
}
request->send(400);
}
void httpNotFound(AsyncWebServerRequest *request) {
if (request->method() == HTTP_OPTIONS) {
request->send(200);
} else {
request->send(404, "text/plain", "Not found");
}
}
const char *getWebsocketTypeName(AwsEventType type) {
switch (type) {
case WS_EVT_CONNECT:
return "CONNECT";
case WS_EVT_DISCONNECT:
return "DISCONNECT";
case WS_EVT_PONG:
return "PONG";
case WS_EVT_ERROR:
return "ERROR";
case WS_EVT_DATA:
return "DATA";
default:
return "[???]";
}
}
void httpSetup() {
server.on("/action/left", HTTP_GET, httpActionLeft);
server.on("/action/up", HTTP_GET, httpActionUp);
server.on("/action/down", HTTP_GET, httpActionDown);
server.on("/action/right", HTTP_GET, httpActionRight);
server.on("/action/cancel", HTTP_GET, httpActionCancel);
server.on("/action/confirm", HTTP_GET, httpActionConfirm);
server.on("/app/config", HTTP_GET, httpAppConfig);
server.serveStatic("/", LittleFS, "/http/", "max-age=86400").setDefaultFile("index.html");
server.onNotFound(httpNotFound);
server.addHandler(&ws);
server.begin();
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type");
websocketStarted = true;
}
void httpLoop() {
ws.cleanupClients();
}
void httpStop() {
ws.closeAll();
ws.enable(false);
server.end();
}
void websocketSendAll(const char *message) {
if (websocketStarted) {
ws.textAll(message);
}
}