2025-02-17 12:41:25 +01:00
|
|
|
#include <Arduino.h>
|
|
|
|
#include "ota.h"
|
2025-02-18 11:42:52 +01:00
|
|
|
#include <Update.h>
|
|
|
|
#include <SPIFFS.h>
|
|
|
|
#include "commonFS.h"
|
|
|
|
|
|
|
|
void handleOTAUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
2025-02-18 14:18:14 +01:00
|
|
|
static size_t contentLength = 0;
|
|
|
|
|
2025-02-18 11:42:52 +01:00
|
|
|
if (!index) {
|
2025-02-18 14:18:14 +01:00
|
|
|
contentLength = request->contentLength();
|
|
|
|
Serial.printf("Update size: %u bytes\n", contentLength);
|
|
|
|
|
|
|
|
if (contentLength == 0) {
|
|
|
|
request->send(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid file size\"}");
|
2025-02-18 11:42:52 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2025-02-20 01:08:48 +01:00
|
|
|
// Determine if this is a full image (firmware + SPIFFS) or just firmware
|
|
|
|
bool isFullImage = (contentLength > 0x3D0000); // SPIFFS starts at 0x3D0000
|
|
|
|
|
|
|
|
if (!Update.begin(contentLength, isFullImage ? U_FLASH : U_SPIFFS)) {
|
2025-02-18 14:18:14 +01:00
|
|
|
Serial.printf("Not enough space: %u required\n", contentLength);
|
|
|
|
request->send(400, "application/json", "{\"status\":\"error\",\"message\":\"Not enough space available\"}");
|
2025-02-18 11:42:52 +01:00
|
|
|
return;
|
|
|
|
}
|
2025-02-18 12:28:47 +01:00
|
|
|
|
2025-02-20 01:08:48 +01:00
|
|
|
Serial.println(isFullImage ? "Full image update started" : "Firmware update started");
|
2025-02-18 11:42:52 +01:00
|
|
|
}
|
2025-02-20 01:08:48 +01:00
|
|
|
|
|
|
|
// Write chunk to flash
|
2025-02-18 11:42:52 +01:00
|
|
|
if (Update.write(data, len) != len) {
|
2025-02-18 14:18:14 +01:00
|
|
|
Update.printError(Serial);
|
|
|
|
request->send(400, "application/json", "{\"status\":\"error\",\"message\":\"Error writing update\"}");
|
2025-02-18 11:42:52 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (final) {
|
2025-02-18 14:18:14 +01:00
|
|
|
if (Update.end(true)) {
|
|
|
|
Serial.println("Update complete");
|
|
|
|
request->send(200, "application/json", "{\"status\":\"success\",\"message\":\"Update successful! Device will restart...\",\"restart\":true}");
|
|
|
|
delay(1000);
|
2025-02-18 11:42:52 +01:00
|
|
|
ESP.restart();
|
2025-02-18 14:18:14 +01:00
|
|
|
} else {
|
|
|
|
Update.printError(Serial);
|
|
|
|
request->send(400, "application/json", "{\"status\":\"error\",\"message\":\"Update failed\"}");
|
2025-02-18 11:42:52 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2025-02-17 12:41:25 +01:00
|
|
|
|