Add repeater filtering, clock sync, and companion fixes

This commit is contained in:
mikecarper committed 2026-07-15 17:40:20 -07:00
1 parent 0d2eb2420c
commit 63776482e1
30 files changed
+2757 -65

No files matched your search

+24
View File
@@ -8,6 +8,12 @@
namespace mesh {
enum class RadioParamApplyResult : uint8_t {
APPLIED,
BUSY,
FAILED
};
/**
* \brief Abstraction of local/volatile clock with Millisecond granularity.
*/
@@ -89,6 +95,24 @@ public:
virtual bool supportsRxPowerSaving() const { return false; }
virtual bool setRxPowerSaving(bool enabled, uint32_t rx_us, uint32_t sleep_us) { return !enabled; }
/**
* \brief Attempts to change the radio modulation parameters without waiting.
*
* BUSY means the request is valid but the radio is temporarily unable to
* leave RX/TX. Callers may retry it from their main loop. FAILED means the
* radio attempted or rejected the change and retrying the same tuple is not
* expected to help.
*/
virtual RadioParamApplyResult trySetParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings = nullptr) {
(void)freq;
(void)bw;
(void)sf;
(void)cr;
(void)rx_ps_timings;
return RadioParamApplyResult::FAILED;
}
/**
* \returns true if the radio is currently mid-receive of a packet.
*/
+7
View File
@@ -140,6 +140,13 @@ public:
}
return last_unique = t;
}
/** Reset the monotonic timestamp helper after an intentional RTC correction.
* This is needed when a caller explicitly permits moving the wall clock
* backward and wants subsequent generated timestamps to use the new clock. */
void resetUniqueTime(uint32_t time) {
last_unique = time > 0 ? time - 1 : 0;
}
};
}
+4
View File
@@ -17,6 +17,10 @@ public:
virtual bool isReadBusy() const = 0;
virtual bool isWriteBusy() const = 0;
// True while application-level transport work still needs loop service.
// Backends whose busy methods are throttling/high-water signals should
// override this with their actual queue state.
virtual bool hasPendingIO() const { return isReadBusy() || isWriteBusy(); }
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;
virtual size_t checkRecvFrame(uint8_t dest[]) = 0;
};
+1 -2
View File
@@ -110,8 +110,7 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
ClientInfo* oldest = NULL;
for (int i = 0; i < num_clients; i++) {
if (id.matches(clients[i].id)) return &clients[i]; // already known
if ( (!clients[i].isAdmin() && !clients[i].isRegionMgr())
&& clients[i].last_activity < min_time) {
if (!clients[i].isProtectedManager() && clients[i].last_activity < min_time) {
oldest = &clients[i];
min_time = oldest->last_activity;
}
+3
View File
@@ -10,6 +10,7 @@
#define PERM_ACL_READ_WRITE 2
#define PERM_ACL_ADMIN 3
#define PERM_ACL_REGION_MGR 4
#define PERM_ACL_FILTER_MGR 5
#define OUT_PATH_FORCE_FLOOD 0xFE
#define OUT_PATH_UNKNOWN 0xFF
@@ -36,6 +37,8 @@ struct ClientInfo {
bool isAdmin() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_ADMIN; }
bool isRegionMgr() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_REGION_MGR; }
bool isFilterMgr() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_FILTER_MGR; }
bool isProtectedManager() const { return isAdmin() || isRegionMgr() || isFilterMgr(); }
};
#ifndef MAX_CLIENTS
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stdint.h>
namespace mesh {
struct ClockSyncConsensusResult {
bool consensus;
uint8_t fresh_count;
uint8_t agreeing_count;
uint8_t required_count;
uint32_t estimate;
};
// Evaluate an in-place set of current-time estimates. A configured quorum is
// always required, and when more samples are present the agreeing cluster must
// also be a strict majority. This makes an 8-vs-8 split fail instead of letting
// the upper median choose one side arbitrarily.
inline ClockSyncConsensusResult evaluateClockSyncConsensus(uint32_t* values,
uint8_t count,
uint8_t configured_required,
uint32_t window_seconds) {
ClockSyncConsensusResult result = {false, count, 0, configured_required, 0};
if (values == nullptr || count < configured_required) return result;
uint8_t strict_majority = (uint8_t)(count / 2U + 1U);
if (strict_majority > result.required_count) result.required_count = strict_majority;
for (uint8_t i = 1; i < count; i++) {
uint32_t value = values[i];
uint8_t j = i;
while (j > 0 && values[j - 1] > value) {
values[j] = values[j - 1];
j--;
}
values[j] = value;
}
result.estimate = values[count / 2U];
for (uint8_t i = 0; i < count; i++) {
uint32_t difference = values[i] > result.estimate
? values[i] - result.estimate : result.estimate - values[i];
if (difference <= window_seconds) result.agreeing_count++;
}
result.consensus = result.agreeing_count >= result.required_count;
return result;
}
} // namespace mesh
+2
View File
@@ -1780,6 +1780,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (sender_timestamp > curr) {
getRTCClock()->setCurrentTime(sender_timestamp + 1);
_callbacks->onManualClockSet();
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
@@ -1825,6 +1826,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (secs > curr) {
getRTCClock()->setCurrentTime(secs);
_callbacks->onManualClockSet();
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
+4
View File
@@ -351,6 +351,10 @@ struct LegacyObserverTail {
class CommonCLICallbacks {
public:
virtual void savePrefs() = 0;
// Called only after a CLI command successfully changes the RTC. Roles that
// derive time from untrusted radio traffic can use this to prefer the manual
// value for the remainder of the boot.
virtual void onManualClockSet() { }
virtual const char* getFirmwareVer() = 0;
virtual const char* getBuildDate() = 0;
virtual const char* getRole() = 0;
+3 -2
View File
@@ -297,8 +297,9 @@ void NRF52Board::sleep(uint32_t secs) {
sd_softdevice_is_enabled(&sd_enabled);
if (sd_enabled) {
// first call processes pending softdevice events, second call sleeps.
sd_app_evt_wait();
// A single call is required here. If an interrupt arrived since the last
// wait, SoftDevice returns immediately so the main loop can service the
// flag or BLE queue before sleeping again.
sd_app_evt_wait();
} else {
// softdevice is disabled, use raw WFE
+67
View File
@@ -413,6 +413,8 @@ MQTTBridge::MQTTBridge(const MQTTNodeInfo& node_info, MQTTPrefs *obs,
_ntp_client(_ntp_udp, effectiveNtpPrimary(obs), 0, 60000), _last_ntp_sync(0), _ntp_synced(false), _ntp_sync_pending(false), _slots_setup_done(false), _max_active_slots(RUNTIME_MQTT_SLOTS),
_ntp_force_requested(false), _ntp_force_done(false), _ntp_force_result(false),
_ntp_diag_requested(false), _ntp_diag_done(false), _ntp_diag_count(0),
_ntp_estimate_requested(false), _ntp_estimate_done(false),
_ntp_estimate_ok(false), _ntp_estimate_epoch(0),
// Default to UTC; setRules() will be called from syncTimeWithNTP when a
// non-UTC timezone string is configured. Timezone has no default ctor,
// so we must pass rules here.
@@ -547,6 +549,12 @@ void MQTTBridge::begin() {
}
_cached_has_connected_slots = false;
_slots_setup_done = false;
// A prior bridge session may have ended while a delayed clock estimate was
// queued or being consumed. Never carry that handshake into this session.
_ntp_estimate_requested = false;
_ntp_estimate_done = false;
_ntp_estimate_ok = false;
_ntp_estimate_epoch = 0;
// PSRAM diagnostic - helps debug memory fragmentation on boards with external RAM
#ifdef BOARD_HAS_PSRAM
@@ -838,6 +846,10 @@ void MQTTBridge::end() {
_initialized = false;
_slots_setup_done = false; // Reset so deferred setup runs again on next begin()
_ntp_estimate_requested = false;
_ntp_estimate_done = false;
_ntp_estimate_ok = false;
_ntp_estimate_epoch = 0;
MQTT_DEBUG_PRINTLN("MQTT Bridge stopped");
}
@@ -990,6 +1002,17 @@ void MQTTBridge::mqttTaskLoop() {
_ntp_diag_done = true; // set last so the waiter sees populated results
}
// Delayed clock bootstrap uses a non-blocking request from the radio task.
// Query only; the requester applies its configured drift threshold before
// deciding whether to move the RTC forward or backward.
if (_ntp_estimate_requested) {
runNtpEstimateProbe();
_ntp_estimate_done = true;
// Keep requested asserted for the entire probe so another caller cannot
// queue work that shares and overwrites the result fields above.
_ntp_estimate_requested = false;
}
// Deferred slot setup: wait until NTP is synced so JWT tokens get valid timestamps.
// This avoids wasted TLS handshakes that get rejected due to bad token times.
if (_ntp_synced && !_slots_setup_done) {
@@ -2188,6 +2211,11 @@ void MQTTBridge::loop() {
_ntp_sync_pending = false;
syncTimeWithNTP();
}
if (_ntp_estimate_requested) {
runNtpEstimateProbe();
_ntp_estimate_done = true;
_ntp_estimate_requested = false;
}
// Deferred slot setup after NTP sync (non-ESP32 path)
if (_ntp_synced && !_slots_setup_done) {
@@ -3163,6 +3191,45 @@ void MQTTBridge::runNtpDiagProbe() {
r.epoch = ok ? (uint32_t)_ntp_client.getEpochTime() : 0;
}
_ntp_diag_count = count;
_ntp_client.end();
}
void MQTTBridge::runNtpEstimateProbe() {
const char* servers[kMaxNtpServers];
int count = 0;
fillNtpServerList(_obs, servers, count);
_ntp_estimate_ok = false;
_ntp_estimate_epoch = 0;
_ntp_client.begin();
for (int i = 0; i < count && !_ntp_estimate_ok; i++) {
_ntp_client.setPoolServerName(servers[i]);
if (!_ntp_client.forceUpdate()) continue;
uint32_t epoch = (uint32_t)_ntp_client.getEpochTime();
if (epoch >= 1704067200UL && epoch <= 4102444799UL) {
_ntp_estimate_epoch = epoch;
_ntp_estimate_ok = true;
}
}
_ntp_client.end();
}
bool MQTTBridge::requestNtpTimeEstimate() {
if (!isRunning() || WiFi.status() != WL_CONNECTED || _ntp_estimate_requested) return false;
_ntp_estimate_done = false;
_ntp_estimate_ok = false;
_ntp_estimate_epoch = 0;
_ntp_estimate_requested = true;
return true;
}
bool MQTTBridge::takeNtpTimeEstimate(uint32_t& epoch, bool& finished) {
finished = _ntp_estimate_done;
if (!finished) return false;
bool success = _ntp_estimate_ok;
epoch = success ? _ntp_estimate_epoch : 0;
_ntp_estimate_done = false; // consume the result
return success;
}
bool MQTTBridge::ntpDiag(char* reply, size_t reply_size, bool verbose) {
+14 -1
View File
@@ -199,7 +199,7 @@ private:
WiFiUDP _ntp_udp;
NTPClient _ntp_client;
unsigned long _last_ntp_sync;
bool _ntp_synced;
volatile bool _ntp_synced;
bool _ntp_sync_pending; // Flag to trigger NTP sync from loop() instead of event handler
bool _slots_setup_done; // Deferred: slots set up after NTP sync
// WiFi.onEvent() handler registered once and never removed by end(); the bridge
@@ -236,6 +236,12 @@ private:
};
NtpDiagResult _ntp_diag_results[kMaxNtpServers];
int _ntp_diag_count;
// Non-blocking, read-only NTP estimate used by the delayed clock-bootstrap
// policy. The MQTT task performs network I/O; the radio/main task only polls.
volatile bool _ntp_estimate_requested;
volatile bool _ntp_estimate_done;
volatile bool _ntp_estimate_ok;
volatile uint32_t _ntp_estimate_epoch;
// Timezone handling.
// _timezone_storage is inline class storage (zero heap) that is reconfigured
@@ -380,6 +386,7 @@ private:
bool isAnySlotConnected();
void refreshNTP(); // Lightweight periodic NTP refresh (non-blocking)
void runNtpDiagProbe(); // Probe every server for connectivity; never sets the clock. Core 0 only.
void runNtpEstimateProbe(); // Query the first usable server without changing any clock. Core 0 only.
// Populates dst_out/std_out with TimeChangeRules for the given IANA or
// abbreviation string. Returns false if the string is not recognized
// (callers should fall back to UTC). Zero-allocation.
@@ -488,6 +495,12 @@ public:
* summary in reply; verbose=false fills reply with a compact "<server> ok|fail" list
* (for LoRa). Returns false if the bridge is not running. */
bool ntpDiag(char* reply, size_t reply_size, bool verbose);
/** Queue a read-only NTP query on the MQTT task without blocking the radio loop. */
bool requestNtpTimeEstimate();
/** Poll/consume the queued estimate. finished=false means it is still pending. */
bool takeNtpTimeEstimate(uint32_t& epoch, bool& finished);
/** True after this bridge has successfully set the RTC from NTP this boot. */
bool hasNtpTime() const { return _ntp_synced; }
static void formatMqttStatusReply(char* buf, size_t bufsize, const MQTTPrefs* obs);
/** True when WiFi is set and at least one MQTT slot can run (preset + custom host if needed). */
static bool isConfigValid(const MQTTPrefs* obs);
+10 -1
View File
@@ -11,9 +11,18 @@ public:
uint32_t getRngSeed();
mesh::RadioParamApplyResult trySetParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings = nullptr) override {
(void)freq;
(void)bw;
(void)sf;
(void)cr;
(void)rx_ps_timings;
return mesh::RadioParamApplyResult::APPLIED;
}
bool setParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings = nullptr) {
return true;
return trySetParams(freq, bw, sf, cr, rx_ps_timings) == mesh::RadioParamApplyResult::APPLIED;
}
void powerOff() { /* no-op */ }
+1
View File
@@ -78,6 +78,7 @@ public:
bool isReadBusy() const override;
bool isWriteBusy() const override;
bool hasPendingIO() const override { return recv_queue_len > 0 || send_queue_len > 0; }
size_t writeFrame(const uint8_t src[], size_t len) override;
size_t checkRecvFrame(uint8_t dest[]) override;
};
+1
View File
@@ -54,6 +54,7 @@ public:
bool isConnected() const override;
bool isReadBusy() const override;
bool isWriteBusy() const override;
bool hasPendingIO() const override { return recv_queue_len > 0 || send_queue_len > 0; }
size_t writeFrame(const uint8_t src[], size_t len) override;
size_t checkRecvFrame(uint8_t dest[]) override;
+4
View File
@@ -408,3 +408,7 @@ bool SerialBLEInterface::isReadBusy() const {
bool SerialBLEInterface::isWriteBusy() const {
return send_queue_len >= (FRAME_QUEUE_SIZE * 2 / 3);
}
bool SerialBLEInterface::hasPendingIO() const {
return recv_queue_len > 0 || send_queue_len > 0;
}
+1
View File
@@ -68,6 +68,7 @@ public:
bool isConnected() const override;
bool isReadBusy() const override;
bool isWriteBusy() const override;
bool hasPendingIO() const override;
size_t writeFrame(const uint8_t src[], size_t len) override;
size_t checkRecvFrame(uint8_t dest[]) override;
};
+12 -5
View File
@@ -92,12 +92,14 @@ void RadioLibWrapper::endReconfigure(bool resume_rx) {
if (resume_rx) startRecv();
}
bool RadioLibWrapper::setParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings) {
if (rx_ps_timings != NULL && !supportsRxPowerSaving()) return false;
mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings) {
if (rx_ps_timings != NULL && !supportsRxPowerSaving()) {
return mesh::RadioParamApplyResult::FAILED;
}
uint8_t resume_rx = beginReconfigure();
if (resume_rx > 1) return false;
if (resume_rx > 1) return mesh::RadioParamApplyResult::BUSY;
const bool had_previous_params = _params_valid;
const float previous_freq = _cur_freq;
@@ -137,7 +139,12 @@ bool RadioLibWrapper::setParams(float freq, float bw, uint8_t sf, uint8_t cr,
}
endReconfigure(resume_rx);
return success;
return success ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}
bool RadioLibWrapper::setParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings) {
return trySetParams(freq, bw, sf, cr, rx_ps_timings) == mesh::RadioParamApplyResult::APPLIED;
}
bool RadioLibWrapper::setRxBoostedGainMode(bool enabled) {
+2
View File
@@ -128,6 +128,8 @@ public:
// When rx_ps_timings is supplied, update and re-arm the RX duty cycle in the
// same standby transition as the modulation change. Values are {rx, sleep}.
mesh::RadioParamApplyResult trySetParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings = NULL) override;
bool setParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings = NULL);
uint16_t getDefaultPreambleLength() const override { return preambleLengthForSF(_preamble_sf); }
+10
View File
@@ -6,10 +6,20 @@
class LocationProvider {
protected:
bool _time_sync_needed = true;
bool _time_sync_applied = false;
void markTimeSyncApplied() { _time_sync_applied = true; }
public:
virtual void syncTime() { _time_sync_needed = true; }
virtual bool waitingTimeSync() { return _time_sync_needed; }
// Edge-triggered notification for consumers that need to know a GPS time
// was actually written, rather than merely seeing a valid location fix.
bool consumeTimeSyncApplied() {
bool applied = _time_sync_applied;
_time_sync_applied = false;
return applied;
}
virtual long getLatitude() = 0;
virtual long getLongitude() = 0;
virtual long getAltitude() = 0;
@@ -150,6 +150,7 @@ public :
if (_time_sync_needed && time_valid > 2) {
if (_clock != NULL) {
_clock->setCurrentTime(getTimestamp());
markTimeSyncApplied();
_time_sync_needed = false;
_last_time_sync = millis();
}