mirror of
https://github.com/rstrouse/ESPSomfy-RTS.git
synced 2026-10-31 22:02:17 +01:00
feat!: remove the old API, ports 8081 and 8080 (step 4a)
Step 4a of docs/SECURITY_PLAN.md. Port 80 keeps the eleven HTTP routes of ADR 0006 and the socket at /ws; everything else moved to protocol 2. - Port 8081 (ApiRoutes) and the socket on 8080 (SocketEmitter) are gone. Protocol 2 owns its frame buffer and loop-task check. - Port 80 drops every route the old web UI called: reads, edits, settings, scans, reboot, /shades.cfg, /discovery. HttpRoutes.cpp holds what stays. - ModelSnapshot, SnapshotSlots and the read documents are gone. The item snapshot types stay, as ItemSnapshot, for events, MQTT and the command replies. - Model edits reply only to their protocol 2 op: requestResult goes. - The settings' toJSON writers, used only by the settings routes, go. - The _espsomfy_rts._tcp mDNS record moves to port 80, with path=/ws. - The memory event reports the loop-rate window it closes. - A deleted room no longer re-publishes its retained MQTT topics. - e2e: the heap check reads the sync's status; the sync is checked on its own instead of against /controller. - README gets an API and ports section. BREAKING CHANGE: ports 8081 and 8080 and the old HTTP routes are gone. Home Assistant needs integration 3.0.0 or newer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c91c20d444
commit
2a954aa158
53 changed files with 613 additions and 3549 deletions
|
|
@ -1,51 +0,0 @@
|
|||
#include <ESPAsyncWebServer.h>
|
||||
#include <AsyncJson.h>
|
||||
#include "Web.h"
|
||||
#include "WebRoutes.h"
|
||||
|
||||
// ApiRoutes: the routes integrations such as Home Assistant call on port 8081.
|
||||
// The handlers are the ones the config web UI calls too (Web.cpp).
|
||||
|
||||
extern Web webServer;
|
||||
|
||||
void registerApiRoutes(AsyncWebServer &server) {
|
||||
// GET endpoints
|
||||
server.on("/discovery", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *r) { webServer.handleDiscovery(r); });
|
||||
server.on("/rooms", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *r) { webServer.handleGetRooms(r); });
|
||||
server.on("/shades", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *r) { webServer.handleGetShades(r); });
|
||||
server.on("/groups", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *r) { webServer.handleGetGroups(r); });
|
||||
server.on("/controller", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *r) { webServer.handleController(r); });
|
||||
server.on("/room", HTTP_GET, [](AsyncWebServerRequest *r) { webServer.handleRoom(r); });
|
||||
server.on("/shade", HTTP_GET, [](AsyncWebServerRequest *r) { webServer.handleShade(r); });
|
||||
server.on("/group", HTTP_GET, [](AsyncWebServerRequest *r) { webServer.handleGroup(r); });
|
||||
server.on("/backup", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *r) { webServer.handleBackup(r); });
|
||||
server.on("/reboot", WebRequestMethodComposite(HTTP_POST) | HTTP_PUT, [](AsyncWebServerRequest *r) { webServer.handleReboot(r); });
|
||||
// JSON body endpoints
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/shadeCommand",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleShadeCommand(r, j); }));
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/groupCommand",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleGroupCommand(r, j); }));
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/tiltCommand",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleTiltCommand(r, j); }));
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/repeatCommand",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleRepeatCommand(r, j); }));
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setPositions",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleSetPositions(r, j); }));
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setSensor",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleSetSensor(r, j); }));
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/login",
|
||||
[](AsyncWebServerRequest *r, JsonVariant &j) { webServer.handleLogin(r, j); }));
|
||||
// GET fallback for command endpoints (query params)
|
||||
server.on("/shadeCommand", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleShadeCommand(r, v); });
|
||||
server.on("/groupCommand", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleGroupCommand(r, v); });
|
||||
server.on("/tiltCommand", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleTiltCommand(r, v); });
|
||||
server.on("/repeatCommand", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleRepeatCommand(r, v); });
|
||||
server.on("/setPositions", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleSetPositions(r, v); });
|
||||
server.on("/setSensor", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleSetSensor(r, v); });
|
||||
server.on("/login", HTTP_GET, [](AsyncWebServerRequest *r) { JsonVariant v; webServer.handleLogin(r, v); });
|
||||
// OPTIONS preflight + not found
|
||||
server.onNotFound([](AsyncWebServerRequest *r) {
|
||||
if(r->method() == HTTP_OPTIONS) { r->send(200); return; }
|
||||
webServer.handleNotFound(r);
|
||||
});
|
||||
}
|
||||
234
src/entryPoints/HttpRoutes.cpp
Normal file
234
src/entryPoints/HttpRoutes.cpp
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
#include <LittleFS.h>
|
||||
#include <Update.h>
|
||||
#include "TaskWdt.h"
|
||||
#include "esp_log.h"
|
||||
#include "ConfigSettings.h"
|
||||
#include "ConfigFile.h"
|
||||
#include "Utils.h"
|
||||
#include "SSDP.h"
|
||||
#include "Somfy.h"
|
||||
#include "LoopQueue.h"
|
||||
#include "Web.h"
|
||||
#include "WebRoutes.h"
|
||||
#include "MqttConnection.h"
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <AsyncJson.h>
|
||||
|
||||
// HttpRoutes: the HTTP routes on port 80, the web UI's files and the few that
|
||||
// stay HTTP (docs/adr/0006-two-security-modes-eleven-http-routes.md).
|
||||
// Everything else is an op on the socket at /ws.
|
||||
|
||||
extern ConfigSettings settings;
|
||||
extern SSDPClass SSDP;
|
||||
extern rebootDelay_t rebootDelay;
|
||||
extern SomfyShadeController somfy;
|
||||
extern Web webServer;
|
||||
extern MqttConnection mqtt;
|
||||
|
||||
static const char *TAG = "Web";
|
||||
|
||||
// A restore's options travel through the loop queue as RESTORE_* bits.
|
||||
static uint8_t restoreParts(const restore_options_t &opts) {
|
||||
return (opts.settings ? RESTORE_SETTINGS : 0) | (opts.shades ? RESTORE_SHADES : 0) |
|
||||
(opts.network ? RESTORE_NETWORK : 0) | (opts.transceiver ? RESTORE_TRANSCEIVER : 0) |
|
||||
(opts.repeaters ? RESTORE_REPEATERS : 0) | (opts.mqtt ? RESTORE_MQTT : 0);
|
||||
}
|
||||
// The radio and MQTT are shut down once an upload starts and only a reboot
|
||||
// brings them back. The completion handler schedules it but never runs if the
|
||||
// client goes away mid-upload, so make sure the device reboots then too.
|
||||
static void onUploadDisconnect() {
|
||||
if(webServer.uploadSuccess || rebootDelay.reboot) return;
|
||||
ESP_LOGW(TAG, "Upload abandoned, rebooting");
|
||||
if(Update.isRunning()) Update.abort();
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
}
|
||||
void registerHttpRoutes(AsyncWebServer &server) {
|
||||
server.on("/loginContext", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncJsonResponse *response = new AsyncJsonResponse();
|
||||
JsonObject root = response->getRoot().to<JsonObject>();
|
||||
root["type"] = static_cast<uint8_t>(settings.Security.type);
|
||||
root["permissions"] = settings.Security.permissions;
|
||||
root["serverId"] = settings.serverId;
|
||||
root["version"] = settings.fwVersion.name;
|
||||
root["model"] = "ESPSomfyRTS";
|
||||
root["hostname"] = settings.hostname;
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
// Commands for scripts, as a JSON body or query parameters.
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/shadeCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleShadeCommand(request, json); }));
|
||||
server.on("/shadeCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleShadeCommand(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/groupCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleGroupCommand(request, json); }));
|
||||
server.on("/groupCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleGroupCommand(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/tiltCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleTiltCommand(request, json); }));
|
||||
server.on("/tiltCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleTiltCommand(request, v); });
|
||||
|
||||
server.on("/upnp.xml", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncResponseStream *response = request->beginResponseStream("text/xml");
|
||||
SSDP.schema(*response);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/login",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleLogin(request, json); }));
|
||||
server.on("/login", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleLogin(request, v); });
|
||||
|
||||
server.on("/backup", HTTP_GET, [](AsyncWebServerRequest *request) { webServer.handleBackup(request); });
|
||||
|
||||
server.on("/restore", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
if(webServer.uploadSuccess) {
|
||||
restore_options_t opts;
|
||||
if(asyncHasParam(request, "data")) {
|
||||
String dataStr = asyncParam(request, "data");
|
||||
ESP_LOGD(TAG, "%s", dataStr.c_str());
|
||||
JsonDocument doc;
|
||||
DeserializationError err = deserializeJson(doc, dataStr);
|
||||
if(err) {
|
||||
request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}");
|
||||
return;
|
||||
}
|
||||
else {
|
||||
JsonObject obj = doc.as<JsonObject>();
|
||||
opts.fromJSON(obj);
|
||||
}
|
||||
}
|
||||
else {
|
||||
ESP_LOGD(TAG, "No restore options sent. Using defaults...");
|
||||
opts.shades = true;
|
||||
}
|
||||
// Checked here so the client hears about a bad file. It only reads
|
||||
// the file; the shades are still changed on loop() alone.
|
||||
if(!ShadeConfigFile::validateFile("/shades.tmp")) {
|
||||
LittleFS.remove("/shades.tmp");
|
||||
request->send(400, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"This isn't a valid backup file, so nothing was restored.\"}"));
|
||||
return;
|
||||
}
|
||||
// The main loop restores, since it owns the shades and their rolling
|
||||
// codes, and then reboots.
|
||||
loop_item_t item;
|
||||
item.type = loop_item_type_t::restore_shades;
|
||||
item.restoreParts = restoreParts(opts);
|
||||
if(!queueLoopItem(request, item)) return;
|
||||
request->send(200, _encoding_json, "{\"status\":\"Success\",\"desc\":\"Restoring Shade settings\"}");
|
||||
}
|
||||
else request->send(400, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"The upload didn't complete, so nothing was restored.\"}"));
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
resetTaskWdt();
|
||||
if(index == 0) {
|
||||
webServer.uploadSuccess = false;
|
||||
ESP_LOGD(TAG, "Restore: %s", filename.c_str());
|
||||
File fup = LittleFS.open("/shades.tmp", "w");
|
||||
fup.close();
|
||||
}
|
||||
if(len > 0) {
|
||||
File fup = LittleFS.open("/shades.tmp", "a");
|
||||
fup.write(data, len);
|
||||
fup.close();
|
||||
}
|
||||
if(final) {
|
||||
webServer.uploadSuccess = true;
|
||||
}
|
||||
});
|
||||
|
||||
// updateFirmware - file upload
|
||||
server.on("/updateFirmware", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
if(Update.hasError())
|
||||
request->send(500, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"Error updating firmware: \"}");
|
||||
else
|
||||
request->send(200, _encoding_json, "{\"status\":\"SUCCESS\",\"desc\":\"Successfully updated firmware\"}");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
if(index == 0) {
|
||||
webServer.uploadSuccess = false;
|
||||
ESP_LOGI(TAG, "Update: %s", filename.c_str());
|
||||
if(!Update.begin(UPDATE_SIZE_UNKNOWN)) {
|
||||
ESP_LOGE(TAG, "Update begin failed");
|
||||
}
|
||||
else {
|
||||
somfy.transceiver.end();
|
||||
mqtt.end();
|
||||
request->onDisconnect(onUploadDisconnect);
|
||||
}
|
||||
}
|
||||
if(len > 0) {
|
||||
if(Update.write(data, len) != len) {
|
||||
ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", filename.c_str(), len);
|
||||
Update.abort();
|
||||
}
|
||||
}
|
||||
if(final) {
|
||||
if(Update.end(true)) {
|
||||
ESP_LOGI(TAG, "Update Success: %u Rebooting...", index + len);
|
||||
webServer.uploadSuccess = true;
|
||||
}
|
||||
else {
|
||||
ESP_LOGE(TAG, "Update end failed");
|
||||
}
|
||||
}
|
||||
resetTaskWdt();
|
||||
});
|
||||
|
||||
// updateApplication - file upload
|
||||
server.on("/updateApplication", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
if(Update.hasError())
|
||||
request->send(500, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"Error updating application: \"}");
|
||||
else
|
||||
request->send(200, _encoding_json, "{\"status\":\"SUCCESS\",\"desc\":\"Successfully updated application\"}");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
if(index == 0) {
|
||||
webServer.uploadSuccess = false;
|
||||
ESP_LOGI(TAG, "Update: %s", filename.c_str());
|
||||
if(!Update.begin(UPDATE_SIZE_UNKNOWN, U_SPIFFS)) {
|
||||
ESP_LOGE(TAG, "Update begin failed");
|
||||
}
|
||||
else {
|
||||
somfy.transceiver.end();
|
||||
mqtt.end();
|
||||
request->onDisconnect(onUploadDisconnect);
|
||||
}
|
||||
}
|
||||
if(len > 0) {
|
||||
if(Update.write(data, len) != len) {
|
||||
ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", filename.c_str(), len);
|
||||
Update.abort();
|
||||
}
|
||||
}
|
||||
if(final) {
|
||||
if(Update.end(true)) {
|
||||
webServer.uploadSuccess = true;
|
||||
ESP_LOGI(TAG, "Update Success: %u Rebooting...", index + len);
|
||||
somfy.commit();
|
||||
}
|
||||
else {
|
||||
somfy.commit();
|
||||
ESP_LOGE(TAG, "Update end failed");
|
||||
}
|
||||
}
|
||||
resetTaskWdt();
|
||||
});
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *r) {
|
||||
if(r->method() == HTTP_OPTIONS) { r->send(200); return; }
|
||||
webServer.handleNotFound(r);
|
||||
});
|
||||
|
||||
// serveStatic MUST be registered AFTER all route handlers so it doesn't shadow them
|
||||
server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
|
||||
|
||||
}
|
||||
|
|
@ -1,7 +1,4 @@
|
|||
#include <WiFi.h>
|
||||
#include <LittleFS.h>
|
||||
#include <Update.h>
|
||||
#include <esp_task_wdt.h>
|
||||
#include <esp_timer.h>
|
||||
#include "esp_log.h"
|
||||
#include "mbedtls/md.h"
|
||||
|
|
@ -9,52 +6,36 @@
|
|||
#include <esp_random.h>
|
||||
#include <bootloader_random.h>
|
||||
#include "ConfigSettings.h"
|
||||
#include "ConfigFile.h"
|
||||
#include "Utils.h"
|
||||
#include "SSDP.h"
|
||||
#include "Somfy.h"
|
||||
#include "WResp.h"
|
||||
#include "LoopQueue.h"
|
||||
#include "ModelSnapshot.h"
|
||||
#include "ItemSnapshot.h"
|
||||
#include "SomfySnapshot.h"
|
||||
#include "SomfyEditor.h"
|
||||
#include "Web.h"
|
||||
#include "WebRoutes.h"
|
||||
#include "outputs/ProtoSocket.h"
|
||||
#include "MqttConnection.h"
|
||||
#include "ESPNetwork.h"
|
||||
#include "Timing.h"
|
||||
#include "LoginThrottle.h"
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <AsyncJson.h>
|
||||
#include <memory>
|
||||
|
||||
extern ConfigSettings settings;
|
||||
extern SSDPClass SSDP;
|
||||
extern rebootDelay_t rebootDelay;
|
||||
extern LoopStats loopStats;
|
||||
extern SomfyShadeController somfy;
|
||||
extern Web webServer;
|
||||
extern MqttConnection mqtt;
|
||||
extern ESPNetwork net;
|
||||
extern LoopQueue loopQueue;
|
||||
extern SnapshotSlots snapshotSlots;
|
||||
|
||||
char g_async_content[WEB_MAX_RESPONSE];
|
||||
|
||||
|
||||
// General responses
|
||||
static const char _response_404[] = "404: Service Not Found";
|
||||
|
||||
|
||||
// Encodings
|
||||
const char _encoding_text[] = "text/plain";
|
||||
const char _encoding_json[] = "application/json";
|
||||
|
||||
static const char *TAG = "Web";
|
||||
|
||||
// Failed logins per client IP, on both web servers.
|
||||
// Failed logins per client IP.
|
||||
static LoginThrottle loginThrottle;
|
||||
// The throttle's key for a client: its IPv4 address. The firmware doesn't
|
||||
// enable IPv6; an IPv6 client would share key 0 with every other one.
|
||||
|
|
@ -65,7 +46,7 @@ static uint64_t loginNow() { return (uint64_t)esp_timer_get_time() / 1000; }
|
|||
// The tokens' HMAC key. It has its own NVS namespace, which no settings
|
||||
// save clears and no backup holds, so only erasing NVS replaces it.
|
||||
static uint8_t tokenKey[API_TOKEN_KEY_SIZE];
|
||||
// Reads the token key, or makes one on first boot. Runs before either web
|
||||
// Reads the token key, or makes one on first boot. Runs before the web
|
||||
// server starts, so no token is made with an empty key, and before WiFi, so
|
||||
// the hardware RNG takes its entropy from the bootloader's source: calling it
|
||||
// once the radio is on would disturb WiFi.
|
||||
|
|
@ -82,6 +63,14 @@ static void loadTokenKey() {
|
|||
pref.end();
|
||||
}
|
||||
|
||||
// Sent when a command can't be handed to the main loop.
|
||||
static void sendQueueFull(AsyncWebServerRequest *request) {
|
||||
request->send(503, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Command queue full\"}"));
|
||||
}
|
||||
// Sent when the radio can't take a frame (suspended or queue full).
|
||||
static void sendRadioUnavailable(AsyncWebServerRequest *request) {
|
||||
request->send(503, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Radio TX unavailable\"}"));
|
||||
}
|
||||
// Hands an item to loop(), which owns the shades. When it can't be the
|
||||
// request is answered with the reason and false is returned.
|
||||
bool queueLoopItem(AsyncWebServerRequest *request, const loop_item_t &item) {
|
||||
|
|
@ -91,27 +80,15 @@ bool queueLoopItem(AsyncWebServerRequest *request, const loop_item_t &item) {
|
|||
if(!loopQueue.submit(item)) { sendQueueFull(request); return false; }
|
||||
return true;
|
||||
}
|
||||
bool queueShadeRequest(AsyncWebServerRequest *request, const shade_request_t &req) {
|
||||
static bool queueShadeRequest(AsyncWebServerRequest *request, const shade_request_t &req) {
|
||||
loop_item_t item;
|
||||
item.request = req;
|
||||
return queueLoopItem(request, item);
|
||||
}
|
||||
// Sent when a command can't be handed to the main loop.
|
||||
void sendQueueFull(AsyncWebServerRequest *request) {
|
||||
request->send(503, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Command queue full\"}"));
|
||||
}
|
||||
// Sent when the radio can't take a frame (suspended or queue full).
|
||||
void sendRadioUnavailable(AsyncWebServerRequest *request) {
|
||||
request->send(503, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Radio TX unavailable\"}"));
|
||||
}
|
||||
|
||||
AsyncWebServer asyncServer(80);
|
||||
AsyncWebServer asyncApiServer(8081);
|
||||
void Web::startup() {
|
||||
ESP_LOGI(TAG, "Launching web server...");
|
||||
loadTokenKey();
|
||||
asyncApiServer.begin();
|
||||
ESP_LOGI(TAG, "Async API server started on port 8081");
|
||||
}
|
||||
void Web::loop() {
|
||||
delay(1);
|
||||
|
|
@ -187,183 +164,20 @@ bool asyncHasParam(AsyncWebServerRequest *request, const char *name) {
|
|||
}
|
||||
|
||||
// -- Serialization helpers --
|
||||
// Replies that still read the live shade model on this task (command and edit
|
||||
// replies) copy one item into the ModelSnapshot types and write it the way the
|
||||
// read routes do. The read routes themselves write from a ModelSnapshot that
|
||||
// loop() fills (sendSnapshot).
|
||||
void serializeShadeRef(SomfyShade *shade, JsonFormatter &json) {
|
||||
// The command replies read the live shade model on this task: they copy the
|
||||
// one item into the snapshot types and write its reference.
|
||||
static void serializeShadeRef(SomfyShade *shade, JsonFormatter &json) {
|
||||
shade_snapshot_t s;
|
||||
snapshotShade(*shade, s);
|
||||
writeShadeRef(json, s);
|
||||
}
|
||||
// paired and lastRollingCode are passed in for a response that reports the
|
||||
// change the main loop is about to make. An unpair is held until it goes on
|
||||
// air (holdLoopItem), so the answer comes true.
|
||||
void serializeShade(SomfyShade *shade, JsonFormatter &json, bool paired, uint16_t lastRollingCode) {
|
||||
shade_snapshot_t s;
|
||||
snapshotShade(*shade, s);
|
||||
s.paired = paired;
|
||||
s.lastRollingCode = lastRollingCode;
|
||||
writeShade(json, s);
|
||||
}
|
||||
void serializeShade(SomfyShade *shade, JsonFormatter &json) { serializeShade(shade, json, shade->paired, shade->lastRollingCode); }
|
||||
static void serializeGroupRef(SomfyGroup *group, JsonFormatter &json) {
|
||||
group_snapshot_t s;
|
||||
snapshotGroup(*group, s);
|
||||
writeGroupRef(json, s);
|
||||
}
|
||||
static void serializeGroup(SomfyGroup *group, JsonFormatter &json) {
|
||||
group_snapshot_t s;
|
||||
snapshotGroup(*group, s);
|
||||
shade_snapshot_t linked;
|
||||
writeGroup(json, s, liveShade, &linked);
|
||||
}
|
||||
void serializeTransceiverConfig(JsonFormatter &json) {
|
||||
auto &cfg = somfy.transceiver.config;
|
||||
json.addElem("type", cfg.type);
|
||||
json.addElem("TXPin", cfg.TXPin);
|
||||
json.addElem("RXPin", cfg.RXPin);
|
||||
json.addElem("SCKPin", cfg.SCKPin);
|
||||
json.addElem("MOSIPin", cfg.MOSIPin);
|
||||
json.addElem("MISOPin", cfg.MISOPin);
|
||||
json.addElem("CSNPin", cfg.CSNPin);
|
||||
json.addElem("rxBandwidth", cfg.rxBandwidth);
|
||||
json.addElem("frequency", cfg.frequency);
|
||||
json.addElem("deviation", cfg.deviation);
|
||||
json.addElem("txPower", cfg.txPower);
|
||||
json.addElem("proto", static_cast<uint8_t>(cfg.proto));
|
||||
json.addElem("enabled", cfg.enabled);
|
||||
json.addElem("noiseDetection", cfg.noiseDetection);
|
||||
json.addElem("radioInit", cfg.radioInit);
|
||||
}
|
||||
void serializeAppVersion(JsonFormatter &json, appver_t &ver) {
|
||||
json.addElem("name", ver.name);
|
||||
json.addElem("major", ver.major);
|
||||
json.addElem("minor", ver.minor);
|
||||
json.addElem("build", ver.build);
|
||||
json.addElem("suffix", ver.suffix);
|
||||
}
|
||||
void serializeVersion(JsonFormatter &json) {
|
||||
json.beginObject("fwVersion");
|
||||
serializeAppVersion(json, settings.fwVersion);
|
||||
json.endObject();
|
||||
json.beginObject("appVersion");
|
||||
serializeAppVersion(json, settings.appVersion);
|
||||
json.endObject();
|
||||
}
|
||||
|
||||
// The parts of /controller that aren't in the shade model.
|
||||
static void controllerHeader(JsonFormatter &json, const model_snapshot_t &snap) {
|
||||
json.addElem("maxRooms", (uint8_t)SOMFY_MAX_ROOMS);
|
||||
json.addElem("maxShades", (uint8_t)SOMFY_MAX_SHADES);
|
||||
json.addElem("maxGroups", (uint8_t)SOMFY_MAX_GROUPS);
|
||||
json.addElem("maxGroupedShades", (uint8_t)SOMFY_MAX_GROUPED_SHADES);
|
||||
json.addElem("maxLinkedRemotes", (uint8_t)SOMFY_MAX_LINKED_REMOTES);
|
||||
json.addElem("startingAddress", snap.startingAddress);
|
||||
json.beginObject("transceiver");
|
||||
json.beginObject("config");
|
||||
serializeTransceiverConfig(json);
|
||||
json.endObject();
|
||||
json.endObject();
|
||||
json.beginObject("version");
|
||||
serializeVersion(json);
|
||||
json.endObject();
|
||||
}
|
||||
// The parts of /discovery that aren't in the shade model.
|
||||
static void discoveryHeader(JsonFormatter &json, const model_snapshot_t &snap) {
|
||||
(void)snap;
|
||||
json.addElem("serverId", settings.serverId);
|
||||
json.addElem("version", settings.fwVersion.name);
|
||||
json.addElem("model", "ESPSomfyRTS");
|
||||
json.addElem("hostname", settings.hostname);
|
||||
json.addElem("authType", static_cast<uint8_t>(settings.Security.type));
|
||||
json.addElem("permissions", settings.Security.permissions);
|
||||
json.addElem("chipModel", settings.chipModel);
|
||||
json.addElem("connType", net.connTypeName());
|
||||
json.beginObject("memory");
|
||||
json.addElem("max", ESP.getMaxAllocHeap());
|
||||
json.addElem("free", ESP.getFreeHeap());
|
||||
json.addElem("min", ESP.getMinFreeHeap());
|
||||
json.addElem("total", ESP.getHeapSize());
|
||||
json.addElem("uptime", (uint64_t)millis());
|
||||
// This runs on the web server's task, so it reports the last window the
|
||||
// loop task closed rather than reading the one it is still filling.
|
||||
json.addElem("loopRate", loopStats.publishedRate());
|
||||
json.addElem("loopMaxUs", loopStats.publishedMaxUs());
|
||||
json.endObject();
|
||||
}
|
||||
|
||||
// A read served from a ModelSnapshot that loop() fills, so the document
|
||||
// describes one moment (docs/adr/0002-loop-task-is-the-only-writer-of-the-shade-model.md).
|
||||
// Each item is formatted into a fixed 3 KB unit and streamed as the TCP send
|
||||
// window allows, so there is no growing response buffer either.
|
||||
struct SnapshotRead {
|
||||
uint8_t slot;
|
||||
char unit[SNAPSHOT_UNIT_SIZE];
|
||||
SnapshotWriter writer;
|
||||
SnapshotRead(uint8_t slot, snapshot_doc_t doc, uint8_t id, snapshot_header_t header)
|
||||
: slot(slot), writer(snapshotSlots.snapshot(slot), doc, id, header, unit, sizeof(unit)) {}
|
||||
// The response is gone, whether it finished or the client went away.
|
||||
~SnapshotRead() { snapshotSlots.release(this->slot); }
|
||||
};
|
||||
void sendSnapshot(AsyncWebServerRequest *request, snapshot_doc_t doc, uint8_t id, snapshot_header_t header) {
|
||||
const int8_t slot = snapshotSlots.acquire();
|
||||
if(slot < 0) {
|
||||
request->send(503, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Busy, try the read again\"}"));
|
||||
return;
|
||||
}
|
||||
loop_item_t item;
|
||||
item.type = loop_item_type_t::snapshot_fill;
|
||||
item.slot = static_cast<uint8_t>(slot);
|
||||
if(!loopQueue.submit(item)) {
|
||||
snapshotSlots.cancel(slot);
|
||||
sendQueueFull(request);
|
||||
return;
|
||||
}
|
||||
auto read = std::make_shared<SnapshotRead>(static_cast<uint8_t>(slot), doc, id, header);
|
||||
// The headers go now; the body waits until loop() has filled the snapshot.
|
||||
// The library asks again on the next ACK or poll.
|
||||
AsyncWebServerResponse *response = request->beginChunkedResponse(_encoding_json,
|
||||
[read](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
|
||||
(void)index;
|
||||
if(!snapshotSlots.filled(read->slot)) return RESPONSE_TRY_AGAIN;
|
||||
return read->writer.generate(buffer, maxLen);
|
||||
});
|
||||
request->send(response);
|
||||
}
|
||||
|
||||
// -- Async handler implementations --
|
||||
void Web::handleDiscovery(AsyncWebServerRequest *request) {
|
||||
if(request->method() == HTTP_POST || request->method() == HTTP_GET) {
|
||||
ESP_LOGD(TAG, "Async Discovery Requested");
|
||||
sendSnapshot(request, snapshot_doc_t::discovery, 0, discoveryHeader);
|
||||
}
|
||||
else
|
||||
request->send(500, _encoding_text, "Invalid http method");
|
||||
}
|
||||
void Web::handleGetRooms(AsyncWebServerRequest *request) {
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_POST || request->method() == HTTP_GET) sendSnapshot(request, snapshot_doc_t::rooms);
|
||||
else request->send(404, _encoding_text, _response_404);
|
||||
}
|
||||
void Web::handleGetShades(AsyncWebServerRequest *request) {
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_POST || request->method() == HTTP_GET) sendSnapshot(request, snapshot_doc_t::shades);
|
||||
else request->send(404, _encoding_text, _response_404);
|
||||
}
|
||||
void Web::handleGetGroups(AsyncWebServerRequest *request) {
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_POST || request->method() == HTTP_GET) sendSnapshot(request, snapshot_doc_t::groups);
|
||||
else request->send(404, _encoding_text, _response_404);
|
||||
}
|
||||
void Web::handleController(AsyncWebServerRequest *request) {
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_POST || request->method() == HTTP_GET) {
|
||||
settings.printAvailHeap();
|
||||
sendSnapshot(request, snapshot_doc_t::controller, 0, controllerHeader);
|
||||
}
|
||||
else request->send(404, _encoding_text, _response_404);
|
||||
}
|
||||
void Web::handleLogin(AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
char token[API_TOKEN_SIZE];
|
||||
|
|
@ -534,188 +348,6 @@ void Web::handleTiltCommand(AsyncWebServerRequest *request, JsonVariant &json) {
|
|||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade with the specified id not found.\"}"));
|
||||
}
|
||||
}
|
||||
void Web::handleRepeatCommand(AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
uint8_t shadeId = 255;
|
||||
uint8_t groupId = 255;
|
||||
shade_request_t req;
|
||||
if(asyncHasParam(request, "shadeId")) shadeId = asyncParam(request, "shadeId").toInt();
|
||||
else if(asyncHasParam(request, "groupId")) groupId = asyncParam(request, "groupId").toInt();
|
||||
if(asyncHasParam(request, "command")) req.command = translateSomfyCommand(asyncParam(request, "command"));
|
||||
if(asyncHasParam(request, "repeat")) req.repeat = requestRepeat(asyncParam(request, "repeat").toInt());
|
||||
if(asyncHasParam(request, "stepSize")) req.stepSize = asyncParam(request, "stepSize").toInt();
|
||||
if(shadeId == 255 && groupId == 255 && !json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["shadeId"].isNull()) shadeId = obj["shadeId"];
|
||||
if(!obj["groupId"].isNull()) groupId = obj["groupId"];
|
||||
if(!obj["stepSize"].isNull()) req.stepSize = obj["stepSize"];
|
||||
if(!obj["command"].isNull()) { String scmd = obj["command"]; req.command = translateSomfyCommand(scmd); }
|
||||
if(!obj["repeat"].isNull()) req.repeat = requestRepeat(obj["repeat"].as<int>());
|
||||
}
|
||||
if(shadeId != 255) {
|
||||
ESP_LOGI(TAG, "handleRepeatCommand shade=%u command=%s", shadeId, translateSomfyCommand(req.command).c_str());
|
||||
SomfyShade *shade = somfy.getShadeById(shadeId);
|
||||
if(!shade) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade reference could not be found.\"}")); return; }
|
||||
req.type = shade_request_type_t::shade_repeat;
|
||||
req.id = shadeId;
|
||||
if(!queueShadeRequest(request, req)) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShadeRef(shade, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else if(groupId != 255) {
|
||||
ESP_LOGI(TAG, "handleRepeatCommand group=%u command=%s", groupId, translateSomfyCommand(req.command).c_str());
|
||||
SomfyGroup *group = somfy.getGroupById(groupId);
|
||||
if(!group) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Group reference could not be found.\"}")); return; }
|
||||
req.type = shade_request_type_t::group_repeat;
|
||||
req.id = groupId;
|
||||
if(!queueShadeRequest(request, req)) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeGroupRef(group, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Invalid Http method\"}"));
|
||||
}
|
||||
void Web::handleRoom(AsyncWebServerRequest *request) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_GET) {
|
||||
if(asyncHasParam(request, "roomId")) {
|
||||
int roomId = asyncParam(request, "roomId").toInt();
|
||||
// The status goes out before the snapshot is filled, so whether the room
|
||||
// exists is checked here, on the live model.
|
||||
if(somfy.getRoomById(roomId)) sendSnapshot(request, snapshot_doc_t::room, roomId);
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Room Id not found.\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"You must supply a valid room id.\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Invalid Http method\"}"));
|
||||
}
|
||||
void Web::handleShade(AsyncWebServerRequest *request) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_GET) {
|
||||
if(asyncHasParam(request, "shadeId")) {
|
||||
int shadeId = asyncParam(request, "shadeId").toInt();
|
||||
// As for /room, existence is checked on the live model.
|
||||
if(somfy.getShadeById(shadeId)) sendSnapshot(request, snapshot_doc_t::shade, shadeId);
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade Id not found.\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"You must supply a valid shade id.\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Invalid Http method\"}"));
|
||||
}
|
||||
void Web::handleGroup(AsyncWebServerRequest *request) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_GET) {
|
||||
if(asyncHasParam(request, "groupId")) {
|
||||
int groupId = asyncParam(request, "groupId").toInt();
|
||||
// As for /room, existence is checked on the live model.
|
||||
if(somfy.getGroupById(groupId)) sendSnapshot(request, snapshot_doc_t::group, groupId);
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Group Id not found.\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"You must supply a valid group id.\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Invalid Http method\"}"));
|
||||
}
|
||||
void Web::handleSetPositions(AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
shade_request_t req;
|
||||
req.type = shade_request_type_t::set_positions;
|
||||
if(asyncHasParam(request, "shadeId")) req.id = asyncParam(request, "shadeId").toInt();
|
||||
if(asyncHasParam(request, "position")) req.position = requestTarget(asyncParam(request, "position").toInt());
|
||||
if(asyncHasParam(request, "tiltPosition")) req.tiltPosition = requestTarget(asyncParam(request, "tiltPosition").toInt());
|
||||
if(!json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["shadeId"].isNull()) req.id = obj["shadeId"];
|
||||
if(!obj["position"].isNull()) req.position = requestTarget(obj["position"].as<int>());
|
||||
if(!obj["tiltPosition"].isNull()) req.tiltPosition = requestTarget(obj["tiltPosition"].as<int>());
|
||||
}
|
||||
if(req.id != 255) {
|
||||
ESP_LOGI(TAG, "handleSetPositions shade=%u pos=%d tiltPos=%d", req.id, req.position, req.tiltPosition);
|
||||
SomfyShade *shade = somfy.getShadeById(req.id);
|
||||
if(shade) {
|
||||
if(!queueShadeRequest(request, req)) return;
|
||||
// loop() applies the request after we answer so this is the state before
|
||||
// it. Clients get the result from the shadeState socket event.
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShade(shade, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"An invalid shadeId was provided\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"shadeId was not provided\"}"));
|
||||
}
|
||||
void Web::handleSetSensor(AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
uint8_t shadeId = asyncHasParam(request, "shadeId") ? asyncParam(request, "shadeId").toInt() : 255;
|
||||
uint8_t groupId = asyncHasParam(request, "groupId") ? asyncParam(request, "groupId").toInt() : 255;
|
||||
shade_request_t req;
|
||||
if(asyncHasParam(request, "sunny")) req.sunny = toBoolean(asyncParam(request, "sunny").c_str(), false) ? 1 : 0;
|
||||
if(asyncHasParam(request, "windy")) req.windy = asyncParam(request, "windy").toInt();
|
||||
if(asyncHasParam(request, "repeat")) req.repeat = requestRepeat(asyncParam(request, "repeat").toInt());
|
||||
if(!json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["shadeId"].isNull()) shadeId = obj["shadeId"].as<uint8_t>();
|
||||
if(!obj["groupId"].isNull()) groupId = obj["groupId"].as<uint8_t>();
|
||||
if(!obj["sunny"].isNull()) {
|
||||
if(obj["sunny"].is<bool>()) req.sunny = obj["sunny"].as<bool>() ? 1 : 0;
|
||||
else req.sunny = obj["sunny"].as<int8_t>();
|
||||
}
|
||||
if(!obj["windy"].isNull()) {
|
||||
if(obj["windy"].is<bool>()) req.windy = obj["windy"].as<bool>() ? 1 : 0;
|
||||
else req.windy = obj["windy"].as<int8_t>();
|
||||
}
|
||||
if(!obj["repeat"].isNull()) req.repeat = requestRepeat(obj["repeat"].as<int>());
|
||||
}
|
||||
if(shadeId != 255) {
|
||||
SomfyShade *shade = somfy.getShadeById(shadeId);
|
||||
if(shade) {
|
||||
req.type = shade_request_type_t::shade_sensor;
|
||||
req.id = shadeId;
|
||||
if(!queueShadeRequest(request, req)) return;
|
||||
// The main loop applies the command after we answer so this is the state
|
||||
// before it. Clients get the result from the shadeState socket event.
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShade(shade, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"An invalid shadeId was provided\"}"));
|
||||
}
|
||||
else if(groupId != 255) {
|
||||
SomfyGroup *group = somfy.getGroupById(groupId);
|
||||
if(group) {
|
||||
req.type = shade_request_type_t::group_sensor;
|
||||
req.id = groupId;
|
||||
if(!queueShadeRequest(request, req)) return;
|
||||
// As above, this is the state before the command and groupState follows.
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeGroup(group, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"An invalid groupId was provided\"}"));
|
||||
}
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"shadeId was not provided\"}"));
|
||||
}
|
||||
void Web::handleBackup(AsyncWebServerRequest *request) {
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
bool attach = false;
|
||||
|
|
@ -744,17 +376,6 @@ void Web::handleBackup(AsyncWebServerRequest *request) {
|
|||
request->send(200, _encoding_text, somfy.backupData);
|
||||
}
|
||||
}
|
||||
void Web::handleReboot(AsyncWebServerRequest *request) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
if(!this->isAuthenticated(request)) return;
|
||||
if(request->method() == HTTP_POST || request->method() == HTTP_PUT) {
|
||||
ESP_LOGI(TAG, "Async Rebooting ESP...");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
request->send(200, _encoding_json, "{\"status\":\"OK\",\"desc\":\"Successfully started reboot\"}");
|
||||
}
|
||||
else request->send(201, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"Invalid HTTP Method\"}");
|
||||
}
|
||||
void Web::handleNotFound(AsyncWebServerRequest *request) {
|
||||
if(request->method() == HTTP_OPTIONS) { request->send(200); return; }
|
||||
snprintf(g_async_content, sizeof(g_async_content), "404 Service Not Found: %s", request->url().c_str());
|
||||
|
|
@ -762,41 +383,37 @@ void Web::handleNotFound(AsyncWebServerRequest *request) {
|
|||
}
|
||||
|
||||
// Logs how long part of a request took, when it is worth logging.
|
||||
static void logRequestTime(const char *server, AsyncWebServerRequest *request, const IPAddress &ip, const char *part, uint32_t us) {
|
||||
static void logRequestTime(AsyncWebServerRequest *request, const IPAddress &ip, const char *part, uint32_t us) {
|
||||
if(!worthLogging(us)) return;
|
||||
char what[112];
|
||||
snprintf(what, sizeof(what), "%s %s %s from %u.%u.%u.%u %s", server, request->methodToString(), request->url().c_str(),
|
||||
snprintf(what, sizeof(what), "web %s %s from %u.%u.%u.%u %s", request->methodToString(), request->url().c_str(),
|
||||
ip[0], ip[1], ip[2], ip[3], part);
|
||||
logElapsed(TAG, what, us);
|
||||
}
|
||||
// Logs how long a request takes to handle and, once the connection closes, how
|
||||
// long the whole exchange took. The total includes chunked bodies like
|
||||
// /controller that are built while they are sent, after the handler returns.
|
||||
// The server name must be a literal as the disconnect handler keeps it.
|
||||
static void timeRequest(AsyncWebServerRequest *request, ArMiddlewareNext next, const char *server) {
|
||||
// long the whole exchange took. The total includes bodies sent after the
|
||||
// handler returns, such as a web UI file.
|
||||
static void timeRequest(AsyncWebServerRequest *request, ArMiddlewareNext next) {
|
||||
ElapsedTimer timer;
|
||||
// Taken now as the client may already be gone when the disconnect runs.
|
||||
IPAddress ip = request->client() ? request->client()->remoteIP() : IPAddress();
|
||||
// Uploads set their own disconnect handler while the body arrives, before
|
||||
// this runs, and replacing it would stop the reboot after an update.
|
||||
if(!request->multipart()) {
|
||||
request->onDisconnect([request, timer, server, ip]() { logRequestTime(server, request, ip, "total", timer.us()); });
|
||||
request->onDisconnect([request, timer, ip]() { logRequestTime(request, ip, "total", timer.us()); });
|
||||
}
|
||||
next();
|
||||
logRequestTime(server, request, ip, "handler", timer.us());
|
||||
logRequestTime(request, ip, "handler", timer.us());
|
||||
}
|
||||
|
||||
void Web::begin() {
|
||||
ESP_LOGI(TAG, "Creating Web MicroServices...");
|
||||
asyncApiServer.addMiddleware([](AsyncWebServerRequest *r, ArMiddlewareNext next) { timeRequest(r, next, "api"); });
|
||||
asyncServer.addMiddleware([](AsyncWebServerRequest *r, ArMiddlewareNext next) { timeRequest(r, next, "web"); });
|
||||
// Async API Server (port 8081)
|
||||
asyncServer.addMiddleware([](AsyncWebServerRequest *r, ArMiddlewareNext next) { timeRequest(r, next); });
|
||||
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
|
||||
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
|
||||
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "*");
|
||||
registerApiRoutes(asyncApiServer);
|
||||
// Before the routes, so serveStatic never answers /ws.
|
||||
protoSocket.begin(asyncServer);
|
||||
registerWebUiRoutes(asyncServer);
|
||||
registerHttpRoutes(asyncServer);
|
||||
asyncServer.begin();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,24 +18,12 @@ class Web {
|
|||
bool createAPIPasswordToken(const IPAddress ipAddress, const char *username, const char *password, char *token);
|
||||
bool isAuthenticated(AsyncWebServerRequest *request, bool cfg = false);
|
||||
|
||||
// Async API handlers
|
||||
void handleDiscovery(AsyncWebServerRequest *request);
|
||||
void handleGetRooms(AsyncWebServerRequest *request);
|
||||
void handleGetShades(AsyncWebServerRequest *request);
|
||||
void handleGetGroups(AsyncWebServerRequest *request);
|
||||
void handleController(AsyncWebServerRequest *request);
|
||||
void handleRoom(AsyncWebServerRequest *request);
|
||||
void handleShade(AsyncWebServerRequest *request);
|
||||
void handleGroup(AsyncWebServerRequest *request);
|
||||
// HTTP handlers
|
||||
void handleLogin(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleShadeCommand(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleGroupCommand(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleTiltCommand(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleRepeatCommand(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleSetPositions(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleSetSensor(AsyncWebServerRequest *request, JsonVariant &json);
|
||||
void handleBackup(AsyncWebServerRequest *request);
|
||||
void handleReboot(AsyncWebServerRequest *request);
|
||||
void handleNotFound(AsyncWebServerRequest *request);
|
||||
};
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,17 +1,13 @@
|
|||
#ifndef WEB_ROUTES_H
|
||||
#define WEB_ROUTES_H
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include "Somfy.h"
|
||||
#include "LoopQueue.h"
|
||||
#include "ModelSnapshot.h"
|
||||
|
||||
// What WebUiRoutes, ApiRoutes and the handlers both of them call (Web.cpp)
|
||||
// share. Internal to the web servers.
|
||||
// What HttpRoutes and the handlers it calls (Web.cpp) share. Internal to the
|
||||
// web server.
|
||||
|
||||
// Registers the routes the config web UI calls on port 80, and its files.
|
||||
void registerWebUiRoutes(AsyncWebServer &server);
|
||||
// Registers the routes integrations such as Home Assistant call on port 8081.
|
||||
void registerApiRoutes(AsyncWebServer &server);
|
||||
// Registers the HTTP routes on port 80, and the web UI's files.
|
||||
void registerHttpRoutes(AsyncWebServer &server);
|
||||
|
||||
#define WEB_MAX_RESPONSE 4096
|
||||
// Where replies are formatted before they are sent. async_tcp only.
|
||||
|
|
@ -19,26 +15,10 @@ extern char g_async_content[WEB_MAX_RESPONSE];
|
|||
extern const char _encoding_text[];
|
||||
extern const char _encoding_json[];
|
||||
|
||||
// Sent when a request can't be handed to loop().
|
||||
void sendQueueFull(AsyncWebServerRequest *request);
|
||||
// Sent when the radio can't take a frame (suspended or queue full).
|
||||
void sendRadioUnavailable(AsyncWebServerRequest *request);
|
||||
// Hands an item to loop(), which owns the shades. When it can't be the
|
||||
// request is answered with the reason and false is returned.
|
||||
bool queueLoopItem(AsyncWebServerRequest *request, const loop_item_t &item);
|
||||
bool queueShadeRequest(AsyncWebServerRequest *request, const shade_request_t &req);
|
||||
// A query parameter, or an empty string when it is missing.
|
||||
String asyncParam(AsyncWebServerRequest *request, const char *name);
|
||||
bool asyncHasParam(AsyncWebServerRequest *request, const char *name);
|
||||
// Serves a read from a ModelSnapshot that loop() fills.
|
||||
void sendSnapshot(AsyncWebServerRequest *request, snapshot_doc_t doc, uint8_t id = 0, snapshot_header_t header = nullptr);
|
||||
|
||||
// One item of a reply, copied from the live shade model.
|
||||
void serializeShadeRef(SomfyShade *shade, JsonFormatter &json);
|
||||
void serializeShade(SomfyShade *shade, JsonFormatter &json);
|
||||
void serializeShade(SomfyShade *shade, JsonFormatter &json, bool paired, uint16_t lastRollingCode);
|
||||
void serializeTransceiverConfig(JsonFormatter &json);
|
||||
void serializeAppVersion(JsonFormatter &json, appver_t &ver);
|
||||
// The installed firmware and web application versions.
|
||||
void serializeVersion(JsonFormatter &json);
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,902 +0,0 @@
|
|||
#include <WiFi.h>
|
||||
#include <LittleFS.h>
|
||||
#include <Update.h>
|
||||
#include "TaskWdt.h"
|
||||
#include "esp_log.h"
|
||||
#include "ConfigSettings.h"
|
||||
#include "ConfigFile.h"
|
||||
#include "Utils.h"
|
||||
#include "Secrets.h"
|
||||
#include "SSDP.h"
|
||||
#include "Somfy.h"
|
||||
#include "WResp.h"
|
||||
#include "LoopQueue.h"
|
||||
#include "ModelSnapshot.h"
|
||||
#include "SomfyEditor.h"
|
||||
#include "Web.h"
|
||||
#include "WebRoutes.h"
|
||||
#include "MqttConnection.h"
|
||||
#include "ESPNetwork.h"
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <AsyncJson.h>
|
||||
|
||||
// WebUiRoutes: the routes the config web UI calls on port 80, and the UI's own
|
||||
// files.
|
||||
|
||||
extern ConfigSettings settings;
|
||||
extern SSDPClass SSDP;
|
||||
extern rebootDelay_t rebootDelay;
|
||||
extern SomfyShadeController somfy;
|
||||
extern Web webServer;
|
||||
extern MqttConnection mqtt;
|
||||
extern ESPNetwork net;
|
||||
extern LoopQueue loopQueue;
|
||||
|
||||
static const char *TAG = "Web";
|
||||
static const char _encoding_html[] = "text/html";
|
||||
|
||||
static bool queueSetMyPosition(AsyncWebServerRequest *request, SomfyShade *shade, int8_t pos, int8_t tilt) {
|
||||
shade_request_t req;
|
||||
req.type = shade_request_type_t::set_favorite;
|
||||
req.id = shade->getShadeId();
|
||||
req.position = pos;
|
||||
req.tiltPosition = tilt;
|
||||
return queueShadeRequest(request, req);
|
||||
}
|
||||
// loop() clears paired and saves it once the Prog is queued. The shade
|
||||
// belongs to loop() so it isn't changed here.
|
||||
static bool queueUnpairShade(AsyncWebServerRequest *request, SomfyShade *shade) {
|
||||
shade_request_t req;
|
||||
req.type = shade_request_type_t::unpair;
|
||||
req.id = shade->getShadeId();
|
||||
return queueShadeRequest(request, req);
|
||||
}
|
||||
// Sending a command reads and commits the rolling code on loop(), so a new
|
||||
// code is set there too.
|
||||
static bool queueSetRollingCode(AsyncWebServerRequest *request, SomfyShade *shade, uint16_t rollingCode) {
|
||||
shade_request_t req;
|
||||
req.type = shade_request_type_t::set_rolling_code;
|
||||
req.id = shade->getShadeId();
|
||||
req.rollingCode = rollingCode;
|
||||
return queueShadeRequest(request, req);
|
||||
}
|
||||
// A restore's options travel through the loop queue as RESTORE_* bits.
|
||||
static uint8_t restoreParts(const restore_options_t &opts) {
|
||||
return (opts.settings ? RESTORE_SETTINGS : 0) | (opts.shades ? RESTORE_SHADES : 0) |
|
||||
(opts.network ? RESTORE_NETWORK : 0) | (opts.transceiver ? RESTORE_TRANSCEIVER : 0) |
|
||||
(opts.repeaters ? RESTORE_REPEATERS : 0) | (opts.mqtt ? RESTORE_MQTT : 0);
|
||||
}
|
||||
// The radio and MQTT are shut down once an upload starts and only a reboot
|
||||
// brings them back. The completion handler schedules it but never runs if the
|
||||
// client goes away mid-upload, so make sure the device reboots then too.
|
||||
static void onUploadDisconnect() {
|
||||
if(webServer.uploadSuccess || rebootDelay.reboot) return;
|
||||
ESP_LOGW(TAG, "Upload abandoned, rebooting");
|
||||
if(Update.isRunning()) Update.abort();
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
}
|
||||
// Hands an edit of the shade model to loop() (docs/adr/0002-loop-task-is-the-only-writer-of-the-shade-model.md).
|
||||
// The reply only says it was accepted; the result reaches every client as a
|
||||
// requestResult event carrying the same requestId once loop() has applied it.
|
||||
static void queueModelEdit(AsyncWebServerRequest *request, model_edit_type_t type, JsonVariantConst body) {
|
||||
bool busy;
|
||||
model_edit_t *edit = newModelEdit(type, busy);
|
||||
if(!edit) {
|
||||
if(busy) request->send(503, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Busy, try the change again\"}"));
|
||||
else sendQueueFull(request);
|
||||
return;
|
||||
}
|
||||
edit->requestId = nextEditRequestId();
|
||||
edit->doc.set(body);
|
||||
const uint32_t requestId = edit->requestId;
|
||||
if(!submitModelEdit(edit)) {
|
||||
sendQueueFull(request);
|
||||
return;
|
||||
}
|
||||
char reply[64];
|
||||
snprintf(reply, sizeof(reply), "{\"status\":\"accepted\",\"requestId\":%lu}", (unsigned long)requestId);
|
||||
request->send(200, _encoding_json, reply);
|
||||
}
|
||||
// The JSON (PUT/POST) form of an edit route. Bodies over 4 KB are refused with
|
||||
// 413 before they reach the heap.
|
||||
static AsyncCallbackJsonWebHandler *editHandler(const char *uri, model_edit_type_t type) {
|
||||
auto *handler = new AsyncCallbackJsonWebHandler(uri, [type](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No object supplied.\"}")); return; }
|
||||
queueModelEdit(request, type, json);
|
||||
});
|
||||
handler->setMaxContentLength(4096);
|
||||
return handler;
|
||||
}
|
||||
// The GET form of an edit route: its query parameters become the request.
|
||||
static void queueModelEditFromParams(AsyncWebServerRequest *request, model_edit_type_t type, std::initializer_list<const char *> names) {
|
||||
JsonDocument body;
|
||||
for(const char *name : names) {
|
||||
if(!asyncHasParam(request, name)) continue;
|
||||
const String value = asyncParam(request, name);
|
||||
if(strcmp(name, "paired") == 0) body[name] = toBoolean(value.c_str(), false);
|
||||
else body[name] = strtoul(value.c_str(), nullptr, 10);
|
||||
}
|
||||
queueModelEdit(request, type, body.as<JsonVariantConst>());
|
||||
}
|
||||
|
||||
void registerWebUiRoutes(AsyncWebServer &server) {
|
||||
server.on("/loginContext", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncJsonResponse *response = new AsyncJsonResponse();
|
||||
JsonObject root = response->getRoot().to<JsonObject>();
|
||||
root["type"] = static_cast<uint8_t>(settings.Security.type);
|
||||
root["permissions"] = settings.Security.permissions;
|
||||
root["serverId"] = settings.serverId;
|
||||
root["version"] = settings.fwVersion.name;
|
||||
root["model"] = "ESPSomfyRTS";
|
||||
root["hostname"] = settings.hostname;
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
// Web Interface
|
||||
// Command endpoints - delegate to async handler methods
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/tiltCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleTiltCommand(request, json); }));
|
||||
server.on("/tiltCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleTiltCommand(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/repeatCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleRepeatCommand(request, json); }));
|
||||
server.on("/repeatCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleRepeatCommand(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/shadeCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleShadeCommand(request, json); }));
|
||||
server.on("/shadeCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleShadeCommand(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/groupCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleGroupCommand(request, json); }));
|
||||
server.on("/groupCommand", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleGroupCommand(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setPositions",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleSetPositions(request, json); }));
|
||||
server.on("/setPositions", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleSetPositions(request, v); });
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setSensor",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleSetSensor(request, json); }));
|
||||
server.on("/setSensor", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleSetSensor(request, v); });
|
||||
|
||||
server.on("/upnp.xml", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncResponseStream *response = request->beginResponseStream("text/xml");
|
||||
SSDP.schema(*response);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// / and /loginContext are already handled by serveStatic and startup()
|
||||
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/login",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) { webServer.handleLogin(request, json); }));
|
||||
server.on("/login", HTTP_GET, [](AsyncWebServerRequest *request) { JsonVariant v; webServer.handleLogin(request, v); });
|
||||
|
||||
server.on("/shades.cfg", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(LittleFS, "/shades.cfg", _encoding_text);
|
||||
});
|
||||
server.on("/shades.tmp", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(LittleFS, "/shades.tmp", _encoding_text);
|
||||
});
|
||||
|
||||
server.on("/backup", HTTP_GET, [](AsyncWebServerRequest *request) { webServer.handleBackup(request); });
|
||||
|
||||
server.on("/restore", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
if(webServer.uploadSuccess) {
|
||||
restore_options_t opts;
|
||||
if(asyncHasParam(request, "data")) {
|
||||
String dataStr = asyncParam(request, "data");
|
||||
ESP_LOGD(TAG, "%s", dataStr.c_str());
|
||||
JsonDocument doc;
|
||||
DeserializationError err = deserializeJson(doc, dataStr);
|
||||
if(err) {
|
||||
request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}");
|
||||
return;
|
||||
}
|
||||
else {
|
||||
JsonObject obj = doc.as<JsonObject>();
|
||||
opts.fromJSON(obj);
|
||||
}
|
||||
}
|
||||
else {
|
||||
ESP_LOGD(TAG, "No restore options sent. Using defaults...");
|
||||
opts.shades = true;
|
||||
}
|
||||
// Checked here so the client hears about a bad file. It only reads
|
||||
// the file; the shades are still changed on loop() alone.
|
||||
if(!ShadeConfigFile::validateFile("/shades.tmp")) {
|
||||
LittleFS.remove("/shades.tmp");
|
||||
request->send(400, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"This isn't a valid backup file, so nothing was restored.\"}"));
|
||||
return;
|
||||
}
|
||||
// The main loop restores, since it owns the shades and their rolling
|
||||
// codes, and then reboots.
|
||||
loop_item_t item;
|
||||
item.type = loop_item_type_t::restore_shades;
|
||||
item.restoreParts = restoreParts(opts);
|
||||
if(!queueLoopItem(request, item)) return;
|
||||
request->send(200, _encoding_json, "{\"status\":\"Success\",\"desc\":\"Restoring Shade settings\"}");
|
||||
}
|
||||
else request->send(400, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"The upload didn't complete, so nothing was restored.\"}"));
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
resetTaskWdt();
|
||||
if(index == 0) {
|
||||
webServer.uploadSuccess = false;
|
||||
ESP_LOGD(TAG, "Restore: %s", filename.c_str());
|
||||
File fup = LittleFS.open("/shades.tmp", "w");
|
||||
fup.close();
|
||||
}
|
||||
if(len > 0) {
|
||||
File fup = LittleFS.open("/shades.tmp", "a");
|
||||
fup.write(data, len);
|
||||
fup.close();
|
||||
}
|
||||
if(final) {
|
||||
webServer.uploadSuccess = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Static file routes removed - handled by serveStatic in startup()
|
||||
|
||||
server.on("/controller", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleController(request); });
|
||||
server.on("/rooms", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleGetRooms(request); });
|
||||
server.on("/shades", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleGetShades(request); });
|
||||
server.on("/groups", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleGetGroups(request); });
|
||||
server.on("/room", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleRoom(request); });
|
||||
server.on("/shade", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleShade(request); });
|
||||
server.on("/group", WebRequestMethodComposite(HTTP_GET) | HTTP_POST, [](AsyncWebServerRequest *request) { webServer.handleGroup(request); });
|
||||
|
||||
// What a new room, shade or group would get, from a snapshot.
|
||||
server.on("/getNextRoom", HTTP_GET, [](AsyncWebServerRequest *request) { sendSnapshot(request, snapshot_doc_t::nextRoom); });
|
||||
server.on("/getNextShade", HTTP_GET, [](AsyncWebServerRequest *request) { sendSnapshot(request, snapshot_doc_t::nextShade); });
|
||||
server.on("/getNextGroup", HTTP_GET, [](AsyncWebServerRequest *request) { sendSnapshot(request, snapshot_doc_t::nextGroup); });
|
||||
server.on("/groupOptions", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
if(!asyncHasParam(request, "groupId")) {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"You must supply a valid group id.\"}"));
|
||||
return;
|
||||
}
|
||||
const int groupId = atoi(asyncParam(request, "groupId").c_str());
|
||||
// As for /group, existence is checked on the live model.
|
||||
if(somfy.getGroupById(groupId)) sendSnapshot(request, snapshot_doc_t::groupOptions, groupId);
|
||||
else request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Group Id not found.\"}"));
|
||||
});
|
||||
// Adding and saving rooms, shades and groups. Edits of the shade model:
|
||||
// loop() applies them and sends requestResult.
|
||||
server.addHandler(editHandler("/addRoom", model_edit_type_t::add_room));
|
||||
server.addHandler(editHandler("/addShade", model_edit_type_t::add_shade));
|
||||
server.addHandler(editHandler("/addGroup", model_edit_type_t::add_group));
|
||||
server.addHandler(editHandler("/saveRoom", model_edit_type_t::save_room));
|
||||
server.addHandler(editHandler("/saveShade", model_edit_type_t::save_shade));
|
||||
server.addHandler(editHandler("/saveGroup", model_edit_type_t::save_group));
|
||||
|
||||
|
||||
// setMyPosition - supports both GET with query params and POST/PUT with JSON body
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setMyPosition",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
uint8_t shadeId = 255;
|
||||
int8_t pos = -1;
|
||||
int8_t tilt = -1;
|
||||
if(!json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["shadeId"].isNull()) shadeId = obj["shadeId"];
|
||||
else { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No shade id was supplied.\"}")); return; }
|
||||
if(!obj["pos"].isNull()) pos = obj["pos"].as<int8_t>();
|
||||
if(!obj["tilt"].isNull()) tilt = obj["tilt"].as<int8_t>();
|
||||
}
|
||||
SomfyShade* shade = somfy.getShadeById(shadeId);
|
||||
if(shade) {
|
||||
if(pos >= 0 && pos <= 100)
|
||||
if(!queueSetMyPosition(request, shade, pos, requestTarget(tilt))) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShadeRef(shade, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade with the specified id not found.\"}"));
|
||||
}
|
||||
}));
|
||||
server.on("/setMyPosition", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
uint8_t shadeId = 255;
|
||||
int8_t pos = -1;
|
||||
int8_t tilt = -1;
|
||||
if(asyncHasParam(request, "shadeId")) {
|
||||
shadeId = atoi(asyncParam(request, "shadeId").c_str());
|
||||
if(asyncHasParam(request, "pos")) pos = atoi(asyncParam(request, "pos").c_str());
|
||||
if(asyncHasParam(request, "tilt")) tilt = atoi(asyncParam(request, "tilt").c_str());
|
||||
}
|
||||
else { request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No shade object supplied.\"}")); return; }
|
||||
SomfyShade* shade = somfy.getShadeById(shadeId);
|
||||
if(shade) {
|
||||
if(pos >= 0 && pos <= 100)
|
||||
if(!queueSetMyPosition(request, shade, pos, requestTarget(tilt))) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShadeRef(shade, resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
else {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade with the specified id not found.\"}"));
|
||||
}
|
||||
});
|
||||
|
||||
// setRollingCode - supports both query params and JSON body
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setRollingCode",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
uint8_t shadeId = 255;
|
||||
uint16_t rollingCode = 0;
|
||||
if(!json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["shadeId"].isNull()) shadeId = obj["shadeId"];
|
||||
if(!obj["rollingCode"].isNull()) rollingCode = obj["rollingCode"];
|
||||
}
|
||||
SomfyShade* shade = nullptr;
|
||||
if(shadeId != 255) shade = somfy.getShadeById(shadeId);
|
||||
if(!shade) {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade not found to set rolling code\"}"));
|
||||
}
|
||||
else {
|
||||
if(!queueSetRollingCode(request, shade, rollingCode)) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShade(shade, resp, shade->paired, rollingCode);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
}));
|
||||
server.on("/setRollingCode", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
uint8_t shadeId = 255;
|
||||
uint16_t rollingCode = 0;
|
||||
if(asyncHasParam(request, "shadeId")) {
|
||||
shadeId = atoi(asyncParam(request, "shadeId").c_str());
|
||||
rollingCode = atoi(asyncParam(request, "rollingCode").c_str());
|
||||
}
|
||||
SomfyShade* shade = nullptr;
|
||||
if(shadeId != 255) shade = somfy.getShadeById(shadeId);
|
||||
if(!shade) {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade not found to set rolling code\"}"));
|
||||
}
|
||||
else {
|
||||
if(!queueSetRollingCode(request, shade, rollingCode)) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShade(shade, resp, shade->paired, rollingCode);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
});
|
||||
|
||||
server.addHandler(editHandler("/setPaired", model_edit_type_t::set_paired));
|
||||
server.on("/setPaired", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
queueModelEditFromParams(request, model_edit_type_t::set_paired, { "shadeId", "paired" });
|
||||
});
|
||||
|
||||
// unpairShade
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/unpairShade",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
uint8_t shadeId = 255;
|
||||
if(!json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["shadeId"].isNull()) shadeId = obj["shadeId"];
|
||||
}
|
||||
SomfyShade* shade = nullptr;
|
||||
if(shadeId != 255) shade = somfy.getShadeById(shadeId);
|
||||
if(!shade) {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade not found to unpair\"}"));
|
||||
}
|
||||
else {
|
||||
if(!queueUnpairShade(request, shade)) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShade(shade, resp, false, shade->lastRollingCode);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
}));
|
||||
server.on("/unpairShade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
uint8_t shadeId = 255;
|
||||
if(asyncHasParam(request, "shadeId"))
|
||||
shadeId = atoi(asyncParam(request, "shadeId").c_str());
|
||||
SomfyShade* shade = nullptr;
|
||||
if(shadeId != 255) shade = somfy.getShadeById(shadeId);
|
||||
if(!shade) {
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"Shade not found to unpair\"}"));
|
||||
}
|
||||
else {
|
||||
if(!queueUnpairShade(request, shade)) return;
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeShade(shade, resp, false, shade->lastRollingCode);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}
|
||||
});
|
||||
|
||||
// Linking repeaters, remotes and group members, and deleting. Edits of the
|
||||
// shade model: loop() applies them and sends requestResult.
|
||||
server.addHandler(editHandler("/linkRepeater", model_edit_type_t::link_repeater));
|
||||
server.on("/linkRepeater", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
queueModelEditFromParams(request, model_edit_type_t::link_repeater, { "address" });
|
||||
});
|
||||
server.addHandler(editHandler("/unlinkRepeater", model_edit_type_t::unlink_repeater));
|
||||
server.on("/unlinkRepeater", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
queueModelEditFromParams(request, model_edit_type_t::unlink_repeater, { "address" });
|
||||
});
|
||||
server.addHandler(editHandler("/linkRemote", model_edit_type_t::link_remote));
|
||||
server.addHandler(editHandler("/unlinkRemote", model_edit_type_t::unlink_remote));
|
||||
server.addHandler(editHandler("/linkToGroup", model_edit_type_t::link_to_group));
|
||||
server.addHandler(editHandler("/unlinkFromGroup", model_edit_type_t::unlink_from_group));
|
||||
server.addHandler(editHandler("/deleteRoom", model_edit_type_t::delete_room));
|
||||
server.on("/deleteRoom", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
queueModelEditFromParams(request, model_edit_type_t::delete_room, { "roomId" });
|
||||
});
|
||||
server.addHandler(editHandler("/deleteShade", model_edit_type_t::delete_shade));
|
||||
server.on("/deleteShade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
queueModelEditFromParams(request, model_edit_type_t::delete_shade, { "shadeId" });
|
||||
});
|
||||
server.addHandler(editHandler("/deleteGroup", model_edit_type_t::delete_group));
|
||||
server.on("/deleteGroup", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
queueModelEditFromParams(request, model_edit_type_t::delete_group, { "groupId" });
|
||||
});
|
||||
// The repeaters, from a snapshot like the other reads.
|
||||
server.on("/repeaters", HTTP_GET, [](AsyncWebServerRequest *request) { sendSnapshot(request, snapshot_doc_t::repeaters); });
|
||||
|
||||
|
||||
// updateFirmware - file upload
|
||||
server.on("/updateFirmware", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
if(Update.hasError())
|
||||
request->send(500, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"Error updating firmware: \"}");
|
||||
else
|
||||
request->send(200, _encoding_json, "{\"status\":\"SUCCESS\",\"desc\":\"Successfully updated firmware\"}");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
if(index == 0) {
|
||||
webServer.uploadSuccess = false;
|
||||
ESP_LOGI(TAG, "Update: %s", filename.c_str());
|
||||
if(!Update.begin(UPDATE_SIZE_UNKNOWN)) {
|
||||
ESP_LOGE(TAG, "Update begin failed");
|
||||
}
|
||||
else {
|
||||
somfy.transceiver.end();
|
||||
mqtt.end();
|
||||
request->onDisconnect(onUploadDisconnect);
|
||||
}
|
||||
}
|
||||
if(len > 0) {
|
||||
if(Update.write(data, len) != len) {
|
||||
ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", filename.c_str(), len);
|
||||
Update.abort();
|
||||
}
|
||||
}
|
||||
if(final) {
|
||||
if(Update.end(true)) {
|
||||
ESP_LOGI(TAG, "Update Success: %u Rebooting...", index + len);
|
||||
webServer.uploadSuccess = true;
|
||||
}
|
||||
else {
|
||||
ESP_LOGE(TAG, "Update end failed");
|
||||
}
|
||||
}
|
||||
resetTaskWdt();
|
||||
});
|
||||
|
||||
// updateShadeConfig - file upload
|
||||
server.on("/updateShadeConfig", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
request->send(200, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"Updating Shade Config: \"}");
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
if(index == 0) {
|
||||
ESP_LOGI(TAG, "Update: shades.cfg");
|
||||
File fup = LittleFS.open("/shades.tmp", "w");
|
||||
fup.close();
|
||||
}
|
||||
if(len > 0) {
|
||||
File fup = LittleFS.open("/shades.tmp", "a");
|
||||
fup.write(data, len);
|
||||
fup.close();
|
||||
}
|
||||
if(final) {
|
||||
// The main loop loads it, since it owns the shades.
|
||||
loop_item_t item;
|
||||
item.type = loop_item_type_t::load_shades;
|
||||
loopQueue.submit(item);
|
||||
}
|
||||
});
|
||||
|
||||
// updateApplication - file upload
|
||||
server.on("/updateApplication", HTTP_POST,
|
||||
[](AsyncWebServerRequest *request) {
|
||||
if(Update.hasError())
|
||||
request->send(500, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"Error updating application: \"}");
|
||||
else
|
||||
request->send(200, _encoding_json, "{\"status\":\"SUCCESS\",\"desc\":\"Successfully updated application\"}");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 500;
|
||||
},
|
||||
[](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
if(index == 0) {
|
||||
webServer.uploadSuccess = false;
|
||||
ESP_LOGI(TAG, "Update: %s", filename.c_str());
|
||||
if(!Update.begin(UPDATE_SIZE_UNKNOWN, U_SPIFFS)) {
|
||||
ESP_LOGE(TAG, "Update begin failed");
|
||||
}
|
||||
else {
|
||||
somfy.transceiver.end();
|
||||
mqtt.end();
|
||||
request->onDisconnect(onUploadDisconnect);
|
||||
}
|
||||
}
|
||||
if(len > 0) {
|
||||
if(Update.write(data, len) != len) {
|
||||
ESP_LOGE(TAG, "Upload of %s aborted invalid size %d", filename.c_str(), len);
|
||||
Update.abort();
|
||||
}
|
||||
}
|
||||
if(final) {
|
||||
if(Update.end(true)) {
|
||||
webServer.uploadSuccess = true;
|
||||
ESP_LOGI(TAG, "Update Success: %u Rebooting...", index + len);
|
||||
somfy.commit();
|
||||
}
|
||||
else {
|
||||
somfy.commit();
|
||||
ESP_LOGE(TAG, "Update end failed");
|
||||
}
|
||||
}
|
||||
resetTaskWdt();
|
||||
});
|
||||
|
||||
server.on("/scanaps", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
const bool wdtPaused = pauseTaskWdt();
|
||||
if(net.softAPOpened) WiFi.disconnect(false);
|
||||
int n = WiFi.scanNetworks(false, true);
|
||||
resumeTaskWdt(wdtPaused);
|
||||
ESP_LOGI(TAG, "Scanned %d networks", n);
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
resp.beginObject("connected");
|
||||
resp.addElem("name", settings.WIFI.ssid);
|
||||
resp.addElem("strength", (int32_t)WiFi.RSSI());
|
||||
resp.addElem("channel", (int32_t)WiFi.channel());
|
||||
resp.endObject();
|
||||
resp.beginArray("accessPoints");
|
||||
for(int i = 0; i < n; ++i) {
|
||||
if(WiFi.SSID(i).length() == 0 || WiFi.RSSI(i) < -95) continue;
|
||||
resp.beginObject();
|
||||
resp.addElem("name", WiFi.SSID(i).c_str());
|
||||
resp.addElem("channel", (int32_t)WiFi.channel(i));
|
||||
resp.addElem("strength", (int32_t)WiFi.RSSI(i));
|
||||
resp.addElem("macAddress", WiFi.BSSIDstr(i).c_str());
|
||||
resp.endObject();
|
||||
}
|
||||
resp.endArray();
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
});
|
||||
|
||||
server.on("/reboot", WebRequestMethodComposite(HTTP_POST) | HTTP_PUT, [](AsyncWebServerRequest *request) { webServer.handleReboot(request); });
|
||||
|
||||
// saveSecurity
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/saveSecurity",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(400, _encoding_html, "Error parsing JSON body");
|
||||
return;
|
||||
}
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
settings.Security.fromJSON(obj);
|
||||
settings.Security.save();
|
||||
char token[API_TOKEN_SIZE];
|
||||
webServer.createAPIToken(request->client()->remoteIP(), token);
|
||||
JsonDocument sdoc;
|
||||
JsonObject sobj = sdoc.to<JsonObject>();
|
||||
settings.Security.toJSON(sobj);
|
||||
sobj["apiKey"] = token;
|
||||
serializeJson(sdoc, g_async_content, sizeof(g_async_content));
|
||||
request->send(200, _encoding_json, g_async_content);
|
||||
}));
|
||||
|
||||
// getSecurity
|
||||
server.on("/getSecurity", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
JsonDocument doc;
|
||||
JsonObject obj = doc.to<JsonObject>();
|
||||
settings.Security.toJSON(obj);
|
||||
serializeJson(doc, g_async_content, sizeof(g_async_content));
|
||||
request->send(200, _encoding_json, g_async_content);
|
||||
});
|
||||
|
||||
// saveRadio
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/saveRadio",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(400, _encoding_html, "Error parsing JSON body");
|
||||
return;
|
||||
}
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
somfy.transceiver.fromJSON(obj);
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
resp.beginObject("config");
|
||||
serializeTransceiverConfig(resp);
|
||||
resp.endObject();
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
}));
|
||||
|
||||
// getRadio
|
||||
server.on("/getRadio", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeTransceiverConfig(resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
});
|
||||
|
||||
// sendRemoteCommand - supports GET with query params and POST/PUT with JSON body
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/sendRemoteCommand",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
somfy_frame_t frame;
|
||||
uint8_t repeats = 0;
|
||||
if(!json.isNull()) {
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
String scmd;
|
||||
if(!obj["address"].isNull()) frame.remoteAddress = obj["address"];
|
||||
if(!obj["command"].isNull()) scmd = obj["command"].as<String>();
|
||||
if(!obj["repeats"].isNull()) repeats = obj["repeats"];
|
||||
if(!obj["rcode"].isNull()) frame.rollingCode = obj["rcode"];
|
||||
if(!obj["encKey"].isNull()) frame.encKey = obj["encKey"];
|
||||
frame.cmd = translateSomfyCommand(scmd.c_str());
|
||||
}
|
||||
if(frame.remoteAddress > 0 && frame.rollingCode > 0) {
|
||||
if(somfy.sendFrame(frame, repeats))
|
||||
request->send(200, _encoding_json, F("{\"status\":\"SUCCESS\",\"desc\":\"Command Sent\"}"));
|
||||
else
|
||||
sendRadioUnavailable(request);
|
||||
}
|
||||
else
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No address or rolling code provided\"}"));
|
||||
}));
|
||||
server.on("/sendRemoteCommand", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
somfy_frame_t frame;
|
||||
uint8_t repeats = 0;
|
||||
if(asyncHasParam(request, "address")) {
|
||||
frame.remoteAddress = atoi(asyncParam(request, "address").c_str());
|
||||
if(asyncHasParam(request, "encKey")) frame.encKey = atoi(asyncParam(request, "encKey").c_str());
|
||||
if(asyncHasParam(request, "command")) frame.cmd = translateSomfyCommand(asyncParam(request, "command"));
|
||||
if(asyncHasParam(request, "rcode")) frame.rollingCode = atoi(asyncParam(request, "rcode").c_str());
|
||||
if(asyncHasParam(request, "repeats")) repeats = atoi(asyncParam(request, "repeats").c_str());
|
||||
}
|
||||
if(frame.remoteAddress > 0 && frame.rollingCode > 0) {
|
||||
if(somfy.sendFrame(frame, repeats))
|
||||
request->send(200, _encoding_json, F("{\"status\":\"SUCCESS\",\"desc\":\"Command Sent\"}"));
|
||||
else
|
||||
sendRadioUnavailable(request);
|
||||
}
|
||||
else
|
||||
request->send(500, _encoding_json, F("{\"status\":\"ERROR\",\"desc\":\"No address or rolling code provided\"}"));
|
||||
});
|
||||
|
||||
// setgeneral
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setgeneral",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}");
|
||||
return;
|
||||
}
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
if(!obj["hostname"].isNull() || !obj["ssdpBroadcast"].isNull()) {
|
||||
settings.fromJSON(obj);
|
||||
settings.save();
|
||||
if(!obj["hostname"].isNull()) net.updateHostname();
|
||||
}
|
||||
if(!obj["ntpServer"].isNull() || !obj["posixZone"].isNull()) {
|
||||
settings.NTP.fromJSON(obj);
|
||||
settings.NTP.save();
|
||||
}
|
||||
request->send(200, "application/json", "{\"status\":\"OK\",\"desc\":\"Successfully set General Settings\"}");
|
||||
}));
|
||||
|
||||
// setNetwork
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setNetwork",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(400, _encoding_html, "Error parsing JSON body");
|
||||
return;
|
||||
}
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
bool reboot = false;
|
||||
if(!obj["connType"].isNull() && obj["connType"].as<uint8_t>() != static_cast<uint8_t>(settings.connType)) {
|
||||
settings.connType = static_cast<conn_types_t>(obj["connType"].as<uint8_t>());
|
||||
settings.save();
|
||||
reboot = true;
|
||||
}
|
||||
if(!obj["wifi"].isNull()) {
|
||||
JsonObject objWifi = obj["wifi"];
|
||||
// Compared after fromJSON, which decides whether an empty passphrase keeps the stored one.
|
||||
WifiSettings before = settings.WIFI;
|
||||
settings.WIFI.fromJSON(objWifi);
|
||||
settings.WIFI.save();
|
||||
if(settings.connType == conn_types_t::wifi && WiFi.softAPgetStationNum() == 0 &&
|
||||
(strcmp(before.ssid, settings.WIFI.ssid) != 0 || strcmp(before.passphrase, settings.WIFI.passphrase) != 0))
|
||||
reboot = true;
|
||||
}
|
||||
if(!obj["ethernet"].isNull()) {
|
||||
JsonObject objEth = obj["ethernet"];
|
||||
if(settings.connType == conn_types_t::ethernet || settings.connType == conn_types_t::ethernetpref)
|
||||
reboot = true;
|
||||
#if HAS_ETHERNET
|
||||
settings.Ethernet.fromJSON(objEth);
|
||||
settings.Ethernet.save();
|
||||
#endif
|
||||
}
|
||||
if(reboot) {
|
||||
ESP_LOGI(TAG, "Rebooting ESP for new Network settings...");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 1000;
|
||||
}
|
||||
request->send(200, "application/json", "{\"status\":\"OK\",\"desc\":\"Successfully set Network Settings\"}");
|
||||
}));
|
||||
|
||||
// setIP
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/setIP",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}");
|
||||
return;
|
||||
}
|
||||
ESP_LOGD(TAG, "Setting IP...");
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
settings.IP.fromJSON(obj);
|
||||
settings.IP.save();
|
||||
request->send(200, "application/json", "{\"status\":\"OK\",\"desc\":\"Successfully set Network Settings\"}");
|
||||
}));
|
||||
|
||||
// connectwifi
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/connectwifi",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}");
|
||||
return;
|
||||
}
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
ESP_LOGD(TAG, "Settings WIFI connection...");
|
||||
String ssid = "";
|
||||
if(!obj["ssid"].isNull()) ssid = obj["ssid"].as<String>();
|
||||
bool newSsid = ssid.compareTo(settings.WIFI.ssid) != 0;
|
||||
// Clients never receive the stored passphrase: an omitted or empty one keeps it unless the SSID changes.
|
||||
char passphrase[sizeof(settings.WIFI.passphrase)];
|
||||
SETCHARPROP(passphrase, settings.WIFI.passphrase, sizeof(passphrase));
|
||||
bool newPassphrase = applySecret(obj["passphrase"].as<const char *>(), passphrase, sizeof(passphrase), newSsid);
|
||||
bool reboot = newSsid || newPassphrase;
|
||||
if(!settings.WIFI.ssidExists(ssid.c_str()) && ssid.length() > 0) {
|
||||
request->send(400, _encoding_json, "{\"status\":\"ERROR\",\"desc\":\"WiFi Network Does not exist\"}");
|
||||
}
|
||||
else {
|
||||
SETCHARPROP(settings.WIFI.ssid, ssid.c_str(), sizeof(settings.WIFI.ssid));
|
||||
SETCHARPROP(settings.WIFI.passphrase, passphrase, sizeof(settings.WIFI.passphrase));
|
||||
settings.WIFI.save();
|
||||
settings.WIFI.print();
|
||||
request->send(201, _encoding_json, "{\"status\":\"OK\",\"desc\":\"Successfully set server connection\"}");
|
||||
if(reboot) {
|
||||
ESP_LOGI(TAG, "Rebooting ESP for new WiFi settings...");
|
||||
rebootDelay.reboot = true;
|
||||
rebootDelay.rebootTime = millis() + 1000;
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// modulesettings
|
||||
server.on("/modulesettings", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
resp.addElem("fwVersion", settings.fwVersion.name);
|
||||
resp.addElem("ssdpBroadcast", settings.ssdpBroadcast);
|
||||
resp.addElem("hostname", settings.hostname);
|
||||
resp.addElem("connType", static_cast<uint8_t>(settings.connType));
|
||||
resp.addElem("chipModel", settings.chipModel);
|
||||
resp.addElem("ntpServer", settings.NTP.ntpServer);
|
||||
resp.addElem("posixZone", settings.NTP.posixZone);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
});
|
||||
|
||||
// networksettings
|
||||
server.on("/networksettings", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
JsonDocument doc;
|
||||
JsonObject obj = doc.to<JsonObject>();
|
||||
settings.toJSON(obj);
|
||||
obj["fwVersion"] = settings.fwVersion.name;
|
||||
// The web UI hides the Ethernet settings when the chip has no MAC.
|
||||
obj["hasEthernet"] = HAS_ETHERNET == 1;
|
||||
JsonObject eth = obj.createNestedObject("ethernet");
|
||||
#if HAS_ETHERNET
|
||||
settings.Ethernet.toJSON(eth);
|
||||
#endif
|
||||
JsonObject wifi = obj.createNestedObject("wifi");
|
||||
settings.WIFI.toJSON(wifi);
|
||||
JsonObject ip = obj.createNestedObject("ip");
|
||||
settings.IP.toJSON(ip);
|
||||
serializeJson(doc, g_async_content, sizeof(g_async_content));
|
||||
request->send(200, _encoding_json, g_async_content);
|
||||
});
|
||||
|
||||
// connectmqtt
|
||||
server.addHandler(new AsyncCallbackJsonWebHandler("/connectmqtt",
|
||||
[](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
if(json.isNull()) {
|
||||
request->send(500, "application/json", "{\"status\":\"ERROR\",\"desc\":\"JSON parse error\"}");
|
||||
return;
|
||||
}
|
||||
JsonObject obj = json.as<JsonObject>();
|
||||
ESP_LOGD(TAG, "Saving MQTT");
|
||||
mqtt.disconnect();
|
||||
settings.MQTT.fromJSON(obj);
|
||||
settings.MQTT.save();
|
||||
JsonDocument sdoc;
|
||||
JsonObject sobj = sdoc.to<JsonObject>();
|
||||
settings.MQTT.toJSON(sobj);
|
||||
serializeJson(sdoc, g_async_content, sizeof(g_async_content));
|
||||
request->send(200, _encoding_json, g_async_content);
|
||||
}));
|
||||
|
||||
// mqttsettings
|
||||
server.on("/mqttsettings", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
JsonDocument doc;
|
||||
JsonObject obj = doc.to<JsonObject>();
|
||||
settings.MQTT.toJSON(obj);
|
||||
serializeJson(doc, g_async_content, sizeof(g_async_content));
|
||||
request->send(200, _encoding_json, g_async_content);
|
||||
});
|
||||
|
||||
// Sort orders: the ids in the order the client lists them.
|
||||
server.addHandler(editHandler("/roomSortOrder", model_edit_type_t::room_order));
|
||||
server.addHandler(editHandler("/shadeSortOrder", model_edit_type_t::shade_order));
|
||||
server.addHandler(editHandler("/groupSortOrder", model_edit_type_t::group_order));
|
||||
|
||||
server.on("/beginFrequencyScan", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
somfy.transceiver.beginFrequencyScan();
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeTransceiverConfig(resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
});
|
||||
|
||||
server.on("/endFrequencyScan", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
somfy.transceiver.endFrequencyScan();
|
||||
AsyncJsonResp resp;
|
||||
resp.beginResponse(request, g_async_content, sizeof(g_async_content));
|
||||
resp.beginObject();
|
||||
serializeTransceiverConfig(resp);
|
||||
resp.endObject();
|
||||
resp.endResponse();
|
||||
});
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *r) {
|
||||
if(r->method() == HTTP_OPTIONS) { r->send(200); return; }
|
||||
webServer.handleNotFound(r);
|
||||
});
|
||||
|
||||
// serveStatic MUST be registered AFTER all route handlers so it doesn't shadow them
|
||||
server.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue