Reduce background polling and radio power use

This commit is contained in:
mikecarper committed 2026-07-13 14:36:34 -07:00
1 parent b9e7e416be
commit 4f839d3477
19 files changed
+802 -273

No files matched your search

+28 -26
View File
@@ -329,44 +329,46 @@ public:
prefix_len = MAX_ROUTE_HASH_BYTES;
}
// Keep exact prefixes distinct so a 1-byte path prefix does not collapse
// independent 2/3-byte repeaters that share the same first byte.
int empty_idx = -1;
int oldest_idx = 0;
#if ARDUINO
const uint32_t now = millis();
uint32_t oldest_age = 0;
bool have_oldest = false;
#endif
// Find a match, the first empty slot, and the oldest occupied slot in one
// pass. Keep exact prefixes distinct so a 1-byte path prefix does not
// collapse independent 2/3-byte repeaters that share the same first byte.
for (int i = 0; i < _max_recent_repeaters; i++) {
RecentRepeaterInfo& existing = _recent_repeaters[i];
if (existing.prefix_len == 0) {
if (empty_idx < 0) empty_idx = i;
continue;
}
if (existing.prefix_len != prefix_len || memcmp(existing.prefix, prefix, prefix_len) != 0) {
#if ARDUINO
uint32_t age = (uint32_t)(now - existing.last_heard_millis);
if (!have_oldest || age > oldest_age) {
oldest_age = age;
oldest_idx = i;
have_oldest = true;
}
#endif
continue;
}
existing.snr_x4 = weightedSnrX4RoundUp(existing.snr_x4, snr_x4);
#if ARDUINO
existing.last_heard_millis = millis();
existing.last_heard_millis = now;
#else
existing.last_heard_millis = 0;
#endif
return true;
}
int slot_idx = -1;
for (int i = 0; i < _max_recent_repeaters; i++) {
if (_recent_repeaters[i].prefix_len == 0) {
slot_idx = i;
break;
}
}
if (slot_idx < 0) {
// Table is full: evict the oldest heard entry.
slot_idx = 0;
#if ARDUINO
uint32_t now = millis();
uint32_t oldest_age = (uint32_t)(now - _recent_repeaters[0].last_heard_millis);
for (int i = 1; i < _max_recent_repeaters; i++) {
uint32_t age = (uint32_t)(now - _recent_repeaters[i].last_heard_millis);
if (age > oldest_age) {
oldest_age = age;
slot_idx = i;
}
}
#endif
}
// Non-Arduino tests have no monotonic clock, so a full table retains the
// historical deterministic fallback of evicting slot zero.
int slot_idx = empty_idx >= 0 ? empty_idx : oldest_idx;
RecentRepeaterInfo& slot = _recent_repeaters[slot_idx];
memset(slot.prefix, 0, sizeof(slot.prefix));
@@ -374,7 +376,7 @@ public:
slot.prefix_len = prefix_len;
slot.snr_x4 = snr_x4;
#if ARDUINO
slot.last_heard_millis = millis();
slot.last_heard_millis = now;
#else
slot.last_heard_millis = 0;
#endif
+35 -11
View File
@@ -6,6 +6,7 @@ PacketQueue::PacketQueue(int max_entries) {
_schedule_table = new uint32_t[max_entries];
_size = max_entries;
_num = 0;
_next_schedule = 0;
}
int PacketQueue::countBefore(uint32_t now) const {
@@ -19,6 +20,25 @@ int PacketQueue::countBefore(uint32_t now) const {
return n;
}
bool PacketQueue::getNextTime(uint32_t now, uint32_t& scheduled_for) const {
if (_num == 0) return false;
scheduled_for = (int32_t)(_next_schedule - now) <= 0 ? now : _next_schedule;
return true;
}
void PacketQueue::rebuildNextTime() {
if (_num == 0) {
_next_schedule = 0;
return;
}
_next_schedule = _schedule_table[0];
for (int i = 1; i < _num; i++) {
if ((int32_t)(_schedule_table[i] - _next_schedule) < 0) {
_next_schedule = _schedule_table[i];
}
}
}
mesh::Packet* PacketQueue::get(uint32_t now) {
uint8_t min_pri = 0xFF;
int best_idx = -1;
@@ -31,16 +51,7 @@ mesh::Packet* PacketQueue::get(uint32_t now) {
}
if (best_idx < 0) return NULL; // empty, or all items are still in the future
mesh::Packet* top = _table[best_idx];
int i = best_idx;
_num--;
while (i < _num) {
_table[i] = _table[i+1];
_pri_table[i] = _pri_table[i+1];
_schedule_table[i] = _schedule_table[i+1];
i++;
}
return top;
return removeByIdx(best_idx);
}
mesh::Packet* PacketQueue::peek(uint32_t now) const {
@@ -57,9 +68,10 @@ mesh::Packet* PacketQueue::peek(uint32_t now) const {
}
mesh::Packet* PacketQueue::removeByIdx(int i) {
if (i >= _num) return NULL; // invalid index
if (i < 0 || i >= _num) return NULL; // invalid index
mesh::Packet* item = _table[i];
uint32_t removed_schedule = _schedule_table[i];
_num--;
while (i < _num) {
_table[i] = _table[i+1];
@@ -67,6 +79,7 @@ mesh::Packet* PacketQueue::removeByIdx(int i) {
_schedule_table[i] = _schedule_table[i+1];
i++;
}
if (_num == 0 || removed_schedule == _next_schedule) rebuildNextTime();
return item;
}
@@ -77,6 +90,9 @@ bool PacketQueue::add(mesh::Packet* packet, uint8_t priority, uint32_t scheduled
_table[_num] = packet;
_pri_table[_num] = priority;
_schedule_table[_num] = scheduled_for;
if (_num == 0 || (int32_t)(scheduled_for - _next_schedule) < 0) {
_next_schedule = scheduled_for;
}
_num++;
return true;
}
@@ -121,6 +137,10 @@ int StaticPoolPacketManager::getOutboundTotal() const {
return send_queue.count();
}
bool StaticPoolPacketManager::getNextOutboundTime(uint32_t now, uint32_t& scheduled_for) const {
return send_queue.getNextTime(now, scheduled_for);
}
int StaticPoolPacketManager::getFreeCount() const {
return unused.count();
}
@@ -141,3 +161,7 @@ void StaticPoolPacketManager::queueInbound(mesh::Packet* packet, uint32_t schedu
mesh::Packet* StaticPoolPacketManager::getNextInbound(uint32_t now) {
return rx_queue.get(now);
}
bool StaticPoolPacketManager::getNextInboundTime(uint32_t now, uint32_t& scheduled_for) const {
return rx_queue.getNextTime(now, scheduled_for);
}
+6
View File
@@ -7,6 +7,9 @@ class PacketQueue {
uint8_t* _pri_table;
uint32_t* _schedule_table;
int _size, _num;
uint32_t _next_schedule;
void rebuildNextTime();
public:
PacketQueue(int max_entries);
@@ -15,6 +18,7 @@ public:
bool add(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for);
int count() const { return _num; }
int countBefore(uint32_t now) const;
bool getNextTime(uint32_t now, uint32_t& scheduled_for) const;
mesh::Packet* itemAt(int i) const { return _table[i]; }
mesh::Packet* removeByIdx(int i);
};
@@ -32,9 +36,11 @@ public:
mesh::Packet* peekNextOutbound(uint32_t now) override;
int getOutboundCount(uint32_t now) const override;
int getOutboundTotal() const override;
bool getNextOutboundTime(uint32_t now, uint32_t& scheduled_for) const override;
int getFreeCount() const override;
mesh::Packet* getOutboundByIdx(int i) override;
mesh::Packet* removeOutboundByIdx(int i) override;
void queueInbound(mesh::Packet* packet, uint32_t scheduled_for) override;
mesh::Packet* getNextInbound(uint32_t now) override;
bool getNextInboundTime(uint32_t now, uint32_t& scheduled_for) const override;
};
+100 -35
View File
@@ -8,13 +8,16 @@
#define STATE_TX_DONE 4
#define STATE_INT_READY 16
#define NUM_NOISE_FLOOR_SAMPLES 64
#define NUM_NOISE_FLOOR_SAMPLES 16
#define SAMPLING_THRESHOLD 14
// periodic noise-floor calibration windows (RX duty-cycle powersaving only)
#define NF_CALIB_INTERVAL_MS 60000UL // at least once a minute
// On-demand noise-floor calibration windows (RX duty-cycle powersaving only).
// Requests are coalesced so retries cannot repeatedly force continuous RX.
#define NF_CALIB_INTERVAL_MS 300000UL // no more than once every five minutes
#define NF_CALIB_TIMEOUT_MS 5000UL // give up on the batch (busy channel)
#define NF_CONTINUOUS_TIMEOUT_MS 1000UL // bound awake time without RX powersaving
#define NF_CALIB_SETTLE_MS 20UL // frontend/AGC settle after RX entry
#define NF_SAMPLE_INTERVAL_MS 20UL // avoid back-to-back SPI RSSI reads
static volatile uint8_t state = STATE_IDLE;
@@ -40,12 +43,19 @@ void RadioLibWrapper::begin() {
}
_noise_floor = 0;
_noise_floor_valid = false;
_threshold = 0;
_cad_enabled = false;
// start average out some samples
_num_floor_samples = 0;
_floor_sample_sum = 0;
_nf_calib_active = false;
_nf_last_calib = 0;
_nf_sample_from = 0;
_nf_refresh_requested = true; // establish one baseline after startup
_nf_calib_deadline = millis() + NF_CONTINUOUS_TIMEOUT_MS;
_nf_next_sample_at = 0;
}
uint32_t RadioLibWrapper::getRngSeed() {
@@ -124,10 +134,19 @@ void RadioLibWrapper::idle() {
void RadioLibWrapper::triggerNoiseFloorCalibrate(int threshold) {
_threshold = threshold;
if (_num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES) { // ignore trigger if currently sampling
_num_floor_samples = 0;
_floor_sample_sum = 0;
}
// With interference detection disabled, Dispatcher polling is a free flag
// update: passive retries request a refresh themselves only when the cached
// floor is stale. An enabled threshold keeps the floor periodically fresh.
if (threshold != 0) requestNoiseFloorRefresh();
}
void RadioLibWrapper::requestNoiseFloorRefresh() {
if (_nf_refresh_requested) return;
_nf_refresh_requested = true;
_num_floor_samples = 0;
_floor_sample_sum = 0;
_nf_calib_deadline = millis() + NF_CONTINUOUS_TIMEOUT_MS;
_nf_next_sample_at = 0;
}
void RadioLibWrapper::doResetAGC() {
@@ -147,8 +166,15 @@ void RadioLibWrapper::resetAGC() {
// too low (-106) to accept normal samples (~-105), self-reinforcing the
// stuck value even after the receiver has recovered.
_noise_floor = 0;
_noise_floor_valid = false;
_nf_calib_active = false;
_nf_refresh_requested = true;
_nf_last_calib = 0;
_nf_sample_from = 0;
_num_floor_samples = 0;
_floor_sample_sum = 0;
_nf_calib_deadline = millis() + NF_CONTINUOUS_TIMEOUT_MS;
_nf_next_sample_at = 0;
}
void RadioLibWrapper::rxPsWatchdogCheck() {
@@ -225,28 +251,30 @@ void RadioLibWrapper::rxPsWatchdogCheck() {
}
}
// Periodic noise-floor calibration, active only with RX duty-cycle powersaving:
// On-demand noise-floor calibration, active only with RX duty-cycle powersaving:
// a duty-cycled receiver can't be sampled reliably (the frontend is off in the
// sleep windows and settling right after each wake), so at least once a minute
// the receive mode is dropped to plain continuous RX, a fresh sample batch is
// collected exactly like the non-powersaving path does, and the duty cycle is
// re-armed. The published average stays in _noise_floor as usual.
void RadioLibWrapper::noiseFloorCalibCheck() {
unsigned long now = millis();
// sleep windows and settling right after each wake), so a requested refresh
// drops receive mode to plain continuous RX, collects a fresh sample batch,
// and re-arms the duty cycle. Requests are rate-limited and coalesced.
void RadioLibWrapper::noiseFloorCalibCheck(unsigned long now) {
if (_nf_calib_active) {
if (!_rx_ps_enabled || (long)(now - _nf_calib_deadline) >= 0) {
if (!_rx_ps_enabled
|| ((long)(now - _nf_calib_deadline) >= 0
&& _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES)) {
// powersaving turned off mid-window, or the batch couldn't complete
// (busy channel / stuck filter) - keep the previous floor
endNoiseFloorCalib(now);
}
} else if (_rx_ps_enabled && _rx_ps_armed && state == STATE_RX
&& now - _nf_last_calib >= NF_CALIB_INTERVAL_MS
} else if (_nf_refresh_requested && _rx_ps_enabled && _rx_ps_armed && state == STATE_RX
&& ((!_noise_floor_valid && _nf_last_calib == 0)
|| now - _nf_last_calib >= NF_CALIB_INTERVAL_MS)
&& !isReceivingPacket()) {
// never interrupt an ongoing reception to calibrate (a TX in flight is
// already excluded by state == STATE_RX); retries next loop iteration
_nf_calib_active = true;
_nf_calib_deadline = now + NF_CALIB_TIMEOUT_MS;
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
_nf_next_sample_at = _nf_sample_from;
_num_floor_samples = 0; // start a fresh batch for this window
_floor_sample_sum = 0;
state = STATE_IDLE; // recvRaw() re-arms; startReceiveMode() sees the
@@ -256,7 +284,9 @@ void RadioLibWrapper::noiseFloorCalibCheck() {
void RadioLibWrapper::endNoiseFloorCalib(unsigned long now) {
_nf_calib_active = false;
_nf_refresh_requested = false;
_nf_last_calib = now;
_nf_next_sample_at = 0;
// force a receive re-arm back into duty-cycle mode, but don't clobber a
// completed-but-unread packet or an in-flight TX (recvRaw()/onSendFinished()
// will re-arm right after those anyway; same guard style as setRxPowerSaving)
@@ -269,33 +299,58 @@ void RadioLibWrapper::loop() {
if (_rx_ps_enabled) {
rxPsWatchdogCheck();
}
noiseFloorCalibCheck();
if (state == STATE_RX && _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES) {
// Noise floor is only sampled outside RX duty-cycle mode: continuously in
// plain RX (powersaving off), or inside the periodic calibration window
// (powersaving on), skipping the first moments after RX entry there while
// the frontend/AGC settles (unsettled GetRssiInst reads ~-127 dBm garbage).
if (!_rx_ps_armed
&& !(_nf_calib_active && (long)(millis() - _nf_sample_from) < 0)
&& !isReceivingPacket()) {
int rssi = getCurrentRSSI();
if (rssi < _noise_floor + SAMPLING_THRESHOLD) { // only consider samples below current floor + sampling THRESHOLD
_num_floor_samples++;
_floor_sample_sum += rssi;
}
}
} else if (_num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES && _floor_sample_sum != 0) {
unsigned long now = millis();
if (_nf_calib_active || _nf_refresh_requested) {
noiseFloorCalibCheck(now);
}
if (_nf_refresh_requested && _num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES
&& _floor_sample_sum != 0) {
_noise_floor = _floor_sample_sum / NUM_NOISE_FLOOR_SAMPLES;
if (_noise_floor < -120) {
_noise_floor = -120; // clamp to lower bound of -120dBi
}
_floor_sample_sum = 0;
_noise_floor_valid = true;
_nf_refresh_requested = false;
_nf_last_calib = now;
_nf_next_sample_at = 0;
MESH_DEBUG_PRINTLN("RadioLibWrapper: noise_floor = %d", (int)_noise_floor);
if (_nf_calib_active) {
endNoiseFloorCalib(millis()); // fresh floor published - back to duty cycle
endNoiseFloorCalib(now); // fresh floor published - back to duty cycle
}
return;
}
if (_nf_refresh_requested && !_rx_ps_enabled && _nf_calib_deadline != 0
&& (long)(now - _nf_calib_deadline) >= 0) {
// A continuously busy channel can reject every candidate sample. Do not
// keep the MCU awake indefinitely; retain the previous floor and wait for
// the normal stale-floor interval before another requested burst.
_nf_refresh_requested = false;
_nf_last_calib = now;
_nf_next_sample_at = 0;
_num_floor_samples = 0;
_floor_sample_sum = 0;
}
if (_nf_refresh_requested && state == STATE_RX
&& _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES
&& (_nf_next_sample_at == 0 || (long)(now - _nf_next_sample_at) >= 0)) {
// Noise floor is only sampled outside RX duty-cycle mode: continuously in
// plain RX (powersaving off), or inside an on-demand calibration window
// (powersaving on), skipping the first moments after RX entry there while
// the frontend/AGC settles (unsettled GetRssiInst reads ~-127 dBm garbage).
if (!_rx_ps_armed
&& !(_nf_calib_active && (long)(now - _nf_sample_from) < 0)
&& !isReceivingPacket()) {
int rssi = getCurrentRSSI();
_nf_next_sample_at = now + NF_SAMPLE_INTERVAL_MS;
if (rssi < _noise_floor + SAMPLING_THRESHOLD) { // only consider samples below current floor + sampling THRESHOLD
_num_floor_samples++;
_floor_sample_sum += rssi;
}
}
}
}
@@ -471,6 +526,16 @@ bool RadioLibWrapper::isReceivingPassive(int interference_margin_db) {
if (isChipBusy()) return true;
if (isReceivingPacket()) return true;
unsigned long now = millis();
if ((!_noise_floor_valid && _nf_last_calib == 0)
|| now - _nf_last_calib >= NF_CALIB_INTERVAL_MS) {
requestNoiseFloorRefresh();
}
// Until the startup baseline is ready, defer rather than compare against the
// zero-initialized floor and transmit blind. Dispatcher retains its bounded
// busy timeout if sampling cannot complete.
if (!_noise_floor_valid) return true;
// Use a fixed margin for retries even when the normal interference threshold
// is disabled. This is passive (RSSI only): unlike CAD it does not restart RX
// and cannot erase the forwarding echo that would cancel the retry.
+18 -12
View File
@@ -17,6 +17,8 @@ protected:
uint32_t n_recv, n_sent, n_recv_errors;
int16_t _noise_floor, _threshold;
bool _cad_enabled;
bool _noise_floor_valid;
bool _nf_refresh_requested;
uint16_t _num_floor_samples;
int32_t _floor_sample_sum;
unsigned long last_recv_millis;
@@ -51,20 +53,21 @@ protected:
bool _cur_rx_boosted_gain;
bool _params_valid, _dbm_valid, _rx_boosted_gain_valid;
// Periodic noise-floor calibration (only while RX duty-cycle powersaving is
// armed): a duty-cycled receiver can't be sampled reliably, so at least once
// a minute the wrapper drops to plain continuous RX, collects a fresh sample
// batch exactly like the non-powersaving path does, publishes the average
// into _noise_floor and re-arms the duty cycle.
// On-demand noise-floor calibration while RX duty-cycle powersaving is
// armed. A duty-cycled receiver can't be sampled reliably, so a requested
// refresh briefly drops to continuous RX, publishes an average, then re-arms
// the duty cycle.
bool _nf_calib_active;
unsigned long _nf_last_calib; // millis of last completed/attempted window
unsigned long _nf_calib_deadline; // abort window if the batch can't complete
unsigned long _nf_sample_from; // no samples before this (RX entry settle)
unsigned long _nf_next_sample_at; // pace SPI RSSI reads during a sample batch
void idle() override;
void startRecv() override;
void rxPsWatchdogCheck();
void noiseFloorCalibCheck();
void requestNoiseFloorRefresh();
void noiseFloorCalibCheck(unsigned long now);
void endNoiseFloorCalib(unsigned long now);
void cacheParams(float freq, float bw, uint8_t sf, uint8_t cr) {
_cur_freq = freq; _cur_bw = bw; _cur_sf = sf; _cur_cr = cr; _params_valid = true;
@@ -89,12 +92,14 @@ protected:
public:
RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board)
: _radio(&radio), _board(&board), _preamble_sf(0), _rx_ps_enabled(false), _rx_ps_armed(false),
: _radio(&radio), _board(&board), _noise_floor_valid(false), _nf_refresh_requested(true),
_preamble_sf(0), _rx_ps_enabled(false), _rx_ps_armed(false),
_rx_ps_rx_us(RX_PS_FALLBACK_RX_US), _rx_ps_sleep_us(RX_PS_FALLBACK_SLEEP_US),
_wd_last_busy(false), _wd_stage(0), _wd_strikes(0), _startrx_fails(0), _wd_last_transition(0),
_wd_stuck_thresh(0), _wd_observe_until(0), _wd_observe_ms(0),
_cur_rx_boosted_gain(false), _params_valid(false), _dbm_valid(false), _rx_boosted_gain_valid(false),
_nf_calib_active(false), _nf_last_calib(0), _nf_calib_deadline(0), _nf_sample_from(0)
_nf_calib_active(false), _nf_last_calib(0), _nf_calib_deadline(0), _nf_sample_from(0),
_nf_next_sample_at(0)
{
n_recv = n_sent = n_recv_errors = n_wd_soft = n_wd_hard = 0;
last_recv_millis = 0;
@@ -154,10 +159,11 @@ public:
// true while the watchdog is actively watching for BUSY transitions; used by
// the app's hasPendingWork() to keep the MCU out of light sleep for the window
bool isWatchdogObserving() const { return _wd_observe_until != 0; }
// true while a periodic noise-floor calibration window is in progress; the
// app's hasPendingWork() must keep the MCU awake so the sample batch and the
// return to duty-cycle complete promptly
bool isCalibratingNoiseFloor() const { return _nf_calib_active; }
// true while a noise-floor batch needs prompt loop service; the app's
// hasPendingWork() keeps the MCU awake only for this short sample burst.
bool isCalibratingNoiseFloor() const {
return _nf_calib_active || (_nf_refresh_requested && !_rx_ps_enabled);
}
void resetStats() { n_recv = n_sent = n_recv_errors = 0; }
uint8_t getRadioState() const override;