Merge main into ota-admin: tools split, WITH_RX_POWERSAVING

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-13 16:12:20 +01:00
commit 81d7f600d8
53 files changed
+7121 -64

No files matched your search

+4
View File
@@ -413,6 +413,10 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
const char *key = (num > 0) ? parts[0] : "";
const char *value = (num > 1) ? parts[1] : "null";
if (_sensors->setSettingValue(key, value)) {
if (strcmp(key, "ina.shunt") == 0) { // CUSTOM (TeTeHacko): survives a reboot
_prefs->ina_shunt_mohm = atof(value);
savePrefs();
}
strcpy(reply, "ok");
} else {
strcpy(reply, "can't find custom var");
+15
View File
@@ -68,8 +68,12 @@ public:
uint8_t advert_loc_policy = 0;
uint32_t discovery_mod_timestamp = 0;
float adc_multiplier = 0;
float ina_shunt_mohm = 0; // CUSTOM (TeTeHacko): INA shunt in mOhm, 0 = build default
char owner_info[120];
uint8_t rx_boosted_gain = 0; // power settings
#ifdef WITH_RX_POWERSAVING
RxPowerSavingConfig rxps; // CUSTOM (TeTeHacko): RX duty cycle, off by default
#endif
uint8_t radio_fem_rxgain = 0; // LoRa FEM RX gain setting
uint8_t radio_fem_txgain = 0; // LoRa FEM TX gain setting
uint8_t path_hash_mode = 0; // which path mode to use when sending
@@ -124,10 +128,20 @@ private:
def("agc_int", _parent->agc_reset_interval);
def("hash_mode", _parent->path_hash_mode);
def("multi_ack", _parent->multi_acks);
#ifdef WITH_RX_POWERSAVING
def("rxps_en", _parent->rxps.enabled);
def("rxps_rx_us", _parent->rxps.rx_us);
def("rxps_sleep_us", _parent->rxps.sleep_us);
def("rxps_level", _parent->rxps.level);
def("rxps_preamble", _parent->rxps.preamble);
#endif
def("rsilence", _parent->radio_silence_min);
}
public:
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
#ifdef WITH_RX_POWERSAVING
RxPowerSavingConfig* getRxPowerSavingConfig() override { return &_parent->rxps; }
#endif
// CommonRadioPrefs interface
float getFreq() const override { return _parent->freq; }
void setFreq(float f) override { _parent->freq = f; markDirty(); }
@@ -225,6 +239,7 @@ private:
protected:
void structure() override {
def("adc_mult", _parent->adc_multiplier);
def("ina_shunt", _parent->ina_shunt_mohm);
def("pwr_sav_en", _parent->powersaving_enabled);
def("bicon", _parent->batt_icon);
def("bicon_lo", _parent->batt_icon_lo);
+66
View File
@@ -3,6 +3,9 @@
#include "Utils.h"
#include "target.h"
#include <ctype.h>
#ifdef WITH_RX_POWERSAVING
#include "radiolib/RXPowerSavingCLI.h"
#endif
namespace {
@@ -17,8 +20,35 @@ bool looksLikeANumber(const char* s) {
return isdigit((unsigned char)*s) || *s == '.';
}
#ifdef WITH_RX_POWERSAVING
RxPowerSavingControl* rxpsControl() {
#ifdef WRAPPER_CLASS
return &radio_driver;
#else
return nullptr;
#endif
}
#endif
} // namespace
#ifdef WITH_RX_POWERSAVING
bool CommonRadioPrefs::applyRxPowerSaving(uint8_t sf, float bw) {
_active_sf = sf;
_active_bw = bw;
RxPowerSavingConfig* config = getRxPowerSavingConfig();
if (!config) return false;
// temporary radio parameters must not overwrite the saved automatic periods
RxPowerSavingConfig active = *config;
return applyRxPowerSavingConfig(&active, sf, bw, rxpsControl());
}
bool CommonRadioPrefs::isRxPowerSavingCalibrationActive() const {
const auto* control = rxpsControl();
return control && control->isRxPowerSavingCalibrationActive();
}
#endif
bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) {
if (strcmp(key, "fem_rxgain") == 0) {
snprintf(value, max_len, "%d", (uint32_t)getFEMRxGain());
@@ -45,6 +75,30 @@ bool CommonRadioPrefs::setByKey(const char* key, const char* value) {
}
bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timestamp, char* reply) {
#ifdef WITH_RX_POWERSAVING
if (strncmp(command, "get radio.rxps", 14) == 0 && (command[14] == 0 || command[14] == ' ')) {
const char* suffix = command + 14;
while (*suffix == ' ') ++suffix;
if (*suffix) return false;
auto* config = getRxPowerSavingConfig();
if (!config) { strcpy(reply, "Error: unsupported"); return true; }
const uint8_t sf = _active_sf ? _active_sf : getSpreadFactor();
const float bw = _active_sf ? _active_bw : getBandwidth();
RxPowerSavingConfig active = *config;
normalizeRxPowerSavingConfig(&active, sf, bw,
rxPowerSavingCaptureCost(rxpsControl()), rxPowerSavingTransition(rxpsControl()));
RXPowerSavingCLI::get(&active, rxpsControl(), sf, bw, reply, 160);
return true;
}
if (strncmp(command, "set radio.rxps ", 15) == 0) {
auto* config = getRxPowerSavingConfig();
if (!config) { strcpy(reply, "Error: unsupported"); return true; }
if (RXPowerSavingCLI::set(command + 15,
_active_sf ? _active_sf : getSpreadFactor(), _active_sf ? _active_bw : getBandwidth(),
config, rxpsControl(), reply, 160)) markDirty();
return true;
}
#endif
if (strcmp(command, "get radio") == 0) {
char freq[16], bw[16];
strcpy(freq, StrHelper::ftoa(getFreq()));
@@ -66,7 +120,19 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
setCodingRate(cr);
setFreq(freq);
setBandwidth(bw);
#ifdef WITH_RX_POWERSAVING
// the RXPS timing is in symbols: a new SF/BW can make it invalid
auto* rxps = getRxPowerSavingConfig();
const bool timing_ok = !rxps || !rxps->enabled || normalizeRxPowerSavingConfig(
rxps, sf, bw, rxPowerSavingCaptureCost(rxpsControl()), rxPowerSavingTransition(rxpsControl()));
if (!timing_ok && rxpsControl()) {
rxpsControl()->setRxPowerSaving(false, rxps->rx_us, rxps->sleep_us);
rxpsControl()->setRxPowerSavingConfigError(true);
}
strcpy(reply, timing_ok ? "OK - reboot to apply" : "OK - reboot to apply; RXPS continuous: invalid timing");
#else
strcpy(reply, "OK - reboot to apply");
#endif
} else {
strcpy(reply, "Error, invalid radio params");
}
+16
View File
@@ -1,9 +1,16 @@
#pragma once
#include "ConfigSerializer.h"
#include "KeyValueStore.h"
#ifdef WITH_RX_POWERSAVING
#include "radiolib/RXPowerSaving.h"
#endif
class CommonRadioPrefs : public ConfigSerializer, public KeyValueStore {
bool _is_dirty = false;
#ifdef WITH_RX_POWERSAVING
uint8_t _active_sf = 0; // what the radio runs now (tempradio differs from prefs)
float _active_bw = 0;
#endif
protected:
CommonRadioPrefs() { }
public:
@@ -64,6 +71,15 @@ public:
bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply);
#ifdef WITH_RX_POWERSAVING
// CUSTOM (TeTeHacko): RXPS, see radiolib/RXPowerSaving.h. Prefs that carry an
// RXPS config override getRxPowerSavingConfig(); apply after every change of
// the radio's SF/BW (the timing is in symbols).
virtual RxPowerSavingConfig* getRxPowerSavingConfig() { return nullptr; }
bool applyRxPowerSaving(uint8_t sf, float bw);
bool isRxPowerSavingCalibrationActive() const;
#endif
bool setByKey(const char* key, const char* value) override; // for dynamic key/value access
bool getByKey(const char* key, char* value, size_t max_len) override;
};
+10
View File
@@ -1,6 +1,7 @@
#pragma once
#include <CayenneLPP.h>
#include <stdio.h>
#include "sensors/LocationProvider.h"
#define TELEM_PERM_BASE 0x01 // 'base' permission includes battery
@@ -60,6 +61,15 @@ public:
// With a periodic collector that costs one cycle and needs no scheduling.
virtual void requestLocationRefresh() { }
// CUSTOM (TeTeHacko): the INA shunt (mOhm) from prefs back into the driver
// after boot; 0 = keep the build's value. A no-op without an INA chip.
void applyInaShunt(float mohm) {
if (mohm <= 0) return;
char v[16];
snprintf(v, sizeof(v), "%.3f", mohm);
setSettingValue("ina.shunt", v);
}
// Live I2C scan, written into dest as text. Returns the number of devices
// that answered, or -1 when the platform has no bus to scan.
//
+65
View File
@@ -2,6 +2,9 @@
#include <RadioLib.h>
#include "MeshCore.h"
#ifdef WITH_RX_POWERSAVING
#include "RXPowerSaving.h" // MC_TCXO_DELAY_US
#endif
class CustomSX1262 : public SX1262 {
uint32_t _preambleMillis = 66;
@@ -12,6 +15,68 @@ class CustomSX1262 : public SX1262 {
public:
CustomSX1262(Module *mod) : SX1262(mod) { }
#ifdef WITH_RX_POWERSAVING
// CUSTOM (TeTeHacko): RXPS support, from EasySkyMesh PowerSaving v18.
// The sleep -> RX transition RadioLib subtracts from a duty-cycle sleep;
// protected in the RadioLib base, read through here.
uint32_t getTcxoDelay() const { return tcxoDelay; }
// RadioLib's begin() installs a 5000 us TCXO startup delay, which is also the
// floor of every duty-cycle sleep. MC_TCXO_DELAY_US (1600, 4x the worst of
// five measured modules) is written afterwards and the RC calibrations redone.
// Every variant reaches the radio through this class (std_init() calls it).
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;
}
// tcxoVoltage read back from the chip object: begin() zeroes it when it falls
// back to an XTAL, and a TCXO supply on DIO3 of a board without one is 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);
delay(50);
return state;
}
int16_t startReceiveDutyCycle(uint32_t rxPeriod, uint32_t sleepPeriod,
RadioLibIrqFlags_t irqFlags = RADIOLIB_IRQ_RX_DEFAULT_FLAGS,
RadioLibIrqFlags_t irqMask = RADIOLIB_IRQ_RX_DEFAULT_MASK) {
int16_t state = SX1262::startReceiveDutyCycle(rxPeriod, sleepPeriod, irqFlags, irqMask);
if (state == RADIOLIB_ERR_NONE) {
// RadioLib stages RX through standby, which leaves a host-controlled
// RXEN switch in IDLE; set it back to RX for the whole duty cycle.
this->mod->setRfSwitchState(Module::MODE_RX);
}
return state;
}
// BUSY is high in the duty cycle's sleep phase.
bool isChipBusy() {
uint32_t busy = this->mod->getGpio();
return busy != RADIOLIB_NC && this->mod->hal->digitalRead(busy);
}
int16_t stopRTC() {
uint8_t rtcStop = 0x00;
int16_t state = writeRegister(RADIOLIB_SX126X_REG_RTC_CTRL, &rtcStop, 1);
RADIOLIB_ASSERT(state);
uint8_t rtcEvent = 0;
state = readRegister(RADIOLIB_SX126X_REG_EVENT_MASK, &rtcEvent, 1);
RADIOLIB_ASSERT(state);
rtcEvent |= 0x02;
return writeRegister(RADIOLIB_SX126X_REG_EVENT_MASK, &rtcEvent, 1);
}
#endif
#ifdef RP2040_PLATFORM
bool std_init(SPIClassRP2040* spi = NULL)
#else
@@ -12,7 +12,19 @@ class CustomSX1262Wrapper : public RadioLibWrapper {
public:
CustomSX1262Wrapper(CustomSX1262& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
#ifdef WITH_RX_POWERSAVING
// The duty-cycle sleep floor is this board's TCXO delay + 1000 us (RadioLib
// subtracts it from the sleep; below it the register underflows).
uint32_t rxPowerSavingTransitionUs() const override {
return ((CustomSX1262 *)_radio)->getTcxoDelay() + 1000;
}
bool supportsRxPowerSaving() const override { return true; }
#endif
void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
#ifdef WITH_RX_POWERSAVING
prepareForRadioConfig();
#endif
((CustomSX1262 *)_radio)->setFrequency(freq);
((CustomSX1262 *)_radio)->setSpreadingFactor(sf);
((CustomSX1262 *)_radio)->setBandwidth(bw);
@@ -29,8 +41,17 @@ public:
return crc;
}
bool isReceivingPacket() override {
#ifdef WITH_RX_POWERSAVING
// In the sleep phase (BUSY high) an SPI probe of the IRQ flags would wake the
// chip and break the cycle -- and there is nothing to receive. Outside RXPS
// this stays a real channel check: Dispatcher::checkSend() relies on it.
if (_rx_ps_armed && ((CustomSX1262 *)_radio)->isChipBusy()) return false;
#endif
return ((CustomSX1262 *)_radio)->isReceiving();
}
#ifdef WITH_RX_POWERSAVING
bool isChipBusy() override { return ((CustomSX1262 *)_radio)->isChipBusy(); }
#endif
#if defined(LORA_POLL_IRQ) || defined(PIN_DIAG)
// CUSTOM (TeTeHacko): SX126x native status bits. TIMEOUT is in the mask because
// an RX window that expires has to end the wait too -- with the DIO1 line dead
@@ -42,8 +63,10 @@ public:
float getCurrentRSSI() override {
return ((CustomSX1262 *)_radio)->getRSSI(false);
}
#ifndef WITH_RX_POWERSAVING // with it, the base class answers from the values cached at RX
float getLastRSSI() const override { return ((CustomSX1262 *)_radio)->getRSSI(); }
float getLastSNR() const override { return ((CustomSX1262 *)_radio)->getSNR(); }
#endif
float packetScore(float snr, int packet_len) override {
int sf = ((CustomSX1262 *)_radio)->spreadingFactor;
@@ -51,11 +74,17 @@ public:
}
uint8_t getSpreadingFactor() const override { return ((CustomSX1262 *)_radio)->spreadingFactor; }
virtual void powerOff() override {
#ifdef WITH_RX_POWERSAVING
if (_rx_ps_armed) stopReceiveDutyCycle();
#endif
((CustomSX1262 *)_radio)->sleep(false);
}
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
#ifdef WITH_RX_POWERSAVING
prepareForRadioConfig();
#endif
return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
bool getRxBoostedGainMode() const override {
@@ -64,6 +93,26 @@ public:
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); }
#ifdef WITH_RX_POWERSAVING
protected:
int16_t armDutyCycle(RadioLibIrqFlags_t irq_flags, RadioLibIrqFlags_t irq_mask,
uint32_t* eff_rx_us, uint32_t* eff_sleep_us) override {
// RadioLib programs exactly what is asked (it subtracts the wake-up
// transition from the sleep internally).
*eff_rx_us = _rx_ps_rx_us;
*eff_sleep_us = _rx_ps_sleep_us;
return ((CustomSX1262 *)_radio)->startReceiveDutyCycle(_rx_ps_rx_us, _rx_ps_sleep_us, irq_flags, irq_mask);
}
int16_t stopDutyCycleHardware() override {
int16_t standby_err = _radio->standby();
int16_t rtc_err = ((CustomSX1262 *)_radio)->stopRTC();
return standby_err != RADIOLIB_ERR_NONE ? standby_err : rtc_err;
}
// continuous RX keeps the preamble-detect IRQ, like CustomSX1262::startReceive()
int16_t startContinuousReceive() override { return ((CustomSX1262 *)_radio)->startReceive(); }
public:
#endif
#ifdef RADIO_DIAG
protected:
// CUSTOM (TeTeHacko): `radiostat`, chip side. mode: 2 STBY_RC, 3 STBY_XOSC,
+251
View File
@@ -0,0 +1,251 @@
// CUSTOM (TeTeHacko): from EasySkyMesh PowerSaving v18 (IoTThinks/MeshCore,
// MIT, https://github.com/IoTThinks/MeshCore/tree/PowerSaving-v18) -- RXPS, the
// SX126x/LR11x0 RX duty cycle. Compiled only with -D WITH_RX_POWERSAVING.
#ifdef WITH_RX_POWERSAVING
#include "RXPowerSaving.h"
#include <math.h>
static uint32_t ceilRxPowerSavingValue(float value) {
uint32_t rounded = (uint32_t)value;
return value > (float)rounded ? rounded + 1 : rounded;
}
// Both radios program their duty cycle in 15.625 us ticks and truncate 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.
static uint32_t rxPowerSavingTickToUs(uint64_t tick) {
if (tick == 0) tick = 1;
return (uint32_t)((tick * 125 + 7) / 8); // ceil(tick * 15.625)
}
static 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.
static uint32_t snapRxPowerSavingUpToTick(uint32_t us) {
return rxPowerSavingTickToUs(((uint64_t)us * 8 + 124) / 125); // ceil
}
bool isValidRxPowerSavingPeriod(uint32_t us) {
return us >= RX_POWERSAVING_MIN_PERIOD_US && us <= RX_POWERSAVING_MAX_PERIOD_US;
}
uint8_t rxPowerSavingPreambleForSF(uint8_t sf) {
return sf <= 8 ? 32 : 16;
}
bool isRxPowerSavingNumeric(const char* value) {
if (value == nullptr || *value == 0) return false;
while (*value) {
if (*value < '0' || *value > '9') return false;
value++;
}
return true;
}
float rxPowerSavingCaptureCost(const RxPowerSavingControl* control) {
return control != nullptr ? control->rxPowerSavingCaptureCostSymbols()
: RX_POWERSAVING_CAPTURE_COST_SYMBOLS;
}
uint32_t rxPowerSavingTransition(const RxPowerSavingControl* control) {
return control != nullptr ? control->rxPowerSavingTransitionUs()
: RX_POWERSAVING_TRANSITION_US;
}
// 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-10 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};
static 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;
}
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, uint32_t transition_us) {
if (rx_us == nullptr || sleep_us == nullptr || level < 1 ||
level > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL || sf < 5 || sf > 12 ||
!isfinite(bw) || bw <= 0.0f || !isfinite(capture_cost_symbols) ||
capture_cost_symbols <= 0 || capture_cost_symbols >= preamble || transition_us >= RX_POWERSAVING_MAX_PERIOD_US || (preamble != 16 && preamble != 32)) {
return false;
}
const bool unguarded = isRxPowerSavingUnguardedLevel(level);
const float symbol_us = (1000.0f * (float)(1UL << sf)) / bw;
if (!isfinite(symbol_us) || symbol_us * 64.0f > (float)(UINT32_MAX / 8)) return false;
// 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 ((float)min_sleep_us > sleep_edge_symbols * symbol_us) {
// Even zero margin would not fit above the floor: no level of this
// profile can duty cycle at this SF/BW. Say so instead of returning
// something that will silently fall back.
return false;
}
// The floor eats into the margin. Levels below it collapse onto one point;
// the reply still reports the periods, so the loss of margin is visible.
*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 true;
}
void ensureRxPowerSavingDefaults(uint32_t* rx_us, uint32_t* sleep_us) {
if (!isValidRxPowerSavingPeriod(*rx_us)) *rx_us = RX_POWERSAVING_DEFAULT_RX_US;
if (!isValidRxPowerSavingPeriod(*sleep_us)) *sleep_us = RX_POWERSAVING_DEFAULT_SLEEP_US;
}
bool recalcRxPowerSavingFromLevel(uint8_t level, uint8_t sf, float bw, uint8_t preamble,
uint32_t* rx_us, uint32_t* sleep_us,
float capture_cost_symbols, uint32_t transition_us) {
if (level < 1 || level > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL) return false;
if (preamble == 0) preamble = rxPowerSavingPreambleForSF(sf);
uint32_t calculated_rx_us = 0;
uint32_t calculated_sleep_us = 0;
if (!calcRxPowerSavingLevel(level, sf, bw, preamble, &calculated_rx_us, &calculated_sleep_us,
capture_cost_symbols, transition_us) ||
!isValidRxPowerSavingPeriod(calculated_rx_us) ||
!isValidRxPowerSavingPeriod(calculated_sleep_us)) {
return false;
}
*rx_us = calculated_rx_us;
*sleep_us = calculated_sleep_us;
return true;
}
bool normalizeRxPowerSavingConfig(RxPowerSavingConfig* config, uint8_t sf, float bw,
float capture_cost_symbols, uint32_t transition_us) {
if (config == nullptr || sf < 5 || sf > 12 || !isfinite(bw) || bw <= 0) return false;
RxPowerSavingConfig proposed = *config;
proposed.enabled = proposed.enabled ? 1 : 0;
if (proposed.level > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL) {
proposed.level = RX_POWERSAVING_BALANCED_LEVEL;
}
if (proposed.preamble != 0 && proposed.preamble != 16 && proposed.preamble != 32) {
proposed.preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
}
if (proposed.level == 0) {
if (!isValidRxPowerSavingPeriod(proposed.rx_us) ||
!isValidRxPowerSavingPeriod(proposed.sleep_us)) return false;
} else if (!recalcRxPowerSavingFromLevel(proposed.level, sf, bw, proposed.preamble,
&proposed.rx_us, &proposed.sleep_us,
capture_cost_symbols, transition_us)) {
return false;
}
*config = proposed;
return true;
}
bool applyRxPowerSavingConfig(RxPowerSavingConfig* config, uint8_t sf, float bw,
RxPowerSavingControl* control) {
if (config == nullptr) return false;
const bool valid = !config->enabled || normalizeRxPowerSavingConfig(
config, sf, bw, rxPowerSavingCaptureCost(control), rxPowerSavingTransition(control));
if (control == nullptr) return !config->enabled;
const bool accepted = control->setRxPowerSaving(
config->enabled && valid, config->rx_us, config->sleep_us);
control->setRxPowerSavingConfigError(!valid);
return valid && accepted;
}
#endif // WITH_RX_POWERSAVING
+278
View File
@@ -0,0 +1,278 @@
// CUSTOM (TeTeHacko): from EasySkyMesh PowerSaving v18 (IoTThinks/MeshCore,
// MIT, https://github.com/IoTThinks/MeshCore/tree/PowerSaving-v18) -- RXPS, the
// SX126x/LR11x0 RX duty cycle. Compiled only with -D WITH_RX_POWERSAVING.
#pragma once
#include <stdint.h>
static constexpr uint32_t RX_POWERSAVING_DEFAULT_RX_US = 65625UL;
static constexpr uint32_t RX_POWERSAVING_DEFAULT_SLEEP_US = 60000UL;
static constexpr uint32_t RX_POWERSAVING_MIN_PERIOD_US = 1000UL;
static constexpr uint32_t RX_POWERSAVING_MAX_PERIOD_US = 30000000UL;
// The level scale is a catch dial, in symbols of the sender's preamble.
//
// 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 where reception is guaranteed anyway.
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. Overdrive is lossless and 4-12
// percentage points cheaper in duty cycle; `riskyWorkingMax` is the measured
// working edge and drops ~2% of packets by design.
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;
static constexpr uint8_t RX_POWERSAVING_CONSERVATIVE_LEVEL = 3; // catches 13 (P16) / 16 (P32)
static constexpr uint8_t RX_POWERSAVING_BALANCED_LEVEL = 6; // catches 10 (P16) / 10 (P32)
static constexpr uint8_t 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:
// a wrapper overrides rxPowerSavingCaptureCostSymbols() and every variant using
// that radio picks it up. LR1110 needs about one symbol more - on the bench it
// 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, so a board that knows its real TCXO delay overrides
// one method and both the sleep floor and the timer guard follow.
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;
// Both radio families program their duty cycle in these units, and truncate 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 assumes the 5000 us TCXO delay RadioLib installs; a wrapper that
// can read its radio overrides this with the board's real value.
static constexpr uint32_t RX_POWERSAVING_MIN_SLEEP_US =
RX_POWERSAVING_TRANSITION_US + RX_POWERSAVING_MIN_SLEEP_MARGIN_US;
class RxPowerSavingArmRetryState {
uint8_t _consecutive_failures = 0;
public:
bool canAttempt() const {
return _consecutive_failures < RX_POWERSAVING_MAX_CONSEC_ARM_FAILURES;
}
void recordSuccess() { _consecutive_failures = 0; }
void recordFailure() {
if (_consecutive_failures < RX_POWERSAVING_MAX_CONSEC_ARM_FAILURES) {
_consecutive_failures++;
}
}
void reset() { _consecutive_failures = 0; }
uint8_t consecutiveFailures() const { return _consecutive_failures; }
};
struct RxPowerSavingConfig {
uint8_t enabled = 0;
uint32_t rx_us = RX_POWERSAVING_DEFAULT_RX_US;
uint32_t sleep_us = RX_POWERSAVING_DEFAULT_SLEEP_US;
uint8_t level = RX_POWERSAVING_BALANCED_LEVEL;
uint8_t preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
};
struct RxPowerSavingStatus {
bool supported = false;
bool armed = false;
int16_t last_error = 0;
uint32_t arm_failures = 0;
// Periods the radio actually runs with. A driver may clamp the requested
// values to satisfy a hardware constraint, so these can differ from the
// configured rx_us/sleep_us. Zero means "nothing armed yet".
uint32_t effective_rx_us = 0;
uint32_t effective_sleep_us = 0;
};
class RxPowerSavingControl {
public:
virtual ~RxPowerSavingControl() = default;
virtual bool setRxPowerSaving(bool enabled, uint32_t rx_us, uint32_t sleep_us) {
(void)rx_us;
(void)sleep_us;
return !enabled;
}
virtual RxPowerSavingStatus getRxPowerSavingStatus() const { return {}; }
virtual void setRxPowerSavingConfigError(bool invalid) { (void)invalid; }
virtual bool isRxPowerSavingCalibrationActive() const { return false; }
// Symbols of the sender's preamble consumed before a packet can be latched.
// Overridden per radio family; see RX_POWERSAVING_CAPTURE_COST_SYMBOLS.
virtual float rxPowerSavingCaptureCostSymbols() const {
return RX_POWERSAVING_CAPTURE_COST_SYMBOLS;
}
// Sleep -> RX transition of this radio, in microseconds. The sleep floor and
// the SetRxDutyCycle timer guard are both derived from it, so a wrapper that
// can read its own tcxoDelay only needs to override this one method.
virtual uint32_t rxPowerSavingTransitionUs() const {
return RX_POWERSAVING_TRANSITION_US;
}
};
// Margin this level asks for, in symbols. Only meaningful on the guarded scale.
// Symbols of the sender's preamble this level undertakes to catch. The two
// profiles have separate ladders, so the profile has to be passed in; anything
// other than 16 or 32 is treated as the 16-symbol profile, matching the
// validation in calcRxPowerSavingLevel().
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;
}
bool isValidRxPowerSavingPeriod(uint32_t us);
uint8_t rxPowerSavingPreambleForSF(uint8_t sf);
bool isRxPowerSavingNumeric(const char* value);
// capture_cost_symbols defaults to the SX126x figure so callers without a radio
// handy still compile; anything holding a RxPowerSavingControl should pass
// rxPowerSavingCaptureCost(control) instead.
float rxPowerSavingCaptureCost(const RxPowerSavingControl* control);
uint32_t rxPowerSavingTransition(const RxPowerSavingControl* control);
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 = RX_POWERSAVING_CAPTURE_COST_SYMBOLS,
uint32_t transition_us = RX_POWERSAVING_TRANSITION_US);
void ensureRxPowerSavingDefaults(uint32_t* rx_us, uint32_t* sleep_us);
bool recalcRxPowerSavingFromLevel(uint8_t level, uint8_t sf, float bw, uint8_t preamble,
uint32_t* rx_us, uint32_t* sleep_us,
float capture_cost_symbols = RX_POWERSAVING_CAPTURE_COST_SYMBOLS,
uint32_t transition_us = RX_POWERSAVING_TRANSITION_US);
bool normalizeRxPowerSavingConfig(RxPowerSavingConfig* config, uint8_t sf, float bw,
float capture_cost_symbols = RX_POWERSAVING_CAPTURE_COST_SYMBOLS,
uint32_t transition_us = RX_POWERSAVING_TRANSITION_US);
// The requested configuration survives a timing failure; only the radio falls back.
bool applyRxPowerSavingConfig(RxPowerSavingConfig* config, uint8_t sf, float bw,
RxPowerSavingControl* control);
static constexpr int16_t RX_POWERSAVING_ERR_TIMING = -10001;
+274
View File
@@ -0,0 +1,274 @@
// CUSTOM (TeTeHacko): from EasySkyMesh PowerSaving v18 (IoTThinks/MeshCore,
// MIT, https://github.com/IoTThinks/MeshCore/tree/PowerSaving-v18) -- RXPS, the
// SX126x/LR11x0 RX duty cycle. Compiled only with -D WITH_RX_POWERSAVING.
#ifdef WITH_RX_POWERSAVING
#include "RXPowerSavingCLI.h"
#include <Utils.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
// Suffix printed after the level so an unguarded profile is never mistaken for
// an ordinary one, in both the `set` echo and the `get` report.
static const char* rxPowerSavingLevelTag(uint8_t level) {
if (isRxPowerSavingRiskyWorkingMaxLevel(level)) return "(riskyWorkingMax)";
if (isRxPowerSavingOverdriveLevel(level)) return "(overdrive)";
return "";
}
static bool parseRxPowerSavingUint32(const char* value, uint32_t* parsed) {
if (parsed == nullptr || !isRxPowerSavingNumeric(value)) return false;
uint32_t result = 0;
while (*value) {
uint32_t digit = (uint32_t)(*value++ - '0');
if (result > (UINT32_MAX - digit) / 10U) return false;
result = result * 10U + digit;
}
*parsed = result;
return true;
}
bool RXPowerSavingCLI::set(const char* value, uint8_t sf, float bw,
RxPowerSavingConfig* config, RxPowerSavingControl* control,
char* reply, size_t reply_size) {
if (value == nullptr || config == nullptr || reply == nullptr || reply_size == 0) return false;
RxPowerSavingConfig proposed = *config;
uint8_t level = 0;
uint8_t preamble = rxPowerSavingPreambleForSF(sf);
bool level_requested = false;
bool preamble_overridden = false;
ensureRxPowerSavingDefaults(&proposed.rx_us, &proposed.sleep_us);
if (strcmp(value, "off") == 0) {
proposed.enabled = 0;
} else if (strcmp(value, "on") == 0 || strcmp(value, "conservative") == 0) {
proposed.enabled = 1;
level = RX_POWERSAVING_CONSERVATIVE_LEVEL;
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
level_requested = true;
preamble_overridden = true;
} else if (strcmp(value, "max") == 0) {
// Top of the guarded scale. Like every named preset it assumes the worst
// case a mixed network can present - a sender using a 16-symbol preamble -
// so at SF<=8 it is markedly less economical than `level 10`, which follows
// the SF and picks the 32-symbol profile. `max preamble 32` gets that back.
proposed.enabled = 1;
level = RX_POWERSAVING_MAX_LEVEL;
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
level_requested = true;
preamble_overridden = true;
} else if (strcmp(value, "overdrive") == 0) {
// One step past the guarded scale: measured lossless, outside the
// datasheet's timer condition. Same worst-case preamble as the presets above.
proposed.enabled = 1;
level = RX_POWERSAVING_OVERDRIVE_LEVEL;
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
level_requested = true;
preamble_overridden = true;
} else if (strcmp(value, "riskyWorkingMax") == 0) {
// This one is not lossless, so the risk is explicit in its name. Same
// worst-case preamble as the presets above.
proposed.enabled = 1;
level = RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL;
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
level_requested = true;
preamble_overridden = true;
} else if (strcmp(value, "balanced") == 0) {
proposed.enabled = 1;
level = RX_POWERSAVING_BALANCED_LEVEL;
preamble = RX_POWERSAVING_PROFILE_PREAMBLE;
level_requested = true;
preamble_overridden = true;
} else {
char input[128];
if (strlen(value) >= sizeof(input)) {
snprintf(reply, reply_size,
"ERROR: use off|on|conservative|balanced|max|overdrive|riskyWorkingMax|level <1-10>|<rx_us> <sleep_us>");
return false;
}
strcpy(input, value);
const char* parts[4];
int count = mesh::Utils::parseTextParts(input, parts, 4, ' ');
uint32_t first = 0;
uint32_t second = 0;
if (count == 1 && parseRxPowerSavingUint32(parts[0], &first)) {
if (first < 1 || first > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL) {
snprintf(reply, reply_size, "ERROR: level range is 1-%u (or max|overdrive|riskyWorkingMax); preamble is 16 or 32",
RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL);
return false;
}
level = (uint8_t)first;
level_requested = true;
proposed.enabled = 1;
} else if (count >= 2 && strcmp(parts[1], "preamble") == 0 &&
(strcmp(parts[0], "max") == 0 || strcmp(parts[0], "overdrive") == 0 ||
strcmp(parts[0], "riskyWorkingMax") == 0)) {
if (count != 3 || !parseRxPowerSavingUint32(parts[2], &first) ||
(first != 16 && first != 32)) {
snprintf(reply, reply_size, "ERROR: use %s preamble <16|32>", parts[0]);
return false;
}
level = strcmp(parts[0], "overdrive") == 0 ? RX_POWERSAVING_OVERDRIVE_LEVEL
: strcmp(parts[0], "max") == 0 ? RX_POWERSAVING_MAX_LEVEL
: RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL;
preamble = (uint8_t)first;
level_requested = true;
preamble_overridden = true;
proposed.enabled = 1;
} else if (count == 2 && strcmp(parts[0], "level") == 0 &&
parseRxPowerSavingUint32(parts[1], &first)) {
if (first < 1 || first > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL) {
snprintf(reply, reply_size, "ERROR: level range is 1-%u (or max|overdrive|riskyWorkingMax); preamble is 16 or 32",
RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL);
return false;
}
level = (uint8_t)first;
level_requested = true;
proposed.enabled = 1;
} else if (count == 4 && strcmp(parts[0], "level") == 0 &&
parseRxPowerSavingUint32(parts[1], &first) &&
strcmp(parts[2], "preamble") == 0 &&
parseRxPowerSavingUint32(parts[3], &second)) {
if (first < 1 || first > RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL ||
(second != 16 && second != 32)) {
snprintf(reply, reply_size, "ERROR: level range is 1-%u (or max|overdrive|riskyWorkingMax); preamble is 16 or 32",
RX_POWERSAVING_RISKY_WORKING_MAX_LEVEL);
return false;
}
level = (uint8_t)first;
preamble = (uint8_t)second;
level_requested = true;
preamble_overridden = true;
proposed.enabled = 1;
} else if (count == 2 && parseRxPowerSavingUint32(parts[0], &first) &&
parseRxPowerSavingUint32(parts[1], &second)) {
proposed.rx_us = first;
proposed.sleep_us = second;
proposed.enabled = 1;
} else {
snprintf(reply, reply_size,
"ERROR: use off|on|conservative|balanced|max|overdrive|riskyWorkingMax|level <1-10>|<rx_us> <sleep_us>");
return false;
}
}
if (proposed.enabled && (sf < 5 || sf > 12 || !isfinite(bw) || bw <= 0)) {
if (control) {
control->setRxPowerSaving(false, proposed.rx_us, proposed.sleep_us);
control->setRxPowerSavingConfigError(true);
}
snprintf(reply, reply_size, "ERROR: invalid SF/BW for RXPS");
return false;
}
if (level_requested &&
!recalcRxPowerSavingFromLevel(level, sf, bw, preamble,
&proposed.rx_us, &proposed.sleep_us,
rxPowerSavingCaptureCost(control),
rxPowerSavingTransition(control))) {
// Level and preamble were validated above, so the only way to get here is
// that no sleep exists which both arms the hardware and still lets a
// preamble of this length be caught - i.e. the symbol is too short for RXPS
// at this SF/BW. Saying "level range is 1-10" would send the user hunting
// for the wrong thing.
if (control) {
control->setRxPowerSaving(false, proposed.rx_us, proposed.sleep_us);
control->setRxPowerSavingConfigError(true);
}
snprintf(reply, reply_size, "ERROR: RXPS does not fit this SF/BW with preamble %lu",
(unsigned long)preamble);
return false;
}
if (!isValidRxPowerSavingPeriod(proposed.rx_us) ||
!isValidRxPowerSavingPeriod(proposed.sleep_us)) {
snprintf(reply, reply_size, "ERROR: range is %lu-%lu us",
(unsigned long)RX_POWERSAVING_MIN_PERIOD_US,
(unsigned long)RX_POWERSAVING_MAX_PERIOD_US);
return false;
}
bool applied = control != nullptr
? control->setRxPowerSaving(proposed.enabled != 0, proposed.rx_us, proposed.sleep_us)
: proposed.enabled == 0;
if (!applied) {
snprintf(reply, reply_size, "ERROR: RX powersaving unsupported");
return false;
}
if (control) control->setRxPowerSavingConfigError(false);
if (level_requested) {
proposed.level = level;
proposed.preamble = preamble_overridden ? preamble : 0;
} else if (strcmp(value, "off") != 0) {
proposed.level = 0;
proposed.preamble = 0;
}
*config = proposed;
snprintf(reply, reply_size, "OK - %s,level=%lu%s,preamble=%lu,rx=%lu,sleep=%lu",
config->enabled ? "on" : "off", (unsigned long)config->level,
rxPowerSavingLevelTag(config->level),
(unsigned long)config->preamble, (unsigned long)config->rx_us,
(unsigned long)config->sleep_us);
return true;
}
void RXPowerSavingCLI::get(const RxPowerSavingConfig* config,
const RxPowerSavingControl* control,
uint8_t sf, float bw, char* reply, size_t reply_size) {
if (config == nullptr || reply == nullptr || reply_size == 0) return;
RxPowerSavingStatus status = control != nullptr
? control->getRxPowerSavingStatus()
: RxPowerSavingStatus{};
// Preamble symbols the node actually catches. Not simply the number the level
// asked for: the sleep floor can shorten the sleep further, and at SF6 with
// the 16-symbol profile that collapses the first few levels onto the same
// point. Reporting the requested value there would be a lie.
char margin[24];
margin[0] = 0;
if (status.last_error == 0 && isValidRxPowerSavingPeriod(config->sleep_us) &&
config->level >= 1 && config->level <= RX_POWERSAVING_GUARDED_LEVELS &&
sf >= 5 && sf <= 12 && isfinite(bw) && bw > 0.0f) {
const uint8_t preamble = config->preamble ? config->preamble : rxPowerSavingPreambleForSF(sf);
const float symbol_us = (1000.0f * (float)(1UL << sf)) / bw;
const float effective = (float)preamble - (float)config->sleep_us / symbol_us;
// No %f on this platform's printf, and rounding the whole and fractional
// parts separately overflows: 4.999 came out as "4.10".
const float scaled = effective * 10.0f + (effective < 0.0f ? -0.5f : 0.5f);
if (isfinite(scaled) && scaled > (float)INT_MIN && scaled < (float)INT_MAX) {
const int tenths = (int)scaled;
snprintf(margin, sizeof(margin), ",catch=%d.%d", tenths / 10,
tenths < 0 ? -(tenths % 10) : tenths % 10);
}
}
// Overdrive has to be visible here, otherwise it reads as an ordinary level
// and nobody remembers it runs outside the datasheet rule.
int len = snprintf(reply, reply_size,
"> desired=%s,effective=%s,supported=%s,err=%d,fail=%lu,level=%lu%s%s,preamble=%lu,rx=%lu,sleep=%lu",
config->enabled ? "on" : "off", status.armed ? "armed" : "continuous",
status.supported ? "yes" : "no", (int)status.last_error,
(unsigned long)status.arm_failures, (unsigned long)config->level,
rxPowerSavingLevelTag(config->level), margin,
(unsigned long)config->preamble, (unsigned long)config->rx_us,
(unsigned long)config->sleep_us);
// Only report the periods the hardware really runs with when a driver had to
// clamp them - printing them always would not fit the 160 byte reply buffer.
if (len > 0 && (size_t)len < reply_size && status.armed &&
(status.effective_rx_us != config->rx_us ||
status.effective_sleep_us != config->sleep_us)) {
snprintf(reply + len, reply_size - (size_t)len, ",erx=%lu,eslp=%lu",
(unsigned long)status.effective_rx_us,
(unsigned long)status.effective_sleep_us);
}
}
#endif // WITH_RX_POWERSAVING
+18
View File
@@ -0,0 +1,18 @@
// CUSTOM (TeTeHacko): from EasySkyMesh PowerSaving v18 (IoTThinks/MeshCore,
// MIT, https://github.com/IoTThinks/MeshCore/tree/PowerSaving-v18) -- RXPS, the
// SX126x/LR11x0 RX duty cycle. Compiled only with -D WITH_RX_POWERSAVING.
#pragma once
#include <stddef.h>
#include "RXPowerSaving.h"
class RXPowerSavingCLI {
public:
static bool set(const char* value, uint8_t sf, float bw, RxPowerSavingConfig* config,
RxPowerSavingControl* control, char* reply, size_t reply_size);
// sf/bw are needed to turn the stored periods back into symbols, which is
// what the level scale is expressed in.
static void get(const RxPowerSavingConfig* config, const RxPowerSavingControl* control,
uint8_t sf, float bw, char* reply, size_t reply_size);
};
+249
View File
@@ -11,6 +11,12 @@
#define NUM_NOISE_FLOOR_SAMPLES 64
#define SAMPLING_THRESHOLD 14
#ifdef WITH_RX_POWERSAVING
#define NF_CALIB_INTERVAL_MS 60000UL // continuous-RX window for the noise floor, this often
#define NF_CALIB_TIMEOUT_MS 5000UL // ... and at most this long
#define NF_CALIB_SETTLE_MS 20UL // RSSI settles after leaving the duty cycle
#endif
static volatile uint8_t state = STATE_IDLE;
#ifdef RADIO_DIAG
static volatile uint32_t diag_isr_count = 0; // DIO1 edges that reached the MCU
@@ -56,6 +62,9 @@ uint32_t RadioLibWrapper::getRngSeed() {
}
void RadioLibWrapper::setTxPower(int8_t dbm) {
#ifdef WITH_RX_POWERSAVING
prepareForRadioConfig(); // PA config is a standby-only command
#endif
#if defined(USE_LR2021)
// Upstream 114093ee: on LR2021, setOutputPower() writes the PA config and
// TxParams, which are standby-only commands, and recvRaw() keeps state ==
@@ -73,6 +82,9 @@ void RadioLibWrapper::setTxPower(int8_t dbm) {
}
void RadioLibWrapper::idle() {
#ifdef WITH_RX_POWERSAVING
if (_rx_ps_armed) stopReceiveDutyCycle();
#endif
_radio->standby();
state = STATE_IDLE; // need another startReceive()
}
@@ -99,6 +111,13 @@ void RadioLibWrapper::resetAGC() {
// make sure we're not mid-receive of packet!
if ((state & STATE_INT_READY) != 0 || isReceivingPacket()) return;
#ifdef WITH_RX_POWERSAVING
if (_rx_ps_armed) stopReceiveDutyCycle();
// Duty cycling never samples RSSI outside a calibration window, so the
// reconvergence below has to have one: schedule it now. (Upstream RXPS
// recalibrates synchronously here -- up to ~0.3 s blocking the main loop.)
_nf_last_calib = 0;
#endif
doResetAGC();
state = STATE_IDLE; // trigger a startReceive()
@@ -143,6 +162,25 @@ void RadioLibWrapper::loop() {
pollIrq();
#endif
#ifdef WITH_RX_POWERSAVING
if (_rx_ps_restart_pending && (state & ~STATE_INT_READY) != STATE_TX_WAIT &&
!isPacketPendingOrReceiving()) {
_rx_ps_restart_pending = false;
requestRestartRecv();
}
noiseFloorCalibCheck();
if (state == STATE_RX && _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES) {
// no RSSI while duty cycling (the chip sleeps between windows), nor in the
// settle time right after a calibration window opened
if (!_rx_ps_armed && !(_nf_calib_active && (long)(millis() - _nf_sample_from) < 0) &&
!isReceivingPacket()) {
sampleNoiseFloorOnce();
}
} else if (publishNoiseFloor()) {
if (_nf_calib_active) endNoiseFloorCalib(millis());
}
#else
if (state == STATE_RX && _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES) {
if (!isReceivingPacket()) {
int rssi = getCurrentRSSI();
@@ -162,13 +200,18 @@ void RadioLibWrapper::loop() {
MESH_DEBUG_PRINTLN("RadioLibWrapper: noise_floor = %d", (int)_noise_floor);
#endif
}
#endif
}
void RadioLibWrapper::startRecv() {
#if defined(USE_LR2021)
_radio->standby(); // without this LR2021 can throw -706 when calling startReceive after hardware CAD when side detectors are enabled
#endif
#ifdef WITH_RX_POWERSAVING
int err = startReceiveMode();
#else
int err = _radio->startReceive();
#endif
if (err == RADIOLIB_ERR_NONE) {
state = STATE_RX;
} else {
@@ -176,6 +219,175 @@ void RadioLibWrapper::startRecv() {
}
}
#ifdef WITH_RX_POWERSAVING
// Clear the RX/idle state so the next loop calls startRecv() again, without
// dropping a STATE_INT_READY the ISR may raise meanwhile: a plain
// `state = STATE_IDLE` loses that flag -- and a received packet -- when setFlag()
// fires between the test and the store.
void RadioLibWrapper::requestRestartRecv() {
noInterrupts();
if ((state & ~STATE_INT_READY) != STATE_TX_WAIT) {
state &= STATE_INT_READY;
}
interrupts();
}
bool RadioLibWrapper::isPacketPendingOrReceiving() {
return (state & STATE_INT_READY) != 0 || isReceivingPacket();
}
void RadioLibWrapper::sampleNoiseFloorOnce() {
int rssi = getCurrentRSSI();
if (rssi < _noise_floor + SAMPLING_THRESHOLD) {
_num_floor_samples++;
_floor_sample_sum += rssi;
}
}
bool RadioLibWrapper::publishNoiseFloor() {
if (_num_floor_samples < NUM_NOISE_FLOOR_SAMPLES || _floor_sample_sum == 0) return false;
_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;
#ifdef MESH_DEBUG_NOISE_FLOOR
MESH_DEBUG_PRINTLN("RadioLibWrapper: noise_floor = %d", (int)_noise_floor);
#endif
return true;
}
void RadioLibWrapper::noiseFloorCalibCheck() {
unsigned long now = millis();
if (_nf_calib_active) {
if (!_rx_ps_enabled || (long)(now - _nf_calib_deadline) >= 0) {
endNoiseFloorCalib(now);
} else if (_rx_ps_armed && !isPacketPendingOrReceiving()) {
requestRestartRecv(); // a packet delayed the switch to continuous RX
}
} else if (_rx_ps_enabled && _rx_ps_armed && state == STATE_RX &&
(_nf_last_calib == 0 || now - _nf_last_calib >= NF_CALIB_INTERVAL_MS) &&
!isPacketPendingOrReceiving()) {
_nf_calib_active = true;
_nf_calib_deadline = now + NF_CALIB_TIMEOUT_MS;
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
_num_floor_samples = 0;
_floor_sample_sum = 0;
requestRestartRecv(); // startReceiveMode() goes continuous while calibrating
}
}
void RadioLibWrapper::endNoiseFloorCalib(unsigned long now) {
_nf_calib_active = false;
_nf_last_calib = now;
if (!isPacketPendingOrReceiving()) requestRestartRecv();
}
int16_t RadioLibWrapper::startReceiveMode() {
// A preamble that arrived after the scheduler's idle check must not be
// aborted by stopping the duty cycle for a calibration window.
if (_nf_calib_active && _rx_ps_armed && isPacketPendingOrReceiving()) {
return RADIOLIB_ERR_NONE;
}
if (_rx_ps_armed) stopReceiveDutyCycle();
if (!_rx_ps_enabled || _nf_calib_active) {
_rx_ps_armed = false;
const int16_t err = startContinuousReceive();
_rx_ps_last_error = err;
return err;
}
if (!_rx_ps_arm_retry.canAttempt()) {
// arming failed repeatedly: continuous RX until the config changes
_rx_ps_armed = false;
const int16_t err = startContinuousReceive();
if (err != RADIOLIB_ERR_NONE) _rx_ps_last_error = err;
return err;
}
const RadioLibIrqFlags_t irq_flags =
RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED);
const RadioLibIrqFlags_t irq_mask =
(1UL << RADIOLIB_IRQ_RX_DONE) | (1UL << RADIOLIB_IRQ_TIMEOUT) |
(1UL << RADIOLIB_IRQ_CRC_ERR) | (1UL << RADIOLIB_IRQ_HEADER_ERR);
uint32_t eff_rx_us = _rx_ps_rx_us;
uint32_t eff_sleep_us = _rx_ps_sleep_us;
int16_t err = armDutyCycle(irq_flags, irq_mask, &eff_rx_us, &eff_sleep_us);
if (err == RADIOLIB_ERR_NONE) {
_rx_ps_armed = true;
_rx_ps_last_error = RADIOLIB_ERR_NONE;
_rx_ps_arm_retry.recordSuccess();
_rx_ps_eff_rx_us = eff_rx_us;
_rx_ps_eff_sleep_us = eff_sleep_us;
return err;
}
_rx_ps_armed = false;
_rx_ps_last_error = err;
_rx_ps_eff_rx_us = 0;
_rx_ps_eff_sleep_us = 0;
n_rx_ps_arm_failures++;
_rx_ps_arm_retry.recordFailure();
MESH_DEBUG_PRINTLN("RadioLibWrapper: startReceiveDutyCycle(%d), continuous RX fallback", err);
stopDutyCycleHardware();
int16_t fallback_err = startContinuousReceive();
if (fallback_err != RADIOLIB_ERR_NONE) _rx_ps_last_error = fallback_err;
return fallback_err;
}
void RadioLibWrapper::stopReceiveDutyCycle() {
int16_t err = stopDutyCycleHardware();
_rx_ps_armed = false;
_rx_ps_eff_rx_us = 0;
_rx_ps_eff_sleep_us = 0;
if (err != RADIOLIB_ERR_NONE) _rx_ps_last_error = err;
}
bool RadioLibWrapper::isPacketReady() {
if (!_rx_ps_armed) return true;
return _radio->checkIrq(RADIOLIB_IRQ_RX_DONE) != 0;
}
void RadioLibWrapper::prepareForRadioConfig() {
if (!_rx_ps_armed) return;
stopReceiveDutyCycle();
requestRestartRecv();
}
bool RadioLibWrapper::setRxPowerSaving(bool enabled, uint32_t rx_us, uint32_t sleep_us) {
if (enabled && (!isValidRxPowerSavingPeriod(rx_us) || !isValidRxPowerSavingPeriod(sleep_us))) {
_rx_ps_enabled = false;
_rx_ps_last_error = RX_POWERSAVING_ERR_TIMING;
requestRestartRecv();
return false;
}
if (enabled && !supportsRxPowerSaving()) return false;
_rx_ps_enabled = enabled;
_rx_ps_rx_us = rx_us;
_rx_ps_sleep_us = sleep_us;
_rx_ps_last_error = RADIOLIB_ERR_NONE;
_rx_ps_arm_retry.reset(); // new config, a fresh chance for the hardware
_rx_ps_restart_pending = true;
if ((state & ~STATE_INT_READY) != STATE_TX_WAIT && !isPacketPendingOrReceiving()) {
_rx_ps_restart_pending = false;
requestRestartRecv();
}
return true;
}
RxPowerSavingStatus RadioLibWrapper::getRxPowerSavingStatus() const {
RxPowerSavingStatus status;
status.supported = supportsRxPowerSaving();
status.armed = _rx_ps_armed;
status.last_error = _rx_ps_config_error ? RX_POWERSAVING_ERR_TIMING : _rx_ps_last_error;
status.arm_failures = n_rx_ps_arm_failures;
status.effective_rx_us = _rx_ps_eff_rx_us;
status.effective_sleep_us = _rx_ps_eff_sleep_us;
return status;
}
#endif
bool RadioLibWrapper::isInRecvMode() const {
return (state & ~STATE_INT_READY) == STATE_RX;
}
@@ -183,7 +395,20 @@ bool RadioLibWrapper::isInRecvMode() const {
int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) {
int len = 0;
if (state & STATE_INT_READY) {
#ifdef WITH_RX_POWERSAVING
// While duty cycling DIO1 also carries timeouts; only a real RX_DONE has data.
if (isPacketReady()) {
if (_rx_ps_armed) stopReceiveDutyCycle();
len = _radio->getPacketLength();
if (len > 0) {
_last_snr = _radio->getSNR();
_last_rssi = _radio->getRSSI();
_last_metrics_valid = true;
}
}
#else
len = _radio->getPacketLength();
#endif
if (len > 0) {
if (len > sz) { len = sz; }
int err = _radio->readData(bytes, len);
@@ -210,12 +435,16 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) {
}
if (state != STATE_RX) {
#ifdef WITH_RX_POWERSAVING
startRecv(); // duty cycle or continuous, as configured
#else
int err = _radio->startReceive();
if (err == RADIOLIB_ERR_NONE) {
state = STATE_RX;
} else {
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: startReceive(%d)", err);
}
#endif
}
return len;
}
@@ -225,6 +454,9 @@ uint32_t RadioLibWrapper::getEstAirtimeFor(int len_bytes) {
}
bool RadioLibWrapper::startSendRaw(const uint8_t* bytes, int len) {
#ifdef WITH_RX_POWERSAVING
if (_rx_ps_armed) stopReceiveDutyCycle();
#endif
_board->onBeforeTransmit();
int err = _radio->startTransmit((uint8_t *) bytes, len);
if (err == RADIOLIB_ERR_NONE) {
@@ -320,10 +552,19 @@ int RadioLibWrapper::probeDio1(uint32_t* irq_out, int* dio1_level, int* probe_le
bool RadioLibWrapper::isChannelActive() {
// int.thresh: RSSI-based interference detection (relative to noise floor)
#ifdef WITH_RX_POWERSAVING
// no RSSI read while the duty-cycling chip sleeps (BUSY high)
if (_threshold != 0 && !(_rx_ps_armed && isChipBusy()) &&
getCurrentRSSI() > _noise_floor + _threshold) return true;
#else
if (_threshold != 0 && getCurrentRSSI() > _noise_floor + _threshold) return true;
#endif
// cad: hardware channel activity detection
if (_cad_enabled) {
#ifdef WITH_RX_POWERSAVING
if (_rx_ps_armed) stopReceiveDutyCycle();
#endif
int16_t result = performChannelScan();
// scanChannel() triggers DIO interrupt (CAD done) which sets STATE_INT_READY
// via setFlag() ISR. Clear it before restarting RX so recvRaw() doesn't
@@ -337,9 +578,17 @@ bool RadioLibWrapper::isChannelActive() {
}
float RadioLibWrapper::getLastRSSI() const {
#ifdef WITH_RX_POWERSAVING
if (_last_metrics_valid) return _last_rssi;
if (_rx_ps_armed) return 0;
#endif
return _radio->getRSSI();
}
float RadioLibWrapper::getLastSNR() const {
#ifdef WITH_RX_POWERSAVING
if (_last_metrics_valid) return _last_snr;
if (_rx_ps_armed) return 0;
#endif
return _radio->getSNR();
}
+76 -1
View File
@@ -2,6 +2,15 @@
#include <Mesh.h>
#include <RadioLib.h>
#ifdef WITH_RX_POWERSAVING
// CUSTOM (TeTeHacko): RX duty cycle ("RXPS"), ported from EasySkyMesh PowerSaving
// v18 (IoTThinks/MeshCore, MIT). Build-flag only and off at runtime by default:
// without the flag this class is byte-for-byte what it was. See RXPowerSaving.h.
#include "RXPowerSaving.h"
#if defined(LORA_POLL_IRQ)
#error "WITH_RX_POWERSAVING and LORA_POLL_IRQ do not mix: polling the IRQ register wakes a duty-cycling chip"
#endif
#endif
#ifdef USE_CC310_HW_CRYPTO
#include <Adafruit_nRFCrypto.h>
@@ -11,7 +20,11 @@ struct PacketMillis {
uint32_t payloadMillis; // header-valid -> rx-done deadline
};
class RadioLibWrapper : public mesh::Radio {
class RadioLibWrapper : public mesh::Radio
#ifdef WITH_RX_POWERSAVING
, public RxPowerSavingControl
#endif
{
protected:
PhysicalLayer* _radio;
mesh::MainBoard* _board;
@@ -26,6 +39,51 @@ protected:
void idle();
void startRecv();
#ifdef WITH_RX_POWERSAVING
// RXPS state. _rx_ps_enabled = what the config asks for, _rx_ps_armed = the
// chip is duty cycling right now (cleared by anything that takes it out).
bool _rx_ps_restart_pending = false;
bool _rx_ps_config_error = false;
bool _rx_ps_enabled = false;
bool _rx_ps_armed = false;
uint32_t _rx_ps_rx_us = RX_POWERSAVING_DEFAULT_RX_US;
uint32_t _rx_ps_sleep_us = RX_POWERSAVING_DEFAULT_SLEEP_US;
uint32_t _rx_ps_eff_rx_us = 0; // periods the driver actually armed with
uint32_t _rx_ps_eff_sleep_us = 0;
int16_t _rx_ps_last_error = 0;
uint32_t n_rx_ps_arm_failures = 0;
RxPowerSavingArmRetryState _rx_ps_arm_retry;
// Noise floor while duty cycling: RSSI cannot be sampled in the sleep phase,
// so every NF_CALIB_INTERVAL the receiver goes continuous for a short window.
bool _nf_calib_active = false;
unsigned long _nf_last_calib = 0;
unsigned long _nf_calib_deadline = 0;
unsigned long _nf_sample_from = 0;
// RSSI/SNR of the last packet, read at RX: reading the registers later, with
// the chip asleep between windows, would wake it and return nothing useful.
float _last_rssi = 0, _last_snr = 0;
bool _last_metrics_valid = false;
void requestRestartRecv();
bool isPacketPendingOrReceiving();
void prepareForRadioConfig();
void sampleNoiseFloorOnce();
bool publishNoiseFloor();
void noiseFloorCalibCheck();
void endNoiseFloorCalib(unsigned long now);
int16_t startReceiveMode();
void stopReceiveDutyCycle();
// eff_rx_us/eff_sleep_us report the periods the driver really programmed.
virtual int16_t armDutyCycle(RadioLibIrqFlags_t irq_flags, RadioLibIrqFlags_t irq_mask,
uint32_t* eff_rx_us, uint32_t* eff_sleep_us) {
(void)irq_flags; (void)irq_mask; (void)eff_rx_us; (void)eff_sleep_us;
return RADIOLIB_ERR_UNSUPPORTED;
}
virtual int16_t stopDutyCycleHardware() { return _radio->standby(); }
virtual int16_t startContinuousReceive() { return _radio->startReceive(); }
virtual bool isPacketReady();
virtual bool isChipBusy() { return false; }
#endif
#ifdef LORA_POLL_IRQ
void pollIrq(); // CUSTOM (TeTeHacko): DIO1-less completion detection, see .cpp
#endif
@@ -41,7 +99,17 @@ public:
}
void begin() override;
#ifdef WITH_RX_POWERSAVING
virtual void powerOff() { if (_rx_ps_armed) stopReceiveDutyCycle(); _radio->sleep(); }
virtual bool supportsRxPowerSaving() const { return false; }
void setRxPowerSavingConfigError(bool invalid) override { _rx_ps_config_error = invalid; }
bool setRxPowerSaving(bool enabled, uint32_t rx_us, uint32_t sleep_us) override;
RxPowerSavingStatus getRxPowerSavingStatus() const override;
bool isRxPowerSavingCalibrationActive() const override { return _nf_calib_active; }
#else
virtual void powerOff() { _radio->sleep(); }
#endif
int recvRaw(uint8_t* bytes, int sz) override;
uint32_t getEstAirtimeFor(int len_bytes) override;
bool startSendRaw(const uint8_t* bytes, int len) override;
@@ -89,7 +157,14 @@ public:
void kickRx();
uint32_t getPacketsRecvErrors() const { return n_recv_errors; }
uint32_t getPacketsSent() const { return n_sent; }
#ifdef WITH_RX_POWERSAVING
void resetStats() {
n_recv = n_sent = n_recv_errors = n_rx_ps_arm_failures = 0;
_rx_ps_arm_retry.reset(); // a fresh set of arm attempts, see startReceiveMode()
}
#else
void resetStats() { n_recv = n_sent = n_recv_errors = 0; }
#endif
virtual float getLastRSSI() const override;
virtual float getLastSNR() const override;
@@ -114,6 +114,9 @@ static Adafruit_INA3221 INA3221;
#ifndef TELEM_INA219_ADDRESS
#define TELEM_INA219_ADDRESS 0x40 // INA219 single channel current sensor I2C address
#endif
#ifndef TELEM_INA219_SHUNT_VALUE
#define TELEM_INA219_SHUNT_VALUE 0.100 // CUSTOM (TeTeHacko): what Adafruit's calibration assumes
#endif
#include <Adafruit_INA219.h>
static Adafruit_INA219 INA219(TELEM_INA219_ADDRESS);
#endif
@@ -146,6 +149,18 @@ static class INA226 INA226_ALT(TELEM_INA226_ALT_ADDR(TELEM_INA226_ADDRESS), TELE
static class INA226* active_ina226 = &INA226; // `class`: the object INA226 hides the type
#endif
#if ENV_INCLUDE_INA219 || ENV_INCLUDE_INA226 || ENV_INCLUDE_INA3221
// CUSTOM (TeTeHacko): the shunt is a property of the module, not of the
// firmware -- `sensor set ina.shunt <mOhm>`, kept in prefs (ina_shunt), 0 = the
// build's value for the chip. INA219/INA226 current is computed here from the
// shunt voltage (as in the Chytra Budka), so a new value needs no recalibration;
// INA3221 gets it through its driver.
static float ina_shunt_mohm = 0;
static float ina_shunt_ohm(float build_default) {
return ina_shunt_mohm > 0 ? ina_shunt_mohm / 1000.0f : build_default;
}
#endif
#if ENV_INCLUDE_MLX90614
#ifndef TELEM_MLX90614_ADDRESS
#define TELEM_MLX90614_ADDRESS 0x5A // MLX90614 IR temperature sensor I2C address
@@ -326,7 +341,7 @@ static void query_lps22hb(uint8_t ch, uint8_t, CayenneLPP& lpp) {
static uint8_t init_ina3221(TwoWire* wire, uint8_t addr) {
if (!INA3221.begin(addr, wire)) return 0;
for (int i = 0; i < TELEM_INA3221_NUM_CHANNELS; i++) {
INA3221.setShuntResistance(i, TELEM_INA3221_SHUNT_VALUE);
INA3221.setShuntResistance(i, ina_shunt_ohm(TELEM_INA3221_SHUNT_VALUE));
}
// Each enabled hardware channel becomes its own telemetry channel.
uint8_t enabled = 0;
@@ -401,9 +416,11 @@ static void query_ina219(uint8_t ch, uint8_t, CayenneLPP& lpp) {
// begin() selects 12-bit single-sample bus and shunt conversions, 532 us each:
// 3 ms covers the wake-up and one fresh pair with margin.
delay(3);
lpp.addVoltage(ch, active_ina219->getBusVoltage_V());
lpp.addCurrent(ch, active_ina219->getCurrent_mA() / 1000.0f);
lpp.addPower(ch, active_ina219->getPower_mW() / 1000.0f);
const float volts = active_ina219->getBusVoltage_V();
const float amps = active_ina219->getShuntVoltage_mV() / 1000.0f / ina_shunt_ohm(TELEM_INA219_SHUNT_VALUE);
lpp.addVoltage(ch, volts);
lpp.addCurrent(ch, amps);
lpp.addPower(ch, volts * amps);
active_ina219->powerSave(true);
}
#endif
@@ -451,9 +468,11 @@ static void query_ina226(uint8_t ch, uint8_t, CayenneLPP& lpp) {
ina->shutDown();
return;
}
lpp.addVoltage(ch, ina->getBusVoltage());
lpp.addCurrent(ch, ina->getCurrent_mA() / 1000.0f);
lpp.addPower(ch, ina->getPower_mW() / 1000.0f);
const float volts = ina->getBusVoltage();
const float amps = ina->getShuntVoltage() / ina_shunt_ohm(TELEM_INA226_SHUNT_VALUE);
lpp.addVoltage(ch, volts);
lpp.addCurrent(ch, amps);
lpp.addPower(ch, volts * amps);
ina->shutDown();
}
#endif
@@ -820,11 +839,21 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen
}
// CUSTOM (TeTeHacko): an INA chip whose shunt `ina.shunt` applies to is active.
bool EnvironmentSensorManager::hasShuntIna() const {
for (int j = 0; j < _active_sensor_count; j++) {
const char* n = _active_sensors[j].name;
if (n && (strcmp(n, "INA219") == 0 || strcmp(n, "INA226") == 0 || strcmp(n, "INA3221") == 0)) return true;
}
return false;
}
int EnvironmentSensorManager::getNumSettings() const {
int settings = 0;
#if ENV_INCLUDE_GPS
if (gps_detected) settings += 1; // GPS enablement
#endif
if (hasShuntIna()) settings += 1; // ina.shunt
return settings;
}
@@ -835,6 +864,7 @@ const char* EnvironmentSensorManager::getSettingName(int i) const {
return "gps";
}
#endif
if (hasShuntIna() && i == settings++) return "ina.shunt";
return NULL;
}
@@ -849,10 +879,34 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const {
return _location->isGpsOn() ? "1" : "0";
}
#endif
#if ENV_INCLUDE_INA219 || ENV_INCLUDE_INA226 || ENV_INCLUDE_INA3221
if (hasShuntIna() && i == settings++) {
static char buf[16]; // mOhm; 0 = the build's value
snprintf(buf, sizeof(buf), "%.3f", ina_shunt_mohm);
return buf;
}
#endif
return NULL;
}
bool EnvironmentSensorManager::setSettingValue(const char* name, const char* value) {
#if ENV_INCLUDE_INA219 || ENV_INCLUDE_INA226 || ENV_INCLUDE_INA3221
if (strcmp(name, "ina.shunt") == 0) {
if (!hasShuntIna()) return false;
// a number of mOhm, 0 = the build's value; atof() alone would take "nan"
const char* c = value;
if (!((*c >= '0' && *c <= '9') || *c == '.')) return false;
float mohm = atof(value);
if (!(mohm >= 0.0f && mohm <= 10000.0f)) return false;
ina_shunt_mohm = mohm;
#if ENV_INCLUDE_INA3221
for (int i = 0; i < TELEM_INA3221_NUM_CHANNELS; i++) {
INA3221.setShuntResistance(i, ina_shunt_ohm(TELEM_INA3221_SHUNT_VALUE));
}
#endif
return true;
}
#endif
#if ENV_INCLUDE_GPS
if (gps_detected && strcmp(name, "gps") == 0) {
if (strcmp(value, "0") == 0) {
@@ -58,4 +58,5 @@ public:
const char* getSettingValue(int i) const override;
bool setSettingValue(const char* name, const char* value) override;
int scanI2C(char* dest, size_t max_len) override;
bool hasShuntIna() const; // CUSTOM (TeTeHacko): `ina.shunt` applies
};