Make ESP32 OTA startup handle WiFi and WebConfig automatically

Report the upload address and required network, honor AP switches on an existing uploader, and keep delayed WebConfig cleanup from disabling OTA WiFi. Preserve actionable startup errors and account for OTA in wireless state controls.

Exercise the production OTA lifecycle and stock website console, including power-saving idle sessions, in host regression tests.
This commit is contained in:
mikecarper committed 2026-10-05 10:31:43 -07:00
1 parent 22e1e405f4
commit 47135e081c
23 files changed
+965 -46

No files matched your search

+16 -5
View File
@@ -2749,14 +2749,21 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
const bool force_ap = command[9] == ' ' && strcmp(&command[10], "ap") == 0;
if (command[9] == ' ' && !force_ap) {
strcpy(reply, "ERR: usage start ota [ap]");
} else
return;
}
bool webconfig_stopped = false;
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && !defined(WEBCONFIG_DISABLED)
if (_callbacks->isWebConfigActive()) {
strcpy(reply, "ERR: stop webconfig first");
} else
if (!_callbacks->stopWebConfigForOTA(reply)) {
if (!reply[0]) strcpy(reply, "ERR: could not stop WebConfig for OTA");
return;
}
webconfig_stopped = true;
}
#endif
reply[0] = 0;
if (!_board->startOTAUpdate(_prefs->node_name, reply, force_ap)) {
strcpy(reply, "Error");
if (!reply[0]) strcpy(reply, "Error");
}
#if defined(WITH_MQTT_BRIDGE) && defined(LIGHTWEIGHT_WIFI_OTA)
else {
@@ -2764,9 +2771,13 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
_callbacks->setBridgeState(false);
}
#endif
if (webconfig_stopped) {
const size_t used = strlen(reply);
snprintf(reply + used, 160 - used, "; WebConfig stopped");
}
} else if (memcmp(command, "stop ota", 8) == 0 && (command[8] == 0 || command[8] == ' ')) {
if (!_board->stopOTAUpdate(reply)) {
strcpy(reply, "Error");
if (!reply[0]) strcpy(reply, "Error");
}
#if defined(WITH_MQTT_BRIDGE) && defined(LIGHTWEIGHT_WIFI_OTA)
else if (_prefs->bridge_enabled) {
+4
View File
@@ -625,6 +625,10 @@ public:
(void)reply;
return false;
};
virtual bool stopWebConfigForOTA(char* reply) {
(void)reply;
return false;
};
virtual bool isWebConfigActive() const {
return false;
};
+27 -16
View File
@@ -1,6 +1,7 @@
#ifdef ESP_PLATFORM
#include "ESP32Board.h"
#include "WirelessControl.h"
#include <target.h>
#include "UsbLogging.h"
#include "FileRead.h"
@@ -68,8 +69,8 @@ bool ESP32Board::isUserGpioAvailable(uint8_t pin) const {
static bool lightweight_ota_started_ap;
// Full Companion keeps WebConfig on port 80 while an explicitly started
// updater uses 8080. Infrastructure retains its established /update URL.
// Full Companion retains its established uploader URL on port 8080.
// Infrastructure uses port 80; CLI startup hands WebConfig's WiFi to OTA.
#if defined(COMPANION_RADIO_FULL)
static constexpr uint16_t LIGHTWEIGHT_OTA_PORT = 8080;
#else
@@ -275,10 +276,15 @@ bool ESP32Board::startOTAUpdate(const char* id, char reply[], bool force_ap) {
return false;
}
#endif
if (!mesh::wireless::control().allowWiFiForOTA()) {
strcpy(reply, "ERR: wireless change pending; retry start ota");
return false;
}
inhibit_sleep = true;
IPAddress ip;
if (!force_ap && WiFi.status() == WL_CONNECTED) {
const bool use_ap = force_ap || WiFi.status() != WL_CONNECTED;
if (!use_ap) {
ip = WiFi.localIP();
} else {
if (!lightweight_ota_started_ap) {
@@ -288,7 +294,7 @@ bool ESP32Board::startOTAUpdate(const char* id, char reply[], bool force_ap) {
&& WiFi.softAP("MeshCore-OTA", nullptr);
}
if (!lightweight_ota_started_ap) {
inhibit_sleep = false;
inhibit_sleep = ota_server != nullptr;
strcpy(reply, "ERR: OTA WiFi failed");
return false;
}
@@ -306,11 +312,12 @@ bool ESP32Board::startOTAUpdate(const char* id, char reply[], bool force_ap) {
ota_server = &lightweight_ota_server;
}
const char* network = use_ap ? "Join WiFi MeshCore-OTA" : "Use same WiFi/LAN";
if (LIGHTWEIGHT_OTA_PORT == 80) {
snprintf(reply, 160, "Started: http://%s/update", ip.toString().c_str());
snprintf(reply, 160, "Started: http://%s/update - WiFi on; %s", ip.toString().c_str(), network);
} else {
snprintf(reply, 160, "Started: http://%s:%u/update", ip.toString().c_str(),
static_cast<unsigned>(LIGHTWEIGHT_OTA_PORT));
snprintf(reply, 160, "Started: http://%s:%u/update - WiFi on; %s", ip.toString().c_str(),
static_cast<unsigned>(LIGHTWEIGHT_OTA_PORT), network);
}
MESH_DEBUG_PRINTLN("startOTAUpdate: %s", reply);
return true;
@@ -341,13 +348,11 @@ bool ESP32Board::stopOTAUpdate(char reply[]) {
#include <SPIFFS.h>
bool ESP32Board::startOTAUpdate(const char* id, char reply[], bool force_ap) {
inhibit_sleep = true; // prevent sleep during OTA
if (ota_server != nullptr) { // already running (idempotent restart)
IPAddress cur_ip = (WiFi.status() == WL_CONNECTED) ? WiFi.localIP() : WiFi.softAPIP();
sprintf(reply, "Started: http://%s/update", cur_ip.toString().c_str());
return true;
if (!mesh::wireless::control().allowWiFiForOTA()) {
strcpy(reply, "ERR: wireless change pending; retry start ota");
return false;
}
inhibit_sleep = true; // prevent sleep during OTA
// If the device is already on a WiFi network (e.g. an observer joined in STA
// mode), serve ElegantOTA on the station IP so it's reachable from the LAN
@@ -356,23 +361,29 @@ bool ESP32Board::startOTAUpdate(const char* id, char reply[], bool force_ap) {
// reachable even when the joined network applies client isolation and the
// station IP can't be reached.
IPAddress ip;
if (!force_ap && WiFi.status() == WL_CONNECTED) {
const bool use_ap = force_ap || WiFi.status() != WL_CONNECTED;
if (!use_ap) {
ip = WiFi.localIP();
} else {
const IPAddress ap_ip(192, 168, 4, 1);
const IPAddress ap_mask(255, 255, 255, 0);
if (!WiFi.softAPConfig(ap_ip, ap_ip, ap_mask)
|| !WiFi.softAP("MeshCore-OTA", NULL)) {
inhibit_sleep = false;
inhibit_sleep = ota_server != nullptr;
strcpy(reply, "ERR: OTA WiFi failed");
return false;
}
ip = WiFi.softAPIP();
}
sprintf(reply, "Started: http://%s/update", ip.toString().c_str());
snprintf(reply, 160, "Started: http://%s/update - WiFi on; %s", ip.toString().c_str(),
use_ap ? "Join WiFi MeshCore-OTA" : "Use same WiFi/LAN");
MESH_DEBUG_PRINTLN("startOTAUpdate: %s", reply);
// Select the requested network even when the HTTP listener already exists.
// In particular, `start ota ap` must work after an earlier LAN-mode start.
if (ota_server != nullptr) return true;
static char id_buf[60];
sprintf(id_buf, "%s (%s)", id, getManufacturerName());
static char home_buf[90];
+11
View File
@@ -72,6 +72,17 @@ public:
blocked_.store(blocked_.load() & ~service);
return true;
}
// An explicit OTA start owns its WiFi startup, including after a user has
// disabled 2.4 GHz for this boot. Leave the other services disabled. Do not
// race a pending shutdown, which could otherwise turn OTA off afterwards.
bool allowWiFiForOTA() {
if (pending_) return false;
blocked_.store(blocked_.load() & ~WiFi);
master_off_ = false;
saved_valid_ = false;
error_ = nullptr;
return true;
}
uint8_t enabled() const { return backend_ ? backend_->enabled() : 0; }
bool handle(const char* text, char* reply, size_t size, uint32_t now, uint8_t requester) {
+33 -8
View File
@@ -245,12 +245,11 @@ static_assert(WC_BOARD_CMD_COUNT <= 8, "board command mask must fit uint8_t");
// POST so nothing in the sequence runs, rather than failing halfway with a
// reply that does not explain itself. Returns the reason, or NULL if fine.
static const char* wcCliUnavailable(const char* cmd, bool streamed = false) {
// ESP32Board::startOTAUpdate() does `new AsyncWebServer(80)` with no bind
// check and answers "Started" regardless. The portal already holds port 80,
// so from here it can only leak the allocation, inhibit sleep, and lie.
// OTA stops this portal, including the session carrying this command. It
// needs an independent reply route so the user receives the upload URL.
if (strncmp(cmd, "start ota", 9) == 0) {
return "start ota needs port 80, which this portal is using. "
"Run it from the serial console, or use `ota update`.";
return "start ota stops WebConfig. Run it from USB/Bluetooth or LoRa "
"to receive the upload URL, or use `ota update`.";
}
// `clock sync` sets the clock from the CALLER's timestamp. Web requests carry
// none (execCommand passes 0), so CommonCLI always rejects it as moving the
@@ -967,6 +966,31 @@ void WebConfigServer::requestStop() {
_stop_warned = false;
}
bool WebConfigServer::stopForOTA(char reply[]) {
if (!isRunning() && !isStopping()) return true;
// Keep a STA interface alive while removing our setup AP. Switching the
// last interface off and immediately creating the OTA AP races ESP32 netif
// teardown. A connected station keeps its address throughout the handoff.
if (_was_setup_ap && !WiFi.enableSTA(true)) {
strcpy(reply, "ERR: could not prepare WiFi for OTA");
return false;
}
_keep_wifi_on_stop = true;
requestStop(); // Detaches routes and releases port 80 synchronously.
if (_was_setup_ap) {
WiFi.softAPdisconnect(true);
// Arduino 2.x can return false even when enableAP(false) succeeded.
// Check the resulting mode instead of that return value.
if (WiFi.getMode() & WIFI_AP) {
strcpy(reply, "ERR: WebConfig stopped; WiFi AP handoff failed");
return false;
}
_was_setup_ap = false;
}
strcpy(reply, "WebConfig stopped");
return true;
}
void WebConfigServer::finalizeTeardown() {
closeTerminal();
// Async requests keep a pointer to their server until disconnect. Retain the
@@ -976,7 +1000,7 @@ void WebConfigServer::finalizeTeardown() {
delete _dns;
_dns = NULL;
const bool was_setup_ap = _was_setup_ap;
if (was_setup_ap) {
if (was_setup_ap && !_keep_wifi_on_stop) {
WiFi.softAPdisconnect(true);
// Nothing else owns WiFi when we raised the AP: either the node is
// unconfigured, or `start webconfig ap` required the bridge stopped.
@@ -985,11 +1009,12 @@ void WebConfigServer::finalizeTeardown() {
} else {
WiFi.mode(WIFI_STA);
}
_was_setup_ap = false;
}
if (_owns_wifi && !was_setup_ap) {
if (_owns_wifi && !was_setup_ap && !_keep_wifi_on_stop) {
stopOwnedWiFiRadio();
}
_was_setup_ap = false;
_keep_wifi_on_stop = false;
_initial_setup = false;
_setup_started_at = 0;
_stopping = false;
+4
View File
@@ -217,6 +217,9 @@ public:
bool startAutoMode(char reply[]); // use saved WiFi, or setup AP when absent
bool reloadStandaloneWiFi();
void requestStop(); // stop listening and detach this session
// Release HTTP/DNS for the updater without delayed teardown taking its
// WiFi down. Existing HTTP request objects still drain through tick().
bool stopForOTA(char reply[]);
void tick(uint32_t now); // call every loop iteration
Mode mode() const { return _mode; }
@@ -267,6 +270,7 @@ private:
SemaphoreHandle_t _mux;
Mode _mode = MODE_OFF;
bool _stopping = false;
bool _keep_wifi_on_stop = false;
bool _was_setup_ap = false;
bool _initial_setup = false;
uint32_t _setup_started_at = 0;