diff --git a/library.json b/library.json index e32a3aa..932f164 100644 --- a/library.json +++ b/library.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/platformio/platformio-core/develop/platformio/assets/schema/library.json", "name": "ha-mqtt", - "version": "1.9.0", + "version": "1.10.0", "description": "Home Assistant classes for integration with MQTT auto discovery", "repository": { "type": "git", @@ -16,7 +16,8 @@ ], "dependencies": { "bblanchon/ArduinoJson": "6.21.5", - "marvinroger/AsyncMqttClient": "^0.9.0" + "marvinroger/AsyncMqttClient": "^0.9.0", + "esphome/ESPAsyncWebServer-esphome": "^3.4.0" }, "license": "MIT", "frameworks": "arduino", diff --git a/src/webserver.h b/src/webserver.h new file mode 100644 index 0000000..01c3db7 --- /dev/null +++ b/src/webserver.h @@ -0,0 +1,56 @@ +#ifdef ESP32 +#include +#elif defined(ESP8266) +#include +#endif +#include +#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(); + for (auto it = Command::mapCommandIds.begin(); it != Command::mapCommandIds.end(); ++it) { + StaticJsonDocument 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(); + } +}