mirror of
https://github.com/Laxilef/OTGateway.git
synced 2026-11-30 10:13:04 +05:00
refactor: streamline portal responses and request handling
Return download responses from the filename helper and simplify response construction while preserving JSON lengths, authentication and body limits. Move RequestInterface to shared types, clarify route comments and group validation and OTA branches consistently.
This commit is contained in:
1 parent
8fba88636e
commit
09b5f6c9e0
2 files changed
+165
-87
No files matched your search
@@ -78,6 +78,13 @@ enum HaEntity : uint8_t {
|
|||||||
HA_ENTITY_COUNT
|
HA_ENTITY_COUNT
|
||||||
};
|
};
|
||||||
|
|
||||||
|
enum class RequestInterface : uint8_t {
|
||||||
|
UNKNOWN,
|
||||||
|
AP,
|
||||||
|
STA,
|
||||||
|
ETH
|
||||||
|
};
|
||||||
|
|
||||||
enum class NetworkEvent : uint8_t {
|
enum class NetworkEvent : uint8_t {
|
||||||
CONNECTED,
|
CONNECTED,
|
||||||
DISCONNECTED,
|
DISCONNECTED,
|
||||||
|
|||||||
+158
-87
@@ -27,16 +27,8 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
WebSerial* webSerial = nullptr;
|
WebSerial* webSerial = nullptr;
|
||||||
|
|
||||||
AsyncWebServer* webServer = nullptr;
|
AsyncWebServer* webServer = nullptr;
|
||||||
|
|
||||||
enum class RequestInterface : uint8_t {
|
|
||||||
UNKNOWN,
|
|
||||||
AP,
|
|
||||||
STA,
|
|
||||||
ETH
|
|
||||||
};
|
|
||||||
|
|
||||||
static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
|
static RequestInterface getRequestInterface(AsyncWebServerRequest* request) {
|
||||||
if (request == nullptr || request->client() == nullptr) {
|
if (request == nullptr || request->client() == nullptr) {
|
||||||
return RequestInterface::UNKNOWN;
|
return RequestInterface::UNKNOWN;
|
||||||
@@ -117,7 +109,7 @@ static bool isAuthenticationRequired(AsyncWebServerRequest* request) {
|
|||||||
return settings.portal.auth && strlen(settings.portal.password);
|
return settings.portal.auth && strlen(settings.portal.password);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void setDownloadFilename(AsyncWebServerResponse* response, const char* type, const char* extension) {
|
static AsyncWebServerResponse* setDownloadFilename(AsyncWebServerResponse* response, const char* type, const char* extension) {
|
||||||
const time_t now = time(nullptr);
|
const time_t now = time(nullptr);
|
||||||
|
|
||||||
tm localNow {};
|
tm localNow {};
|
||||||
@@ -133,9 +125,11 @@ static void setDownloadFilename(AsyncWebServerResponse* response, const char* ty
|
|||||||
networkSettings.hostname, localNowValue, type, extension
|
networkSettings.hostname, localNowValue, type, extension
|
||||||
);
|
);
|
||||||
response->addHeader("Content-Disposition", contentDisposition);
|
response->addHeader("Content-Disposition", contentDisposition);
|
||||||
|
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
// auth middleware
|
// Authenticate requests
|
||||||
static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
|
static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) {
|
||||||
if (!isAuthenticationRequired(request)) {
|
if (!isAuthenticationRequired(request)) {
|
||||||
return next();
|
return next();
|
||||||
@@ -172,37 +166,39 @@ static void initWebSerial() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static void routes() {
|
static void routes() {
|
||||||
// index page
|
// Redirect to index page
|
||||||
webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
request->redirect("/index.html");
|
request->redirect("/index.html");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Serve index page
|
||||||
webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE);
|
webServer->serveStatic("/index.html", LittleFS, "/pages/index.html", PORTAL_CACHE);
|
||||||
|
|
||||||
// dashboard page
|
// Serve dashboard page
|
||||||
webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE)
|
webServer->serveStatic("/dashboard.html", LittleFS, "/pages/dashboard.html", PORTAL_CACHE)
|
||||||
.addMiddleware(&authMiddleware);
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// network settings page
|
// Serve network settings page
|
||||||
webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE)
|
webServer->serveStatic("/network.html", LittleFS, "/pages/network.html", PORTAL_CACHE)
|
||||||
.addMiddleware(&authMiddleware);
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// settings page
|
// Serve settings page
|
||||||
webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE)
|
webServer->serveStatic("/settings.html", LittleFS, "/pages/settings.html", PORTAL_CACHE)
|
||||||
.addMiddleware(&authMiddleware);
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// sensors page
|
// Serve sensors page
|
||||||
webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE)
|
webServer->serveStatic("/sensors.html", LittleFS, "/pages/sensors.html", PORTAL_CACHE)
|
||||||
.addMiddleware(&authMiddleware);
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// upgrade page
|
// Serve upgrade page
|
||||||
webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE)
|
webServer->serveStatic("/upgrade.html", LittleFS, "/pages/upgrade.html", PORTAL_CACHE)
|
||||||
.addMiddleware(&authMiddleware);
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// logs page
|
// Serve logs page
|
||||||
webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE)
|
webServer->serveStatic("/logs.html", LittleFS, "/pages/logs.html", PORTAL_CACHE)
|
||||||
.addMiddleware(&authMiddleware);
|
.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// not found
|
// Handle unmatched requests
|
||||||
webServer->onNotFound([](AsyncWebServerRequest *request) {
|
webServer->onNotFound([](AsyncWebServerRequest *request) {
|
||||||
const auto& url = request->url();
|
const auto& url = request->url();
|
||||||
ESP_LOGD(L_PORTAL_WEBSERVER, "Page not found, uri: %s", url.c_str());
|
ESP_LOGD(L_PORTAL_WEBSERVER, "Page not found, uri: %s", url.c_str());
|
||||||
@@ -218,40 +214,46 @@ static void routes() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Serve static assets
|
||||||
webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE);
|
webServer->serveStatic("/robots.txt", LittleFS, "/static/robots.txt", PORTAL_CACHE);
|
||||||
webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE);
|
webServer->serveStatic("/favicon.ico", LittleFS, "/static/images/favicon.ico", PORTAL_CACHE);
|
||||||
webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE);
|
webServer->serveStatic("/static", LittleFS, "/static", PORTAL_CACHE);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void restApi() {
|
static void restApi() {
|
||||||
// OTA
|
// Handle OTA updates
|
||||||
auto upgradeHandler = (new UpgradeHandler("/api/upgrade"))
|
auto upgradeHandler = (new UpgradeHandler("/api/upgrade"))
|
||||||
->setBeforeUpgradeCallback([](AsyncWebServerRequest *request, UpgradeHandler::UpgradeType type) -> bool {
|
->setBeforeUpgradeCallback([](AsyncWebServerRequest *request, UpgradeHandler::UpgradeType type) -> bool {
|
||||||
// Upload callbacks run before middleware; reject before pausing tasks or writing.
|
// Upload callbacks run before middleware; reject before pausing tasks or writing.
|
||||||
if (isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) {
|
if (isAuthenticationRequired(request) && !request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
|
|
||||||
if (restartTask.scheduled() || restartTask.active()) {
|
} else if (restartTask.scheduled() || restartTask.active()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpgradeHandler invokes this callback for every upload chunk.
|
// UpgradeHandler invokes this callback for every upload chunk.
|
||||||
if (upgrading) {
|
if (upgrading) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prepare for upgrade and pause Core tasks
|
||||||
upgrading = true;
|
upgrading = true;
|
||||||
coreTaskManager.pause();
|
coreTaskManager.pause();
|
||||||
|
|
||||||
// Core owns MQTT; finish its current callback before stopping the client.
|
// Core owns MQTT; finish its current callback before stopping the client.
|
||||||
if (!coreTaskManager.waitForPaused(5000)) {
|
if (!coreTaskManager.waitForPaused(5000)) {
|
||||||
upgrading = false;
|
upgrading = false;
|
||||||
|
|
||||||
if (!restartTask.scheduled() && !restartTask.active()) {
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
coreTaskManager.resume();
|
coreTaskManager.resume();
|
||||||
}
|
}
|
||||||
|
|
||||||
ESP_LOGW(L_PORTAL_OTA, "Core task manager pause not confirmed, upgrade cancelled");
|
ESP_LOGW(L_PORTAL_OTA, "Core task manager pause not confirmed, upgrade cancelled");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stop MQTT after Core has paused
|
||||||
stopMqtt(false);
|
stopMqtt(false);
|
||||||
|
|
||||||
// An MQTT command already in flight may have scheduled a restart before end().
|
// An MQTT command already in flight may have scheduled a restart before end().
|
||||||
@@ -260,27 +262,33 @@ static void restApi() {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pause sensor tasks
|
||||||
sensorsTaskManager.pause();
|
sensorsTaskManager.pause();
|
||||||
if (!sensorsTaskManager.waitForPaused(5000)) {
|
if (!sensorsTaskManager.waitForPaused(5000)) {
|
||||||
requestReconfigureMqtt();
|
requestReconfigureMqtt();
|
||||||
upgrading = false;
|
upgrading = false;
|
||||||
|
|
||||||
if (!restartTask.scheduled() && !restartTask.active()) {
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
coreTaskManager.resume();
|
coreTaskManager.resume();
|
||||||
sensorsTaskManager.resume();
|
sensorsTaskManager.resume();
|
||||||
}
|
}
|
||||||
|
|
||||||
ESP_LOGW(L_PORTAL_OTA, "Sensors task manager pause not confirmed, upgrade cancelled");
|
ESP_LOGW(L_PORTAL_OTA, "Sensors task manager pause not confirmed, upgrade cancelled");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pause OpenTherm tasks
|
||||||
openthermTaskManager.pause();
|
openthermTaskManager.pause();
|
||||||
if (!openthermTaskManager.waitForPaused(5000)) {
|
if (!openthermTaskManager.waitForPaused(5000)) {
|
||||||
requestReconfigureMqtt();
|
requestReconfigureMqtt();
|
||||||
upgrading = false;
|
upgrading = false;
|
||||||
|
|
||||||
if (!restartTask.scheduled() && !restartTask.active()) {
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
coreTaskManager.resume();
|
coreTaskManager.resume();
|
||||||
sensorsTaskManager.resume();
|
sensorsTaskManager.resume();
|
||||||
openthermTaskManager.resume();
|
openthermTaskManager.resume();
|
||||||
}
|
}
|
||||||
|
|
||||||
ESP_LOGW(L_PORTAL_OTA, "OpenTherm task manager pause not confirmed, upgrade cancelled");
|
ESP_LOGW(L_PORTAL_OTA, "OpenTherm task manager pause not confirmed, upgrade cancelled");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -291,9 +299,12 @@ static void restApi() {
|
|||||||
return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed");
|
return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Process upgrade results
|
||||||
unsigned short status = 406;
|
unsigned short status = 406;
|
||||||
if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) {
|
if (fwResult.status == UpgradeHandler::UpgradeStatus::SUCCESS || fsResult.status == UpgradeHandler::UpgradeStatus::SUCCESS) {
|
||||||
status = 202;
|
status = 202;
|
||||||
|
|
||||||
|
// Schedule restart after a successful upgrade
|
||||||
if (!restartTask.scheduled() && !restartTask.active()) {
|
if (!restartTask.scheduled() && !restartTask.active()) {
|
||||||
restartTask.resume(15000);
|
restartTask.resume(15000);
|
||||||
}
|
}
|
||||||
@@ -302,6 +313,7 @@ static void restApi() {
|
|||||||
requestReconfigureMqtt();
|
requestReconfigureMqtt();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resume tasks after a failed upgrade
|
||||||
upgrading = false;
|
upgrading = false;
|
||||||
if (status != 202 && !restartTask.scheduled() && !restartTask.active()) {
|
if (status != 202 && !restartTask.scheduled() && !restartTask.active()) {
|
||||||
coreTaskManager.resume();
|
coreTaskManager.resume();
|
||||||
@@ -313,7 +325,7 @@ static void restApi() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
@@ -325,7 +337,7 @@ static void restApi() {
|
|||||||
fsDoc["status"] = static_cast<uint8_t>(fsResult.status);
|
fsDoc["status"] = static_cast<uint8_t>(fsResult.status);
|
||||||
fsDoc["error"] = fsResult.error;
|
fsDoc["error"] = fsResult.error;
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
response->setCode(status);
|
response->setCode(status);
|
||||||
request->send(response);
|
request->send(response);
|
||||||
@@ -334,17 +346,17 @@ static void restApi() {
|
|||||||
webServer->addHandler(upgradeHandler);
|
webServer->addHandler(upgradeHandler);
|
||||||
|
|
||||||
|
|
||||||
// backup
|
// Get backup
|
||||||
webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/backup/save", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
// add network settings
|
// Add network settings
|
||||||
auto networkDoc = doc[S_NETWORK].to<JsonObject>();
|
auto networkDoc = doc[S_NETWORK].to<JsonObject>();
|
||||||
toJson(networkSettings, networkDoc);
|
toJson(networkSettings, networkDoc);
|
||||||
|
|
||||||
// add main settings
|
// Add main settings
|
||||||
auto settingsDoc = doc[S_SETTINGS].to<JsonObject>();
|
auto settingsDoc = doc[S_SETTINGS].to<JsonObject>();
|
||||||
toJson(settings.system, settingsDoc[S_SYSTEM].to<JsonObject>());
|
toJson(settings.system, settingsDoc[S_SYSTEM].to<JsonObject>());
|
||||||
toJson(settings.portal, settingsDoc[S_PORTAL].to<JsonObject>());
|
toJson(settings.portal, settingsDoc[S_PORTAL].to<JsonObject>());
|
||||||
@@ -358,7 +370,7 @@ static void restApi() {
|
|||||||
toJson(settings.externalPump, settingsDoc[S_EXTERNAL_PUMP].to<JsonObject>());
|
toJson(settings.externalPump, settingsDoc[S_EXTERNAL_PUMP].to<JsonObject>());
|
||||||
toJson(settings.cascadeControl, settingsDoc[S_CASCADE_CONTROL].to<JsonObject>());
|
toJson(settings.cascadeControl, settingsDoc[S_CASCADE_CONTROL].to<JsonObject>());
|
||||||
|
|
||||||
// add sensors settings
|
// Add sensor settings
|
||||||
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
if (const auto sensor = Sensors::getSettings(sensorId)) {
|
if (const auto sensor = Sensors::getSettings(sensorId)) {
|
||||||
auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to<JsonObject>();
|
auto sensorsettingsDoc = doc[S_SENSORS][sensorId].to<JsonObject>();
|
||||||
@@ -366,25 +378,27 @@ static void restApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
setDownloadFilename(response, "backup", "json");
|
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(setDownloadFilename(response, "backup", "json"));
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// restart
|
|
||||||
|
// Request restart
|
||||||
webServer->on("/api/restart", HTTP_POST, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/restart", HTTP_POST, [](AsyncWebServerRequest *request) {
|
||||||
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
return request->send(503);
|
return request->send(503);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Schedule restart
|
||||||
restartTask.resume(15000);
|
restartTask.resume(15000);
|
||||||
request->send(202);
|
request->send(202);
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// network
|
|
||||||
|
// Get network settings
|
||||||
webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/network/settings", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
toJson(networkSettings, doc);
|
toJson(networkSettings, doc);
|
||||||
@@ -392,32 +406,36 @@ static void restApi() {
|
|||||||
doc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
|
doc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
auto& nsHandler = webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
|
||||||
|
// Set network settings
|
||||||
|
auto& networkSettingsHandler = webServer->on("/api/network/settings", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
return request->send(503);
|
return request->send(503);
|
||||||
}
|
|
||||||
|
|
||||||
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
} else if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
||||||
return request->send(400);
|
return request->send(400);
|
||||||
}
|
}
|
||||||
|
|
||||||
// prepare request
|
// Apply network settings
|
||||||
const auto result = fromJson(requestDoc, networkSettings);
|
const auto result = fromJson(requestDoc, networkSettings);
|
||||||
if (result.changed) {
|
if (result.changed) {
|
||||||
|
// Request network settings save
|
||||||
requestSaveNetworkSettings();
|
requestSaveNetworkSettings();
|
||||||
}
|
}
|
||||||
requestDoc.clear();
|
requestDoc.clear();
|
||||||
|
|
||||||
|
// If the noresponse parameter is provided,
|
||||||
|
// simply return HTTP 200/201 with an empty body.
|
||||||
if (request->hasParam("noresponse")) {
|
if (request->hasParam("noresponse")) {
|
||||||
request->send(result.changed ? 201 : 200);
|
request->send(result.changed ? 201 : 200);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& responseDoc = response->getRoot();
|
auto& responseDoc = response->getRoot();
|
||||||
toJson(networkSettings, responseDoc);
|
toJson(networkSettings, responseDoc);
|
||||||
@@ -425,20 +443,23 @@ static void restApi() {
|
|||||||
responseDoc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
|
responseDoc[S_ETHERNET][S_CONFIGURED] = isEthernetConfigured();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
response->setCode(result.changed ? 201 : 200);
|
response->setCode(result.changed ? 201 : 200);
|
||||||
request->send(response);
|
request->send(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reconnect network
|
||||||
if (result.changed && !request->hasParam("noreconnect")) {
|
if (result.changed && !request->hasParam("noreconnect")) {
|
||||||
// Queue the response before a network reset can disconnect this request.
|
// Queue the response before a network reset can disconnect this request.
|
||||||
reconnectNetwork();
|
reconnectNetwork();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
nsHandler.setMaxContentLength(1024);
|
networkSettingsHandler.setMaxContentLength(1024);
|
||||||
nsHandler.addMiddleware(&authMiddleware);
|
networkSettingsHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// Scan Wi-Fi
|
||||||
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/network/scan", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
// Ethernet mode must not start the Wi-Fi radio for a scan.
|
// Ethernet mode must not start the Wi-Fi radio for a scan.
|
||||||
if (networkSettings.type != NetworkMode::STA) {
|
if (networkSettings.type != NetworkMode::STA) {
|
||||||
@@ -446,10 +467,12 @@ static void restApi() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read scan status
|
||||||
auto apCount = WiFi.scanComplete();
|
auto apCount = WiFi.scanComplete();
|
||||||
|
|
||||||
switch (apCount) {
|
switch (apCount) {
|
||||||
case WIFI_SCAN_FAILED:
|
case WIFI_SCAN_FAILED:
|
||||||
|
// Start asynchronous scan
|
||||||
WiFi.scanNetworks(true, true, true);
|
WiFi.scanNetworks(true, true, true);
|
||||||
request->send(404);
|
request->send(404);
|
||||||
break;
|
break;
|
||||||
@@ -459,7 +482,7 @@ static void restApi() {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
// make respponse
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse(true);
|
auto *response = new AsyncJsonResponse(true);
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
for (short int i = 0; i < apCount; i++) {
|
for (short int i = 0; i < apCount; i++) {
|
||||||
@@ -471,24 +494,28 @@ static void restApi() {
|
|||||||
doc[i][S_AUTH] = WiFi.encryptionType(i);
|
doc[i][S_AUTH] = WiFi.encryptionType(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
|
|
||||||
// clear
|
// Release scan results
|
||||||
WiFi.scanDelete();
|
WiFi.scanDelete();
|
||||||
}
|
}
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
// settings
|
// Get settings
|
||||||
webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
|
// Parse settings section
|
||||||
const auto& url = request->url();
|
const auto& url = request->url();
|
||||||
const auto section = std::string_view(url.c_str(), url.length())
|
const auto section = std::string_view(url.c_str(), url.length())
|
||||||
.substr(sizeof("/api/settings/") - 1);
|
.substr(sizeof("/api/settings/") - 1);
|
||||||
|
|
||||||
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
|
// Add section settings
|
||||||
if (section == S_SYSTEM) {
|
if (section == S_SYSTEM) {
|
||||||
toJson(settings.system, doc);
|
toJson(settings.system, doc);
|
||||||
|
|
||||||
@@ -527,27 +554,29 @@ static void restApi() {
|
|||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// Set settings
|
||||||
auto& settingsHandler = webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
auto& settingsHandler = webServer->on(AsyncURIMatcher::prefix("/api/settings/"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
request->send(503);
|
return request->send(503);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
} else if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
||||||
request->send(400);
|
return request->send(400);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse settings section
|
||||||
const auto& url = request->url();
|
const auto& url = request->url();
|
||||||
const auto section = std::string_view(url.c_str(), url.length())
|
const auto section = std::string_view(url.c_str(), url.length())
|
||||||
.substr(sizeof("/api/settings/") - 1);
|
.substr(sizeof("/api/settings/") - 1);
|
||||||
SettingResult result;
|
|
||||||
bool mqttChanged = false;
|
|
||||||
|
|
||||||
|
// Apply section settings
|
||||||
|
bool mqttChanged = false;
|
||||||
|
SettingResult result;
|
||||||
if (section == S_SYSTEM) {
|
if (section == S_SYSTEM) {
|
||||||
result = fromJson(requestDoc, settings.system);
|
result = fromJson(requestDoc, settings.system);
|
||||||
|
|
||||||
@@ -594,14 +623,19 @@ static void restApi() {
|
|||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalize settings
|
||||||
result.changed = normalizeSettings(settings) || result.changed;
|
result.changed = normalizeSettings(settings) || result.changed;
|
||||||
if (result.changed) {
|
if (result.changed) {
|
||||||
|
// Request settings save and logging update
|
||||||
requestSaveSettings();
|
requestSaveSettings();
|
||||||
configureLoggingTask.resume();
|
configureLoggingTask.resume();
|
||||||
|
|
||||||
|
// Request MQTT reconfiguration
|
||||||
if (mqttChanged) {
|
if (mqttChanged) {
|
||||||
requestReconfigureMqtt();
|
requestReconfigureMqtt();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Request MQTT settings publication
|
||||||
// If busy, the periodic task will publish the current settings.
|
// If busy, the periodic task will publish the current settings.
|
||||||
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
|
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
|
||||||
if (lock.owns_lock() && mqttPublishSettingsTask) {
|
if (lock.owns_lock() && mqttPublishSettingsTask) {
|
||||||
@@ -610,13 +644,17 @@ static void restApi() {
|
|||||||
}
|
}
|
||||||
requestDoc.clear();
|
requestDoc.clear();
|
||||||
|
|
||||||
|
// If the noresponse parameter is provided,
|
||||||
|
// simply return HTTP 200/201 with an empty body.
|
||||||
if (request->hasParam("noresponse")) {
|
if (request->hasParam("noresponse")) {
|
||||||
return request->send(result.changed ? 201 : 200);
|
return request->send(result.changed ? 201 : 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& responseDoc = response->getRoot();
|
auto& responseDoc = response->getRoot();
|
||||||
|
|
||||||
|
// Add section settings
|
||||||
if (section == S_SYSTEM) {
|
if (section == S_SYSTEM) {
|
||||||
toJson(settings.system, responseDoc);
|
toJson(settings.system, responseDoc);
|
||||||
|
|
||||||
@@ -651,6 +689,7 @@ static void restApi() {
|
|||||||
toJson(settings.cascadeControl, responseDoc);
|
toJson(settings.cascadeControl, responseDoc);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
response->setCode(result.changed ? 201 : 200);
|
response->setCode(result.changed ? 201 : 200);
|
||||||
request->send(response);
|
request->send(response);
|
||||||
@@ -659,14 +698,14 @@ static void restApi() {
|
|||||||
settingsHandler.addMiddleware(&authMiddleware);
|
settingsHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
// sensors list
|
// Get sensors list
|
||||||
webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/sensors", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
// make response
|
// Prepare response
|
||||||
bool detailed = request->hasParam("detailed");
|
bool detailed = request->hasParam("detailed");
|
||||||
auto *response = new AsyncJsonResponse(true);
|
auto *response = new AsyncJsonResponse(true);
|
||||||
auto& responseDoc = response->getRoot();
|
auto& responseDoc = response->getRoot();
|
||||||
|
|
||||||
// add sensors
|
// Build sensor list
|
||||||
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
for (uint8_t sensorId = 0; sensorId <= Sensors::getMaxSensorId(); sensorId++) {
|
||||||
if (detailed) {
|
if (detailed) {
|
||||||
if (const auto snapshot = Sensors::getSnapshot(sensorId)) {
|
if (const auto snapshot = Sensors::getSnapshot(sensorId)) {
|
||||||
@@ -682,54 +721,62 @@ static void restApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
// sensor settings
|
|
||||||
|
// Get sensor settings
|
||||||
webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
if (!request->hasParam("id")) {
|
if (!request->hasParam("id")) {
|
||||||
return request->send(400);
|
return request->send(400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse sensor ID
|
||||||
const auto& id = request->getParam("id")->value();
|
const auto& id = request->getParam("id")->value();
|
||||||
const auto sensorId = Sensors::parseId(id.c_str());
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
if (!sensorId) {
|
if (!sensorId) {
|
||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get sensor settings for response
|
||||||
const auto sensor = Sensors::getSettings(*sensorId);
|
const auto sensor = Sensors::getSettings(*sensorId);
|
||||||
if (!sensor) {
|
if (!sensor) {
|
||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
toJson(*sensorId, *sensor, doc);
|
toJson(*sensorId, *sensor, doc);
|
||||||
|
|
||||||
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
auto& ssHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
|
||||||
|
// Set sensor settings
|
||||||
|
auto& sensorSettingsHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
return request->send(503);
|
return request->send(503);
|
||||||
}
|
|
||||||
|
|
||||||
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
} else if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
||||||
return request->send(400);
|
return request->send(400);
|
||||||
}
|
|
||||||
|
|
||||||
if (!request->hasParam("id")) {
|
} else if (!request->hasParam("id")) {
|
||||||
return request->send(400);
|
return request->send(400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse sensor ID
|
||||||
auto& id = request->getParam("id")->value();
|
auto& id = request->getParam("id")->value();
|
||||||
const auto sensorId = Sensors::parseId(id.c_str());
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
if (!sensorId) {
|
if (!sensorId) {
|
||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Apply sensor settings
|
||||||
Sensors::Settings previousSettings;
|
Sensors::Settings previousSettings;
|
||||||
bool isDifferent = false;
|
bool isDifferent = false;
|
||||||
SettingResult result;
|
SettingResult result;
|
||||||
@@ -764,59 +811,68 @@ static void restApi() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (result.changed) {
|
if (result.changed) {
|
||||||
|
// Request MQTT sensor reconfiguration
|
||||||
if (isDifferent) {
|
if (isDifferent) {
|
||||||
requestReconfigureMqttSensor(*sensorId, previousSettings);
|
requestReconfigureMqttSensor(*sensorId, previousSettings);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Request sensor settings save
|
||||||
requestSaveSensorsSettings();
|
requestSaveSensorsSettings();
|
||||||
}
|
}
|
||||||
requestDoc.clear();
|
requestDoc.clear();
|
||||||
|
|
||||||
|
// If the noresponse parameter is provided,
|
||||||
|
// simply return HTTP 200/201 with an empty body.
|
||||||
if (request->hasParam("noresponse")) {
|
if (request->hasParam("noresponse")) {
|
||||||
return request->send(result.changed ? 201 : 200);
|
return request->send(result.changed ? 201 : 200);
|
||||||
}
|
}
|
||||||
|
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& responseDoc = response->getRoot();
|
auto& responseDoc = response->getRoot();
|
||||||
|
|
||||||
if (const auto sensor = Sensors::getSettings(*sensorId)) {
|
if (const auto sensor = Sensors::getSettings(*sensorId)) {
|
||||||
toJson(*sensorId, *sensor, responseDoc);
|
toJson(*sensorId, *sensor, responseDoc);
|
||||||
}
|
}
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
response->setCode(result.changed ? 201 : 200);
|
response->setCode(result.changed ? 201 : 200);
|
||||||
request->send(response);
|
request->send(response);
|
||||||
});
|
});
|
||||||
ssHandler.setMaxContentLength(1024);
|
sensorSettingsHandler.setMaxContentLength(1024);
|
||||||
ssHandler.addMiddleware(&authMiddleware);
|
sensorSettingsHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
// sensor measurements
|
// Get sensor measurements
|
||||||
webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
if (!request->hasParam("id")) {
|
if (!request->hasParam("id")) {
|
||||||
return request->send(400);
|
return request->send(400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse sensor ID
|
||||||
const auto& id = request->getParam("id")->value();
|
const auto& id = request->getParam("id")->value();
|
||||||
const auto sensorId = Sensors::parseId(id.c_str());
|
const auto sensorId = Sensors::parseId(id.c_str());
|
||||||
if (!sensorId) {
|
if (!sensorId) {
|
||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get sensor snapshot for response
|
||||||
const auto sensor = Sensors::getSnapshot(*sensorId);
|
const auto sensor = Sensors::getSnapshot(*sensorId);
|
||||||
if (!sensor) {
|
if (!sensor) {
|
||||||
return request->send(404);
|
return request->send(404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
toJson(sensor->settings, sensor->result, doc);
|
toJson(sensor->settings, sensor->result, doc);
|
||||||
|
|
||||||
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
// Set sensor value (JSON)
|
// Set sensor value (JSON)
|
||||||
auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
@@ -948,42 +1004,43 @@ static void restApi() {
|
|||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
|
||||||
// vars
|
// Get vars
|
||||||
webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
toJson(vars, doc);
|
toJson(vars, doc);
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
});
|
});
|
||||||
|
|
||||||
auto& vHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
// Set vars
|
||||||
|
auto& varsHandler = webServer->on("/api/vars", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
|
||||||
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
if (upgrading || restartTask.scheduled() || restartTask.active()) {
|
||||||
return request->send(503);
|
return request->send(503);
|
||||||
}
|
|
||||||
|
|
||||||
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
} else if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
|
||||||
return request->send(400);
|
return request->send(400);
|
||||||
}
|
}
|
||||||
|
|
||||||
// prepare request
|
// Apply requested actions
|
||||||
const auto result = fromJson(requestDoc, vars);
|
const auto result = fromJson(requestDoc, vars);
|
||||||
requestDoc.clear();
|
requestDoc.clear();
|
||||||
|
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& responseDoc = response->getRoot();
|
auto& responseDoc = response->getRoot();
|
||||||
toJson(vars, responseDoc);
|
toJson(vars, responseDoc);
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
response->setCode(result.changed ? 201 : 200);
|
response->setCode(result.changed ? 201 : 200);
|
||||||
request->send(response);
|
request->send(response);
|
||||||
|
|
||||||
if (result.changed) {
|
if (result.changed) {
|
||||||
|
// Request MQTT state publication
|
||||||
// If busy, the periodic task will publish the current state.
|
// If busy, the periodic task will publish the current state.
|
||||||
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
|
std::unique_lock<std::mutex> lock(mqttMutex, std::try_to_lock);
|
||||||
if (lock.owns_lock() && mqttPublishStateTask) {
|
if (lock.owns_lock() && mqttPublishStateTask) {
|
||||||
@@ -991,11 +1048,12 @@ static void restApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
vHandler.setMaxContentLength(1536);
|
varsHandler.setMaxContentLength(1536);
|
||||||
vHandler.addMiddleware(&authMiddleware);
|
varsHandler.addMiddleware(&authMiddleware);
|
||||||
|
|
||||||
|
// Get info
|
||||||
webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
|
webServer->on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||||
// make response
|
// Prepare response
|
||||||
auto *response = new AsyncJsonResponse();
|
auto *response = new AsyncJsonResponse();
|
||||||
auto& doc = response->getRoot();
|
auto& doc = response->getRoot();
|
||||||
|
|
||||||
@@ -1003,10 +1061,12 @@ static void restApi() {
|
|||||||
doc[S_FEATURES][S_ETHERNET] = true;
|
doc[S_FEATURES][S_ETHERNET] = true;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// Add system information
|
||||||
auto docSystem = doc[S_SYSTEM].to<JsonObject>();
|
auto docSystem = doc[S_SYSTEM].to<JsonObject>();
|
||||||
docSystem[S_RESET_REASON] = getResetReason();
|
docSystem[S_RESET_REASON] = getResetReason();
|
||||||
docSystem[S_UPTIME] = millis() / 1000;
|
docSystem[S_UPTIME] = millis() / 1000;
|
||||||
|
|
||||||
|
// Add network information
|
||||||
const bool isConnected = isNetworkConnected();
|
const bool isConnected = isNetworkConnected();
|
||||||
const bool wifiUplink = getNetworkMode() == NetworkMode::STA;
|
const bool wifiUplink = getNetworkMode() == NetworkMode::STA;
|
||||||
auto docNetwork = doc[S_NETWORK].to<JsonObject>();
|
auto docNetwork = doc[S_NETWORK].to<JsonObject>();
|
||||||
@@ -1022,6 +1082,7 @@ static void restApi() {
|
|||||||
docNetwork[S_GATEWAY] = isConnected ? getNetworkGateway().toString() : "";
|
docNetwork[S_GATEWAY] = isConnected ? getNetworkGateway().toString() : "";
|
||||||
docNetwork[S_DNS] = isConnected ? getNetworkDns().toString() : "";
|
docNetwork[S_DNS] = isConnected ? getNetworkDns().toString() : "";
|
||||||
|
|
||||||
|
// Add build information
|
||||||
auto docBuild = doc[S_BUILD].to<JsonObject>();
|
auto docBuild = doc[S_BUILD].to<JsonObject>();
|
||||||
docBuild[S_VERSION] = BUILD_VERSION;
|
docBuild[S_VERSION] = BUILD_VERSION;
|
||||||
docBuild[S_COMMIT] = BUILD_COMMIT;
|
docBuild[S_COMMIT] = BUILD_COMMIT;
|
||||||
@@ -1030,6 +1091,7 @@ static void restApi() {
|
|||||||
docBuild[S_CORE] = ESP.getCoreVersion();
|
docBuild[S_CORE] = ESP.getCoreVersion();
|
||||||
docBuild[S_SDK] = ESP.getSdkVersion();
|
docBuild[S_SDK] = ESP.getSdkVersion();
|
||||||
|
|
||||||
|
// Add memory metrics
|
||||||
const auto memory = getMemoryMetrics();
|
const auto memory = getMemoryMetrics();
|
||||||
auto docHeap = doc[S_HEAP].to<JsonObject>();
|
auto docHeap = doc[S_HEAP].to<JsonObject>();
|
||||||
docHeap[S_TOTAL] = memory.heap.total;
|
docHeap[S_TOTAL] = memory.heap.total;
|
||||||
@@ -1044,21 +1106,25 @@ static void restApi() {
|
|||||||
docPsram[S_MIN_FREE] = memory.psram.minimum_free_bytes;
|
docPsram[S_MIN_FREE] = memory.psram.minimum_free_bytes;
|
||||||
docPsram[S_MAX_FREE_BLOCK] = memory.psram.largest_free_block;
|
docPsram[S_MAX_FREE_BLOCK] = memory.psram.largest_free_block;
|
||||||
|
|
||||||
|
// Add chip information
|
||||||
auto docChip = doc[S_CHIP].to<JsonObject>();
|
auto docChip = doc[S_CHIP].to<JsonObject>();
|
||||||
docChip[S_MODEL] = ESP.getChipModel();
|
docChip[S_MODEL] = ESP.getChipModel();
|
||||||
docChip[S_REV] = ESP.getChipRevision();
|
docChip[S_REV] = ESP.getChipRevision();
|
||||||
docChip[S_CORES] = ESP.getChipCores();
|
docChip[S_CORES] = ESP.getChipCores();
|
||||||
docChip[S_FREQ] = ESP.getCpuFreqMHz();
|
docChip[S_FREQ] = ESP.getCpuFreqMHz();
|
||||||
|
|
||||||
|
// Add flash information
|
||||||
auto docFlash = doc[S_FLASH].to<JsonObject>();
|
auto docFlash = doc[S_FLASH].to<JsonObject>();
|
||||||
docFlash[S_SIZE] = ESP.getFlashChipSize();
|
docFlash[S_SIZE] = ESP.getFlashChipSize();
|
||||||
|
|
||||||
// send response
|
// Send response
|
||||||
response->setLength();
|
response->setLength();
|
||||||
request->send(response);
|
request->send(response);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Get coredump
|
||||||
webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) {
|
webServer->on("/api/coredump", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||||
|
// Locate core dump image
|
||||||
size_t address = 0;
|
size_t address = 0;
|
||||||
size_t size = 0;
|
size_t size = 0;
|
||||||
|
|
||||||
@@ -1068,11 +1134,13 @@ static void restApi() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate core dump image
|
||||||
if (esp_core_dump_image_check() != ESP_OK) {
|
if (esp_core_dump_image_check() != ESP_OK) {
|
||||||
request->send(500);
|
request->send(500);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate core dump partition
|
||||||
const esp_partition_t* partition = esp_partition_find_first(
|
const esp_partition_t* partition = esp_partition_find_first(
|
||||||
ESP_PARTITION_TYPE_DATA,
|
ESP_PARTITION_TYPE_DATA,
|
||||||
ESP_PARTITION_SUBTYPE_DATA_COREDUMP,
|
ESP_PARTITION_SUBTYPE_DATA_COREDUMP,
|
||||||
@@ -1083,12 +1151,14 @@ static void restApi() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prepare core dump download
|
||||||
auto* response = request->beginResponse("application/octet-stream", size,
|
auto* response = request->beginResponse("application/octet-stream", size,
|
||||||
[partition, size](uint8_t* buffer, size_t maximum, size_t index) -> size_t {
|
[partition, size](uint8_t* buffer, size_t maximum, size_t index) -> size_t {
|
||||||
if (index >= size) {
|
if (index >= size) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read core dump chunk
|
||||||
const size_t remaining = size - index;
|
const size_t remaining = size - index;
|
||||||
const size_t count = remaining < maximum ? remaining : maximum;
|
const size_t count = remaining < maximum ? remaining : maximum;
|
||||||
if (esp_partition_read(partition, index, buffer, count) != ESP_OK) {
|
if (esp_partition_read(partition, index, buffer, count) != ESP_OK) {
|
||||||
@@ -1097,12 +1167,13 @@ static void restApi() {
|
|||||||
|
|
||||||
return count;
|
return count;
|
||||||
});
|
});
|
||||||
setDownloadFilename(response, "coredump", "bin");
|
|
||||||
request->send(response);
|
// Send response
|
||||||
|
request->send(setDownloadFilename(response, "coredump", "bin"));
|
||||||
}).addMiddleware(&authMiddleware);
|
}).addMiddleware(&authMiddleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialization
|
// Initialize portal
|
||||||
void initPortal() {
|
void initPortal() {
|
||||||
webServer = new AsyncWebServer(80);
|
webServer = new AsyncWebServer(80);
|
||||||
initWebSerial();
|
initWebSerial();
|
||||||
|
|||||||
Reference in new issue
Block a user