Skip to content

Commit 6152aeb

Browse files
RCGV1NomDeTom
andauthored
Avoid unnecessary reboots in admin edit transactions (#28)
* reconfigure tests * Narrow radio-reload trigger to LoRa-affecting saves only reloadConfig() inferred "the radio needs reconfiguring" from whether saveWhat included SEGMENT_CONFIG. But Config is a monolithic segment (device/position/power/network/display/lora/bluetooth/security share one file), so every non-LoRa AdminModule save still fired the live SX126x reconfigure - the same live-SPI-on-the-admin-thread sequence that crashes on a favorite (#11146), just reached via a Bluetooth toggle, WiFi PSK change, or keypair rotation. Separate the two concerns: add an explicit radioAffected flag threaded through AdminModule::saveChanges() into MeshService::reloadConfig(). The gate becomes `radioAffected && (saveWhat & (SEGMENT_CONFIG|SEGMENT_CHANNELS))` - the bitmask inference is kept as a backstop and only suppressible, and radioAffected defaults to true so the ~35 existing reloadConfig() callers (MenuHandler, MenuApplet, portduino) keep today's behavior untouched. Only handleSetConfig()'s lora_tag sets radioAffected; every other sub-message, plus set_fixed_position/remove_fixed_position and position's nested save, opt out. set_channel/commit_edit_settings/restore keep the default and still reload. Add native coverage in test_admin_radio for each non-LoRa sub-message (asserting no reconfigure), regression guards that lora/set_channel still reconfigure, and direct reloadConfig() guards pinning the fail-safe default. * mark up todo sites for checking reloadConfig use * added clarifying note * Don't reboot on no-op position/network/bluetooth config sets handleSetConfig() starts requiresReboot=true and device/power/display each gate it back down when nothing reboot-worthy changed, but position, network, and bluetooth never touched requiresReboot - so they rebooted on *every* set, including a client re-pushing byte-identical config (which happens routinely on connect/retry). Add a no-op gate to those three: if the incoming sub-message is byte-identical to the current one, skip the reboot. A whole-struct memcmp is the right tool here (unlike the field-by-field device/power/display gates, which must ignore benign fields) - it answers "did anything change?" and fails safe: its only error mode is padding-byte differences causing an unnecessary reboot, never a missed change. All three sub-messages are POD (no pb_callback_t fields). Any real change still reboots exactly as before. This is Tier 1 of plan-narrow-reboot-trigger; Tier 2 will further narrow position to reboot only on boot-only fields (GPIO/GPS). Adds native coverage asserting rebootAtMsec stays unset on a no-op set and is armed on a real change, for each of the three sub-messages. * Apply live position config changes without a reboot Tier 2 of plan-narrow-reboot-trigger. A position set that touches only fields the position module consumes live now applies without restarting. PositionModule reads position_broadcast_secs, position_broadcast_smart_enabled, broadcast_smart_minimum_distance, position_flags, and fixed_position directly from config on every send/schedule cycle (fixed_position also has dedicated live admin handlers) - changing only those needs no reboot. Everything else stays on the reboot path: GPS driver state (gps_mode/gps_enabled/ gps_update_interval/gps_attempt_time) and GPIO pin assignments (rx_gpio/ tx_gpio/gps_en_gpio), all of which touch subsystem/hardware init. The live set is deliberately limited to what static analysis proves is applied live, so this ships without hardware verification; GPS-timing fields that might also be live were left rebooting (fail toward current behavior). The gate neutralizes the live fields in a copy and reboots if any other byte differs, so a future PositionConfig field reboots until explicitly cleared as live - fail safe for schema growth. This supersedes the Tier 1 no-op memcmp gate for position (network/bluetooth keep theirs). Native coverage: a broadcast-interval change does not schedule a reboot; gps_mode and rx_gpio changes still do. * docs: config-save radio-reload & reboot gating Document the AdminModule config-save side-effect work: the radioAffected and requiresReboot axes, which operations now skip the radio reload or the reboot, and the operations deliberately left unchanged (commit_edit_settings, network/bluetooth live-apply, GPS-timing position fields, module config, and the on-device menu reloadConfig sites) with the reason for each. * docs: add hardware testing section to config-save gating The doc only mentioned the outstanding GPS-timing pass in one line and omitted the radio-reload/crash validation entirely, with no procedure. Add a Hardware testing section covering: the meshtastic-mcp setup (BLE connected throughout, nRF52840 SX126x reference board); the radio-reload/crash regression guard for the favorite-node fix (with a lora/set_channel positive control); and a per-field procedure with pass/fail criteria for deciding whether GPS-timing position fields can be reclassified as live - fail toward rebooting. * docs: clarify hardware tests run over serial, not menus/BLE The hardware section implied a BLE connection was required and that the crash ran on the BLE callback thread. On nRF52 the BLE onWrite only queues; handleToRadio -> saveChanges -> reloadConfig runs on the main FreeRTOS task, same context SerialConsole uses. So serial drives the exact code/thread under test, the on-device menus are unrelated (separate path), and the original crash was serial-proven. State that serial is sufficient and correct the thread references accordingly. * docs: correct crash mechanism to the off-main-thread spiLock lockup The previous edit, while right that the reconfigure is invoked on the main task (not the BLE callback thread), oversimplified the failure. The crash is cross-thread: the main-task setStandby()+SPI reprogram collides with the radio's off-main NotifiedWorkerThread over the shared non-recursive spiLock (FreeRTOS binary semaphore), locking it up and tripping the watchdog reboot (#11146; same spiLock hazard as #10705/#10728). Restore that in both the Axis 1 rationale and the hardware test-1 description. Does not change the serial-is-sufficient conclusion (the collision is transport-independent). * docs: clarify config save behavior for GPS position updates * menu actions * menu actions reboot * Persist telemetry screen toggles from the frame menu The three moduleConfig.telemetry.*_screen_enabled toggles in the frame-toggle menu changed the value in memory and never wrote it, so they reverted on any reboot that did not happen to go through the reboot menu (which saves every segment). Their sibling entries in the same menu persist via Screen::toggleFrameVisibility -> saveFrameVisibility, so half the menu was durable and three entries were not. These three live in moduleConfig rather than the hiddenFrames blob, so they need their own SEGMENT_MODULECONFIG save. radioAffected is false: a screen preference has no business re-initialising the LoRa chip. clod helped too * Drop redundant and over-broad config writes from the menus reloadConfig() ends with an unconditional saveToDisk(saveWhat), outside the radioAffected guard, so nine sites in the InkHUD menu were writing the same proto file twice in a row: saveToDisk(X) immediately followed by reloadConfig(X, ...). One of the nine is the shared applyConfigReload() helper, so thirteen menu actions were affected. Five sites in the BaseUI menu called saveUIConfig() after changing a field that lives in config.proto. saveUIConfig() only writes /prefs/uiconfig.proto, so those writes could not persist the changed field and did nothing but cost a flash write. GPSFormatMenu had the mirror image: a uiconfig-only change that also called reloadConfig(), rewriting config.proto for a field not in it. Three bare saveToDisk() calls rewrote all five segments to change one bit - a channel mute flag and two NodeInfoLite bits - so they now pass the segment they actually touch. NodeInfoLite is written by saveNodeDatabaseToDisk() under SEGMENT_NODEDATABASE, not SEGMENT_DEVICESTATE. The reboot menu keeps its bare call: a full flush before a deliberate reboot is correct. reloadConfig() becomes virtual so tests can count calls; the accompanying test pins down the saveToDisk equivalence the nine deletions rely on. clod helped too * Route config saves through one MeshService::applyConfigChange helper Applying a config change involves three independent decisions: which proto files to persist, whether the LoRa chip needs re-initialising, and whether the field only takes effect after a restart. Those were spread across four helpers with three different parameter orders, two of which took adjacent bools that compile fine when transposed. InkHUD's applyConfigReload was the sharp edge: its second parameter was `reboot`, sitting exactly where reloadConfig and saveChanges take `radioAffected`. There is now a single entry point taking a flags enum, so each call site states its intent and cannot silently mean the opposite. Migrated 23 BaseUI sites, 20 InkHUD sites and the wasm glue. applyConfigReload is deleted and its five callers inlined; applyLoRaRegion and applyLoRaPreset stay, since they hold real domain logic beyond bundling, and just delegate. Adjacent `rebootAtMsec = millis() + ...` assignments fold into the reboot flag. The one caller that deliberately uses a shorter delay keeps it via the trailing rebootSeconds parameter. Reboot scheduling itself moves into requestReboot() in main.cpp, next to the global it sets: previously only AdminModule had a helper for this, and it was private, which is why every menu open-coded the deadline. requestReboot carries no UI, because BaseUI already renders the notice at draw time whenever rebootAtMsec is set. saveChanges keeps its signature and its edit-transaction deferral, so its fourteen call sites and the existing gating tests are untouched. clod helped too * Extract menu config actions into testable functions None of the menu save behaviour was reachable from a test: every action lived in a lambda assigned to BannerOverlayOptions.bannerCallback, which only ever runs via screen->showOverlayBanner(), so exercising one needed a live Screen. That is why the defects this series fixes went unnoticed - MenuHandler.cpp compiles in the native test build, but nothing in it could be called. Three actions move out into functions that own the whole decision: which segment to persist, whether the radio needs reconfiguring, and whether to reboot. Chosen because each covers a defect this series touched - the telemetry toggles that never persisted, the smart-position reboot that PR #11181 removed, and a node-DB bit write that must not reach the radio. Deliberately picked extractions that also deduplicate: three telemetry call sites collapse onto one function and two smart-position sites onto another, so the promicro image is byte-identical to before. Worth knowing, because that board has under 1.4 KB of headroom before the warmstore region. toggleNodeMuted also gains a guard for an unknown node, so a stale pickedNodeNum can no longer cause a pointless flash write. clod helped too * Sort out InkHUD applying-changes notifications notifyApplyingChanges() was doing two jobs at its call sites in MenuApplet.cpp: signalling a live change that is applied without restarting, and warning of an imminent reboot. Audited every site. The finding is that none of them are redundant, so this records why rather than removing anything. The two live-change calls - LoRa region and modem preset - cover the seconds the e-ink takes to redraw while the radio reconfigures, and nothing else raises them. The reboot-path calls warn before the display goes. requestReboot() cannot absorb those: it deliberately carries no UI, because BaseUI renders its own notice at draw time from rebootAtMsec, while e-ink only draws when pushed. Also worth recording: the existing notifyReboot Observable (sleep.h, fired from Power::reboot) is a different moment - reboot execution, not scheduling - and InkHUD already observes it to save settings and shut applets down. A new "reboot scheduled" observable to centralise these calls would be a third reboot signal for no functional gain, so it is not added. clod helped too * stylee * Fix stale doc references and document the menu path Addresses review feedback. Four comments pointed at plan documents that were never committed (plan-narrow-reboot-trigger.md, plan-decouple-nodedb-admin-saves.md), so the rationale they cited was not discoverable. They now point at docs/admin-config-save-gating.md, which is in-repo. The doc listed the commit SHAs it described. All five had already been orphaned by the rebases this branch has been through, exactly as predicted, so it cites the PR instead. "Status: Implemented" also overstated things while hardware validation is still outstanding. The doc's biggest problem was that it had gone out of date within its own PR: it described the on-device menus as an untouched code path that still reloads the radio on any Config save, with per-site TODO markers. That stopped being true when the menus moved onto applyConfigChange. Replaced with a section covering the new entry point, the flags, why they are a flags enum rather than two bools, and the saveToDisk equivalence that makes pairing the two calls a double write. clod helped too * Fix smart-broadcast-interval reboot and carry transaction flags Four review findings. broadcast_smart_minimum_interval_secs is not read live, despite the comment this branch added claiming it was. PositionModule::minimumTimeThreshold is a const data member initialised when the module is constructed, so the value is captured at boot; only the sibling distance field is genuinely re-read (PositionModule.cpp :630). The InkHUD menu therefore applied it with no reboot and it silently did nothing until the next restart. It now reboots, matching the AdminModule path. Note the review suggested the opposite fix - adding the field to AdminModule's live-field list - which would have made the admin path silently ineffective too. While an edit transaction is open saveChanges() defers the write, which threw away the per-field reboot and radio decisions; the commit then used the parameter defaults and always rebooted and reconfigured the radio. Since phone apps write config through transactions, none of this branch's narrowing reached them. The deferred decisions now accumulate and the commit honours them. Two test fixes: the set_ignored_node test relied on an earlier RUN_TEST having created the node, which breaks under -f or a registration reorder. And the telemetry test asserted only values it had just assigned - replaced with one that drives the real toggle and checks the save path sets has_telemetry, the flag whose absence caused the TAK persistence bug fixed upstream in #11216. clod helped too * Stop the edit transaction discarding the per-field save decisions Review of this branch's own output, plus the two findings Copilot raised on The headline defect is that none of this branch's narrowing reached phone apps. saveChanges() defers while an edit transaction is open, and radioAffected defaulted to true, so eight call sites that never thought about the radio - the five node-DB handlers, set_owner, set_module_config, and the nested save in the position case - accumulated a true into deferredRadioAffected. Outside a transaction that was harmless, because reloadConfig()'s saveWhat & (SEGMENT_CONFIG | SEGMENT_CHANNELS) bitmask independently blocks a node-DB-only save from reaching the radio whatever it asks for. Inside one the commit saves under a fixed full mask, so the bitmask always passes and radioAffected is the only thing left deciding it. Favouriting a node from the phone app therefore still ran the live SX126x reconfigure at commit - the The fix is to remove the default from saveChanges() rather than gate the deferred flag on the segment mask, which is what the review suggested. Gating would reinstate exactly the segment-to-radio inference this branch exists to delete - NodeDB.h now carries a comment telling the next person not to do that - and it fixes the symptom while leaving the wrong default in place for the next call site. With no default the compiler makes all fourteen sites state the answer. The commit also consumes and clears the deferred flags, so a stray second commit cannot inherit the previous transaction's answer. That gap existed because every radio test ran outside a transaction, which is the one arrangement where the bug is unreachable. Nine tests now cover the deferred path, asserting both axes independently across a commit. Verified they fail against the old behaviour: five go red while every pre-existing test stays green, which is the point. requestReboot()'s comment had the semantics backwards - it claimed a negative delay meant "now" and that rebootAtMsec == 0 was an immediate-reboot sentinel. Both are inverted: 0 means no reboot pending at every read site, and admin.proto documents reboot_seconds "<0 to cancel reboot". The expression was a faithful copy of AdminModule's, so only the comment was wrong, but it was wrong on the newly-created central helper. The negative branch now says so and logs it. Five sites still open-coded the deadline despite that helper existing; they are pure reboots with no config save, so applyConfigChange() does not fit but requestReboot() does exactly. SET_SMART_BROADCAST_INTERVAL was the only CONFIG_APPLY_REBOOT site in the InkHUD menu without a notifyApplyingChanges() beside it - re-adding its reboot last commit dropped the warning that applyConfigReload() used to raise, so the e-ink would go dark unannounced. And four channel actions carried CONFIG_APPLY_RADIO for uplink/downlink and position_precision, none of which touch the name, PSK or frequency slot the radio derives anything from; they had it only because the old reloadConfig(SEGMENT_CHANNELS) inferred it from the bitmask. The doc had gone stale inside its own PR again: it still listed commit_edit_settings under "intentionally left unchanged". Replaced with a section on why the bitmask stops protecting you inside a transaction, since that is the non-obvious part. Also dropped a commit SHA that had already been orphaned by rebase, exactly as its own note predicted, and a stale plan-doc reference in the tests that the last doc pass missed. Full native suite green, 810 cases across 40 suites. t-echo and t-echo-inkhud both build, covering the menu changes no native env compiles. * post rebase fixes * gps-toggle-noreboot * fix(admin): preserve live config transactions * fix(admin): avoid unnecessary config restarts * fix(admin): keep edit timeout dormant while idle * fix(admin): skip normalized no-op reboots * fix(admin): disable idle transaction timer --------- Co-authored-by: nomdetom <nomdetom@protonmail.com>
1 parent 593166b commit 6152aeb

4 files changed

Lines changed: 705 additions & 45 deletions

File tree

src/modules/AdminModule.cpp

Lines changed: 102 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include "SPILock.h"
1111
#include "gps/RTC.h"
1212
#include "input/InputBroker.h"
13+
#include "mesh/mesh-pb-constants.h"
1314
#include "meshUtils.h"
1415
#include <ErriezCRC32.h>
1516
#include <FSCommon.h>
@@ -70,6 +71,10 @@
7071

7172
AdminModule *adminModule;
7273

74+
#ifdef PIO_UNIT_TESTING
75+
uint32_t disableBluetoothCallCountForTest = 0;
76+
#endif
77+
7378
#if !(MESHTASTIC_EXCLUDE_PKI_KEYGEN || MESHTASTIC_EXCLUDE_PKI)
7479
static bool licensedIdentityWillMigrate()
7580
{
@@ -94,6 +99,37 @@ static void writeSecret(char *buf, size_t bufsz, const char *currentVal)
9499
}
95100
}
96101

102+
template <size_t MaxSize> static NOINLINE bool protobufsEqual(const pb_msgdesc_t *fields, const void *left, const void *right)
103+
{
104+
// NOINLINE limits peak stack use to this frame: two MaxSize encode buffers.
105+
uint8_t leftBytes[MaxSize], rightBytes[MaxSize];
106+
const size_t leftSize = pb_encode_to_bytes(leftBytes, sizeof(leftBytes), fields, left);
107+
const size_t rightSize = pb_encode_to_bytes(rightBytes, sizeof(rightBytes), fields, right);
108+
return leftSize == rightSize && memcmp(leftBytes, rightBytes, leftSize) == 0;
109+
}
110+
111+
static NOINLINE bool loraRadioConfigChanged(const meshtastic_Config_LoRaConfig &oldConfig,
112+
const meshtastic_Config_LoRaConfig &newConfig)
113+
{
114+
auto oldEffective = oldConfig;
115+
auto newEffective = newConfig;
116+
if (oldEffective.use_preset && newEffective.use_preset) {
117+
oldEffective.bandwidth = newEffective.bandwidth = 0;
118+
oldEffective.spread_factor = newEffective.spread_factor = 0;
119+
oldEffective.coding_rate = newEffective.coding_rate = 0;
120+
}
121+
newEffective.hop_limit = oldEffective.hop_limit;
122+
newEffective.tx_enabled = oldEffective.tx_enabled;
123+
newEffective.override_duty_cycle = oldEffective.override_duty_cycle;
124+
// The admin setter applies this immediately through RF95_FAN_EN where supported.
125+
newEffective.pa_fan_disabled = oldEffective.pa_fan_disabled;
126+
newEffective.ignore_incoming_count = oldEffective.ignore_incoming_count;
127+
memcpy(newEffective.ignore_incoming, oldEffective.ignore_incoming, sizeof(newEffective.ignore_incoming));
128+
newEffective.ignore_mqtt = oldEffective.ignore_mqtt;
129+
newEffective.config_ok_to_mqtt = oldEffective.config_ok_to_mqtt;
130+
return !protobufsEqual<meshtastic_Config_LoRaConfig_size>(&meshtastic_Config_LoRaConfig_msg, &oldEffective, &newEffective);
131+
}
132+
97133
/**
98134
* @brief Handle received protobuf message
99135
*
@@ -482,14 +518,18 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
482518
}
483519
case meshtastic_AdminMessage_begin_edit_settings_tag: {
484520
LOG_INFO("Begin transaction for editing settings");
521+
if (!hasOpenEditTransaction) {
522+
deferredEditSegments = 0;
523+
deferredShouldReboot = false;
524+
deferredRadioAffected = false;
525+
}
485526
hasOpenEditTransaction = true;
486527
editTransactionActivityMs = millis();
487-
deferredShouldReboot = false;
488-
deferredRadioAffected = false;
528+
enabled = true;
529+
setIntervalFromNow(EDIT_TRANSACTION_IDLE_MS);
489530
break;
490531
}
491532
case meshtastic_AdminMessage_commit_edit_settings_tag: {
492-
disableBluetooth();
493533
LOG_INFO("Commit transaction for edited settings");
494534
hasOpenEditTransaction = false;
495535
deferredEditSegments = 0;
@@ -498,6 +538,9 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
498538
const bool commitReboot = deferredShouldReboot, commitRadio = deferredRadioAffected;
499539
deferredShouldReboot = false;
500540
deferredRadioAffected = false;
541+
disable();
542+
if (commitReboot)
543+
disableBluetooth();
501544
saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS | SEGMENT_NODEDATABASE,
502545
commitReboot, commitRadio);
503546
flushChannelWarnings(); // one coalesced message for everything edited in this transaction
@@ -1030,13 +1073,12 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c, bool fromOthers)
10301073
case meshtastic_Config_network_tag: {
10311074
LOG_INFO("Set config: WiFi");
10321075
config.has_network = true;
1076+
auto incoming = c.payload_variant.network;
1077+
writeSecret(incoming.wifi_psk, sizeof(incoming.wifi_psk), config.network.wifi_psk);
10331078
// No-op set must not reboot; any real change still restarts the network stack. memcmp fails safe.
1034-
if (memcmp(&config.network, &c.payload_variant.network, sizeof(config.network)) == 0)
1079+
if (memcmp(&config.network, &incoming, sizeof(config.network)) == 0)
10351080
requiresReboot = false;
1036-
char prevPsk[sizeof(config.network.wifi_psk)];
1037-
memcpy(prevPsk, config.network.wifi_psk, sizeof(prevPsk));
1038-
config.network = c.payload_variant.network;
1039-
writeSecret(config.network.wifi_psk, sizeof(config.network.wifi_psk), prevPsk);
1081+
config.network = incoming;
10401082
break;
10411083
}
10421084
case meshtastic_Config_display_tag:
@@ -1066,7 +1108,6 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c, bool fromOthers)
10661108

10671109
LOG_INFO("Set config: LoRa");
10681110
config.has_lora = true;
1069-
radioAffected = true; // the only sub-message that legitimately needs a live radio reconfigure
10701111

10711112
if (validatedLora.coding_rate != clampCodingRate(validatedLora.coding_rate)) {
10721113
LOG_WARN("Invalid coding_rate %d, setting to %d", validatedLora.coding_rate, LORA_CR_DEFAULT);
@@ -1213,6 +1254,7 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c, bool fromOthers)
12131254
}
12141255
#endif
12151256

1257+
radioAffected = loraRadioConfigChanged(oldLoraConfig, validatedLora);
12161258
config.lora = validatedLora; // Finally, return the validated config back to the main config
12171259
if (validatedLora.modem_preset != oldLoraConfig.modem_preset) {
12181260
pendingOldLora = oldLoraConfig;
@@ -1232,6 +1274,7 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c, bool fromOthers)
12321274
break;
12331275
case meshtastic_Config_security_tag: {
12341276
LOG_INFO("Set config: Security");
1277+
const auto oldSecurity = config.security;
12351278
meshtastic_Config_SecurityConfig incoming = c.payload_variant.security;
12361279
// Preserve our keypair when a SET omits the private key but we already hold one: regenerating would
12371280
// change our NodeNum (== crc32(public_key)) and orphan us on the mesh. A SET without the key is a
@@ -1278,11 +1321,11 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c, bool fromOthers)
12781321
LOG_WARN(warning);
12791322
sendWarning(warning);
12801323
}
1324+
requiresReboot = !protobufsEqual<meshtastic_Config_SecurityConfig_size>(&meshtastic_Config_SecurityConfig_msg,
1325+
&oldSecurity, &config.security);
12811326

12821327
changes = SEGMENT_CONFIG | SEGMENT_DEVICESTATE | SEGMENT_NODEDATABASE;
12831328

1284-
requiresReboot = true;
1285-
12861329
break;
12871330
}
12881331
case meshtastic_Config_device_ui_tag:
@@ -1304,12 +1347,6 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c, bool fromOthers)
13041347
bool AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c)
13051348
{
13061349
bool shouldReboot = true;
1307-
// If we are in an open transaction or configuring MQTT or Serial (which have validation), defer disabling Bluetooth
1308-
// Otherwise, disable Bluetooth to prevent the phone from interfering with the config
1309-
if (!hasOpenEditTransaction && !IS_ONE_OF(c.which_payload_variant, meshtastic_ModuleConfig_mqtt_tag,
1310-
meshtastic_ModuleConfig_serial_tag, meshtastic_ModuleConfig_statusmessage_tag)) {
1311-
disableBluetooth();
1312-
}
13131350

13141351
switch (c.which_payload_variant) {
13151352
case meshtastic_ModuleConfig_mqtt_tag:
@@ -1321,14 +1358,13 @@ bool AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c)
13211358
if (!MQTT::isValidConfig(c.payload_variant.mqtt)) {
13221359
return false;
13231360
}
1324-
// Disable Bluetooth to prevent interference during MQTT configuration
1325-
disableBluetooth();
13261361
moduleConfig.has_mqtt = true;
13271362
{
1328-
char prevPass[sizeof(moduleConfig.mqtt.password)];
1329-
memcpy(prevPass, moduleConfig.mqtt.password, sizeof(prevPass));
1330-
moduleConfig.mqtt = c.payload_variant.mqtt;
1331-
writeSecret(moduleConfig.mqtt.password, sizeof(moduleConfig.mqtt.password), prevPass);
1363+
auto incoming = c.payload_variant.mqtt;
1364+
writeSecret(incoming.password, sizeof(incoming.password), moduleConfig.mqtt.password);
1365+
shouldReboot = !protobufsEqual<meshtastic_ModuleConfig_MQTTConfig_size>(&meshtastic_ModuleConfig_MQTTConfig_msg,
1366+
&moduleConfig.mqtt, &incoming);
1367+
moduleConfig.mqtt = incoming;
13321368
}
13331369
#endif
13341370
break;
@@ -1340,9 +1376,10 @@ bool AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c)
13401376
LOG_ERROR("Invalid serial config");
13411377
return false;
13421378
}
1343-
disableBluetooth(); // Disable Bluetooth to prevent interference during Serial configuration
13441379
#endif
13451380
moduleConfig.has_serial = true;
1381+
shouldReboot = !protobufsEqual<meshtastic_ModuleConfig_SerialConfig_size>(
1382+
&meshtastic_ModuleConfig_SerialConfig_msg, &moduleConfig.serial, &c.payload_variant.serial);
13461383
moduleConfig.serial = c.payload_variant.serial;
13471384
break;
13481385
case meshtastic_ModuleConfig_external_notification_tag:
@@ -1362,6 +1399,9 @@ bool AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c)
13621399
break;
13631400
case meshtastic_ModuleConfig_telemetry_tag:
13641401
LOG_INFO("Set module config: Telemetry");
1402+
shouldReboot = !moduleConfig.has_telemetry ||
1403+
!protobufsEqual<meshtastic_ModuleConfig_TelemetryConfig_size>(
1404+
&meshtastic_ModuleConfig_TelemetryConfig_msg, &moduleConfig.telemetry, &c.payload_variant.telemetry);
13651405
moduleConfig.has_telemetry = true;
13661406
moduleConfig.telemetry = c.payload_variant.telemetry;
13671407
break;
@@ -1506,13 +1546,19 @@ bool AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c)
15061546
}
15071547
#endif
15081548
}
1549+
if (shouldReboot && !hasOpenEditTransaction)
1550+
disableBluetooth();
15091551
// No module config feeds RadioInterface::reconfigure() - that reads config.lora only.
15101552
saveChanges(SEGMENT_MODULECONFIG, shouldReboot, /*radioAffected=*/false);
15111553
return true;
15121554
}
15131555

15141556
void AdminModule::handleSetChannel(const meshtastic_Channel &cc)
15151557
{
1558+
const ChannelIndex oldPrimaryIndex = channels.getPrimaryIndex();
1559+
char oldPrimaryName[32];
1560+
snprintf(oldPrimaryName, sizeof(oldPrimaryName), "%s", channels.getName(oldPrimaryIndex));
1561+
15161562
channels.setChannel(cc);
15171563
if (channels.ensureLicensedOperation()) {
15181564
warnLicensedMode();
@@ -1537,8 +1583,13 @@ void AdminModule::handleSetChannel(const meshtastic_Channel &cc)
15371583
}
15381584
if (clamped)
15391585
sendWarning(publicChannelPrecisionMessage);
1540-
saveChanges(SEGMENT_CHANNELS, false, /*radioAffected=*/true); // real frequency-slot / PSK change
1541-
warnOnChannelSet(channels.getByIndex(cc.index)); // passes the saved channel
1586+
const ChannelIndex newPrimaryIndex = channels.getPrimaryIndex();
1587+
const bool usesChannelNameForFrequency = config.lora.override_frequency == 0 && RadioInterface::uses_default_frequency_slot &&
1588+
getRegion(config.lora.region)->overrideSlot == OVERRIDE_SLOT_DEFAULT_CHANNEL_HASH;
1589+
const bool radioAffected = usesChannelNameForFrequency && (oldPrimaryIndex != newPrimaryIndex ||
1590+
strcmp(oldPrimaryName, channels.getName(newPrimaryIndex)) != 0);
1591+
saveChanges(SEGMENT_CHANNELS, false, radioAffected);
1592+
warnOnChannelSet(channels.getByIndex(cc.index)); // passes the saved channel
15421593
// Inside an edit transaction the queued warnings are flushed once at commit; otherwise emit now.
15431594
if (!hasOpenEditTransaction)
15441595
flushChannelWarnings();
@@ -1955,15 +2006,29 @@ void AdminModule::expireStaleEditTransaction()
19552006
deferredEditSegments = 0;
19562007
// Same consume-and-clear as a real commit: an abandoned transaction must not leave its
19572008
// decisions behind for the next one.
1958-
const bool expiredRadio = deferredRadioAffected;
2009+
const bool expiredReboot = deferredShouldReboot, expiredRadio = deferredRadioAffected;
19592010
deferredShouldReboot = false;
19602011
deferredRadioAffected = false;
1961-
// No reboot: the settings are already live in RAM and the client that would expect one is gone.
2012+
disable();
2013+
// Boot-only changes must still take effect if the client disappears. Persisting without this
2014+
// reboot would leave runtime behavior out of sync with the stored configuration.
2015+
if (expiredReboot)
2016+
disableBluetooth();
19622017
if (segments)
1963-
saveChanges(segments, false, expiredRadio);
2018+
saveChanges(segments, expiredReboot, expiredRadio);
19642019
flushChannelWarnings();
19652020
}
19662021

2022+
int32_t AdminModule::runOnce()
2023+
{
2024+
expireStaleEditTransaction();
2025+
if (!hasOpenEditTransaction)
2026+
return disable();
2027+
2028+
const uint32_t elapsed = millis() - editTransactionActivityMs;
2029+
return elapsed < EDIT_TRANSACTION_IDLE_MS ? EDIT_TRANSACTION_IDLE_MS - elapsed : 1;
2030+
}
2031+
19672032
// radioAffected is mandatory here - see the note on the declaration in AdminModule.h for why it
19682033
// must not be allowed to default now that the deferred transaction flags accumulate it.
19692034
void AdminModule::saveChanges(int saveWhat, bool shouldReboot, bool radioAffected)
@@ -1980,6 +2045,8 @@ void AdminModule::saveChanges(int saveWhat, bool shouldReboot, bool radioAffecte
19802045
deferredRadioAffected |= radioAffected;
19812046
LOG_INFO("Delay save of changes to disk until the open transaction is committed");
19822047
editTransactionActivityMs = millis(); // still in use, so not the abandoned kind we time out
2048+
enabled = true;
2049+
setIntervalFromNow(EDIT_TRANSACTION_IDLE_MS);
19832050
deferredEditSegments |= saveWhat;
19842051
return;
19852052
}
@@ -2060,8 +2127,10 @@ void AdminModule::handleSetHamMode(const meshtastic_HamParameters &p)
20602127
/*radioAffected=*/true);
20612128
}
20622129

2063-
AdminModule::AdminModule() : ProtobufModule("Admin", meshtastic_PortNum_ADMIN_APP, &meshtastic_AdminMessage_msg)
2130+
AdminModule::AdminModule()
2131+
: ProtobufModule("Admin", meshtastic_PortNum_ADMIN_APP, &meshtastic_AdminMessage_msg), concurrency::OSThread("AdminTimeout")
20642132
{
2133+
disable();
20652134
// restrict to the admin channel for rx
20662135
// boundChannel = Channels::adminChannel;
20672136
}
@@ -2567,6 +2636,9 @@ void AdminModule::warnOnLoraPresetChange(const meshtastic_Config_LoRaConfig &old
25672636

25682637
void disableBluetooth()
25692638
{
2639+
#ifdef PIO_UNIT_TESTING
2640+
disableBluetoothCallCountForTest++;
2641+
#endif
25702642
#if HAS_BLUETOOTH
25712643
#ifdef ARCH_ESP32
25722644
if (nimbleBluetooth)

src/modules/AdminModule.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include <esp_ota_ops.h>
44
#endif
55
#include "ProtobufModule.h"
6+
#include "concurrency/OSThread.h"
67
#include "meshUtils.h"
78
#include <sys/types.h>
89
#if HAS_WIFI
@@ -21,7 +22,9 @@ struct AdminModule_ObserverData {
2122
/**
2223
* Admin module for admin messages
2324
*/
24-
class AdminModule : public ProtobufModule<meshtastic_AdminMessage>, public Observable<AdminModule_ObserverData *>
25+
class AdminModule : public ProtobufModule<meshtastic_AdminMessage>,
26+
public Observable<AdminModule_ObserverData *>,
27+
private concurrency::OSThread
2528
{
2629
friend class AdminModuleTestShim; // test/support/AdminModuleTestShim.h - native tests reach the private handlers/state
2730

@@ -37,6 +40,7 @@ class AdminModule : public ProtobufModule<meshtastic_AdminMessage>, public Obser
3740
@return true if you've guaranteed you've handled this message and no other handlers should be considered for it
3841
*/
3942
virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_AdminMessage *p) override;
43+
virtual int32_t runOnce() override;
4044

4145
private:
4246
bool hasOpenEditTransaction = false;
@@ -49,6 +53,7 @@ class AdminModule : public ProtobufModule<meshtastic_AdminMessage>, public Obser
4953
void expireStaleEditTransaction();
5054
#ifdef PIO_UNIT_TESTING
5155
int lastSaveWhatForTest = 0;
56+
unsigned long editTransactionTimerIntervalForTest() const { return interval; }
5257
#endif
5358

5459
// While a transaction is open, saveChanges() defers the write - so the per-field reboot and

test/support/AdminModuleTestShim.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,19 @@ class AdminModuleTestShim : public AdminModule
2929
{
3030
hasOpenEditTransaction = true;
3131
editTransactionActivityMs = millis();
32+
enabled = true;
33+
setIntervalFromNow(EDIT_TRANSACTION_IDLE_MS);
3234
deferredShouldReboot = false;
3335
deferredRadioAffected = false;
3436
}
3537
int savedSegments() const { return lastSaveWhatForTest; }
3638

3739
bool editTransactionOpen() const { return hasOpenEditTransaction; }
40+
bool editTransactionTimerEnabled() const { return enabled; }
41+
unsigned long editTransactionTimerInterval() const { return editTransactionTimerIntervalForTest(); }
3842
// Backdate past the idle window so a test sees an abandoned transaction without waiting it out.
3943
void ageEditTransaction() { editTransactionActivityMs = millis() - EDIT_TRANSACTION_IDLE_MS - 1; }
44+
int32_t runTransactionTimer() { return runOnce(); }
4045

4146
// Setters may allocate an error reply from packetPool; drain it each iteration or the pool leaks.
4247
void drainReply()

0 commit comments

Comments
 (0)