Merge PowerSaving-v17 and harden noise calibration and RX recovery
Port the measured RXPS model without changing Cascade wire preambles or automatically enabling experimental levels. Use a spaced weighted median with bounded calibration windows, preserve packet ownership across CAD, and check actual SX126x receive mode before recovery. Preserve Cascade sleep and radio fixes, integrate the new sensor and board profiles, and correct BSEC script inheritance and the MKE UART pin conflict. Native regressions, production-method/SPI harnesses, and ESP32, nRF52, and STM32 builds pass. Hardware comparison and fault-injection validation are recorded privately.
This commit is contained in:
commit
a60a6a1f60
34 files changed
+1800
-495
No files matched your search
@@ -730,6 +730,13 @@ struct RxPowerSavingArguments {
|
||||
uint32_t sleep_us;
|
||||
};
|
||||
|
||||
inline uint8_t rxPowerSavingNamedLevel(const char* name) {
|
||||
if (strcmp(name, "max") == 0) return 8;
|
||||
if (strcmp(name, "overdrive") == 0) return 9;
|
||||
if (strcmp(name, "riskyWorkingMax") == 0) return 10;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Parse every documented radio.rxps spelling while leaving hardware-specific
|
||||
// period and level ranges to the caller. Exact token shapes prevent suffixes or
|
||||
// injected extra arguments from being silently accepted.
|
||||
@@ -753,6 +760,10 @@ inline bool parseRxPowerSavingArgumentsStrict(
|
||||
parsed.mode = RxPowerSavingArgumentMode::Conservative;
|
||||
} else if (strcmp(fields[0], "balanced") == 0) {
|
||||
parsed.mode = RxPowerSavingArgumentMode::Balanced;
|
||||
} else if (rxPowerSavingNamedLevel(fields[0]) != 0) {
|
||||
parsed.mode = RxPowerSavingArgumentMode::Level;
|
||||
parsed.level = rxPowerSavingNamedLevel(fields[0]);
|
||||
parsed.preamble = 16;
|
||||
} else if (parseUnsignedIntegerStrict(fields[0], parsed.level)) {
|
||||
parsed.mode = RxPowerSavingArgumentMode::Level;
|
||||
} else {
|
||||
@@ -769,6 +780,12 @@ inline bool parseRxPowerSavingArgumentsStrict(
|
||||
}
|
||||
parsed.mode = RxPowerSavingArgumentMode::Manual;
|
||||
}
|
||||
} else if (field_count == 3
|
||||
&& rxPowerSavingNamedLevel(fields[0]) != 0
|
||||
&& strcmp(fields[1], "preamble") == 0
|
||||
&& parseUnsignedIntegerStrict(fields[2], parsed.preamble)) {
|
||||
parsed.mode = RxPowerSavingArgumentMode::Level;
|
||||
parsed.level = rxPowerSavingNamedLevel(fields[0]);
|
||||
} else if (field_count == 4
|
||||
&& strcmp(fields[0], "level") == 0
|
||||
&& strcmp(fields[2], "preamble") == 0
|
||||
|
||||
+28
-38
@@ -452,7 +452,7 @@ static void appendRxPowerSavingAdjustmentNote(char* reply, const NodePrefs* pref
|
||||
char note[96] = {};
|
||||
if (rxPowerSavingUsesContinuousFallback(rx_us, sleep_us)) {
|
||||
snprintf(note, sizeof(note),
|
||||
"; RXPS continuous-fast (no safe level %u-10)",
|
||||
"; RXPS continuous-fast (requested level %u)",
|
||||
(unsigned)prefs->rx_ps_level);
|
||||
} else {
|
||||
const uint8_t requested_preamble = prefs->rx_ps_preamble == 0
|
||||
@@ -3477,48 +3477,38 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
rx_us = _prefs->rx_ps_rx_us;
|
||||
sleep_us = _prefs->rx_ps_sleep_us;
|
||||
|
||||
if (strcmp(value, "off") == 0) {
|
||||
mesh::cli::RxPowerSavingArguments parsed = {};
|
||||
if (!mesh::cli::parseRxPowerSavingArgumentsStrict(value, parsed)) {
|
||||
strcpy(reply, "ERROR: use off|on|conservative|balanced|max|overdrive|riskyWorkingMax|level <1-10>|<rx_us> <sleep_us>");
|
||||
return;
|
||||
}
|
||||
using mesh::cli::RxPowerSavingArgumentMode;
|
||||
if (parsed.mode == RxPowerSavingArgumentMode::Off) {
|
||||
enable = 0;
|
||||
} else if (strcmp(value, "on") == 0 || strcmp(value, "conservative") == 0) {
|
||||
} else if (parsed.mode == RxPowerSavingArgumentMode::Manual) {
|
||||
rx_us = parsed.rx_us;
|
||||
sleep_us = parsed.sleep_us;
|
||||
enable = 1;
|
||||
level = RX_POWERSAVING_CONSERVATIVE_LEVEL;
|
||||
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
|
||||
level_requested = true;
|
||||
preamble_overridden = true;
|
||||
} else if (strcmp(value, "balanced") == 0) {
|
||||
enable = 1;
|
||||
level = RX_POWERSAVING_BALANCED_LEVEL;
|
||||
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
|
||||
level_requested = true;
|
||||
preamble_overridden = true;
|
||||
manual_timings_requested = true;
|
||||
} else {
|
||||
StrHelper::strncpy(tmp, value, sizeof(tmp));
|
||||
const char *parts[4];
|
||||
int num = mesh::Utils::parseTextParts(tmp, parts, 4, ' ');
|
||||
if (num == 1 && isNumeric(parts[0])) {
|
||||
level = _atoi(parts[0]);
|
||||
level_requested = true;
|
||||
enable = 1;
|
||||
} else if (num == 2 && strcmp(parts[0], "level") == 0 && isNumeric(parts[1])) {
|
||||
level = _atoi(parts[1]);
|
||||
level_requested = true;
|
||||
enable = 1;
|
||||
} else if (num == 4 && strcmp(parts[0], "level") == 0 && isNumeric(parts[1]) &&
|
||||
strcmp(parts[2], "preamble") == 0 && isNumeric(parts[3])) {
|
||||
level = _atoi(parts[1]);
|
||||
preamble = _atoi(parts[3]);
|
||||
level_requested = true;
|
||||
preamble_overridden = true;
|
||||
enable = 1;
|
||||
} else if (num == 2 && isNumeric(parts[0]) && isNumeric(parts[1])) {
|
||||
rx_us = _atoi(parts[0]);
|
||||
sleep_us = _atoi(parts[1]);
|
||||
enable = 1;
|
||||
manual_timings_requested = true;
|
||||
} else {
|
||||
strcpy(reply, "ERROR: use off|on|conservative|balanced|level <1-10>|<rx_us> <sleep_us>");
|
||||
uint32_t requested_level = parsed.level;
|
||||
uint32_t requested_preamble = parsed.preamble;
|
||||
if (parsed.mode == RxPowerSavingArgumentMode::Conservative
|
||||
|| parsed.mode == RxPowerSavingArgumentMode::Balanced) {
|
||||
requested_level = parsed.mode == RxPowerSavingArgumentMode::Conservative
|
||||
? RX_POWERSAVING_CONSERVATIVE_LEVEL : RX_POWERSAVING_BALANCED_LEVEL;
|
||||
requested_preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
|
||||
}
|
||||
if (requested_level < 1 || requested_level > 10
|
||||
|| (requested_preamble != 0 && requested_preamble != 16 && requested_preamble != 32)) {
|
||||
strcpy(reply, "ERROR: level range is 1-10; preamble is 16 or 32");
|
||||
return;
|
||||
}
|
||||
level = requested_level;
|
||||
if (requested_preamble != 0) preamble = requested_preamble;
|
||||
preamble_overridden = requested_preamble != 0;
|
||||
level_requested = true;
|
||||
enable = 1;
|
||||
}
|
||||
|
||||
if (level_requested && preamble_overridden
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
#pragma once
|
||||
#include "SX126xReceiveMode.h"
|
||||
|
||||
#include "CustomLLCC68.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
#include "SX126xReset.h"
|
||||
|
||||
class CustomLLCC68Wrapper : public RadioLibWrapper {
|
||||
protected:
|
||||
int8_t readReceiveMode() override { return sx126xReceiveMode((SX126x*)_radio); }
|
||||
|
||||
public:
|
||||
CustomLLCC68Wrapper(CustomLLCC68& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include "MeshCore.h"
|
||||
#include "RXPowerSaving.h"
|
||||
#include "LR1110RxRecovery.h"
|
||||
|
||||
#ifndef LR11X0_TX_BUSY_TIMEOUT_MS
|
||||
@@ -18,6 +19,26 @@ class CustomLR1110 : public LR1110 {
|
||||
public:
|
||||
CustomLR1110(Module *mod) : LR1110(mod) { }
|
||||
|
||||
// Apply the measured TCXO delay on every initialization, including recovery.
|
||||
int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7,
|
||||
uint8_t syncWord = RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, int8_t power = 10,
|
||||
uint16_t preambleLength = 8, float tcxoVoltage = 1.6) {
|
||||
int16_t state = LR1110::begin(freq, bw, sf, cr, syncWord, power, preambleLength,
|
||||
tcxoVoltage);
|
||||
if (state == RADIOLIB_ERR_NONE) state = applyMeshCoreTcxoDelay();
|
||||
return state;
|
||||
}
|
||||
|
||||
int16_t applyMeshCoreTcxoDelay() {
|
||||
if (tcxoVoltage <= 0.0f) return RADIOLIB_ERR_NONE;
|
||||
int16_t state = setTCXO(tcxoVoltage, MC_TCXO_DELAY_US);
|
||||
RADIOLIB_ASSERT(state);
|
||||
state = calibrate(0x3F);
|
||||
RADIOLIB_ASSERT(state); // all blocks; setTCXO moved the gating window
|
||||
delay(50);
|
||||
return RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
// MeshCore keeps the LR1110 in LoRa mode. Calculate from RadioLib's cached
|
||||
// parameters so an airtime query never issues GetPacketType while RX duty
|
||||
// cycling has the chip asleep. RadioLib's LR11x0 implementation ignores a
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#pragma once
|
||||
#include "SX126xReceiveMode.h"
|
||||
|
||||
#include "CustomSTM32WLx.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
@@ -6,6 +7,9 @@
|
||||
#include <math.h>
|
||||
|
||||
class CustomSTM32WLxWrapper : public RadioLibWrapper {
|
||||
protected:
|
||||
int8_t readReceiveMode() override { return sx126xReceiveMode((SX126x*)_radio); }
|
||||
|
||||
public:
|
||||
CustomSTM32WLxWrapper(CustomSTM32WLx& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
|
||||
|
||||
@@ -19,6 +19,30 @@ class CustomSX1262 : public SX1262 {
|
||||
public:
|
||||
CustomSX1262(Module *mod) : SX1262(mod) { }
|
||||
|
||||
// Apply the measured TCXO delay on every initialization, including recovery.
|
||||
int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7,
|
||||
uint8_t syncWord = RADIOLIB_SX126X_SYNC_WORD_PRIVATE, int8_t power = 10,
|
||||
uint16_t preambleLength = 8, float tcxoVoltage = 1.6,
|
||||
bool useRegulatorLDO = false) {
|
||||
int16_t state = SX1262::begin(freq, bw, sf, cr, syncWord, power, preambleLength,
|
||||
tcxoVoltage, useRegulatorLDO);
|
||||
if (state == RADIOLIB_ERR_NONE) state = applyMeshCoreTcxoDelay();
|
||||
return state;
|
||||
}
|
||||
|
||||
// Read tcxoVoltage back from the chip object rather than from the argument:
|
||||
// begin() zeroes it when it falls back to an XTAL, and re-asserting a TCXO
|
||||
// supply on DIO3 for a board that has none would be worse than a long delay.
|
||||
int16_t applyMeshCoreTcxoDelay() {
|
||||
if (tcxoVoltage <= 0.0f) return RADIOLIB_ERR_NONE;
|
||||
int16_t state = setTCXO(tcxoVoltage, MC_TCXO_DELAY_US);
|
||||
RADIOLIB_ASSERT(state);
|
||||
state = calibrate(RADIOLIB_SX126X_CALIBRATE_ALL);
|
||||
RADIOLIB_ASSERT(state);
|
||||
delay(50);
|
||||
return RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
// MeshCore keeps the SX1262 in LoRa mode. Use RadioLib's cached modem
|
||||
// parameters instead of issuing GetPacketType while RX duty cycling may
|
||||
// have the chip asleep. A failed live query otherwise becomes an encoded
|
||||
@@ -111,12 +135,12 @@ class CustomSX1262 : public SX1262 {
|
||||
#endif
|
||||
}
|
||||
|
||||
// RadioLib's default DIO3 TCXO delay is 5 ms and its RX duty-cycle
|
||||
// MeshCore configures the DIO3 TCXO delay and the RX duty-cycle
|
||||
// command adds another 1 ms for sleep/wake transitions. If begin()
|
||||
// fell back to a crystal, only the fixed 1 ms transition remains. Use
|
||||
// RadioLib's resolved oscillator mode: it only falls back after reading
|
||||
// the SX126x XOSC_START_ERR device flag, not for an arbitrary SPI error.
|
||||
_rxDutyCycleTransitionUs = this->tcxoVoltage > 0.0f ? 6000UL : 1000UL;
|
||||
_rxDutyCycleTransitionUs = this->tcxoDelay + 1000UL;
|
||||
|
||||
setCRC(1);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#pragma once
|
||||
#include "SX126xReceiveMode.h"
|
||||
|
||||
#include "CustomSX1262.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
@@ -9,6 +10,9 @@
|
||||
#endif
|
||||
|
||||
class CustomSX1262Wrapper : public RadioLibWrapper {
|
||||
protected:
|
||||
int8_t readReceiveMode() override { return sx126xReceiveMode((SX126x*)_radio); }
|
||||
|
||||
public:
|
||||
CustomSX1262Wrapper(CustomSX1262& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#pragma once
|
||||
#include "SX126xReceiveMode.h"
|
||||
|
||||
#include "CustomSX1268.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
@@ -9,6 +10,9 @@
|
||||
#endif
|
||||
|
||||
class CustomSX1268Wrapper : public RadioLibWrapper {
|
||||
protected:
|
||||
int8_t readReceiveMode() override { return sx126xReceiveMode((SX126x*)_radio); }
|
||||
|
||||
public:
|
||||
CustomSX1268Wrapper(CustomSX1268& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
// PR #2933's spaced median and bounded rise hold, retaining Cascade's
|
||||
// fractional dBm and 25% previous / 75% new weighting. No radio or clock I/O.
|
||||
class NoiseFloorEstimator {
|
||||
public:
|
||||
static constexpr uint16_t SAMPLE_COUNT = 64;
|
||||
static constexpr uint32_t SAMPLE_INTERVAL_MS = 50;
|
||||
static constexpr uint32_t WINDOW_TIMEOUT_MS = 10000;
|
||||
static constexpr uint8_t MAX_HELD_BLOCKS = 3;
|
||||
static constexpr int32_t MAX_RISE_CENTI_DB = 1500;
|
||||
|
||||
private:
|
||||
int16_t _samples[SAMPLE_COUNT] = {};
|
||||
uint16_t _count = 0;
|
||||
uint32_t _last_sample_at = 0;
|
||||
uint8_t _held_blocks = 0;
|
||||
|
||||
public:
|
||||
uint16_t count() const { return _count; }
|
||||
bool complete() const { return _count == SAMPLE_COUNT; }
|
||||
bool ready(uint32_t now) const {
|
||||
return !complete() && (_count == 0 || uint32_t(now - _last_sample_at) >= SAMPLE_INTERVAL_MS);
|
||||
}
|
||||
uint8_t heldBlocks() const { return _held_blocks; }
|
||||
|
||||
// A timeout discards a partial block. Only completed blocks count toward
|
||||
// persistent-rise recovery. Radio/gain resets also clear contamination history.
|
||||
void reset(bool clear_history = false) {
|
||||
_count = 0;
|
||||
if (clear_history) _held_blocks = 0;
|
||||
}
|
||||
|
||||
bool add(float rssi, uint32_t now) {
|
||||
if (!ready(now)
|
||||
|| !isfinite(rssi) || rssi < -200.0f || rssi >= 0.0f) return false;
|
||||
_samples[_count++] = static_cast<int16_t>(rssi * 100.0f - 0.5f);
|
||||
_last_sample_at = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Call once per complete block. A held block leaves the published value intact.
|
||||
bool publish(int32_t& floor_centi_dbm, bool previous_valid) {
|
||||
if (!complete()) return false;
|
||||
for (uint16_t i = 1; i < SAMPLE_COUNT; ++i) {
|
||||
const int16_t key = _samples[i];
|
||||
uint16_t j = i;
|
||||
while (j > 0 && _samples[j - 1] > key) {
|
||||
_samples[j] = _samples[j - 1];
|
||||
--j;
|
||||
}
|
||||
_samples[j] = key;
|
||||
}
|
||||
int32_t median = (int32_t(_samples[SAMPLE_COUNT / 2 - 1])
|
||||
+ _samples[SAMPLE_COUNT / 2]) / 2;
|
||||
if (median < -12000) median = -12000;
|
||||
if (previous_valid && median > floor_centi_dbm + MAX_RISE_CENTI_DB) {
|
||||
if (++_held_blocks < MAX_HELD_BLOCKS) return false;
|
||||
}
|
||||
_held_blocks = 0;
|
||||
if (previous_valid) {
|
||||
const int32_t weighted = floor_centi_dbm + 3 * median;
|
||||
floor_centi_dbm = (weighted - 2) / 4;
|
||||
} else {
|
||||
floor_centi_dbm = median;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -20,12 +20,158 @@
|
||||
// the fallback without persisting invalid sub-millisecond periods.
|
||||
#define RX_POWERSAVING_CONTINUOUS_FALLBACK_US 1000UL
|
||||
|
||||
// Named profiles keep a conservative 16-symbol timing assumption. The adaptive
|
||||
// calculation may use the longer physical preamble only when the configured
|
||||
// assumption cannot safely cover the current tuple.
|
||||
#define RX_POWERSAVING_CONSERVATIVE_LEVEL 1
|
||||
#define RX_POWERSAVING_BALANCED_LEVEL 5
|
||||
#define RX_POWERSAVING_PROFILE_PREAMBLE 16
|
||||
// The level scale is a catch dial, in symbols of the sender's preamble.
|
||||
// Its empirical constants and measurements below come from PowerSaving-v17;
|
||||
// those bench results do not establish reception guarantees on every board.
|
||||
//
|
||||
// Level N means: "at least this many symbols of the sender's preamble land
|
||||
// inside an open RX window." That is the quantity the radio actually needs -
|
||||
// a preamble is latched once enough of it has been heard - so the level states
|
||||
// the requirement directly instead of stating a distance from an edge.
|
||||
//
|
||||
// The arithmetic follows from that in one step. Worst case, a preamble starts
|
||||
// the instant an RX window closes, so what survives into the next window is
|
||||
// `preamble - sleep`. Requiring that to be at least the level's catch gives
|
||||
//
|
||||
// sleep = preamble - catch
|
||||
//
|
||||
// and the chip's capture cost never enters the geometry. It becomes a
|
||||
// validation instead: a level is usable when its catch is at least the cost.
|
||||
// The floor of the scale is 8 symbols precisely because that is what the
|
||||
// slower of the two families needs (LR11x0 8, SX126x 6), so **every level
|
||||
// means the same geometry on both radios** - which the previous margin-based
|
||||
// scale could not do, because the cost sat inside its formula.
|
||||
//
|
||||
// The two profiles get their own ladders. On a 16-symbol preamble there are
|
||||
// only 8 symbols to spend between the floor and the whole preamble, so the
|
||||
// steps are single symbols; on a 32-symbol preamble there are 24, so the low
|
||||
// levels can take much larger strides while retaining a larger capture margin.
|
||||
static constexpr uint8_t RX_POWERSAVING_GUARDED_LEVELS = 8;
|
||||
static constexpr float RX_POWERSAVING_LEVEL_CATCH_P16[RX_POWERSAVING_GUARDED_LEVELS] = {
|
||||
15.0f, 14.0f, 13.0f, 12.0f, 11.0f, 10.0f, 9.0f, 8.0f
|
||||
};
|
||||
static constexpr float RX_POWERSAVING_LEVEL_CATCH_P32[RX_POWERSAVING_GUARDED_LEVELS] = {
|
||||
24.0f, 20.0f, 16.0f, 14.0f, 12.0f, 10.0f, 9.0f, 8.0f
|
||||
};
|
||||
|
||||
// Smallest catch any guarded level asks for, and the reason it is 8: the
|
||||
// LR11x0 needs 8 symbols to latch where the SX126x needs 6.
|
||||
static constexpr float RX_POWERSAVING_MIN_CATCH_SYMBOLS = 8.0f;
|
||||
|
||||
// On top of the ladder, every guarded level sleeps this much less than the
|
||||
// arithmetic demands - so it catches 0.2 symbols more than its level promises.
|
||||
// The reason is not capture safety: it is that specific register pairs the
|
||||
// calculation lands on are defective (preamble latched, header never
|
||||
// validated) in the same way isolated rxPeriod ticks 320 and 640 are. Nudging
|
||||
// every generated geometry off those points cost 0.05 mA and took the worst
|
||||
// measured cell from 3.33% packet loss to 0.11% across the whole ladder.
|
||||
// Levels 9 and 10 are exempt - their geometries are pinned to bench
|
||||
// measurements and shifting them would invalidate that data.
|
||||
static constexpr float RX_POWERSAVING_MARGIN_PAD_SYMBOLS = 0.2f;
|
||||
|
||||
// Past the guarded scale sit two settings that break the datasheet's
|
||||
// SetRxDutyCycle timer condition on purpose. Upstream bench measurements
|
||||
// reported lower duty cycle for overdrive and packet loss at riskyWorkingMax.
|
||||
// Neither measurement establishes a guarantee for other boards or RF links.
|
||||
static constexpr uint8_t RX_POWERSAVING_OVERDRIVE_LEVEL = 9;
|
||||
static constexpr uint8_t RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL = 10;
|
||||
static constexpr float RX_POWERSAVING_RISKY_WORKING_MAX_VIRTUAL_P32 = 11.0f;
|
||||
static constexpr float RX_POWERSAVING_RISKY_WORKING_MAX_VIRTUAL_P16 = 10.25f;
|
||||
|
||||
// Top of the guarded scale: catches the ladder floor of 8 symbols (8.2 with
|
||||
// the pad), the cheapest setting that still meets the datasheet condition and
|
||||
// still works on both radio families. The CLI calls it `max`.
|
||||
static constexpr uint8_t RX_POWERSAVING_MAX_LEVEL = RX_POWERSAVING_GUARDED_LEVELS;
|
||||
|
||||
#define RX_POWERSAVING_CONSERVATIVE_LEVEL 3 // catches 13 (P16) / 16 (P32)
|
||||
#define RX_POWERSAVING_BALANCED_LEVEL 6 // catches 10 (P16) / 10 (P32)
|
||||
#define RX_POWERSAVING_PROFILE_PREAMBLE 16
|
||||
static constexpr uint8_t RX_POWERSAVING_MAX_CONSEC_ARM_FAILURES = 3;
|
||||
|
||||
// Symbols of a sender's preamble consumed before a packet can be latched:
|
||||
// ~2 to latch the preamble plus ~2 lost to RX-window startup, measured on
|
||||
// SX1262 at SF8/BW62.5. Capture needs sleep <= sender_preamble - this.
|
||||
// Note this is well below the 8 symbols RadioLib quotes (SX126x.h) - that
|
||||
// figure is the datasheet's margin for *reliable* latching, not the floor.
|
||||
//
|
||||
// Chip dependent, so it belongs with the driver rather than with each board:
|
||||
// the build selects the family capture cost. On the upstream bench, LR1110
|
||||
// held 300/300 at a margin of 7.78 symbols and started dropping packets at
|
||||
// 6.89, for both profiles, where SX1262 is clean down to 6.
|
||||
static constexpr float RX_POWERSAVING_CAPTURE_COST_SYMBOLS = 6.0f;
|
||||
static constexpr float RX_POWERSAVING_CAPTURE_COST_SYMBOLS_LR11X0 = 8.0f;
|
||||
|
||||
// TCXO startup delay handed to SetDIO3AsTCXOCtrl (SX126x DS 13.3.6) /
|
||||
// SetTcxoMode (LR11x0 UM 6.3.2). RadioLib defaults it to 5000 us and nothing
|
||||
// overrode it, so every board paid 5 ms on every duty-cycle wake whatever
|
||||
// crystal was fitted. Measured lowest working value on five modules: T096 400,
|
||||
// Tracker V2 300, Waveshare 150, ThinkNode M3 200, T1000-E 200 us - so 1600
|
||||
// keeps 4x margin over the worst of them.
|
||||
//
|
||||
// One knob for the whole tree, in `arduino_base`, because it is a property of
|
||||
// the parts MeshCore is built with rather than of any one board. A variant that
|
||||
// needs its own value defines it in its own build_flags and the later -D wins.
|
||||
#ifndef MC_TCXO_DELAY_US
|
||||
#define MC_TCXO_DELAY_US 1600
|
||||
#endif
|
||||
|
||||
// Sleep -> RX transition: RadioLib subtracts tcxoDelay + 1000 us from the
|
||||
// requested sleep before writing the register, and the hardware spends that
|
||||
// long saving context, restarting the XTAL and locking the PLL. Everything
|
||||
// below derives from it. Callers can supply the resolved transition delay so
|
||||
// both the sleep floor and the timer guard follow it.
|
||||
static constexpr uint32_t RX_POWERSAVING_TRANSITION_US = MC_TCXO_DELAY_US + 1000;
|
||||
|
||||
// Slack the timer guard leaves on top of the datasheet condition, in symbols.
|
||||
//
|
||||
// Closing the condition exactly is not enough. The calculator lands on register
|
||||
// pairs that satisfy it by a hair and still lose packets: rx=2476/sleep=2455
|
||||
// ticks clears it by 22 us at 0.12 symbol and drops 2-6% on every SX1262 tried,
|
||||
// while moving any one component clears the fault. It is the same family as the
|
||||
// isolated bad ticks 320 and 640 - the condition does not predict which pairs
|
||||
// misbehave, so the answer is to stop generating geometries that sit on its
|
||||
// edge. One whole symbol of slack is what the bench evidence supports.
|
||||
#ifndef MC_RXPS_TIMER_SLACK_SYMBOLS
|
||||
#define MC_RXPS_TIMER_SLACK_SYMBOLS 1.0f
|
||||
#endif
|
||||
static constexpr float RX_POWERSAVING_TIMER_SLACK_SYMBOLS = MC_RXPS_TIMER_SLACK_SYMBOLS;
|
||||
|
||||
// SX126x programs its duty cycle in these units and truncates the
|
||||
// microsecond value on the way in. Everything the timer guard compares has to
|
||||
// be expressed in whole ticks or it comes out short by a fraction of one.
|
||||
static constexpr float RX_POWERSAVING_TICK_US = 15.625f;
|
||||
|
||||
// Margin above the transition before a duty cycle actually works; see below.
|
||||
static constexpr uint32_t RX_POWERSAVING_MIN_SLEEP_MARGIN_US = 250;
|
||||
|
||||
// Symbols between the end of the sender's preamble and the end of the header:
|
||||
// the LoRa sync word plus the 8-symbol explicit header. SF5/SF6 use a longer
|
||||
// sync word than SF7 and above. Used by the SetRxDutyCycle timer guard.
|
||||
static constexpr float RX_POWERSAVING_SYNC_SYMBOLS_LOW_SF = 6.25f;
|
||||
static constexpr float RX_POWERSAVING_SYNC_SYMBOLS = 4.25f;
|
||||
static constexpr float RX_POWERSAVING_HEADER_SYMBOLS = 8.0f;
|
||||
|
||||
// Shortest sleep that actually produces a working duty cycle.
|
||||
//
|
||||
// RadioLib subtracts tcxoDelay + 1000 us from the requested sleep before
|
||||
// writing the register. At or below that the register underflows and arming
|
||||
// fails with RADIOLIB_ERR_INVALID_SLEEP_PERIOD (-708), after which the wrapper
|
||||
// falls back to continuous RX while the config still says power saving is on.
|
||||
// Measured on SX1262: the P16 profile fails to arm on levels 1-5 at SF6 and on
|
||||
// levels 1-2 at SF7, exactly where that bound predicts.
|
||||
//
|
||||
// But arming successfully is NOT the boundary. Just above it the SX1262 accepts
|
||||
// the command, returns ERR_NONE, and then detects **zero** preambles - a
|
||||
// silently deaf receiver, which is worse than the honest -708. Measured twice,
|
||||
// on two different SF and RX windows: sleep 6050-6100 us is dead, 6200 us and
|
||||
// everything above it is lossless (40/40 at every value up to 21617 us). The
|
||||
// chip needs roughly 200 us of *programmed* sleep, i.e. ~12 register ticks, so
|
||||
// this leaves 250 us of margin on top of the transition time.
|
||||
//
|
||||
// The default follows MC_TCXO_DELAY_US; a caller can supply another transition.
|
||||
static constexpr uint32_t RX_POWERSAVING_MIN_SLEEP_US =
|
||||
RX_POWERSAVING_TRANSITION_US + RX_POWERSAVING_MIN_SLEEP_MARGIN_US;
|
||||
|
||||
|
||||
// Optional initial settings for infrastructure roles. They are intentionally
|
||||
// disabled unless a build profile supplies them, so upstream/default builds
|
||||
@@ -80,11 +226,19 @@ inline bool rxPowerSavingUsesContinuousFallback(uint32_t rx_us, uint32_t sleep_u
|
||||
|
||||
inline uint32_t rxPowerSavingDefaultTransitionUs() {
|
||||
#if defined(SX126X_DIO3_TCXO_VOLTAGE)
|
||||
// RadioLib uses a 5 ms DIO3 TCXO delay plus 1 ms for sleep/wake.
|
||||
return 6000UL;
|
||||
return SX126X_DIO3_TCXO_VOLTAGE > 0.0f ? MC_TCXO_DELAY_US + 1000UL : 1000UL;
|
||||
#elif defined(LR11X0_DIO3_TCXO_VOLTAGE)
|
||||
return LR11X0_DIO3_TCXO_VOLTAGE > 0.0f ? MC_TCXO_DELAY_US + 1000UL : 1000UL;
|
||||
#else
|
||||
// Crystal and non-SX126x implementations still need transition headroom.
|
||||
return 1000UL;
|
||||
return MC_TCXO_DELAY_US + 1000UL;
|
||||
#endif
|
||||
}
|
||||
|
||||
inline float rxPowerSavingDefaultCaptureCost() {
|
||||
#ifdef USE_LR1110
|
||||
return RX_POWERSAVING_CAPTURE_COST_SYMBOLS_LR11X0;
|
||||
#else
|
||||
return RX_POWERSAVING_CAPTURE_COST_SYMBOLS;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -116,52 +270,186 @@ inline uint32_t ceilPositiveFloat(float value) {
|
||||
return value > (float)rounded ? rounded + 1 : rounded;
|
||||
}
|
||||
|
||||
inline bool calcRxPowerSavingLevel(uint8_t level, uint8_t sf, float bw, uint8_t preamble, uint32_t *rx_us,
|
||||
uint32_t *sleep_us) {
|
||||
if (!rx_us || !sleep_us || level < 1 || level > 10 || sf < 5 || sf > 12
|
||||
|| bw <= 0.0f || !isRxPowerSavingPreamble(preamble)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const float symbol_us = (1000.0f * (float)(1UL << sf)) / bw;
|
||||
const float amount = (float)(level - 1) / 9.0f;
|
||||
const float rx_start_symbols = preamble == 16 ? 12.0f : 16.0f;
|
||||
const float sleep_start_symbols = preamble == 16 ? 2.0f : 15.0f;
|
||||
const float rx_edge_symbols = 8.0f;
|
||||
const float sleep_edge_symbols = (float)preamble + 4.25f - 8.0f;
|
||||
|
||||
const float rx_symbols = rx_start_symbols + amount * (rx_edge_symbols - rx_start_symbols);
|
||||
const float sleep_symbols = sleep_start_symbols + amount * (sleep_edge_symbols - sleep_start_symbols);
|
||||
|
||||
uint32_t calculated_rx_us = ceilPositiveFloat(rx_symbols * symbol_us);
|
||||
uint32_t calculated_sleep_us = (uint32_t)(sleep_symbols * symbol_us);
|
||||
|
||||
// Do not scale an undersized period up: that would break the preamble-overlap
|
||||
// guarantee. The 32 us floor is the first whole-microsecond value that
|
||||
// produces a non-zero timer tick on every supported duty-cycle radio.
|
||||
if (calculated_rx_us < RX_POWERSAVING_MIN_PERIOD_US
|
||||
|| calculated_sleep_us < RX_POWERSAVING_MIN_PERIOD_US) {
|
||||
calculated_rx_us = RX_POWERSAVING_CONTINUOUS_FALLBACK_US;
|
||||
calculated_sleep_us = RX_POWERSAVING_CONTINUOUS_FALLBACK_US;
|
||||
}
|
||||
|
||||
*rx_us = calculated_rx_us;
|
||||
*sleep_us = calculated_sleep_us;
|
||||
return true;
|
||||
inline uint32_t ceilRxPowerSavingValue(float value) {
|
||||
uint32_t rounded = (uint32_t)value;
|
||||
return value > (float)rounded ? rounded + 1 : rounded;
|
||||
}
|
||||
|
||||
// MeshCore wire-preamble convention. SF5-SF8 normally use 32 symbols. Try 64
|
||||
// and then 128 only when every shorter choice fails to support RXPS at any
|
||||
// level. If none works, retain 32 and fall back to continuous receive. This
|
||||
// must stay in sync with RadioLibWrapper::preambleLengthForParams().
|
||||
// SX126x programs its duty cycle in 15.625 us ticks and truncates the
|
||||
// microsecond value on the way in, so a period of 10013 us is really 10000 us
|
||||
// on air while the CLI happily reports 10013. Snapping to the nearest tick and
|
||||
// returning the smallest microsecond value that still lands on it makes the
|
||||
// reported periods the ones the hardware runs - which matters here, because the
|
||||
// register value turned out to be what a duty-cycle defect keys on, not the
|
||||
// microseconds we asked for.
|
||||
inline uint32_t rxPowerSavingTickToUs(uint64_t tick) {
|
||||
if (tick == 0) tick = 1;
|
||||
return (uint32_t)((tick * 125 + 7) / 8); // ceil(tick * 15.625)
|
||||
}
|
||||
|
||||
inline uint32_t snapRxPowerSavingToTick(uint32_t us) {
|
||||
return rxPowerSavingTickToUs(((uint64_t)us * 8 + 62) / 125); // nearest
|
||||
}
|
||||
|
||||
// Rounding the listen window to the *nearest* tick can shave a few microseconds
|
||||
// off, and the timer guard below has no room to give: it must hold with the
|
||||
// register values the radio actually runs. So that one rounds up.
|
||||
inline uint32_t snapRxPowerSavingUpToTick(uint32_t us) {
|
||||
return rxPowerSavingTickToUs(((uint64_t)us * 8 + 124) / 125); // ceil
|
||||
}
|
||||
|
||||
inline float rxPowerSavingLevelCatch(uint8_t level, uint8_t preamble) {
|
||||
if (level < 1 || level > RX_POWERSAVING_GUARDED_LEVELS) return 0.0f;
|
||||
return preamble >= 32 ? RX_POWERSAVING_LEVEL_CATCH_P32[level - 1]
|
||||
: RX_POWERSAVING_LEVEL_CATCH_P16[level - 1];
|
||||
}
|
||||
|
||||
inline bool isRxPowerSavingOverdriveLevel(uint8_t level) {
|
||||
return level == RX_POWERSAVING_OVERDRIVE_LEVEL;
|
||||
}
|
||||
|
||||
inline bool isRxPowerSavingRiskyWorkingMaxLevel(uint8_t level) {
|
||||
return level == RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL;
|
||||
}
|
||||
|
||||
// Both levels past the guarded scale run outside the datasheet's timer
|
||||
// condition. Worth surfacing wherever a level is reported.
|
||||
inline bool isRxPowerSavingUnguardedLevel(uint8_t level) {
|
||||
return level >= RX_POWERSAVING_OVERDRIVE_LEVEL;
|
||||
}
|
||||
|
||||
// rxPeriod register values measured to break SetRxDutyCycle on SX1262: the
|
||||
// radio latches the preamble and then never validates a header, losing 35% of
|
||||
// packets at SF6 and all of them at SF7. Both were reproduced on two boards
|
||||
// with an LR1110 witnessing 100% of the same transmissions, and both bands are
|
||||
// exactly one tick wide - 639 and 641 are lossless.
|
||||
//
|
||||
// This list is certainly incomplete: about thirty values were sampled out of
|
||||
// the thousands a profile can generate. Levels 1-8 do not need it because the
|
||||
// timer guard makes any value safe; it exists only for the unguarded maximum,
|
||||
// where it is the one protection left.
|
||||
static const uint32_t RX_POWERSAVING_BAD_RX_TICKS[] = {320, 640};
|
||||
|
||||
inline uint32_t avoidBadRxPowerSavingTick(uint32_t rx_us) {
|
||||
const uint32_t tick = (rx_us * 8) / 125;
|
||||
for (uint32_t bad : RX_POWERSAVING_BAD_RX_TICKS) {
|
||||
// One tick longer costs 15.625 us of listening and steps clear of the band.
|
||||
if (tick == bad) return (uint32_t)((((uint64_t)tick + 1) * 125 + 7) / 8);
|
||||
}
|
||||
return rx_us;
|
||||
}
|
||||
|
||||
inline bool calcRxPowerSavingLevel(uint8_t level, uint8_t sf, float bw, uint8_t preamble,
|
||||
uint32_t* rx_us, uint32_t* sleep_us,
|
||||
float capture_cost_symbols = rxPowerSavingDefaultCaptureCost(),
|
||||
uint32_t transition_us = rxPowerSavingDefaultTransitionUs()) {
|
||||
if (rx_us == nullptr || sleep_us == nullptr || level < 1 ||
|
||||
level > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL || sf < 5 || sf > 12 ||
|
||||
!(bw > 0.0f) || bw > 1000000.0f || !isRxPowerSavingPreamble(preamble)) {
|
||||
return false;
|
||||
}
|
||||
const bool unguarded = isRxPowerSavingUnguardedLevel(level);
|
||||
|
||||
const float symbol_us = (1000.0f * (float)(1UL << sf)) / bw;
|
||||
// Worst case a preamble starts the instant an RX window closes, so the part
|
||||
// that survives into the next window is `preamble - sleep`. The absolute
|
||||
// limit is therefore reached when that equals the chip's capture cost; the
|
||||
// unguarded levels are pinned to geometries measured at or past that point,
|
||||
// which is why they still need it.
|
||||
const float sleep_edge_symbols = (float)preamble - capture_cost_symbols;
|
||||
|
||||
float sleep_symbols;
|
||||
float rx_symbols = 0.0f; // only used by the unguarded levels
|
||||
if (unguarded) {
|
||||
// Kept on the old interpolation because that is the geometry the bench
|
||||
// measured: overdrive is the top of the profile, and `riskyWorkingMax` is
|
||||
// the point past it where delivery started to fall.
|
||||
float amount = 1.0f;
|
||||
if (isRxPowerSavingRiskyWorkingMaxLevel(level)) {
|
||||
const float virtual_level = preamble == 16 ? RX_POWERSAVING_RISKY_WORKING_MAX_VIRTUAL_P16
|
||||
: RX_POWERSAVING_RISKY_WORKING_MAX_VIRTUAL_P32;
|
||||
amount = (virtual_level - 1.0f) / 9.0f;
|
||||
}
|
||||
const float rx_start_symbols = preamble == 16 ? 12.0f : 16.0f;
|
||||
const float sleep_start_symbols = preamble == 16 ? 2.0f : 15.0f;
|
||||
rx_symbols = rx_start_symbols + amount * (8.0f - rx_start_symbols);
|
||||
sleep_symbols = sleep_start_symbols + amount * (sleep_edge_symbols - sleep_start_symbols);
|
||||
} else {
|
||||
// Guarded levels state their catch directly, so the sleep is just what is
|
||||
// left of the preamble - no capture cost involved. The pad makes the node
|
||||
// catch a fifth of a symbol more than promised, which is what keeps the
|
||||
// generated register pairs off the defective ones.
|
||||
const float catch_symbols = rxPowerSavingLevelCatch(level, preamble);
|
||||
// A level that undertakes to catch less than this radio needs to latch is
|
||||
// not usable: say so rather than return a geometry that cannot work.
|
||||
if (catch_symbols < capture_cost_symbols) return false;
|
||||
sleep_symbols = (float)preamble - catch_symbols - RX_POWERSAVING_MARGIN_PAD_SYMBOLS;
|
||||
if (sleep_symbols < 0.0f) sleep_symbols = 0.0f;
|
||||
}
|
||||
|
||||
*sleep_us = (uint32_t)(sleep_symbols * symbol_us);
|
||||
|
||||
// Below the hardware floor the duty cycle cannot be armed at all: the driver
|
||||
// returns -708 and the wrapper quietly runs continuous RX, so the node keeps
|
||||
// reporting power saving while spending full RX current. Just above that the
|
||||
// SX1262 arms with ERR_NONE and then detects no preambles at all, which is
|
||||
// worse. Measured floor: 6050-6100 us dead, 6200 us and up lossless.
|
||||
const uint32_t min_sleep_us = transition_us + RX_POWERSAVING_MIN_SLEEP_MARGIN_US;
|
||||
if (*sleep_us < min_sleep_us) {
|
||||
if (!unguarded || (float)min_sleep_us > sleep_edge_symbols * symbol_us) {
|
||||
return false;
|
||||
}
|
||||
*sleep_us = min_sleep_us;
|
||||
}
|
||||
*sleep_us = transition_us + snapRxPowerSavingToTick(*sleep_us - transition_us);
|
||||
|
||||
// SetRxDutyCycle timer guard, straight out of the SX1261/2 datasheet: on
|
||||
// preamble detection the radio restarts its timer with 2*rxPeriod +
|
||||
// sleepPeriod (register values), and the packet dies if the header does not
|
||||
// arrive inside it. The datasheet states the requirement as
|
||||
// Tpreamble + Theader <= 2 * rxPeriod + sleepPeriod
|
||||
// Measured: when it holds, no period value causes trouble. When it is broken
|
||||
// the SX1262 usually gets away with it - but not always, and the exceptions
|
||||
// are a single register tick wide. rxPeriod 640 (exactly 10.000 ms) loses
|
||||
// 60-65% of packets at SF6 and everything at SF7, on two different boards,
|
||||
// while 639 and 641 are lossless; rxPeriod 320 behaves the same way. Nothing
|
||||
// in the register value predicts which ticks misbehave, so satisfy the
|
||||
// condition instead of dodging the values. The listen window is therefore not
|
||||
// a free parameter on the guarded scale - it is whatever the condition needs.
|
||||
const float sync_symbols =
|
||||
sf <= 6 ? RX_POWERSAVING_SYNC_SYMBOLS_LOW_SF : RX_POWERSAVING_SYNC_SYMBOLS;
|
||||
const float need_us =
|
||||
((float)preamble + sync_symbols + RX_POWERSAVING_HEADER_SYMBOLS +
|
||||
RX_POWERSAVING_TIMER_SLACK_SYMBOLS) * symbol_us;
|
||||
// Work in the radio's own units: the driver truncates (sleep - transition) to
|
||||
// 15.625 us ticks, so the microsecond difference overstates the programmed
|
||||
// sleep by up to one tick - enough to leave the condition short on every
|
||||
// level of a profile.
|
||||
const uint32_t sleep_ticks = ((*sleep_us - transition_us) * 8) / 125;
|
||||
const float programmed_sleep_us = (float)sleep_ticks * RX_POWERSAVING_TICK_US;
|
||||
|
||||
if (unguarded) {
|
||||
*rx_us = ceilRxPowerSavingValue(rx_symbols * symbol_us);
|
||||
} else {
|
||||
const float min_rx_us = (need_us - programmed_sleep_us) / 2.0f;
|
||||
*rx_us = ceilRxPowerSavingValue(min_rx_us > 0.0f ? min_rx_us : symbol_us);
|
||||
}
|
||||
|
||||
*rx_us = snapRxPowerSavingUpToTick(*rx_us);
|
||||
if (unguarded) *rx_us = avoidBadRxPowerSavingTick(*rx_us);
|
||||
return isValidRxPowerSavingPeriod(*rx_us) && isValidRxPowerSavingPeriod(*sleep_us);
|
||||
}
|
||||
|
||||
// Preserve the deployed Cascade wire-preamble convention. The longer choices
|
||||
// were established with the previous timing model and 6 ms transition budget.
|
||||
// They remain a network compatibility contract, independent of the new local
|
||||
// RXPS model, oscillator configuration, or whether RXPS is enabled.
|
||||
inline uint8_t rxPowerSavingPreambleForParams(uint8_t sf, float bw) {
|
||||
if (sf > 8) return 16;
|
||||
if (sf < 5 || bw <= 0.0f) return 32;
|
||||
|
||||
// The validated LoRa bandwidth grid tops out at 500 kHz and contains 125,
|
||||
// 250, and 500 kHz at the fast end. Checking the resulting safe boundaries
|
||||
// directly is equivalent to searching all ten levels, but keeps this common
|
||||
// sender-side decision small enough for the 256 KiB STM32WL targets.
|
||||
// Fixed boundaries keep every sender compatible and avoid a timing-model
|
||||
// search in the sender path on small STM32WL targets.
|
||||
if (sf >= 7 || bw <= 125.0f || (sf == 6 && bw <= 250.0f)) return 32;
|
||||
if (sf == 6 || bw <= 250.0f) return 64;
|
||||
return 128;
|
||||
@@ -180,7 +468,7 @@ inline bool calcRxPowerSavingLevelAtOrAbove(
|
||||
uint8_t *effective_level = nullptr,
|
||||
uint8_t *effective_preamble = nullptr) {
|
||||
if (!rx_us || !sleep_us || requested_level < 1 || requested_level > 10
|
||||
|| sf < 5 || sf > 12 || bw <= 0.0f
|
||||
|| sf < 5 || sf > 12 || !(bw > 0.0f) || bw > 1000000.0f
|
||||
|| !isRxPowerSavingPreamble(preamble)) {
|
||||
return false;
|
||||
}
|
||||
@@ -196,19 +484,28 @@ inline bool calcRxPowerSavingLevelAtOrAbove(
|
||||
for (uint8_t pass = 0; pass < pass_count; pass++) {
|
||||
const uint8_t candidate_preamble = pass == 0
|
||||
? configured_preamble : transmitted_preamble;
|
||||
for (uint8_t level = requested_level; level <= 10; level++) {
|
||||
const float symbol_us = (1000.0f * (float)(1UL << sf)) / bw;
|
||||
const float amount = (float)(level - 1) / 9.0f;
|
||||
const float rx_start_symbols = candidate_preamble == 16 ? 12.0f : 16.0f;
|
||||
const float sleep_start_symbols = candidate_preamble == 16 ? 2.0f : 15.0f;
|
||||
const float rx_edge_symbols = 8.0f;
|
||||
const float sleep_edge_symbols = (float)candidate_preamble + 4.25f - 8.0f;
|
||||
const float rx_symbols = rx_start_symbols
|
||||
+ amount * (rx_edge_symbols - rx_start_symbols);
|
||||
const float sleep_symbols = sleep_start_symbols
|
||||
+ amount * (sleep_edge_symbols - sleep_start_symbols);
|
||||
const uint32_t candidate_rx_us = ceilPositiveFloat(rx_symbols * symbol_us);
|
||||
const uint32_t candidate_sleep_us = (uint32_t)(sleep_symbols * symbol_us);
|
||||
// Automatic adjustment never opts an operator into experimental levels.
|
||||
const uint8_t last_level = requested_level <= RX_POWERSAVING_MAX_LEVEL
|
||||
? RX_POWERSAVING_MAX_LEVEL : requested_level;
|
||||
for (uint8_t level = requested_level; level <= last_level; level++) {
|
||||
uint32_t candidate_rx_us = 0, candidate_sleep_us = 0;
|
||||
if (!calcRxPowerSavingLevel(level, sf, bw, candidate_preamble,
|
||||
&candidate_rx_us, &candidate_sleep_us,
|
||||
rxPowerSavingDefaultCaptureCost(), transition_us)) continue;
|
||||
|
||||
// The catch assumption can be conservative, but the receive timeout
|
||||
// must still cover the entire preamble our senders actually transmit.
|
||||
if (!isRxPowerSavingUnguardedLevel(level)) {
|
||||
const float symbol_us = (1000.0f * (float)(1UL << sf)) / bw;
|
||||
const float sync = sf <= 6 ? RX_POWERSAVING_SYNC_SYMBOLS_LOW_SF
|
||||
: RX_POWERSAVING_SYNC_SYMBOLS;
|
||||
const float need = (transmitted_preamble + sync
|
||||
+ RX_POWERSAVING_HEADER_SYMBOLS + RX_POWERSAVING_TIMER_SLACK_SYMBOLS) * symbol_us;
|
||||
const uint32_t sleep_ticks = ((candidate_sleep_us - transition_us) * 8UL) / 125UL;
|
||||
const uint32_t guarded_rx = snapRxPowerSavingUpToTick(ceilRxPowerSavingValue(
|
||||
(need - sleep_ticks * RX_POWERSAVING_TICK_US) / 2.0f));
|
||||
if (guarded_rx > candidate_rx_us) candidate_rx_us = guarded_rx;
|
||||
}
|
||||
|
||||
if (isValidRxPowerSavingPeriod(candidate_rx_us)
|
||||
&& isValidRxPowerSavingPeriod(candidate_sleep_us)
|
||||
|
||||
@@ -8,14 +8,11 @@
|
||||
#define STATE_TX_DONE 4
|
||||
#define STATE_INT_READY 16
|
||||
|
||||
#define NUM_NOISE_FLOOR_SAMPLES 64
|
||||
#define SAMPLING_THRESHOLD 14
|
||||
|
||||
// On-demand noise-floor calibration windows (RX duty-cycle powersaving only).
|
||||
// Bounded noise-floor calibration in continuous RX, including RXPS refreshes.
|
||||
// Requests are coalesced so retries cannot repeatedly force continuous RX.
|
||||
#define NF_CALIB_INTERVAL_MS 2000UL // match the original 2-second refresh cadence
|
||||
#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_TIMEOUT_MS NoiseFloorEstimator::WINDOW_TIMEOUT_MS
|
||||
#define NF_CONTINUOUS_TIMEOUT_MS NoiseFloorEstimator::WINDOW_TIMEOUT_MS
|
||||
#define NF_CALIB_SETTLE_MS 20UL // frontend/AGC settle after RX entry
|
||||
|
||||
static volatile uint8_t state = STATE_IDLE;
|
||||
@@ -66,13 +63,14 @@ void RadioLibWrapper::begin() {
|
||||
_noise_floor_valid = false;
|
||||
_threshold = 0;
|
||||
_cad_enabled = false;
|
||||
_rx_mode_checked_at = millis();
|
||||
_rx_mode_failures = 0;
|
||||
_last_rssi = 0;
|
||||
_last_snr = 0;
|
||||
_rx_hold_continuous = false;
|
||||
|
||||
// start average out some samples
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum_centi_dbm = 0;
|
||||
_floor_estimator.reset(true);
|
||||
_nf_calib_active = false;
|
||||
_nf_last_calib = 0;
|
||||
_nf_sample_from = 0;
|
||||
@@ -226,14 +224,12 @@ void RadioLibWrapper::triggerNoiseFloorCalibrate(int threshold) {
|
||||
}
|
||||
|
||||
void RadioLibWrapper::recalibrateNoiseFloor() {
|
||||
// A receive-gain change can move the real floor above the old floor's
|
||||
// sampling gate. Invalidate that reference so the next batch is seeded from
|
||||
// scratch instead of rejecting the new baseline as interference.
|
||||
// A gain or tuning change starts a new baseline. Keep the published value
|
||||
// available while discarding the old samples and rise-hold history.
|
||||
_noise_floor_valid = false;
|
||||
_nf_refresh_requested = true;
|
||||
_nf_last_calib = 0;
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum_centi_dbm = 0;
|
||||
_floor_estimator.reset(true);
|
||||
|
||||
const unsigned long now = millis();
|
||||
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
|
||||
@@ -251,8 +247,7 @@ void RadioLibWrapper::recalibrateNoiseFloor() {
|
||||
void RadioLibWrapper::requestNoiseFloorRefresh() {
|
||||
if (_nf_refresh_requested) return;
|
||||
_nf_refresh_requested = true;
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum_centi_dbm = 0;
|
||||
_floor_estimator.reset();
|
||||
_nf_calib_deadline = 0; // starts when continuous RX is actually available
|
||||
}
|
||||
|
||||
@@ -268,10 +263,12 @@ void RadioLibWrapper::resetAGC() {
|
||||
state = STATE_IDLE; // trigger a startReceive()
|
||||
if (_rx_boosted_gain_valid) applyRxBoostedGainMode(_cur_rx_boosted_gain);
|
||||
|
||||
// Preserve the last published value while a fresh post-reset batch is
|
||||
// collected. Invalidating the sample gate lets the new floor converge even
|
||||
// when the old value was stuck at its lower clamp.
|
||||
// AGC reset discards stale samples, but the established floor remains usable
|
||||
// for LBT while the next spaced block is collected. Gain/tuning changes use
|
||||
// recalibrateNoiseFloor() directly to seed a fresh baseline.
|
||||
const bool previous_valid = _noise_floor_valid;
|
||||
recalibrateNoiseFloor();
|
||||
_noise_floor_valid = previous_valid;
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::recoverRadio(bool hard) {
|
||||
@@ -407,9 +404,9 @@ void RadioLibWrapper::noiseFloorCalibCheck(unsigned long now) {
|
||||
if (_nf_calib_active) {
|
||||
if (!_rx_ps_enabled
|
||||
|| ((long)(now - _nf_calib_deadline) >= 0
|
||||
&& _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES)) {
|
||||
&& !_floor_estimator.complete())) {
|
||||
// powersaving turned off mid-window, or the batch couldn't complete
|
||||
// (busy channel / stuck filter) - keep the previous floor
|
||||
// (busy channel) - keep the previous floor
|
||||
endNoiseFloorCalib(now);
|
||||
} else if (_rx_ps_armed && !isPacketPendingOrReceiving()) {
|
||||
// A packet can delay the transition from RXPS to continuous RX. Retry
|
||||
@@ -425,8 +422,7 @@ void RadioLibWrapper::noiseFloorCalibCheck(unsigned long now) {
|
||||
_nf_calib_active = true;
|
||||
_nf_calib_deadline = now + NF_CALIB_TIMEOUT_MS;
|
||||
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
|
||||
_num_floor_samples = 0; // start a fresh batch for this window
|
||||
_floor_sample_sum_centi_dbm = 0;
|
||||
_floor_estimator.reset();
|
||||
if (!isPacketPendingOrReceiving()) {
|
||||
requestRestartRecv(); // startReceiveMode() selects continuous RX
|
||||
}
|
||||
@@ -447,11 +443,39 @@ void RadioLibWrapper::endNoiseFloorCalib(unsigned long now) {
|
||||
}
|
||||
}
|
||||
|
||||
void RadioLibWrapper::checkReceiveMode(uint32_t now) {
|
||||
// Duty-cycle standby/sleep is expected. Never wake it for a status probe,
|
||||
// touch an in-flight TX, or discard a completed/pending receive interrupt.
|
||||
if (state != STATE_RX || _rx_ps_armed || isChipBusy()
|
||||
|| uint32_t(now - _rx_mode_checked_at) < 10000UL) return;
|
||||
_rx_mode_checked_at = now;
|
||||
if (isPacketPendingOrReceiving()) return;
|
||||
const int8_t mode = readReceiveMode();
|
||||
if (isPacketPendingOrReceiving()) return;
|
||||
if (mode < 0) return; // an SPI error is not evidence of a particular mode
|
||||
if (mode == 1) {
|
||||
_rx_mode_failures = 0;
|
||||
return;
|
||||
}
|
||||
if (_rx_mode_failures < 3) ++_rx_mode_failures;
|
||||
if (_rx_mode_failures < 2) return;
|
||||
|
||||
// Confirmed silent loss of RX (including a late RTC event after CAD).
|
||||
// Reuse the existing recovery path: it preserves tuning, TX power and gain.
|
||||
// A healthy status observation, rather than an accepted re-arm command,
|
||||
// clears the streak. A failed soft recovery can therefore reach hard reset.
|
||||
_floor_estimator.reset(true);
|
||||
MESH_DEBUG_PRINTLN("RadioLibWrapper: chip left RX, %s recovery",
|
||||
_rx_mode_failures < 3 ? "soft" : "hard");
|
||||
recoverRadio(_rx_mode_failures >= 3);
|
||||
}
|
||||
|
||||
void RadioLibWrapper::loop() {
|
||||
if (_rx_ps_enabled && !_rx_ps_continuous_fallback) {
|
||||
rxPsWatchdogCheck();
|
||||
}
|
||||
unsigned long now = millis();
|
||||
checkReceiveMode(static_cast<uint32_t>(now));
|
||||
if (_nf_calib_active || _nf_refresh_requested) {
|
||||
noiseFloorCalibCheck(now);
|
||||
}
|
||||
@@ -463,31 +487,12 @@ void RadioLibWrapper::loop() {
|
||||
// or a request made while the radio is idle, transmitting, or starting up.
|
||||
_nf_calib_deadline = now + NF_CONTINUOUS_TIMEOUT_MS;
|
||||
}
|
||||
if (_nf_refresh_requested && _num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES
|
||||
&& _floor_sample_sum_centi_dbm != 0) {
|
||||
int32_t sampled_floor_centi_dbm =
|
||||
_floor_sample_sum_centi_dbm / NUM_NOISE_FLOOR_SAMPLES;
|
||||
if (sampled_floor_centi_dbm < -12000) {
|
||||
sampled_floor_centi_dbm = -12000;
|
||||
if (_nf_refresh_requested && _floor_estimator.complete()) {
|
||||
if (_floor_estimator.publish(_noise_floor_centi_dbm, _noise_floor_valid)) {
|
||||
_noise_floor_valid = true;
|
||||
// Retain the whole-dB API/wire format and the fractional display value.
|
||||
_noise_floor = (_noise_floor_centi_dbm - 50) / 100;
|
||||
}
|
||||
if (_noise_floor_valid) {
|
||||
// Favor the fresh high-rate batch while retaining a small amount of
|
||||
// history: 25% previous floor + 75% newly sampled floor.
|
||||
int32_t weighted_floor = _noise_floor_centi_dbm
|
||||
+ 3L * sampled_floor_centi_dbm;
|
||||
_noise_floor_centi_dbm = weighted_floor < 0
|
||||
? (weighted_floor - 2) / 4
|
||||
: (weighted_floor + 2) / 4;
|
||||
} else {
|
||||
_noise_floor_centi_dbm = sampled_floor_centi_dbm;
|
||||
}
|
||||
// Preserve the existing whole-dB API and wire formats while exposing the
|
||||
// fractional 64-sample mean to local displays.
|
||||
_noise_floor = _noise_floor_centi_dbm < 0
|
||||
? (_noise_floor_centi_dbm - 50) / 100
|
||||
: (_noise_floor_centi_dbm + 50) / 100;
|
||||
_floor_sample_sum_centi_dbm = 0;
|
||||
_noise_floor_valid = true;
|
||||
_nf_refresh_requested = false;
|
||||
_nf_last_calib = now;
|
||||
_nf_calib_deadline = 0;
|
||||
@@ -495,7 +500,7 @@ void RadioLibWrapper::loop() {
|
||||
MESH_DEBUG_PRINTLN("RadioLibWrapper: noise_floor = %d", (int)_noise_floor);
|
||||
|
||||
if (_nf_calib_active) {
|
||||
endNoiseFloorCalib(now); // fresh floor published - back to duty cycle
|
||||
endNoiseFloorCalib(now); // complete block, including a held rise - back to duty cycle
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -510,30 +515,23 @@ void RadioLibWrapper::loop() {
|
||||
_nf_refresh_requested = false;
|
||||
_nf_last_calib = now;
|
||||
_nf_calib_deadline = 0;
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum_centi_dbm = 0;
|
||||
_floor_estimator.reset();
|
||||
}
|
||||
|
||||
if (_nf_refresh_requested && state == STATE_RX
|
||||
&& _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES) {
|
||||
&& !_floor_estimator.complete()) {
|
||||
// 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). Skip the first moments after entering RX or changing
|
||||
// gain while the frontend/AGC settles (unsettled GetRssiInst reads
|
||||
// ~-127 dBm garbage).
|
||||
if (!_rx_ps_armed
|
||||
&& _floor_estimator.ready(static_cast<uint32_t>(now))
|
||||
&& !(_nf_sample_from != 0 && (long)(now - _nf_sample_from) < 0)
|
||||
&& !isReceivingPacket()) {
|
||||
float rssi = getCurrentRSSI();
|
||||
if (!_noise_floor_valid
|
||||
|| rssi < getNoiseFloorDbm() + SAMPLING_THRESHOLD) {
|
||||
// With no valid baseline (startup, AGC reset, or gain change), seed
|
||||
// unconditionally. Otherwise reject likely traffic above the current
|
||||
// floor plus the sampling margin.
|
||||
_num_floor_samples++;
|
||||
_floor_sample_sum_centi_dbm +=
|
||||
static_cast<int32_t>(rssi * 100.0f);
|
||||
}
|
||||
// Admission is independent of the old floor, allowing upward recovery.
|
||||
// The estimator enforces 50 ms spacing and rejects invalid radio readings.
|
||||
_floor_estimator.add(getCurrentRSSI(), static_cast<uint32_t>(now));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -541,7 +539,11 @@ void RadioLibWrapper::loop() {
|
||||
void RadioLibWrapper::startRecv() {
|
||||
int err = startReceiveMode();
|
||||
if (err == RADIOLIB_ERR_NONE) {
|
||||
state = STATE_RX;
|
||||
// A very short frame may complete while startReceiveMode() returns.
|
||||
// Retain that RX interrupt instead of overwriting it with software state.
|
||||
noInterrupts();
|
||||
state = (state & STATE_INT_READY) | STATE_RX;
|
||||
interrupts();
|
||||
_startrx_fails = 0;
|
||||
if (_rx_ps_armed) {
|
||||
// (re)base the duty-cycle watchdog on the freshly armed cycle
|
||||
@@ -770,6 +772,7 @@ int16_t RadioLibWrapper::performChannelScanWithTimeout(unsigned long timeout_ms)
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::isChannelActive() {
|
||||
if (isPacketPendingOrReceiving() || (state & ~STATE_INT_READY) == STATE_TX_WAIT) return true;
|
||||
// int.thresh: RSSI-based interference detection (relative to noise floor).
|
||||
// In RX duty-cycle mode only checked while the chip is in a listen window
|
||||
// (during the sleep window the frontend is off and the read would stall).
|
||||
@@ -789,7 +792,8 @@ bool RadioLibWrapper::isChannelActive() {
|
||||
// try to read a non-existent packet and count a spurious recv error.
|
||||
state = STATE_IDLE;
|
||||
startRecv();
|
||||
if (result != RADIOLIB_CHANNEL_FREE) {
|
||||
if (result != RADIOLIB_CHANNEL_FREE || (state & ~STATE_INT_READY) != STATE_RX
|
||||
|| isPacketPendingOrReceiving()) {
|
||||
_board->n_cad_busy++;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "NoiseFloorEstimator.h"
|
||||
|
||||
#include <Mesh.h>
|
||||
#include <RadioLib.h>
|
||||
#include "CadTiming.h"
|
||||
@@ -36,8 +38,9 @@ protected:
|
||||
uint32_t _cad_scan_timeout_override_ms;
|
||||
bool _noise_floor_valid;
|
||||
bool _nf_refresh_requested;
|
||||
uint16_t _num_floor_samples;
|
||||
int32_t _floor_sample_sum_centi_dbm;
|
||||
NoiseFloorEstimator _floor_estimator;
|
||||
uint32_t _rx_mode_checked_at = 0;
|
||||
uint8_t _rx_mode_failures = 0;
|
||||
unsigned long last_recv_millis;
|
||||
unsigned long last_radio_interrupt_millis; // updated on any ISR event, even CRC errors
|
||||
bool _rx_ps_enabled;
|
||||
@@ -141,6 +144,8 @@ protected:
|
||||
bool restoreAfterDeepInit();
|
||||
float packetScoreInt(float snr, int sf, int packet_len);
|
||||
virtual bool isReceivingPacket() =0;
|
||||
virtual int8_t readReceiveMode() { return -1; }
|
||||
void checkReceiveMode(uint32_t now);
|
||||
virtual void doResetAGC();
|
||||
|
||||
public:
|
||||
@@ -244,7 +249,7 @@ public:
|
||||
// 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 noise-floor batch needs prompt loop service; the app's
|
||||
// hasPendingWork() keeps the MCU awake only for this short sample burst.
|
||||
// hasPendingWork() keeps the MCU awake for the bounded spaced-sample window.
|
||||
bool isCalibratingNoiseFloor() const {
|
||||
return _nf_calib_active
|
||||
|| (_nf_refresh_requested
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
#include <RadioLib.h>
|
||||
|
||||
// -1: no reliable observation, 0: confirmed non-RX mode, 1: RX.
|
||||
// GetStatus is C0 followed by one response byte (Semtech sx126x driver).
|
||||
// RadioLib's pinned getStatus() requests zero payload bytes and returns zero.
|
||||
template <typename Radio>
|
||||
inline int8_t sx126xReceiveMode(Radio* radio) {
|
||||
Module* module = radio->getMod();
|
||||
const uint32_t busy = module->getGpio();
|
||||
if (busy != RADIOLIB_NC && module->hal->digitalRead(busy)) return -1;
|
||||
|
||||
// GetStatus has no separate status-prefix byte. Use the normal SPI transport
|
||||
// with that command's layout, then restore the layout used by other commands.
|
||||
const Module::BitWidth_t status_width = module->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_STATUS];
|
||||
module->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_STATUS] = Module::BITS_0;
|
||||
uint8_t status = 0;
|
||||
const int16_t result = module->SPIreadStream(
|
||||
RADIOLIB_SX126X_CMD_GET_STATUS, &status, 1, false, false);
|
||||
module->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_STATUS] = status_width;
|
||||
if (result != RADIOLIB_ERR_NONE || status == 0 || status == 0xFF) return -1;
|
||||
const uint8_t mode = (status >> 4) & 7;
|
||||
if (mode < 2 || mode > 6) return -1;
|
||||
return mode == 5 ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user