fix: harden firmware builds and runtime reliability

This commit is contained in:
mikecarper committed 2026-08-26 15:42:12 -07:00
1 parent 66c9e3f73b
commit bd3a94bddb
71 files changed
+2102 -466

No files matched your search

+32 -28
View File
@@ -2,6 +2,7 @@
#if MESH_PACKET_LOGGING
#include <Arduino.h>
#include <helpers/SerialPacketLog.h>
#endif
#include <math.h>
@@ -165,8 +166,14 @@ bool Dispatcher::startOutboundTransmit() {
#if MESH_PACKET_LOGGING
if (isUsbLoggingEnabled()) {
logPacketStart("TX", outbound, len);
logPacketEnd(outbound);
#if MESH_PACKET_LOGGING_COMPACT
SerialLogLine<> line;
line.printf("T");
line.hex(raw, len);
line.flush(usbLoggingPort(), false);
#else
logPacketLine("TX", outbound, len, false, 0.0f, 0);
#endif
}
#endif
return true;
@@ -207,26 +214,31 @@ uint32_t Dispatcher::getCADFailMaxDuration() const {
}
#if MESH_PACKET_LOGGING
void Dispatcher::logPacketStart(const char* direction, const Packet* packet, int len) {
Stream& logging_port = usbLoggingPort();
logging_port.print(getLogDateTime());
logging_port.printf(": %s, len=%d (type=%d, route=%s, payload_len=%d)",
direction, len, packet->getPayloadType(),
packet->isRouteDirect() ? "D" : "F",
packet->payload_len);
}
void Dispatcher::logPacketLine(const char* direction, const Packet* packet,
int len, bool include_rx_metrics, float score,
uint32_t air_time) {
SerialLogLine<256> line;
line.printf("%s: %s, len=%d (type=%d, route=%s, payload_len=%d)",
getLogDateTime(), direction, len, packet->getPayloadType(),
packet->isRouteDirect() ? "D" : "F", packet->payload_len);
if (include_rx_metrics) {
line.printf(" SNR=%d RSSI=%d score=%d time=%u", (int)packet->getSNR(),
(int)packet->getRSSI(), (int)(score * 1000),
(unsigned)air_time);
uint8_t packet_hash[MAX_HASH_SIZE];
packet->calculatePacketHash(packet_hash);
line.printf(" hash=");
line.hex(packet_hash, MAX_HASH_SIZE);
}
void Dispatcher::logPacketEnd(const Packet* packet) {
const uint8_t type = packet->getPayloadType();
if (packet->payload_len >= 2
&& (type == PAYLOAD_TYPE_PATH || type == PAYLOAD_TYPE_REQ
|| type == PAYLOAD_TYPE_RESPONSE || type == PAYLOAD_TYPE_TXT_MSG)) {
usbLoggingPort().printf(" [%02X -> %02X]\n",
(uint32_t)packet->payload[1],
(uint32_t)packet->payload[0]);
} else {
usbLoggingPort().write((uint8_t)'\n');
line.printf(" [%02X -> %02X]", (uint32_t)packet->payload[1],
(uint32_t)packet->payload[0]);
}
line.flush(usbLoggingPort());
}
#endif
@@ -567,6 +579,7 @@ void Dispatcher::checkRecv() {
} else {
if (tryParsePacket(pkt, raw, len)) {
pkt->_snr = snr * 4.0f;
pkt->_rssi = (int16_t)rssi;
score = _radio->packetScore(snr, len);
air_time = _radio->getEstAirtimeFor(len);
rx_air_time += air_time;
@@ -580,19 +593,9 @@ void Dispatcher::checkRecv() {
}
}
if (pkt) {
#if MESH_PACKET_LOGGING
#if MESH_PACKET_LOGGING && !MESH_PACKET_LOGGING_COMPACT
if (isUsbLoggingEnabled()) {
logPacketStart("RX", pkt, pkt->getRawLength());
Stream& logging_port = usbLoggingPort();
logging_port.printf(" SNR=%d RSSI=%d score=%d time=%d",
(int)pkt->getSNR(), (int)rssi,
(int)(score * 1000), air_time);
static uint8_t packet_hash[MAX_HASH_SIZE];
pkt->calculatePacketHash(packet_hash);
logging_port.print(" hash=");
mesh::Utils::printHex(logging_port, packet_hash, MAX_HASH_SIZE);
logPacketEnd(pkt);
logPacketLine("RX", pkt, pkt->getRawLength(), true, score, air_time);
}
#endif
logRx(pkt, pkt->getRawLength(), score); // hook for custom logging
@@ -724,6 +727,7 @@ Packet* Dispatcher::obtainNewPacket() {
_err_flags |= ERR_EVENT_FULL;
} else {
pkt->payload_len = pkt->path_len = 0;
pkt->_rssi = 0;
pkt->_snr = 0;
pkt->tx_cr = 0;
pkt->flood_retry_policy = FLOOD_RETRY_POLICY_DEFAULT;
+3 -3
View File
@@ -382,9 +382,9 @@ public:
private:
#if MESH_PACKET_LOGGING
void logPacketStart(const char* direction, const Packet* packet, int len)
__attribute__((noinline));
void logPacketEnd(const Packet* packet) __attribute__((noinline));
void logPacketLine(const char* direction, const Packet* packet, int len,
bool include_rx_metrics, float score,
uint32_t air_time) __attribute__((noinline));
#endif
void checkRecv();
void checkSend();
+4
View File
@@ -8,6 +8,8 @@ Packet::Packet() {
header = 0;
path_len = 0;
payload_len = 0;
_rssi = 0;
_snr = 0;
tx_cr = 0;
flood_retry_policy = FLOOD_RETRY_POLICY_DEFAULT;
}
@@ -68,6 +70,8 @@ bool Packet::readFrom(const uint8_t src[], uint8_t len) {
if (src == NULL || len < 2) return false; // header + path_len
uint8_t i = 0;
_rssi = 0;
_snr = 0;
tx_cr = 0;
flood_retry_policy = FLOOD_RETRY_POLICY_DEFAULT;
header = src[i++];
+2
View File
@@ -55,6 +55,7 @@ public:
uint16_t transport_codes[2];
uint8_t path[MAX_PATH_SIZE];
uint8_t payload[MAX_PACKET_PAYLOAD];
int16_t _rssi; // dBm, captured with _snr when this packet is received
int8_t _snr;
uint8_t tx_cr; // volatile local-only TX coding-rate override; not serialized
uint8_t flood_retry_policy; // volatile receive-policy result; not serialized
@@ -99,6 +100,7 @@ public:
bool isMarkedDoNotRetransmit() const { return header == 0xFF; }
float getSNR() const { return ((float)_snr) / 4.0f; }
int16_t getRSSI() const { return _rssi; }
/**
* \returns the encoded/wire format length of this packet
+1 -1
View File
@@ -68,7 +68,7 @@ public:
/**
* \brief Prints the hexadecimal representation of 'src' bytes of given length, to Stream 's'.
*/
*/
static void printHex(Stream& s, const uint8_t* src, size_t len);
/**
+232
View File
@@ -0,0 +1,232 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
namespace AlertFaultPolicy {
static const uint32_t kCheckIntervalMs = 5000UL;
static const uint16_t kMinIntervalMinutes = 60;
static const uint32_t kMsPerMinute = 60000UL;
enum class State : uint8_t { OK, FIRING };
struct Fault {
State state;
uint32_t fired_at_ms;
uint32_t last_outage_started_ms;
};
struct OutageSnapshot {
bool down;
uint32_t started_ms;
uint8_t reason;
};
enum class Action : uint8_t { None, FireDown, FireRecovered };
struct TickResult {
Action action;
uint32_t duration_ms;
};
static inline OutageSnapshot fromStartMs(uint32_t started_ms) {
OutageSnapshot snapshot{};
snapshot.down = started_ms != 0;
snapshot.started_ms = started_ms;
return snapshot;
}
// Pack the cross-task outage state into one atomic word. The explicit down bit
// means an outage beginning at millis()==0 remains representable.
static const uint64_t kOutageDownBit = 1ULL << 40;
static inline uint64_t packOutageSnapshot(OutageSnapshot snapshot) {
if (!snapshot.down) {
snapshot.started_ms = 0;
snapshot.reason = 0;
}
uint64_t value = (uint64_t)snapshot.started_ms;
value |= (uint64_t)snapshot.reason << 32;
if (snapshot.down) value |= kOutageDownBit;
return value;
}
static inline OutageSnapshot unpackOutageSnapshot(uint64_t value) {
OutageSnapshot snapshot{};
snapshot.started_ms = (uint32_t)value;
snapshot.reason = (uint8_t)(value >> 32);
snapshot.down = (value & kOutageDownBit) != 0;
if (!snapshot.down) {
snapshot.started_ms = 0;
snapshot.reason = 0;
}
return snapshot;
}
static inline OutageSnapshot applyWifiStatus(uint32_t now, bool connected,
OutageSnapshot current,
bool initialized) {
if (connected) {
if (!initialized || current.down) return OutageSnapshot{};
return current;
}
if (!initialized || !current.down) {
OutageSnapshot snapshot{};
snapshot.down = true;
snapshot.started_ms = now;
snapshot.reason = current.reason;
return snapshot;
}
return current;
}
static inline OutageSnapshot applyWifiGotIp(OutageSnapshot) {
return OutageSnapshot{};
}
// Preserve the first outage start and first useful reason. Reconnect attempts
// may produce later local disconnect events which must not rewrite either.
static inline OutageSnapshot applyWifiDisconnectEvent(
uint32_t now, uint8_t reason, OutageSnapshot current) {
if (!current.down) {
OutageSnapshot snapshot{};
snapshot.down = true;
snapshot.started_ms = now;
snapshot.reason = reason;
return snapshot;
}
if (current.reason == 0 && reason != 0) current.reason = reason;
return current;
}
static inline uint32_t elapsedMs(uint32_t now, uint32_t then) {
return now - then;
}
static inline bool checkDue(uint32_t now, uint32_t next_check_ms) {
return (int32_t)(now - next_check_ms) >= 0;
}
static inline uint32_t nextCheckMs(uint32_t now) {
return now + kCheckIntervalMs;
}
static inline uint32_t minIntervalMs(uint16_t configured_minutes) {
uint16_t minutes = configured_minutes < kMinIntervalMinutes
? kMinIntervalMinutes
: configured_minutes;
return (uint32_t)minutes * kMsPerMinute;
}
static inline uint32_t thresholdMs(uint16_t minutes) {
return (uint32_t)minutes * kMsPerMinute;
}
static inline uint32_t downDurationMs(uint32_t now,
const OutageSnapshot& snapshot) {
return snapshot.down ? elapsedMs(now, snapshot.started_ms) : 0;
}
static inline bool rateLimitAllows(uint32_t now, uint32_t fired_at_ms,
uint32_t min_interval_ms) {
return fired_at_ms == 0 ||
elapsedMs(now, fired_at_ms) >= min_interval_ms;
}
static inline TickResult tick(const Fault& fault, uint32_t now,
const OutageSnapshot& snapshot,
uint32_t threshold_ms,
uint32_t min_interval_ms) {
TickResult result = {Action::None, 0};
if (fault.state == State::OK) {
const uint32_t down_ms = downDurationMs(now, snapshot);
if (snapshot.down && down_ms >= threshold_ms &&
rateLimitAllows(now, fault.fired_at_ms, min_interval_ms)) {
result.action = Action::FireDown;
result.duration_ms = down_ms;
}
} else if (!snapshot.down) {
result.action = Action::FireRecovered;
result.duration_ms = elapsedMs(now, fault.last_outage_started_ms);
}
return result;
}
static inline void commitDown(Fault& fault, uint32_t now,
uint32_t outage_start_ms) {
fault.state = State::FIRING;
fault.fired_at_ms = now;
fault.last_outage_started_ms = outage_start_ms;
}
static inline void commitRecovered(Fault& fault) {
fault.state = State::OK;
}
static inline void reset(Fault& fault) {
fault.state = State::OK;
fault.fired_at_ms = 0;
}
static inline void rearmIfDisabled(Fault& fault) {
if (fault.state == State::FIRING) fault.state = State::OK;
}
static inline void formatAge(uint32_t age_ms, char* out, size_t out_size) {
if (!out || out_size == 0) return;
uint32_t seconds = age_ms / 1000U;
uint32_t hours = seconds / 3600U;
uint32_t minutes = (seconds % 3600U) / 60U;
if (hours > 0) {
snprintf(out, out_size, "%uh%um", (unsigned)hours, (unsigned)minutes);
} else {
snprintf(out, out_size, "%um", (unsigned)minutes);
}
}
static inline bool formatWifiAlert(char* out, size_t out_size,
const TickResult& result,
const OutageSnapshot& snapshot) {
if (!out || out_size == 0) return false;
char age[16];
formatAge(result.duration_ms, age, sizeof(age));
if (result.action == Action::FireDown) {
if (snapshot.reason != 0) {
snprintf(out, out_size, "WiFi down %s (reason %u)", age,
(unsigned)snapshot.reason);
} else {
snprintf(out, out_size, "WiFi down %s", age);
}
return true;
}
if (result.action == Action::FireRecovered) {
snprintf(out, out_size, "WiFi recovered after %s", age);
return true;
}
return false;
}
static inline void formatMqttDown(char* out, size_t out_size, int slot_1based,
const char* preset_name,
uint32_t duration_ms) {
if (!out || out_size == 0) return;
char age[16];
formatAge(duration_ms, age, sizeof(age));
snprintf(out, out_size, "MQTT slot %d (%s) down %s", slot_1based,
preset_name ? preset_name : "?", age);
}
static inline void formatMqttRecovered(char* out, size_t out_size,
int slot_1based,
const char* preset_name,
uint32_t duration_ms) {
if (!out || out_size == 0) return;
char age[16];
formatAge(duration_ms, age, sizeof(age));
snprintf(out, out_size, "MQTT slot %d (%s) recovered after %s", slot_1based,
preset_name ? preset_name : "?", age);
}
} // namespace AlertFaultPolicy
+50 -93
View File
@@ -4,6 +4,9 @@
#include <Packet.h>
#include <string.h>
#include <stdio.h>
#ifdef WITH_MQTT_BRIDGE
#include "AlertFaultPolicy.h"
#endif
// Header layout for PAYLOAD_TYPE_GRP_TXT before encryption:
// [0..3] timestamp (uint32_t LE) - also helps make packet_hash unique
@@ -129,11 +132,9 @@ bool AlertReporter::resolveChannel(mesh::GroupChannel& out) const {
void AlertReporter::onConfigChanged() {
// Reset transient state so a config change re-arms the edge detector.
#ifdef WITH_MQTT_BRIDGE
_wifi.state = OK;
_wifi.fired_at_ms = 0;
AlertFaultPolicy::reset(_wifi);
for (size_t i = 0; i < sizeof(_mqtt) / sizeof(_mqtt[0]); i++) {
_mqtt[i].state = OK;
_mqtt[i].fired_at_ms = 0;
AlertFaultPolicy::reset(_mqtt[i]);
}
#endif
}
@@ -194,122 +195,78 @@ bool AlertReporter::sendText(const char* text) {
return sendChannel(text);
}
void AlertReporter::formatAge(unsigned long age_ms, char* out, size_t out_size) const {
unsigned long secs = age_ms / 1000UL;
unsigned long h = secs / 3600UL;
unsigned long m = (secs % 3600UL) / 60UL;
if (h > 0) {
snprintf(out, out_size, "%luh%lum", h, m);
} else {
snprintf(out, out_size, "%lum", m);
}
}
void AlertReporter::onLoop(unsigned long now_ms) {
if (!_prefs || !_obs || !_obs->alert_enabled) return;
if (!_mesh) return;
// Throttle: ~5 s cadence. The thresholds are minutes-scale so this is fine.
if ((long)(now_ms - _next_check_ms) < 0) return;
_next_check_ms = now_ms + 5000UL;
const uint32_t now = (uint32_t)now_ms;
if (!AlertFaultPolicy::checkDue(now, (uint32_t)_next_check_ms)) return;
_next_check_ms = AlertFaultPolicy::nextCheckMs(now);
#ifdef WITH_MQTT_BRIDGE
// Clamp to a 60-minute floor regardless of what's in NodePrefs. The CLI
// already enforces this on set, but a stale prefs file or future field
// tweak shouldn't be able to drag the floor below 1 hour and let a
// flapping link spam the mesh.
//
// The rate limiter only applies between two real sends: fired_at_ms == 0
// means "never fired since boot/config change", and treating it as a send
// at millis()==0 would suppress every first alert until uptime reaches
// min_interval (observed as a 30-minute alert.mqtt threshold not reporting
// until 60 minutes after a reboot).
uint16_t cfg_min = _obs->alert_min_interval_min;
if (cfg_min < 60) cfg_min = 60;
unsigned long min_interval_ms = (unsigned long)cfg_min * 60000UL;
const uint32_t min_interval_ms =
AlertFaultPolicy::minIntervalMs(_obs->alert_min_interval_min);
// -------- WiFi fault --------
if (_obs->alert_wifi_minutes > 0) {
unsigned long wifi_disc_ms = MQTTBridge::getLastWifiDisconnectTime();
unsigned long wifi_conn_ms = MQTTBridge::getWifiConnectedAtMillis();
bool wifi_down = (wifi_disc_ms != 0 && wifi_conn_ms == 0);
unsigned long down_ms = wifi_down ? (now_ms - wifi_disc_ms) : 0;
unsigned long thresh_ms = (unsigned long)_obs->alert_wifi_minutes * 60000UL;
if (_wifi.state == OK) {
if (wifi_down && down_ms >= thresh_ms &&
(_wifi.fired_at_ms == 0 || (now_ms - _wifi.fired_at_ms) >= min_interval_ms)) {
char age[16];
formatAge(down_ms, age, sizeof(age));
uint8_t reason = MQTTBridge::getLastWifiDisconnectReason();
if (_bridge != nullptr) {
const AlertFaultPolicy::OutageSnapshot snapshot =
_bridge->getWifiOutageSnapshot();
AlertFaultPolicy::TickResult result = AlertFaultPolicy::tick(
_wifi, now, snapshot,
AlertFaultPolicy::thresholdMs(_obs->alert_wifi_minutes),
min_interval_ms);
if (result.action == AlertFaultPolicy::Action::FireDown) {
char text[80];
if (reason != 0) {
snprintf(text, sizeof(text), "WiFi down %s (reason %u)", age, (unsigned)reason);
} else {
snprintf(text, sizeof(text), "WiFi down %s", age);
}
AlertFaultPolicy::formatWifiAlert(text, sizeof(text), result, snapshot);
if (sendChannel(text)) {
_wifi.state = FIRING;
_wifi.fired_at_ms = now_ms;
_wifi.last_outage_started_ms = wifi_disc_ms;
AlertFaultPolicy::commitDown(_wifi, now, snapshot.started_ms);
}
}
} else { // FIRING
if (!wifi_down) {
unsigned long total = (wifi_conn_ms != 0 && _wifi.last_outage_started_ms != 0)
? (wifi_conn_ms - _wifi.last_outage_started_ms) : 0;
char age[16];
formatAge(total, age, sizeof(age));
} else if (result.action == AlertFaultPolicy::Action::FireRecovered) {
char text[80];
snprintf(text, sizeof(text), "WiFi recovered after %s", age);
if (sendChannel(text)) _wifi.state = OK;
AlertFaultPolicy::formatWifiAlert(text, sizeof(text), result, snapshot);
sendChannel(text);
AlertFaultPolicy::commitRecovered(_wifi);
}
}
} else if (_wifi.state == FIRING) {
_wifi.state = OK; // threshold disabled mid-fault: silently re-arm
} else {
AlertFaultPolicy::rearmIfDisabled(_wifi);
}
// -------- MQTT slot faults --------
if (_obs->alert_mqtt_minutes > 0 && _bridge != nullptr) {
int n = MQTTBridge::getRuntimeSlotCount();
if (n > (int)(sizeof(_mqtt) / sizeof(_mqtt[0]))) n = (int)(sizeof(_mqtt) / sizeof(_mqtt[0]));
unsigned long thresh_ms = (unsigned long)_obs->alert_mqtt_minutes * 60000UL;
const uint32_t threshold_ms =
AlertFaultPolicy::thresholdMs(_obs->alert_mqtt_minutes);
for (int i = 0; i < n; i++) {
Fault& f = _mqtt[i];
AlertFaultPolicy::Fault& fault = _mqtt[i];
if (!_bridge->isSlotEnabledAndAttempted(i)) {
if (f.state == FIRING) f.state = OK; // slot disabled mid-fault
AlertFaultPolicy::rearmIfDisabled(fault);
continue;
}
unsigned long outage_start = _bridge->getSlotCurrentOutageStartMs(i);
bool down = (outage_start != 0);
unsigned long down_ms = down ? (now_ms - outage_start) : 0;
if (f.state == OK) {
if (down && down_ms >= thresh_ms &&
(f.fired_at_ms == 0 || (now_ms - f.fired_at_ms) >= min_interval_ms)) {
char age[16];
formatAge(down_ms, age, sizeof(age));
char text[100];
snprintf(text, sizeof(text), "MQTT slot %d (%s) down %s",
i + 1, _bridge->getSlotPresetName(i), age);
if (sendChannel(text)) {
f.state = FIRING;
f.fired_at_ms = now_ms;
f.last_outage_started_ms = outage_start;
}
}
} else { // FIRING
if (!down) {
unsigned long total = (f.last_outage_started_ms != 0)
? (now_ms - f.last_outage_started_ms) : 0;
char age[16];
formatAge(total, age, sizeof(age));
char text[100];
snprintf(text, sizeof(text), "MQTT slot %d (%s) recovered after %s",
i + 1, _bridge->getSlotPresetName(i), age);
if (sendChannel(text)) f.state = OK;
const uint32_t outage_start =
(uint32_t)_bridge->getSlotCurrentOutageStartMs(i);
const AlertFaultPolicy::OutageSnapshot snapshot =
AlertFaultPolicy::fromStartMs(outage_start);
AlertFaultPolicy::TickResult result = AlertFaultPolicy::tick(
fault, now, snapshot, threshold_ms, min_interval_ms);
if (result.action == AlertFaultPolicy::Action::FireDown) {
char text[100];
AlertFaultPolicy::formatMqttDown(
text, sizeof(text), i + 1, _bridge->getSlotPresetName(i),
result.duration_ms);
if (sendChannel(text)) {
AlertFaultPolicy::commitDown(fault, now, outage_start);
}
} else if (result.action == AlertFaultPolicy::Action::FireRecovered) {
char text[100];
AlertFaultPolicy::formatMqttRecovered(
text, sizeof(text), i + 1, _bridge->getSlotPresetName(i),
result.duration_ms);
sendChannel(text);
AlertFaultPolicy::commitRecovered(fault);
}
}
}
+3 -10
View File
@@ -6,6 +6,7 @@
#ifdef WITH_MQTT_BRIDGE
#include "bridges/MQTTBridge.h"
#include "AlertFaultPolicy.h"
#endif
/**
@@ -89,14 +90,6 @@ public:
private:
bool resolveChannel(mesh::GroupChannel& out) const;
bool sendChannel(const char* text);
void formatAge(unsigned long age_ms, char* out, size_t out_size) const;
enum FaultState { OK, FIRING };
struct Fault {
FaultState state;
unsigned long fired_at_ms; // millis() when we last sent a "down" alert
unsigned long last_outage_started_ms; // remembered so the recovered msg can quote duration
};
NodePrefs* _prefs;
MQTTPrefs* _obs;
@@ -104,8 +97,8 @@ private:
CommonCLICallbacks* _callbacks;
#ifdef WITH_MQTT_BRIDGE
MQTTBridge* _bridge;
Fault _wifi;
Fault _mqtt[RUNTIME_MQTT_SLOTS];
AlertFaultPolicy::Fault _wifi;
AlertFaultPolicy::Fault _mqtt[RUNTIME_MQTT_SLOTS];
#endif
unsigned long _next_check_ms;
};
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <stddef.h>
namespace DatagramPayloadLimits {
// Encrypted datagrams append a MAC and round the plaintext up to a whole
// cipher block. Reserving block_size - 1 bytes covers the worst-case padding.
static constexpr size_t maxPlaintext(size_t packet_payload_size,
size_t mac_size,
size_t block_size) {
return block_size > 0 &&
packet_payload_size >= mac_size + block_size - 1
? packet_payload_size - mac_size - (block_size - 1)
: 0;
}
} // namespace DatagramPayloadLimits
+54
View File
@@ -17,6 +17,7 @@ static const uint8_t kMaxFailuresAtMaxBackoff = 3;
static const uint32_t kDefaultJwtLifetimeSecs = 86400UL;
static const uint32_t kMaxJwtStaggerSecs = 300UL;
static const uint32_t kMinimumValidEpoch = 1000000000UL;
static const uint32_t kJwtReconnectSafetyMarginSecs = 60UL;
static const uint32_t kJwtClockThreshold = 1735689600UL; // 2025-01-01 UTC
// A wall clock at or past this instant was set from a real source (NTP or an
// admin); anything earlier is the firmware's unset-clock default (1715770351,
@@ -157,6 +158,23 @@ static inline bool tokenNeedsRenewal(bool time_synced, uint32_t current_time,
return current_time >= token_expires_at - renewal_buffer_secs;
}
// Reuse credentials only when their validity is known to outlast the next
// handshake. Uncertain credentials are refreshed before reconnecting.
static inline bool canReuseJwtForReconnect(bool time_synced, bool has_token,
bool force_mint,
uint32_t current_time,
uint32_t token_expires_at,
uint32_t renewal_buffer_secs) {
const uint32_t floor_secs =
renewal_buffer_secs > UINT32_MAX - kJwtReconnectSafetyMarginSecs
? UINT32_MAX
: renewal_buffer_secs + kJwtReconnectSafetyMarginSecs;
return time_synced && has_token && !force_mint &&
token_expires_at >= kMinimumValidEpoch &&
current_time < token_expires_at &&
(token_expires_at - current_time) > floor_secs;
}
static inline bool renewalAttemptAllowed(uint32_t now, uint32_t last_attempt) {
return elapsedMs(now, last_attempt) >= kRenewalThrottleMs;
}
@@ -196,4 +214,40 @@ static inline SlotActivation classifySlotActivation(int slot, const bool* enable
: SlotActivation::OverActiveCap;
}
enum class StaleTokenAction : uint8_t {
Defer,
Reconnect,
Bounce,
KeepAlive,
};
// A failed mint must not reconnect with credentials that a clock correction
// just invalidated. A live session only needs a bounce when its broker enforces
// token expiration on the existing connection.
static inline StaleTokenAction classifyStaleToken(bool minted, bool connected,
bool broker_enforces_exp) {
if (!minted) return StaleTokenAction::Defer;
if (!connected) return StaleTokenAction::Reconnect;
return broker_enforces_exp ? StaleTokenAction::Bounce
: StaleTokenAction::KeepAlive;
}
enum class ClockSource : uint8_t {
None,
System,
Rtc,
};
// Prefer a plausible system clock, then an RTC. Server validation may not use
// a local clock as evidence that the requested NTP host answered.
static inline ClockSource chooseFallbackClock(bool validating_server,
uint32_t system_time,
uint32_t rtc_time,
uint32_t min_valid_epoch) {
if (validating_server) return ClockSource::None;
if (system_time >= min_valid_epoch) return ClockSource::System;
if (rtc_time >= min_valid_epoch) return ClockSource::Rtc;
return ClockSource::None;
}
} // namespace MQTTConnectionPolicy
+3 -2
View File
@@ -205,6 +205,7 @@ int MQTTMessageBuilder::buildPacketJSON(
// Routing path (direct packets only): pass raw hop bytes to buildPacketMessage,
// which emits them as an array of lowercase hex hop tokens.
bool has_path = packet->isRouteDirect() && packet->getPathHashCount() > 0;
const bool has_rx_metrics = !is_tx && packet->getRSSI() < 0;
return buildPacketMessage(
doc,
@@ -215,8 +216,8 @@ int MQTTMessageBuilder::buildPacketJSON(
packet_type, route_str,
packet->payload_len,
raw_hex,
12.5f, // SNR - using reasonable default
-65, // RSSI - using reasonable default
has_rx_metrics ? packet->getSNR() : -999.0f,
has_rx_metrics ? packet->getRSSI() : -999,
NAN, // score - unknown on this reconstruction-less fallback path
hash_str,
has_path ? packet->path : nullptr,
+11 -5
View File
@@ -121,9 +121,6 @@ int MQTTPayloadBuilder::buildPacketMessage(
snprintf(len_str, sizeof(len_str), "%d", len);
snprintf(packet_type_str, sizeof(packet_type_str), "%d", packet_type);
snprintf(payload_len_str, sizeof(payload_len_str), "%d", payload_len);
StrHelper::ftoaFixed(snr_str, sizeof(snr_str), snr, 1);
snprintf(rssi_str, sizeof(rssi_str), "%d", rssi);
root["timestamp"] = timestamp;
root["hash"] = hash;
root["origin"] = origin;
@@ -139,8 +136,14 @@ int MQTTPayloadBuilder::buildPacketMessage(
root["origin_id"] = origin_id;
if (direction && strcmp(direction, "rx") == 0) {
root["SNR"] = snr_str;
root["RSSI"] = rssi_str;
if (snr > -900.0f) {
StrHelper::ftoaFixed(snr_str, sizeof(snr_str), snr, 1);
root["SNR"] = snr_str;
}
if (rssi > -900) {
snprintf(rssi_str, sizeof(rssi_str), "%d", rssi);
root["RSSI"] = rssi_str;
}
if (!isnan(score)) {
snprintf(score_str, sizeof(score_str), "%d", static_cast<int>(score * 1000));
root["score"] = score_str;
@@ -222,6 +225,9 @@ static void addNeighborsMessageEntry(
JsonObject nb = arr.add<JsonObject>();
nb["pubkey"] = neighbor.pubkey_hex;
nb["snr"] = neighbor.snr;
if (neighbor.rssi < 0) {
nb["rssi"] = neighbor.rssi;
}
if (neighbor.heard_unknown) {
nb["heard_secs_ago"] = nullptr; // age unknown, not zero
} else {
+1
View File
@@ -76,6 +76,7 @@ public:
uint32_t heard_secs_ago;
const char* scopes;
const char* status;
int rssi; // dBm; non-negative means no measurement is available
// True renders heard_secs_ago as JSON null, for a neighbour whose stored
// stamp cannot yield an age. No default initializer: the struct stays an
// aggregate for the device toolchain, and a zeroed tail means "age known",
+8
View File
@@ -54,6 +54,14 @@ struct MQTTPresetDef {
// Braces match topic placeholders ({device}/{iata}); never send this string to the broker.
static const char MQTT_USERPASS_USERNAME_PUBKEY[] = "{pubkey}";
// Most brokers enforce JWT expiration on a live connection and need a
// proactive credential bounce. Waev keeps an established session alive, so
// refreshing credentials in place avoids an unnecessary TLS handshake.
static inline bool mqttPresetEnforcesTokenExp(const MQTTPresetDef* preset) {
if (!preset || !preset->name) return true;
return strcmp(preset->name, "waev") != 0;
}
static inline bool mqttPresetUsesDevicePubkeyUsername(const MQTTPresetDef* preset) {
return preset && preset->auth_type == MQTT_AUTH_USERPASS &&
preset->userpass_username &&
+6
View File
@@ -2,6 +2,7 @@
#include <stddef.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
// Bounded, clamping printf-append for the fixed-size CLI reply buffers used by
@@ -41,3 +42,8 @@ static inline void replyAppendf(char* buf, size_t bufsize, int* pos, const char*
*pos += n;
if ((size_t)*pos >= bufsize) *pos = (int)bufsize - 1; // clamp truncated append
}
static inline uint32_t mbedtlsErrorMagnitude(int32_t stack_err) {
return stack_err < 0 ? (uint32_t)(-(int64_t)stack_err)
: (uint32_t)stack_err;
}
+137
View File
@@ -0,0 +1,137 @@
#pragma once
#include <Arduino.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
namespace mesh {
// A USB CDC host can leave a port open without draining it. Some platform
// implementations then wait indefinitely inside write(), which stalls the
// mesh loop. Packet log lines use this bounded writer so a stalled host costs
// a diagnostic line instead of radio service.
#ifndef SERIAL_LOG_LINE_MAX
#define SERIAL_LOG_LINE_MAX 640
#endif
#ifndef SERIAL_LOG_WRITE_BUDGET_MS
#define SERIAL_LOG_WRITE_BUDGET_MS 20
#endif
inline uint32_t& serialLogDroppedCount() {
static uint32_t count = 0;
return count;
}
inline bool& serialLogPortSeen() {
static bool seen = false;
return seen;
}
template <class T>
bool serialLogEmit(T& out, const char* data, size_t len) {
if (out.availableForWrite() <= 0) return false;
const uint32_t start = millis();
size_t sent = 0;
while (sent < len) {
int space = out.availableForWrite();
if (space <= 0) {
if ((uint32_t)(millis() - start) >= SERIAL_LOG_WRITE_BUDGET_MS) {
return false;
}
delay(1);
continue;
}
size_t chunk = (size_t)space;
if (chunk > len - sent) chunk = len - sent;
size_t written = out.write(
reinterpret_cast<const uint8_t*>(data + sent), chunk);
if (written == 0) return false;
sent += written;
}
serialLogPortSeen() = true;
return true;
}
template <size_t CAP = SERIAL_LOG_LINE_MAX>
class SerialLogLine {
public:
static_assert(CAP >= 3, "SerialLogLine needs room for text and CRLF");
void printf(const char* format, ...) {
size_t room = capacity() - _len;
if (room == 0) {
_truncated = true;
return;
}
va_list args;
va_start(args, format);
int count = vsnprintf(&_buffer[_len], room, format, args);
va_end(args);
if (count < 0) return;
if ((size_t)count >= room) {
_len = capacity() - 1;
_truncated = true;
} else {
_len += (size_t)count;
}
}
void hex(const uint8_t* source, size_t len) {
static const char digits[] = "0123456789ABCDEF";
while (len > 0) {
if (_len + 2 > capacity()) {
_truncated = true;
return;
}
uint8_t value = *source++;
_buffer[_len++] = digits[value >> 4];
_buffer[_len++] = digits[value & 0x0F];
len--;
}
}
// Preserve the compact packet logger's LF-only wire format when requested.
template <class T>
bool flush(T& out, bool use_crlf = true) {
bool complete = !_truncated;
if (use_crlf) _buffer[_len++] = '\r';
_buffer[_len++] = '\n';
const size_t line_len = _len;
_len = 0;
_truncated = false;
uint32_t& dropped = serialLogDroppedCount();
if (dropped > 0) {
char marker[24];
int count = snprintf(marker, sizeof(marker), "DROP:%u\r\n",
(unsigned)dropped);
if (count > 0 && serialLogEmit(out, marker, (size_t)count)) dropped = 0;
}
if (!serialLogEmit(out, _buffer, line_len)) complete = false;
if (!complete && serialLogPortSeen()) dropped++;
return complete;
}
private:
size_t capacity() const { return CAP - 2; }
char _buffer[CAP];
size_t _len = 0;
bool _truncated = false;
};
inline void serialLogBegin() {
#if defined(ESP32_PLATFORM) && defined(ARDUINO_USB_CDC_ON_BOOT) && \
(ARDUINO_USB_CDC_ON_BOOT == 1)
Serial.setTxTimeoutMs(0);
#endif
}
} // namespace mesh
+8
View File
@@ -34,7 +34,14 @@
namespace mesh {
#if defined(COMPANION_RADIO_FULL)
// Full Companion owns its primary USB stream for framed traffic until saved
// preferences are loaded. Starting disabled prevents early boot diagnostics
// from corrupting that stream before single-TTY builds can enter terminal mode.
static std::atomic<bool> usb_logging_enabled{false};
#else
static std::atomic<bool> usb_logging_enabled{true};
#endif
static std::atomic<bool> usb_logging_preference_known{false};
class NullUsbLoggingStream : public Stream {
@@ -151,6 +158,7 @@ void beginUsbLoggingPort() {
// A terminal opening or closing the diagnostics interface must never reboot
// the node or put it into the ROM downloader.
dedicated_usb_logging_port->enableReboot(false);
dedicated_usb_logging_port->setTxTimeoutMs(0);
dedicated_usb_logging_port->begin(115200);
#elif defined(MESH_NRF52_DUAL_CDC_LOGGING)
dedicated_usb_logging_port.begin(115200);
+4 -5
View File
@@ -12,11 +12,11 @@
#endif
#if defined(ARDUINO)
class Stream;
#include <Arduino.h>
namespace mesh {
// Ordinary logging images start enabled. Dual-CDC Full Companion starts with
// Ordinary logging images start enabled. Every Full Companion starts with
// logging disabled and restores its saved choice after preferences load.
bool isUsbLoggingEnabled();
void setUsbLoggingEnabled(bool enabled);
@@ -26,9 +26,8 @@ void setUsbLoggingEnabled(bool enabled);
// mirror. Returns false only when that mirror could not be saved.
bool saveUsbLoggingBootPreference(bool enabled);
// Start the optional dedicated USB logging interface. Ordinary builds keep
// using Serial. Supported Full Companion builds expose a second CDC ACM
// interface so plaintext diagnostics never share the framed Companion stream.
// Start the optional dedicated USB logging interface. Ordinary and single-TTY
// builds use Serial; dual-CDC Full Companion builds use a second CDC ACM port.
void beginUsbLoggingPort();
Stream& usbLoggingPort();
bool hasDedicatedUsbLoggingPort();
+239 -76
View File
@@ -23,6 +23,7 @@
#ifdef ESP_PLATFORM
#include <esp_wifi.h>
#include <esp_sntp.h>
#include <esp_heap_caps.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
@@ -583,7 +584,8 @@ void MQTTBridge::formatSlotDiagReply(char* buf, size_t bufsize, int slot_index)
}
// mbedTLS stack error (shown as negative hex per convention)
if (slot.last_tls_stack_err != 0) {
replyAppendf(buf, bufsize, &pos, ", mbedtls:-0x%04X", (unsigned)(-slot.last_tls_stack_err));
replyAppendf(buf, bufsize, &pos, ", mbedtls:-0x%04X",
(unsigned)mbedtlsErrorMagnitude(slot.last_tls_stack_err));
}
// Socket errno
if (slot.last_sock_errno != 0) {
@@ -688,7 +690,7 @@ MQTTBridge::MQTTBridge(const MQTTNodeInfo& node_info, MQTTPrefs *obs,
_snmp_agent(nullptr),
#endif
_last_wifi_check(0), _last_wifi_status(WL_DISCONNECTED), _wifi_status_initialized(false),
_wifi_disconnected_time(0), _last_wifi_reconnect_attempt(0), _wifi_reconnect_backoff_attempt(0),
_wifi_outage_bits{0}, _last_wifi_reconnect_attempt(0), _wifi_reconnect_backoff_attempt(0),
_last_slot_reconnect_ms(0)
#ifdef ESP_PLATFORM
, _packet_queue_handle(nullptr), _mqtt_task_handle(nullptr),
@@ -733,6 +735,7 @@ MQTTBridge::MQTTBridge(const MQTTNodeInfo& node_info, MQTTPrefs *obs,
_slots[i].last_log_time = 0;
_slots[i].port = 1883;
_slot_reconfigure_pending[i] = false;
_slot_force_jwt_mint[i] = false;
_status_publish_pending[i] = false;
}
@@ -797,17 +800,8 @@ void MQTTBridge::allocateRuntimeBuffers() {
_json_scratch_buffer ? "PSRAM" : "stack fallback");
#endif
#if defined(WITH_MQTT_NEIGHBORS)
// Persistent neighbors JSON buffer, heap-allocated on every board: too large to
// keep inline in the bridge object the way the non-PSRAM status/packet buffers
// are. psram_malloc() falls back to internal DRAM, so this works without PSRAM.
// Unlike status/packet there is no stack fallback -- a nullptr simply disables
// publishing (requestPublishNeighbors/publishNeighbors both no-op on nullptr).
_neighbors_json_buffer = static_cast<char*>(MQTTRuntimeBufferLifecycle::allocateIfMissing(
_neighbors_json_buffer, NEIGHBORS_JSON_BUFFER_SIZE, psram_malloc));
MQTT_DEBUG_PRINTLN("Neighbors buffer: %s",
_neighbors_json_buffer ? "ready" : "unavailable");
#endif
// The neighbors JSON buffer is allocated lazily by requestPublishNeighbors().
// Nodes which never publish neighbors do not spend this memory.
}
void MQTTBridge::releaseRuntimeBuffers() {
@@ -824,7 +818,7 @@ void MQTTBridge::releaseRuntimeBuffers() {
_json_scratch_doc.clear();
#if defined(WITH_MQTT_NEIGHBORS)
// Paired with the unconditional allocation in allocateRuntimeBuffers().
// Paired with the lazy allocation in requestPublishNeighbors().
_neighbors_json_buffer = static_cast<char*>(MQTTRuntimeBufferLifecycle::release(
_neighbors_json_buffer, psram_free));
_neighbors_publish_len = 0;
@@ -993,6 +987,17 @@ void MQTTBridge::begin() {
_slots[i].enabled = false;
}
}
} else {
// Preferences are authoritative across bridge restarts. teardownSlot()
// intentionally preserves configuration for reuse, so explicitly clear
// fields for a slot that is now disabled.
_slots[i].enabled = false;
_slots[i].preset = nullptr;
_slots[i].host[0] = '\0';
_slots[i].username[0] = '\0';
_slots[i].password[0] = '\0';
_slots[i].audience[0] = '\0';
_slots[i].port = 0;
}
}
@@ -1217,8 +1222,10 @@ void MQTTBridge::LifecycleOps::releaseResources() {
if (b->_mqtt_task_handle != nullptr) {
vTaskDelete(b->_mqtt_task_handle);
}
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) b->teardownSlot(i);
b->destroySlotClients();
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
b->teardownSlot(i, /*force=*/true);
}
b->destroySlotClients(/*force=*/true);
}
// Clean path (or a task that acked right at the deadline): the MQTT task
// already disconnected/deleted its clients on Core 0 and self-terminated, so
@@ -1297,16 +1304,23 @@ void MQTTBridge::initializeWiFiInTask() {
switch(event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
MQTT_DEBUG_PRINTLN("WiFi connected: %s", IPAddress(info.got_ip.ip_info.ip.addr).toString().c_str());
setWifiOutage(AlertFaultPolicy::applyWifiGotIp(wifiOutage()));
_wifi_reconnect_backoff_attempt = 0;
// Set flag to trigger NTP sync from loop() instead of doing it here
if (!_ntp_synced && !_ntp_sync_pending) {
_ntp_sync_pending = true;
}
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
s_wifi_disconnect_reason = info.wifi_sta_disconnected.reason;
s_wifi_disconnect_time = millis();
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: {
const uint8_t reason = info.wifi_sta_disconnected.reason;
const unsigned long event_time = millis();
s_wifi_disconnect_reason = reason;
s_wifi_disconnect_time = event_time;
setWifiOutage(AlertFaultPolicy::applyWifiDisconnectEvent(
(uint32_t)event_time, reason, wifiOutage()));
MQTT_DEBUG_PRINTLN("WiFi disconnected: reason %d", s_wifi_disconnect_reason);
break;
}
default:
break;
}
@@ -1677,6 +1691,7 @@ bool MQTTBridge::ensureSlotClient(int index) {
slot.client->onConnect([this, index](bool sessionPresent) {
MQTT_DEBUG_PRINTLN("MQTT%d connected", index + 1);
_slots[index].connected = true;
_slot_force_jwt_mint[index] = false;
// NOTE: reconnect_backoff / max_backoff_failures are NOT reset here.
// A CONNACK alone doesn't prove the link is healthy -- a broker that
// accepts and then drops within seconds would reset the ladder every
@@ -1723,6 +1738,7 @@ bool MQTTBridge::ensureSlotClient(int index) {
_slots[index].last_sock_errno = error.esp_transport_sock_errno;
_slots[index].last_error_time = millis();
if (error.error_type == MQTT_ERROR_TYPE_CONNECTION_REFUSED) {
_slot_force_jwt_mint[index] = true;
// Broker rejected the MQTT CONNECT itself -- not a transport failure.
// return code: 1=protocol, 2=client-id rejected, 3=server unavailable,
// 4=bad username/password, 5=not authorized. Codes 3/4/5 point at a
@@ -1779,11 +1795,13 @@ void MQTTBridge::releaseSlotAuthToken(int index) {
slot.last_token_renewal = 0;
}
void MQTTBridge::destroySlotClients() {
void MQTTBridge::destroySlotClients(bool force) {
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
MQTTSlot& slot = _slots[i];
if (slot.client != nullptr) {
if (slot.client->connected()) {
if (force) {
slot.client->forceStop();
} else if (slot.client->connected()) {
slot.client->disconnect();
}
#ifdef ESP_PLATFORM
@@ -1875,6 +1893,7 @@ bool MQTTBridge::setupSlot(int index) {
slot.max_backoff_failures = 0;
slot.circuit_breaker_tripped = false;
slot.last_reconnect_attempt = 0;
_slot_force_jwt_mint[index] = false;
}
bool uses_jwt = (slot.preset && slot.preset->auth_type == MQTT_AUTH_JWT) || slot.audience[0] != '\0';
@@ -2043,12 +2062,16 @@ bool MQTTBridge::setupSlot(int index) {
// the client object alive so a subsequent setupSlot() can reuse its mbedTLS
// context. This is called both on reconfigure (preset change) and at shutdown;
// destruction of the underlying client happens once in destroySlotClients().
void MQTTBridge::teardownSlot(int index) {
void MQTTBridge::teardownSlot(int index, bool force) {
if (index < 0 || index >= RUNTIME_MQTT_SLOTS) return;
MQTTSlot& slot = _slots[index];
if (slot.client && slot.client->connected()) {
slot.client->disconnect();
if (slot.client && (force || slot.client->connected())) {
if (force) {
slot.client->forceStop();
} else {
slot.client->disconnect();
}
#ifdef ESP_PLATFORM
vTaskDelay(pdMS_TO_TICKS(50));
#else
@@ -2070,6 +2093,20 @@ void MQTTBridge::teardownSlot(int index) {
slot.last_reconnect_attempt = 0;
slot.last_log_time = 0;
slot.last_deferred_log_ms = 0;
_slot_force_jwt_mint[index] = false;
}
void MQTTBridge::reconnectSlotClient(int index) {
if (index < 0 || index >= RUNTIME_MQTT_SLOTS) return;
MQTTSlot& slot = _slots[index];
if (slot.client == nullptr) return;
if (!slot.client->isStarted()) {
MQTT_DEBUG_PRINTLN("MQTT%d start (client was stopped)", index + 1);
slot.client->connect();
return;
}
slot.client->reconnect();
}
void MQTTBridge::maintainSlotConnections() {
@@ -2211,15 +2248,26 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
(time_synced && old_token_expires_at >= 1000000000 &&
current_time >= (old_token_expires_at - renewal_buffer));
if (old_token_expired_or_imminent || !slot.client->connected()) {
// Disconnect + reconnect with fresh credentials, reusing existing client
// to avoid internal heap leak/fragmentation from destroy/create cycles
const bool exp_forces_bounce =
old_token_expired_or_imminent &&
mqttPresetEnforcesTokenExp(slot.preset);
if (!exp_forces_bounce && old_token_expired_or_imminent &&
slot.client->connected()) {
MQTT_DEBUG_PRINTLN(
"MQTT%d token renewed, no bounce (broker does not enforce exp)",
index + 1);
}
if (exp_forces_bounce || !slot.client->connected()) {
MQTT_DEBUG_PRINTLN("MQTT%d token renewal: reconnecting with fresh credentials", index + 1);
if (slot.client->connected()) {
slot.client->disconnect(); // stops the client internally
if (slot.client->isStarted()) {
// Retain the esp-mqtt task and its stack across the TLS handshake.
slot.client->softDisconnect();
slot.client->setCredentials(_jwt_username, slot.auth_token);
slot.client->reconnect();
} else {
slot.client->setCredentials(_jwt_username, slot.auth_token);
slot.client->connect();
}
slot.client->setCredentials(_jwt_username, slot.auth_token);
slot.client->connect(); // restart stopped client; reconnect() fails silently on a stopped client
reconnect_attempted = true;
_last_slot_reconnect_ms = now_millis;
MQTT_DEBUG_PRINTLN("MQTT%d int_heap=%d at token renewal reconnect", index + 1,
@@ -2244,6 +2292,64 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
// persistent clients (Phase 1), the mbedTLS context is allocated once at
// startup and the preflight is no longer necessary.
const auto prepareJwtReconnect = [&](bool force_mint, int backoff_level) {
const bool has_token = slot.auth_token && slot.auth_token[0] != '\0';
const unsigned long expires_at = slot.token_expires_at;
const bool remaining_known =
time_synced && expires_at >= MQTTConnectionPolicy::kMinimumValidEpoch;
const unsigned long remaining_secs =
current_time < expires_at ? expires_at - current_time : 0;
const bool force_after_refusal = _slot_force_jwt_mint[index];
force_mint = force_mint || force_after_refusal;
const uint32_t renewal_buffer = MQTTConnectionPolicy::renewalBufferSecs(
static_cast<uint32_t>(slotTokenLifetime(index)));
const bool reuse_token = MQTTConnectionPolicy::canReuseJwtForReconnect(
time_synced, has_token, force_mint,
static_cast<uint32_t>(current_time),
static_cast<uint32_t>(expires_at), renewal_buffer);
const char* mint_reason = "none";
if (!reuse_token) {
if (backoff_level < 0) {
mint_reason = "circuit-breaker-probe";
} else if (force_after_refusal) {
mint_reason = "connection-refused";
} else if (!time_synced) {
mint_reason = "clock-unsynced";
} else if (!has_token) {
mint_reason = "empty-token";
} else if (expires_at < MQTTConnectionPolicy::kMinimumValidEpoch) {
mint_reason = "invalid-expiry";
} else if (current_time >= expires_at) {
mint_reason = "expired";
} else if (remaining_secs <=
MQTTConnectionPolicy::kJwtReconnectSafetyMarginSecs) {
mint_reason = "safety-margin";
} else if (remaining_secs <= renewal_buffer) {
mint_reason = "renewal-due";
} else {
mint_reason = "renewal-imminent";
}
}
const char* mint_result = reuse_token ? "REUSED" : "FAILED";
if (!reuse_token && createSlotAuthToken(index)) {
slot.client->setCredentials(_jwt_username, slot.auth_token);
mint_result = "OK";
}
char remaining_text[24];
if (remaining_known) {
snprintf(remaining_text, sizeof(remaining_text), "%lus", remaining_secs);
} else {
strncpy(remaining_text, "unknown", sizeof(remaining_text));
remaining_text[sizeof(remaining_text) - 1] = '\0';
}
MQTT_DEBUG_PRINTLN(
"MQTT%d JWT reconnect backoff=%d token=%s mint_reason=%s result=%s remaining=%s",
index + 1, backoff_level, reuse_token ? "REUSE" : "MINT",
mint_reason, mint_result, remaining_text);
};
// Periodic probe for circuit-breaker-tripped slots (recovery from transient outages)
// Attempts a single reconnect every 30 minutes to see if the server has come back
if (slot.circuit_breaker_tripped && !reconnect_attempted) {
@@ -2260,17 +2366,9 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
_radio ? _radio->getRadioState() : -1,
(_radio && _radio->getLastRecvMillis() > 0) ? (_ms->getMillis() - _radio->getLastRecvMillis()) : 0);
if (slot_uses_jwt) {
// Regenerate or refresh token, then reconnect the persistent client.
// Reaching the ladder at all means setupSlot() ran, so the client object
// and its mbedTLS context are live and no full setup is needed here.
if (createSlotAuthToken(index)) {
slot.client->setCredentials(_jwt_username, slot.auth_token);
MQTT_DEBUG_PRINTLN("MQTT%d circuit breaker probe (fresh token)", index + 1);
}
slot.client->reconnect();
} else {
slot.client->reconnect();
prepareJwtReconnect(true, -1);
}
reconnectSlotClient(index);
// If the connect callback fires and sets slot.connected = true,
// it will clear circuit_breaker_tripped via the onConnect handler
}
@@ -2300,22 +2398,12 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
reconnect_attempted = true;
_last_slot_reconnect_ms = now_millis;
if (slot_uses_jwt) {
// Always lightweight reconnect on the persistent client. A stale/expired
// token is handled by regenerating it in place and updating credentials
// - no teardown is needed because the client and its mbedTLS context
// persist for the bridge lifetime.
if (createSlotAuthToken(index)) {
slot.client->setCredentials(_jwt_username, slot.auth_token);
MQTT_DEBUG_PRINTLN("MQTT%d reconnect (fresh token, backoff %d)", index + 1, slot.reconnect_backoff);
} else {
MQTT_DEBUG_PRINTLN("MQTT%d reconnect (token refresh failed, backoff %d)", index + 1, slot.reconnect_backoff);
}
slot.client->reconnect();
prepareJwtReconnect(false, slot.reconnect_backoff);
} else {
// Non-JWT slots - lightweight reconnect on existing client.
MQTT_DEBUG_PRINTLN("MQTT%d reconnect (non-JWT, backoff %d)", index + 1, slot.reconnect_backoff);
slot.client->reconnect();
}
reconnectSlotClient(index);
}
}
}
@@ -2750,11 +2838,17 @@ bool MQTTBridge::handleWiFiConnection(unsigned long now) {
if (!_wifi_status_initialized) {
_last_wifi_status = current_wifi_status;
_wifi_status_initialized = true;
if (current_wifi_status != WL_CONNECTED) {
_wifi_disconnected_time = now;
}
setWifiOutage(AlertFaultPolicy::applyWifiStatus(
(uint32_t)now, current_wifi_status == WL_CONNECTED, wifiOutage(),
false));
}
if (now - _last_wifi_check <= 10000) {
if (current_wifi_status == WL_CONNECTED) {
AlertFaultPolicy::OutageSnapshot snapshot = wifiOutage();
if (snapshot.down) {
setWifiOutage(AlertFaultPolicy::applyWifiGotIp(snapshot));
}
}
return false;
}
_last_wifi_check = now;
@@ -2762,7 +2856,8 @@ bool MQTTBridge::handleWiFiConnection(unsigned long now) {
if (current_wifi_status == WL_CONNECTED) {
if (_last_wifi_status != WL_CONNECTED) {
transitioned_to_connected = true;
_wifi_disconnected_time = 0;
setWifiOutage(AlertFaultPolicy::applyWifiStatus(
(uint32_t)now, true, wifiOutage(), true));
s_wifi_connected_at = now;
_wifi_reconnect_backoff_attempt = 0;
#ifdef ESP_PLATFORM
@@ -2795,8 +2890,12 @@ bool MQTTBridge::handleWiFiConnection(unsigned long now) {
}
_last_wifi_status = WL_CONNECTED;
} else {
if (_last_wifi_status == WL_CONNECTED) {
_wifi_disconnected_time = now;
const bool last_connected = (_last_wifi_status == WL_CONNECTED);
AlertFaultPolicy::OutageSnapshot snapshot =
AlertFaultPolicy::applyWifiStatus(
(uint32_t)now, false, wifiOutage(), true);
setWifiOutage(snapshot);
if (last_connected) {
s_wifi_connected_at = 0;
// Disconnect all slot clients when WiFi drops
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
@@ -2804,13 +2903,13 @@ bool MQTTBridge::handleWiFiConnection(unsigned long now) {
_slots[i].client->disconnect();
}
}
} else if (_wifi_disconnected_time > 0) {
} else if (snapshot.down) {
// Backoff ladder + wrap-safe timing live in MQTTConnectionPolicy (Phase 6),
// exercised by host tests. Behavior is unchanged: both the link-down
// duration and the since-last-attempt interval must clear the current rung
// (elapsedMs is the wrap-safe form of the old ULONG_MAX branch).
if (_manage_wifi && MQTTConnectionPolicy::wifiReconnectDue(
(uint32_t)now, (uint32_t)_wifi_disconnected_time,
(uint32_t)now, snapshot.started_ms,
(uint32_t)_last_wifi_reconnect_attempt,
_wifi_reconnect_backoff_attempt)) {
_last_wifi_reconnect_attempt = now;
@@ -3718,10 +3817,20 @@ void MQTTBridge::setNeighborsSchedule(NeighborsPhase phase, uint32_t secs_until_
}
void MQTTBridge::requestPublishNeighbors(const char* json, size_t len) {
if (!_neighbors_json_buffer || !json || len == 0) return;
if (!json || len == 0) return;
// Drop a new snapshot while one is still being published (Core 0 clears the
// flag when done). Acquire pairs with the task loop's release store.
if (_neighbors_publish_pending.load(std::memory_order_acquire)) return;
// A discovery can finish after bridge shutdown. Do not allocate a buffer
// which has no task left to consume or release it.
if (!isRunning()) return;
_neighbors_json_buffer = static_cast<char*>(
MQTTRuntimeBufferLifecycle::allocateIfMissing(
_neighbors_json_buffer, NEIGHBORS_JSON_BUFFER_SIZE, psram_malloc));
if (!_neighbors_json_buffer) {
MQTT_DEBUG_PRINTLN("Neighbors buffer unavailable, dropping snapshot");
return;
}
if (len >= NEIGHBORS_JSON_BUFFER_SIZE) {
len = NEIGHBORS_JSON_BUFFER_SIZE - 1;
}
@@ -3952,15 +4061,20 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
const int kMaxNtpRetriesPerServer = 2;
for (int s = 0; s < server_count && !ntp_ok; s++) {
const char* server = servers[s];
_ntp_client.setPoolServerName(server);
#ifdef ESP_PLATFORM
IPAddress resolved_ip;
if (!WiFi.hostByName(server, resolved_ip)) {
MQTT_DEBUG_PRINTLN("WARNING: DNS resolution failed for %s - NTP sync may fail", server);
// NTPClient ignores a failed beginPacket(), while WiFiUDP retains the
// prior remote address. Sending here could credit the previous server
// to this unresolvable name.
MQTT_DEBUG_PRINTLN("NTP: %s does not resolve - skipping", server);
continue;
}
#endif
_ntp_client.setPoolServerName(server);
for (int attempt = 1; attempt <= kMaxNtpRetriesPerServer && !ntp_ok; attempt++) {
if (attempt > 1) {
MQTT_DEBUG_PRINTLN("NTP retry %d/%d on %s...", attempt, kMaxNtpRetriesPerServer, server);
@@ -3984,23 +4098,55 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
for (int s = 0; s < server_count && !ntp_ok; s++) {
const char* server = servers[s];
MQTT_DEBUG_PRINTLN("SNTP fallback trying %s...", server);
if (sntp_enabled()) sntp_stop();
sntp_set_sync_status(SNTP_SYNC_STATUS_RESET);
configTime(0, 0, server);
for (int i = 0; i < 20; i++) {
delay(500);
if (sntp_get_sync_status() != SNTP_SYNC_STATUS_COMPLETED) continue;
epochTime = (unsigned long)time(nullptr);
if (epochTime >= kMinValidEpoch) {
ntp_ok = true;
ntp_server_used = server;
MQTT_DEBUG_PRINTLN("SNTP fallback succeeded on %s: %lu", server, epochTime);
break;
} else {
MQTT_DEBUG_PRINTLN(
"SNTP fallback: %s synced an implausible epoch %lu", server,
epochTime);
}
break;
}
}
}
#endif
if (ntp_ok && ntp_server_used) {
configTime(0, 0, ntp_server_used);
if (!ntp_ok) {
const unsigned long system_time = (unsigned long)time(nullptr);
const unsigned long rtc_time =
_rtc ? (unsigned long)_rtc->getCurrentTime() : 0;
const MQTTConnectionPolicy::ClockSource source =
MQTTConnectionPolicy::chooseFallbackClock(
primary_only, (uint32_t)system_time, (uint32_t)rtc_time,
(uint32_t)kMinValidEpoch);
if (source != MQTTConnectionPolicy::ClockSource::None) {
const bool from_rtc = source == MQTTConnectionPolicy::ClockSource::Rtc;
epochTime = from_rtc ? rtc_time : system_time;
ntp_ok = true;
MQTT_DEBUG_PRINTLN(
"No NTP server answered; continuing on the existing %s: %lu",
from_rtc ? "RTC" : "system clock", epochTime);
}
}
if (ntp_ok) {
// Make the accepted epoch authoritative before stale-token checks or JWT
// creation read time(nullptr). configTime() itself is asynchronous.
struct timeval accepted;
accepted.tv_sec = (time_t)epochTime;
accepted.tv_usec = 0;
settimeofday(&accepted, nullptr);
if (ntp_server_used) configTime(0, 0, ntp_server_used);
if (_rtc) {
_rtc->setCurrentTime(epochTime);
@@ -4011,11 +4157,11 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
_last_ntp_sync = millis();
sync_in_progress = false;
MQTT_DEBUG_PRINTLN("Time synced: %lu (via %s)", epochTime, ntp_server_used);
MQTT_DEBUG_PRINTLN("Time synced: %lu (via %s)", epochTime,
ntp_server_used ? ntp_server_used : "existing clock");
// If slots are already set up and the time jumped significantly (e.g., SNTP
// initially returned stale RTC time, then a later sync corrected it), tear down
// and re-setup all JWT-authenticated slots so they get fresh tokens.
// If a correction made an existing JWT stale, stage fresh credentials and
// choose the reconnect action appropriate to the client and broker state.
if (_slots_setup_done && was_ntp_synced) {
unsigned long current_time = (unsigned long)time(nullptr);
// Every slot, not _max_active_slots: that is a count of positions, never an
@@ -4028,14 +4174,31 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
bool slot_jwt = (_slots[i].preset && _slots[i].preset->auth_type == MQTT_AUTH_JWT) ||
(!_slots[i].preset && _slots[i].audience[0] != '\0');
if (_slots[i].enabled && slot_jwt && _slots[i].client) {
// Token created before NTP corrected the clock - refresh credentials
// in place and reconnect the persistent client. No teardown needed.
if (_slots[i].token_expires_at > 0 && current_time > _slots[i].token_expires_at) {
MQTT_DEBUG_PRINTLN("MQTT%d token stale after time correction, re-creating", i + 1);
if (createSlotAuthToken(i)) {
_slots[i].client->setCredentials(_jwt_username, _slots[i].auth_token);
const MQTTConnectionPolicy::StaleTokenAction action =
MQTTConnectionPolicy::classifyStaleToken(
createSlotAuthToken(i), _slots[i].client->connected(),
mqttPresetEnforcesTokenExp(_slots[i].preset));
if (action == MQTTConnectionPolicy::StaleTokenAction::Defer) {
MQTT_DEBUG_PRINTLN(
"MQTT%d token refresh failed after time correction; deferring",
i + 1);
continue;
}
_slots[i].client->setCredentials(_jwt_username,
_slots[i].auth_token);
if (action == MQTTConnectionPolicy::StaleTokenAction::Reconnect) {
reconnectSlotClient(i);
} else if (action == MQTTConnectionPolicy::StaleTokenAction::Bounce) {
MQTT_DEBUG_PRINTLN(
"MQTT%d bouncing for the corrected-clock token", i + 1);
_slots[i].client->softDisconnect();
_slots[i].client->reconnect();
} else {
MQTT_DEBUG_PRINTLN(
"MQTT%d token re-created without a live-session bounce", i + 1);
}
_slots[i].client->reconnect();
}
}
}
+22 -3
View File
@@ -13,6 +13,7 @@
#include "helpers/MQTTPacketFilter.h"
#include "helpers/MQTTPresets.h"
#include "helpers/MQTTLifecycle.h"
#include "helpers/AlertFaultPolicy.h"
#include <atomic>
#ifdef WITH_SNMP
@@ -233,6 +234,10 @@ private:
// Pending slot reconfigure: set from CLI (Core 1), processed by MQTT task (Core 0)
volatile bool _slot_reconfigure_pending[RUNTIME_MQTT_SLOTS];
// A broker refusal can invalidate an otherwise clock-valid JWT. The event
// callback sets this byte and the bridge task consumes it.
volatile bool _slot_force_jwt_mint[RUNTIME_MQTT_SLOTS];
// Pending on-connect status publish: set from the onConnect callback (which
// runs on the esp-mqtt event task, NOT this bridge task), consumed by the MQTT
// task (Core 0). publishStatusToSlot() touches the shared status doc/buffer/
@@ -416,11 +421,20 @@ private:
unsigned long _last_wifi_check;
wl_status_t _last_wifi_status;
bool _wifi_status_initialized;
unsigned long _wifi_disconnected_time; // 0 when connected
std::atomic<uint64_t> _wifi_outage_bits;
unsigned long _last_wifi_reconnect_attempt;
uint8_t _wifi_reconnect_backoff_attempt; // 0..5 -> 15s, 30s, 60s, 120s, 300s; reset on connect
unsigned long _last_slot_reconnect_ms; // guards against concurrent TLS handshakes (15 s inter-slot gap)
AlertFaultPolicy::OutageSnapshot wifiOutage() const {
return AlertFaultPolicy::unpackOutageSnapshot(
_wifi_outage_bits.load(std::memory_order_acquire));
}
void setWifiOutage(AlertFaultPolicy::OutageSnapshot snapshot) {
_wifi_outage_bits.store(AlertFaultPolicy::packOutageSnapshot(snapshot),
std::memory_order_release);
}
// Optional pointers for collecting stats internally (set by mesh if available)
mesh::Dispatcher* _dispatcher; // For air times and errors
mesh::Radio* _radio; // For noise floor
@@ -449,7 +463,7 @@ private:
bool ensureSlotClient(int index); // Allocate this slot's persistent client + callbacks on first use
bool ensureSlotAuthToken(int index); // Allocate this slot's JWT token buffer on first token creation
void releaseSlotAuthToken(int index);// Free the token buffer (only with the client -- see MQTTSlot)
void destroySlotClients(); // Delete all persistent clients (shutdown only)
void destroySlotClients(bool force = false);
bool setupSlot(int index); // Configure and connect the slot; false = not activated
// Single definition of "this slot holds one of the _max_active_slots positions":
// it is enabled and has been through a successful setupSlot(). Startup, the
@@ -457,7 +471,8 @@ private:
// exceeded by one route while another enforces it.
int activatedSlotCount() const;
bool canActivateSlot(int index) const;
void teardownSlot(int index); // Disconnect the slot's client (keeps the object alive)
void teardownSlot(int index, bool force = false);
void reconnectSlotClient(int index);
void maintainSlotConnections(); // Maintain all slot connections (token renewal, reconnect)
void maintainSlotConnection(int index, unsigned long now_millis, unsigned long current_time, bool time_synced, bool& reconnect_attempted, bool& teardown_attempted);
bool createSlotAuthToken(int index); // Create/renew JWT token for a slot
@@ -650,6 +665,10 @@ public:
static unsigned long getWifiConnectedAtMillis();
AlertFaultPolicy::OutageSnapshot getWifiOutageSnapshot() const {
return wifiOutage();
}
/**
* Per-slot outage accessors used by AlertReporter to detect prolonged
* MQTT broker outages. Indices are 0..RUNTIME_MQTT_SLOTS-1.
+2 -2
View File
@@ -80,8 +80,8 @@ uint32_t ESPNOWRadio::getRngSeed() {
return millis() + intID(); // TODO: where to get some entropy?
}
void ESPNOWRadio::setTxPower(uint8_t dbm) {
esp_wifi_set_max_tx_power(dbm * 4);
bool ESPNOWRadio::setTxPower(int8_t dbm) {
return esp_wifi_set_max_tx_power(dbm * 4) == ESP_OK;
}
uint32_t ESPNOWRadio::intID() {
+1 -1
View File
@@ -59,7 +59,7 @@ public:
bool isCalibratingNoiseFloor() const { return false; }
uint32_t intID();
void setTxPower(uint8_t dbm);
bool setTxPower(int8_t dbm);
};
#if ESPNOW_DEBUG_LOGGING && ARDUINO
+23 -2
View File
@@ -36,11 +36,20 @@ ColorVal UIColor::corp_blue = 0x001A;
bool ST7789LCDDisplay::begin() {
if (!_isOn) {
if (_peripher_power) _peripher_power->claim();
if (_peripher_power) {
_peripher_power->claim();
#ifdef HELTEC_V4_R8_TFT
delay(100);
#endif
}
if (PIN_TFT_LEDA_CTL != -1) {
pinMode(PIN_TFT_LEDA_CTL, OUTPUT);
#ifdef HELTEC_V4_R8_TFT
digitalWrite(PIN_TFT_LEDA_CTL, !PIN_TFT_LEDA_CTL_ACTIVE);
#else
digitalWrite(PIN_TFT_LEDA_CTL, HIGH);
#endif
}
// Im not sure if this is just a t-deck problem or not, if your display is slow try this.
@@ -57,7 +66,13 @@ bool ST7789LCDDisplay::begin() {
display.setTextColor(ST77XX_WHITE);
display.setTextSize(2 * DISPLAY_SCALE_X);
display.cp437(true); // Use full 256 char 'Code Page 437' font
#ifdef HELTEC_V4_R8_TFT
if (PIN_TFT_LEDA_CTL != -1) {
digitalWrite(PIN_TFT_LEDA_CTL, PIN_TFT_LEDA_CTL_ACTIVE);
}
#endif
_isOn = true;
}
@@ -71,14 +86,20 @@ void ST7789LCDDisplay::turnOn() {
void ST7789LCDDisplay::turnOff() {
if (_isOn) {
if (PIN_TFT_LEDA_CTL != -1) {
#ifdef HELTEC_V4_R8_TFT
digitalWrite(PIN_TFT_LEDA_CTL, !PIN_TFT_LEDA_CTL_ACTIVE);
#else
digitalWrite(PIN_TFT_LEDA_CTL, HIGH);
#endif
}
if (PIN_TFT_RST != -1) {
digitalWrite(PIN_TFT_RST, LOW);
}
#ifndef HELTEC_V4_R8_TFT
if (PIN_TFT_LEDA_CTL != -1) {
digitalWrite(PIN_TFT_LEDA_CTL, LOW);
}
#endif
_isOn = false;
if (_peripher_power) _peripher_power->release();