Speed up SX1262 profile switching and verify radio lab behavior

Keep TCXO warm during owned dual-profile retunes, batch modulation setup, and enable guarded fast RX with buffered 8 MHz SPI on XIAO S3 WIO and Indicator LoRa. Preserve lifecycle invalidation, packet guards, rollback, and existing scheduling budgets.

Add reliable sequence-scoped USB lab transport, native regression coverage, bounded channel and preamble diagnostics, and byte-exact measurement records including failed experiments and qualification limits.
This commit is contained in:
mikecarper committed 2026-09-14 01:22:09 -07:00
1 parent 25eab1a581
commit bd30388436
90 files changed
+146200 -20

No files matched your search

+5 -4
View File
@@ -38,10 +38,11 @@ class RadioProfiles {
static constexpr uint8_t MinFastListenSymbols = 4;
static constexpr uint8_t AcquisitionSymbols = 8;
static constexpr uint16_t MaxPreamble = 65528;
// The mixed-profile bench tests measured ~1.2 ms/visit with fast RX. Normal
// drivers may wake a TCXO; production V4 measured up to 4.4 ms. Budget
// 6 ms per change plus 4 ms of loop jitter. Packet receptions can extend
// a visit; these budgets describe an otherwise idle scan.
// The integrated fast RX/buffered-SPI path measures ~0.549 ms/hop on XIAO
// and ~8.263 ms on Indicator (expander GPIO), excluding application scheduling.
// Keep existing defaults unchanged during board/application qualification.
// Thus 6 ms is not an upper bound: board-specific budgeting needs follow-up.
// Packet receptions can extend a visit; these budgets describe an idle scan.
static constexpr uint32_t SwitchBudgetUs = 6000;
static constexpr uint32_t LoopBudgetUs = 4000;
+164 -1
View File
@@ -3,6 +3,11 @@
#include <RadioLib.h>
#include "MeshCore.h"
#include "RXPowerSaving.h"
#include "SX1262ProfileSwitchState.h"
#ifndef MC_SX1262_FAST_PROFILE_SWITCH
#define MC_SX1262_FAST_PROFILE_SWITCH 0
#endif
#ifndef SX126X_TX_BUSY_TIMEOUT_MS
#define SX126X_TX_BUSY_TIMEOUT_MS 1000UL
@@ -15,18 +20,148 @@ class CustomSX1262 : public SX1262 {
bool _headerSeen = false;
bool _rx_ps_rf_rx_disabled = false;
uint32_t _rxDutyCycleTransitionUs = 1000;
SX1262ProfileSwitchState _profileSwitch{MC_SX1262_FAST_PROFILE_SWITCH != 0};
uint32_t _profileFastResumes = 0;
bool _coldStandby = true;
bool _tcxoWakePending = false;
public:
CustomSX1262(Module *mod) : SX1262(mod) { }
void setProfileSwitchOptimization(bool enabled) {
_profileSwitch.enabled = enabled;
_profileSwitch.invalidate();
}
void beginProfileSwitch(bool continuousRx) { _profileSwitch.begin(continuousRx, standbyXOSC); }
void endProfileSwitch(bool success) { _profileSwitch.end(success); }
bool profileSwitchFailed() const { return _profileSwitch.failed(); }
uint32_t getOptimizedProfileSwitches() const { return _profileFastResumes; }
int16_t restoreTcxoAfterSleep() {
if (!_tcxoWakePending) return RADIOLIB_ERR_NONE;
// Both RC and warm policies showed a wake-only XOSC error on the WIO
// module. Restore the existing DIO3 voltage/delay, never disable TCXO.
// RadioLib clears XOSC_START_ERR here; do not hide unrelated faults.
if (getDeviceErrors() & ~RADIOLIB_SX126X_XOSC_START_ERR) return RADIOLIB_ERR_SPI_CMD_FAILED;
_tcxoWakePending = false; // setTCXO calls our explicit standby override
const int16_t rc = SX1262::setTCXO(tcxoVoltage, tcxoDelay);
if (rc != RADIOLIB_ERR_NONE) _tcxoWakePending = true;
return rc;
}
int16_t standby() override {
const bool alreadyAwake = !_coldStandby && _profileSwitch.active && _profileSwitch.rxValid;
if (!alreadyAwake) _profileSwitch.invalidate();
int16_t rc = alreadyAwake
? SX1262::standby(RADIOLIB_SX126X_STANDBY_XOSC, false)
: _coldStandby ? SX1262::standby(RADIOLIB_SX126X_STANDBY_RC) : SX1262::standby();
if (rc == RADIOLIB_ERR_NONE) rc = restoreTcxoAfterSleep();
if (rc != RADIOLIB_ERR_NONE) _coldStandby = true;
_profileSwitch.standbyResult(rc);
return rc;
}
int16_t standby(uint8_t mode) override {
_profileSwitch.invalidate();
int16_t rc = SX1262::standby(mode);
if (rc == RADIOLIB_ERR_NONE) rc = restoreTcxoAfterSleep();
if (mode == RADIOLIB_SX126X_STANDBY_RC || rc != RADIOLIB_ERR_NONE) _coldStandby = true;
_profileSwitch.standbyResult(rc);
return rc;
}
// SetSleep is only valid from standby (SX1261/2 datasheet 13.1.1).
// ResetAGC may call us directly from RX. Use RC for sleep entry/wake,
// retaining the requested warm policy for subsequent established RX.
int16_t sleep() override { return sleep(true); }
int16_t sleep(bool retainConfig) {
_profileSwitch.invalidate();
_coldStandby = true;
const int16_t rc = SX1262::standby(RADIOLIB_SX126X_STANDBY_RC);
_tcxoWakePending = tcxoVoltage > 0.0f;
return rc == RADIOLIB_ERR_NONE ? SX1262::sleep(retainConfig) : rc;
}
int16_t reset(bool verify = true) { _profileSwitch.invalidate(); _coldStandby = true; _tcxoWakePending = false; return SX1262::reset(verify); }
int16_t stageMode(RadioModeType_t mode, RadioModeConfig_t* cfg) override {
// All ordinary RX/TX staging rebuilds hardware state. In particular TX
// changes IRQ mapping, packet length and buffer contents/base settings.
_profileSwitch.invalidate();
return SX1262::stageMode(mode, cfg);
}
int16_t setPreambleLength(size_t symbols) override {
if (_profileSwitch.canResumeFast()) {
// The owned hop will commit the complete packet tuple once, in RX
// resume. A failed hop discards this capability before rollback.
preambleLengthLoRa = symbols;
return RADIOLIB_ERR_NONE;
}
return SX1262::setPreambleLength(symbols);
}
// Apply one complete LoRa modulation tuple instead of three separate
// SetModulationParams commands. Keep RadioLib's caches and automatic LDRO
// calculation consistent with its ordinary SF/BW/CR setters. Caller must
// own a safe standby/reconfigure window, just as for those setters.
int16_t setLoRaModulationParams(float bw, uint8_t sf, uint8_t cr) {
if (sf < 5 || sf > 12) return RADIOLIB_ERR_INVALID_SPREADING_FACTOR;
if (cr < 4 || cr > 8) return RADIOLIB_ERR_INVALID_CODING_RATE;
if (!isfinite(bw)) return RADIOLIB_ERR_INVALID_BANDWIDTH;
static constexpr float bandwidths[] = {7.8f, 10.4f, 15.6f, 20.8f, 31.25f,
41.7f, 62.5f, 125.0f, 250.0f, 500.0f};
static constexpr uint8_t codes[] = {
RADIOLIB_SX126X_LORA_BW_7_8, RADIOLIB_SX126X_LORA_BW_10_4,
RADIOLIB_SX126X_LORA_BW_15_6, RADIOLIB_SX126X_LORA_BW_20_8,
RADIOLIB_SX126X_LORA_BW_31_25, RADIOLIB_SX126X_LORA_BW_41_7,
RADIOLIB_SX126X_LORA_BW_62_5, RADIOLIB_SX126X_LORA_BW_125_0,
RADIOLIB_SX126X_LORA_BW_250_0, RADIOLIB_SX126X_LORA_BW_500_0};
size_t index = 0;
while (index < sizeof(bandwidths) / sizeof(bandwidths[0])
&& fabsf(bw - bandwidths[index]) >= 0.01f) ++index;
if (index == sizeof(bandwidths) / sizeof(bandwidths[0])) {
return RADIOLIB_ERR_INVALID_BANDWIDTH;
}
if (getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA) {
return RADIOLIB_ERR_WRONG_MODEM;
}
const auto oldSf = spreadingFactor;
const auto oldBw = bandwidth;
const auto oldBwKhz = bandwidthKhz;
const auto oldCr = codingRate;
const auto oldLdro = ldrOptimize;
spreadingFactor = sf;
bandwidth = codes[index];
bandwidthKhz = bw;
codingRate = cr - 4; // ordinary LoRa CR, not long-interleaving encoding
const int16_t state = setModulationParams(sf, bandwidth, codingRate, ldrOptimize);
if (state != RADIOLIB_ERR_NONE) {
// The wrapper restores the physical tuple after a failed command.
// Do not publish a new software tuple when hardware success is unknown.
spreadingFactor = oldSf;
bandwidth = oldBw;
bandwidthKhz = oldBwKhz;
codingRate = oldCr;
ldrOptimize = oldLdro;
}
return state;
}
// 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) {
_profileSwitch.invalidate();
// A held dual-profile oscillator must not be selected during reset or
// setup, before DIO3/TCXO configuration has been restored. Restore the
// software standby policy on both success and failure; only subsequent
// standby/RX commands can actually turn the oscillator back on.
const bool savedStandbyXosc = standbyXOSC;
_coldStandby = true;
_tcxoWakePending = false;
standbyXOSC = false;
int16_t state = SX1262::begin(freq, bw, sf, cr, syncWord, power, preambleLength,
tcxoVoltage, useRegulatorLDO);
if (state == RADIOLIB_ERR_NONE) state = applyMeshCoreTcxoDelay();
standbyXOSC = savedStandbyXosc;
return state;
}
@@ -179,6 +314,8 @@ class CustomSX1262 : public SX1262 {
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) {
_profileSwitch.invalidate();
_coldStandby = true;
int16_t state = SX1262::startReceiveDutyCycle(rxPeriod, sleepPeriod, irqFlags, irqMask);
if (state == RADIOLIB_ERR_NONE && !_rx_ps_rf_rx_disabled) {
// RadioLib stages RX duty-cycle through standby, which leaves a
@@ -271,12 +408,38 @@ class CustomSX1262 : public SX1262 {
}
int16_t startReceive() override {
if (_profileSwitch.canResumeFast()) {
// Existing continuous RX already established buffer bases and the
// MeshCore IRQ map (including preamble detection). No TX/CAD/sleep/
// reset/staging may intervene without revoking that context.
_profileSwitch.rxValid = false; // fail closed on any command error
int16_t rc = clearIrqStatus();
if (rc == RADIOLIB_ERR_NONE) {
rc = setPacketParams(preambleLengthLoRa, crcTypeLoRa, implicitLen,
headerType, invertIQEnabled);
}
if (rc == RADIOLIB_ERR_NONE) {
rxTimeout = RADIOLIB_SX126X_RX_TIMEOUT_INF;
getMod()->setRfSwitchState(Module::MODE_RX);
rc = setRx(rxTimeout); // original BUSY waits and status checks
}
stagedMode = RADIOLIB_RADIO_MODE_NONE;
if (rc == RADIOLIB_ERR_NONE) ++_profileFastResumes;
_coldStandby = rc != RADIOLIB_ERR_NONE;
_profileSwitch.rxResult(rc, true);
return rc;
}
// Make preamble detection visible to CAD while retaining RadioLib's
// normal RX-complete and error events.
return SX1262::startReceive(
const int16_t rc = SX1262::startReceive(
RADIOLIB_SX126X_RX_TIMEOUT_INF,
RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED),
RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
const bool reusable = rc == RADIOLIB_ERR_NONE && _profileSwitch.enabled
&& getPacketType() == RADIOLIB_SX126X_PACKET_TYPE_LORA;
_coldStandby = rc != RADIOLIB_ERR_NONE;
_profileSwitch.rxResult(rc, reusable);
return rc;
}
bool isReceiving() {
+23 -3
View File
@@ -10,8 +10,29 @@
#endif
class CustomSX1262Wrapper : public RadioLibWrapper {
bool _profile_standby_held = false;
bool _saved_standby_xosc = false;
protected:
int8_t readReceiveMode() override { return sx126xReceiveMode((SX126x*)_radio); }
void beginProfileRetune(bool continuousRx) override {
static_cast<CustomSX1262*>(_radio)->beginProfileSwitch(continuousRx);
}
void endProfileRetune(bool success) override {
static_cast<CustomSX1262*>(_radio)->endProfileSwitch(success);
}
void setProfileStandbyWarm(bool enabled) override {
if (enabled == _profile_standby_held) return;
auto* radio = static_cast<CustomSX1262*>(_radio);
if (enabled) {
_saved_standby_xosc = radio->standbyXOSC;
radio->standbyXOSC = true;
} else {
radio->standbyXOSC = _saved_standby_xosc;
}
_profile_standby_held = enabled;
}
public:
CustomSX1262Wrapper(CustomSX1262& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
@@ -30,10 +51,9 @@ protected:
}
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
if (static_cast<CustomSX1262*>(_radio)->profileSwitchFailed()) return false;
bool success = ((CustomSX1262 *)_radio)->setFrequency(freq) == RADIOLIB_ERR_NONE
&& ((CustomSX1262 *)_radio)->setSpreadingFactor(sf) == RADIOLIB_ERR_NONE
&& ((CustomSX1262 *)_radio)->setBandwidth(bw) == RADIOLIB_ERR_NONE
&& ((CustomSX1262 *)_radio)->setCodingRate(cr) == RADIOLIB_ERR_NONE
&& ((CustomSX1262 *)_radio)->setLoRaModulationParams(bw, sf, cr) == RADIOLIB_ERR_NONE
&& updatePreamble(sf, bw);
if (!success) return false;
@@ -0,0 +1,17 @@
#pragma once
#include <hal/Arduino/ArduinoHal.h>
#ifndef MC_SX1262_SPI_HZ
#define MC_SX1262_SPI_HZ 8000000
#endif
// Opted-in ESP32 boards only. Keep RadioLib's transaction/CS, BUSY polling and
// status parsing unchanged; send each full-duplex buffer in one SPI operation.
class ESP32BufferedRadioHal : public ArduinoHal {
public:
explicit ESP32BufferedRadioHal(SPIClass& bus)
: ArduinoHal(bus, SPISettings(MC_SX1262_SPI_HZ, MSBFIRST, SPI_MODE0)) {}
void spiTransfer(uint8_t* out, size_t len, uint8_t* in) override {
if (len) spi->transferBytes(out, in, len);
}
};
+31 -4
View File
@@ -235,23 +235,48 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) {
&& _physical_preamble == preamble) return mesh::RadioParamApplyResult::APPLIED;
if (!validateProfile(p)) return mesh::RadioParamApplyResult::FAILED;
const uint32_t started = micros();
beginProfileRetune(isInRecvMode() && !_rx_ps_armed && !_rx_ps_enabled);
const uint8_t resume = beginReconfigure();
if (resume > 1) return mesh::RadioParamApplyResult::BUSY;
if (resume > 1) {
endProfileRetune(true); // guard deferred before changing hardware
return mesh::RadioParamApplyResult::BUSY;
}
const float old_freq = _cur_freq, old_bw = _cur_bw;
const uint8_t old_sf = _cur_sf, old_cr = _cur_cr, old_profile = _active_profile;
const uint32_t old_generation = _profile_generation;
const bool old_refresh = _profile_refresh_required;
const bool old_params_valid = _params_valid;
const uint16_t old_preamble = _physical_preamble;
_physical_preamble = preamble;
const bool applied = applyParams(p.freq, p.bw, p.sf, p.cr);
bool applied = applyParams(p.freq, p.bw, p.sf, p.cr);
if (applied) {
cacheParams(p.freq, p.bw, p.sf, p.cr);
_active_profile = profile;
_profile_generation = _profiles.generation[profile];
_profile_refresh_required = false;
endReconfigure(resume);
applied = !resume || isInRecvMode();
}
endProfileRetune(applied);
if (applied) {
++_profiles.switches;
} else {
++_profiles.switch_failures;
// RX restart is part of the transaction, not merely a best-effort tail.
// Revoke any fast-RX capability and restore both the physical tuple and
// published profile on an apply or receive-resume failure.
cacheParams(old_freq, old_bw, old_sf, old_cr);
_params_valid = old_params_valid;
_active_profile = old_profile;
_profile_generation = old_generation;
_profile_refresh_required = old_refresh;
_physical_preamble = old_preamble;
if (!applyParams(_cur_freq, _cur_bw, _cur_sf, _cur_cr)) restoreAfterDeepInit();
bool restored = old_params_valid && _radio->standby() == RADIOLIB_ERR_NONE
&& applyParams(old_freq, old_bw, old_sf, old_cr);
if (!restored) restored = restoreAfterDeepInit();
if (restored) endReconfigure(resume);
if (!restored || (resume && !isInRecvMode())) _profile_refresh_required = true;
}
endReconfigure(resume);
_profile_visit_us = micros();
const uint32_t elapsed = _profile_visit_us - started;
if (elapsed > _profiles.longest_switch_us) _profiles.longest_switch_us = elapsed;
@@ -278,6 +303,7 @@ void RadioLibWrapper::serviceProfileScan() {
_nf_calib_active = false;
_noise_floor_valid = false; // a single-channel floor cannot describe both channels
_profile_refresh_required = true; // refresh side detectors even if the tuple is unchanged
setProfileStandbyWarm(true);
endReconfigure(resume);
}
uint8_t target = _active_profile;
@@ -308,6 +334,7 @@ void RadioLibWrapper::serviceProfileScan() {
_rx_ps_enabled = _profile_saved_rxps;
_profile_rxps_suspended = false;
_profile_refresh_required = true;
setProfileStandbyWarm(false);
recalibrateNoiseFloor();
endReconfigure(resume);
}
+6
View File
@@ -150,6 +150,12 @@ protected:
return _radio->setOutputPower(dbm);
}
virtual bool applyRxBoostedGainMode(bool) { return false; }
// Dual-profile scanning already suspends RXPS. Supported radios can also
// retain their oscillator across the intervening standby/reconfigure steps.
// Called only at the safe scan-mode entry/exit boundary, not during a packet.
virtual void setProfileStandbyWarm(bool) {}
virtual void beginProfileRetune(bool) {}
virtual void endProfileRetune(bool) {}
// 0 = reconfigure from idle, 1 = resume RX afterwards, 2 = currently busy.
uint8_t beginReconfigure();
void endReconfigure(bool resume_rx);
@@ -0,0 +1,46 @@
#pragma once
#include <stdint.h>
// A short-lived capability for reusing a fully configured continuous-RX
// context. Standby outside the owned hop, staging, sleep and reset revoke it.
struct SX1262ProfileSwitchState {
bool enabled;
bool rxValid = false;
bool open = false;
bool active = false;
bool standbyReady = false;
int16_t error = 0;
explicit SX1262ProfileSwitchState(bool enable) : enabled(enable) {}
void invalidate() { rxValid = active = standbyReady = false; }
void begin(bool continuousRx, bool warm) {
open = true;
error = 0;
standbyReady = false;
active = enabled && rxValid && continuousRx && warm;
}
void standbyResult(int16_t result) {
if (result != 0) {
if (open) error = result;
invalidate();
} else if (active) {
standbyReady = true;
}
}
bool canResumeFast() const { return open && active && rxValid && standbyReady && error == 0; }
bool failed() const { return open && error != 0; }
void rxResult(int16_t result, bool reusable) {
if (result != 0) {
if (open) error = result;
invalidate();
} else {
rxValid = enabled && reusable;
standbyReady = false;
}
}
void end(bool success) {
if (!success) invalidate();
open = active = standbyReady = false;
error = 0;
}
};