Suspend failed ESP32 MQTT and NTP uplinks for power saving

Share one bounded WiFi outage and recovery schedule across MQTT, automatic NTP, Companion station ownership and WebConfig. Preserve enabled settings and foreground access while allowing normal sleep after confirmed physical shutdown.

Honor failed SDK client stops before handing off WiFi, protect clean teardown and reconfiguration, and retry transient ESP-NOW channel restoration without repeated disconnects. Add production-method, SDK failure and real sleep regressions to CI.

Validation: native MQTT/NTP/clock/reconnect suites; production power and wrapper failure tests; browser, room HTTP, OTA and combined bridge regressions; Full Heltec V4 repeater, room and companion builds with capability, flash and linked-memory checks.
This commit is contained in:
mikecarper committed 2026-10-12 14:57:01 -07:00
1 parent f62cc7b527
commit 6b3f7df4d0
37 files changed
+3258 -82

No files matched your search

+10 -2
View File
@@ -7,6 +7,7 @@
#include "helpers/AlertFaultPolicy.h"
#include "helpers/MQTTConnectionPolicy.h"
#include "helpers/WiFiPowerSave.h"
#include "helpers/WiFiNetworkPowerPolicy.h"
#define MQTT_DEBUG_PRINTLN(...) ((void)0)
#define pdMS_TO_TICKS(value) (value)
using TickType_t=uint32_t;
@@ -69,6 +70,9 @@ namespace mesh{namespace wifi{
int s_wifi_disconnect_reason=0;uint32_t s_wifi_disconnect_time=0;
unsigned long s_wifi_connected_at=0;
struct MQTTBridge{
mesh::wifi::NetworkPowerPolicy _network_power_policy;
std::atomic<bool>_network_suspended{false};
bool _network_espnow_restore_pending=false;
bool _wifi_event_registered=false,_manage_wifi=true,_ntp_sync_pending=false;
int _wifi_reconnect_backoff_attempt=0;
std::atomic<bool>_ntp_synced{true},_stop_requested{false},_stop_acked{false};
@@ -78,13 +82,14 @@ struct MQTTBridge{
void setWifiOutage(AlertFaultPolicy::OutageSnapshot value){outage=value;}
char _wifi_ssid[8]="mesh",_wifi_password[8]="secret";
void beginWiFiStation();
void applyTimezoneRules() {}
bool _wifi_status_initialized=true;
int _last_wifi_status=WL_DISCONNECTED;
unsigned long _last_wifi_check=0,_last_wifi_reconnect_attempt=0;
uint8_t _wifi_power_save=1;
struct{bool canonical_wifi=true;}_node_info;
struct{uint8_t wifi_power_save=1;}prefs,*_obs=&prefs;
struct Client{void disconnect(){}};
struct Client{void disconnect(){}bool isStarted()const{return false;}};
struct Slot{Client* client=nullptr;bool connected=false;}_slots[RUNTIME_MQTT_SLOTS];
bool _slot_attempt_pending[RUNTIME_MQTT_SLOTS]={};
std::vector<std::string> cleanup;
@@ -96,8 +101,11 @@ struct MQTTBridge{
bool handleWiFiConnection(unsigned long now);
void mqttTaskLoop(){
@TASK_START@
while(true){
@TASK_STOP@
++slot_work;
++slot_work;
break;
}
}
};
@INITIALIZE@
+35 -2
View File
@@ -113,6 +113,7 @@ struct MQTTNodeInfo {
class MQTTBridge : public AbstractBridge {
bool running = false;
bool stopping = false;
bool network_suspended = false;
public:
inline static unsigned live = 0, fail_starts = 0;
unsigned begins = 0, ends = 0, loops = 0, sent = 0, received = 0;
@@ -127,12 +128,21 @@ public:
assert(filters); ++begins;
if (fail_starts) { --fail_starts; return; }
running = true;
network_suspended = false;
}
void end() override { ++ends; running = stopping = false; }
void end() override { ++ends; running = stopping = network_suspended = false; }
void requestStop() { stopping = running; }
bool isStopping() const { return stopping; }
bool isRunning() const override { return running; }
void loop() override { ++loops; if (stopping) { ++ends; running = stopping = false; } }
bool isNetworkSuspended() const { return network_suspended; }
void setNetworkSuspended(bool paused) {
assert(running && !stopping);
network_suspended = paused;
}
void loop() override {
++loops;
if (stopping) { ++ends; running = stopping = network_suspended = false; }
}
void sendPacket(mesh::Packet* p) override { if (allow(p)) ++sent; }
void onPacketReceived(mesh::Packet* p) { if (allow(p)) ++received; }
};
@@ -270,6 +280,29 @@ int main() {
expect_get(cli, "bridge.type", "> mqtt+rs232+espnow");
expect_get(cli, "rs232.enabled", "> off");
expect_get(cli, "rs232.running", "> off");
fresh.mqtt_bridge->setNetworkSuspended(true);
assert(fresh.isMqttBridgeRunning() && fresh._prefs.bridge_enabled);
assert(fresh.bridgesPreventSleep()); // ESP-NOW retains its radio owner.
assert(fresh.setEspNowBridgeState(false));
assert(!fresh.bridgesPreventSleep()); // Paused MQTT is still configured.
assert(fresh.setRs232BridgeState(true));
assert(fresh.bridgesPreventSleep()); // An active UART remains independent.
assert(fresh.setRs232BridgeState(false));
assert(!fresh.bridgesPreventSleep());
fresh.mqtt_bridge->setNetworkSuspended(false);
assert(fresh.bridgesPreventSleep()); // The recovery probe owns the radio.
char pause_reply[256] = {};
cli.set("espnow.enabled off", pause_reply);
assert(strcmp(pause_reply, "OK") == 0);
fresh.mqtt_bridge->setNetworkSuspended(true);
assert(fresh.requestMqttBridgeStop());
assert(fresh.isMqttBridgeStopping() && fresh.bridgesPreventSleep());
fresh.serviceBridges();
assert(!fresh.isMqttBridgeRunning() && !fresh.bridgesPreventSleep());
assert(fresh.setBridgeState(true));
assert(fresh.isMqttBridgeRunning() && fresh.bridgesPreventSleep());
cli.set("espnow.enabled on", pause_reply);
assert(strcmp(pause_reply, "OK") == 0 && fresh.isEspNowBridgeRunning());
}
MyMesh mesh; mesh.defaults(); mesh.boot(); CommonCLI cli(mesh);
char reply[256] = {};
+2
View File
@@ -337,6 +337,8 @@ struct WebConfigServer {
bool auth_allowed = true;
~WebConfigServer() { delete _dns; }
void createServer() { ++servers; }
void requestNetworkAccess() {}
void refreshNetworkPowerHold(uint32_t) {}
bool startSetupMode(char reply[]);
bool checkAuth(AsyncWebServerRequest*) const { return auth_allowed; }
void handleScan(AsyncWebServerRequest* req);
+13 -1
View File
@@ -5,11 +5,14 @@
#include <cstring>
#include <initializer_list>
#include <helpers/RoomWebMailbox.h>
#include <helpers/WiFiNetworkPowerPolicy.h>
static uint32_t millis() { return 123; }
struct WebConfigBatch {
static uint32_t scheduleAt(uint32_t now, uint32_t delay) { return now + delay; }
static bool deadlineReached(uint32_t now, uint32_t at) { return int32_t(now - at) >= 0; }
};
struct WCLock { explicit WCLock(void*) {} };
constexpr int WIFI_STA = 1;
constexpr int WIFI_AP = 2;
struct WiFiFake {
@@ -29,7 +32,7 @@ struct DNS { void stop() {} };
struct Callbacks { unsigned stops = 0; void onWebConfigStopped() { ++stops; } };
struct WebConfigServer {
enum Mode { MODE_OFF, MODE_LAN, MODE_SETUP };
enum { STOP_WARN_MS = 1000, BATCH_IDLE = 0, BATCH_CONFIG = 0 };
enum { STOP_WARN_MS = 1000, BATCH_IDLE = 0, BATCH_PENDING = 1, BATCH_CONFIG = 0 };
Server server;
Server* _server = &server;
DNS* _dns = nullptr;
@@ -46,11 +49,18 @@ struct WebConfigServer {
uint32_t _setup_reconnect_deadline = 0, _reboot_at = 0, _batch_state = 0;
uint32_t _batch_next = 0, _setup_wifi_handoff_deadline = 0, _batch_kind = 0;
uint32_t _board_cmds = 0;
uint32_t _network_activity_until = 0;
void* _mux = nullptr;
struct Terminal { bool running = false; struct { bool pending = false; } queue; };
Terminal* _terminal = nullptr;
char _wifi_ssid[32] = {}, _setup_wifi_handoff_ip[16] = {};
char _session_token[16] = {}, _stats_json[16] = {};
bool routes = true;
void detachRoutes() { routes = false; }
void closeTerminal() {}
uint32_t handlerRefCount() const { return 0; }
bool isNetworkForegroundActive(uint32_t) const;
void refreshNetworkPowerHold(uint32_t);
bool isRunning() const { return _mode != MODE_OFF; }
bool isStopping() const { return _stopping; }
void requestStop();
@@ -75,6 +85,7 @@ int main() {
assert(portal.stopForOTA(reply));
assert(strcmp(reply, "WebConfig stopped") == 0);
assert(!portal.routes && !portal.server.listening && portal.isStopping());
assert(mesh::wifi::networkPower().foregroundActive());
assert(WiFi.sta && !WiFi.ap && WiFi.stops == 0);
assert(WiFi.connected == !setup);
// OTA can now bind port 80 and create its own AP, while HTTP request
@@ -86,6 +97,7 @@ int main() {
assert(WiFi.ap && WiFi.sta && WiFi.stops == 0);
assert(WiFi.ap_stops == unsigned(setup));
assert(portal.callbacks.stops == 1 && !portal._keep_wifi_on_stop);
assert(!mesh::wifi::networkPower().foregroundActive());
}
}
WebConfigServer ordinary;
+5
View File
@@ -47,6 +47,8 @@ struct WebConfigServer {
uint32_t _last_activity=0, _session_last_seen=0, _login_lock_until=0;
int _login_fails=0; Callback callback; Callback* _cb=&callback;
WebConfigServer() { strcpy(callback.node.admin_password, "existing-secret"); }
unsigned network_activity = 0;
void noteNetworkActivity() { ++network_activity; }
bool checkAuth(AsyncWebServerRequest*);
void handleLogin(AsyncWebServerRequest*);
void handleLogout(AsyncWebServerRequest*);
@@ -58,12 +60,15 @@ int main() {
attacker.body="{\"set\":{\"password\":\"attacker\",\"wifi.ssid\":\"EvilNet\"}}";
attacker._tempObject=attacker.body.data();
assert(!portal.checkAuth(&attacker));
assert(portal.network_activity==0);
portal.checkConfigPost(&attacker);
assert(attacker.status==401 && !portal.config_accepted);
attacker.password("wrong"); portal.handleLogin(&attacker);
assert(attacker.status==401 && portal._session_token[0]==0);
assert(portal.network_activity==0);
AsyncWebServerRequest admin; admin.password("existing-secret");
portal.handleLogin(&admin); assert(admin.status==200);
assert(portal.network_activity>0);
assert(strlen(portal._session_token)==32);
assert(admin.response.headers["Set-Cookie"].find("HttpOnly; SameSite=Lax")!=std::string::npos);
admin.header.cookies=std::string("wcs=")+portal._session_token;
+1
View File
@@ -23,6 +23,7 @@ struct WebConfigServer {
bool isRunning() const { return false; }
bool isStopping() const { return false; }
void updateWiFiOwnership(bool owner) { owns = owner; }
void requestNetworkAccess() {}
bool startAutoMode(char* reply) { strcpy(reply, "starting"); return true; }
bool startSetupMode(char* reply) { strcpy(reply, "setup"); return true; }
};
+30
View File
@@ -6,6 +6,7 @@
#include <string>
#include <helpers/RoomWebMailbox.h>
#include <helpers/WiFiReconnectPolicy.h>
#include <helpers/WiFiNetworkPowerPolicy.h>
static uint32_t clock_ms = 1000;
uint32_t millis() { return clock_ms; }
void delay(unsigned) {}
@@ -96,6 +97,7 @@ public:
bool _stopping = false, _retry_saved_wifi_in_setup = false;
bool _setup_reconnect_in_progress = false, _board_cmds_probed = false;
bool _was_setup_ap = false, _initial_setup = false;
bool foreground = false;
uint32_t _setup_reconnect_deadline = 0, _connect_deadline = 0;
uint32_t _setup_started_at = 0, _last_activity = 0;
WiFiReconnectPolicy::Tracker _wifi_reconnect_tracker;
@@ -134,6 +136,7 @@ public:
void probeBoardCommands() { _board_cmds_probed = true; }
void serviceTerminal(uint32_t) {}
void serviceRoom(uint32_t) {}
bool isNetworkForegroundActive(uint32_t) const { return foreground || _mode == MODE_SETUP; }
bool bluetoothWiFiCoexistenceRequired() { return false; }
bool acceptWiFi(Entry& e, const char* value) {
@CREDENTIAL_BATCH@
@@ -197,6 +200,33 @@ int main() {
companion.tick(16000);
assert(companion.setup_starts == 1 && companion._retry_saved_wifi_in_setup);
assert(!companion._runtime_wifi_ownership_managed);
#elif defined(TEST_BACKGROUND_SUSPEND)
auto& power = mesh::wifi::networkPower();
power.setManaged(true); power.setSuspended(true);
portal._mode = WebConfigServer::MODE_LAN;
clock_ms = 301000;
portal.tick(clock_ms);
assert(WiFi.begins == 0 && portal.setup_starts == 0);
// A connecting listener must not reopen an AP or acquire STA while the
// background owner has deliberately stopped MQTT and NTP for the cooldown.
portal._mode = WebConfigServer::MODE_CONNECTING;
portal._connect_deadline = 16000;
portal.tick(clock_ms);
assert(WiFi.begins == 0 && portal.setup_starts == 0);
portal._connect_deadline = 0;
portal.foreground = true;
portal.tick(++clock_ms);
assert(WiFi.begins == 1 && portal._connect_deadline == clock_ms + 15000);
portal.foreground = false;
clock_ms += 16000;
portal.tick(clock_ms);
assert(portal.setup_starts == 0 && WiFi.begins == 1);
// Resuming the worker permits ordinary ownership/reconnect logic again.
power.setSuspended(false);
portal._mode = WebConfigServer::MODE_LAN;
clock_ms += 301000;
portal.tick(clock_ms);
assert(WiFi.begins == 2);
#elif defined(TEST_EXTERNAL_OWNER)
portal.updateWiFiOwnership(false);
assert(portal._runtime_wifi_ownership_managed);