Apply busy radio settings and recover service starts automatically

Save valid busy RX, fast-switch and Companion tuple changes once, then
apply the latest accepted intent at a safe radio gap. Preserve checked-save
rollback, runtime RXEN intent, TempRadio ownership and exact remote reply
delivery. Repair failed preamble compensation without hiding uncertain saves.

Retry WebConfig, MQTT and NimBLE startup failures automatically. Preserve
explicit off choices, OTA ownership and the latest WiFi credentials through
cooperative shutdown. Add regression coverage and update command guides.

Validation: focused host transaction, rollback, ownership and lifecycle suites;
Full RAK4631, Heltec V4 R8 TFT and RC32 packages; representative room, sensor,
LR1110, LR2021, SX1276, STM32WL and ESP-NOW builds. Linked RAK crypto and OTA
workspace checks pass; its complete OTA image uses 712644/712704 bytes.
This commit is contained in:
mikecarper committed 2026-10-25 15:20:55 -07:00
1 parent fb73e3afac
commit 73c5f572eb
89 files changed
+2978 -816

No files matched your search

+3 -1
View File
@@ -73,7 +73,9 @@ public:
uint8_t dirty_contacts_failures=0;
bool(*save_filter)(const ContactInfo&)=nullptr;
bool _radio_available=false, _iter_started=false;
bool command_radio_apply_pending=false, saved_radio_apply_pending=false;
bool saved_radio_apply_pending=false, tx_power_apply_pending=false;
int8_t rf_rx_disable_pending=-1;
struct {bool hasPendingTuning() const{return false;}} _radio_profiles;
uint32_t _scheduled_reboot_at=0, radio_apply_retry_at=0;
uint32_t emergency_client_repeat_send_at=0;
void* sign_data=nullptr;
+27 -2
View File
@@ -10,7 +10,11 @@
// This fixture isolates the actual CommonCLI setting branches and callbacks.
namespace mesh {
enum class RadioParamApplyResult : uint8_t { APPLIED, BUSY, FAILED };
struct Radio { bool isCarrierWaveActive() const { return false; } };
struct Radio {
bool isCarrierWaveActive() const { return false; }
const RadioProfiles* profiles() const { return nullptr; }
};
inline bool morseTimingActive(const Radio*) { return false; }
struct RadioProfileCLI {
static bool parseSuffix(const char* input, unsigned fields, char* legacy,
size_t size, uint16_t& preamble) {
@@ -52,7 +56,7 @@ struct Prefs {
uint8_t path_hash_mode=0, multi_acks=0, rx_ps_level=0, rx_ps_preamble=0;
int8_t tx_power_dbm=10;
uint32_t rx_ps_rx_us=1000, rx_ps_sleep_us=1000;
bool cad_enabled=false, rx_boosted_gain=false;
bool cad_enabled=false, rx_boosted_gain=false, rx_powersaving_enabled=false;
uint8_t extra_sf[4]={};
uint8_t flood_max=16, flood_max_advert=16, flood_max_unscoped=16;
};
@@ -70,7 +74,20 @@ struct Callbacks {
bool isTxPowerApplied(int8_t value) const { return power == value; }
const mesh::Radio* getProfileRadio() const { return nullptr; }
bool setRxBoostedGain(bool value) { ++gain_calls; if (!accept) return false; gain=value; return true; }
bool supportsRxBoostedGain() const { return true; }
mesh::RadioParamApplyResult trySetRxBoostedGain(bool value) {
return setRxBoostedGain(value) ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}
mesh::RadioParamApplyResult trySetRxPowerSaving(bool, uint32_t, uint32_t) {
return mesh::RadioParamApplyResult::FAILED;
}
mesh::RadioParamApplyResult trySetRxPowerSavingRfRxDisabled(bool) {
return mesh::RadioParamApplyResult::FAILED;
}
bool configSideDetectors(const uint8_t*,uint8_t,float) { return accept; }
mesh::RadioParamApplyResult tryConfigSideDetectors(const uint8_t* sfs,uint8_t count,float bw) {
return configSideDetectors(sfs,count,bw) ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}
};
struct Board { unsigned n_cad_busy=0; };
bool isValidLoRaBandwidth(float bw) { return bw==125 || bw==62.5f; }
@@ -89,10 +106,17 @@ public:
Board* _board=&board;
bool _tx_power_pending=false;
uint32_t _tx_power_retry_at=0;
enum RxSetting : uint8_t { RxGain=1, RxPowerSaving=2, RxSideDetectors=4, RxRfRx=8,
RxPendingMask=15, RxRfRxDisabled=128 };
uint8_t _rx_settings_pending=0;
uint32_t _rx_settings_retry_at=0;
void savePrefs() { callbacks.savePrefs(); }
bool trySavePrefs() { savePrefs(); return true; }
void applyAndSaveTxPower(int8_t power, char* reply);
void servicePendingTxPower();
mesh::RadioParamApplyResult applyRxSetting(uint8_t);
bool saveRxSetting(uint8_t, mesh::RadioParamApplyResult, char*);
void restoreRxSetting(uint8_t, mesh::RadioParamApplyResult, uint8_t, uint32_t);
bool savePrimaryRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, uint16_t) {
prefs.freq=freq; prefs.bw=bw; prefs.sf=sf; prefs.cr=cr;
prefs.tx_power_dbm=mesh::clampLoRaTxPower(prefs.tx_power_dbm,freq);
@@ -119,6 +143,7 @@ public:
};
@TX_METHODS@
@RX_METHODS@
struct Case { const char *key, *value; double expected; };
int main() {
+3 -1
View File
@@ -82,7 +82,8 @@ public:
uint32_t _tx_power_retry_at = 0;
bool _common_save_result_known = false;
bool _common_save_succeeded = false;
struct Profiles { void loop() {} } _radio_profiles;
struct Profiles { void loop() {} void servicePendingTuning() {} } _radio_profiles;
Profiles& radioProfiles() { return _radio_profiles; }
struct MorseReply { void complete(const void*) {} } _morse_reply;
MorseReply& morseReply() { return _morse_reply; }
CommonCLI() { callbacks.owner = this; }
@@ -91,6 +92,7 @@ public:
void loop();
void applyAndSaveTxPower(int8_t, char*);
void servicePendingTxPower();
void servicePendingRxSettings() {}
bool trySavePrefs(PrefsSaveRouting::Scope scope = PrefsSaveRouting::Scope::Common);
void command(const char* text, char* reply) {
if (!strncmp(text, "set ", 4)) {
+15
View File
@@ -7,6 +7,7 @@
#include <vector>
#include <helpers/CompanionRadioDiagnostics.h>
#include <helpers/radiolib/RXPowerSaving.h>
namespace mesh { enum class RadioParamApplyResult : uint8_t { APPLIED, BUSY, FAILED }; }
constexpr int RADIOLIB_NC=-1;
constexpr int RADIOLIB_ERR_NONE=0;
@@ -55,6 +56,9 @@ public:
bool isInRecvMode() const;
virtual bool supportsRxPowerSavingRfRxDisable() const {return false;}
virtual bool setRxPowerSavingRfRxDisabled(bool) {return false;}
virtual mesh::RadioParamApplyResult trySetRxPowerSavingRfRxDisabled(bool) {
return mesh::RadioParamApplyResult::FAILED;
}
virtual bool isRxPowerSavingRfRxDisabled() const {return false;}
uint32_t getRxPsWatchdogSoftCount() const {return n_wd_soft;}
uint32_t getRxPsWatchdogHardCount() const {return n_wd_hard;}
@@ -162,6 +166,17 @@ static void radio2_suspended_rxps() {
#endif
}
int main() {
{
Driver driver;
char reply[80] = "untouched";
const auto before = driver.physical.flag_writes;
assert(!mesh::companion::handleRadioDiagnosticsCommand<false>(driver, true,
"set radio.rxps.rfrx_disabled on", reply, sizeof(reply), []() {}));
assert(driver.physical.flag_writes == before && !strcmp(reply, "untouched"));
assert(mesh::companion::handleRadioDiagnosticsCommand<false>(driver, true,
"get rxps.wd", reply, sizeof(reply), []() {}));
assert(strncmp(reply, "> soft=", 7) == 0);
}
backend_guards();radio2_suspended_rxps();Harness h;char reply[160];
bounds(h,"get rxps.wd","> soft=11,hard=13");
#if defined(SX126X_RXEN) && SX126X_RXEN != -1
+6
View File
@@ -10,6 +10,7 @@
#include <helpers/CompanionHardwareCommandCompat.h>
#include <helpers/radiolib/RXPowerSaving.h>
namespace mesh {enum class RadioParamApplyResult {APPLIED,BUSY,FAILED};}
struct Prefs {
uint8_t rx_powersaving_enabled = 0, rx_ps_level = 8, rx_ps_preamble = 16, sf = 7;
uint32_t rx_ps_rx_us = 3000, rx_ps_sleep_us = 4000;
@@ -26,6 +27,9 @@ struct Driver {
unsigned calls = 0;
uint32_t rx = 3000, sleep = 4000;
std::deque<bool> results;
mesh::RadioParamApplyResult trySetRxPowerSaving(bool enable,uint32_t rx,uint32_t sleep) {
return setRxPowerSaving(enable,rx,sleep)?mesh::RadioParamApplyResult::APPLIED:mesh::RadioParamApplyResult::FAILED;
}
bool supportsRxPowerSaving() const { return supported; }
bool setRxPowerSaving(bool enable, uint32_t receive, uint32_t rest) {
++calls;
@@ -53,6 +57,7 @@ struct MyMesh {
Serial serial;
Serial* _serial = &serial;
bool _radio_available = true, storage_accepts = true, saved_radio_apply_pending = false;
bool _primary_radio_blocked=false;
unsigned saves = 0;
uint32_t radio_apply_retry_at = 0;
uint8_t radio_apply_failures = 0;
@@ -60,6 +65,7 @@ struct MyMesh {
char reply_buf[160] = {};
MyMesh() { radio_driver = Driver(); }
bool savePrefs() { ++saves; if (!storage_accepts) return false; durable = _prefs; return true; }
void queueSavedRadioApply();
bool applyAndSaveRxPowerSaving(const char*, char*);
bool handleLocalControlCommand(const char*, char*, size_t);
bool handleCommand(const char*, uint32_t, char*);
+3
View File
@@ -1,3 +1,4 @@
#include <helpers/TempRadioReplyBarrier.h>
namespace mesh { struct Packet { bool radio_reply=false; }; }
struct ContactInfo {
struct { uint8_t pub_key[32]={}; } id;
@@ -10,6 +11,8 @@ static uint32_t millis() { return 100; }
struct MyMesh {
mesh::MorseReplyHandoff _morse_reply;
bool _morse_reply_admission=false;
mesh::TempRadioReplyBarrier _primary_radio_reply;
bool _primary_radio_reply_admission=false;
TestRadio radio;
unsigned active=0, forwarded=0;
uint32_t handled_timestamp=0;
+1
View File
@@ -28,6 +28,7 @@ struct CommonCLI {
void loopBatteryForwarding(bool = false) {}
void loopManagement() { ++management_loops; }
void servicePendingTxPower() { ++tx_services; }
void servicePendingRxSettings() {}
void loop();
};
@LOOP@
+18
View File
@@ -75,6 +75,7 @@ struct MQTTBridge{
std::atomic<bool>_network_suspended{false};
bool _network_espnow_restore_pending=false;
bool _wifi_event_registered=false,_manage_wifi=true,_ntp_sync_pending=false;
bool _wifi_credentials_changed=false;
int _wifi_reconnect_backoff_attempt=0;
std::atomic<bool>_ntp_synced{true},_stop_requested{false},_stop_acked{false};
struct{void noteGotIp(){}}_ntp_reconnect_latch;
@@ -169,6 +170,23 @@ int main(int argc,char** argv){
race_ap=true;assert(!bridge.initializeWiFiInTask());
assert(sdk_mode==WIFI_AP_STA&&event_registers==0&&reconnect_writes==0&&station_begins==0);
race_ap=false;sdk_mode=WIFI_STA;assert(bridge.initializeWiFiInTask());assert(event_registers==1);
}else if(scenario=="changed_credentials"){
// A different saved tuple must replace an old, still-connected station.
bridge._wifi_credentials_changed=true;
assert(bridge.initializeWiFiInTask());
assert(station_disconnects==1&&station_begins==1&&!bridge._wifi_credentials_changed);
WiFi.state=WL_CONNECTED;
assert(bridge.initializeWiFiInTask());
assert(station_disconnects==1&&station_begins==1);
// A setup/OTA owner defers that reconnect without consuming the intent.
sdk_mode=WIFI_AP_STA;WiFi.state=WL_CONNECTED;bridge._wifi_credentials_changed=true;
assert(!bridge.initializeWiFiInTask()&&bridge._wifi_credentials_changed);
assert(!bridge.handleWiFiConnection(20000)&&bridge._wifi_credentials_changed);
assert(station_disconnects==1&&station_begins==1);
sdk_mode=WIFI_STA;
now_ms=20000;
bridge.handleWiFiConnection(20000);
assert(!bridge._wifi_credentials_changed&&station_disconnects==2&&station_begins==2);
}else if(scenario=="recovery"||scenario=="companion_recovery"){
bridge._manage_wifi=scenario!="companion_recovery";
for(int mode:{WIFI_AP,WIFI_AP_STA}){
+15 -1
View File
@@ -18,7 +18,9 @@ void beginStation(const char* ssid, const char* password) {
}}
@WEB_POLICY@
enum { WIFI_OFF, WIFI_STA, WIFI_PS_NONE, WIFI_PS_MAX_MODEM, WIFI_PS_MIN_MODEM };
struct { int getMode() { return WIFI_STA; } } WiFi;
struct { unsigned disconnects = 0; int getMode() { return WIFI_STA; }
void disconnect() { ++disconnects; } } WiFi;
uint32_t millis() { return 1000; }
using wifi_ps_type_t = int;
using wifi_mode_t = int;
using esp_err_t = int;
@@ -79,6 +81,9 @@ struct MQTTBridge {
MQTTPrefs* _obs;
MQTTNodeInfo _node_info;
bool _manage_wifi = true, _wifi_configured = false, _initialized = false;
bool _wifi_credentials_changed = false, _start_requested = false;
uint32_t _last_wifi_reconnect_attempt = 0;
uint8_t _wifi_reconnect_backoff_attempt = 0;
char _wifi_ssid[32] = {}, _wifi_password[65] = {};
uint8_t _wifi_power_save = 0;
std::atomic<bool> _stop_requested{false};
@@ -167,6 +172,15 @@ int main() {
// Saved changes affect a new boot/restart, never a live worker snapshot.
assert(WebConfigServer::saveStandaloneWiFi("changed", "new-password", 0));
assert_selected(portal, "portal", "password");
// The same stopped bridge keeps the old verified tuple until begin snapshots
// the latest settings, and retains changed intent through failed allocations.
assert(portal.prepareWiFiCredentials());
assert(portal._wifi_credentials_changed);
assert(portal.prepareWiFiCredentials() && portal._wifi_credentials_changed);
const auto old_disconnects = WiFi.disconnects;
portal.beginWiFiStation();
assert(!portal._wifi_credentials_changed && WiFi.disconnects == old_disconnects + 1);
assert_selected(portal, "changed", "new-password");
MQTTBridge reboot(obs); reboot.begin();
assert(reboot._wifi_power_save == 0); assert_selected(reboot, "changed", "new-password");
std::string raw(64, 'A');
@@ -101,6 +101,36 @@ static void authenticate(SerialBLEInterface& interface, NimBLEConnInfo& info) {
interface.checkRecvFrame(discarded);
}
static void test_advertising_restart_retries_and_disable_cancels() {
reset(); SerialBLEInterface interface;
assert(interface.begin("MeshCore-", "retry", 123456));
interface.enable();
NimBLEConnInfo info; authenticate(interface, info);
auto* server = NimBLEDevice::server.get();
server->connected = false;
server->callbacks->onDisconnect(server, info, 0);
uint8_t frame[MAX_FRAME_SIZE]; interface.checkRecvFrame(frame);
failure = "advertise";
const auto attempts = std::count(calls.begin(), calls.end(), "advertise");
test_millis += 1000; interface.checkRecvFrame(frame);
assert(!server->advertising.active);
assert(std::count(calls.begin(), calls.end(), "advertise") == attempts + 1);
for (unsigned i = 0; i < 100; ++i) interface.checkRecvFrame(frame);
assert(std::count(calls.begin(), calls.end(), "advertise") == attempts + 1);
failure.clear(); test_millis += 999; interface.checkRecvFrame(frame);
assert(!server->advertising.active);
++test_millis; interface.checkRecvFrame(frame);
assert(server->advertising.active);
assert(std::count(calls.begin(), calls.end(), "advertise") == attempts + 2);
authenticate(interface, info);
server->connected = false; server->callbacks->onDisconnect(server, info, 0);
interface.checkRecvFrame(frame); interface.disable();
const auto before_off = std::count(calls.begin(), calls.end(), "advertise");
test_millis += 10000; interface.checkRecvFrame(frame);
assert(std::count(calls.begin(), calls.end(), "advertise") == before_off);
NimBLEDevice::deinit(true);
}
static void test_authentication_and_bond_lifecycle() {
for (unsigned missing = 0; missing < 3; ++missing) {
reset(); SerialBLEInterface interface;
@@ -493,6 +523,7 @@ int main() {
test_identity_modes();
test_pairing_wake_for_random_and_saved_pins();
test_startup_failures();
test_advertising_restart_retries_and_disable_cancels();
test_authentication_and_bond_lifecycle();
test_connection_parameters_only_on_current_authenticated_transition();
test_real_transport_frames();
+82 -9
View File
@@ -280,13 +280,10 @@ static void localOnlyAndBusyTransactions() {
const auto original = f.radio.tuning;
const auto saved = f.fs.files["/radio_fast"];
const unsigned persists = f.radio.persists;
for (const auto result : {mesh::RadioParamApplyResult::BUSY,
mesh::RadioParamApplyResult::FAILED}) {
f.radio.admission = result;
f.cmd("set radio.fast.fs on", false);
assert(f.radio.tuning == original && f.radio.persists == persists);
assert(f.fs.files["/radio_fast"] == saved);
}
f.radio.admission = mesh::RadioParamApplyResult::FAILED;
f.cmd("set radio.fast.fs on", false);
assert(f.radio.tuning == original && f.radio.persists == persists);
assert(f.fs.files["/radio_fast"] == saved);
f.radio.admission = mesh::RadioParamApplyResult::APPLIED;
assert(strstr(f.cmd("set radio.fast.fs on", false, true), "local"));
f.cli.beginReplyCommand();
@@ -299,6 +296,77 @@ static void localOnlyAndBusyTransactions() {
puts("Fast tuning: busy admission and local-only changes passed");
}
static void busyTargetsComposeAndApplyOnce() {
TuningFixture f;
const auto original = f.radio.tuning;
f.radio.admission = mesh::RadioParamApplyResult::BUSY;
assert(strstr(f.cmd("set radio.fast.warm off"), "pending"));
assert(f.cli.hasPendingTuning());
assert(strstr(f.cmd("set radio.fast.spi 9"), "pending"));
const auto committed = f.fs.files["/radio_fast"];
assert(f.radio.tuning == original);
// This pending feature must survive a rejected replacement save.
f.fs.fail_write = true;
f.cmd("set radio.fast.packet off", false);
f.fs.fail_write = false;
assert(f.fs.files["/radio_fast"] == committed);
const auto saved = f.fs.files;
for (unsigned i = 0; i < 40; ++i) f.advance(1000);
assert(f.cli.hasPendingTuning() && f.fs.files == saved);
// Completion hooks call this before the next queued packet starts.
f.radio.admission = mesh::RadioParamApplyResult::APPLIED;
f.cli.servicePendingTuning();
assert(!f.cli.hasPendingTuning());
assert(!(f.radio.tuning.flags & mesh::RadioSwitchTuning::Warm));
assert(f.radio.tuning.flags & mesh::RadioSwitchTuning::Packet);
assert(f.radio.tuning.spi_mhz == 9 && f.fs.files == saved);
const auto attempts = f.radio.attempts;
f.cli.servicePendingTuning();
assert(f.radio.attempts == attempts);
TuningRadio reboot;
mesh::RadioProfileCLI restored;
restored.begin(&f.fs, &reboot, &f.clock);
assert(reboot.tuning == f.radio.tuning);
puts("Fast tuning: BUSY targets compose, survive failed save and apply once without a retry command");
}
static void failedPreambleCompensationRepairsDurably() {
for (bool rollover : {false, true}) for (bool explicit_save : {false, true}) {
TuningFixture f;
assert(f.cli.savePrimaryPreamble(32));
const auto old = f.fs.files["/radio_profiles"];
assert(f.cli.savePrimaryPreamble(64));
const auto candidate = f.fs.files["/radio_profiles"];
assert(candidate != old);
const auto physical = f.radio.p.primary;
f.fs.fail_write = true;
assert(!f.cli.restorePrimaryPreamble(32));
assert(f.cli.primaryPreamble() == 32 && f.cli.hasPendingTuning());
assert(f.fs.files["/radio_profiles"] == candidate);
// RAM equality is insufficient evidence of a durable compensation.
assert(!f.cli.savePrimaryPreamble(32));
assert(f.cli.hasPendingTuning());
g_mock_millis = rollover ? UINT32_MAX - 500 : 100;
f.cli.servicePendingTuning();
f.fs.fail_write = false;
if (explicit_save) {
assert(f.cli.savePrimaryPreamble(32));
} else {
f.advance(999);
assert(f.cli.hasPendingTuning() && f.fs.files["/radio_profiles"] == candidate);
f.advance(1);
}
assert(!f.cli.hasPendingTuning() && f.fs.files["/radio_profiles"] == old);
assert(f.radio.p.primary == physical); // Persistence repair never retunes RX.
TuningRadio reboot; mesh::RadioProfileCLI restored;
restored.begin(&f.fs, &reboot, &f.clock);
assert(restored.primaryPreamble() == 32);
assert(!f.cli.restorePrimaryPreamble(7));
assert(f.cli.primaryPreamble() == 32 && !f.cli.hasPendingTuning());
}
puts("Preamble compensation: old runtime target, checked identical save, delayed durable repair and rollover passed");
}
static void storageFailureKeepsCommittedPolicy() {
for (unsigned failure = 0; failure < 6; ++failure) {
TuningFixture f;
@@ -435,11 +503,14 @@ static void bootRetriesAreBoundedAcrossRollover() {
restored.loop();
assert(reboot.attempts == 2 && reboot.tuning != expected);
restored.loop();
assert(reboot.attempts == 2);
// BUSY is just an admission check: service can use the next TX gap.
// Real hardware failures retain the one-second retry backoff.
const unsigned before = admission == mesh::RadioParamApplyResult::BUSY ? 3 : 2;
assert(reboot.attempts == before);
reboot.admission = mesh::RadioParamApplyResult::APPLIED;
g_mock_millis += 1000;
restored.loop();
assert(reboot.attempts == 3 && reboot.tuning == expected);
assert(reboot.attempts == before + 1 && reboot.tuning == expected);
assert(f.fs.files == saved && !reboot.persists);
}
}
@@ -491,6 +562,8 @@ int main() {
roundedClockRequiresCapabilityAndBootAdmission();
clockOnlyLegacyHalKeepsFeaturesUnavailable();
localOnlyAndBusyTransactions();
busyTargetsComposeAndApplyOnce();
failedPreambleCompensationRepairsDurably();
storageFailureKeepsCommittedPolicy();
bootRecoveryAndDeferredAdmission();
malformedAndUnreadableImagesStayProtected();
+1 -1
View File
@@ -321,7 +321,7 @@ static void recoveryOwnershipAdmission() {
for (bool between_checks : {false, true}) {
RadioLibWrapper w; selectMode(w, mode);
w._rx_ps_armed = mode == 1;
w._rx_boosted_gain_valid = w._cur_rx_boosted_gain = true;
w._rx_boosted_gain_valid = w._rx_boosted_gain_applied = w._cur_rx_boosted_gain = true;
w._nf_refresh_requested = false; w._nf_last_calib = now_ms;
assert(w._floor_estimator.add(-105, now_ms));
const uint8_t payload[] = {0x18, 0x27, 0x36, 0x45, 0x54};
+13 -6
View File
@@ -132,6 +132,7 @@ class MQTTBridge : public AbstractBridge {
bool running = false;
bool stopping = false;
bool network_suspended = false;
bool start_pending = false;
public:
inline static unsigned live = 0, fail_starts = 0;
unsigned begins = 0, ends = 0, loops = 0, sent = 0, received = 0;
@@ -143,13 +144,16 @@ public:
void setBuildDate(const char*) {}
void setStatsSources(void*, void*, void*, void*) {}
void begin() override {
if (stopping) { start_pending = true; return; }
assert(filters); ++begins;
if (fail_starts) { --fail_starts; return; }
if (fail_starts) { --fail_starts; start_pending = true; return; }
running = true;
start_pending = false;
network_suspended = false;
}
void end() override { ++ends; running = stopping = network_suspended = false; }
void requestStop() { stopping = running; }
void end() override { ++ends; running = stopping = network_suspended = start_pending = false; }
void requestStop() { start_pending = false; stopping = running; }
bool isStartPending() const { return start_pending; }
bool isStopping() const { return stopping; }
bool isRunning() const override { return running; }
bool isNetworkSuspended() const { return network_suspended; }
@@ -159,7 +163,8 @@ public:
}
void loop() override {
++loops;
if (stopping) { ++ends; running = stopping = network_suspended = false; }
if (stopping) { ++ends; running = stopping = network_suspended = false; return; }
if (start_pending) begin();
}
void sendPacket(mesh::Packet* p) override { if (allow(p)) ++sent; }
void onPacketReceived(mesh::Packet* p) { if (allow(p)) ++received; }
@@ -205,6 +210,7 @@ struct Callbacks {
virtual bool setMqttBridgeState(bool) = 0;
virtual bool requestMqttBridgeStop() = 0;
virtual bool isMqttBridgeStopping() = 0;
virtual bool isMqttBridgeStartPending() = 0;
virtual bool restartMqttBridge() = 0;
};
class MyMesh : public Callbacks {
@@ -418,10 +424,11 @@ int main() {
expect_get(cli, "mqtt.stopping", "> on");
const unsigned stopping_saves = cli.saves;
cli.set("mqtt.enabled on", reply);
assert(strstr(reply, "MQTT is stopping") && !mesh._prefs.bridge_enabled);
assert(cli.saves == stopping_saves && !mesh.setMqttBridgeState(true));
assert(!strcmp(reply, "OK") && mesh._prefs.bridge_enabled);
assert(cli.saves == stopping_saves + 1 && mesh.isMqttBridgeStartPending());
cli.set("mqtt.enabled off", reply); // a repeated request is accepted
assert(strcmp(reply, "OK") == 0 && mesh.isMqttBridgeStopping());
assert(!mesh.isMqttBridgeStartPending());
assert(mesh.isRs232BridgeRunning() && mesh.bridgesPreventSleep());
const unsigned uart_tx_before = mesh.bridge->sent;
mesh.routeRx(&packet); mesh.serviceBridges();
+1 -1
View File
@@ -95,7 +95,7 @@ struct CLI {
bool scheduled = false;
unsigned attempts = 0;
bool hasActiveUserGpioTimer() const { return false; }
bool hasPendingTxPower() const { return false; }
bool hasPendingRadioSettings() const { return false; }
void loop();
};
class SensorMesh : public mesh::Mesh {
+3 -1
View File
@@ -327,7 +327,7 @@ void serializeJson(DynamicJsonDocument& doc, AsyncResponseStream& response) {
struct WebConfigServer {
enum Mode { MODE_OFF, MODE_LAN, MODE_SETUP };
Mode _mode = MODE_OFF;
bool _owns_wifi = true, _stopping = false;
bool _owns_wifi = true, _stopping = false, _start_retryable = false;
bool _retry_saved_wifi_in_setup = true, _setup_reconnect_in_progress = true;
bool _was_setup_ap = false, _initial_setup = false;
bool _setup_provisioning_privilege = false;
@@ -394,6 +394,7 @@ int main() {
WebConfigServer portal; char reply[160] = {};
assert(!portal.startSetupMode(reply));
assert(strstr(reply, "stop ESP-NOW") && WiFi.live_mode == WIFI_STA);
assert(!portal._start_retryable);
assert(WiFi.sta_only_calls == 0 && WiFi.ap_calls == 0 && WiFi.scans == 0);
mesh::wifi::setLongRangeOwner(owner, false);
}
@@ -409,6 +410,7 @@ int main() {
char reply[160] = {};
const uint32_t started = millis();
assert(!portal.startSetupMode(reply));
assert(portal._start_retryable);
assert(millis() - started < 4500);
assert(portal._mode == WebConfigServer::MODE_OFF && !portal._dns && portal.servers == 0);
const unsigned prepared = fault != Fault::ModeSetterFailure
+9 -1
View File
@@ -39,7 +39,8 @@ struct WebConfigServer {
Callbacks callbacks;
Callbacks* _cb = &callbacks;
mesh::RoomWebMailbox* _room_mailbox = new mesh::RoomWebMailbox;
Mode _mode = MODE_LAN;
Mode _mode = MODE_LAN, _start_mode = MODE_OFF;
uint32_t _start_retry_at = 0, _start_retry_delay = 5000;
bool _stopping = false, _keep_wifi_on_stop = false, _was_setup_ap = false;
bool _owns_wifi = true, _stop_warned = false, _initial_setup = false;
bool _setup_provisioning_privilege = false;
@@ -139,4 +140,11 @@ int main() {
assert(!failed.stopForOTA(reply));
assert(strstr(reply, "WebConfig stopped; WiFi AP handoff failed"));
assert(!failed.server.listening);
// OTA cancels a queued AP retry even when no listener was created yet.
WebConfigServer pending;
pending._mode = WebConfigServer::MODE_OFF;
pending._start_mode = WebConfigServer::MODE_SETUP;
pending._start_retry_at = 5000;
assert(pending.stopForOTA(reply));
assert(pending._start_mode == WebConfigServer::MODE_OFF && !pending._start_retry_at);
}
+1
View File
@@ -24,6 +24,7 @@ struct WebConfigServer {
bool isStopping() const { return false; }
void updateWiFiOwnership(bool owner) { owns = owner; }
void requestNetworkAccess() {}
bool requestStart(bool ap, char* reply) { return ap ? startSetupMode(reply) : startAutoMode(reply); }
bool startAutoMode(char* reply) { strcpy(reply, "starting"); return true; }
bool startSetupMode(char* reply) { strcpy(reply, "setup"); return true; }
};
+2 -1
View File
@@ -6,6 +6,7 @@
#include <string>
#include <helpers/RoomWebMailbox.h>
#include <helpers/WiFiReconnectPolicy.h>
#include <helpers/WebConfigBatch.h>
#include <helpers/WiFiNetworkPowerPolicy.h>
#define MESH_MANAGEMENT_PASSWORD_HOST_TEST
#include <helpers/esp32/ManagementPassword.h>
@@ -102,7 +103,7 @@ public:
char _wifi_ssid[32] = {}, _wifi_password[65] = {};
uint8_t _wifi_power_save = 0;
Mode _mode = MODE_OFF;
bool _stopping = false, _retry_saved_wifi_in_setup = false;
bool _stopping = false, _retry_saved_wifi_in_setup = false, _start_retryable = false;
bool _setup_reconnect_in_progress = false, _board_cmds_probed = false;
bool _was_setup_ap = false, _initial_setup = false;
bool foreground = false;
+2 -1
View File
@@ -86,7 +86,8 @@ struct RadioLibWrapper {
bool _rx_ps_enabled = false, _rx_ps_armed = false, _rx_hold_continuous = false;
bool _rx_ps_continuous_fallback = false, _nf_calib_active = false;
bool _nf_refresh_requested = false;
bool _rx_boosted_gain_valid = true, _cur_rx_boosted_gain = true;
bool _rx_boosted_gain_valid = true, _rx_boosted_gain_applied = true;
bool _cur_rx_boosted_gain = true;
bool _noise_floor_valid = true, _noise_floor_secondary_valid = true;
bool _wd_last_busy = false;
uint8_t _startrx_fails = 0, _irq_probe_failures = 0;
+60
View File
@@ -80,6 +80,61 @@ OBSERVER_QUERY_EXCEPTIONS = {
class CLISettingsContractTest(unittest.TestCase):
def test_shared_primary_parser_can_be_skipped_without_changing_other_commands(self):
harness = r'''
#include <cassert>
#include <cstdio>
#include <cstring>
#include "examples/companion_radio/NodePrefs.h"
int main() {
CompanionNodePrefs prefs;
prefs.freq = 915; prefs.bw = 125; prefs.sf = 7; prefs.cr = 5;
auto* radio = prefs.getRadioPrefs(); radio->clearDirty();
char reply[160] = "unchanged";
for (const char* text : {"set radio 916,125,8,6", "set radio invalid"}) {
assert(!radio->handleCommand(text, 0, reply, false));
assert(!strcmp(reply, "unchanged") && !radio->isDirty());
assert(prefs.freq == 915 && prefs.bw == 125 && prefs.sf == 7 && prefs.cr == 5);
}
assert(radio->handleCommand("get radio", 0, reply, false));
float f = 0, bw = 0; unsigned sf = 0, cr = 0;
assert(sscanf(reply, "> %f,%f,%u,%u", &f, &bw, &sf, &cr) == 4);
assert(f == 915 && bw == 125 && sf == 7 && cr == 5);
assert(radio->handleCommand("set af 2", 0, reply, false));
assert(!strcmp(reply, "OK") && prefs.airtime_factor == 2 && radio->isDirty());
radio->clearDirty();
// The three-argument/default path keeps the complete legacy parser.
assert(radio->handleCommand("set radio invalid", 0, reply));
assert(strstr(reply, "invalid radio") && !radio->isDirty());
assert(radio->handleCommand("set radio 916,125,8,6", 0, reply));
assert(!strncmp(reply, "OK", 2) && radio->isDirty());
assert(prefs.freq == 916 && prefs.bw == 125 && prefs.sf == 8 && prefs.cr == 6);
}
'''
with tempfile.TemporaryDirectory(prefix='common-radio-dispatch-') as directory:
work = Path(directory)
(work / 'test.cpp').write_text('#include <initializer_list>\n' + harness)
(work / 'Utils.h').write_text('''#pragma once
#include <Arduino.h>
#include <cassert>
namespace mesh { struct Utils {
static void printHex(Stream&,const uint8_t*,size_t){assert(false);}
static void fromHex(uint8_t*,size_t,const char*){assert(false);}
}; }
''')
sources = ['ConfigSerializer.cpp', 'DynamicConfigSerializer.cpp',
'CommonRadioPrefs.cpp', 'radiolib/RXPowerSaving.cpp',
'radiolib/RXPowerSavingCLI.cpp', 'TxtDataHelpers.cpp']
compiled = subprocess.run(['g++', '-std=c++17', '-DNRF52_PLATFORM=1',
'-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-fno-pie', '-no-pie',
'-I', str(work), '-I', str(ROOT / 'test/fixtures/radio_profiles/mocks'),
'-I', str(ROOT / 'test/mocks'), '-I', str(ROOT / 'src'), '-I', str(ROOT),
str(work / 'test.cpp'), *(str(ROOT / 'src/helpers' / name) for name in sources),
'-o', str(work / 'test')], text=True, capture_output=True)
self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr)
checked = subprocess.run([str(work / 'test')], text=True, capture_output=True)
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
def test_feature_guarded_query_coverage(self):
compiler = shutil.which('g++') or shutil.which('clang++')
self.assertIsNotNone(compiler, 'Host C++ compiler required')
@@ -275,6 +330,11 @@ class CLISettingsContractTest(unittest.TestCase):
extract_braced(source, signature).replace('CommonCLI::', 'CLI::')
for signature in ('void CommonCLI::applyAndSaveTxPower(',
'void CommonCLI::servicePendingTxPower(')))
fixture = fixture.replace('@RX_METHODS@', '\n'.join(
extract_braced(source, signature).replace('CommonCLI::', 'CLI::')
for signature in ('mesh::RadioParamApplyResult CommonCLI::applyRxSetting(',
'bool CommonCLI::saveRxSetting(',
'void CommonCLI::restoreRxSetting(')))
cpp.write_text(fixture, encoding='utf-8')
sanitizers = (['-fsanitize=address,undefined', '-fno-sanitize-recover=all',
'-fno-pie', '-no-pie'] if sys.platform.startswith('linux') else [])
+8 -5
View File
@@ -22,10 +22,11 @@ namespace mesh {
void setUsbLoggingEnabled(bool value) { live_usb = value; ++usb_calls; }
}
struct Callbacks {
bool live_wifi = false, apply_ok = true, stopping = false;
bool live_wifi = false, apply_ok = true, stopping = false, pending = false;
unsigned calls = 0;
bool setMqttBridgeState(bool value) {
++calls;
if (apply_ok && value && stopping) { pending = true; return true; }
if (apply_ok) live_wifi = value;
return apply_ok;
}
@@ -91,15 +92,17 @@ int main() {
assert(cli.persisted.usb_logging_enabled && cli.persisted.bridge_enabled);
assert(live_usb && !cli.callbacks.live_wifi);
assert(strstr(reply, "saved, but MQTT runtime change failed"));
// A restart during cleanup must not save ON or change either live output.
// A restart during cleanup saves intent without interrupting the old worker.
cli.callbacks.stopping = true;
cli.callbacks.apply_ok = true;
cli.prefs = cli.persisted = {0, 0};
live_usb = false;
const unsigned before_saves = cli.saves, before_calls = cli.callbacks.calls;
cli.set("logging.output both", reply);
assert(strstr(reply, "MQTT is stopping"));
assert(cli.saves == before_saves && cli.callbacks.calls == before_calls);
assert(!cli.prefs.bridge_enabled && !cli.persisted.bridge_enabled && !live_usb);
assert(strstr(reply, "(saved)"));
assert(cli.saves == before_saves + 1 && cli.callbacks.calls == before_calls + 1);
assert(cli.prefs.bridge_enabled && cli.persisted.bridge_enabled && live_usb);
assert(cli.callbacks.pending && !cli.callbacks.live_wifi);
#endif
}
'''
+5 -3
View File
@@ -113,6 +113,8 @@ struct TxRole : mesh::Mesh {
uint8_t tracker_packet_hash[MAX_HASH_SIZE] = {};
uint32_t futureMillis(uint32_t delay) const { return millis() + delay; }
void finishRadioReply(bool) {}
void processScheduledRadioSettings(bool) {}
void servicePendingPrimaryRadioSettings(bool) {}
void onSendComplete(mesh::Packet*) override;
};
@CALLBACK@
@@ -225,12 +227,12 @@ int main() {
f'mesh::powerdiag::Mask {name}::pendingWorkReason() const')
# Include pending intent during hardware-failure backoff too:
# nRF52's event-driven sleep has no guaranteed timer wake.
self.assertIn('_cli.hasPendingTxPower()', pending)
self.assertLess(pending.index('_cli.hasPendingTxPower()'),
self.assertIn('_cli.hasPendingRadioSettings()', pending)
self.assertLess(pending.index('_cli.hasPendingRadioSettings()'),
pending.index('radio_apply_backoff')
if 'radio_apply_backoff' in pending else len(pending))
recovery = extract_braced(header, 'bool canRecoverUsbLogging() const')
self.assertIn('!_cli.hasPendingTxPower()', recovery)
self.assertIn('!_cli.hasPendingRadioSettings()', recovery)
self.assertIn('_cli.loop();', extract_braced(source, f'void {name}::loop('))
+63 -4
View File
@@ -13,6 +13,7 @@ SOURCE = ROOT / 'examples/companion_radio/MyMesh.cpp'
HARNESS = r'''
#include <cassert>
#include <helpers/TempRadioReplyBarrier.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
@@ -24,6 +25,8 @@ HARNESS = r'''
#include <algorithm>
#include <helpers/CLICommandUtils.h>
#include <helpers/radiolib/RXPowerSaving.h>
namespace mesh { enum class RadioParamApplyResult { APPLIED, BUSY, FAILED }; }
using Apply=mesh::RadioParamApplyResult;
using std::min;
using std::isfinite;
#define constrain(value,lo,hi) ((value)<(lo)?(lo):((value)>(hi)?(hi):(value)))
@@ -74,6 +77,18 @@ struct Driver {
uint32_t rx=3000,sleep=4000;
unsigned calls=0,gain_calls=0;
std::deque<bool> results,gain_results;
std::deque<Apply> rx_accepted,gain_accepted;
Apply trySetRxPowerSaving(bool enable,uint32_t rx,uint32_t sleep) {
if(!rx_accepted.empty()) { const auto result=rx_accepted.front();rx_accepted.pop_front();if(result!=Apply::APPLIED){++calls;return result;} }
return setRxPowerSaving(enable,rx,sleep)?Apply::APPLIED:Apply::FAILED;
}
Apply trySetRxBoostedGainMode(bool enable) {
if(!gain_accepted.empty()) { const auto result=gain_accepted.front();gain_accepted.pop_front();if(result!=Apply::APPLIED){++gain_calls;return result;} }
return setRxBoostedGainMode(enable)?Apply::APPLIED:Apply::FAILED;
}
Apply trySetTxPower(int8_t) {return Apply::APPLIED;}
Apply trySetRxPowerSavingRfRxDisabled(bool) {return Apply::APPLIED;}
bool supportsRxBoostedGainMode() const { return gain_supported; }
bool supportsRxPowerSaving() const { return supported; }
bool setRxPowerSaving(bool enable,uint32_t r,uint32_t s) {
@@ -92,7 +107,34 @@ struct Driver {
} radio_driver;
@PARSERS@
struct Clock { uint32_t getMillis() const { return 100; } } clock_source;
struct CommonRadioPrefs {static bool isValidBandwidth(float){return true;}};
struct MyMesh {
mesh::TempRadioReplyBarrier _primary_radio_reply;
bool _primary_radio_blocked=false,_primary_radio_reply_admission=false;
int8_t rf_rx_disable_pending=-1;uint32_t rf_rx_retry_at=0;
struct {
bool acceptsPrimary(float,float,uint8_t,uint8_t,uint16_t) const {return true;}
uint16_t primaryPreamble() const {return 0;}
bool savePrimaryPreamble(uint16_t) {return true;}
bool restorePrimaryPreamble(uint16_t) {return true;}
void servicePendingTuning() {}
} _radio_profiles;
struct {
struct {struct {uint8_t sf=7;float bw=250;} primary;} p;
auto* profiles() {return &p;}
bool isCarrierWaveActive() const {return false;}
bool isMorseTxActive() const {return false;}
bool isMorseRxActive() const {return false;}
} radio;
decltype(radio)* _radio=&radio;
enum class RadioSettingResult {Saved,RadioRejected,SaveFailed,SaveUnconfirmed};
RadioSettingResult applyAndSaveRadioParams(float,float,uint8_t,uint8_t,uint8_t,uint16_t,bool=false);
bool isValidClientRepeatFreq(uint32_t) const {return true;}
Apply tryApplyRadioParams(float,float,uint8_t,uint8_t) {return Apply::APPLIED;}
void queueSavedRadioApply();
void servicePendingTxPower() {}
void servicePendingLocalRadioSettings();
Prefs _prefs,durable;
double durable_lat=10,durable_lon=20;
bool storage_accepts=true,_radio_available=true;
@@ -140,7 +182,7 @@ struct MyMesh {
bool millisHasNowPassed(uint32_t) const { return true; }
uint32_t futureMillis(uint32_t delay) const { return delay+100; }
bool applySavedRadioParams() { return true; }
void recover() { @RECOVERY@ }
void recover() { servicePendingLocalRadioSettings(); }
void expectOriginal() const {
assert(!memcmp(&_prefs,&durable,sizeof(Prefs)));
assert(!strcmp(_prefs.node_name,"original"));
@@ -292,6 +334,21 @@ int main() {
assert(!m.applyAndSaveRxPowerSaving("10000 20000",reply));++checks;
assert(m.saves==0);m.expectOriginal();
}
for(bool gain:{false,true}) {
MyMesh m;char reply[160]={};
if(gain)radio_driver.gain_accepted={Apply::BUSY};else radio_driver.rx_accepted={Apply::BUSY};
assert(gain?m.applyAndSaveRxBoostedGain(true):m.applyAndSaveRxPowerSaving("10000 20000",reply));++checks;
assert(m.saves==1 && m.saved_radio_apply_pending);
assert(gain?bool(m.durable.rx_boosted_gain):bool(m.durable.rx_powersaving_enabled));
m.recover();assert(!m.saved_radio_apply_pending && m.saves==1);
assert(gain?radio_driver.boosted_gain:radio_driver.rxps);
// A failed BUSY replacement leaves the first desired target intact.
m.saved_radio_apply_pending=true;m.radio_apply_retry_at=500;m.storage_accepts=false;
if(gain)radio_driver.gain_accepted={Apply::BUSY};else radio_driver.rx_accepted={Apply::BUSY};
assert(!(gain?m.applyAndSaveRxBoostedGain(false):m.applyAndSaveRxPowerSaving("off",reply)));++checks;
assert(m.saved_radio_apply_pending && m.radio_apply_retry_at==500 && m.saves==2);
assert(gain?bool(m._prefs.rx_boosted_gain):bool(m._prefs.rx_powersaving_enabled));
}
// Boosted gain uses the actual setter and the shared saved-radio recovery.
// Cover both directions, rejected saves, busy restoration, and unsupported radios.
for(bool initial:{false,true})for(bool save_ok:{false,true}) {
@@ -329,7 +386,7 @@ int main() {
{
MyMesh m;radio_driver.gain_results={false};
assert(!m.applyAndSaveRxBoostedGain(true));++checks;
assert(m.saves==0 && !radio_driver.boosted_gain && !m.saved_radio_apply_pending);
assert(m.saves==0 && !radio_driver.boosted_gain && m.saved_radio_apply_pending);
m.expectOriginal();
}
{
@@ -342,7 +399,7 @@ int main() {
for(bool save_ok:{false,true}) {
MyMesh m;m._radio_available=false;m.storage_accepts=save_ok;
assert(m.applyAndSaveRxBoostedGain(true)==save_ok);++checks;
assert(m.saves==1 && radio_driver.gain_calls==0 && !m.saved_radio_apply_pending);
assert(m.saves==1 && radio_driver.gain_calls==0 && m.saved_radio_apply_pending==save_ok);
assert(m._prefs.rx_boosted_gain==save_ok && m.durable.rx_boosted_gain==save_ok);
}
for(bool initial:{false,true})for(bool save_ok:{false,true}) {
@@ -399,12 +456,14 @@ class CompanionPrefsTransactionTests(unittest.TestCase):
'bool MyMesh::applyAndSaveRxPowerSaving(',
'bool MyMesh::applyAndSaveRxBoostedGain(',
'bool MyMesh::applyAndSavePowerSaving(',
'void MyMesh::queueSavedRadioApply(',
'void MyMesh::servicePendingLocalRadioSettings(',
'MyMesh::RadioSettingResult MyMesh::applyAndSaveRadioParams(',
)),
'@FRAMES@': ' else '.join(extract_braced(text, f'if (cmd_frame[0] == {cmd})') for cmd in frames),
'@WEB@': ' else '.join(extract_braced(text,f'if ({expr})') for expr in web),
'@TERMINAL@': ' else '.join(extract_braced(text,f'if ({expr})') for expr in terminal),
'@GPS@': extract_braced(text,'if (gps_value)'),
'@RECOVERY@': extract_braced(text,'if (!command_radio_apply_pending && saved_radio_apply_pending && !hasOutbound()'),
}
harness = HARNESS
for marker,value in replacements.items():
@@ -16,6 +16,7 @@ ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <helpers/RadioProfileCLI.h>
#include <helpers/TempRadioReplyBarrier.h>
#include <helpers/TxtDataHelpers.h>
#include <helpers/radiolib/RXPowerSaving.h>
#include <helpers/esp32/PowerTestControls.h>
@@ -78,6 +79,21 @@ template<typename... Args> bool handleMorseCommand(Args&&...) { return false; }
}
@COMMAND_FILTER@
struct MyMesh : CompanionFleetFixture {
mesh::TempRadioReplyBarrier _primary_radio_reply;
bool _primary_radio_blocked=false,_primary_radio_reply_admission=false;
enum class RadioSettingResult {Saved,RadioRejected,SaveFailed,SaveUnconfirmed};
bool _radio_available=true,saved_radio_apply_pending=false;
uint32_t radio_apply_retry_at=0;
uint8_t radio_apply_failures=0;
void queueSavedRadioApply();
RadioSettingResult applyAndSaveRadioParams(float,float,uint8_t,uint8_t,uint8_t,uint16_t,bool=false);
bool isValidClientRepeatFreq(uint32_t) const {return true;}
mesh::RadioParamApplyResult tryApplyRadioParams(float f,float bw,uint8_t sf,uint8_t cr) {
radio.p.primary.freq=f;radio.p.primary.bw=bw;radio.p.primary.sf=sf;radio.p.primary.cr=cr;
return mesh::RadioParamApplyResult::APPLIED;
}
bool applySavedRadioParams() {return tryApplyRadioParams(_prefs.freq,_prefs.bw,_prefs.sf,_prefs.cr)==mesh::RadioParamApplyResult::APPLIED;}
struct NoMorseReply {} _morse_reply;
uint8_t self_id = 0; // Signing is unreachable in this radio-only fixture.
CompanionNodePrefs _prefs;
@@ -274,7 +290,8 @@ def production_primary_radio_harness():
replacements = {
'@SAVE_PREFS@': extract_braced(header, 'bool savePrefs()'),
'@COMMAND_FILTER@': extract_braced(companion, 'static bool isCompanionRadioPrefsCommand('),
'@DISPATCH@': dispatch,
'@DISPATCH@': extract_braced(companion, 'void MyMesh::queueSavedRadioApply(') + '\n'
+ extract_braced(companion, 'MyMesh::RadioSettingResult MyMesh::applyAndSaveRadioParams(') + '\n' + dispatch,
'@COMPANION_SANITIZE@': boot_checks(companion, '_prefs.airtime_factor'),
'@INFRA_SANITIZE@': boot_checks(infra, '_prefs->airtime_factor'),
'@INFRA_SETTER@': extract_braced(infra, 'if (memcmp(config, "dutycycle ", 10) == 0)'),
+1
View File
@@ -18,6 +18,7 @@ class CompanionRadioDiagnosticsTests(unittest.TestCase):
methods='\n'.join(body(wrapper,signature) for signature in (
'bool supportsRxPowerSavingRfRxDisable() const override',
'bool setRxPowerSavingRfRxDisabled(bool disabled) override',
'mesh::RadioParamApplyResult trySetRxPowerSavingRfRxDisabled(bool disabled) override',
'bool isRxPowerSavingRfRxDisabled() const override'))
admission='\n'.join(body(radio,signature) for signature in (
'uint8_t RadioLibWrapper::beginReconfigure()',
+54 -5
View File
@@ -26,7 +26,7 @@ template<typename T> T nextResult(std::deque<T>& results,T fallback) {
}
struct Prefs {
float freq=915,bw=250;
uint8_t sf=7,cr=5,rx_boosted_gain=0;
uint8_t sf=7,cr=5,rx_boosted_gain=0,rx_ps_level=0,rx_ps_preamble=0;
bool radio_fem_rxgain=false,radio_fem_txgain=false,cad_enabled=false;
bool rx_powersaving_enabled=false;
uint32_t rx_ps_rx_us=1000,rx_ps_sleep_us=2000;
@@ -42,9 +42,16 @@ struct Board {
} board;
struct Driver {
bool gain=false,supported=true,hardware_present=true;
bool rxps_supported=false,rxps_enabled=false;
int power=0;
unsigned gain_calls=0,power_calls=0;
std::deque<bool> gain_results,power_results;
Apply trySetRxBoostedGainMode(bool enabled){return setRxBoostedGainMode(enabled)?Apply::APPLIED:Apply::FAILED;}
Apply trySetTxPower(int8_t power){return setTxPower(power)?Apply::APPLIED:Apply::FAILED;}
Apply trySetRxPowerSaving(bool enabled,uint32_t,uint32_t){
assert(hardware_present);rxps_enabled=enabled;return Apply::APPLIED;
}
Apply trySetRxPowerSavingRfRxDisabled(bool){return Apply::APPLIED;}
bool supportsRxBoostedGainMode(){return supported;}
bool setRxBoostedGainMode(bool value){
assert(hardware_present);
@@ -61,18 +68,26 @@ struct Driver {
if(ok)power=value;
return ok;
}
bool supportsRxPowerSaving(){return false;}
bool supportsRxPowerSaving(){return rxps_supported;}
bool setRxPowerSaving(bool,uint32_t,uint32_t){assert(hardware_present);return true;}
void setCADScanTimeoutMillis(int){}
} radio_driver;
bool recalcRxPowerSavingFromLevel(uint8_t,uint8_t,float,uint8_t,uint32_t*,uint32_t*) {return true;}
struct Radio {
struct {struct {uint8_t sf=7;float bw=250;} primary;} p;
auto* profiles() {return &p;}
bool isCarrierWaveActive() const{return false;}
bool isMorseTxActive() const{return false;}
bool isMorseRxActive() const{return false;}
void setCADEnabled(bool){}
void recalibrateNoiseFloor(){}
} radio;
struct Clock { uint32_t getMillis(){return now_ms;} } clock_source;
@RETRY_DELAY@
struct MyMesh {
int8_t rf_rx_disable_pending=-1;uint32_t rf_rx_retry_at=0;
Prefs _prefs;
bool _primary_radio_blocked=false;
Radio* _radio=&radio;
Clock* _ms=&clock_source;
bool _radio_available=true,saved_radio_apply_pending=false;
@@ -97,13 +112,17 @@ struct MyMesh {
return result;
}
bool savePrefs(){++saves;return false;}
struct {void servicePendingTuning(){}} _radio_profiles;
void servicePendingTxPower(){}
void queueSavedRadioApply();
void servicePendingLocalRadioSettings();
void configureRadioFromPrefs();
bool applySavedRadioParams();
bool applyAndSaveRxBoostedGain(bool);
#if COMPANION_FEATURE_TEMP_RADIO
void serviceTempRadio();
#endif
void recover(){@RECOVERY@}
void recover(){servicePendingLocalRadioSettings();}
};
@METHODS@
@@ -168,6 +187,20 @@ static void checkStartupAndRetry(){
m.saved_radio_apply_pending=true;m.recover();
assert(!m.saved_radio_apply_pending && !radio_driver.gain_calls);
}
{
// Accepting RXPS off while unavailable must survive both configuration
// passes. A tuple with no RXPS timings does not disable the cached mode.
MyMesh m;m.saved_radio_apply_pending=true;m._radio_available=false;
radio_driver.hardware_present=false;
radio_driver.rxps_supported=true;radio_driver.rxps_enabled=true;
m.configureRadioFromPrefs();
assert(m.saved_radio_apply_pending && radio_driver.rxps_enabled);
m._radio_available=true;radio_driver.hardware_present=true;
m.configureRadioFromPrefs();
assert(m.saved_radio_apply_pending && radio_driver.rxps_enabled);
m.recover();
assert(!m.saved_radio_apply_pending && !radio_driver.rxps_enabled && !m.saves);
}
}
#if COMPANION_FEATURE_TEMP_RADIO
@@ -211,6 +244,8 @@ static void checkTempRadioRestoration(){
assert(radio_driver.gain==bool(m._prefs.rx_boosted_gain));
assert(!m._temp_radio_applied && !m._temp_radio_revert_at);
assert(!m._temp_radio_retry_at && !m._temp_radio_failures);
assert(m.saved_radio_apply_pending==rollback_pending);
m.recover();
assert(!m.saved_radio_apply_pending && m.live_freq==m._prefs.freq);
assert(m.saves==unsigned(rollback_pending)); // Restoring never saves settings.
}
@@ -218,9 +253,22 @@ static void checkTempRadioRestoration(){
MyMesh m;m._temp_radio_applied=true;m._temp_radio_revert_at=now_ms;
m.saved_radio_apply_pending=true;radio_driver.supported=false;
radio_driver.gain_results={false};m.serviceTempRadio();
assert(!m._temp_radio_revert_at && !m.saved_radio_apply_pending);
assert(!m._temp_radio_revert_at && m.saved_radio_apply_pending);
m.recover();assert(!m.saved_radio_apply_pending);
assert(!radio_driver.gain_calls);
}
{
// A pending RXPS-off setting is not fulfilled by restoring only the
// TempRadio tuple, power and gain. The durable service still owns it.
MyMesh m;m._temp_radio_applied=true;m._temp_radio_revert_at=now_ms;
m.saved_radio_apply_pending=true;
radio_driver.rxps_supported=true;radio_driver.rxps_enabled=true;
m.serviceTempRadio();
assert(!m._temp_radio_applied && m.saved_radio_apply_pending);
assert(radio_driver.rxps_enabled);
m.recover();
assert(!m.saved_radio_apply_pending && !radio_driver.rxps_enabled && !m.saves);
}
{
MyMesh m;m._temp_radio_applied=true;m._temp_radio_revert_at=now_ms;
m.outbound=true;m.serviceTempRadio();
@@ -247,6 +295,8 @@ class CompanionRadioGainRestoreTests(unittest.TestCase):
'void MyMesh::configureRadioFromPrefs(',
'bool MyMesh::applySavedRadioParams(',
'bool MyMesh::applyAndSaveRxBoostedGain(',
'void MyMesh::queueSavedRadioApply(',
'void MyMesh::servicePendingLocalRadioSettings(',
))
methods += '\n#if COMPANION_FEATURE_TEMP_RADIO\n'
methods += extract_braced(text, 'void MyMesh::serviceTempRadio(')
@@ -254,7 +304,6 @@ class CompanionRadioGainRestoreTests(unittest.TestCase):
replacements = {
'@METHODS@': methods,
'@RETRY_DELAY@': extract_braced(text, 'static uint32_t nextRadioApplyRetryDelay('),
'@RECOVERY@': extract_braced(text, 'if (!command_radio_apply_pending && saved_radio_apply_pending && !hasOutbound()'),
}
harness = HARNESS
for marker, value in replacements.items():
+325 -58
View File
@@ -21,8 +21,11 @@ HARNESS = r'''
#include <initializer_list>
#include <vector>
#include <helpers/CLICommandUtils.h>
#include <helpers/RadioProfileCommandUtils.h>
#include <helpers/TempRadioReplyBarrier.h>
#define MESH_DEBUG_PRINTLN(...) ((void)0)
#define MAX_LORA_TX_POWER 22
#define PUB_KEY_SIZE 32
#define COMPANION_FEATURE_TEMP_RADIO 1
#define COMMAND_RADIO_APPLY_TIMEOUT_MS 3000
@CODES@
@@ -30,9 +33,12 @@ static bool tx_inflight=false;
static std::vector<unsigned> completion_order;
namespace mesh {
enum class RadioParamApplyResult { APPLIED, BUSY, FAILED };
struct Packet {};
struct Packet {bool radio_reply=false;};
struct Mesh {
void onSendComplete(Packet*) { completion_order.push_back(1); }
void onSendFail(Packet*) {}
void onRadioProfileCopyQueued(Packet*,const Packet*,uint8_t) {}
bool allowDirectRetry(const Packet*,const uint8_t*,uint8_t) const {return true;}
};
}
using Apply = mesh::RadioParamApplyResult;
@@ -53,18 +59,40 @@ struct Prefs {
int8_t tx_power_dbm=3;
bool rx_boosted_gain=false, rx_powersaving_enabled=false;
};
void recalcRxPowerSavingFromLevel(uint8_t,uint8_t sf,float bw,uint8_t,
bool recalcRxPowerSavingFromLevel(uint8_t,uint8_t sf,float bw,uint8_t,
uint32_t* rx,uint32_t* sleep) {
*rx=sf*100; *sleep=uint32_t(bw*100);
*rx=sf*100; *sleep=uint32_t(bw*100);return true;
}
struct Radio {
bool carrier=false, morse_tx=false, morse_rx=false;
bool isCarrierWaveActive() const { return carrier; }
bool isMorseTxActive() const { return morse_tx; }
bool isMorseRxActive() const { return morse_rx; }
struct {struct {uint8_t sf=7;float bw=250;} primary;} p;
auto* profiles() {return &p;}
} radio;
struct ContactInfo {
struct {uint8_t pub_key[32]={};} id;
bool isRemoteCLIAllowed() const {return true;}
};
namespace mesh {
struct RadioProfileCLI {
static bool parseSuffix(const char* input,unsigned fields,char* out,size_t size,uint16_t& preamble) {
return cli::parseRadioPreambleSuffix(input,fields,out,size,preamble);
}
};
}
#define TXT_TYPE_CLI_COMMAND 1
struct Driver {
bool partial_failure=false, power_verified=true;
bool partial_failure=false, power_verified=true, rf_supported=true, rf_disabled=false;
std::deque<Apply> rf_results;
bool supportsRxPowerSavingRfRxDisable() const {return rf_supported;}
Apply trySetRxPowerSavingRfRxDisabled(bool disabled) {
const auto result=rf_results.empty()?Apply::APPLIED:rf_results.front();
if(!rf_results.empty())rf_results.pop_front();
if(result==Apply::APPLIED)rf_disabled=disabled;
return result;
}
int8_t power=3, invalid_power=127;
unsigned calls=0;
std::deque<Apply> accepted;
@@ -81,14 +109,52 @@ struct Driver {
return result;
}
bool setTxPower(int8_t requested) { return trySetTxPower(requested)==Apply::APPLIED; }
Apply trySetRxBoostedGainMode(bool) { return Apply::APPLIED; }
bool rxps_supported=false;
uint32_t rx_us=0,sleep_us=0;
Apply trySetRxPowerSaving(bool,uint32_t rx,uint32_t sleep) {
rx_us=rx;sleep_us=sleep;return Apply::APPLIED;
}
bool supportsRxBoostedGainMode() const { return false; }
bool setRxBoostedGainMode(bool) { return true; }
bool supportsRxPowerSaving() const { return false; }
bool supportsRxPowerSaving() const { return rxps_supported; }
bool setRxPowerSaving(bool,uint32_t,uint32_t) { return true; }
} radio_driver;
@RETRY_DELAY@
struct CommonRadioPrefs {static bool isValidBandwidth(float){return true;}};
struct MyMesh : mesh::Mesh {
int8_t rf_rx_disable_pending=-1;uint32_t rf_rx_retry_at=0;
struct Profiles {
uint16_t preamble=0,persisted_preamble=0;
bool storage_ok=true,dirty=false;
std::deque<bool> save_results;
bool acceptsPrimary(float f,float bw,uint8_t sf,uint8_t cr,uint16_t) const {
return f>=150 && f<=2500 && bw>=7 && bw<=500 && sf>=5 && sf<=12 && cr>=5 && cr<=8;
}
uint16_t primaryPreamble() const { return preamble; }
bool savePrimaryPreamble(uint16_t next) {
bool ok=storage_ok;
if(!save_results.empty()){ok=save_results.front();save_results.pop_front();}
if(!ok)return false;
preamble=persisted_preamble=next;dirty=false;return true;
}
bool restorePrimaryPreamble(uint16_t previous) {
if(savePrimaryPreamble(previous))return true;
preamble=previous;dirty=true;return false;
}
void servicePendingTuning() {if(dirty)savePrimaryPreamble(preamble);}
bool hasPendingTuning() const {return dirty;}
void appendPrimaryChirpWarning(char*,size_t,uint8_t,float,uint16_t) {}
} _radio_profiles;
mesh::TempRadioReplyBarrier _primary_radio_reply;
bool _primary_radio_blocked=false,_primary_radio_reply_admission=false;
Prefs _prefs, durable, live;
uint16_t live_preamble=0;
float _temp_radio_freq=916,_temp_radio_bw=125;
uint8_t _temp_radio_sf=8,_temp_radio_cr=6;
uint16_t _temp_radio_preamble=16;
uint32_t _temp_radio_retry_at=0;
uint8_t _temp_radio_failures=0;
BaseSerialInterface serial, original, other;
BaseSerialInterface* _serial=&serial;
Clock* _ms=&clock_source;
@@ -110,7 +176,18 @@ struct MyMesh : mesh::Mesh {
std::vector<Reply> replies;
struct {
void complete(mesh::Packet*) { completion_order.push_back(3); }
void fail(mesh::Packet*) {}
void copy(const mesh::Packet*,const mesh::Packet*) {}
bool ownsReply(const mesh::Packet*) const {return false;}
uint32_t generation() const {return 0;}
void beginCommand(const uint8_t*) {}
void endCommand() {}
bool pending() const {return false;}
const uint8_t* actor() const {static uint8_t key[32]={};return key;}
void prepareReply(mesh::Packet*) {}
void armReply(mesh::Packet*,bool) {}
} _morse_reply;
bool _morse_reply_admission=false;
@RESULT_ENUM@;
MyMesh() {
serial.current=&original;radio_driver=Driver();radio=Radio();now_ms=100;
@@ -124,23 +201,45 @@ struct MyMesh : mesh::Mesh {
bool savePrefs() { ++saves; if(!storage_accepts)return false; durable=_prefs; return true; }
void writeOKFrame(BaseSerialInterface* route=nullptr) { replies.push_back({0,route?route:serial.current}); }
void writeErrFrame(uint8_t code,BaseSerialInterface* route=nullptr) { replies.push_back({code,route?route:serial.current}); }
Apply tryApplyRadioParams(float freq,float bw,uint8_t sf,uint8_t cr) {
Apply tryApplyRadioParams(float freq,float bw,uint8_t sf,uint8_t cr,bool=false,uint16_t=0) {
++applies;
Apply result=Apply::APPLIED;
if(!accepted.empty()) { result=accepted.front(); accepted.pop_front(); }
if(result==Apply::APPLIED) { live.freq=freq;live.bw=bw;live.sf=sf;live.cr=cr; }
if(result==Apply::APPLIED) {
live.freq=freq;live.bw=bw;live.sf=sf;live.cr=cr;
radio.p.primary.sf=sf;radio.p.primary.bw=bw;live_preamble=_radio_profiles.preamble;
}
return result;
}
bool applySavedRadioParams();
RadioSettingResult applyAndSaveTxPower(int8_t);
void servicePendingTxPower();
void onSendComplete(mesh::Packet*);
void finishRadioParamApply(float,float,uint8_t,uint8_t,uint8_t,BaseSerialInterface* = nullptr);
void deferRadioCommand();
void servicePendingRadioParamApply();
void cancelPendingRadioParamApply();
void onSendFail(mesh::Packet*);
void onRadioProfileCopyQueued(mesh::Packet*,const mesh::Packet*,uint8_t);
bool allowDirectRetry(const mesh::Packet*,const uint8_t*,uint8_t) const;
void finishPrimaryRadioReply(bool);
void onCLICommandRecv(const ContactInfo&,mesh::Packet*,uint32_t,const char*,char*);
void onCLIReplyPrepared(const ContactInfo&,mesh::Packet*);
void onCLIReplyQueued(const ContactInfo&,mesh::Packet*,bool);
void markConnectionActive(const ContactInfo&) {}
template<typename... T> void queueMessage(T&&...) {}
bool handleCommand(const char* command,uint32_t sender_timestamp,char* reply) {
const size_t reply_capacity=160;
@RADIO_CLI_BRANCH@
@FREQ_CLI_BRANCH@
return false;
}
RadioSettingResult applyAndSaveRadioParams(float,float,uint8_t,uint8_t,uint8_t,uint16_t,bool=false);
bool scheduleTempRadio(float,float,uint8_t,uint8_t,uint32_t,char*,size_t);
void scheduleNormalRadio(char*,size_t);
void appendRxPowerSavingAdjustmentNote(char*,size_t,uint8_t,float) const {}
void serviceTempRadio();
void queueSavedRadioApply();
void servicePendingLocalRadioSettings();
bool applyRxPowerSavingRfRxDisabled(const char*,char*,size_t);
void frame(size_t len) { @FRAME_BRANCHES@ }
void recover() { @RECOVERY@ }
void recover() { servicePendingLocalRadioSettings(); }
bool command(const char* command,char* reply) {
const size_t reply_capacity=160;
#if defined(MESH_HIL_TX_FREQ_MHZ)
@@ -200,6 +299,23 @@ int main() {
assert(!m.command("get tx.status",reply));
}
#endif
// Runtime RXEN admission is automatic but never writes persistent prefs.
{
MyMesh m;char reply[160]={};radio_driver.rf_results={Apply::BUSY,Apply::BUSY,Apply::APPLIED};
assert(m.applyRxPowerSavingRfRxDisabled("on",reply,sizeof(reply)) && !strcmp(reply,"OK"));
assert(m.rf_rx_disable_pending==1 && !radio_driver.rf_disabled && !m.saves);
assert(m.applyRxPowerSavingRfRxDisabled("off",reply,sizeof(reply)) && !strcmp(reply,"OK"));
assert(m.rf_rx_disable_pending==0);
m.servicePendingLocalRadioSettings();
assert(m.rf_rx_disable_pending<0 && !radio_driver.rf_disabled && !m.saves);
for(const char* invalid:{"", "ON", "off extra", "2"}) {
assert(m.applyRxPowerSavingRfRxDisabled(invalid,reply,sizeof(reply)) && strstr(reply,"Error"));
assert(m.rf_rx_disable_pending<0 && !m.saves);
}
radio_driver.rf_supported=false;
assert(m.applyRxPowerSavingRfRxDisabled("on",reply,sizeof(reply)) && strstr(reply,"unsupported"));
assert(m.rf_rx_disable_pending<0 && !m.saves);
}
// Invalid input never reaches hardware or storage.
for (int value : {-10,23}) {
MyMesh m;m.powerFrame(uint8_t(value));m.expectError(ERR_CODE_ILLEGAL_ARG);
@@ -213,14 +329,14 @@ int main() {
// a pending tuple prevents the ordinary hardware setter from being called.
for(bool tuple_pending : {false,true}) {
MyMesh m;radio_driver.accepted={Apply::BUSY};m.powerFrame(17);
m.replies.clear();m.command_radio_apply_pending=tuple_pending;
m.replies.clear();m.saved_radio_apply_pending=tuple_pending;
m.tx_power_apply_retry_at=now_ms+1000;radio_driver.invalid_power=18;
const unsigned calls=radio_driver.calls;
m.powerFrame(18);m.expectError(ERR_CODE_BAD_STATE);
assert(m.tx_power_apply_pending && m.tx_power_apply_retry_at==now_ms+1000);
assert(m._prefs.tx_power_dbm==17 && m.durable.tx_power_dbm==17);
assert(m.saves==1 && radio_driver.calls==calls);
assert(m.command_radio_apply_pending==tuple_pending);
assert(m.saved_radio_apply_pending==tuple_pending);
}
// Immediate application still commits before acknowledging the request.
{
@@ -376,20 +492,16 @@ int main() {
radio=Radio();m._temp_radio_applied=true;m.servicePendingTxPower();
assert(!m.tx_power_apply_pending && radio_driver.power==17 && m.applies==0);
}
// A pending tuple retains its original route/deadline, while power is saved
// independently. Completing the tuple cannot overwrite newer power intent.
// A tuple and power setting accepted during RX share durable latest intent.
{
MyMesh m;m.accepted={Apply::BUSY,Apply::APPLIED};m.tupleFrame();
assert(m.replies.empty() && m.command_radio_apply_pending && m.saves==0);
m.serial.current=&m.other;m.powerFrame(17);m.expectError(0,&m.other);
assert(m.command_radio_apply_pending && m.tx_power_apply_pending && radio_driver.calls==0);
assert(m.durable.freq==915 && m.durable.tx_power_dbm==17);
m.replies.clear();m.servicePendingTxPower();assert(radio_driver.calls==0);
m.servicePendingRadioParamApply();m.expectError(0);
assert(!m.command_radio_apply_pending && m.tx_power_apply_pending);
assert(m.durable.freq==920 && m.durable.tx_power_dbm==17);
m.servicePendingTxPower();
assert(!m.tx_power_apply_pending && radio_driver.power==17 && m.saves==2);
MyMesh m;m.accepted={Apply::BUSY,Apply::APPLIED};m.tupleFrame();m.expectError(0);
assert(m.saved_radio_apply_pending && m.saves==1 && m.durable.freq==920);
m.replies.clear();m.serial.current=&m.other;radio_driver.accepted={Apply::BUSY};
m.powerFrame(17);m.expectError(0,&m.other);
assert(m.tx_power_apply_pending && m.durable.tx_power_dbm==17);
m.servicePendingLocalRadioSettings();
assert(!m.saved_radio_apply_pending && !m.tx_power_apply_pending);
assert(m.live.freq==920 && radio_driver.power==17 && m.saves==2);
}
// Frontends retain strict validation and report accepted pending intent.
{
@@ -399,7 +511,7 @@ int main() {
assert(m.saves==1 && m.durable.tx_power_dbm==17);
m.servicePendingTxPower();assert(!m.tx_power_apply_pending && radio_driver.power==17);
}
// Both immediate and deferred tuple changes still commit before OK.
// Immediate tuple changes commit before OK; failed saves restore hardware.
{
MyMesh m;m.tupleFrame();m.expectError(0);
assert(m._prefs.freq==920 && m.durable.freq==920 && m.live.freq==920);
@@ -410,27 +522,174 @@ int main() {
MyMesh m;m.storage_accepts=false;m.tupleFrame();m.expectError(ERR_CODE_FILE_IO_ERROR);
m.expectOriginalPrefs();assert(m.live.freq==915 && !m.saved_radio_apply_pending);
}
// BUSY tuple acceptance survives disconnect and more than 30 seconds.
{
MyMesh m;m.accepted={Apply::BUSY,Apply::APPLIED};m.tupleFrame();
assert(m.replies.empty() && m.command_radio_apply_pending && m.saves==0);
m.serial.current=&m.other;m.servicePendingRadioParamApply();m.expectError(0);
assert(!m.command_radio_apply_pending && m.durable.freq==920);
MyMesh m;m.accepted={Apply::BUSY};m.tupleFrame();m.expectError(0);
assert(m.saved_radio_apply_pending && m.saves==1 && m.durable.freq==920);
m.serial.disconnected=&m.original;
for(uint32_t elapsed=0;elapsed<=31000;elapsed+=1000) {
now_ms=100+elapsed;m.accepted={Apply::BUSY};m.servicePendingLocalRadioSettings();
assert(m.saved_radio_apply_pending && m.saves==1 && m.replies.size()==1);
}
m.accepted={Apply::APPLIED};m.servicePendingLocalRadioSettings();
assert(!m.saved_radio_apply_pending && m.live.freq==920 && m.saves==1);
}
// A newer accepted tuple replaces the desired target. A failed save does not.
{
MyMesh m;m.accepted={Apply::BUSY,Apply::BUSY,Apply::BUSY,Apply::APPLIED};
m.tupleFrame();m.replies.clear();
assert(m.applyAndSaveRadioParams(921,62.5f,8,5,0,32)==MyMesh::RadioSettingResult::Saved);
assert(m.durable.freq==921 && m._radio_profiles.preamble==32);
m.storage_accepts=false;
assert(m.applyAndSaveRadioParams(922,125,7,5,0,16)==MyMesh::RadioSettingResult::SaveFailed);
assert(m.durable.freq==921 && m._prefs.freq==921 && m._radio_profiles.preamble==32);
m.servicePendingLocalRadioSettings();
assert(!m.saved_radio_apply_pending && m.live.freq==921 && m.saves==3);
}
// Rollback failure queues the old durable tuple, not the rejected candidate.
{
MyMesh m;m.storage_accepts=false;m.accepted={Apply::APPLIED,Apply::BUSY,Apply::APPLIED};
m.tupleFrame();m.expectError(ERR_CODE_FILE_IO_ERROR);m.expectOriginalPrefs();
assert(m.saved_radio_apply_pending && m.live.freq==920);
m.servicePendingLocalRadioSettings();
assert(!m.saved_radio_apply_pending && m.live.freq==915 && m.saves==1);
}
// A temporary lease retains the modem until it ends; no resend is needed.
{
MyMesh m;m._temp_radio_applied=true;m.tupleFrame();m.expectError(0);
assert(m.saved_radio_apply_pending && m.applies==0 && m.durable.freq==920);
m.servicePendingLocalRadioSettings();assert(m.applies==0);
m._temp_radio_applied=false;m.servicePendingLocalRadioSettings();
assert(!m.saved_radio_apply_pending && m.live.freq==920 && m.saves==1);
}
// Saved full settings apply in the completion gap despite queued TX work.
{
MyMesh m;mesh::Packet packet;m.accepted={Apply::BUSY,Apply::APPLIED};m.tupleFrame();
m.outbound=true;m.onSendComplete(&packet);
assert(!m.saved_radio_apply_pending && m.live.freq==920 && m.saves==1);
}
// Both stores can fail in succession. Compensation still restores the old
// runtime preamble, reports uncertainty, and repairs storage automatically.
{
MyMesh m;m._radio_profiles.preamble=m._radio_profiles.persisted_preamble=48;
m._radio_profiles.save_results={true,false};m.storage_accepts=false;
char reply[160]={};
assert(m.handleCommand("set radio 920,125,9,6,32",0,reply));
assert(!strcmp(reply,"Error: radio save unconfirmed"));
assert(m._prefs.freq==915 && m._radio_profiles.preamble==48);
assert(m._radio_profiles.persisted_preamble==32 && m._radio_profiles.dirty);
assert(m.live.freq==915 && m.live_preamble==48 && m.saved_radio_apply_pending);
m.recover();
assert(!m._radio_profiles.dirty && m._radio_profiles.persisted_preamble==48);
assert(!m.saved_radio_apply_pending && m.saves==1);
}
// A remote change shares durable acceptance with local frontends, but its
// exact two reply copies must drain before the primary can move. RXPS still
// follows the old active SF/BW until that handoff finishes.
{
MyMesh m;ContactInfo from;mesh::Packet a,b,unrelated;char reply[160]={};
m.saved_radio_apply_pending=true;m._prefs.rx_powersaving_enabled=true;
radio_driver.rxps_supported=true;
m.onCLICommandRecv(from,nullptr,10,"set radio 920,125,9,6",reply);
assert(!strcmp(reply,"OK") && m.saves==1 && m._primary_radio_blocked);
m.onCLIReplyPrepared(from,&a);m.onRadioProfileCopyQueued(&b,&a,0);
m.onCLIReplyQueued(from,&a,true);
assert(a.radio_reply && !m.allowDirectRetry(&a,nullptr,0));
m.recover();
assert(m.applies==0 && !m.saved_radio_apply_pending);
assert(radio_driver.rx_us==700 && radio_driver.sleep_us==25000);
m.onSendComplete(&unrelated);assert(m._primary_radio_blocked && m.applies==0);
m.onSendComplete(&a);assert(m._primary_radio_blocked && m.applies==0);
m.onSendFail(&b);assert(!m._primary_radio_blocked);
m.recover();
assert(m.live.freq==920 && m.applies==1 && m.saves==1);
assert(radio_driver.rx_us==900 && radio_driver.sleep_us==12500);
}
// Every outcome pair uses the actual completion/failure hooks: one
// successful copy is enough only after both exact copies have drained.
for(unsigned successes=0;successes<4;++successes) {
MyMesh m;ContactInfo from;mesh::Packet a,b;char reply[160]={};
m.onCLICommandRecv(from,nullptr,10,"set freq 920",reply);
m.onCLIReplyPrepared(from,&a);m.onRadioProfileCopyQueued(&b,&a,0);
m.onCLIReplyQueued(from,&a,true);
if(successes&1)m.onSendComplete(&a);else m.onSendFail(&a);
assert(m._primary_radio_blocked && m.applies==0);
if(successes&2)m.onSendComplete(&b);else m.onSendFail(&b);
m.recover();
assert(m._primary_radio_blocked==(successes==0));
assert(m.live.freq==(successes?920:915) && m.saves==1);
}
// Losing every response retains the old runtime channel. A duplicate of
// the saved request replays acknowledgement ownership without another save;
// an old or unrelated completion cannot release the new response barrier.
{
MyMesh m;ContactInfo from;mesh::Packet a,b,replay,unrelated;char reply[160]={};
m.onCLICommandRecv(from,nullptr,10,"set freq 920",reply);
m.onCLIReplyPrepared(from,&a);m.onRadioProfileCopyQueued(&b,&a,0);
m.onCLIReplyQueued(from,&a,true);m.onSendFail(&a);m.onSendFail(&b);
now_ms+=31000;m.recover();
assert(m._primary_radio_blocked && m.live.freq==915 && m.applies==0 && m.saves==1);
m.onCLICommandRecv(from,nullptr,11,"set freq 920",reply);
assert(!strcmp(reply,"OK") && m.saves==1);
m.onCLIReplyPrepared(from,&replay);m.onCLIReplyQueued(from,&replay,true);
m.onSendComplete(&a);m.onSendComplete(&unrelated);
assert(m._primary_radio_blocked && m.applies==0);
m.onSendComplete(&replay);
assert(!m._primary_radio_blocked && m.live.freq==920 && m.saves==1);
}
// A failed newer save cannot replace the older exact reply. A successful
// newer remote request does replace it; late older completions are inert.
for(bool save_new:{false,true}) {
MyMesh m;ContactInfo from;mesh::Packet old,newer;char reply[160]={};
m.onCLICommandRecv(from,nullptr,10,"set freq 920",reply);
m.onCLIReplyPrepared(from,&old);m.onCLIReplyQueued(from,&old,true);
m.storage_accepts=save_new;
m.onCLICommandRecv(from,nullptr,11,"set freq 921",reply);
assert((!strncmp(reply,"OK",2))==save_new);
m.onCLIReplyPrepared(from,&newer);m.onCLIReplyQueued(from,&newer,true);
m.onSendComplete(&old);
if(save_new) {
assert(m._primary_radio_blocked && m.applies==0);
m.onSendComplete(&newer);
assert(!m._primary_radio_blocked && m.live.freq==921);
} else assert(!m._primary_radio_blocked && m.live.freq==920);
assert(m.saves==2);
}
// No packet allocation is not evidence of delivery. A later local primary
// setting can deliberately replace that blocked remote intent.
{
MyMesh m;ContactInfo from;mesh::Packet unrelated;char reply[160]={};
m.onCLICommandRecv(from,nullptr,10,"set freq 920",reply);
m.onCLIReplyQueued(from,nullptr,false);m.onSendComplete(&unrelated);
assert(m._primary_radio_blocked && m.applies==0 && m.live.freq==915);
assert(m.handleCommand("set freq 922",0,reply) && !strcmp(reply,"OK"));
assert(!m._primary_radio_blocked && m.saved_radio_apply_pending);
m.recover();assert(m.live.freq==922 && m.saves==2);
}
// TempRadio owns both its active tuple and its future normal restoration.
// A remote permanent command is rejected before saving, and failing its
// error reply cannot strand an active lease when that lease expires.
for(unsigned phase=0;phase<3;++phase) {
MyMesh m;ContactInfo from;mesh::Packet error;char reply[160]={};
if(phase==0)m._temp_radio_set_at=now_ms+10;
if(phase==1)m._temp_radio_applied=true;
if(phase==2)m._temp_radio_revert_at=now_ms+10;
m.onCLICommandRecv(from,nullptr,10,"set radio 920,125,9,6",reply);
assert(strstr(reply,"Error") && m.saves==0 && !m._primary_radio_blocked);
m.onCLIReplyPrepared(from,&error);m.onCLIReplyQueued(from,&error,true);
m.onSendFail(&error);
m._temp_radio_set_at=0;m._temp_radio_applied=true;m._temp_radio_revert_at=now_ms;
m.live.freq=916;m.serviceTempRadio();
assert(!m._temp_radio_applied && !m._temp_radio_revert_at && m.live.freq==915);
}
{
MyMesh m;m.storage_accepts=false;m.accepted={Apply::BUSY,Apply::APPLIED,Apply::BUSY};
m.tupleFrame();assert(m.replies.empty() && m.command_radio_apply_pending);
m.serial.current=&m.other;m.servicePendingRadioParamApply();
m.expectError(ERR_CODE_FILE_IO_ERROR);m.expectOriginalPrefs();
assert(m.saved_radio_apply_pending && m.live.freq==920 && !m.command_radio_apply_pending);
m.recover();assert(!m.saved_radio_apply_pending && m.live.freq==915);
assert(m.saves==1 && m.replies.size()==1);
}
// Disconnect still cancels an unsaved tuple.
{
MyMesh m;m.accepted={Apply::BUSY};m.tupleFrame();
m.serial.disconnected=&m.original;m.servicePendingRadioParamApply();
assert(!m.command_radio_apply_pending && m.replies.empty() && m.saves==0);
m.expectOriginalPrefs();
MyMesh m;ContactInfo from;char reply[160]={};
m.onCLICommandRecv(from,nullptr,10,"set freq 920",reply);
assert(!m.scheduleTempRadio(916,125,8,6,1,reply,sizeof(reply)));
assert(strstr(reply,"acknowledgement") && !m._temp_radio_set_at);
m.scheduleNormalRadio(reply,sizeof(reply));
assert(strstr(reply,"acknowledgement") && !m._temp_radio_revert_at);
}
puts("Companion automatic TX-power commit and recovery regressions passed");
}
@@ -459,12 +718,14 @@ struct ContactStore {
@CONTACT_RECOVERY_API@
};
struct MyMesh {
struct {bool hasPendingTuning() const{return false;}} _radio_profiles;
ContactStore store;
ContactStore* _store=&store;
bool _radio_available=true, _iter_started=false;
bool command_radio_apply_pending=false;
bool saved_radio_apply_pending=false, _terminal_trace_pending=false;
bool tx_power_apply_pending=false;
int8_t rf_rx_disable_pending=-1;uint32_t rf_rx_retry_at=0;
uint32_t tx_power_apply_retry_at=0;
uint32_t radio_apply_retry_at=0, _scheduled_reboot_at=0;
uint32_t emergency_client_repeat_send_at=0, dirty_contacts_expiry=0;
@@ -494,11 +755,6 @@ struct MyMesh {
int main() {
MyMesh m;
assert(!m.hasPendingWork());
m.command_radio_apply_pending=true;
assert(m.hasPendingWork()); // Deferred tuples must keep the retry loop awake.
assert(m.pendingWorkReason()==mesh::powerdiag::mask(mesh::powerdiag::Reason::Scheduled));
m.command_radio_apply_pending=false;
assert(!m.hasPendingWork());
m.tx_power_apply_pending=true;
assert(m.hasPendingWork()); // TX-only intent must be serviced automatically.
assert(m.pendingWorkReason()==mesh::powerdiag::mask(mesh::powerdiag::Reason::Scheduled));
@@ -520,7 +776,7 @@ int main() {
m.radio_apply_retry_at=0;
assert(m.hasPendingWork());
m.radio_apply_retry_at=now_ms+10;
assert(!m.hasPendingWork());
assert(m.hasPendingWork()); // Retry backoff must not strand accepted intent.
now_ms+=10;
assert(m.hasPendingWork());
m.radio_apply_retry_at=0;
@@ -598,12 +854,22 @@ class CompanionRadioSettingsTransactionTests(unittest.TestCase):
methods = '\n'.join(extract_braced(text, signature) for signature in (
'bool MyMesh::applySavedRadioParams(',
'MyMesh::RadioSettingResult MyMesh::applyAndSaveTxPower(',
'void MyMesh::finishRadioParamApply(',
'void MyMesh::deferRadioCommand(',
'void MyMesh::servicePendingTxPower(',
'void MyMesh::queueSavedRadioApply(',
'bool MyMesh::applyRxPowerSavingRfRxDisabled(',
'MyMesh::RadioSettingResult MyMesh::applyAndSaveRadioParams(',
'void MyMesh::servicePendingLocalRadioSettings(',
'void MyMesh::onSendComplete(',
'void MyMesh::cancelPendingRadioParamApply(',
'void MyMesh::servicePendingRadioParamApply(',
'void MyMesh::onSendFail(',
'void MyMesh::onRadioProfileCopyQueued(',
'bool MyMesh::allowDirectRetry(',
'void MyMesh::finishPrimaryRadioReply(',
'void MyMesh::onCLICommandRecv(',
'void MyMesh::onCLIReplyPrepared(',
'void MyMesh::onCLIReplyQueued(',
'bool MyMesh::scheduleTempRadio(',
'void MyMesh::scheduleNormalRadio(',
'void MyMesh::serviceTempRadio(',
))
frame_branches = ' else '.join(extract_braced(text, f'if (cmd_frame[0] == {command})')
for command in ('CMD_SET_RADIO_PARAMS', 'CMD_SET_RADIO_TX_POWER'))
@@ -615,7 +881,8 @@ class CompanionRadioSettingsTransactionTests(unittest.TestCase):
'@FRAME_BRANCHES@': frame_branches,
'@TX_STATUS_BRANCH@': extract_braced(text, 'if (strcmp(command, "get tx.status") == 0)'),
'@CLI_BRANCH@': extract_braced(text, 'if (strncmp(command, "set tx ", 7) == 0)'),
'@RECOVERY@': extract_braced(text, 'if (!command_radio_apply_pending && saved_radio_apply_pending && !hasOutbound()'),
'@RADIO_CLI_BRANCH@': extract_braced(extract_braced(text, 'bool MyMesh::handleCommand('), 'if (!strncmp(command, "set radio ", 10))'),
'@FREQ_CLI_BRANCH@': extract_braced(text, 'if (strncmp(command, "set freq ", 9) == 0)'),
}
harness = HARNESS
for marker, value in replacements.items():
@@ -638,7 +905,7 @@ class CompanionRadioSettingsTransactionTests(unittest.TestCase):
self.assertIn('handleCommand(command, 0, local_reply)', terminal)
web = extract_braced(text, 'if (strcmp(key, "tx") == 0)')
self.assertIn('applyAndSaveTxPower(', web)
self.assertIn('servicePendingTxPower();', extract_braced(text, 'void MyMesh::loop()'))
self.assertIn('servicePendingLocalRadioSettings();', extract_braced(text, 'void MyMesh::loop()'))
self.assertIn('RadioSettingResult::SaveFailed',
extract_braced(text, 'if (strncmp(command, "set tx ", 7) == 0)'))
+2 -1
View File
@@ -258,7 +258,8 @@ int main() {
frame = extract_braced(source, "} else if (mesh::companion::isRunCliFrame(")
frame = frame.replace("} else if", "if", 1)
methods = "\n".join((
extract_braced(source, "bool MyMesh::applyAndSaveRxPowerSaving("), entry, adapter,
extract_braced(source, "bool MyMesh::applyAndSaveRxPowerSaving("),
extract_braced(source, "void MyMesh::queueSavedRadioApply("), entry, adapter,
))
constants = "\n".join(line for line in source.splitlines()
if line.startswith(("#define RESP_CODE_CLI_REPLY ",
@@ -373,10 +373,14 @@ class CompanionWiFiNetworkPowerTests(unittest.TestCase):
#include <helpers/WiFiNetworkPowerPolicy.h>
constexpr int WL_CONNECTED = 3, WL_DISCONNECTED = 6;
struct { int status() const { return WL_DISCONNECTED; } } WiFi;
struct { bool ota = false; bool isOTAUpdateRunning() const { return ota; } } board;
namespace mesh { struct Log { void println(const char*) {} };
inline Log& usbLoggingPort() { static Log log; return log; } }
struct Bridge {
int starts = 0; bool running = false;
void loop() {}
bool isStopping() const { return false; }
bool isStartPending() const { return false; }
void begin() { ++starts; running = true; mesh::wifi::networkPower().setManaged(true); }
bool isRunning() const { return running; }
};
@@ -395,6 +399,9 @@ struct MyMesh {
int main() {
Bridge bridge; MyMesh node; node._mqtt_bridge = &bridge;
assert(WiFi.status() == WL_DISCONNECTED);
board.ota = true;
node.serviceMQTT("saved-network", "saved-password");
assert(bridge.starts == 0); board.ota = false;
node._wc_batch_active = true;
node.serviceMQTT("saved-network", "saved-password");
assert(bridge.starts == 0);
+5 -1
View File
@@ -131,6 +131,7 @@ struct RoleCLI {
ObserverPrefs* getObserverPrefs() { return &prefs; }
bool hasActiveUserGpioTimer() const { return false; }
bool hasPendingTxPower() const { return false; }
bool hasPendingRadioSettings() const { return false; }
};
struct AbstractBridge {
bool running = false, stopping = false, allow_flash = true;
@@ -152,6 +153,7 @@ struct MQTTNodeInfo {
struct MQTTBridge : AbstractBridge {
bool network_suspended = false;
bool isNetworkSuspended() const { return network_suspended; }
bool isStartPending() const { return false; }
template<class... Args> explicit MQTTBridge(Args...) {}
void setDeviceID(const char*) {} void setFirmwareVersion(const char*) {}
void setBoardModel(const char*) {} void setBuildDate(const char*) {}
@@ -197,6 +199,8 @@ struct WebConfigServer {
return true;
}
bool startAutoMode(char* reply) { return startSetupMode(reply); }
bool requestStart(bool ap, char* reply) { return ap ? startSetupMode(reply) : startAutoMode(reply); }
bool isStartPending() const { return false; }
void requestStop() { running = false; stopping = true; }
bool stopForOTA(char*) { running = stopping = false; WiFi.mode(WIFI_STA); return true; }
void tick(uint32_t now) {
@@ -393,7 +397,7 @@ class ESP32FullPowerLifecycleTest(unittest.TestCase):
"bool startSharedEspNowBridgeIfReady()", "bool setEspNowBridgeState(",
"bool setMqttBridgeState(", "bool setBridgeState(",
"bool isEspNowBridgeRunning()", "bool isMqttBridgeRunning()",
"bool isMqttBridgeStopping()",
"bool isMqttBridgeStopping()", "bool isMqttBridgeStartPending()",
"bool isWebConfigActive() const", "bool isWebConfigStopping() const",
"bool hasWirelessNetworkClient() const", "bool stopWebConfigForOTA("))
methods = "\n".join(extract_braced(source, signature) for signature in (
+1 -1
View File
@@ -373,7 +373,7 @@ void finalizeHMAC(const uint8_t* key,size_t size,void* out,size_t n){{SHA256Base
'void MyMesh::checkRxInactivityWatchdog()', 'void MyMesh::setTempRadioTiming(',
'void MyMesh::updateAdvertTimer()', 'void MyMesh::updateFloodAdvertTimer()',
'void MyMesh::queueSavedRadioApply()', 'bool MyMesh::applySavedRadioParams()',
'void MyMesh::refreshScheduledRadioState()', 'void MyMesh::processScheduledRadioSettings()',
'void MyMesh::refreshScheduledRadioState()', 'void MyMesh::processScheduledRadioSettings(bool tx_gap)',
'void MyMesh::applyTempRadioParams(', 'bool MyMesh::scheduleNormalRadio()',
'void MyMesh::clearScheduledRadioSetting(', 'int MyMesh::findFreeScheduledRadioSlot() const',
'int MyMesh::countScheduledRadioSettings(', 'bool MyMesh::scheduledRadioConflicts(',
+3 -1
View File
@@ -65,7 +65,7 @@ struct CachedSensors {
++reads; lat = latitude; lon = longitude; return valid;
}
};
struct Profiles {};
struct Profiles {void servicePendingTuning(){}};
struct Fleet {
unsigned received = 0, serviced = 0;
bool scoped = false;
@@ -88,6 +88,7 @@ struct Fleet {
struct CLI {
Fleet fleet;
void servicePendingTxPower() {}
void servicePendingRxSettings() {}
Profiles profiles;
struct NoMorseReply {
void complete(const void*) {}
@@ -144,6 +145,7 @@ class Room : public mesh::Mesh {
void onGroupPacketRecv(mesh::Packet*);
void serviceFleet();
#if MESH_ENABLE_FLEET_CONTROL
void servicePendingPrimaryRadioSettings(bool) {}
void onSendComplete(mesh::Packet*) override;
void onSendFail(mesh::Packet*) override;
void onRadioProfileCopyQueued(mesh::Packet*, const mesh::Packet*, uint8_t) override;
+22 -8
View File
@@ -13,6 +13,7 @@ SANITIZER_FLAGS = [] if os.name == "nt" else ["-fsanitize=address,undefined", "-
PREAMBLE = r'''
#include <cassert>
#include <helpers/TempRadioReplyBarrier.h>
#include <cstdio>
#include <cstring>
#include <cstdint>
@@ -55,6 +56,7 @@ struct RadioProfileCLI {
}
bool acceptsPrimary(float, float, uint8_t, uint8_t, uint16_t) { return true; }
bool savePrimaryPreamble(uint16_t) { return true; }
bool restorePrimaryPreamble(uint16_t) { return true; }
uint16_t primaryPreamble() const { return 0; }
void appendSavedPreamble(char*, size_t, uint8_t, float) {}
void appendPrimaryChirpWarning(char*, size_t, uint8_t, float, uint16_t) const {}
@@ -91,7 +93,8 @@ struct Store {
bool formatFileSystem(){++erased;return success;}
};
struct Prefs {
uint8_t lost_reply=0;
uint8_t lost_reply=0, client_repeat=0;
bool rx_powersaving_enabled=false;
float tx_delay_factor=0.5f, direct_tx_delay_factor=0.2f;
uint8_t interference_threshold=0, agc_reset_interval=0;
float tz_offset=0;
@@ -101,7 +104,7 @@ struct Prefs {
int8_t tx_power_dbm=10;
char node_name[32]="test";
Prefs* getRadioPrefs(){return this;}
bool handleCommand(const char*,uint32_t,char*){return false;}
bool handleCommand(const char*,uint32_t,char*,bool=true){return false;}
bool isDirty() const {return false;}
void clearDirty(){}
};
@@ -116,7 +119,7 @@ struct Board {
bool supportsBatteryChargeTarget(uint16_t mv){return mv==4100 || mv==4200;}
bool setBatteryChargeTarget(uint16_t mv){++charge_writes;charge_target=mv;return true;}
bool rebootToUf2Bootloader(){return false;}
bool handleCommand(const char*,uint32_t,char*){return false;}
bool handleCommand(const char*,uint32_t,char*,bool=true){return false;}
void powerOff(){++power_offs;}
} board;
struct Radio {
@@ -134,7 +137,7 @@ struct Radio {
} radio_driver;
struct AdvertDataParser {static bool isValidName(const char*){return true;}};
struct StrHelper {static void strncpy(char* out,const char* in,size_t len){::strncpy(out,in,len);}};
void recalcRxPowerSavingFromLevel(uint8_t,uint8_t,float,uint8_t,uint32_t*,uint32_t*){}
bool recalcRxPowerSavingFromLevel(uint8_t,uint8_t,float,uint8_t,uint32_t*,uint32_t*){return true;}
struct StatsFormatHelper {
template<class... T> static void formatCoreStats(char* out,T&&...){strcpy(out,"core");}
template<class... T> static void formatRadioStats(char* out,T&&...){strcpy(out,"radio");}
@@ -146,7 +149,11 @@ struct WebConfigServer {
};
const char* FIRMWARE_VERSION="test";
const char* FIRMWARE_BUILD_DATE="test";
struct CommonRadioPrefs {static bool isValidBandwidth(float){return true;}};
struct MyMesh : CompanionFleetFixture {
mesh::TempRadioReplyBarrier _primary_radio_reply;
bool _primary_radio_blocked=false,_primary_radio_reply_admission=false;
mesh::MorseReplyHandoff _morse_reply;
bool _morse_reply_admission = false;
mesh::RadioProfileCLI _radio_profiles;
@@ -164,8 +171,13 @@ struct MyMesh : CompanionFleetFixture {
unsigned radio_apply_retry_at=0;
uint8_t radio_apply_failures=0;
int resets=0, saves=0;
enum class RadioSettingResult { Saved, RadioRejected, SaveFailed };
enum class RadioSettingResult { Saved, RadioRejected, SaveFailed, SaveUnconfirmed };
RadioSettingResult applyAndSaveTxPower(int8_t);
RadioSettingResult applyAndSaveRadioParams(float,float,uint8_t,uint8_t,uint8_t,uint16_t,bool=false);
void queueSavedRadioApply();
bool isValidClientRepeatFreq(uint32_t) const {return true;}
mesh::RadioParamApplyResult tryApplyRadioParams(float,float,uint8_t,uint8_t) {return mesh::RadioParamApplyResult::APPLIED;}
bool applySavedRadioParams(){return true;}
bool saveAdvertName(const char*);
bool handleCommand(const char*,uint32_t,char*);
bool handleDirectCommand(const char*,char*,size_t);
@@ -261,15 +273,15 @@ int main() {
}
assert(node.handleCommand("set freq 915.25",0,reply));
assert(!node._radio_profiles.remote_origin);
assert(node._prefs.freq==915.25f && strstr(reply,"reboot to apply"));
assert(node._prefs.freq==915.25f && !strncmp(reply,"OK",2));
assert(node.handleCommand("set freq 920",100,reply));
assert(node._radio_profiles.remote_origin);
assert(node._prefs.freq==920.0f && strstr(reply,"reboot to apply"));
assert(node._prefs.freq==920.0f && !strcmp(reply,"OK"));
for(uint32_t stamp:{0u,100u}) {
reply[0]=0;
node.onCLICommandRecv(ContactInfo{},nullptr,stamp,"A7|set freq 921.125",reply);
assert(node._radio_profiles.remote_origin); // even a zero-timestamp LoRa command
assert(node._prefs.freq==921.125f && !strcmp(reply,"A7|OK - reboot to apply"));
assert(node._prefs.freq==921.125f && !strcmp(reply,"A7|OK"));
assert(node._prefs.bw==125.0f && node._prefs.sf==7 && node._prefs.cr==5);
for(const char* bad:{"set freq 149.9","set freq 2500.1","set freq 920oops",
"set freq NaN","set freq inf","set freq 1e3","set freq "}) {
@@ -471,6 +483,8 @@ int main() {
implementation = "\n".join(extract_braced(source, signature) for signature in (
"static bool isCompanionRadioPrefsCommand(",
"MyMesh::RadioSettingResult MyMesh::applyAndSaveTxPower(",
"MyMesh::RadioSettingResult MyMesh::applyAndSaveRadioParams(",
"void MyMesh::queueSavedRadioApply(",
"bool MyMesh::saveAdvertName(",
"void MyMesh::onContactCacheFlushed()",
"bool MyMesh::handleDirectCommand(", "bool MyMesh::handleCommand(",
+4 -1
View File
@@ -172,10 +172,11 @@ struct CommonCLI {
Callbacks callbacks; Callbacks* _callbacks=&callbacks;
UserGpio _user_gpio;
struct Profiles { unsigned loops=0; void loop() { ++loops; } } _radio_profiles;
unsigned management=0, tx_services=0;
unsigned management=0, tx_services=0, rx_services=0;
void loopBatteryForwarding(bool = false) {}
void loopManagement() { ++management; }
void servicePendingTxPower() { ++tx_services; }
void servicePendingRxSettings() { ++rx_services; }
void loop();
};
@LOOP@
@@ -187,10 +188,12 @@ int main() {
const unsigned ordinary=mode==1 || mode==2 ? 0:1;
assert(cli._radio_profiles.loops==ordinary && cli.management==ordinary);
assert(cli.tx_services==ordinary);
assert(cli.rx_services==ordinary);
radio_driver.tx=radio_driver.rx=false;
cli.loop();
assert(cli._radio_profiles.loops==ordinary+1 && cli.management==ordinary+1);
assert(cli.tx_services==ordinary+1);
assert(cli.rx_services==ordinary+1);
assert(cli._user_gpio.loops==2 && cli.callbacks.completed==1);
}
}
+3
View File
@@ -72,6 +72,9 @@ class MQTTAccessPointOwnershipTest(unittest.TestCase):
def test_cold_start_and_repeated_restart_register_events_once(self):
self.run_fixture("cold_and_restart")
def test_changed_credentials_replace_connected_station_after_ownership_release(self):
self.run_fixture("changed_credentials")
def test_sdk_read_and_station_enable_failures_defer_and_retry(self):
self.run_fixture("failures")
+1
View File
@@ -197,6 +197,7 @@ struct MQTTBridge {
void* _identity = this;
bool _slots_setup_done = true;
bool _wifi_status_initialized = true, _manage_wifi = false;
bool _wifi_credentials_changed = false;
wl_status_t _last_wifi_status = WL_CONNECTED;
unsigned long _last_wifi_check = 0, _last_wifi_reconnect_attempt = 0;
uint8_t _wifi_reconnect_backoff_attempt = 0, _wifi_power_save = 1;
+2
View File
@@ -428,6 +428,7 @@ struct MQTTBridge {
std::atomic<bool> _stop_requested{false}, _stop_acked{false};
std::atomic<bool> _network_suspended{true};
bool _initialized = true, resources_owned = true;
bool _start_requested = false; uint32_t _start_retry_at = 0;
bool _slots_setup_done = true, _staged_raw_valid = true;
bool _ntp_estimate_requested = true, _ntp_estimate_done = true, _ntp_estimate_ok = true;
uint32_t _ntp_estimate_epoch = 123;
@@ -441,6 +442,7 @@ struct MQTTBridge {
mesh::wifi::networkPower().setSuspended(true);
}
void cancelNtpRefresh() { ++cancels; }
void begin() { assert(false); }
void requestStop();
void end();
void finishStopped();
+8 -14
View File
@@ -674,10 +674,8 @@ int main() {
self.assertIn(
"_delayed_replies.request.route == route", session_operations
)
self.assertIn(
"command_radio_reply_route == route", session_operations
)
self.assertIn("cancelPendingRadioParamApply();", session_operations)
self.assertNotIn("cancelPendingRadioParamApply", session_operations)
self.assertNotIn("saved_radio_apply_pending = false", session_operations)
self.assertIn("if (_cli_rescue)", session_operations)
self.assertIn(
"memset(cli_command, 0, sizeof(cli_command));",
@@ -712,16 +710,12 @@ int main() {
self.assertIn("serial->writeFrameToRoute(reply.route,", service)
self.assertNotRegex(service, r"serial->writeFrame\(")
self.assertNotIn("_serial->writeFrame(out_frame, i);", pending_writer)
self.assertIn(
"command_radio_reply_route = _serial->captureReplyRoute();",
mesh_source,
)
self.assertIn(
"isReplyRouteAvailable(command_radio_reply_route)", mesh_source
)
self.assertIn(
"isReplyRouteWriteBusy(command_radio_reply_route)", mesh_source
)
# Settings now acknowledge a durable target immediately. A host
# reconnect must not discard it or route an unrelated late reply.
radio_setter = extract_braced(mesh_source, 'if (cmd_frame[0] == CMD_SET_RADIO_PARAMS)')
self.assertIn("applyAndSaveRadioParams(", radio_setter)
self.assertNotIn("captureReplyRoute", radio_setter)
self.assertNotIn("command_radio_reply_route", mesh_source)
completion = source[
source.index("static void completePrimaryUsbSessionReset(") :
+51 -4
View File
@@ -26,6 +26,9 @@ HARNESS = r'''
#include <helpers/radiolib/NoiseFloorEstimator.h>
#include <helpers/radiolib/RXPowerSaving.h>
#include <helpers/TelemetryHistoryConfig.h>
#ifndef MESH_RECEIVE_HARNESS_HAS_DISPATCHER
namespace mesh { enum class RadioParamApplyResult : uint8_t { APPLIED, BUSY, FAILED }; }
#endif
#define STATE_IDLE 0
#define STATE_RX 1
#define STATE_TX_WAIT 3
@@ -85,7 +88,8 @@ struct RadioLibWrapper {
uint32_t _nf_published_at[2] = {}, _nf_published_generation[2] = {};
uint8_t _nf_published_valid = 0;
bool _cad_enabled = true, packet = false, busy = false, inject_arm_irq = false;
bool _rx_boosted_gain_valid = false, _cur_rx_boosted_gain = false, gain_apply_success = true;
bool _rx_boosted_gain_valid = false, _rx_boosted_gain_applied = false;
bool _cur_rx_boosted_gain = false, gain_apply_success = true, physical_gain = false;
bool _wd_last_busy = false;
uint8_t _startrx_fails = 0, _rx_mode_failures = 0;
uint32_t _rx_retry_at = 0;
@@ -125,10 +129,13 @@ struct RadioLibWrapper {
unsigned long getEstAirtimeFor(int) { return 10; }
void stopReceiveDutyCycle() { ++stops; _rx_ps_armed = false; }
void doResetAGC() { ++agc_resets; }
bool applyRxBoostedGainMode(bool) { ++gain_changes; return gain_apply_success; }
bool applyRxBoostedGainMode(bool enabled) {
++gain_changes; physical_gain = enabled; return gain_apply_success;
}
uint8_t beginReconfigure() { return 0; } // counted SPI/RX boundaries are separate
void endReconfigure(bool) {}
bool supportsRxPowerSaving() const { return true; }
bool supportsRxBoostedGainMode() const { return true; }
int startReceiveMode() {
++arms;
if (_nf_calib_active) ++calibration_arms;
@@ -146,7 +153,9 @@ struct RadioLibWrapper {
bool isChannelActive();
bool isReceivingPassive(int);
bool setRxPowerSaving(bool, uint32_t, uint32_t);
mesh::RadioParamApplyResult trySetRxPowerSaving(bool, uint32_t, uint32_t);
bool setRxBoostedGainMode(bool);
mesh::RadioParamApplyResult trySetRxBoostedGainMode(bool);
void startRecv();
void checkReceiveMode(uint32_t);
void loop();
@@ -343,12 +352,33 @@ static void periodicRefreshContracts() {
}
static void agcAdmissionContracts() {
{
using Result = mesh::RadioParamApplyResult;
RadioLibWrapper w;
w._rx_boosted_gain_valid = w._rx_boosted_gain_applied = true;
w.gain_apply_success = false;
assert(w.trySetRxBoostedGainMode(true) == Result::FAILED);
assert(!w._rx_boosted_gain_applied && w._rx_boosted_gain_valid && !w._cur_rx_boosted_gain);
assert(w.physical_gain); // Failure deliberately models a partial chip write.
const auto failed_writes = w.gain_changes;
w.gain_apply_success = true;
assert(w.trySetRxBoostedGainMode(false) == Result::APPLIED);
assert(w._rx_boosted_gain_applied && w._rx_boosted_gain_valid && !w._cur_rx_boosted_gain);
assert(!w.physical_gain);
assert(w.gain_changes == failed_writes + 1);
const auto repaired_writes = w.gain_changes;
assert(w.trySetRxBoostedGainMode(false) == Result::APPLIED);
assert(w.gain_changes == repaired_writes); // Verified matching gain is a true no-op.
w._cw_active = true;
assert(w.trySetRxBoostedGainMode(false) == Result::BUSY);
assert(w.gain_changes == repaired_writes);
}
unsigned cases = 0;
for (unsigned mode : {0U, 1U, 2U}) for (unsigned owned : {0U, 1U, 2U, 3U, 4U}) {
if (mode == 1 && owned == 1) continue; // known RXPS sleep has an explicit wake path
RadioLibWrapper w; selectMode(w, mode);
w._rx_ps_armed = mode == 1;
w._rx_boosted_gain_valid = w._cur_rx_boosted_gain = true;
w._rx_boosted_gain_valid = w._rx_boosted_gain_applied = w._cur_rx_boosted_gain = true;
w._nf_last_calib = now_ms;
w._nf_calib_deadline = now_ms + 800;
w._nf_sample_from = now_ms + NF_CALIB_SETTLE_MS;
@@ -416,7 +446,7 @@ static void agcAdmissionContracts() {
for (bool legacy : {false, true}) {
RadioLibWrapper w; selectMode(w, mode);
w._rx_ps_armed = mode == 1 && !active_window;
w._rx_boosted_gain_valid = w._cur_rx_boosted_gain = true;
w._rx_boosted_gain_valid = w._rx_boosted_gain_applied = w._cur_rx_boosted_gain = true;
w._noise_floor_valid = primary; w._noise_floor_secondary_valid = secondary;
w._nf_calib_active = active_window; w._nf_last_calib = now_ms;
w._nf_calib_deadline = now_ms + 800;
@@ -702,6 +732,8 @@ def transition_harness(source=None):
names = [('int16_t', 'performChannelScanWithTimeout'), ('bool', 'isPacketPendingOrReceiving'),
('bool', 'isChannelActive'), ('bool', 'isReceivingPassive'),
('bool', 'setRxPowerSaving'), ('bool', 'setRxBoostedGainMode'),
('mesh::RadioParamApplyResult', 'trySetRxPowerSaving'),
('mesh::RadioParamApplyResult', 'trySetRxBoostedGainMode'),
('void', 'startRecv'), ('void', 'checkReceiveMode'),
('void', 'loop'), ('void', 'triggerNoiseFloorCalibrate'),
('void', 'requestRestartRecv'), ('void', 'noiseFloorCalibCheck'),
@@ -886,6 +918,7 @@ int main() {
#include <initializer_list>
#include <helpers/CLICommandUtils.h>
#include <helpers/radiolib/RXPowerSaving.h>
namespace mesh { enum class RadioParamApplyResult : uint8_t { APPLIED, BUSY, FAILED }; }
struct NodePrefs {
uint8_t rx_powersaving_enabled = 1, rx_ps_level = 6, rx_ps_preamble = 32, sf = 8;
uint32_t rx_ps_rx_us = 40000, rx_ps_sleep_us = 32000;
@@ -895,11 +928,25 @@ struct Callbacks {
bool accept = true;
unsigned calls = 0;
bool setRxPowerSaving(bool, uint32_t, uint32_t) { ++calls; return accept; }
bool supportsRxPowerSaving() const { return true; }
};
struct CommonCLI {
NodePrefs* _prefs;
Callbacks* _callbacks;
unsigned saves = 0;
static constexpr uint8_t RxPowerSaving = 2;
uint8_t _rx_settings_pending = 0;
uint32_t _rx_settings_retry_at = 0;
mesh::RadioParamApplyResult applyRxSetting(uint8_t) {
return _callbacks->setRxPowerSaving(_prefs->rx_powersaving_enabled,
_prefs->rx_ps_rx_us, _prefs->rx_ps_sleep_us)
? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}
bool saveRxSetting(uint8_t, mesh::RadioParamApplyResult result, char*) {
if (result == mesh::RadioParamApplyResult::FAILED) return false;
++saves; return true;
}
void restoreRxSetting(uint8_t, mesh::RadioParamApplyResult, uint8_t, uint32_t) {}
void savePrefs() { ++saves; }
bool calculateRxPowerSavingLevel(uint32_t, uint8_t, float, uint32_t, uint32_t*, uint32_t*);
void set(const char* config, char* reply);
+3 -1
View File
@@ -47,6 +47,8 @@ class RadioReceiveRetryTests(unittest.TestCase):
('bool', 'isPacketPendingOrReceiving'), ('bool', 'isChannelActive'),
('bool', 'isReceivingPassive'), ('bool', 'setRxPowerSaving'),
('bool', 'setRxBoostedGainMode'), ('void', 'startRecv'),
('mesh::RadioParamApplyResult', 'trySetRxPowerSaving'),
('mesh::RadioParamApplyResult', 'trySetRxBoostedGainMode'),
('void', 'checkReceiveMode'), ('void', 'loop'),
('void', 'triggerNoiseFloorCalibrate'), ('void', 'requestRestartRecv'),
('void', 'noiseFloorCalibCheck'), ('void', 'endNoiseFloorCalib'),
@@ -66,7 +68,7 @@ class RadioReceiveRetryTests(unittest.TestCase):
settle = header[start:header.index('#endif', start) + len('#endif')]
harness = HARNESS[:HARNESS.index('int main() {')]
harness = harness.replace('#include <RadioProfiles.h>',
'#include <Dispatcher.h>\n#include <helpers/StaticPoolPacketManager.h>\n'
'#define MESH_RECEIVE_HARNESS_HAS_DISPATCHER 1\n#include <Dispatcher.h>\n#include <helpers/StaticPoolPacketManager.h>\n'
'#include <helpers/PowerManagementUtils.h>\n#define BD_STARTUP_RX_PACKET 1')
harness = harness.replace('struct RadioLibWrapper {', 'struct RadioLibWrapper : mesh::Radio {')
harness = harness.replace('Radio radio{&events}; Radio* _radio',
+11
View File
@@ -36,6 +36,7 @@ struct Mesh {
};
}
struct Profiles {
void servicePendingTuning() {}
bool pending = false, accepted = false;
unsigned completions = 0;
bool finishReplyMutation(bool delivered) {
@@ -44,7 +45,9 @@ struct Profiles {
};
struct CLI {
Profiles profiles;
void servicePendingRxSettings() {}
void servicePendingTxPower() {}
void servicePendingLocalRadioSettings() {}
struct NoMorseReply {
void complete(const void*) {}
void fail(const void*) {}
@@ -63,9 +66,15 @@ struct Manager {
};
struct MyMesh : mesh::Mesh {
CLI _cli;
void servicePendingRxSettings() {}
void servicePendingTxPower() {}
void servicePendingLocalRadioSettings() {}
Manager manager; Manager* _mgr = &manager;
mesh::TempRadioReplyBarrier temp_radio_reply_barrier;
mesh::TempRadioReplyBarrier _primary_radio_reply;
bool _primary_radio_blocked = false, _primary_radio_reply_admission = false;
void finishPrimaryRadioReply(bool) {}
void queueSavedRadioApply() {}
bool radio_reply_secondary = false, primary_radio_mutation_starts_temp = false;
uint32_t radio_reply_deadline = 0;
mesh::Packet* pending_battery_alert_packet = nullptr;
@@ -78,6 +87,8 @@ struct MyMesh : mesh::Mesh {
void cancelOutboundRadioRetry(const mesh::Packet* p) { assert(p == outbound); ++cancellations; }
void releasePacket(mesh::Packet*) { ++released; }
bool scheduleNormalRadio() { ++normal_schedules; return true; }
void processScheduledRadioSettings(bool) {}
void servicePendingPrimaryRadioSettings(bool) {}
void onSendComplete(mesh::Packet*) override;
void onSendFail(mesh::Packet*) override;
void onRadioProfileCopyQueued(mesh::Packet*, const mesh::Packet*, uint8_t) override;
+345
View File
@@ -0,0 +1,345 @@
"""Exercise actual infrastructure RX setters, checked saves, and pending service."""
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
def preprocess(source):
return subprocess.run([os.environ.get("CXX", "g++"), "-E", "-P", "-x", "c++",
"-DUSE_LR2021", "-"], input=source, text=True,
capture_output=True, check=True).stdout
def fixture():
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="ascii")
header = (ROOT / "src/helpers/CommonCLI.h").read_text(encoding="ascii")
methods = "\n".join(extract_braced(source, signature) for signature in (
"mesh::RadioParamApplyResult CommonCLI::applyRxSetting(",
"void CommonCLI::servicePendingRxSettings(", "bool CommonCLI::saveRxSetting(",
"void CommonCLI::restoreRxSetting(", "bool CommonCLI::trySavePrefs(",
"void CommonCLI::loop(", "bool CommonCLI::calculateRxPowerSavingLevel("))
setter = preprocess(extract_braced(source, "void CommonCLI::handleSetCmd("))
branches = [extract_braced(setter, signature) for signature in (
'if (memcmp(config, "radio.rxgain ", 13) == 0)',
'if (memcmp(config, "radio.rxps ", 11) == 0)',
'if (strncmp(config, "radio.rxps.rfrx_disabled ", 25) == 0)',
'if (strcmp(config, "extra.sf") == 0 || memcmp(config, "extra.sf ", 9) == 0)')]
values = {
"METHODS": preprocess(methods),
"SETTERS": preprocess(" else ".join(branches)),
"ENUM": extract_braced(header, "enum RxSetting : uint8_t") + ";",
"PENDING": extract_braced(header, "bool hasPendingRadioSettings() const"),
"NOTE": preprocess(extract_braced(source, "static void appendRxPowerSavingAdjustmentNote(")),
}
result = HARNESS
for key, value in values.items():
result = result.replace("@" + key + "@", value)
return result
HARNESS = r'''
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <deque>
#include <initializer_list>
#include <helpers/CLICommandUtils.h>
#include <helpers/PrefsSaveRouting.h>
#include <helpers/radiolib/RXPowerSaving.h>
#include <helpers/radiolib/LR2021SideDetectorConfig.h>
#define MIN_LOCAL_ADVERT_INTERVAL 60
static uint32_t now_ms = 1000;
uint32_t millis() { return now_ms; }
namespace mesh {
enum class RadioParamApplyResult : uint8_t { APPLIED, BUSY, FAILED };
struct Radio {
bool carrier = false, morse = false;
struct Profiles {
bool dual = false;
struct { uint8_t sf = 7; float bw = 125; } primary;
bool enabled() const { return dual; }
} profile_state;
const Profiles* profiles() const { return &profile_state; }
bool isCarrierWaveActive() const { return carrier; }
};
bool morseTimingActive(const Radio* radio) { return radio && radio->morse; }
}
using Result = mesh::RadioParamApplyResult;
struct Prefs {
uint8_t rx_boosted_gain = 0, rx_powersaving_enabled = 0;
uint32_t rx_ps_rx_us = RX_POWERSAVING_DEFAULT_RX_US;
uint32_t rx_ps_sleep_us = RX_POWERSAVING_DEFAULT_SLEEP_US;
uint8_t rx_ps_level = 0, rx_ps_preamble = 0, sf = 7, advert_interval = 0;
float bw = 125;
uint8_t extra_sf[4] = {};
void clearDirty() {}
};
using NodePrefs = Prefs;
class CommonCLI;
struct Callbacks {
CommonCLI* owner = nullptr;
mesh::Radio radio;
bool gain_supported = true, ps_supported = true, rf_supported = true;
bool transmitting = false, save_ok = true, acknowledge = true;
bool hardware_gain = false, hardware_rf = false;
RxPowerSavingConfig hardware_ps;
uint8_t hardware_sf[4] = {};
Prefs persisted;
unsigned saves = 0, gain_attempts = 0, ps_attempts = 0, sf_attempts = 0, rf_attempts = 0;
std::deque<Result> gain_results, ps_results, sf_results, rf_results;
Result admission(std::deque<Result>& results) {
if (transmitting) return Result::BUSY;
if (results.empty()) return Result::APPLIED;
Result result = results.front(); results.pop_front(); return result;
}
bool supportsRxBoostedGain() const { return gain_supported; }
bool supportsRxPowerSaving() const { return ps_supported; }
bool supportsRxPowerSavingRfRxDisable() const { return rf_supported; }
bool isRxPowerSavingRfRxDisabled() const { return hardware_rf; }
Result trySetRxBoostedGain(bool enabled) {
++gain_attempts; const Result result = admission(gain_results);
if (result != Result::BUSY) hardware_gain = enabled; // FAILED can be a partial write.
return result;
}
Result trySetRxPowerSaving(bool enabled, uint32_t rx, uint32_t sleep) {
++ps_attempts; const Result result = admission(ps_results);
if (result != Result::BUSY) hardware_ps = RxPowerSavingConfig(enabled, rx, sleep, 0, 0);
return result;
}
Result tryConfigSideDetectors(const uint8_t* sfs, uint8_t count, float) {
++sf_attempts; const Result result = admission(sf_results);
if (result != Result::BUSY) {
memset(hardware_sf, 0, sizeof(hardware_sf)); memcpy(hardware_sf, sfs, count);
}
return result;
}
Result trySetRxPowerSavingRfRxDisabled(bool disabled) {
++rf_attempts; const Result result = admission(rf_results);
if (result != Result::BUSY) hardware_rf = disabled;
return result;
}
mesh::Radio* getProfileRadio() { return &radio; }
void updateAdvertTimer() {}
void savePrefs(PrefsSaveRouting::Scope);
};
@NOTE@
class CommonCLI {
public:
@ENUM@
Prefs prefs;
Callbacks callbacks;
Prefs* _prefs = &prefs;
Callbacks* _callbacks = &callbacks;
uint8_t _rx_settings_pending = 0;
uint32_t _rx_settings_retry_at = 0;
bool _tx_power_pending = false, _common_save_result_known = false, _common_save_succeeded = false;
struct Profiles {
bool pending = false;
void loop() {}
bool hasPendingTuning() const { return pending; }
} _radio_profiles;
CommonCLI() { callbacks.owner = this; }
@PENDING@
void loopManagement() {}
void servicePendingTxPower() {}
void loop();
Result applyRxSetting(uint8_t);
void servicePendingRxSettings();
bool saveRxSetting(uint8_t, Result, char*);
void restoreRxSetting(uint8_t, Result, uint8_t, uint32_t);
bool trySavePrefs(PrefsSaveRouting::Scope scope = PrefsSaveRouting::Scope::Common);
bool calculateRxPowerSavingLevel(uint32_t, uint8_t, float, uint32_t, uint32_t*, uint32_t*);
void command(const char* input, char* reply) {
char buffer[160] = {};
strncpy(buffer, input, sizeof(buffer) - 1);
const char* config = buffer;
@SETTERS@
else strcpy(reply, "unknown config");
}
};
void Callbacks::savePrefs(PrefsSaveRouting::Scope scope) {
assert(scope == PrefsSaveRouting::Scope::Common); ++saves;
if (acknowledge) {
owner->_common_save_result_known = true;
owner->_common_save_succeeded = save_ok;
}
if (save_ok) persisted = owner->prefs;
}
@METHODS@
static bool ok(const char* reply) { return strncmp(reply, "OK", 2) == 0; }
int main() {
char reply[160];
{
CommonCLI cli;
for (const char* invalid : {"radio.rxgain banana", "radio.rxgain onjunk", "radio.rxgain off "}) {
cli.command(invalid, reply); assert(!ok(reply));
}
cli.callbacks.gain_supported = false;
cli.command("radio.rxgain on", reply);
assert(!ok(reply) && !cli.callbacks.gain_attempts && !cli.callbacks.saves && !cli.hasPendingRadioSettings());
cli.callbacks.ps_supported = false;
cli.prefs.rx_ps_rx_us = 0; cli.prefs.rx_ps_sleep_us = 0;
for (const char* value : {"radio.rxps banana", "radio.rxps 0 3000", "radio.rxps on"}) {
cli.command(value, reply); assert(!ok(reply));
assert(!cli.prefs.rx_ps_rx_us && !cli.prefs.rx_ps_sleep_us);
}
assert(!cli.callbacks.ps_attempts && !cli.callbacks.saves);
cli.command("extra.sf 99", reply);
assert(!ok(reply) && !cli.callbacks.sf_attempts && !cli.callbacks.saves);
cli.callbacks.radio.profile_state.dual = true;
cli.callbacks.transmitting = true;
cli.command("extra.sf 8", reply);
assert(!ok(reply) && !cli.callbacks.sf_attempts && !cli.callbacks.saves
&& !cli.hasPendingRadioSettings());
cli.callbacks.radio.profile_state.dual = false;
cli.callbacks.radio.profile_state.primary.sf = 8;
cli.command("extra.sf 8", reply);
assert(!ok(reply) && !cli.callbacks.sf_attempts && !cli.hasPendingRadioSettings());
cli.callbacks.rf_supported = false;
cli.command("radio.rxps.rfrx_disabled on", reply);
assert(!ok(reply) && !cli.callbacks.rf_attempts && !cli.hasPendingRadioSettings());
}
{
CommonCLI cli; cli.callbacks.transmitting = true;
cli.command("radio.rxgain on", reply);
assert(ok(reply) && strstr(reply, "pending") && cli.hasPendingRadioSettings());
assert(cli.prefs.rx_boosted_gain && cli.callbacks.persisted.rx_boosted_gain);
cli.command("radio.rxps 2000 3000", reply);
assert(ok(reply) && strstr(reply, "pending"));
cli.command("extra.sf 8,9", reply);
assert(ok(reply) && strstr(reply, "pending"));
assert(cli.callbacks.saves == 3);
cli.command("radio.rxps.rfrx_disabled on", reply);
assert(ok(reply) && strstr(reply, "pending") && cli.callbacks.saves == 3);
cli.loop(); assert(!cli.callbacks.hardware_gain && !cli.callbacks.hardware_ps.enabled);
cli.callbacks.transmitting = false;
cli.loop();
assert(!cli.hasPendingRadioSettings() && cli.callbacks.hardware_gain);
assert(cli.callbacks.hardware_ps.enabled && cli.callbacks.hardware_ps.rx_us == 2000);
assert(cli.callbacks.hardware_sf[0] == 8 && cli.callbacks.hardware_sf[1] == 9);
assert(cli.callbacks.hardware_rf && cli.callbacks.saves == 3);
cli.loop(); assert(cli.callbacks.saves == 3);
cli._radio_profiles.pending = true; assert(cli.hasPendingRadioSettings());
}
{
CommonCLI cli; cli.callbacks.transmitting = true;
cli.command("radio.rxgain on", reply);
cli.command("radio.rxgain off", reply);
cli.command("radio.rxps 2000 3000", reply);
cli.command("radio.rxps 4000 5000", reply);
cli.command("extra.sf 8", reply); cli.command("extra.sf 9", reply);
cli.command("radio.rxps.rfrx_disabled on", reply);
cli.command("radio.rxps.rfrx_disabled off", reply);
cli.callbacks.transmitting = false; cli.servicePendingRxSettings();
assert(!cli.hasPendingRadioSettings() && !cli.callbacks.hardware_gain && !cli.callbacks.hardware_rf);
assert(cli.callbacks.hardware_ps.rx_us == 4000 && cli.callbacks.hardware_sf[0] == 9);
assert(cli.callbacks.saves == 6 && cli.callbacks.persisted.rx_ps_rx_us == 4000);
}
{
CommonCLI cli;
cli.callbacks.save_ok = false;
cli.command("radio.rxgain on", reply);
assert(!ok(reply) && !cli.prefs.rx_boosted_gain && !cli.callbacks.hardware_gain);
cli.command("radio.rxps 2000 3000", reply);
assert(!ok(reply) && !cli.prefs.rx_powersaving_enabled && !cli.callbacks.hardware_ps.enabled);
assert(cli.prefs.rx_ps_rx_us == RX_POWERSAVING_DEFAULT_RX_US && cli.prefs.rx_ps_level == 0);
cli.command("extra.sf 8", reply);
assert(!ok(reply) && !cli.prefs.extra_sf[0] && !cli.callbacks.hardware_sf[0]);
assert(!cli.hasPendingRadioSettings());
cli.callbacks.save_ok = true; cli.callbacks.acknowledge = false;
cli.command("radio.rxgain on", reply);
assert(!ok(reply) && !cli.prefs.rx_boosted_gain && !cli.callbacks.hardware_gain);
}
{
CommonCLI cli; cli.callbacks.transmitting = true;
cli.command("radio.rxgain on", reply);
cli.callbacks.save_ok = false;
cli.command("radio.rxgain off", reply);
assert(!ok(reply) && cli.prefs.rx_boosted_gain && cli.hasPendingRadioSettings());
cli.callbacks.transmitting = false; cli.servicePendingRxSettings();
assert(cli.callbacks.hardware_gain && !cli.hasPendingRadioSettings() && cli.callbacks.saves == 2);
}
{
CommonCLI cli; cli.callbacks.gain_results = {Result::APPLIED, Result::BUSY};
cli.callbacks.save_ok = false;
cli.command("radio.rxgain on", reply);
assert(!ok(reply) && !cli.prefs.rx_boosted_gain && cli.hasPendingRadioSettings());
assert(cli.callbacks.hardware_gain);
cli.servicePendingRxSettings();
assert(!cli.callbacks.hardware_gain && !cli.hasPendingRadioSettings());
cli.callbacks.gain_results = {Result::FAILED, Result::FAILED};
cli.command("radio.rxgain on", reply);
assert(!ok(reply) && !cli.prefs.rx_boosted_gain && cli.hasPendingRadioSettings());
const unsigned attempts = cli.callbacks.gain_attempts;
cli.servicePendingRxSettings(); assert(cli.callbacks.gain_attempts == attempts);
now_ms += 1000; cli.servicePendingRxSettings();
assert(!cli.hasPendingRadioSettings() && !cli.callbacks.hardware_gain);
}
{
CommonCLI cli; cli.callbacks.radio.morse = true;
cli.command("radio.rxgain on", reply);
cli.command("radio.rxps 2000 3000", reply);
cli.command("extra.sf 8", reply);
cli.command("radio.rxps.rfrx_disabled on", reply);
cli.servicePendingRxSettings(); cli.loop();
assert(!cli.callbacks.gain_attempts && !cli.callbacks.ps_attempts
&& !cli.callbacks.sf_attempts && !cli.callbacks.rf_attempts);
cli.callbacks.radio.morse = false; cli.callbacks.radio.carrier = true;
cli.servicePendingRxSettings();
assert(!cli.callbacks.gain_attempts && !cli.callbacks.ps_attempts);
cli.callbacks.radio.carrier = false; cli.servicePendingRxSettings();
assert(!cli.hasPendingRadioSettings() && cli.callbacks.hardware_gain && cli.callbacks.hardware_rf);
assert(cli.callbacks.saves == 3);
}
{
CommonCLI cli;
cli.command("radio.rxps level 8 preamble 32", reply);
assert(ok(reply) && cli.prefs.rx_ps_level == 8 && cli.prefs.rx_ps_preamble == 32);
const auto old_rx = cli.prefs.rx_ps_rx_us;
cli.callbacks.save_ok = false;
cli.command("radio.rxps 2000 3000", reply);
assert(!ok(reply) && cli.prefs.rx_ps_level == 8 && cli.prefs.rx_ps_preamble == 32);
assert(cli.prefs.rx_ps_rx_us == old_rx && cli.callbacks.hardware_ps.rx_us == old_rx);
}
}
'''
class InfrastructureRxSettingsTests(unittest.TestCase):
def test_actual_commands_and_pending_transactions(self):
with tempfile.TemporaryDirectory(prefix="mesh-infra-rx-") as directory:
source, exe = Path(directory) / "test.cpp", Path(directory) / "test"
source.write_text(fixture(), encoding="ascii")
built = subprocess.run([
os.environ.get("CXX", "g++"), "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie",
"-I", str(ROOT / "src"), str(source), "-o", str(exe),
], text=True, capture_output=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
result = subprocess.run([str(exe)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_pending_radio_settings_keep_all_infrastructure_roles_awake(self):
for role, name in (("simple_repeater", "MyMesh"), ("simple_room_server", "MyMesh"),
("simple_sensor", "SensorMesh")):
with self.subTest(role=role):
source = (ROOT / "examples" / role / (name + ".cpp")).read_text(encoding="ascii")
header = (ROOT / "examples" / role / (name + ".h")).read_text(encoding="ascii")
self.assertIn("_cli.hasPendingRadioSettings()", extract_braced(
source, f"mesh::powerdiag::Mask {name}::pendingWorkReason() const"))
self.assertIn("!_cli.hasPendingRadioSettings()", extract_braced(
header, "bool canRecoverUsbLogging() const"))
tracker = (ROOT / "examples/simple_sensor/Tracker.cpp").read_text(encoding="ascii")
self.assertIn("_cli.hasPendingRadioSettings()", extract_braced(
tracker, "bool SensorMesh::trackerNeedsRadio() const"))
if __name__ == "__main__":
unittest.main()
+25 -7
View File
@@ -27,11 +27,24 @@ struct NodePrefs {
struct Callbacks {
RadioLibWrapper& radio_driver;
bool setRxPowerSaving(bool, uint32_t, uint32_t);
bool supportsRxPowerSaving() const { return radio_driver.supportsRxPowerSaving(); }
};
struct CommonCLI {
NodePrefs* _prefs;
Callbacks* _callbacks;
unsigned saves = 0;
static constexpr uint8_t RxPowerSaving = 2;
uint8_t _rx_settings_pending = 0;
uint32_t _rx_settings_retry_at = 0;
mesh::RadioParamApplyResult applyRxSetting(uint8_t) {
return _callbacks->radio_driver.trySetRxPowerSaving(_prefs->rx_powersaving_enabled,
_prefs->rx_ps_rx_us, _prefs->rx_ps_sleep_us);
}
bool saveRxSetting(uint8_t, mesh::RadioParamApplyResult result, char*) {
if (result == mesh::RadioParamApplyResult::FAILED) return false;
++saves; return true;
}
void restoreRxSetting(uint8_t, mesh::RadioParamApplyResult, uint8_t, uint32_t) {}
void savePrefs() { ++saves; }
bool calculateRxPowerSavingLevel(uint32_t,uint8_t,float,uint32_t,uint32_t*,uint32_t*);
void set(const char*, char*);
@@ -196,6 +209,7 @@ class RadioRxpsRejectionTest(unittest.TestCase):
('void', 'serviceProfileScan'), ('bool', 'setRxPowerSaving'),
('void', 'recalibrateNoiseFloor'), ('bool', 'validateProfile')]
names += [('mesh::RadioParamApplyResult', name) for name in (
'trySetRxPowerSaving',
'tuneProfile', 'prepareTransmitProfile', 'tryRestoreCodingRate',
'trySetParams', 'trySetPrimaryParams')]
methods = '\n'.join(method(source, f'{kind} RadioLibWrapper::{name}(')
@@ -220,6 +234,7 @@ class RadioRxpsRejectionTest(unittest.TestCase):
'_rx_ps_armed=supported && _rx_ps_enabled;')
harness = harness.replace(' void recalibrateNoiseFloor() { _noise_floor_valid=false; }',
' void recalibrateNoiseFloor();\n bool setRxPowerSaving(bool,uint32_t,uint32_t);\n'
' mesh::RadioParamApplyResult trySetRxPowerSaving(bool,uint32_t,uint32_t);\n'
+ method(header, 'bool isCalibratingNoiseFloor() const').replace(' override', ''))
harness = harness.replace('bool validateProfile(const mesh::RadioProfileParams& p) const { return mesh::RadioProfiles::valid(p); }',
'bool validateProfile(const mesh::RadioProfileParams&) const;')
@@ -229,16 +244,17 @@ class RadioRxpsRejectionTest(unittest.TestCase):
.replace('MyMesh::', 'Callbacks::'))
cases = cases.replace('@CALCULATOR@', method(common, 'bool CommonCLI::calculateRxPowerSavingLevel('))
cases = cases.replace('@CLI@', method(common, 'if (memcmp(config, "radio.rxps ", 11) == 0)'))
setter = method(source, 'bool RadioLibWrapper::setRxPowerSaving(')
guard = ' if (enabled && !supportsRxPowerSaving()) return false;\n'
setter = method(source, 'mesh::RadioParamApplyResult RadioLibWrapper::trySetRxPowerSaving(')
guard = '|| !supportsRxPowerSaving()'
if setter.count(guard) != 1:
raise AssertionError('expected actual early capability rejection')
suspended = method(setter, 'if (_profile_rxps_suspended)')
if suspended.count('return true;') != 1:
if suspended.count('return Result::APPLIED;') != 1:
raise AssertionError('expected actual accepted deferred branch')
legacy = setter.replace(guard, '', 1).replace(suspended,
suspended.replace('return true;', 'return !enabled || supportsRxPowerSaving();')
+ '\n ' + guard.strip(), 1)
suspended.replace('return Result::APPLIED;',
'return !enabled || supportsRxPowerSaving() ? Result::APPLIED : Result::FAILED;')
+ '\n if (enabled && !supportsRxPowerSaving()) return Result::FAILED;', 1)
sanitize = [] if not sys.platform.startswith('linux') else [
'-fsanitize=address,undefined', '-fno-sanitize-recover=all',
'-fno-omit-frame-pointer', '-fno-pie', '-no-pie']
@@ -296,8 +312,10 @@ class RadioRxpsRejectionTest(unittest.TestCase):
def test_original_suspended_branch_has_intended_semantic_failure(self):
# Outside-scan rejection is a healthy control for the historical code.
self.check_case('reject-outside', 'legacy')
for case in ('reject-inside', 'cli-inside'):
self.check_case(case, 'legacy', fails=True)
self.check_case('reject-inside', 'legacy', fails=True)
# The CLI now checks runtime capability before driver admission, so it
# independently prevents this historical driver's deferred-state bug.
self.check_case('cli-inside', 'legacy')
self.check_case('reject-restoration', 'legacy', fails=True,
diagnostic='rejected RXPS lost calibration request or sleep fence')
+12 -2
View File
@@ -185,7 +185,7 @@ public:
void updateFloodAdvertTimer();
void queueSavedRadioApply();
void refreshScheduledRadioState();
void processScheduledRadioSettings();
void processScheduledRadioSettings(bool tx_gap = false);
void applyTempRadioParams(float, float, uint8_t, uint8_t, int, uint16_t = 0);
bool scheduleNormalRadio();
void clearScheduledRadioSetting(int, bool);
@@ -235,6 +235,16 @@ int main() {
assert(radio_driver.active_gain == m._prefs.rx_boosted_gain);
assert(radio_driver.active_power == m._prefs.tx_power_dbm);
}
{ // Queue pressure must not postpone settings past a completed TX gap.
MyMesh m;
m.queueSavedRadioApply(); m.outbound = true;
m.processScheduledRadioSettings();
assert(m.saved_radio_apply_pending && m.scheduled_radio_retry_at);
assert(!m.scheduled_radio_retry_failures && !m.restores);
m.processScheduledRadioSettings(true);
assert(!m.saved_radio_apply_pending && !m.scheduled_radio_retry_at);
assert(m.restores == 1);
}
{ // A later failed due entry must not undo an earlier durable change.
MyMesh m;
char reply[160];
@@ -575,7 +585,7 @@ int main() {
"void MyMesh::queueSavedRadioApply()",
"bool MyMesh::applySavedRadioParams()",
"void MyMesh::refreshScheduledRadioState()",
"void MyMesh::processScheduledRadioSettings()",
"void MyMesh::processScheduledRadioSettings(bool tx_gap)",
"void MyMesh::applyTempRadioParams(",
"bool MyMesh::scheduleNormalRadio()",
"void MyMesh::clearScheduledRadioSetting(",
+89 -15
View File
@@ -22,6 +22,8 @@ HARNESS = r'''
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <cstring>
#include <helpers/radiolib/LR2021SideDetectorConfig.h>
// Negative controls must fail without opening a Windows CRT abort dialog.
#undef assert
#define assert(condition) do { if (!(condition)) { \
@@ -48,11 +50,20 @@ struct Driver {
bool _profile_repair_required = false, _profile_refresh_required = false;
bool _rx_hold_continuous = false;
bool _dbm_valid = true, _dbm_applied = true, _rx_boosted_gain_valid = false;
bool _rx_boosted_gain_applied = false;
int8_t _cur_dbm = 7;
bool _cur_rx_boosted_gain = false;
unsigned power_commands = 0, gain_commands = 0;
unsigned side_commands = 0;
uint8_t side_sfs[4] = {};
struct Profiles {
bool active = false;
bool enabled() const { return active; }
} profile_state;
const Profiles* profiles() const { return &profile_state; }
std::deque<int16_t> power_results;
std::deque<bool> gain_results;
std::deque<bool> side_results;
Chip* _radio = &chip;
bool hasPendingRadioInterrupt() { return pending_irq; }
bool claimRadioInterrupt() { const bool pending = pending_irq; pending_irq = false; return pending; }
@@ -64,19 +75,30 @@ struct Driver {
int16_t applyCachedTxPower(int8_t) {
++power_commands; return next(power_results, int16_t(0));
}
#if ROOM_ROLE
bool supportsRxBoostedGainMode() { return supported; }
bool applyRxBoostedGainMode(bool) {
assert(supported); ++gain_commands; return next(gain_results, true);
}
bool setRxBoostedGainMode(bool);
#endif
Apply trySetRxBoostedGainMode(bool);
bool supportsRxPowerSaving() { return true; }
uint8_t beginReconfigure();
void endReconfigure(bool);
bool setTxPower(int8_t);
bool isTxPowerValid(int8_t) const { return true; }
mesh::RadioParamApplyResult trySetTxPower(int8_t);
bool configSideDetectors(const uint8_t* sfs, uint8_t count, float) {
++side_commands;
const uint8_t resume = beginReconfigure();
if (resume > 1) return false;
const bool accepted = next(side_results, true);
if (accepted) {
memset(side_sfs, 0, sizeof(side_sfs));
if (count) memcpy(side_sfs, sfs, count);
}
endReconfigure(resume);
return accepted;
}
} radio_driver;
@WRAPPER_METHODS@
struct Prefs {
@@ -86,6 +108,7 @@ struct Prefs {
bool rx_boosted_gain = true, rx_powersaving_enabled = false;
uint8_t rx_ps_level = 0, rx_ps_preamble = 32;
uint32_t rx_ps_rx_us = 1234, rx_ps_sleep_us = 5678;
uint8_t extra_sf[4] = {10, 0, 0, 0};
};
struct Profiles {
float live_freq = 906.5f, live_bw = 125;
@@ -126,6 +149,8 @@ struct @CLASS@ {
bool saved_radio_apply_pending = false, temp_radio_applied = false, outbound = false;
uint32_t set_radio_at = 0, revert_radio_at = 0, radio_apply_retry_at = 0;
uint8_t radio_apply_failures = 0;
unsigned saves = 0;
void savePrefs() { ++saves; }
float pending_freq = 916.5f, pending_bw = 125;
uint8_t pending_sf = 8, pending_cr = 7, pending_preamble = 16;
@CLASS@() { now_ms = 100; radio_driver = Driver(); }
@@ -135,7 +160,7 @@ struct @CLASS@ {
uint32_t rxPowerSavingPreambleForParams(uint8_t, float) { return 32; }
bool applySavedRadioParams();
void startup() { @STARTUP@ }
void service() { @SERVICE@ }
void service(bool tx_gap = false) { @SERVICE@ }
};
@APPLY@
using Node = @CLASS@;
@@ -145,7 +170,7 @@ static void restored(const Node& node) {
assert(node._cli.profiles.live_sf == node._prefs.sf);
assert(node.active_cr == node._prefs.cr);
assert(radio_driver._cur_dbm == node._prefs.tx_power_dbm);
#if ROOM_ROLE
#if 1
if (radio_driver.supported)
assert(radio_driver._cur_rx_boosted_gain == node._prefs.rx_boosted_gain);
#endif
@@ -155,12 +180,10 @@ static unsigned calls(const Node& node) {
}
static void startupAndRetry() {
for (unsigned fault = 0; fault < 3; ++fault) {
#if !ROOM_ROLE
if (fault == 0) continue; // Sensor has no RX-gain feature.
#endif
Node node;
node._prefs.rx_powersaving_enabled = true;
#if ROOM_ROLE
#if 1
if (fault == 0) radio_driver.gain_results = {false, false, true};
#endif
if (fault == 1) node._cli.profiles.results = {Apply::BUSY, Apply::FAILED, Apply::APPLIED};
@@ -221,12 +244,10 @@ static void receiveBetweenTupleAndPower() {
}
static void tempRadioRestoration() {
for (bool pending : {false, true}) for (unsigned fault = 0; fault < 3; ++fault) {
#if !ROOM_ROLE
if (fault == 0) continue;
#endif
Node node; node.saved_radio_apply_pending = pending;
node.temp_radio_applied = true; node.revert_radio_at = now_ms - 1;
#if ROOM_ROLE
#if 1
if (fault == 0) radio_driver.gain_results = {false, true};
#endif
if (fault == 1) node._cli.profiles.results = {Apply::BUSY, Apply::APPLIED};
@@ -255,7 +276,48 @@ static void tempRadioRestoration() {
}
}
int main() {
#if defined(USE_LR2021)
{
Node node; node.startup();
assert(!node.saved_radio_apply_pending && radio_driver.side_sfs[0] == 10);
assert(radio_driver.side_commands == 1);
}
{
Node node; radio_driver.side_results = {false, true}; node.startup();
assert(node.saved_radio_apply_pending && "startup must retain incomplete saved radio work");
node.service(); assert(!node.saved_radio_apply_pending && radio_driver.side_sfs[0] == 10);
}
{
Node node; node._prefs.extra_sf[0] = radio_driver.side_sfs[0] = 7;
node.startup();
assert(!node.saved_radio_apply_pending && !node._prefs.extra_sf[0]);
assert(!radio_driver.side_sfs[0] && node.saves == 1 && radio_driver.side_commands == 2);
}
{
Node node; radio_driver.profile_state.active = true; node.startup();
assert(!node.saved_radio_apply_pending && !radio_driver.side_commands);
assert(node._prefs.extra_sf[0] == 10); // Retain saved intent while dual radio disables it.
}
#endif
startupAndRetry(); receiveBetweenTupleAndPower(); tempRadioRestoration();
{
Node node;
node.outbound = true;
node.set_radio_at = now_ms - 1;
node.revert_radio_at = now_ms + 10000;
node.service(true);
assert(!calls(node) && !node.temp_radio_applied && node.set_radio_at);
node.outbound = false; node.service();
assert(node.temp_radio_applied && !node.set_radio_at);
}
{
Node node;
node.outbound = true;
node.saved_radio_apply_pending = true;
node.service(); assert(!calls(node));
node.service(true); // A queued next packet cannot starve the completed-TX gap.
assert(!node.saved_radio_apply_pending); restored(node);
}
std::puts("PASS: production saved radio startup/retry/TempRadio restoration");
}
'''
@@ -273,6 +335,10 @@ def harness(role, mutation=None):
checked = "&& !radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain)) return false;"
assert checked in apply
apply = apply.replace(checked, ") (void)radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);")
elif mutation == "unchecked-side":
checked = "&& !radio_driver.configSideDetectors(_prefs.extra_sf, extra_sf_count, _prefs.bw)) return false;"
assert checked in apply
apply = apply.replace(checked, ") (void)radio_driver.configSideDetectors(_prefs.extra_sf, extra_sf_count, _prefs.bw);")
begin = body(source, f"void {name}::begin(")
start = begin.index(" saved_radio_apply_pending = !applySavedRadioParams();")
startup = begin[start:begin.index(" const bool fem_gain_changed", start)]
@@ -284,8 +350,8 @@ def harness(role, mutation=None):
"void RadioLibWrapper::endReconfigure(bool resume_rx)",
"bool RadioLibWrapper::setTxPower(int8_t dbm)",
"mesh::RadioParamApplyResult RadioLibWrapper::trySetTxPower(int8_t dbm)"]
if role == "room":
signatures.append("bool RadioLibWrapper::setRxBoostedGainMode(bool enabled)")
signatures.extend(["bool RadioLibWrapper::setRxBoostedGainMode(bool enabled)",
"mesh::RadioParamApplyResult RadioLibWrapper::trySetRxBoostedGainMode(bool enabled)"])
methods = "\n".join(body(wrapper, signature) for signature in signatures)
methods = methods.replace("RadioLibWrapper::", "Driver::")
values = {
@@ -300,7 +366,7 @@ def harness(role, mutation=None):
class RoomSensorRadioRestoreTests(unittest.TestCase):
def run_case(self, role, mutation=None):
def run_case(self, role, mutation=None, lr2021=False):
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
self.assertIsNotNone(compiler)
with tempfile.TemporaryDirectory(prefix="room-sensor-radio-restore-") as folder:
@@ -310,6 +376,8 @@ class RoomSensorRadioRestoreTests(unittest.TestCase):
flags = [] if os.name == "nt" else ["-fsanitize=address,undefined", "-fno-pie", "-no-pie"]
built = subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
f"-DROOM_ROLE={int(role == 'room')}", *flags,
*(["-DUSE_LR2021=1"] if lr2021 else []),
"-I", str(ROOT / "src"),
str(cpp), "-o", str(binary)],
capture_output=True, text=True, timeout=45)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
@@ -334,6 +402,12 @@ class RoomSensorRadioRestoreTests(unittest.TestCase):
def test_old_unchecked_room_gain_cannot_complete(self):
self.run_case("room", "unchecked-gain")
def test_lr2021_saved_detectors_restore_or_keep_recovery_pending(self):
for role in ROLES:
with self.subTest(role=role):
self.run_case(role, lr2021=True)
self.run_case(role, "unchecked-side", lr2021=True)
if __name__ == "__main__":
unittest.main()
+4
View File
@@ -166,6 +166,10 @@ struct WebConfigServer {
struct Terminal { bool running = false; struct { bool pending = false; } queue; };
Terminal* _terminal = nullptr;
bool _stopping = false, _stop_warned = false, _board_cmds_probed = true;
int _start_mode = MODE_OFF;
uint32_t _start_retry_at = 0, _start_retry_delay = 5000;
bool _start_retryable = false;
void serviceStartRetry(uint32_t) {}
uint32_t _handler_refs = 0, _stop_warn_at = 0, _last_activity = 0;
uint32_t _network_activity_until = 0;
std::mutex mutex;
+5 -4
View File
@@ -43,6 +43,7 @@ class RS232MQTTRuntimeTests(unittest.TestCase):
"bool startSharedEspNowBridgeIfReady()", "bool isEspNowBridgeRunning()",
"bool setEspNowBridgeState(bool enable)", "bool restartEspNowBridge()",
"bool isMqttBridgeRunning()", "bool requestMqttBridgeStop()", "bool isMqttBridgeStopping()",
"bool isMqttBridgeStartPending()",
"bool setMqttBridgeState(bool enable)",
"bool restartMqttBridge()", "bool setBridgeState(bool enable)", "bool restartBridge()",
))
@@ -141,7 +142,7 @@ class RS232MQTTRuntimeTests(unittest.TestCase):
"bool rs232BridgeEnabled() const", "bool isBridgeRunning() const override",
"bool isRs232BridgeRunning()", "bool setRs232BridgeState(bool enable)",
"bool restartRs232Bridge()", "bool isMqttBridgeRunning()", "bool requestMqttBridgeStop()",
"bool isMqttBridgeStopping()", "bool setBridgeState(bool enable)",
"bool isMqttBridgeStopping()", "bool isMqttBridgeStartPending()", "bool setBridgeState(bool enable)",
"bool restartBridge()"))
code = (ROOT / "test/fixtures/rs232_mqtt_runtime.cpp").read_text(encoding="ascii")
code = code[:code.index("int main() {")]
@@ -225,10 +226,10 @@ class RS232MQTTRuntimeTests(unittest.TestCase):
assert(!mesh.bridge && !mesh.isMqttBridgeRunning() && !mesh.bridgesPreventSleep());
cli.set("rs232.enabled on", reply); mesh.mqtt_bridge->fail_starts = 1;
cli.set("mqtt.enabled on", reply);
assert(strstr(reply, "setting saved") && !mesh.isMqttBridgeRunning());
assert(!strcmp(reply, "OK") && !mesh.isMqttBridgeRunning() && mesh.isMqttBridgeStartPending());
assert(mesh.isRs232BridgeRunning() && mesh.bridgesPreventSleep());
cli.set("mqtt.enabled on", reply);
assert(strcmp(reply, "OK") == 0 && mesh.isMqttBridgeRunning());
mesh.serviceBridges(); // Automatic start retries without another CLI attempt.
assert(mesh.isMqttBridgeRunning() && !mesh.isMqttBridgeStartPending());
}'''
with tempfile.TemporaryDirectory(prefix="rs232-mqtt-only-") as directory:
work = Path(directory)
+15 -1
View File
@@ -45,11 +45,25 @@ struct NodePrefs {
};
struct Callbacks {
unsigned calls=0;
bool supportsRxPowerSaving() const { return false; }
bool setRxPowerSaving(bool on,uint32_t,uint32_t){++calls;return !on;}
};
struct CommonCLI {
NodePrefs* _prefs; Callbacks* _callbacks; unsigned saves=0;
CommonCLI(NodePrefs& p,Callbacks& c):_prefs(&p),_callbacks(&c){}
static constexpr uint8_t RxPowerSaving = 2;
uint8_t _rx_settings_pending = 0;
uint32_t _rx_settings_retry_at = 0;
mesh::RadioParamApplyResult applyRxSetting(uint8_t) {
return _callbacks->setRxPowerSaving(_prefs->rx_powersaving_enabled,
_prefs->rx_ps_rx_us, _prefs->rx_ps_sleep_us)
? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
}
bool saveRxSetting(uint8_t, mesh::RadioParamApplyResult result, char*) {
if (result == mesh::RadioParamApplyResult::FAILED) return false;
++saves; return true;
}
void restoreRxSetting(uint8_t, mesh::RadioParamApplyResult, uint8_t, uint32_t) {}
static bool calculateRxPowerSavingLevel(uint32_t,uint8_t,float,uint32_t,uint32_t*,uint32_t*);
static bool recalculateRxPowerSavingFromLevel(NodePrefs*);
void savePrefs(){++saves;}
@@ -177,7 +191,7 @@ int main() {
common = (ROOT / 'src/helpers/CommonCLI.cpp').read_text()
setter = body(common, 'if (memcmp(config, "radio.rxps ", 11) == 0)')
if mutate:
guard = body(setter, 'if (!WRAPPER_CLASS::SupportsRxPowerSaving)')
guard = body(setter, 'if (!_callbacks->supportsRxPowerSaving()')
setter = setter.replace(guard, '', 1)
code = HARNESS.replace('@SETTER@', setter)
code = code.replace('@GETTER@', body(common, 'if (strcmp(config, "radio.rxps.config") == 0)'))
+24
View File
@@ -15,6 +15,7 @@ HARNESS = r'''
#include <cstdio>
#include <string>
#include <helpers/radiolib/RXPowerSaving.h>
namespace mesh { enum class RadioParamApplyResult : uint8_t { APPLIED, BUSY, FAILED }; }
#define MESH_ENABLE_TX_BEACONS 1
#define MESH_DEBUG_PRINTLN(...) ((void)0)
@@ -29,6 +30,7 @@ struct RadioLibWrapper {
bool _rx_ps_enabled = true, _rx_ps_armed = false;
bool _rx_ps_continuous_fallback = false, _nf_calib_active = false;
bool _profile_rxps_suspended = false;
bool _profile_repair_required = false;
bool _profile_saved_rxps = false, _beacon_owned = false, _cw_active = false;
uint32_t _rx_ps_rx_us = 50000, _rx_ps_sleep_us = 50000;
uint32_t _rx_ps_eff_rx_us = 0, _rx_ps_eff_sleep_us = 0;
@@ -72,6 +74,7 @@ struct RadioLibWrapper {
int startReceivePowerSaving();
void stopReceiveDutyCycle();
bool setRxPowerSaving(bool, uint32_t, uint32_t);
mesh::RadioParamApplyResult trySetRxPowerSaving(bool, uint32_t, uint32_t);
RxPowerSavingStatus getRxPowerSavingStatus() const;
@RESET_STATS@
};
@@ -98,6 +101,26 @@ static void exhaust(RadioLibWrapper& radio) {
}
int main() {
{
using Result = mesh::RadioParamApplyResult;
RadioLibWrapper radio;
assert(radio.trySetRxPowerSaving(true, 50000, 50000) == Result::APPLIED);
assert(!radio.begin_calls && !radio.end_calls); // Same accepted timings do not re-arm RX.
radio.reconfigure_result = 2;
assert(radio.trySetRxPowerSaving(true, 70000, 90000) == Result::BUSY);
assert(radio._rx_ps_rx_us == 50000 && !radio.end_calls);
radio.reconfigure_result = 3;
assert(radio.trySetRxPowerSaving(true, 70000, 90000) == Result::FAILED);
assert(radio._rx_ps_rx_us == 50000 && !radio.end_calls);
radio.supported = false;
const unsigned before = radio.begin_calls;
assert(radio.trySetRxPowerSaving(true, 70000, 90000) == Result::FAILED);
assert(radio.trySetRxPowerSaving(true, 0, 90000) == Result::FAILED);
assert(radio.begin_calls == before);
radio.supported = true; radio._cw_active = true;
assert(radio.trySetRxPowerSaving(true, 50000, 50000) == Result::BUSY);
assert(radio.begin_calls == before);
}
{
RadioLibWrapper radio;
exhaust(radio);
@@ -214,6 +237,7 @@ def production_source():
"int RadioLibWrapper::startReceivePowerSaving()",
"void RadioLibWrapper::stopReceiveDutyCycle()",
"bool RadioLibWrapper::setRxPowerSaving(",
"mesh::RadioParamApplyResult RadioLibWrapper::trySetRxPowerSaving(",
"RxPowerSavingStatus RadioLibWrapper::getRxPowerSavingStatus()"))
return HARNESS.replace("@METHODS@", methods).replace(
"@RESET_STATS@", body(header, "void resetStats()"))
+1 -1
View File
@@ -34,7 +34,7 @@ struct Radio {bool watchdog=false,calibration=false;
struct Cli {
bool gpio=false,tx_pending=false;
bool hasActiveUserGpioTimer()const{return gpio;}
bool hasPendingTxPower()const{return tx_pending;}
bool hasPendingRadioSettings()const{return tx_pending;}
};
struct Manager {int queued=0;int getOutboundTotal()const{return queued;}};
struct Clock {uint32_t now=100;uint32_t getCurrentTime()const{return now;}};
+303
View File
@@ -0,0 +1,303 @@
"""Execute service start intent, bounded retries and explicit cancellation."""
from pathlib import Path
import unittest
from test_replay_reset_integration import extract_braced
import test_wifi_ota_start as wifi_start
import test_mqtt_transport_results as mqtt
ROOT = Path(__file__).resolve().parents[1]
WEB = r'''
#include <cassert>
#include <cstdint>
#include <cstring>
#include <helpers/WebConfigBatch.h>
uint32_t now = 1000;
uint32_t millis() { return now; }
namespace mesh {
namespace wireless {
enum { WiFi = 1 };
struct Control { bool disabled = false; bool blocked(int) { return disabled; } };
Control& control() { static Control c; return c; }
}
namespace wifi {
bool compatible = true;
bool accessPointCompatibleWithLongRange() { return compatible; }
}
struct Log { void println(const char*) {} };
Log& usbDebugPort() { static Log log; return log; }
}
struct Endpoint { unsigned stops = 0; void end() { ++stops; } void stop() { ++stops; } };
struct WebConfigServer {
enum Mode { MODE_OFF, MODE_SETUP, MODE_CONNECTING, MODE_LAN };
Mode _mode = MODE_OFF, _start_mode = MODE_OFF;
uint32_t _start_retry_at = 0, _start_retry_delay = 5000;
bool _start_retryable = false, _stopping = false, _stop_warned = false;
uint32_t _stop_warn_at = 0;
static constexpr unsigned STOP_WARN_MS = 1000;
Endpoint server, dns; Endpoint* _server = &server; Endpoint* _dns = &dns;
char _wifi_ssid[32] = {};
bool fail_start = false, invalid = false;
unsigned starts = 0; bool last_ap = false; char last_ssid[32] = {};
bool isRunning() const { return _mode != MODE_OFF; }
bool isStopping() const { return _stopping; }
bool isStartPending() const { return _start_mode != MODE_OFF; }
void detachRoutes() {}
void refreshNetworkPowerHold(uint32_t) {}
bool start(bool ap, char* reply) {
++starts; last_ap = ap; strcpy(last_ssid, _wifi_ssid);
_start_retryable = fail_start && !invalid;
if (fail_start || invalid) { strcpy(reply, "Err: startup failed"); return false; }
_mode = ap ? MODE_SETUP : MODE_CONNECTING;
strcpy(reply, "WebConfig started"); return true;
}
bool startSetupMode(char* reply) { return start(true, reply); }
bool startAutoMode(char* reply) { return start(false, reply); }
bool requestStart(bool, char*);
void requestRestart(); void requestStop(); void serviceStartRetry(uint32_t);
};
@METHODS@
int main() {
char reply[160]; WebConfigServer s;
s.fail_start = true;
assert(s.requestStart(true, reply) && s.isStartPending() && s.starts == 1);
assert(strstr(reply, "pending"));
for (unsigned i = 0; i < 100; ++i) s.serviceStartRetry(now);
assert(s.starts == 1);
now = s._start_retry_at - 1; s.serviceStartRetry(now); assert(s.starts == 1);
++now; s.serviceStartRetry(now); assert(s.starts == 2);
assert(s._start_retry_at == now + 10000);
for (unsigned i = 0; i < 8; ++i) {
now = s._start_retry_at; s.serviceStartRetry(now);
assert(s._start_retry_at > now && s._start_retry_at <= now + 60000);
}
s.fail_start = false; now = s._start_retry_at; s.serviceStartRetry(now);
assert(s.isRunning() && !s.isStartPending() && s.last_ap);
// Off/on during teardown waits for cleanup and never loses desired on.
s.requestStop(); const auto before = s.starts;
assert(s.requestStart(false, reply) && s.isStartPending());
now = s._start_retry_at; s.serviceStartRetry(now); assert(s.starts == before);
s._stopping = false; s.serviceStartRetry(now);
assert(s.starts == before + 1 && !s.last_ap && !s.isStartPending());
// SSID/password writes share one restart with the newest saved tuple.
strcpy(s._wifi_ssid, "first"); s.requestRestart();
now += 500; strcpy(s._wifi_ssid, "latest"); s.requestRestart();
s._stopping = false; now += 999; s.serviceStartRetry(now);
assert(s.starts == before + 1);
++now; s.serviceStartRetry(now);
assert(s.starts == before + 2 && !strcmp(s.last_ssid, "latest"));
// Explicit off cancels both a deferred teardown restart and a failed start.
s.requestRestart(); s.requestStop();
s.requestRestart(); // A credential save during explicit off must stay off.
assert(!s.isStartPending()); s._stopping = false;
now += 120000; s.serviceStartRetry(now);
assert(!s.isStartPending() && s.starts == before + 2);
s.fail_start = true; assert(s.requestStart(true, reply)); s.requestStop();
now += 120000; s.serviceStartRetry(now); assert(!s.isStartPending());
// Configuration and ownership conflicts remain errors, not accepted jobs.
s.fail_start = false; s.invalid = true;
assert(!s.requestStart(false, reply) && !s.isStartPending()); s.invalid = false;
mesh::wireless::control().disabled = true;
assert(!s.requestStart(false, reply) && !s.isStartPending());
mesh::wireless::control().disabled = false; mesh::wifi::compatible = false;
assert(!s.requestStart(true, reply) && !s.isStartPending());
mesh::wifi::compatible = true;
// Retry deadlines remain correct when millis() wraps.
now = UINT32_MAX - 500; s.fail_start = true; assert(s.requestStart(true, reply));
const auto attempts = s.starts;
now += 4999; s.serviceStartRetry(now); assert(s.starts == attempts);
++now; s.fail_start = false; s.serviceStartRetry(now);
assert(s.starts == attempts + 1 && !s.isStartPending());
}
'''
class ServiceStartRetryTests(unittest.TestCase):
compile_and_run = wifi_start.WiFiOtaStartTest.compile_and_run
def test_webconfig_retry_coalescing_cancellation_conflicts_and_rollover(self):
source = (ROOT / 'src/helpers/esp32/WebConfigServer.cpp').read_text()
methods = '\n'.join(extract_braced(source, signature) for signature in (
'bool WebConfigServer::requestStart(', 'void WebConfigServer::requestRestart(',
'void WebConfigServer::requestStop(', 'void WebConfigServer::serviceStartRetry('))
self.compile_and_run(WEB.replace('@METHODS@', methods))
def test_pending_starts_are_owned_work_without_claiming_mqtt_running(self):
for role, worker in (('simple_repeater', 'mqtt_bridge'),
('simple_room_server', 'bridge')):
with self.subTest(role=role):
header = (ROOT / 'examples' / role / 'MyMesh.h').read_text()
methods = '\n'.join(extract_braced(header, signature).replace(' override', '')
for signature in ('bool isWebConfigActive() const',
'bool isMqttBridgeRunning()',
'bool isMqttBridgeStartPending()'))
fixture = r'''
#include <cassert>
struct Service {
bool running = false, stopping = false, pending = true;
bool isRunning() const { return running; }
bool isStopping() const { return stopping; }
bool isStartPending() const { return pending; }
} web, mqtt;
struct MyMesh {
Service* _webconfig = &web;
Service* @WORKER@ = &mqtt;
@METHODS@
};
int main() {
MyMesh node;
assert(node.isWebConfigActive());
assert(!node.isMqttBridgeRunning() && node.isMqttBridgeStartPending());
web.pending = mqtt.pending = false;
assert(!node.isWebConfigActive() && !node.isMqttBridgeStartPending());
}
'''.replace('@METHODS@', methods).replace('@WORKER@', worker)
self.compile_and_run(fixture, '-DWITH_MQTT_BRIDGE=1')
def test_companion_credential_reload_finishes_with_a_restarted_lan_listener(self):
source = (ROOT / 'examples/companion_radio/main.cpp').read_text()
actual = extract_braced(source, 'static void serviceCompanionWiFiCredentialReload(')
fixture = r'''
#include <cassert>
#include <cstdint>
#include <cstring>
#define WITH_WEBCONFIG 1
#define WIFI_DEBUG_PRINTLN(...) ((void)0)
uint32_t now = 1000;
uint32_t millis() { return now; }
bool companion_wifi_credential_reload_pending = true;
uint32_t companion_wifi_credential_reload_at = 1500;
bool companion_wifi_espnow_restore_pending = true;
bool companion_wifi_requested = true, companion_wifi_active = true;
bool companion_wifi_has_credentials = true;
char configured_wifi_ssid[32] = {}, configured_wifi_password[65] = {};
const char* saved_ssid = "latest", *saved_password = "latest-password";
bool suspended = false, station_allowed = true;
bool companionWiFiBackgroundSuspended() { return suspended; }
void loadCompanionWiFiCredentials() {
strcpy(configured_wifi_ssid, saved_ssid);
strcpy(configured_wifi_password, saved_password);
}
void resetCompanionWiFiRecoveryState() {}
struct {
bool transition = false, active = true;
bool isWebConfigWiFiTransitionActive() const { return transition; }
bool isWebConfigActiveOrStopping() const { return active; }
} the_mesh;
constexpr int WIFI_STA = 1, WIFI_IF_STA = 0;
struct { void mode(int) {} void disconnect(bool, bool) {} } WiFi;
namespace mesh { namespace wifi {
unsigned starts = 0;
bool stationMutationAllowed() { return station_allowed; }
void applyProtocolMask(int) {} void setStationAutoReconnect(bool) {}
void beginStation(const char* ssid, const char* password) {
++starts; assert(!strcmp(ssid, "latest")); assert(!strcmp(password, "latest-password"));
}
} }
struct { void noteAttempt(uint32_t) {} } wifi_reconnect_tracker;
@METHOD@
int main() {
serviceCompanionWiFiCredentialReload(); assert(companion_wifi_credential_reload_pending);
now = 1500; the_mesh.transition = true;
serviceCompanionWiFiCredentialReload(); assert(companion_wifi_credential_reload_pending);
the_mesh.transition = false; // The LAN listener is active, but does not own association.
assert(the_mesh.isWebConfigActiveOrStopping());
serviceCompanionWiFiCredentialReload();
assert(!companion_wifi_credential_reload_pending && !companion_wifi_espnow_restore_pending);
assert(mesh::wifi::starts == 1);
serviceCompanionWiFiCredentialReload(); assert(mesh::wifi::starts == 1);
}
'''.replace('@METHOD@', actual)
self.compile_and_run(fixture)
def test_mqtt_reenable_waits_for_cleanup_and_failed_start_retries_without_leaks(self):
source = (ROOT / 'src/helpers/bridges/MQTTBridge.cpp').read_text()
# Execute the real begin admission and complete queue/task acquisition,
# rollback and commit. Endpoint parsing between them has its own tests.
begin = extract_braced(source, 'void MQTTBridge::begin()')
admission = begin[:begin.index(' cancelNtpRefresh();')]
resources = begin[begin.index(' // Reset the handshake'):]
begin = admission + ' ++starts; allocateRuntimeBuffers();\n' + resources
preamble = mqtt.ASYNC_STOP_PREAMBLE.replace(' void begin() { assert(false); }', r'''
unsigned starts = 0;
void* _packet_queue_handle = nullptr; uint8_t* _packet_queue_storage = nullptr;
int _packet_queue_struct = 0; void* _mqtt_task_handle = nullptr;
struct QueuedPacket { uint8_t data[8]; };
static constexpr unsigned MAX_QUEUE_SIZE = 4;
static void mqttTask(void*) {}
void allocateRuntimeBuffers() { resources_owned = true; }
void releaseRuntimeBuffers() { resources_owned = false; }
void begin(); void requestRestart();
''')
allocator = r'''
#include <cstdlib>
#define BOARD_HAS_PSRAM 1
using BaseType_t = int;
constexpr int pdPASS = 1;
bool fail_queue = false, fail_task = false;
unsigned storage_live = 0, queues_live = 0;
void* psram_malloc(size_t n) { ++storage_live; return malloc(n); }
void psram_free(void* p) { if (p) { --storage_live; free(p); } }
void* xQueueCreateStatic(unsigned, size_t, uint8_t*, int*) {
if (fail_queue) return nullptr; ++queues_live; return malloc(1);
}
void* xQueueCreate(unsigned n, size_t size) { return xQueueCreateStatic(n, size, nullptr, nullptr); }
void vQueueDelete(void* p) { assert(p); --queues_live; free(p); }
int xTaskCreatePinnedToCore(void (*)(void*), const char*, unsigned, void*, unsigned, void** task, int) {
*task = fail_task ? nullptr : reinterpret_cast<void*>(1); return fail_task ? 0 : pdPASS;
}
'''
# The fake endpoint's release effect owns the same queue/storage that
# the production begin block acquires; lifecycle ordering stays real.
preamble = preamble.replace('struct MQTTBridge;', allocator + '\nstruct MQTTBridge;', 1)
preamble = preamble.replace(' _b->resources_owned = false;', ''' _b->resources_owned = false;
if (_b->_packet_queue_handle) vQueueDelete(_b->_packet_queue_handle);
_b->_packet_queue_handle = nullptr;
psram_free(_b->_packet_queue_storage); _b->_packet_queue_storage = nullptr;''')
methods = '\n'.join(extract_braced(source, signature) for signature in (
'static inline uint32_t mqttStopTimeoutForSlots(int slots)',
'void MQTTBridge::requestStop()', 'void MQTTBridge::requestRestart()',
'void MQTTBridge::end()', 'void MQTTBridge::finishStopped()',
'void MQTTBridge::loop()', 'uint32_t MQTTBridge::LifecycleOps::nowMs()',
'void MQTTBridge::LifecycleOps::startTask()',
'void MQTTBridge::LifecycleOps::deliverStop()'))
scenarios = r'''
int main() {
MQTTBridge b; bridge_waiting = &b;
b.requestStop(); b.begin(); // A fresh on request cannot cancel an active worker stop.
assert(b._start_requested && b._lifecycle.isStopInProgress() && !b.starts);
for (unsigned i = 0; i < 20; ++i) b.loop();
assert(!b.starts && b.releases == 0);
b._stop_acked = true; b.loop(); assert(!b._initialized && b.releases == 1);
fail_queue = true; b.loop();
assert(b.starts == 1 && !b._initialized && b._start_requested);
assert(!b.resources_owned && !queues_live && !storage_live);
for (unsigned i = 0; i < 100; ++i) b.loop(); assert(b.starts == 1);
clock_ms += 4999; b.loop(); assert(b.starts == 1);
++clock_ms; fail_queue = false; fail_task = true; b.loop();
assert(b.starts == 2 && !b._initialized && !queues_live && !storage_live);
clock_ms += 5000; fail_task = false; b.loop();
assert(b.starts == 3 && b._initialized && queues_live == 1 && storage_live == 1);
b.requestRestart(); b.requestStop(); // Explicit off cancels a queued restart.
b._stop_acked = true; b.loop(); clock_ms += 10000; b.loop();
assert(!b._start_requested && !b._initialized && b.starts == 3);
assert(!queues_live && !storage_live);
clock_ms = UINT32_MAX - 100; fail_queue = true; b.begin();
const auto before = b.starts;
clock_ms += 4999; b.loop(); assert(b.starts == before);
++clock_ms; b.loop(); assert(b.starts == before + 1);
b.end(); assert(!b._start_requested); // Off cancels even an uninitialized failure.
clock_ms += 10000; b.loop(); assert(b.starts == before + 1);
}
'''
self.compile_and_run(preamble + begin + methods + scenarios)
if __name__ == '__main__':
unittest.main()
+2
View File
@@ -245,6 +245,7 @@ class MyMesh : public Base {
public:
bool isUDPBridgeNetworkEnabled() const { return true; }
bool isMqttBridgeRunning() const { return false; }
bool isMqttBridgeStartPending() const { return false; }
@ACCESS@:
@METHOD@
public:
@@ -303,6 +304,7 @@ struct {
bool isUDPBridgeConfigured()const{return configured;}
bool setUDPBridgeNetworkState(bool enabled){paused=!enabled;events.push_back(enabled?5:1);if(enabled)WiFi.mode(WIFI_STA);return true;}
bool isMqttBridgeRunning()const{return mqtt;}
bool isMqttBridgeStartPending()const{return false;}
bool setMqttBridgeState(bool value){mqtt=value;return true;}
bool isWebConfigActive()const{return web;}
bool isWebConfigStopping()const{return false;}
+7 -2
View File
@@ -45,9 +45,12 @@ struct SerialInterface {
bool isPassthroughMode() const{return passthrough;}
};
struct RoleMesh {
int8_t rf_rx_disable_pending=-1;
struct {bool pending=false;bool hasPendingTuning() const{return pending;}} _radio_profiles;
struct {
bool pending=false;
bool hasPendingTxPower() const{return pending;}
bool hasPendingRadioSettings() const{return pending;}
} _cli;
uint32_t dirty_contacts_expiry=0, _ota_update_at=0, set_radio_at=0,
_scheduled_reboot_at=0;
@@ -199,10 +202,12 @@ class UsbLoggingWatchdogRoleTests(unittest.TestCase):
callback = method((directory / 'main.cpp').read_text(),
'static bool usbLoggingRecoverySafe(void*)')
role_checks = r'''
the_mesh.command_radio_apply_pending=true;assert(!usbLoggingRecoverySafe(nullptr));
the_mesh.command_radio_apply_pending=false;
the_mesh.tx_power_apply_pending=true;assert(!usbLoggingRecoverySafe(nullptr));
the_mesh.tx_power_apply_pending=false;
the_mesh.rf_rx_disable_pending=1;assert(!usbLoggingRecoverySafe(nullptr));
the_mesh.rf_rx_disable_pending=-1;
the_mesh._radio_profiles.pending=true;assert(!usbLoggingRecoverySafe(nullptr));
the_mesh._radio_profiles.pending=false;
for(auto slot : {&the_mesh._delayed_replies.request, &the_mesh._delayed_replies.trace}){
slot->phase=mesh::CompanionDelayedReplies::AwaitRadio;
assert(!usbLoggingRecoverySafe(nullptr));
+1
View File
@@ -198,6 +198,7 @@ struct MockMesh {
bool web = false, mqtt = false, espnow = false;
bool isWebConfigActive() const { return web; }
bool isMqttBridgeRunning() const { return mqtt; }
bool isMqttBridgeStartPending() const { return false; }
bool isEspNowBridgeRunning() const { return espnow; }
} the_mesh;
+9 -2
View File
@@ -383,7 +383,7 @@ int main() {
#include <cstdio>
#include <cstring>
struct Callbacks {
bool active = true, allow_stop = true, mqtt = true, espnow = true;
bool active = true, allow_stop = true, mqtt = true, espnow = true, mqtt_pending = false;
int stops = 0, bridge_stops = 0, bridge_starts = 0;
int espnow_stops = 0, espnow_starts = 0;
bool isWebConfigActive() const { return active; }
@@ -393,10 +393,11 @@ struct Callbacks {
active = false; strcpy(reply, "WebConfig stopped"); return true;
}
bool isMqttBridgeRunning() const { return mqtt; }
bool isMqttBridgeStartPending() const { return mqtt_pending; }
bool isEspNowBridgeRunning() const { return espnow; }
bool setMqttBridgeState(bool enabled) {
if (enabled) ++bridge_starts; else ++bridge_stops;
mqtt = enabled; return true;
mqtt = enabled; mqtt_pending = false; return true;
}
bool setEspNowBridgeState(bool enabled) {
if (enabled) ++espnow_starts; else ++espnow_stops;
@@ -474,6 +475,12 @@ int main() {
cli.run("start ota ap", reply.text);
cli.run("stop ota", reply.text);
assert(callbacks.bridge_starts == 0 && callbacks.espnow_starts == 1);
// A pending-only start is paused before OTA and resumed only after stop.
callbacks.active = false; callbacks.mqtt = false; callbacks.mqtt_pending = true;
cli.run("start ota", reply.text);
assert(!callbacks.mqtt_pending && !callbacks.mqtt && callbacks.bridge_stops == 2);
cli.run("stop ota", reply.text);
assert(callbacks.mqtt && callbacks.bridge_starts == 1);
assert(reply.guard == 123);
}
'''
+11 -2
View File
@@ -348,15 +348,16 @@ struct {
void init(){active=true;}void end(){active=false;}
} radio_driver;
struct {
bool web=true,stopping=false,bridge=true,network=false;
bool web=true,stopping=false,bridge=true,network=false,mqtt_pending=false;
bool isWebConfigActive(){return web||stopping;}
bool isWebConfigStopping(){return stopping;}
bool hasWirelessNetworkClient(){return network;}
bool isBridgeRunning(){return bridge;}
bool setBridgeState(bool on){bridge=on;return true;}
bool isMqttBridgeRunning(){return bridge;}
bool isMqttBridgeStartPending(){return mqtt_pending;}
bool isEspNowBridgeRunning(){return bridge;}
bool setMqttBridgeState(bool on){bridge=on;return true;}
bool setMqttBridgeState(bool on){bridge=on;mqtt_pending=false;return true;}
bool setEspNowBridgeState(bool on){bridge=on;return true;}
bool stopWebConfig(char*){web=false;stopping=true;return true;}
bool startWebConfig(bool,char*){web=true;return true;}
@@ -382,6 +383,14 @@ int main(){
InfrastructureWirelessBackend ota_backend;
assert(ota_backend.set(mesh::wireless::WiFi,false)==Result::Done);
assert(!board.ota);
// Failed startup is still requested WiFi work and must participate in off/on.
the_mesh.mqtt_pending=true;
assert(b.enabled()&mesh::wireless::WiFi);
InfrastructureWirelessBackend pending_backend;
assert(pending_backend.set(mesh::wireless::WiFi,false)==Result::Done);
assert(!the_mesh.mqtt_pending&&!the_mesh.bridge);
assert(pending_backend.set(mesh::wireless::WiFi,true)==Result::Done);
assert(the_mesh.bridge&&!the_mesh.web);
the_mesh.web=the_mesh.bridge=true;
// Individual WiFi off retains the ESP-NOW driver and stops both its own services.
c.handle("set wifi off",reply,sizeof(reply),600,Independent);c.service(850);