feat(power): battery saving — hardware duty-cycle RX + adaptive TX power

Two independent, default-off toggles under Settings › Radio.

Pwr save: hardware RX duty-cycle (SX126x SetRxDutyCycle via
startReceiveDutyCycleAuto). The chip cycles RX↔sleep and wakes on a preamble —
no MCU state machine; recvRaw reads the packet exactly as in continuous RX.
Falls back to continuous RX on non-SX126x. (Replaces an earlier software-CAD
state machine that fought the hardware: polling a warm-sleeping chip gave a
phantom-busy channel that stalled TX ~4 s and dropped ACKs in the scan gaps.)

Auto pwr: Adaptive Power Control. tx_power_dbm becomes a ceiling; actual TX
power tracks the reverse-link SNR margin (measured above the per-SF demod floor,
EWMA-smoothed, proportional step with a deadband). Feedback comes from direct /
room-server ACKs and, for channels (no ACK), from hearing a repeater rebroadcast
our own flood; a lost confirmation ramps power back up so channel sends can't get
stranded below what the repeaters can hear.

Prefs schema 0xC0DE0009 (rx_powersave, tx_apc). Radio page / name bar show the
live TX power; noise floor reads n/a while duty-cycling.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jakub
2026-06-11 08:15:42 +02:00
co-authored by Claude Opus 4.8
parent baaac3179c
commit 5b58049139
13 changed files with 346 additions and 42 deletions
+117 -2
View File
@@ -487,6 +487,18 @@ void MyMesh::queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packe
}
bool MyMesh::filterRecvFloodPacket(mesh::Packet* packet) {
// APC: a channel/flood packet we originated, heard back from a repeater, is
// positive feedback on the repeater link — sample its SNR. This is the only
// confirmation a channel send gets (no ACK), and is what lets APC recover power
// after it has trimmed too far for the repeaters to hear.
if (_prefs.tx_apc && _apc_flood_pending && packet->payload_len == _apc_flood_len) {
uint8_t h[MAX_HASH_SIZE];
packet->calculatePacketHash(h);
if (memcmp(h, _apc_flood_hash, MAX_HASH_SIZE) == 0) {
_apc_flood_pending = false;
apcSampleSnr(packet->getSNR());
}
}
// REVISIT: try to determine which Region (from transport_codes[1]) that Sender is indicating for replies/responses
// if unknown, fallback to finding Region from transport_codes[0], the 'scope' used by Sender
return false;
@@ -521,6 +533,7 @@ void MyMesh::sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, ui
}
void MyMesh::sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis) {
// TODO: have per-channel send_scope
if (_prefs.tx_apc) apcTrackFloodSend(pkt); // listen for a repeater echo to drive APC (channels have no ACK)
if (send_unscoped) {
sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); // app has explicitly requested un-scoped
} else {
@@ -1056,7 +1069,101 @@ uint32_t MyMesh::calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t
(path_hash_count + 1));
}
void MyMesh::onSendTimeout() {}
// Adaptive Power Control. tx_power_dbm is the user-set ceiling; APC drives the
// radio's *actual* TX power within [APC_MIN_DBM, ceiling] to hold the link margin
// near a target. The link-quality signal is the SNR of a returning confirmation —
// either a direct-message ACK or our own channel/flood packet heard rebroadcast by
// a repeater (both are the *reverse* link, a good proxy on a roughly symmetric RF
// neighbourhood). No protocol change required.
//
// The margin is measured *above this SF's demodulation floor* (not an absolute
// SNR), so the same target works across SF7SF12. A single SNR sample is noisy, so
// we smooth it with an EWMA and step proportionally to the error (capped), with a
// deadband to avoid hunting. A lost confirmation is an ambiguous signal for power,
// so we step up gradually and only jump to the ceiling after a short streak.
#define APC_MIN_DBM -9 // lower bound (SX126x PA floor)
#define APC_TARGET_MARGIN_DB 6.0f // desired SNR margin above the SF demod floor
#define APC_DEADBAND_DB 2.0f // hold while the smoothed margin is within ±this
#define APC_EWMA_ALPHA 0.4f // smoothing weight for each SNR sample
#define APC_MAX_STEP_DB 2 // cap on a single power adjustment (stability)
#define APC_FAIL_STEP_DB 4 // power bump on one lost confirmation
#define APC_FAIL_CEIL_HITS 2 // consecutive losses → jump straight to the ceiling
// How long to wait for a repeater to rebroadcast our channel/flood packet before
// treating it as un-heard (flood retransmit delays are randomised over a few s).
#define APC_FLOOD_ECHO_WINDOW_MS 6000
void MyMesh::applyApc() {
_apc_cur_dbm = _prefs.tx_power_dbm; // start at the ceiling
_apc_margin_ewma = APC_TARGET_MARGIN_DB; // assume on-target until samples say otherwise
_apc_fail_count = 0;
_apc_flood_pending = false;
radio_driver.setTxPower(_apc_cur_dbm);
}
// Feed one reverse-link SNR sample (ACK or heard flood echo) into the controller.
void MyMesh::apcSampleSnr(float snr) {
_apc_fail_count = 0; // a confirmation clears the failure streak
float margin = snr - radio_driver.snrFloorForSF(_prefs.sf);
_apc_margin_ewma += APC_EWMA_ALPHA * (margin - _apc_margin_ewma); // smooth
float err = _apc_margin_ewma - APC_TARGET_MARGIN_DB; // +ve = more margin than needed
if (fabsf(err) <= APC_DEADBAND_DB) return; // inside deadband → hold
int step = (int)lroundf(err * 0.5f); // proportional (~half the error)
if (step > APC_MAX_STEP_DB) step = APC_MAX_STEP_DB;
if (step < -APC_MAX_STEP_DB) step = -APC_MAX_STEP_DB;
if (step == 0) return;
int8_t target = _apc_cur_dbm - step; // surplus margin → lower power
if (target < APC_MIN_DBM) target = APC_MIN_DBM;
if (target > _prefs.tx_power_dbm) target = _prefs.tx_power_dbm;
if (target == _apc_cur_dbm) return;
int8_t delta = target - _apc_cur_dbm;
_apc_cur_dbm = target;
radio_driver.setTxPower(_apc_cur_dbm);
_apc_margin_ewma += (float)delta; // anticipate the margin shift (≈1 dB TX → 1 dB SNR)
}
// A send got no confirmation (missed ACK, or a flood no repeater echoed). Ramp up.
void MyMesh::apcOnFailure() {
if (_apc_cur_dbm >= _prefs.tx_power_dbm) return; // already at the ceiling
int8_t target;
if (++_apc_fail_count >= APC_FAIL_CEIL_HITS) {
target = _prefs.tx_power_dbm; // repeated losses → restore full reliability
} else {
target = _apc_cur_dbm + APC_FAIL_STEP_DB;
if (target > _prefs.tx_power_dbm) target = _prefs.tx_power_dbm;
}
_apc_cur_dbm = target;
_apc_margin_ewma = APC_TARGET_MARGIN_DB; // reset so the next sample doesn't trim straight back
radio_driver.setTxPower(_apc_cur_dbm);
}
// Remember a channel/flood packet we just originated so a heard rebroadcast can be
// matched as positive feedback (and its absence as a failure). The hash excludes
// the mutable path, so it matches across repeater rebroadcasts.
void MyMesh::apcTrackFloodSend(const mesh::Packet* pkt) {
pkt->calculatePacketHash(_apc_flood_hash);
_apc_flood_len = pkt->payload_len;
_apc_flood_deadline = futureMillis(APC_FLOOD_ECHO_WINDOW_MS);
_apc_flood_pending = true;
}
void MyMesh::onSendTimeout() {
if (_prefs.tx_apc) apcOnFailure();
}
void MyMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) {
// onAckRecv also fires for ACKs we merely route or overhear (see Mesh.cpp), whose
// SNR belongs to an unrelated link — only feed APC for ACKs to our own sends.
// Capture the match before the base handler's processAck() clears the entry.
bool ours = _prefs.tx_apc && isAckPending(ack_crc);
BaseChatMesh::onAckRecv(packet, ack_crc);
if (ours) apcSampleSnr(radio_driver.getLastSNR());
}
MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui)
: BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables),
@@ -1201,8 +1308,9 @@ void MyMesh::begin(bool has_display) {
_store->loadChannels(this);
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
radio_driver.setTxPower(_prefs.tx_power_dbm);
applyApc(); // sets TX power to the ceiling and arms APC if enabled
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
radio_driver.setPowerSaving(_prefs.rx_powersave); // hardware duty-cycle RX (battery saver)
MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled");
}
@@ -2536,6 +2644,13 @@ void MyMesh::checkSerialInterface() {
void MyMesh::loop() {
BaseChatMesh::loop();
// APC: a tracked channel/flood send that no repeater echoed within the window is
// treated as a lost confirmation → ramp power up (lets channel sends recover).
if (_apc_flood_pending && millisHasNowPassed(_apc_flood_deadline)) {
_apc_flood_pending = false;
if (_prefs.tx_apc) apcOnFailure();
}
if (_cli_rescue) {
checkCLIRescueCmd();
} else {