Changelog-cs: Repeater, room server, sensor (nRF52): hlavní smyčka spí bez pravidelného tiku místo ~1000 probuzení za sekundu Changelog-topic: tickless Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
706 lines
25 KiB
C++
706 lines
25 KiB
C++
|
|
#define RADIOLIB_STATIC_ONLY 1
|
|
#include "RadioLibWrappers.h"
|
|
|
|
#define STATE_IDLE 0
|
|
#define STATE_RX 1
|
|
#define STATE_TX_WAIT 3
|
|
#define STATE_TX_DONE 4
|
|
#define STATE_INT_READY 16
|
|
|
|
#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
|
|
static volatile uint32_t diag_isr_ms = 0; // millis() of the last one
|
|
#endif
|
|
|
|
#if defined(NRF52_PLATFORM)
|
|
extern "C" void nrf52WakeFromISR(void); // NRF52Board.cpp: ends the loop's tickless wait
|
|
#endif
|
|
|
|
// this function is called when a complete packet
|
|
// is transmitted by the module
|
|
static
|
|
#if defined(ESP8266) || defined(ESP32)
|
|
ICACHE_RAM_ATTR
|
|
#endif
|
|
void setFlag(void) {
|
|
// we sent a packet, set the flag
|
|
state |= STATE_INT_READY;
|
|
#if defined(NRF52_PLATFORM)
|
|
nrf52WakeFromISR();
|
|
#endif
|
|
#ifdef RADIO_DIAG
|
|
diag_isr_count++;
|
|
diag_isr_ms = millis();
|
|
#endif
|
|
}
|
|
|
|
void RadioLibWrapper::begin() {
|
|
_radio->setPacketReceivedAction(setFlag); // this is also SentComplete interrupt
|
|
_preamble_sf = getSpreadingFactor();
|
|
_radio->setPreambleLength(preambleLengthForSF(_preamble_sf)); // longer preamble for lower SF improves reliability
|
|
state = STATE_IDLE;
|
|
|
|
if (_board->getStartupReason() == BD_STARTUP_RX_PACKET) { // received a LoRa packet (while in deep sleep)
|
|
setFlag(); // LoRa packet is already received
|
|
}
|
|
|
|
_noise_floor = 0;
|
|
_threshold = 0;
|
|
_cad_enabled = false;
|
|
|
|
// start average out some samples
|
|
_num_floor_samples = 0;
|
|
_floor_sample_sum = 0;
|
|
}
|
|
|
|
uint32_t RadioLibWrapper::getRngSeed() {
|
|
return _radio->random(0x7FFFFFFF);
|
|
}
|
|
|
|
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 ==
|
|
// STATE_RX there, so nothing re-arms the receiver by itself. Drop to standby
|
|
// first and let checkRecv() re-arm Rx.
|
|
idle();
|
|
#endif
|
|
// CUSTOM (TeTeHacko): keep the status. The signature is an upstream callback
|
|
// and has to stay void, but the return value must not be thrown away: SX1262
|
|
// accepts only -9..+22 dBm and rejects the rest WITHOUT touching the PA, while
|
|
// `set tx` clamps to -9..30, saves the pref and replies "OK". Without this,
|
|
// "the radio refused" and "the radio changed" look identical from the console.
|
|
_last_txpow_dbm = dbm;
|
|
_last_txpow_status = _radio->setOutputPower(dbm);
|
|
}
|
|
|
|
void RadioLibWrapper::idle() {
|
|
#ifdef WITH_RX_POWERSAVING
|
|
if (_rx_ps_armed) stopReceiveDutyCycle();
|
|
#endif
|
|
_radio->standby();
|
|
state = STATE_IDLE; // need another startReceive()
|
|
}
|
|
|
|
void RadioLibWrapper::triggerNoiseFloorCalibrate(int threshold) {
|
|
_threshold = threshold;
|
|
if (_num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES) { // ignore trigger if currently sampling
|
|
_num_floor_samples = 0;
|
|
_floor_sample_sum = 0;
|
|
}
|
|
}
|
|
|
|
void RadioLibWrapper::doResetAGC() {
|
|
_radio->sleep(); // warm sleep to reset analog frontend
|
|
}
|
|
|
|
void RadioLibWrapper::kickRx() {
|
|
if (state == STATE_TX_WAIT) return; // mid-transmit: next check will try again
|
|
_radio->clearIrqFlags(0xFFFFFFFF); // a latched IRQ keeps DIO1 high: no new edge
|
|
idle(); // standby; Dispatcher re-arms RX on its next loop
|
|
}
|
|
|
|
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()
|
|
|
|
// Reset noise floor sampling so it reconverges from scratch.
|
|
// Without this, a stuck _noise_floor of -120 makes the sampling threshold
|
|
// too low (-106) to accept normal samples (~-105), self-reinforcing the
|
|
// stuck value even after the receiver has recovered.
|
|
_noise_floor = 0;
|
|
_num_floor_samples = 0;
|
|
_floor_sample_sum = 0;
|
|
}
|
|
|
|
#ifdef LORA_POLL_IRQ
|
|
// CUSTOM (TeTeHacko): salvage path for a node whose DIO1 interrupt line is dead.
|
|
//
|
|
// setPacketReceivedAction() above is the ONLY thing that ever sets
|
|
// STATE_INT_READY, so a broken DIO1 line means RxDone/TxDone never reach the
|
|
// MCU: TX times out and retries while the frames actually radiate (a witness
|
|
// node hears them), and received packets are never picked up. That is the exact
|
|
// signature that killed bench-board -- see nrf52-radio-fault-diagnosis.
|
|
//
|
|
// The chip latches those events in its IRQ status register regardless of whether
|
|
// they are mapped out to a DIO pin, so reading it over SPI bypasses the whole
|
|
// line -- and therefore works no matter WHICH end of it is broken (dead nRF52
|
|
// input, dead SX1262 output, or a cut trace). Rewiring DIO1 to a spare GPIO only
|
|
// helps in the first of those three cases, so this is the strictly stronger fix:
|
|
// if polling does not revive the node, no wire can either.
|
|
//
|
|
// Cost: one extra SPI read per Dispatcher pass (Dispatcher.cpp:72 -> loop()),
|
|
// alongside the isReceivingPacket() read that already happens in the same path,
|
|
// and completion is noticed on the next pass instead of instantly.
|
|
void RadioLibWrapper::pollIrq() {
|
|
if (state != STATE_RX && state != STATE_TX_WAIT) return; // nothing pending
|
|
uint32_t mask = irqDoneMask();
|
|
if (mask == 0) return; // radio has no mask
|
|
if (_radio->getIrqFlags() & mask) setFlag();
|
|
}
|
|
#endif
|
|
|
|
void RadioLibWrapper::loop() {
|
|
#ifdef LORA_POLL_IRQ
|
|
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();
|
|
if (rssi < _noise_floor + SAMPLING_THRESHOLD) { // only consider samples below current floor + sampling THRESHOLD
|
|
_num_floor_samples++;
|
|
_floor_sample_sum += rssi;
|
|
}
|
|
}
|
|
} else if (_num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES && _floor_sample_sum != 0) {
|
|
_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
|
|
}
|
|
#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 {
|
|
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: startReceive(%d)", err);
|
|
}
|
|
}
|
|
|
|
#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;
|
|
}
|
|
|
|
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);
|
|
if (err == RADIOLIB_ERR_NONE && !lastRxHadCRC()) {
|
|
err = RADIOLIB_ERR_LORA_HEADER_DAMAGED; // header says no CRC, so the payload was never checked
|
|
}
|
|
if (err != RADIOLIB_ERR_NONE) {
|
|
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: readData(%d)", err);
|
|
len = 0;
|
|
n_recv_errors++;
|
|
} else {
|
|
// Serial.print(" readData() -> "); Serial.println(len);
|
|
n_recv++;
|
|
#ifdef RADIO_DIAG
|
|
_diag_last_rx_ms = millis();
|
|
#endif
|
|
}
|
|
}
|
|
#if defined(USE_LR2021)
|
|
state = STATE_RX; // LR2021 stays in Rx after readData, calling startReceive while still in Rx throws -706 errors
|
|
#else
|
|
state = STATE_IDLE; // need another startReceive()
|
|
#endif
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
uint32_t RadioLibWrapper::getEstAirtimeFor(int len_bytes) {
|
|
return _radio->getTimeOnAir(len_bytes) / 1000;
|
|
}
|
|
|
|
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) {
|
|
state = STATE_TX_WAIT;
|
|
return true;
|
|
}
|
|
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: startTransmit(%d)", err);
|
|
idle(); // trigger another startRecv()
|
|
_board->onAfterTransmit();
|
|
return false;
|
|
}
|
|
|
|
bool RadioLibWrapper::isSendComplete() {
|
|
if (state & STATE_INT_READY) {
|
|
state = STATE_IDLE;
|
|
n_sent++;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void RadioLibWrapper::onSendFinished() {
|
|
_radio->finishTransmit();
|
|
_board->onAfterTransmit();
|
|
state = STATE_IDLE;
|
|
}
|
|
|
|
int16_t RadioLibWrapper::performChannelScan() {
|
|
return _radio->scanChannel();
|
|
}
|
|
|
|
#ifdef PIN_DIAG
|
|
// CUSTOM (TeTeHacko): make the radio itself assert DIO1, then report the chip's
|
|
// IRQ status register (read over SPI, independent of the pin) NEXT TO the actual
|
|
// level on the pin. That pair is what a multimeter would otherwise have to tell
|
|
// us, and it says which END of a dead DIO1 line is broken:
|
|
//
|
|
// irq has TX_DONE, pin HIGH -> the line is fine, look elsewhere
|
|
// irq has TX_DONE, pin LOW -> line dead. If a probe wire is fitted from the
|
|
// DIO1 net to PIN_DIAG_PROBE and THAT reads HIGH,
|
|
// the SX1262 still drives and it is the nRF52's
|
|
// input pad that died -- the one case a rewire
|
|
// to a spare GPIO actually fixes.
|
|
// no TX_DONE at all -> the chip never finished the transmit; the
|
|
// fault is not the IRQ line (SPI/BUSY/PA).
|
|
//
|
|
// A 1-byte transmit is used as the stimulus because TX_DONE is unconditional --
|
|
// it needs no peer, no antenna match and no RX activity. It DOES put a frame on
|
|
// the air, so run it on the bench band.
|
|
int RadioLibWrapper::probeDio1(uint32_t* irq_out, int* dio1_level, int* probe_level) {
|
|
if (state == STATE_TX_WAIT) return -1; // mid-transmit, don't clobber it
|
|
|
|
uint32_t mask = irqDoneMask();
|
|
if (mask == 0) return -3; // radio has no chip mask -> can't tell
|
|
|
|
uint8_t dummy = 0;
|
|
_radio->standby();
|
|
_board->onBeforeTransmit();
|
|
int err = _radio->startTransmit(&dummy, 1);
|
|
if (err != RADIOLIB_ERR_NONE) {
|
|
_board->onAfterTransmit();
|
|
idle();
|
|
return err;
|
|
}
|
|
|
|
uint32_t irq = 0;
|
|
unsigned long deadline = millis() + 2000;
|
|
while (millis() < deadline) {
|
|
irq = _radio->getIrqFlags();
|
|
if (irq & mask) break;
|
|
}
|
|
|
|
// Levels have to be sampled while the IRQ is still asserted: DIO1 stays high
|
|
// until the status register is cleared, and finishTransmit() clears it.
|
|
// Runtime compare, not #if: P_LORA_DIO_1 is usually a variant constant like D1
|
|
// (a static const, invisible to the preprocessor, which would silently read 0).
|
|
uint32_t dio1_pin = (uint32_t) P_LORA_DIO_1;
|
|
*dio1_level = (dio1_pin == RADIOLIB_NC) ? -1 : digitalRead(dio1_pin);
|
|
#ifdef PIN_DIAG_PROBE
|
|
pinMode(PIN_DIAG_PROBE, INPUT);
|
|
*probe_level = digitalRead(PIN_DIAG_PROBE);
|
|
#else
|
|
*probe_level = -1;
|
|
#endif
|
|
*irq_out = irq;
|
|
|
|
_radio->finishTransmit();
|
|
_board->onAfterTransmit();
|
|
state = STATE_IDLE; // Dispatcher will startReceive() again
|
|
return (irq & mask) ? 0 : -2;
|
|
}
|
|
#endif
|
|
|
|
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
|
|
// try to read a non-existent packet and count a spurious recv error.
|
|
state = STATE_IDLE;
|
|
startRecv();
|
|
if (result != RADIOLIB_CHANNEL_FREE) return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
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();
|
|
}
|
|
|
|
// Approximate SNR threshold per SF for successful reception (based on Semtech datasheets)
|
|
static float snr_threshold[] = {
|
|
-7.5, // SF7 needs at least -7.5 dB SNR
|
|
-10, // SF8 needs at least -10 dB SNR
|
|
-12.5, // SF9 needs at least -12.5 dB SNR
|
|
-15, // SF10 needs at least -15 dB SNR
|
|
-17.5,// SF11 needs at least -17.5 dB SNR
|
|
-20 // SF12 needs at least -20 dB SNR
|
|
};
|
|
|
|
float RadioLibWrapper::packetScoreInt(float snr, int sf, int packet_len) {
|
|
if (sf < 7) return 0.0f;
|
|
|
|
if (snr < snr_threshold[sf - 7]) return 0.0f; // Below threshold, no chance of success
|
|
|
|
auto success_rate_based_on_snr = (snr - snr_threshold[sf - 7]) / 10.0;
|
|
auto collision_penalty = 1 - (packet_len / 256.0); // Assuming max packet of 256 bytes
|
|
|
|
return max(0.0, min(1.0, success_rate_based_on_snr * collision_penalty));
|
|
}
|
|
|
|
PacketMillis RadioLibWrapper::calcMaxPacketMillis(uint8_t sf, float bw, uint8_t cr, uint8_t preambleSymbols) {
|
|
// based on RadioLib's calculateTimeOnAir()
|
|
uint32_t tsym_us = ((uint32_t)10000 << sf) / (bw * 10);
|
|
uint32_t sfCoeff1_x4 = (sf == 5 || sf == 6) ? 25 : 17; // 6.25 : 4.25, semtech magic numbers to account for sync word + sfd
|
|
|
|
// preamble + syncword + sfd + header
|
|
uint32_t preamble_us = (((preambleSymbols + 8) * 4 + sfCoeff1_x4) * tsym_us) / 4;
|
|
|
|
// airtime for max packet at current radio settings
|
|
uint32_t total_us = _radio->getTimeOnAir(MAX_TRANS_UNIT);
|
|
// airtime for payload only (no preamble, header or SOF).
|
|
//
|
|
// CUSTOM (TeTeHacko): the fallback taken when getTimeOnAir() is not usable yet
|
|
// must not underflow. Upstream writes the intended "4 secs at worst case" as
|
|
// 4000 -- these are MICROseconds, so 4 ms -- and then subtracts an unsigned
|
|
// preamble from it. Our CZ preset (SF8 / BW62.5) has a ~4.1 ms symbol time and
|
|
// a ~116 ms preamble, so the subtraction wraps to ~4.29e9 us and
|
|
// _maxPayloadMillis becomes ~4.29 million seconds. isReceiving() can then never
|
|
// time out a header it has latched: the radio reports "busy receiving" forever,
|
|
// RX is never re-armed, and the node goes deaf while still transmitting
|
|
// normally -- no acks, no channel messages, no adverts.
|
|
//
|
|
// Every SX126x/LR11x0 wrapper feeds this into its stateful isReceiving(), so it
|
|
// reaches the T1000-E and the Wio L1 as much as the SenseCap boards.
|
|
// Fix taken from ALLFATHER-BV/meshcomod d6a72f8 (MIT).
|
|
const uint32_t fallback_total_us = 4000000; // 4 SECONDS, in microseconds
|
|
const uint32_t base_us = (total_us > preamble_us) ? total_us : fallback_total_us;
|
|
uint32_t payload_us = (base_us > preamble_us) ? (base_us - preamble_us) : (base_us / 2);
|
|
// rescale payload_us for max possible CR
|
|
if (cr >= 5 && cr < 8) { payload_us = (payload_us * 8) / cr; }
|
|
|
|
return PacketMillis {(preamble_us + 999) / 1000, (payload_us + 999) / 1000};
|
|
}
|
|
|
|
#ifdef RADIO_DIAG
|
|
// CUSTOM (TeTeHacko): a receiver that silently stops receiving (31. 10. 2026,
|
|
// bench-sensor: recv frozen for minutes, noise_floor -120, last_rssi 0, a reboot
|
|
// revived it) can be stuck in several different places, and each one is a
|
|
// different bug:
|
|
//
|
|
// chip mode != RX -> the chip left RX (reset/brownout, or a
|
|
// command path that put it in standby)
|
|
// while `st` still says RX
|
|
// mode RX, RX_DONE in irq, DIO1=1 -> the packet is there and the line is up,
|
|
// but the edge never reached the MCU
|
|
// (isr count frozen): lost interrupt
|
|
// mode RX, irq clean, RSSI ~floor -> analog front end / AGC stuck
|
|
//
|
|
// `radiostat` reads all of it without touching the radio state. `radiokick`
|
|
// then applies ONE recovery step at a time, from the gentlest; the first step
|
|
// that brings recv back names the layer that was broken.
|
|
bool RadioLibWrapper::diagHandleCommand(const char* command, char* reply) {
|
|
if (strcmp(command, "radiostat") == 0) {
|
|
uint32_t now = millis();
|
|
int n = snprintf(reply, 160, "st=%u isr=%lu/%lus rx=%lu/%lus err=%lu",
|
|
(unsigned) state, (unsigned long) diag_isr_count,
|
|
(unsigned long) ((now - diag_isr_ms) / 1000),
|
|
(unsigned long) n_recv, (unsigned long) ((now - _diag_last_rx_ms) / 1000),
|
|
(unsigned long) n_recv_errors);
|
|
if (n > 0 && n < 160) diagChip(reply + n, 160 - n);
|
|
return true;
|
|
}
|
|
if (memcmp(command, "radiokick ", 10) == 0) {
|
|
const char* what = command + 10;
|
|
if (strcmp(what, "rx") == 0) { // re-arm RX only (no standby, no clear)
|
|
state = STATE_IDLE;
|
|
} else if (strcmp(what, "clrirq") == 0) { // drop latched IRQs: DIO1 falls, next RX_DONE is a new edge
|
|
_radio->clearIrqFlags(0xFFFFFFFF);
|
|
} else if (strcmp(what, "standby") == 0) { // standby + startReceive
|
|
idle();
|
|
} else if (strcmp(what, "agc") == 0) { // warm sleep + calibrate, the agc.reset path
|
|
doResetAGC();
|
|
state = STATE_IDLE;
|
|
} else {
|
|
strcpy(reply, "usage: radiokick rx|clrirq|standby|agc");
|
|
return true;
|
|
}
|
|
sprintf(reply, "OK - %s", what);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
#endif
|