Merge branch 'webserver' into v1.10.0
This commit is contained in:
commit
93c6c67822
56
src/webserver.h
Normal file
56
src/webserver.h
Normal file
@ -0,0 +1,56 @@
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESPAsyncTCP.h>
|
||||
#endif
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include "ha.h"
|
||||
|
||||
AsyncWebServer server(80);
|
||||
|
||||
namespace WebServer {
|
||||
|
||||
void setup() {
|
||||
|
||||
server.on("/commands", HTTP_POST, [](AsyncWebServerRequest *request) {
|
||||
if (request->hasParam("id", true) && request->hasParam("state", true)) {
|
||||
AsyncWebParameter* switchId = request->getParam("id", true);
|
||||
AsyncWebParameter* switchState = request->getParam("state", true);
|
||||
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", "Command not found");
|
||||
}
|
||||
} else {
|
||||
request->send(200, "text/plain", "No parameters provided");
|
||||
}
|
||||
});
|
||||
|
||||
server.on("/commands", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncResponseStream *response = request->beginResponseStream("application/json");
|
||||
|
||||
DynamicJsonDocument jsonResponse(JSON_SIZE*10);
|
||||
JsonArray array = jsonResponse.to<JsonArray>();
|
||||
for (auto it = Command::mapCommandIds.begin(); it != Command::mapCommandIds.end(); ++it) {
|
||||
StaticJsonDocument<JSON_SIZE/2> jsonDoc;
|
||||
it->second->toJson(jsonDoc);
|
||||
array.add(jsonDoc);
|
||||
}
|
||||
serializeJson(jsonResponse, *response);
|
||||
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
});
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void stop() {
|
||||
server.end();
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user