diff --git a/src/webserver.h b/src/webserver.h new file mode 100644 index 0000000..a98dbc4 --- /dev/null +++ b/src/webserver.h @@ -0,0 +1,54 @@ +#ifdef ESP32 +#include +#elif defined(ESP8266) +#include +#endif +#include +#include "ha.h" + +AsyncWebServer server(80); + +namespace WebServer { + void notFound(AsyncWebServerRequest *request) { + request->send(404, "text/plain", "Not found"); + } + + void setup() { + + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain", "Hello, world"); + }); + + server.on("/switch", HTTP_PUT, [](AsyncWebServerRequest *request) { + if (request->hasParam("id") && request->hasParam("state")) { + AsyncWebParameter* switchId = request->getParam("id"); + AsyncWebParameter* switchState = request->getParam("state"); + auto cmd = Command::mapCommandIds[string(switchId->value().c_str())]; + if (cmd) cmd->onCommand(switchState->value().c_str()); + request->send(200, "text/plain", switchState->value().c_str()); + } else { + request->send(200, "text/plain", "No parameters provided"); + } + }); + + server.on("/switch", HTTP_GET, [](AsyncWebServerRequest *request) { + char switchList[1024] = {}; + for ( auto it = Command::mapCommandIds.begin(); it != Command::mapCommandIds.end(); ++it ) + snprintf(switchList, sizeof(switchList), "%s ", it->first.c_str()); + request->send(200, "text/plain", switchList); + }); + + server.on("/restart", HTTP_GET, [](AsyncWebServerRequest *request) { + request->send(200, "text/plain"); + ESP.restart(); + }); + + server.onNotFound(notFound); + + server.begin(); + } + + void stop() { + server.end(); + } +}