Harden radio recovery, OTA reconnects, and companion settings

Reject radio changes when receive mode cannot resume and restore the previous physical profile and power policy. Preserve selected folder OTA captures across disconnects and recoverable host I/O failures, while keeping corruption failures distinct. Validate OTA staging input before arithmetic or buffer writes and revoke published data before edits.

Commit companion channels through verified file replacement on ESP32, RP2040, and STM32, and quarantine incomplete startup reads. Recheck the last management connection during delayed wireless changes and prevent conflicting Bluetooth shutdowns. Detect complete OTA implementation sources rather than the shared inflater when configuring release builds.

Add fault-injection regressions and CI coverage for these paths, and document folder capture reconnect behavior.

Validation: 1,510 native tests; 55 host integration checks; build profile regressions; ESP32, nRF52, STM32, and RP2040 firmware builds.
This commit is contained in:
mikecarper committed 2026-09-15 10:02:23 -07:00
1 parent 6f99250388
commit 7c443e9f71
27 files changed
+852 -137

No files matched your search

+3 -3
View File
@@ -1,6 +1,6 @@
#pragma once
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include <stddef.h>
#include <stdint.h>
@@ -9,7 +9,7 @@
namespace mesh {
/**
* Power-loss-safe file replacement for the nRF52 LittleFS backend.
* Power-loss-safe file replacement for the Adafruit LittleFS backends.
*
* Data is written to a sibling .tmp file. commit() flushes and closes that
* file, reads it back while checking its size and CRC32, and only then uses
@@ -178,4 +178,4 @@ bool AtomicFileWriter::commit(bool content_valid) {
#endif // ATOMIC_FILE_WRITER_IMPLEMENTATION
#endif // NRF52_PLATFORM
#endif // NRF52_PLATFORM || STM32_PLATFORM
+5 -1
View File
@@ -3,7 +3,7 @@
// SPIFFS cannot replace an existing name in one rename. Preserve the previous
// file as .bak until the verified replacement has its final name. Recovery of
// the rename gap happens before loading contacts on the next boot.
#if defined(ESP32_PLATFORM)
#if defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
#include "IdentityStore.h"
#include "PersistentStoreFormat.h"
#include <stdio.h>
@@ -31,7 +31,11 @@ public:
snprintf(_backup, sizeof(_backup), "%s.bak", target);
if (!recover(fs, target)) return;
if (fs->exists(_temp) && !fs->remove(_temp)) return;
#if defined(RP2040_PLATFORM)
_file = fs->open(_temp, "w");
#else
_file = fs->open(_temp, "w", true);
#endif
_ok = static_cast<bool>(_file);
}
~ContactFileTransaction() {
+17 -8
View File
@@ -57,7 +57,7 @@ class Control {
Backend* backend_ = nullptr;
std::atomic<uint8_t> blocked_{0};
uint8_t scope_ = 0, target_ = 0, saved_ = 0;
bool pending_ = false, started_ = false, force_ = false, retained_requester_ = false;
bool pending_ = false, started_ = false, force_ = false, independent_requester_ = false;
bool saved_valid_ = false, master_off_ = false;
uint32_t due_ = 0;
const char* error_ = nullptr;
@@ -104,10 +104,16 @@ public:
return true;
}
const uint8_t scope = command.scope & available;
const bool retained = (requester & ~scope) != 0;
const uint8_t target = !on ? 0 : command.scope == All && command.action != Action::OnAll
? (saved_valid_ ? saved_ : current) & available : scope;
// Restoring a saved subset may also switch off services enabled since a
// failed restore. Protect the actual removals, not just commands named off.
const uint8_t disabling = scope & ~target;
const bool retained = (requester & ~disabling) != 0;
const bool force = command.action == Action::ForceOff;
if (!on && (current & scope) && !force && !retained && !(backend_->clients() & ~scope)) {
snprintf(reply, size, "Error: no remaining management connection; use off force or USB/Ethernet");
if ((current & disabling) && !force && !retained && !(backend_->clients() & ~disabling)) {
snprintf(reply, size, "Error: no remaining management connection; use %s or USB/Ethernet",
on ? "on all" : "off force");
return true;
}
if (command.scope == All && !on && !saved_valid_) {
@@ -115,10 +121,12 @@ public:
saved_valid_ = true;
}
scope_ = scope;
target_ = !on ? 0 : command.scope == All && command.action != Action::OnAll
? (saved_valid_ ? saved_ : current) & available : scope;
target_ = target;
force_ = force;
retained_requester_ = retained;
// An actual USB/UART command proves a host session even on adapters with
// no DTR reporting. Wireless requesters can disconnect during reply drain;
// only their live management sessions may authorize the delayed shutdown.
independent_requester_ = (requester & Independent) != 0;
pending_ = true;
started_ = false;
error_ = nullptr;
@@ -133,7 +141,8 @@ public:
void service(uint32_t now) {
if (!pending_ || !backend_ || int32_t(now - due_) < 0) return;
if (!started_) {
if (!target_ && (enabled() & scope_) && !force_ && !retained_requester_ && !(backend_->clients() & ~scope_)) {
const uint8_t disabling = scope_ & ~target_;
if ((enabled() & disabling) && !force_ && !independent_requester_ && !(backend_->clients() & ~disabling)) {
pending_ = false;
if (master_off_) { master_off_ = false; saved_valid_ = false; }
error_ = " (cancelled: connection lost)";
+12 -12
View File
@@ -37,19 +37,22 @@ bool networkReady() {
return static_cast<uint32_t>(WiFi.softAPIP()) != 0;
}
void detachTcpFolder() {
void detachTcpFolder(bool disconnected) {
if (!tcp_folder_attached) return;
OtaContext* context = ota_context_if_active();
if (context && context->folderLink() == OtaContext::FOLDER_LINK_TCP) {
context->detach_folder();
context->clear_folder_dest();
if (disconnected) context->disconnect_folder();
else {
context->detach_folder();
context->clear_folder_dest();
}
context->manager.announce();
}
tcp_folder_attached = false;
}
void stopClient() {
detachTcpFolder();
void stopClient(bool disconnected = false) {
detachTcpFolder(disconnected);
if (seeder_client) seeder_client.stop();
}
@@ -66,7 +69,9 @@ void WiFiOtaSeeder::loop() {
static_cast<unsigned>(OTA_SEEDER_TCP_PORT));
break;
case ListenerAction::Stop:
stop();
stopClient(true);
seeder_server.end();
listener_active = false;
return;
case ListenerAction::Keep:
break;
@@ -87,7 +92,7 @@ void WiFiOtaSeeder::loop() {
}
if (seeder_client && seeder_client.connected()) return;
stopClient();
stopClient(true);
WiFiClient incoming = seeder_server.available();
if (!incoming) return;
@@ -123,11 +128,6 @@ void WiFiOtaSeeder::loop() {
snprintf(link_info, sizeof(link_info), "tcp %s",
seeder_client.remoteIP().toString().c_str());
context.set_folder_dest(&folder_store, link_info);
if (context.manager.fetchState() == OtaManager::PAUSED) {
// This continues the active host-selected MID; it is not a boot-time
// automatic adoption governed by application autofetch policy.
context.manager.resumeStaged(context.manager.fetchManifestId());
}
context.manager.announce();
mesh::usbLoggingPort().printf(
"OTA seeder client connected (%s)\n", link_info);
+1
View File
@@ -38,6 +38,7 @@ public:
void clear() override { _total = 0; }
bool finalize() override;
bool reopen() override; // OP_STAT: adopt an existing file for resume
bool canReconnect() const override { return true; }
// A host-backed store is fully random-access, so it needs no pinned-meta RAM page and no layout planning.
bool set_meta_size(uint32_t) override { return true; }
+23 -16
View File
@@ -9,6 +9,7 @@
#include "OtaBlInfo.h" // installed bootloader application/update capability views
#endif
#include "Utils.h"
#include "helpers/CLICommandUtils.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
@@ -17,13 +18,6 @@
namespace mesh {
namespace ota {
static uint32_t parse_u32(const char* s) {
uint32_t n = 0;
while (*s == ' ') s++;
while (*s >= '0' && *s <= '9') n = n * 10 + (uint32_t)(*s++ - '0');
return n;
}
static bool parse_page(const char* s, uint16_t& page) {
while (*s == ' ') s++;
if (*s == 0) { page = 1; return true; }
@@ -1066,23 +1060,36 @@ static bool handle_dev(const char* d, char* reply, OtaContext& c) {
strcpy(reply, "ERR ota dev staging/apply is disabled on this seeder-only build");
#else
if (strncmp(d, "stage ", 6) == 0) {
uint32_t sz = parse_u32(d + 6);
if (sz == 0 || sz > OTA_SERVE_BUF_SIZE) { sprintf(reply, "ERR size 1..%u", OTA_SERVE_BUF_SIZE); }
uint32_t sz;
if (!mesh::cli::parseUnsignedIntegerStrict(d + 6, sz) || sz == 0 || sz > OTA_SERVE_BUF_SIZE) {
sprintf(reply, "ERR size 1..%u", OTA_SERVE_BUF_SIZE);
}
else if (!c.ensureServeBuffer()) { strcpy(reply, "ERR stage OOM"); }
else { c.manager.clear_primary(); c.serving = false;
memset(c.serve_buf, 0xFF, sz); c.serve_expected = sz;
sprintf(reply, "OK stage %u bytes", (unsigned)sz); }
} else if (strncmp(d, "recv ", 5) == 0) {
const char* p = d + 5; uint32_t off = parse_u32(p);
const char* hex = strchr(p, ' ');
if (!hex) { strcpy(reply, "ERR usage: ota dev recv <off> <hex>"); return true; }
hex++;
int blen = (int)strlen(hex) / 2;
uint8_t tmp[80];
char arguments[sizeof(tmp) * 2 + 16];
const char* fields[2];
size_t count;
uint32_t off;
if (!mesh::cli::splitWhitespaceFieldsStrict(d + 5, arguments, sizeof(arguments), fields, 2, count)
|| count != 2 || !mesh::cli::parseUnsignedIntegerStrict(fields[0], off)) {
strcpy(reply, "ERR usage: ota dev recv <off> <hex>"); return true;
}
const char* hex = fields[1];
int blen = (int)strlen(hex) / 2;
if (blen <= 0 || blen > (int)sizeof(tmp) || !mesh::Utils::fromHex(tmp, blen, hex)) strcpy(reply, "ERR hex");
else if (!c.serve_buf || off + blen > c.serve_expected) strcpy(reply, "ERR off>size (stage first)");
else { memcpy(c.serve_buf + off, tmp, blen); sprintf(reply, "OK %d@%u", blen, (unsigned)off); }
else if (!c.serve_buf || off > c.serve_expected || (uint32_t)blen > c.serve_expected - off) {
strcpy(reply, "ERR off>size (stage first)");
} else {
// A published view points into this buffer. Revoke it before changing
// bytes, including queued replies that captured its old manifest ID.
if (c.serving) { c.manager.clear_primary(); c.serving = false; }
memcpy(c.serve_buf + off, tmp, blen); sprintf(reply, "OK %d@%u", blen, (unsigned)off);
}
} else if (strncmp(d, "serve self", 10) == 0) { // host our own running firmware, served from flash
if (ota_serve_self(c, 0)) {
+1 -1
View File
@@ -111,7 +111,7 @@ uint8_t ota_hop_limit() {
void ota_release_context_if_idle(bool temporary_radio_active) {
if (!active_context) return;
OtaContext& c = *active_context;
if (c.folder_active || c.folder_dest || c.apply_pending) return;
if (c.folder_active || c.folder_dest || c.apply_pending || c.folderCaptureWaiting()) return;
#if defined(OTA_HEAP_CONTEXT)
// Self-serving ends with the temporary radio window. It must not keep the
// heap workspace forever after the first announcement. Manual staging is
+34 -1
View File
@@ -177,10 +177,18 @@ struct OtaContext {
FolderMotaStore* folder_dest = nullptr; // non-null == a folder destination is currently connected
char folder_dest_info[24] = {0}; // human id of the link (e.g. "tcp 192.168.4.5", "serial")
bool fetch_to_folder = false; // COMPLETE belongs to a capture destination, never install it
FolderMotaStore* disconnected_folder_dest = nullptr;
uint8_t disconnected_folder_link = 0;
bool folderCaptureWaiting() const {
return disconnected_folder_dest && fetch_to_folder
&& manager.fetchState() == OtaManager::PAUSED;
}
void set_folder_dest(FolderMotaStore* fs, const char* info) {
folder_dest = fs;
strncpy(folder_dest_info, info ? info : "?", sizeof(folder_dest_info) - 1);
folder_dest_info[sizeof(folder_dest_info) - 1] = 0;
if (folderCaptureWaiting() && fs == disconnected_folder_dest
&& manager.resumeFetchAfterReconnect()) disconnected_folder_dest = nullptr;
}
void clear_folder_dest() { folder_dest = nullptr; folder_dest_info[0] = 0; }
@@ -412,6 +420,11 @@ struct OtaContext {
msg[cap - 1] = 0;
return false;
}
if (folderCaptureWaiting() && link != disconnected_folder_link) {
snprintf(msg, cap, "ERR paused capture belongs to %s; cancel it first",
folderLinkName(static_cast<FolderLink>(disconnected_folder_link)));
return false;
}
if (folder_active && _folder_link != link) {
snprintf(msg, cap, "ERR folder already attached via %s",
folderLinkName(_folder_link));
@@ -463,7 +476,14 @@ struct OtaContext {
return attach_folder_source(&src, FOLDER_LINK_SERIAL, "serial", msg, cap);
}
#endif
void detach_folder() {
void detach_folder(bool preserve_capture = false) {
disconnected_folder_dest = nullptr;
if (!preserve_capture && fetch_to_folder) {
manager.reset_session();
manager.set_fetch_store(&fetch_store);
fetch_to_folder = false;
}
clear_folder_dest();
if (_folder_source) manager.remove_source(_folder_source);
folder_active = false;
_folder_link = FOLDER_LINK_NONE;
@@ -472,6 +492,19 @@ struct OtaContext {
release_when_idle = true;
#endif
}
// Network loss differs from an operator detach: keep the chosen capture and
// its store until reconnect or an explicit reset/cancel, even outside TempRadio.
void disconnect_folder() {
FolderMotaStore* destination = folder_dest;
const uint8_t link = _folder_link;
const bool paused = destination && fetch_to_folder && manager.pauseFetchForDisconnect();
detach_folder(true);
clear_folder_dest();
if (paused) {
disconnected_folder_dest = destination;
disconnected_folder_link = link;
}
}
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
// Initialize and attach the persistent source lazily. This lets Mesh::begin finish quickly when no card
+62 -12
View File
@@ -82,6 +82,7 @@ uint8_t* OtaManager::ensureScratch() {
void OtaManager::begin(uint32_t my_target_id, OtaSend send, void* ctx) {
_target = my_target_id; _send = send; _ctx = ctx;
_fstate = IDLE; _have = 0; _fbc = 0;
_paused_from = IDLE;
_fetch_error = FETCH_ERROR_NONE;
_archive_fetch = false; _validate = false;
clearFetchIntent();
@@ -1257,8 +1258,11 @@ void OtaManager::clearFetchIntent() {
}
void OtaManager::failFetch(FetchError error) {
if (error == FETCH_ERROR_STORAGE && _fetch && _fetch->canReconnect()
&& pauseFetchForDisconnect()) return;
_fetch_error = error;
_fstate = FAILED;
_paused_from = IDLE;
clearReassembly();
freeLeaves();
_validate = false;
@@ -1269,6 +1273,7 @@ void OtaManager::failFetch(FetchError error) {
void OtaManager::completeFetch() {
_fetch_error = FETCH_ERROR_NONE;
_fstate = COMPLETE;
_paused_from = IDLE;
_validate = false;
_archive_fetch = false;
clearFetchIntent();
@@ -1350,6 +1355,40 @@ bool OtaManager::resumeStagedExplicit(const uint8_t* want_mid, uint32_t expected
return adopted;
}
bool OtaManager::pauseFetchForDisconnect() {
if (!fetchActive()) return false;
if (_fstate != PAUSED) _paused_from = _fstate;
_fetch_error = FETCH_ERROR_STORAGE;
_fstate = PAUSED;
clearReassembly();
return true;
}
bool OtaManager::resumeFetchAfterReconnect() {
if (_fstate != PAUSED || !_fetch) return false;
if (_paused_from == WANT_MANIFEST || _paused_from == WANT_LEAVES) {
// begin/header/manifest/trailer may only have partly reached the host.
// Re-request the manifest and run the full initialization transaction.
// Leaf-diff also restarts initialization: the reconnected host may have
// replaced its seed file, so old metadata/leaf markers cannot be trusted.
freeLeaves();
_mf_total = 0; _mf_mask = 0; _mf_len = 0;
_mf_retries = 0; _loop_last_mfmask = 0;
_fstate = WANT_MANIFEST;
GetManifestMsg gm; memcpy(gm.manifest_id, _fid, 4); gm.want_mask = 0xFFFF;
uint8_t wire[16];
emit(wire, encode_get_manifest(wire, sizeof(wire), gm), false);
} else {
// Reopening is bound to the original MID/target and verifies payload bytes;
// a replacement host file must not silently become the selected capture.
if (!resumeStaged(_fid)) return false;
}
_paused_from = IDLE;
_fetch_error = FETCH_ERROR_NONE;
noteFetchActivity();
return true;
}
void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
ManifestMsg mm;
if (!decode_manifest(m, n, mm) || !_fetch) return;
@@ -1517,17 +1556,23 @@ void OtaManager::diffStep() {
uint8_t blk[OTA_MAX_BLOCK];
for (uint32_t k = 0; k < OTA_DIFF_BATCH && _diff_idx < _fbc; k++, _diff_idx++) {
uint32_t blen = blockLen(_diff_idx);
if (!_fetch->read(_fpoff + _diff_idx * _fbs, blk, blen)) continue; // read fail -> leave missing
if (!_fetch->read(_fpoff + _diff_idx * _fbs, blk, blen)) {
if (_fetch->canReconnect()) { pauseFetchForDisconnect(); return; }
continue; // unreadable local seed -> leave missing
}
uint8_t leaf[4]; merkle_leaf(leaf, blk, blen);
if (memcmp(leaf, _leaves_buf + (size_t)_diff_idx * 4, 4) == 0 && // seed block == target block
_fetch->write(_floff + _diff_idx * 4, _leaves_buf + (size_t)_diff_idx * 4, 4))
_have++; // mark present (payload already seeded)
if (memcmp(leaf, _leaves_buf + (size_t)_diff_idx * 4, 4) == 0) { // seed block == target block
if (_fetch->write(_floff + _diff_idx * 4, _leaves_buf + (size_t)_diff_idx * 4, 4))
_have++; // mark present (payload already seeded)
else if (_fetch->canReconnect()) { pauseFetchForDisconnect(); return; }
}
}
if (_diff_idx < _fbc) return; // more to diff on the next tick
OTA_DBG("OTA: leaf-diff %u/%u already valid; fetching the rest\n", (unsigned)_have, (unsigned)_fbc);
freeLeaves(); // clears _diffing + frees the buffer
if (_have >= _fbc) { // seed covered the whole image
if (!storedLeavesRootMatches()) failFetch(FETCH_ERROR_INTEGRITY);
FetchError error;
if (!storedLeavesRootMatches(error)) failFetch(error);
else if (!_fetch->finalize()) failFetch(FETCH_ERROR_STORAGE);
else completeFetch();
return;
@@ -1606,13 +1651,17 @@ bool OtaManager::blockPresent(uint32_t i) const {
return !(leaf[0]==0xFF && leaf[1]==0xFF && leaf[2]==0xFF && leaf[3]==0xFF);
}
bool OtaManager::storedLeavesRootMatches() const {
bool OtaManager::storedLeavesRootMatches(FetchError& error) const {
error = FETCH_ERROR_INTEGRITY;
if (!_fetch || _fbc == 0) return false;
MerkleAccumulator accumulator;
for (uint32_t i = 0; i < _fbc; ++i) {
uint8_t leaf[4];
if (!_fetch->read(_floff + i * 4, leaf, sizeof(leaf))
|| (leaf[0] == 0xFF && leaf[1] == 0xFF
if (!_fetch->read(_floff + i * 4, leaf, sizeof(leaf))) {
error = FETCH_ERROR_STORAGE;
return false;
}
if ((leaf[0] == 0xFF && leaf[1] == 0xFF
&& leaf[2] == 0xFF && leaf[3] == 0xFF)
|| !accumulator.add(leaf)) {
return false;
@@ -1834,8 +1883,8 @@ bool OtaManager::handleProof(const uint8_t* m, uint16_t n) {
uint8_t leaf[4]; merkle_leaf(leaf, slot.buf, blen);
if (!_fetch->write(_fpoff + block * _fbs, slot.buf, blen) ||
!_fetch->write(_floff + block * 4, leaf, 4)) {
_fetch_error = FETCH_ERROR_STORAGE;
_fstate = PAUSED; clearReassembly(); return true;
pauseFetchForDisconnect();
return true;
}
_have++;
OTA_DBG("OTA: block %u OK have=%u/%u\n", (unsigned)block, (unsigned)_have, (unsigned)_fbc);
@@ -1850,9 +1899,10 @@ bool OtaManager::handleProof(const uint8_t* m, uint16_t n) {
return true;
}
// Every leaf must be readable and collectively match the manifest root.
// A scratch allocation/read failure is an integrity failure, never success.
// Missing/corrupt leaves are integrity failures; a lost host read is resumable.
clearReassembly();
if (!storedLeavesRootMatches()) failFetch(FETCH_ERROR_INTEGRITY);
FetchError error;
if (!storedLeavesRootMatches(error)) failFetch(error);
else if (!_fetch->finalize()) failFetch(FETCH_ERROR_STORAGE);
else completeFetch();
OTA_DBG("OTA: transfer %s\n", _fstate == COMPLETE ? "COMPLETE" : "FAILED(integrity/storage)");
+8 -1
View File
@@ -358,6 +358,11 @@ public:
// this never applies boot-time autofetch/version policy.
bool resumeStagedExplicit(const uint8_t* want_mid, uint32_t expected_target = 0);
// Hold the current selection across loss of an external destination. Metadata
// initialization restarts safely; committed transfers reverify their store.
bool pauseFetchForDisconnect();
bool resumeFetchAfterReconnect();
// Manual cross-target override (decision: deliberate role switch, e.g. companion -> repeater on the
// same hardware). Normally a node only auto-fetches its OWN target_id; `want(T)` makes it accept an
// ADV for target T instead (T=0 restores auto). The user takes responsibility for HW compatibility;
@@ -484,6 +489,7 @@ public:
// Drop the current fetch session back to IDLE so a fresh `ota pull` / advert starts a new one.
void reset_session() {
_fstate = IDLE; _have = 0; _fbc = 0; _ftotal = 0; _fflags = 0;
_paused_from = IDLE;
_req_count = 0; _mf_retries = 0;
_fetch_error = FETCH_ERROR_NONE;
clearFetchIntent();
@@ -607,7 +613,7 @@ private:
}
void setDigest(uint8_t out[4]) const; // sha2-256:4 over our served mids
bool blockPresent(uint32_t i) const;
bool storedLeavesRootMatches() const;
bool storedLeavesRootMatches(FetchError& error) const;
void beginStagedVerification();
void verifyStagedStep();
bool requestSlot(uint8_t slot); // request DATA holes or the proof for one slot
@@ -685,6 +691,7 @@ private:
// fetch
OtaStore* _fetch = nullptr;
FetchState _fstate = IDLE;
FetchState _paused_from = IDLE;
FetchError _fetch_error = FETCH_ERROR_NONE;
uint8_t _fid[4] = {0};
uint8_t _froot[4] = {0};
+4
View File
@@ -61,6 +61,10 @@ public:
// OtaManager then reads + parses the stored manifest to recompute geometry and resume the fetch.
virtual bool reopen() { return false; }
// External host stores can disappear temporarily while retaining their file.
// Preserve the selected fetch on an I/O failure until that link reconnects.
virtual bool canReconnect() const { return false; }
// Optional: declare the container's logical layout once the manifest is parsed, BEFORE begin(), so a
// store backed by a single spare A/B partition (ESP32) can choose placement and reject an unfittable
// fetch up front. A FULL image's payload IS the final firmware (no decode), so it can stream straight
+32 -5
View File
@@ -185,6 +185,13 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
const uint8_t previous_sf = _cur_sf;
const uint8_t previous_cr = _cur_cr;
const uint16_t previous_preamble = _physical_preamble;
const uint8_t previous_profile = _active_profile;
const uint32_t previous_generation = _profile_generation;
const bool previous_refresh = _profile_refresh_required;
const bool previous_rxps = _rx_ps_enabled;
const bool previous_saved_rxps = _profile_saved_rxps;
const bool previous_fallback = _rx_ps_continuous_fallback;
const uint32_t previous_rx_us = _rx_ps_rx_us, previous_sleep_us = _rx_ps_sleep_us;
mesh::RadioProfileParams requested = _profiles.primary;
requested.freq = freq; requested.bw = bw; requested.sf = sf; requested.cr = cr;
const auto previous_primary = _profiles.primary;
@@ -194,10 +201,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
bool success = applyParams(freq, bw, sf, cr);
if (success) {
cacheParams(freq, bw, sf, cr);
_profiles.primary = previous_primary;
_profiles.setPrimary(requested, _profiles.primary_temporary);
_active_profile = 0;
_profile_generation = _profiles.generation[0];
if (rx_ps_timings != NULL) {
if (_profile_rxps_suspended) _profile_saved_rxps = true;
else _rx_ps_enabled = true;
@@ -206,20 +210,43 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
_rx_ps_continuous_fallback = rxPowerSavingUsesContinuousFallback(
_rx_ps_rx_us, _rx_ps_sleep_us);
}
} else {
endReconfigure(resume_rx);
success = !resume_rx || isInRecvMode();
}
if (success) {
_profiles.primary = previous_primary;
_profiles.setPrimary(requested, _profiles.primary_temporary);
_profile_generation = _profiles.generation[0];
_profile_refresh_required = false;
} else {
// RX resume is part of a primary command just as it is for scan hops.
// Restore the active physical profile and power policy before recovery;
// neither a saved command nor a temporary lease may commit a deaf radio.
_profiles.primary = previous_primary;
cacheParams(previous_freq, previous_bw, previous_sf, previous_cr);
_params_valid = had_previous_params;
_active_profile = previous_profile;
_profile_generation = previous_generation;
_profile_refresh_required = previous_refresh;
_physical_preamble = previous_preamble;
_rx_ps_enabled = previous_rxps;
_profile_saved_rxps = previous_saved_rxps;
_rx_ps_continuous_fallback = previous_fallback;
_rx_ps_rx_us = previous_rx_us;
_rx_ps_sleep_us = previous_sleep_us;
bool restored = had_previous_params
&& _radio->standby() == RADIOLIB_ERR_NONE
&& applyParams(previous_freq, previous_bw, previous_sf, previous_cr);
if (!restored) restored = restoreAfterDeepInit();
if (restored) endReconfigure(resume_rx);
if (!restored || (resume_rx && !isInRecvMode())) _profile_refresh_required = true;
if (!restored) {
MESH_DEBUG_PRINTLN("RadioLibWrapper: failed to restore radio parameters after apply failure");
}
}
endReconfigure(resume_rx);
_profile_visit_us = micros();
return success ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}