Complete browser OTA responses before reboot and allow HTTP restarts

This commit is contained in:
mikecarper committed 2026-10-05 11:52:24 -07:00
1 parent 8fbf948d68
commit e95cf6d618
10 files changed
+449 -19

No files matched your search

+139
View File
@@ -0,0 +1,139 @@
#include <atomic>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <string>
using String = std::string;
constexpr int HTTP_GET=0, HTTP_POST=1, U_FLASH=0, U_SPIFFS=100;
constexpr unsigned UPDATE_SIZE_UNKNOWN=~0U;
constexpr int pdPASS=1;
#define pdMS_TO_TICKS(value) (value)
const char ELEGANT_HTML[] = "page";
const unsigned ELEGANT_HTML_SIZE=sizeof(ELEGANT_HTML);
int Serial=0;
bool in_network_callback=false;
struct Esp {
int restarts=0;
void restart() { assert(!in_network_callback); ++restarts; }
} ESP;
void yield() { assert(!in_network_callback); }
void delay(unsigned) { assert(!in_network_callback); }
void vTaskDelay(unsigned) { assert(!in_network_callback); }
void vTaskDelete(void*) {}
using Task = void (*)(void*);
Task pending_task=nullptr;
bool allow_task=true;
int xTaskCreate(Task task, const char*, unsigned, void*, unsigned, void*) {
if (!allow_task) return 0;
assert(!pending_task); pending_task=task; return pdPASS;
}
@REBOOT_STATE@
struct Parameter { String text="valid"; String value() { return text; } };
struct Response {
int code;
void addHeader(const char*, const char*) {}
};
struct Request {
void* _tempObject=nullptr;
bool md5_present=true, authorized=true, sent=false;
int code=0;
std::function<void()> disconnected;
Parameter md5;
~Request() { free(_tempObject); }
bool authenticate(const char*, const char*) { return authorized; }
void requestAuthentication() { code=401; sent=true; }
bool hasParam(const char*, bool) { return md5_present; }
Parameter* getParam(const char*, bool) { return &md5; }
Response* beginResponse(int code, const char*, const char*) { return new Response{code}; }
Response* beginResponse_P(int code, const char*, const char*, unsigned) { return new Response{code}; }
void send(Response* response) { code=response->code; sent=true; delete response; }
void send(int status, const char*, const char*) { code=status; sent=true; }
void send(int status, const char*, const String&) { code=status; sent=true; }
bool isSent() const { return sent; }
void onDisconnect(std::function<void()> fn) { disconnected=fn; }
};
using AsyncWebServerRequest=Request;
static AsyncWebServerRequest* ota_upload_owner=nullptr;
using AsyncWebServerResponse=Response;
struct AsyncWebServer {
std::function<void(Request*)> completion;
std::function<void(Request*,String,size_t,uint8_t*,size_t,bool)> upload;
template<class F> void on(const char*, int, F) {}
template<class F,class U> void on(const char*, int method, F callback, U chunks) {
assert(method==HTTP_POST); completion=callback; upload=chunks;
}
};
struct UpdateFake {
bool error=false, fail_end=false;
int aborts=0;
bool hasError() const { return error; }
bool setMD5(const char* md5) { return String(md5)=="valid"; }
bool begin(unsigned, int) { error=false; return true; }
size_t write(uint8_t*, size_t size) { return size; }
bool end(bool) { error=fail_end; return !error; }
void abort() { error=true; ++aborts; }
void printError(int) {}
} Update;
struct AsyncElegantOtaClass {
AsyncWebServer* _server=nullptr;
bool _authRequired=false;
String _username, _password, _id="fixture";
void begin(AsyncWebServer*, const char*, const char*);
void restart();
bool setEnabled(bool);
};
@BEGIN@
@RESTART@
int main() {
AsyncWebServer server;
AsyncElegantOtaClass ota;
ota.begin(&server,"","");
auto complete=[&](Request& request) {
in_network_callback=true; server.completion(&request); in_network_callback=false;
};
auto upload=[&](Request& request) {
uint8_t data[8]={};
in_network_callback=true;
server.upload(&request,"firmware",0,data,sizeof(data),true);
in_network_callback=false;
};
// A POST without an actual completed upload cannot report OK or reboot.
Request empty;
complete(empty);
assert(empty.code>=400 && !pending_task && ESP.restarts==0);
Request invalid;
invalid.md5_present=false;
upload(invalid); complete(invalid);
assert(invalid.code==400 && !pending_task && ESP.restarts==0);
Request corrupt;
Update.fail_end=true;
upload(corrupt); complete(corrupt);
assert(corrupt.code==400 && !pending_task && ESP.restarts==0);
in_network_callback=true; corrupt.disconnected(); in_network_callback=false;
assert(Update.aborts==1 && ota_upload_owner==nullptr);
Update.fail_end=false;
Request partial;
uint8_t chunk[4]={};
server.upload(&partial,"firmware",0,chunk,sizeof(chunk),false);
assert(!ota.setEnabled(false)); // An admitted upload keeps its listener alive.
Request concurrent;
upload(concurrent); complete(concurrent);
assert(concurrent.code==409 && ota_upload_owner==&partial);
in_network_callback=true; partial.disconnected(); in_network_callback=false;
assert(Update.aborts==2 && ota_upload_owner==nullptr && ESP.restarts==0);
assert(ota.setEnabled(false));
Request stopped;
upload(stopped); complete(stopped);
assert(stopped.code==503 && !ota_upload_owner && !pending_task);
assert(ota.setEnabled(true));
Request valid;
upload(valid); complete(valid);
assert(valid.code==200 && valid.disconnected && !pending_task && ESP.restarts==0);
// The response drains before disconnect; its callback only schedules work.
in_network_callback=true; valid.disconnected(); in_network_callback=false;
assert(pending_task && ESP.restarts==0);
auto task=pending_task; pending_task=nullptr; task(nullptr);
assert(ESP.restarts==1);
}
+32 -2
View File
@@ -12,6 +12,8 @@ constexpr int WL_CONNECTED = 3;
constexpr int HTTP_GET = 0;
constexpr int WIFI_AP = 2;
constexpr int ESP_OK = 0, WIFI_IF_AP = 1;
constexpr int LISTEN = 10;
bool async_bind_allowed = true;
constexpr uint8_t WIFI_PROTOCOL_11B = 1, WIFI_PROTOCOL_11G = 2;
constexpr uint8_t WIFI_PROTOCOL_11N = 4, WIFI_PROTOCOL_LR = 8;
using esp_err_t = int;
@@ -60,15 +62,20 @@ struct AsyncWebServerRequest {
void send(int, const char*, const char*, const char*) {}
};
struct AsyncWebServer {
bool listening = false;
explicit AsyncWebServer(int) {}
template<class F> void on(const char*, int, F) {}
void begin() { ++server_starts; }
void end() {}
void begin() { ++server_starts; listening = async_bind_allowed; }
void end() { listening = false; }
int state() const { return listening ? LISTEN : 0; }
};
struct Elegant {
bool busy = false;
void setID(const char*) {}
void begin(AsyncWebServer*) {}
bool setEnabled(bool enabled) { return enabled || !busy; }
} AsyncElegantOTA;
static AsyncWebServer* async_ota_host = nullptr;
static int SPIFFS;
struct ESP32Board {
bool inhibit_sleep = false;
@@ -141,6 +148,21 @@ int main() {
WiFi.ap = false; // An external driver stop invalidates cached AP ownership.
start(true, "192.168.4.1", "Join WiFi MeshCore-OTA");
assert(WiFi.starts == ap_starts + 1);
#ifndef LIGHTWEIGHT_WIFI_OTA
auto* existing_server = board.ota_server;
existing_server->listening = false;
async_bind_allowed = false;
assert(!board.startOTAUpdate("test node", reply.text, true));
assert(strstr(reply.text, "OTA server failed") && board.inhibit_sleep);
async_bind_allowed = true;
start(true, "192.168.4.1", "Join WiFi MeshCore-OTA");
assert(board.ota_server == existing_server && existing_server->listening);
AsyncElegantOTA.busy = true;
assert(!board.stopOTAUpdate(reply.text));
assert(strstr(reply.text, "OTA upload active") && board.inhibit_sleep);
assert(board.ota_server == existing_server && existing_server->listening);
AsyncElegantOTA.busy = false;
#endif
#ifdef LIGHTWEIGHT_WIFI_OTA
lightweight_ota_server.allow_stop = false;
assert(!board.stopOTAUpdate(reply.text));
@@ -165,6 +187,14 @@ int main() {
assert(!board.startOTAUpdate("test node", reply.text, false));
assert(strcmp(reply.text, "ERR: OTA WiFi failed") == 0);
assert(!board.inhibit_sleep && !board.ota_server);
#ifndef LIGHTWEIGHT_WIFI_OTA
WiFi.allow_ap = true;
async_bind_allowed = false;
assert(!board.startOTAUpdate("test node", reply.text, false));
assert(strstr(reply.text, "OTA server failed"));
assert(!board.inhibit_sleep && !board.ota_server && !WiFi.ap);
async_bind_allowed = true;
#endif
// A pending wireless shutdown must not race a newly started uploader.
struct Backend : mesh::wireless::Backend {
uint8_t active = mesh::wireless::All;
+74
View File
@@ -0,0 +1,74 @@
"""Execute the vendored uploader and pinned TCP listener restart path."""
import importlib.util
from pathlib import Path
import urllib.request
import unittest
from test_replay_reset_integration import extract_braced
import test_wifi_ota_start as wifi_start
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location("async_web_fix", ROOT/"scripts/esp32_async_web_fix.py")
fix=importlib.util.module_from_spec(spec)
spec.loader.exec_module(fix)
class AsyncWebLifecycleTest(unittest.TestCase):
compile_and_run=wifi_start.WiFiOtaStartTest.compile_and_run
def test_upload_response_drains_before_deferred_reboot(self):
source=(ROOT/"arch/esp32/AsyncElegantOTA/src/AsyncElegantOTA.cpp").read_text()
fixture=(ROOT/"test/fixtures/async_ota_completion.cpp").read_text()
state="""static std::atomic<bool> ota_reboot_pending{false};
static std::atomic<bool> ota_uploads_enabled{false};
static std::atomic<bool> ota_upload_busy{false};"""
# The two preprocessor branches for Update.begin each open the same
# logical block, so extract this method by its next declaration.
begin=source[source.index("void AsyncElegantOtaClass::begin("):source.index("// deprecated")]
self.compile_and_run(fixture.replace("@REBOOT_STATE@",state)
.replace("@BEGIN@",begin)
.replace("@RESTART@",extract_braced(source,"void AsyncElegantOtaClass::restart()")),"-DESP32=1")
def test_tcp_listener_can_rebind_with_completed_connections(self):
cached=ROOT/".pio/libdeps/heltec_v4_repeater_observer_mqtt/AsyncTCP/src/AsyncTCP.cpp"
source=(cached.read_text() if cached.exists() else urllib.request.urlopen(
"https://raw.githubusercontent.com/ESP32Async/AsyncTCP/v3.5.0/src/AsyncTCP.cpp",
timeout=30).read().decode("ascii"))
patched=fix.patched_async_tcp(source)
fixture=r'''
#include <cassert>
#define SO_REUSE 1
constexpr int SOF_REUSEADDR=4,ERR_OK=0,ERR_USE=-8;
using err_t=int;
struct tcp_pcb { int flags=0; };
struct tcpip_api_call_data {};
struct tcp_api_call_t : tcpip_api_call_data {
tcp_pcb** pcb;
struct { void* addr=nullptr; unsigned short port=80; } bind;
int err=0;
};
bool active_listener=false,time_wait=true;
void ip_set_option(tcp_pcb* pcb,int flags) { pcb->flags|=flags; }
int tcp_bind(tcp_pcb* pcb,void*,unsigned short) {
return active_listener || (time_wait && !(pcb->flags&SOF_REUSEADDR)) ? ERR_USE : ERR_OK;
}
int tcp_close(tcp_pcb*) { return ERR_OK; }
void tcp_abort(tcp_pcb*) { assert(false); }
@BIND@
int main() {
tcp_pcb pcb,*pointer=&pcb;
tcp_api_call_t message; message.pcb=&pointer;
assert(_tcp_bind_api(&message)==ERR_OK && pointer==&pcb);
active_listener=true;
assert(_tcp_bind_api(&message)==ERR_USE && pointer==nullptr);
}
'''
self.compile_and_run(fixture.replace("@BIND@",extract_braced(patched,"static err_t _tcp_bind_api(")))
with self.assertRaises(AssertionError):
self.compile_and_run(fixture.replace("@BIND@",extract_braced(source,"static err_t _tcp_bind_api(")))
with self.assertRaisesRegex(RuntimeError,"changed pinned source"):
fix.patched_async_tcp(source+"\n// unreviewed change\n")
if __name__=="__main__":
unittest.main()
+7 -1
View File
@@ -39,6 +39,7 @@ STUBS = r'''
constexpr int WL_CONNECTED = 3, WL_DISCONNECTED = 6, HTTP_GET = 0;
constexpr int WIFI_AP = 2;
constexpr int ESP_OK = 0;
constexpr int LISTEN = 10;
struct IPAddress {
uint32_t value = 0;
@@ -102,14 +103,19 @@ struct AsyncWebServerRequest {
template<class... Args> void send(Args...) {}
};
struct AsyncWebServer {
bool listening = false;
explicit AsyncWebServer(int port) { assert(port == 80); ++server_count; }
template<class Handler> void on(const char*, int, Handler) {}
void begin() { ++server_begin_calls; }
void begin() { ++server_begin_calls; listening = true; }
void end() { listening = false; }
int state() const { return listening ? LISTEN : 0; }
};
struct MockElegantOTA {
void setID(const char*) {}
void begin(AsyncWebServer* server) { assert(server != nullptr); }
bool setEnabled(bool) { return true; }
} AsyncElegantOTA;
static AsyncWebServer* async_ota_host = nullptr;
struct MockSPIFFS {} SPIFFS;
class ESP32Board {