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:
Yurii committed 2026-11-29 05:43:51 +03:00
1 parent 8fba88636e
commit 09b5f6c9e0
2 files changed
+165 -87

No files matched your search

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