Recover stalled MQTT transports and broker acknowledgments

This commit is contained in:
mikecarper committed 2026-10-14 10:34:40 -07:00
1 parent 8a49a98709
commit 3347a62780
17 files changed
+1201 -23

No files matched your search

+1
View File
@@ -167,6 +167,7 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_topic_template` | `src/helpers/MQTTTopicTemplate.h` | `{iata}/{device}/{token}/{type}` expansion, overflow/NUL-termination, and a buffer-size fuzz |
| `test_mqtt_topic_router` | `src/helpers/MQTTTopicRouter.h` | complete preset/custom topic-routing contract; MeshRank all types except raw; required identifiers; invalid inputs/slots; exact buffer boundaries |
| `test_mqtt_connection_policy` | `src/helpers/MQTTConnectionPolicy.h` | reconnect guard/backoff/stagger and breaker transitions; stable reset; JWT lifetime/renewal policy; exact timing boundaries and 32-bit `millis()` rollover |
| `test_mqtt_transport_health.py`, `test_mqtt_handshake_scheduler.py` | `src/helpers/MQTTTransportHealth.h`, production `MQTTBridge` methods | oldest outstanding QoS 1 acknowledgment deadline; quiet-session safety; lost/error-only callbacks; serialized stop-before-reconnect recovery; multi-hour scheduling and timer rollover |
| `test_wifi_reconnect_policy` | `src/helpers/WiFiReconnectPolicy.h` | five-minute forced reconnect cadence, connection resets, duplicate disconnect observations, and 32-bit `millis()` rollover |
| `test_radio_liveness` | `src/helpers/RadioLivenessTracker.h`, `src/helpers/radiolib/RxBoostedGainDefaults.h` | staged radio recovery, activity reset and rollover handling; target-specific RX boosted-gain defaults and SX126x precedence |
| `test_lr1110_rx_recovery` | `src/helpers/radiolib/LR1110RxRecovery.h` | LR1110 four-byte RX-buffer shift signature; captured and accumulated shifts; ordinary/scoped packet exclusions |
+10 -1
View File
@@ -6,6 +6,7 @@
#include <vector>
#include "helpers/AlertFaultPolicy.h"
#include "helpers/MQTTConnectionPolicy.h"
#include "helpers/MQTTTransportHealth.h"
#include "helpers/WiFiPowerSave.h"
#include "helpers/WiFiNetworkPowerPolicy.h"
#define MQTT_DEBUG_PRINTLN(...) ((void)0)
@@ -90,8 +91,16 @@ struct MQTTBridge{
struct{bool canonical_wifi=true;}_node_info;
struct{uint8_t wifi_power_save=1;}prefs,*_obs=&prefs;
struct Client{void disconnect(){}bool isStarted()const{return false;}};
struct Slot{Client* client=nullptr;bool connected=false;}_slots[RUNTIME_MQTT_SLOTS];
struct Slot{
Client* client=nullptr;bool connected=false;
uint32_t connected_at_ms=0,current_outage_started_ms=0;
MQTTTransportHealth::State transport_health;
}_slots[RUNTIME_MQTT_SLOTS];
bool _slot_attempt_pending[RUNTIME_MQTT_SLOTS]={};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS]={};
std::atomic<bool> _slot_health_reset_pending[RUNTIME_MQTT_SLOTS]={};
void updateSlotTransportDiag(int,uint32_t){}
void updateCachedConnectionStatus(){}
std::vector<std::string> cleanup;
void cancelNtpRefresh(){cleanup.push_back("ntp");}
void teardownSlot(int index){cleanup.push_back("slot"+std::to_string(index));}
+3
View File
@@ -15,6 +15,7 @@ POLICY_PREAMBLE = r'''
#include <cstddef>
#include <cstdint>
#include "helpers/MQTTConnectionAdmission.h"
#include "helpers/MQTTTransportHealth.h"
namespace Admission = MQTTConnectionAdmission;
using MemoryState = Admission::ClientMemoryState;
'''
@@ -65,8 +66,10 @@ struct MQTTBridge {
const Preset* preset = nullptr;
char broker_uri[128] = {}, host[64] = "broker";
uint16_t port = 8883;
MQTTTransportHealth::State transport_health;
} _slots[RUNTIME_MQTT_SLOTS];
std::atomic<bool> _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
bool hasPendingSlotConnection() const;
bool canStartSlotConnection(int index) const;
};
+6
View File
@@ -27,6 +27,7 @@ HARNESS = r'''
#include <functional>
#include <helpers/WiFiNetworkPowerPolicy.h>
#include <helpers/MQTTConnectionPolicy.h>
#include <helpers/MQTTTransportHealth.h>
#define private public
#include "PsychicMqttClient.h"
#undef private
@@ -100,6 +101,7 @@ struct MQTTBridge {
PsychicMqttClient* client = nullptr;
bool enabled = true, connected = false, circuit_breaker_tripped = false;
uint32_t connected_at_ms = 0, last_reconnect_attempt = 0;
uint32_t current_outage_started_ms = 0;
uint8_t reconnect_backoff = 0;
bool initial_connect_done = true;
char* auth_token = nullptr;
@@ -107,11 +109,14 @@ struct MQTTBridge {
uint32_t token_expires_at = 1, last_token_renewal = 1;
uint32_t last_log_time = 1, last_deferred_log_ms = 1;
uint8_t max_backoff_failures = 0;
MQTTTransportHealth::State transport_health;
} _slots[RUNTIME_MQTT_SLOTS];
using MQTTSlot = Slot;
mesh::wifi::NetworkPowerPolicy _network_power_policy;
std::atomic<bool> _network_suspended{false}, _fresh_ntp_this_boot{false};
bool _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_reset_pending[RUNTIME_MQTT_SLOTS] = {};
bool _status_publish_pending[RUNTIME_MQTT_SLOTS] = {};
bool _slot_force_jwt_mint[RUNTIME_MQTT_SLOTS] = {};
uint32_t _network_publish_acks[RUNTIME_MQTT_SLOTS] = {};
@@ -127,6 +132,7 @@ struct MQTTBridge {
Board* _board = nullptr;
void cancelNtpRefresh() {}
void updateCachedConnectionStatus() {}
void updateSlotTransportDiag(int, uint32_t) {}
void initializeWiFiInTask() {}
void processPacketQueue() { ++queues; }
void teardownSlot(int index, bool force = false);
+499 -7
View File
@@ -21,11 +21,14 @@ PREAMBLE = r'''
#include <cstdio>
#include <cstring>
#include <functional>
#include <new>
#include <sys/time.h>
#include <vector>
#include "helpers/AlertFaultPolicy.h"
#include "helpers/MQTTConnectionAdmission.h"
#include "helpers/MQTTConnectionHealth.h"
#include "helpers/MQTTConnectionPolicy.h"
#include "helpers/MQTTTransportHealth.h"
#include "helpers/WiFiPowerSave.h"
#define ESP_PLATFORM 1
#define MQTT_DEBUG_PRINTLN(...) ((void)0)
@@ -43,6 +46,11 @@ bool enforceStationChannel() { return true; }
bool mqttStationWiFiMutationAllowed() { return true; }
void esp_wifi_set_ps(wifi_ps_type_t) {}
constexpr int MQTT_AUTH_JWT = 1;
constexpr int MQTT_ERROR_TYPE_CONNECTION_REFUSED = 5;
struct esp_mqtt_error_codes {
int esp_tls_last_esp_err = 0, esp_tls_stack_err = 0;
int esp_transport_sock_errno = 0, error_type = 0, connect_return_code = 0;
};
constexpr uint32_t MALLOC_CAP_INTERNAL = 1, MALLOC_CAP_DMA = 2;
static uint32_t clock_ms = 1000;
static unsigned long wall_seconds = 1800000000;
@@ -59,7 +67,8 @@ struct {
} WiFi;
struct { size_t size = 2097152; size_t getPsramSize() const { return size; } } ESP;
size_t heap_caps_get_free_size(uint32_t caps) {
assert(caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)); return dma_free;
assert(caps == MALLOC_CAP_INTERNAL || caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA));
return dma_free;
}
size_t heap_caps_get_largest_free_block(uint32_t caps) {
assert(caps == (MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)); return dma_largest;
@@ -70,17 +79,61 @@ struct Preset {
int auth_type = 0;
unsigned long token_lifetime = 3300;
bool enforce_exp = false;
bool allow_retain = false;
};
bool mqttPresetEnforcesTokenExp(const Preset* preset) {
return preset && preset->enforce_exp;
}
namespace MQTTMessageBuilder {
void formatIsoTimestampForMqtt(long, long, const char*, char* buffer, size_t size) {
snprintf(buffer, size, "2026-10-14T00:00:00+00:00");
}
template<typename... Args>
int buildStatusMessage(int, const char*, const char*, const char*, const char*,
const char*, const char*, const char*, const char*,
char* buffer, int size, Args...) {
assert(size > 2);
strcpy(buffer, "{}");
return 2;
}
}
void formatRadioInfo(float, float, int, int, char* buffer, size_t size) {
snprintf(buffer, size, "909.5,500,5,5");
}
struct PsychicMqttClient {
bool initialized = false, started = false, live = false, model_task_heap = false;
bool stop_succeeds = true;
int starts = 0, reconnects = 0, bounces = 0, credentials = 0, stops = 0;
uint32_t acknowledgments = 0;
int publish_result = 0, publishes = 0;
bool immediate_ack = false;
std::function<void(bool)> connected_callback, disconnected_callback;
std::function<void(esp_mqtt_error_codes)> error_callback;
std::function<void()> disconnected;
bool isInitialized() const { return initialized; }
bool isStarted() const { return started; }
bool connected() const { return live; }
uint32_t getPublishAck() const { return acknowledgments; }
void setAutoReconnect(bool enabled) { assert(!enabled); }
void onConnect(std::function<void(bool)> callback) { connected_callback = callback; }
void onDisconnect(std::function<void(bool)> callback) { disconnected_callback = callback; }
void onError(std::function<void(esp_mqtt_error_codes)> callback) { error_callback = callback; }
void errorWithoutDisconnect() {
live = false; // The real adapter does this before calling onError.
assert(error_callback);
error_callback(esp_mqtt_error_codes{});
}
void connectEvent() {
live = true;
assert(connected_callback);
connected_callback(false);
}
int publish(const char*, int qos, bool, const char*, int, bool async) {
assert(async == (qos > 0));
++publishes;
if (immediate_ack && qos > 0 && publish_result >= 0) ++acknowledgments;
return publish_result;
}
int connect() {
++starts;
if (model_task_heap) {
@@ -93,9 +146,11 @@ struct PsychicMqttClient {
int reconnect() { ++reconnects; return ESP_OK; }
void disconnect() {
++stops;
if (!stop_succeeds) return;
if (model_task_heap && started) dma_free += 6536;
started = live = false;
if (disconnected) disconnected();
if (disconnected_callback) disconnected_callback(false);
}
void softDisconnect() {
++bounces; live = false;
@@ -117,12 +172,26 @@ struct MQTTBridge {
uint8_t reconnect_backoff = 0, max_backoff_failures = 0;
bool circuit_breaker_tripped = false;
uint32_t start_failures = 0;
uint32_t connect_failures = 0, disconnect_count = 0;
unsigned long first_disconnect_time = 0, current_outage_started_ms = 0;
unsigned long last_log_time = 0;
int32_t last_tls_err = 0, last_tls_stack_err = 0;
int last_sock_errno = 0;
unsigned long last_error_time = 0;
MQTTTransportHealth::State transport_health;
} _slots[RUNTIME_MQTT_SLOTS];
PsychicMqttClient clients[RUNTIME_MQTT_SLOTS];
char tokens[RUNTIME_MQTT_SLOTS][16] = {};
bool setup_succeeds[RUNTIME_MQTT_SLOTS] = {true, true, true, true, true, true};
bool ready[RUNTIME_MQTT_SLOTS] = {true, true, true, true, true, true};
std::atomic<bool> _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_reset_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint32_t> _slot_health_recoveries[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint8_t> _slot_health_reason[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_recovering[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint32_t> _slot_health_ack_wait_secs[RUNTIME_MQTT_SLOTS] = {};
bool _status_publish_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _stop_requested{false}, _ntp_synced{true};
bool _slot_force_jwt_mint[RUNTIME_MQTT_SLOTS] = {};
void* _identity = this;
@@ -131,7 +200,11 @@ struct MQTTBridge {
wl_status_t _last_wifi_status = WL_CONNECTED;
unsigned long _last_wifi_check = 0, _last_wifi_reconnect_attempt = 0;
uint8_t _wifi_reconnect_backoff_attempt = 0, _wifi_power_save = 1;
struct { bool canonical_wifi = false; } _node_info;
struct {
bool canonical_wifi = false;
float *freq = nullptr, *bw = nullptr;
int *sf = nullptr, *cr = nullptr;
} _node_info;
struct Observer { uint8_t wifi_power_save = 1; } observer;
Observer* _obs = &observer;
AlertFaultPolicy::OutageSnapshot _wifi_outage{};
@@ -142,6 +215,39 @@ struct MQTTBridge {
void beginWiFiStation() {}
const char* _jwt_username = "jwt";
static const unsigned long SLOT_SETUP_RETRY_INTERVAL = 60000;
static const unsigned long SLOT_LOG_INTERVAL = 60000;
static constexpr int STATUS_JSON_BUFFER_SIZE = 1024, MSG_STATUS = 0;
const char *_timezone = "UTC", *_origin = "node", *_device_id = "id";
const char *_board_model = "V4", *_firmware_version = "test";
int _json_scratch_doc = 0, _queue_count = 0;
char _json_scratch_buffer[STATUS_JSON_BUFFER_SIZE] = {};
struct Board { int getBattMilliVolts() const { return 4000; } };
struct Clock { uint32_t getMillis() const { return clock_ms; } };
struct Dispatcher {
int getErrFlags() const { return 0; }
int getTotalAirTime() const { return 0; }
int getReceiveAirTime() const { return 0; }
int getNumSentFlood() const { return 0; }
int getNumSentDirect() const { return 0; }
int getNumRecvFlood() const { return 0; }
int getNumRecvDirect() const { return 0; }
};
struct Radio {
int getNoiseFloor() const { return -120; }
int getPacketsRecvErrors() const { return 0; }
};
Board* _board = nullptr;
Clock* _ms = nullptr;
Dispatcher* _dispatcher = nullptr;
Radio* _radio = nullptr;
void refreshOriginFromPrefs() {}
void getClientVersion(char* output, size_t size) { snprintf(output, size, "test"); }
int repeatStatus() const { return 0; }
int collectConnHealth() const { return 0; }
bool buildTopicForSlot(int, int, char* output, size_t size) {
snprintf(output, size, "status");
return true;
}
std::vector<int> setups;
bool isSlotReady(int index) { return ready[index]; }
bool setupSlot(int index) {
@@ -162,7 +268,14 @@ struct MQTTBridge {
void complete(int index) {
_slot_attempt_pending[index].store(false, std::memory_order_release);
_slots[index].connected = clients[index].live = true;
if (_slots[index].client) _slots[index].client->live = true;
_slots[index].connected_at_ms = clock_ms;
_slot_health_reset_pending[index] = true;
}
void updateCachedConnectionStatus() {}
bool ensureSlotClient(int index);
bool publishToSlot(int, const char*, const char*, size_t, bool, uint8_t);
void publishStatusToSlot(int);
void only(int index) {
for (int i = 0; i < RUNTIME_MQTT_SLOTS; ++i) _slots[i].enabled = i == index;
}
@@ -173,6 +286,9 @@ struct MQTTBridge {
esp_err_t reconnectSlotClient(int index);
unsigned long slotTokenLifetime(int index) const;
void maintainSlotConnections();
bool recoverSlotTransport(int index, uint32_t now);
void serviceSlotTransportHealth(uint32_t now);
void updateSlotTransportDiag(int index, uint32_t now);
bool handleWiFiConnection(unsigned long);
void maintainSlotConnection(int, unsigned long, unsigned long, bool, bool&, bool&);
};
@@ -188,25 +304,36 @@ class MqttHandshakeSchedulerTest(unittest.TestCase):
"bool MQTTBridge::hasPendingSlotConnection() const",
"bool MQTTBridge::canStartSlotConnection(int index) const",
"esp_err_t MQTTBridge::reconnectSlotClient(int index)",
"bool MQTTBridge::recoverSlotTransport(",
"void MQTTBridge::serviceSlotTransportHealth(",
"void MQTTBridge::updateSlotTransportDiag(",
"bool MQTTBridge::ensureSlotClient(",
"bool MQTTBridge::publishToSlot(",
"void MQTTBridge::publishStatusToSlot(",
"unsigned long MQTTBridge::slotTokenLifetime(int index) const",
"bool MQTTBridge::handleWiFiConnection(unsigned long now)",
"void MQTTBridge::maintainSlotConnections()",
"void MQTTBridge::maintainSlotConnection("))
def compile_run(self, main):
def compile_run(self, main, fixture=None, expect_rejection=False):
compiler = shutil.which("g++") or shutil.which("clang++")
self.assertIsNotNone(compiler, "a host C++ compiler is required")
with tempfile.TemporaryDirectory(prefix="meshcore-mqtt-scheduler-") as temporary:
work = Path(temporary)
source, binary = work / "scheduler.cpp", work / "scheduler"
source.write_text(self.fixture() + main, encoding="utf-8")
source.write_text((self.fixture() if fixture is None else fixture) + main,
encoding="utf-8")
result = subprocess.run(
[compiler, "-std=c++17", "-Wall", "-Wextra", "-I", str(ROOT / "src"),
str(source), "-o", str(binary)], capture_output=True, text=True, timeout=60)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], cwd=work, capture_output=True,
text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if expect_rejection:
self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("Assertion", result.stderr)
else:
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_first_start_is_immediate_and_delayed_callback_serializes_following_slots(self):
self.compile_run(r'''
@@ -220,7 +347,7 @@ int main() {
// still pending. Ordinary maintenance must not launch another SDK request.
clock_ms = 16000;
bridge.maintainSlotConnections();
clock_ms = 3600000;
clock_ms = 60000;
bridge.maintainSlotConnections();
assert(bridge.setups == std::vector<int>{0});
assert(bridge.clients[0].starts == 1 && bridge.clients[0].reconnects == 0);
@@ -419,7 +546,7 @@ int main() {
bridge.maintainSlotConnections();
assert(bridge.clients[0].starts == 1 && dma_free == 35840);
assert(bridge.hasPendingSlotConnection());
clock_ms += 3600000;
clock_ms += 60000;
bridge.maintainSlotConnections();
assert(bridge.clients[1].starts == 0 && bridge.clients[2].starts == 0);
bridge.complete(0);
@@ -450,6 +577,371 @@ int main() {
}
''')
def test_missing_handshake_callback_times_out_only_after_sdk_stop(self):
self.compile_run(r'''
int main() {
MQTTBridge bridge;
bridge.only(0);
clock_ms = 1000;
bridge.maintainSlotConnections();
assert(bridge.clients[0].starts == 1 && bridge._slot_attempt_pending[0]);
clock_ms = 120999;
bridge.maintainSlotConnections();
assert(bridge.clients[0].stops == 0 && bridge._slot_attempt_pending[0]);
clock_ms = 121000;
bridge.maintainSlotConnections();
auto& slot = bridge._slots[0];
assert(bridge.clients[0].stops == 1 && !bridge.clients[0].isStarted());
assert(!bridge._slot_attempt_pending[0] && !bridge.hasPendingSlotConnection());
assert(slot.transport_health.recoveries == 1 && slot.connect_failures == 1);
assert(slot.transport_health.last_recovery_reason ==
MQTTTransportHealth::RecoveryReason::HandshakeTimeout);
assert(slot.last_reconnect_attempt == clock_ms);
// Cleanup doesn't start another SDK task in the same maintenance pass.
assert(bridge.clients[0].starts == 1);
clock_ms += 14999;
bridge.maintainSlotConnections();
assert(bridge.clients[0].starts == 1);
++clock_ms;
bridge.maintainSlotConnections();
assert(bridge.clients[0].starts == 2 && bridge._slot_attempt_pending[0]);
assert(slot.reconnect_backoff == 1);
}
''')
def test_error_callback_without_disconnect_defers_cleanup_and_preserves_reservation(self):
self.compile_run(r'''
int main() {
for (bool established : {false, true}) {
MQTTBridge bridge;
bridge.only(0);
clock_ms = 1000;
assert(bridge.ensureSlotClient(0));
auto& slot = bridge._slots[0];
slot.initial_connect_done = true;
auto* client = slot.client;
assert(bridge.reconnectSlotClient(0) == ESP_OK);
if (established) client->connectEvent();
client->errorWithoutDisconnect();
// The actual production callback latches work. It cannot stop its own
// esp-mqtt task or release a still-running handshake from that callback.
assert(client->stops == 0 && client->isStarted());
assert(bridge._slot_transport_fault_pending[0]);
assert(bridge.hasPendingSlotConnection() && !bridge.canStartSlotConnection(1));
client->stop_succeeds = false;
bridge.maintainSlotConnections();
assert(client->stops == 1 && client->isStarted());
assert(bridge._slot_transport_fault_pending[0]);
assert(bridge._slot_attempt_pending[0] == !established);
assert(bridge.hasPendingSlotConnection() && !bridge.canStartSlotConnection(1));
assert(slot.transport_health.recoveries == 0 && client->starts == 1);
// A later successful stop proves ownership ended, then recovery may admit
// another handshake. Failure accounting remains exactly once.
client->stop_succeeds = true;
bridge.maintainSlotConnections();
assert(client->stops == 2 && !client->isStarted());
assert(!bridge.hasPendingSlotConnection() && !bridge._slot_transport_fault_pending[0]);
assert(slot.transport_health.recoveries == 1);
assert(slot.connect_failures == (established ? 0u : 1u));
assert(slot.transport_health.last_recovery_reason ==
MQTTTransportHealth::RecoveryReason::TransportError);
assert(client->starts == 1); // completed cleanup starts the 15-second gap
delete client;
slot.client = nullptr;
}
}
''')
def test_failed_stop_after_lost_callback_blocks_every_new_handshake(self):
self.compile_run(r'''
int main() {
MQTTBridge bridge;
clock_ms = 1000;
bridge.maintainSlotConnections();
bridge.clients[0].stop_succeeds = false;
clock_ms += MQTTTransportHealth::kAttemptTimeoutMs;
for (int pass = 0; pass < 3; ++pass) {
bridge.maintainSlotConnections();
assert(bridge.clients[0].stops == pass + 1 && bridge.clients[0].isStarted());
assert(bridge._slot_attempt_pending[0] && bridge.hasPendingSlotConnection());
assert(bridge._slots[0].transport_health.recoveries == 0);
assert(bridge.setups == std::vector<int>{0});
for (int i = 0; i < RUNTIME_MQTT_SLOTS; ++i)
assert(!bridge.canStartSlotConnection(i));
clock_ms += 15000;
}
bridge.clients[0].stop_succeeds = true;
bridge.maintainSlotConnections();
assert(!bridge.clients[0].isStarted() && !bridge.hasPendingSlotConnection());
assert(bridge._slots[0].transport_health.recoveries == 1);
assert(bridge.setups == std::vector<int>{0});
}
''')
def test_three_brokers_run_beyond_three_hours_and_only_missing_ack_recovers(self):
self.compile_run(r'''
int main() {
MQTTBridge bridge;
clock_ms = 1000;
for (int i = 0; i < RUNTIME_MQTT_SLOTS; ++i) {
bridge._slots[i].enabled = i < 3;
if (i >= 3) continue;
auto& slot = bridge._slots[i];
slot.client = &bridge.clients[i];
slot.initial_connect_done = true;
slot.client->initialized = slot.client->started = true;
bridge.complete(i);
slot.client->immediate_ack = true;
}
// Two status publishers get real ACK-counter progress; the third is quiet
// (for example, its broker does not accept status topics). Neither condition
// is a transport stall, irrespective of connection age or packet activity.
for (int minute = 0; minute <= 180; ++minute) {
assert(bridge.publishToSlot(0, "status", "{}", 2, true, 1));
assert(bridge.publishToSlot(1, "status", "{}", 2, true, 1));
bridge.maintainSlotConnections();
for (int i = 0; i < 3; ++i) assert(bridge.clients[i].stops == 0);
clock_ms += 60000;
wall_seconds += 60;
}
assert(clock_ms > 3 * 60 * 60 * 1000);
bridge.clients[0].immediate_ack = false;
const uint32_t stalled_at = clock_ms;
assert(bridge.publishToSlot(0, "status", "{}", 2, true, 1));
for (uint32_t elapsed = 0; elapsed < 120000; elapsed += 30000) {
clock_ms = stalled_at + elapsed;
assert(bridge.publishToSlot(0, "status", "{}", 2, true, 1));
assert(bridge.publishToSlot(1, "status", "{}", 2, true, 1));
bridge.maintainSlotConnections();
assert(bridge.clients[0].stops == 0);
assert(bridge._slots[0].transport_health.ack_started_ms == stalled_at);
}
clock_ms = stalled_at + 120000;
bridge.maintainSlotConnections();
assert(bridge.clients[0].stops == 1 && !bridge._slots[0].connected);
assert(bridge._slots[0].transport_health.recoveries == 1);
assert(bridge._slots[0].transport_health.last_recovery_reason ==
MQTTTransportHealth::RecoveryReason::AckTimeout);
for (int i = 1; i < 3; ++i) {
assert(bridge.clients[i].stops == 0 && bridge._slots[i].connected);
assert(bridge._slots[i].transport_health.recoveries == 0);
}
assert(bridge._slot_health_recoveries[0] == 1);
assert(!bridge._slot_health_recovering[0]);
}
''')
def test_on_connect_status_watch_survives_maintenance_and_ack_clears_it(self):
self.compile_run(r'''
int main() {
MQTTBridge bridge;
bridge.only(0); clock_ms = 1000;
assert(bridge.ensureSlotClient(0));
auto& slot = bridge._slots[0];
slot.initial_connect_done = true;
assert(bridge.reconnectSlotClient(0) == ESP_OK);
slot.client->connectEvent();
assert(bridge._slot_health_reset_pending[0] && bridge._status_publish_pending[0]);
// The real worker consumes an on-connect status before it calls maintenance.
bridge.publishStatusToSlot(0);
assert(slot.client->publishes == 1);
assert(!bridge._slot_health_reset_pending[0] && slot.transport_health.ack_pending);
bridge.maintainSlotConnections();
assert(slot.transport_health.ack_pending);
clock_ms += 119999;
++slot.client->acknowledgments;
bridge.maintainSlotConnections();
assert(!slot.transport_health.ack_pending && slot.client->stops == 0);
assert(bridge._slot_health_ack_wait_secs[0] == UINT32_MAX);
slot.client->immediate_ack = true;
assert(bridge.publishToSlot(0, "status", "{}", 2, true, 1));
assert(!slot.transport_health.ack_pending); // ACK arrived inside enqueue
clock_ms += 3600000;
bridge.maintainSlotConnections();
assert(slot.client->stops == 0);
delete slot.client;
slot.client = nullptr;
}
''')
def test_negative_qos0_write_without_disconnect_requests_owner_recovery(self):
self.compile_run(r'''
int main() {
MQTTBridge bridge;
bridge.only(0); clock_ms = 1000;
auto& slot = bridge._slots[0];
slot.client = &bridge.clients[0];
slot.client->initialized = slot.client->started = true;
slot.initial_connect_done = true;
bridge.complete(0);
slot.client->publish_result = -1;
assert(!bridge.publishToSlot(0, "packets", "{}", 2, false, 0));
assert(slot.client->stops == 0 && slot.connected && slot.client->connected());
assert(slot.transport_health.recovery_reason ==
MQTTTransportHealth::RecoveryReason::PublishFailure);
assert(bridge.hasPendingSlotConnection());
assert(!bridge.publishToSlot(0, "packets", "{}", 2, false, 0));
assert(slot.client->publishes == 1); // don't repeatedly hit the broken socket
bridge.maintainSlotConnections();
assert(slot.client->stops == 1 && !slot.connected && !slot.client->isStarted());
assert(slot.transport_health.recoveries == 1);
assert(slot.transport_health.last_recovery_reason ==
MQTTTransportHealth::RecoveryReason::PublishFailure);
}
''')
def test_handshake_and_ack_recovery_are_millis_wrap_safe(self):
self.compile_run(r'''
int main() {
for (bool awaiting_ack : {false, true}) {
MQTTBridge bridge;
bridge.only(0); clock_ms = UINT32_MAX - 60000;
bridge.maintainSlotConnections();
auto& slot = bridge._slots[0];
if (awaiting_ack) {
bridge.complete(0);
assert(bridge.publishToSlot(0, "status", "{}", 2, true, 1));
}
clock_ms += 119999;
bridge.maintainSlotConnections();
assert(slot.client->stops == 0);
++clock_ms;
bridge.maintainSlotConnections();
assert(slot.client->stops == 1 && slot.transport_health.recoveries == 1);
assert(slot.transport_health.last_recovery_reason == (awaiting_ack
? MQTTTransportHealth::RecoveryReason::AckTimeout
: MQTTTransportHealth::RecoveryReason::HandshakeTimeout));
}
}
''')
def test_recovery_preserves_backoff_and_restart_memory_admission(self):
self.compile_run(r'''
int main() {
MQTTBridge bridge;
bridge.only(0); clock_ms = 70000;
auto& slot = bridge._slots[0];
slot.client = &bridge.clients[0];
slot.client->initialized = slot.client->started = true;
slot.initial_connect_done = true;
bridge.complete(0);
slot.reconnect_backoff = 3;
slot.max_backoff_failures = 1;
bridge._slot_transport_fault_pending[0] = true;
bridge.maintainSlotConnections();
assert(slot.client->stops == 1 && slot.reconnect_backoff == 3);
assert(slot.max_backoff_failures == 1 && slot.connect_failures == 0);
clock_ms += 120000;
dma_free = 24575; dma_largest = 20000;
bridge.maintainSlotConnections();
assert(slot.client->starts == 0 && slot.reconnect_backoff == 3);
assert(slot.last_reconnect_attempt == 70000 && slot.start_failures == 0);
dma_free = 24576; dma_largest = 8191;
bridge.maintainSlotConnections();
assert(slot.client->starts == 0 && slot.reconnect_backoff == 3);
dma_largest = 8192;
bridge.maintainSlotConnections();
assert(slot.client->starts == 1 && bridge._slot_attempt_pending[0]);
assert(slot.reconnect_backoff == 4 && slot.max_backoff_failures == 1);
}
''')
def test_late_connected_callback_cannot_release_failed_stop_reservation(self):
self.compile_run(r'''
int main() {
for (bool publish_before_maintenance : {false, true}) {
MQTTBridge bridge;
bridge.only(0); clock_ms = 1000;
assert(bridge.ensureSlotClient(0));
auto& slot = bridge._slots[0];
slot.initial_connect_done = true;
auto* client = slot.client;
assert(bridge.reconnectSlotClient(0) == ESP_OK);
client->connectEvent();
client->errorWithoutDisconnect();
client->stop_succeeds = false;
bridge.maintainSlotConnections();
assert(client->isStarted() && client->stops == 1);
assert(slot.transport_health.recovery_reason != MQTTTransportHealth::RecoveryReason::None);
// An in-flight SDK event arrives after stop failed. CONNACK may clear the
// attempt bit and set a new-session latch, but it cannot prove task join.
client->connectEvent();
assert(!bridge._slot_attempt_pending[0] && bridge._slot_health_reset_pending[0]);
assert(bridge.hasPendingSlotConnection() && !bridge.canStartSlotConnection(1));
if (publish_before_maintenance) {
assert(!bridge.publishToSlot(0, "status", "{}", 2, true, 1));
assert(client->publishes == 0 && bridge.hasPendingSlotConnection());
}
bridge.maintainSlotConnections();
assert(client->stops == 2 && client->isStarted());
assert(bridge.hasPendingSlotConnection() && !bridge.canStartSlotConnection(1));
assert(client->starts == 1 && bridge.setups.empty());
assert(slot.transport_health.recoveries == 0);
client->stop_succeeds = true;
bridge.maintainSlotConnections();
assert(!client->isStarted() && !bridge.hasPendingSlotConnection());
assert(slot.transport_health.recoveries == 1 && client->starts == 1);
delete client;
slot.client = nullptr;
}
}
''')
def test_wifi_loss_failed_stop_and_reconnect_cannot_release_sdk_reservation(self):
self.compile_run(r'''
int main() {
for (bool established : {false, true}) {
MQTTBridge bridge;
bridge.only(0); clock_ms = 70000; WiFi.state = WL_CONNECTED;
assert(bridge.ensureSlotClient(0));
auto& slot = bridge._slots[0];
slot.initial_connect_done = true;
auto* client = slot.client;
assert(bridge.reconnectSlotClient(0) == ESP_OK);
if (established) client->connectEvent();
client->stop_succeeds = false;
WiFi.state = WL_DISCONNECTED;
assert(!bridge.handleWiFiConnection(clock_ms));
assert(client->isStarted() && client->stops == 1 && !slot.connected);
assert(bridge._slot_transport_fault_pending[0] && bridge.hasPendingSlotConnection());
assert(!bridge.canStartSlotConnection(1));
clock_ms += 11000;
WiFi.state = WL_CONNECTED;
assert(bridge.handleWiFiConnection(clock_ms));
client->connectEvent(); // late SDK callback after WiFi recovered
assert(bridge.hasPendingSlotConnection());
bridge.maintainSlotConnections();
assert(client->isStarted() && client->stops == 2 && !slot.connected);
assert(bridge.hasPendingSlotConnection() && !bridge.canStartSlotConnection(1));
assert(client->starts == 1 && bridge.setups.empty());
client->stop_succeeds = true;
bridge.maintainSlotConnections();
assert(!client->isStarted() && !bridge.hasPendingSlotConnection());
assert(slot.transport_health.recoveries == 1 && client->starts == 1);
delete client;
slot.client = nullptr;
}
}
''')
def test_pre_fix_error_callback_without_owner_signal_fails_regression(self):
source = self.fixture()
old_callback = source.replace(
"_slot_transport_fault_pending[index].store(true, std::memory_order_release);",
"/* pre-fix onError had no owner-task recovery signal */", 1)
self.assertNotEqual(source, old_callback)
self.compile_run(r'''
int main() {
MQTTBridge bridge;
bridge.only(0); clock_ms = 1000;
assert(bridge.ensureSlotClient(0));
auto* client = bridge._slots[0].client;
assert(bridge.reconnectSlotClient(0) == ESP_OK);
client->errorWithoutDisconnect();
assert(bridge._slot_transport_fault_pending[0]);
}
''', fixture=old_callback, expect_rejection=True)
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -21,6 +21,7 @@ PREAMBLE = r'''
#include <cstddef>
#include "helpers/MQTTConnectionAdmission.h"
#include "helpers/MQTTConnectionPolicy.h"
#include "helpers/MQTTTransportHealth.h"
struct esp_mqtt_client_config_t {
#if ESP_IDF_VERSION_MAJOR == 5
struct { int keepalive = 0, message_retransmit_timeout = 0; } session;
@@ -98,6 +99,7 @@ int main() {
RECONFIGURE_PREAMBLE = r'''
#include "helpers/MQTTConnectionAdmission.h"
#include "helpers/MQTTConnectionPolicy.h"
#include "helpers/MQTTTransportHealth.h"
#define MQTT_DEBUG_PRINTLN(...) ((void)0)
#define pdMS_TO_TICKS(value) (value)
constexpr int RUNTIME_MQTT_SLOTS = 2, MQTT_AUTH_JWT = 1;
@@ -147,8 +149,11 @@ struct MQTTBridge {
unsigned long last_reconnect_attempt = 0, last_log_time = 0, last_deferred_log_ms = 0;
uint8_t reconnect_backoff = 0, max_backoff_failures = 0;
bool circuit_breaker_tripped = false;
MQTTTransportHealth::State transport_health;
} _slots[RUNTIME_MQTT_SLOTS];
std::atomic<bool> _stop_requested{false}, _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_reset_pending[RUNTIME_MQTT_SLOTS] = {};
bool _slot_force_jwt_mint[RUNTIME_MQTT_SLOTS] = {};
bool _slot_reconfigure_pending[RUNTIME_MQTT_SLOTS] = {};
bool _initialized = true;
@@ -161,6 +166,7 @@ struct MQTTBridge {
bool canStartSlotConnection(int) const;
void optimizeMqttClientConfig(PsychicMqttClient*, bool);
void teardownSlot(int, bool force = false);
void updateSlotTransportDiag(int, uint32_t) {}
void applySlotPreset(int, const char*);
bool setupSlot(int index) {
auto& slot = _slots[index];
+52
View File
@@ -79,6 +79,7 @@ PREAMBLE = r'''
#undef private
#include "helpers/MQTTReplyFormat.h"
#include "helpers/MQTTConnectionHealth.h"
#include "helpers/MQTTTransportHealth.h"
#include "helpers/MQTTPacketFilter.h"
#include "helpers/bridges/MQTTErrorLabels.h"
template<typename... Args> void test_log(Args&&...) {}
@@ -161,6 +162,14 @@ struct MQTTBridge {
int last_sock_errno = 0;
};
MQTTSlot _slots[RUNTIME_MQTT_SLOTS];
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_recovering[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint32_t> _slot_health_recoveries[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint8_t> _slot_health_reason[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint32_t> _slot_health_ack_wait_secs[RUNTIME_MQTT_SLOTS] = {};
MQTTBridge() {
for (auto& wait : _slot_health_ack_wait_secs) wait.store(UINT32_MAX);
}
bool _initialized = true;
bool ready = true;
MQTTPrefs* _obs = nullptr;
@@ -437,6 +446,49 @@ int main() {
}
''')
def test_production_recovery_diagnostics_never_claim_no_errors(self):
self.compile_run(r'''
int main() {
PsychicMqttClient client;
MQTTBridge bridge;
bridge._slots[0].client = &client;
s_mqtt_bridge_instance = &bridge;
bridge._slot_health_reason[0] = static_cast<uint8_t>(
MQTTTransportHealth::RecoveryReason::AckTimeout);
bridge._slot_health_recoveries[0] = 3;
bridge._slot_health_ack_wait_secs[0] = 120;
for (bool fault_latched : {false, true}) {
bridge._slot_health_recovering[0] = !fault_latched;
bridge._slot_transport_fault_pending[0] = fault_latched;
char reply[160];
MQTTBridge::formatSlotDiagReply(reply, sizeof(reply), 0);
assert(strcmp(reply, "> mqtt1: recover, pub_ack:0, rec:3/puback, ack_wait:120s") == 0);
assert(strstr(reply, "no errors") == nullptr);
}
bridge._slot_health_recovering[0] = false;
bridge._slot_transport_fault_pending[0] = false;
char recovered[160];
MQTTBridge::formatSlotDiagReply(recovered, sizeof(recovered), 0);
assert(strstr(recovered, "> mqtt1: ok, no errors") == recovered);
assert(strstr(recovered, "rec:3/puback") != nullptr); // retain history
bridge._slot_health_recovering[0] = true;
bridge._slot_health_recoveries[0] = UINT32_MAX;
bridge._slot_health_ack_wait_secs[0] = UINT32_MAX - 1;
for (size_t capacity = 1; capacity <= 160; ++capacity) {
unsigned char bounded[168];
memset(bounded, 0xA5, sizeof(bounded));
char* reply = reinterpret_cast<char*>(bounded);
MQTTBridge::formatSlotDiagReply(reply, capacity, 0);
assert(memchr(reply, '\0', capacity) != nullptr);
for (size_t pos = capacity; pos < sizeof(bounded); ++pos) assert(bounded[pos] == 0xA5);
// Every appended numeric field is omitted whole when it cannot fit.
if (strstr(reply, "rec:")) assert(strstr(reply, "rec:4294967295/puback"));
if (strstr(reply, "ack_wait:")) assert(strstr(reply, "ack_wait:4294967294s"));
}
}
''')
if __name__ == "__main__":
unittest.main()
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Exercise bounded MQTT liveness clocks without an SDK or PlatformIO build."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class MqttTransportHealthTest(unittest.TestCase):
def compile_run(self, main):
compiler = shutil.which("g++") or shutil.which("clang++")
self.assertIsNotNone(compiler, "a host C++ compiler is required")
source = ('#include <cassert>\n#include <cstring>\n#include <initializer_list>\n'
'#include "helpers/MQTTTransportHealth.h"\n'
'using namespace MQTTTransportHealth;\n') + main
with tempfile.TemporaryDirectory(prefix="meshcore-mqtt-health-") as directory:
work = Path(directory)
path, binary = work / "health.cpp", work / "health"
path.write_text(source, encoding="ascii")
result = subprocess.run(
[compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-I", str(ROOT / "src"), str(path), "-o", str(binary)],
capture_output=True, text=True, timeout=60)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_repeated_acceptance_cannot_postpone_oldest_missing_ack(self):
self.compile_run(r'''
int main() {
State state;
state.acceptedQos1(1000, 7);
for (uint32_t now = 11000; now < 121000; now += 10000) {
state.acceptedQos1(now, 7);
assert(state.ack_started_ms == 1000 && state.ack_snapshot == 7);
assert(!state.ackExpired(now));
}
assert(state.ackExpired(121000));
}
''')
def test_ack_advance_clears_watch_and_new_enqueue_starts_a_new_deadline(self):
self.compile_run(r'''
int main() {
State state;
state.acceptedQos1(1000, 7);
state.observeAck(7);
assert(state.ack_pending);
state.observeAck(8);
assert(!state.ack_pending && !state.ackExpired(121000));
state.acceptedQos1(300000, 8);
assert(state.ack_started_ms == 300000 && state.ack_snapshot == 8);
assert(!state.ackExpired(419999) && state.ackExpired(420000));
// An ACK arriving between maintenance passes is recognized on enqueue.
state.acceptedQos1(450000, 9);
assert(state.ack_started_ms == 450000 && state.ack_snapshot == 9);
}
''')
def test_immediate_ack_race_uses_snapshot_from_before_enqueue(self):
self.compile_run(r'''
int main() {
State state;
const uint32_t before_enqueue = 11;
const uint32_t after_enqueue = 12; // broker event arrived inside SDK enqueue
state.acceptedQos1(1000, before_enqueue);
state.observeAck(after_enqueue);
assert(!state.ack_pending && !state.ackExpired(121000));
}
''')
def test_zero_start_ticks_and_millis_wrap_preserve_bounded_deadlines(self):
self.compile_run(r'''
int main() {
for (uint32_t start : {uint32_t(0), UINT32_MAX - 60000}) {
State state;
state.beginAttempt(start);
state.acceptedQos1(start, UINT32_MAX);
assert(!state.attemptExpired(start + kAttemptTimeoutMs - 1));
assert(state.attemptExpired(start + kAttemptTimeoutMs));
assert(!state.ackExpired(start + kAckTimeoutMs - 1));
assert(state.ackExpired(start + kAckTimeoutMs));
// The acknowledgment counter may wrap too; inequality still proves progress.
state.observeAck(0);
assert(!state.ack_pending);
state.completeAttempt();
assert(!state.attemptExpired(start + kAttemptTimeoutMs));
}
}
''')
def test_recovery_keeps_first_reason_and_saturates_lifetime_counter(self):
self.compile_run(r'''
int main() {
State state;
state.beginAttempt(1000);
state.acceptedQos1(1000, 3);
state.requestRecovery(RecoveryReason::TransportError);
state.requestRecovery(RecoveryReason::AckTimeout);
assert(state.recovery_reason == RecoveryReason::TransportError);
state.recovered();
assert(state.recoveries == 1 && !state.attempt_active && !state.ack_pending);
assert(state.recovery_reason == RecoveryReason::None);
assert(state.last_recovery_reason == RecoveryReason::TransportError);
state.recoveries = UINT32_MAX;
state.requestRecovery(RecoveryReason::PublishFailure);
state.recovered();
assert(state.recoveries == UINT32_MAX);
assert(state.last_recovery_reason == RecoveryReason::PublishFailure);
assert(strcmp(reasonLabel(RecoveryReason::HandshakeTimeout), "handshake") == 0);
assert(strcmp(reasonLabel(RecoveryReason::AckTimeout), "puback") == 0);
}
''')
def test_quiet_session_without_accepted_qos1_never_times_out(self):
self.compile_run(r'''
int main() {
State state;
state.beginAttempt(1000);
state.completeAttempt();
for (uint32_t now = 0; now <= 7 * 24 * 60 * 60 * 1000; now += 60000) {
state.observeAck(0);
assert(!state.attemptExpired(now) && !state.ackExpired(now));
assert(state.recovery_reason == RecoveryReason::None);
}
}
''')
if __name__ == "__main__":
unittest.main()
+4
View File
@@ -32,6 +32,7 @@ PREAMBLE = r'''
#include <cassert>
#include <functional>
#include "helpers/MQTTConnectionHealth.h"
#include "helpers/MQTTTransportHealth.h"
using esp_err_t = int;
using esp_mqtt_client_handle_t = void*;
constexpr int ESP_OK=0, ESP_FAIL=-1, ESP_ERR_INVALID_STATE=2, ESP_ERR_NO_MEM=3;
@@ -53,6 +54,7 @@ static int register_result=ESP_OK, config_result=ESP_OK;
static int start_result=ESP_OK, reconnect_result=ESP_OK;
static int init_calls=0, register_calls=0, destroy_calls=0, config_calls=0;
static int start_calls=0, reconnect_calls=0;
unsigned long millis() { return 1000; }
static std::function<void()> sdk_callback;
void* test_malloc(size_t size) { return fail_malloc ? nullptr : std::malloc(size); }
#define malloc test_malloc
@@ -88,9 +90,11 @@ struct MQTTBridge {
struct MQTTSlot {
PsychicMqttClient* client=nullptr;
uint32_t start_failures=0;
MQTTTransportHealth::State transport_health;
};
MQTTSlot _slots[RUNTIME_MQTT_SLOTS];
std::atomic<bool> _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _stop_requested{false};
bool hasPendingSlotConnection() const;
bool canStartSlotConnection(int index) const;
+60 -2
View File
@@ -22,6 +22,8 @@ BRIDGE = "src/helpers/bridges/MQTTBridge.cpp"
PREAMBLE = r'''
#include <helpers/WiFiNetworkPowerPolicy.h>
#include <helpers/MQTTConnectionPolicy.h>
#include <helpers/MQTTConnectionHealth.h>
#include <helpers/MQTTTransportHealth.h>
#include <helpers/esp32/SntpOperationCoordinator.h>
#include <atomic>
#include <cassert>
@@ -139,17 +141,18 @@ void configTime(int a, int b, const char* primary) {
}
struct Client {
bool started = true, fail_stop = false;
bool started = true, fail_stop = false, live = false;
int stops = 0;
uint32_t publish_acks = 0;
uint32_t getPublishAck() const { return publish_acks; }
bool isStarted() const { return started; }
bool connected() const { return live; }
void disconnect() {
require(!mesh::wifi::networkPower().backgroundSuspended(),
"TLS stopped after handing station off");
++stops;
events.push_back("tls-stop");
if (!fail_stop) started = false;
if (!fail_stop) started = live = false;
if (on_client_stop) on_client_stop();
}
};
@@ -185,9 +188,18 @@ struct MQTTBridge {
uint32_t connected_at_ms = 0, last_reconnect_attempt = 200U;
uint8_t reconnect_backoff = 5;
Client* client = nullptr;
uint32_t connect_failures = 0, current_outage_started_ms = 0;
MQTTTransportHealth::State transport_health;
} _slots[RUNTIME_MQTT_SLOTS];
using MQTTSlot = Slot;
Client clients[RUNTIME_MQTT_SLOTS];
std::atomic<bool> _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_transport_fault_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_reset_pending[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _slot_health_recovering[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint32_t> _slot_health_recoveries[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint8_t> _slot_health_reason[RUNTIME_MQTT_SLOTS] = {};
std::atomic<uint32_t> _slot_health_ack_wait_secs[RUNTIME_MQTT_SLOTS] = {};
std::atomic<bool> _status_publish_pending[RUNTIME_MQTT_SLOTS] = {};
uint32_t _network_publish_acks[RUNTIME_MQTT_SLOTS] = {};
bool _network_espnow_restore_pending = false;
@@ -237,6 +249,10 @@ struct MQTTBridge {
bool isRunning() const { return true; }
bool isNetworkSuspended() const { return _network_suspended.load(); }
bool requestNtpTimeEstimate();
bool hasPendingSlotConnection() const;
void serviceSlotTransportHealth(uint32_t now);
bool recoverSlotTransport(int index, uint32_t now);
void updateSlotTransportDiag(int index, uint32_t now);
bool serviceNetworkPower(uint32_t now);
void serviceEspNowChannelRestore(uint32_t now);
void serviceBackgroundNtp(uint32_t now);
@@ -336,6 +352,40 @@ static void failedSdkStopWithholdsHandoff() {
"successful retry leaked a transport or radio");
}
static void failedSuspendLateConnectCannotAbandonTransportOwnership() {
resetEnvironment();
MQTTBridge bridge;
for (auto& pending : bridge._slot_attempt_pending) pending = false;
bridge.serviceNetworkPower(clock_ms);
bridge.clients[1].fail_stop = true;
clock_ms += grace;
require(!bridge.serviceNetworkPower(clock_ms), "failed stop did not hold handoff");
require(bridge._slot_transport_fault_pending[1] && bridge.hasPendingSlotConnection(),
"failed suspension abandoned a running MQTT transport");
// A foreground owner wakes networking and a late CONNACK sets a fresh-session
// latch. Neither proves the failed SDK stop completed or frees admission.
mesh::wifi::networkPower().setHold(mesh::wifi::NetworkPowerHold::WebConfig, true);
bridge._slots[1].connected = bridge.clients[1].live = true;
bridge._slot_attempt_pending[1] = false;
bridge._slot_health_reset_pending[1] = true;
require(bridge.serviceNetworkPower(++clock_ms), "foreground owner did not keep radio");
bridge.serviceSlotTransportHealth(clock_ms);
require(bridge.clients[1].started && bridge.hasPendingSlotConnection(),
"foreground wake or late CONNACK released failed-stop reservation");
require(!bridge._slots[1].connected && !bridge._network_suspended,
"failed transport was advertised healthy or handed station away");
require(bridge._slots[1].transport_health.recoveries == 0,
"failed SDK stop was counted as recovered");
bridge.clients[1].fail_stop = false;
bridge.serviceSlotTransportHealth(++clock_ms);
require(!bridge.clients[1].started && !bridge.hasPendingSlotConnection(),
"proven successful stop did not release ownership");
require(bridge._slots[1].transport_health.recoveries == 1,
"successful owner cleanup was not counted");
require(WiFi.offs == 0 && WiFi.disconnects == 0,
"transport recovery stopped foreground WiFi");
}
static void recoveryHasOneBoundedWindow() {
for (uint32_t start : {100U, UINT32_MAX - 10000U}) {
resetEnvironment();
@@ -686,6 +736,7 @@ int main(int argc, char** argv) {
try {
if (name == "handoff") failureStopsBothServicesBeforeWifi();
else if (name == "failed-stop") failedSdkStopWithholdsHandoff();
else if (name == "failed-stop-wake") failedSuspendLateConnectCannotAbandonTransportOwnership();
else if (name == "recovery") recoveryHasOneBoundedWindow();
else if (name == "owners") foregroundAndEspNowArePreserved();
else if (name == "background-estimate") automaticClockEstimateCannotWakeSuspendedNetwork();
@@ -769,6 +820,10 @@ class MqttWiFiNetworkPowerTests(unittest.TestCase):
"void MQTTBridge::refreshNTP(",
"void MQTTBridge::pollNtpRefresh(",
"bool MQTTBridge::requestNtpTimeEstimate(",
"bool MQTTBridge::hasPendingSlotConnection(",
"void MQTTBridge::serviceSlotTransportHealth(",
"bool MQTTBridge::recoverSlotTransport(",
"void MQTTBridge::updateSlotTransportDiag(",
))
cls.temporary = tempfile.TemporaryDirectory(prefix="meshcore-mqtt-network-power-")
cls.addClassCleanup(cls.temporary.cleanup)
@@ -815,6 +870,9 @@ class MqttWiFiNetworkPowerTests(unittest.TestCase):
def test_failed_sdk_transport_stop_keeps_station_owned_and_awake(self):
self.run_case("failed-stop")
def test_failed_suspend_late_connect_and_foreground_wake_keep_sdk_reservation(self):
self.run_case("failed-stop-wake")
def test_recovery_restarts_once_and_stops_after_bounded_probe_across_wrap(self):
self.run_case("recovery")