feat(mqtt): persist observer preferences as JSON

This commit is contained in:
agessaman committed 2026-08-14 09:09:05 -07:00
1 parent 40635a53c4
commit 75f3e446e0
27 files changed
+2131 -254

No files matched your search

+360 -60
View File
@@ -6,6 +6,7 @@
#include "MQTTPrefsAtomicStore.h"
#include <RTClib.h>
#include <Utils.h>
#include <new>
#ifndef BRIDGE_MAX_BAUD
#define BRIDGE_MAX_BAUD 115200
@@ -23,6 +24,7 @@
#include "MQTTDefaults.h"
#include "MQTTPrefsCodec.h"
#include "MQTTPrefsRecovery.h"
#include "MQTTPrefsSerializer.h"
#endif
// Believe it or not, this std C function is busted on some platforms!
@@ -94,7 +96,8 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
_prefs->bridge_pkt_src = 1; // Default to RX (logRx) for new installs
}
#ifdef WITH_MQTT_BRIDGE
// Load observer preferences (MQTT/WiFi/timezone/SNMP/alert) from /mqtt_prefs.
// Load observer preferences (MQTT/WiFi/timezone/SNMP/alert) from /mqtt.json,
// migrating the old /mqtt_prefs binary when JSON does not exist yet.
// Readers (MQTTBridge, AlertReporter, observer CLI) use _mqtt_prefs directly —
// these fields no longer exist in NodePrefs, so there is nothing to sync.
MQTTPrefsAtomicStore::LegacyUpgradeGate legacy_upgrade(
@@ -119,13 +122,13 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
}
}
// mqtt_rx_enabled: new field appended to end of MQTTPrefs. On upgrade from older firmware,
// the shorter /mqtt_prefs file won't contain it, so it keeps the default value (1 = on)
// a shorter legacy /mqtt_prefs file won't contain it, so it keeps the default value (1 = on)
// set by setMQTTPrefsDefaults(). No explicit migration needed.
#endif
// Republish legacy binary prefs as /prefs.json. Old-format files also carried a
// trailing observer block, which loadPrefsInt() recovered into _legacy_tail; wait
// for loadMQTTPrefs() to commit that to /mqtt_prefs first. The legacy file is left
// for loadMQTTPrefs() to commit that to /mqtt.json first. The legacy file is left
// on flash either way, so a deferred or failed save just retries on the next boot.
#ifdef WITH_MQTT_BRIDGE
if (loaded_from_legacy || _com_prefs_needs_upgrade) {
@@ -134,7 +137,7 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
legacy_upgrade.recordComPrefsRewrite();
_com_prefs_needs_upgrade = false;
} else {
MESH_DEBUG_PRINTLN("Prefs: deferring /prefs.json migration until /mqtt_prefs commits");
MESH_DEBUG_PRINTLN("Prefs: deferring /prefs.json migration until /mqtt.json commits");
}
}
#else
@@ -376,13 +379,17 @@ bool CommonCLI::savePrefs(FILESYSTEM* fs, bool save_mqtt) {
#ifdef WITH_MQTT_BRIDGE
// Observer config (MQTT/WiFi/timezone/SNMP/alert) is persisted separately. The
// observer CLI writes _mqtt_prefs directly, so no NodePrefs->MQTTPrefs sync runs.
// Runs regardless of the NodePrefs result so a failed JSON write cannot strand it.
// Ordinary NodePrefs callers leave save_mqtt false; migration is the only
// workflow that may explicitly combine these independent transactions.
if (save_mqtt) saveMQTTPrefs(fs);
#endif
return success;
}
#ifdef WITH_MQTT_BRIDGE
static const uint32_t MQTT_JSON_FNV1A_OFFSET_BASIS = 2166136261u;
static const uint32_t MQTT_JSON_FNV1A_PRIME = 16777619u;
// Set default values for MQTT preferences (used when file doesn't exist or is corrupted)
static void setMQTTPrefsDefaults(MQTTPrefs* prefs) {
applyMQTTDefaults(prefs);
@@ -396,6 +403,124 @@ static File openMqttPrefsRead(FILESYSTEM* fs, const char* path = "/mqtt_prefs")
#endif
}
enum class JsonPrefsLoadResult : uint8_t {
Loaded,
LoadedWithRepairs,
UnsupportedVersion,
FutureClaimed,
Invalid,
};
static JsonPrefsLoadResult loadMqttJsonFile(FILESYSTEM* fs, const char* path,
MQTTPrefs* output) {
if (output == nullptr) return JsonPrefsLoadResult::Invalid;
applyMQTTDefaults(output);
// Probe the root version without applying the v1 schema. A future version
// may legitimately change an existing field's type, and must still be held
// opaquely rather than misclassified as corrupt and rolled back.
File version_file = openMqttPrefsRead(fs, path);
if (!version_file) return JsonPrefsLoadResult::Invalid;
MQTTPrefsVersionProbe version_probe;
const bool version_parsed = version_probe.loadSerial(version_file);
version_file.close();
if (version_probe.hasFutureVersion()) {
return version_parsed ? JsonPrefsLoadResult::UnsupportedVersion
: JsonPrefsLoadResult::FutureClaimed;
}
File file = openMqttPrefsRead(fs, path);
if (!file) return JsonPrefsLoadResult::Invalid;
MQTTPrefsSerializer serializer(output);
const bool parsed = serializer.loadSerial(file);
file.close();
if (!parsed) return JsonPrefsLoadResult::Invalid;
if (serializer.hasFutureVersion()) return JsonPrefsLoadResult::UnsupportedVersion;
bool repaired = false;
if (!serializer.apply(&repaired)) return JsonPrefsLoadResult::Invalid;
return repaired ? JsonPrefsLoadResult::LoadedWithRepairs : JsonPrefsLoadResult::Loaded;
}
static MQTTPrefsRecovery::FileState mqttJsonFileState(FILESYSTEM* fs, const char* path) {
if (!fs->exists(path)) return MQTTPrefsRecovery::FileState::Missing;
MQTTPrefs* scratch = new (std::nothrow) MQTTPrefs;
if (scratch == nullptr) return MQTTPrefsRecovery::FileState::Indeterminate;
const JsonPrefsLoadResult result = loadMqttJsonFile(fs, path, scratch);
delete scratch;
if (result == JsonPrefsLoadResult::UnsupportedVersion) {
// Syntax and the mandatory version field were valid, so this can be a
// fully verified transaction written by newer firmware. Keep it distinct
// from a torn/corrupt temp during recovery.
return MQTTPrefsRecovery::FileState::FutureUsable;
}
if (result == JsonPrefsLoadResult::FutureClaimed) {
return MQTTPrefsRecovery::FileState::FutureClaimed;
}
return result == JsonPrefsLoadResult::Loaded ||
result == JsonPrefsLoadResult::LoadedWithRepairs
? MQTTPrefsRecovery::FileState::Usable
: MQTTPrefsRecovery::FileState::Preserve;
}
static bool recoverMqttJsonFiles(FILESYSTEM* fs) {
const MQTTPrefsRecovery::FileState primary = mqttJsonFileState(fs, "/mqtt.json");
const MQTTPrefsRecovery::FileState temp = mqttJsonFileState(fs, "/mqtt.json.tmp");
const MQTTPrefsRecovery::FileState backup = mqttJsonFileState(fs, "/mqtt.json.bak");
const MQTTPrefsRecovery::Action action = MQTTPrefsRecovery::select(primary, temp, backup);
if (action == MQTTPrefsRecovery::Action::KeepPrimary) {
if (primary == MQTTPrefsRecovery::FileState::Usable) {
if (!MQTTPrefsRecovery::uncertain(temp) &&
temp != MQTTPrefsRecovery::FileState::Missing) {
fs->remove("/mqtt.json.tmp");
}
if (!MQTTPrefsRecovery::uncertain(backup) &&
backup != MQTTPrefsRecovery::FileState::Missing) {
fs->remove("/mqtt.json.bak");
}
}
return MQTTPrefsRecovery::uncertain(primary) ||
MQTTPrefsRecovery::uncertain(temp) ||
MQTTPrefsRecovery::uncertain(backup);
}
if (action == MQTTPrefsRecovery::Action::DiscardTemp) {
if (fs->remove("/mqtt.json.tmp")) {
MESH_DEBUG_PRINTLN("MQTT: discarded incomplete first-migration JSON temp");
return false;
}
MESH_DEBUG_PRINTLN("MQTT: could not discard incomplete /mqtt.json temp; source held");
return true;
}
if (action == MQTTPrefsRecovery::Action::PromoteTemp) {
if (fs->rename("/mqtt.json.tmp", "/mqtt.json")) {
if (temp == MQTTPrefsRecovery::FileState::Usable &&
backup != MQTTPrefsRecovery::FileState::Missing) {
fs->remove("/mqtt.json.bak");
}
MESH_DEBUG_PRINTLN("MQTT: recovered /mqtt.json from transaction temp");
return MQTTPrefsRecovery::uncertain(temp) ||
MQTTPrefsRecovery::uncertain(backup);
}
MESH_DEBUG_PRINTLN("MQTT: could not recover /mqtt.json temp; files preserved");
return true;
}
if (action == MQTTPrefsRecovery::Action::PromoteBackup) {
if (fs->rename("/mqtt.json.bak", "/mqtt.json")) {
if (backup == MQTTPrefsRecovery::FileState::Usable &&
!MQTTPrefsRecovery::uncertain(temp) &&
temp != MQTTPrefsRecovery::FileState::Missing) {
fs->remove("/mqtt.json.tmp");
}
MESH_DEBUG_PRINTLN("MQTT: recovered /mqtt.json from transaction backup");
return MQTTPrefsRecovery::uncertain(temp) ||
MQTTPrefsRecovery::uncertain(backup);
}
MESH_DEBUG_PRINTLN("MQTT: could not recover /mqtt.json backup; files preserved");
return true;
}
return false;
}
static MQTTPrefsRecovery::FileState mqttPrefsFileState(FILESYSTEM* fs, const char* path) {
if (!fs->exists(path)) return MQTTPrefsRecovery::FileState::Missing;
File file = openMqttPrefsRead(fs, path);
@@ -432,6 +557,14 @@ static bool recoverMqttPrefsFiles(FILESYSTEM* fs) {
}
return false;
}
if (action == MQTTPrefsRecovery::Action::DiscardTemp) {
if (fs->remove("/mqtt_prefs.tmp")) {
MESH_DEBUG_PRINTLN("MQTT: discarded incomplete legacy transaction temp");
return false;
}
MESH_DEBUG_PRINTLN("MQTT: could not discard incomplete /mqtt_prefs temp; source held");
return true;
}
if (action == MQTTPrefsRecovery::Action::PromoteTemp) {
if (fs->rename("/mqtt_prefs.tmp", "/mqtt_prefs")) {
// A usable temp is now the committed primary. Its backup is necessarily
@@ -463,30 +596,31 @@ static bool recoverMqttPrefsFiles(FILESYSTEM* fs) {
return false;
}
// Filesystem adapter for MQTTPrefsAtomicStore. It writes the new image to
// /mqtt_prefs.tmp and verifies its size. Publishing is a recoverable SPIFFS
// Filesystem adapter for the ConfigSerializer image. It writes to
// /mqtt.json.tmp and verifies its size and checksum. Publishing is a recoverable SPIFFS
// transaction: primary -> .bak, then tmp -> primary, then best-effort backup
// cleanup. A power loss at every boundary leaves at least one recoverable file.
class MQTTPrefsFileStore {
class MQTTPrefsJsonFileStore {
public:
explicit MQTTPrefsFileStore(FILESYSTEM* fs) : _fs(fs) {}
explicit MQTTPrefsJsonFileStore(FILESYSTEM* fs) : _fs(fs) {}
bool begin() {
_finished = false;
_open = false;
_owns_temp = false;
_bytes_written = 0;
_expected_crc = MQTT_JSON_FNV1A_OFFSET_BASIS;
// Recovery owns stale artifacts. Do not delete them here: a failed commit
// may have moved the old primary to .bak and left a verified temp that the
// next boot must choose between. Refusing the save is safer than erasing an
// image this firmware cannot decode.
if (_fs->exists("/mqtt_prefs.tmp") || _fs->exists("/mqtt_prefs.bak")) return false;
if (_fs->exists("/mqtt.json.tmp") || _fs->exists("/mqtt.json.bak")) return false;
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
_file = _fs->open("/mqtt_prefs.tmp", FILE_O_WRITE);
_file = _fs->open("/mqtt.json.tmp", FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
_file = _fs->open("/mqtt_prefs.tmp", "w");
_file = _fs->open("/mqtt.json.tmp", "w");
#else
_file = _fs->open("/mqtt_prefs.tmp", "w", true);
_file = _fs->open("/mqtt.json.tmp", "w", true);
#endif
_open = _file;
_owns_temp = _open;
@@ -496,6 +630,9 @@ public:
size_t write(const uint8_t* bytes, size_t size) {
if (!_open) return 0;
const size_t written = _file.write(bytes, size);
for (size_t i = 0; i < written; ++i) {
_expected_crc = (_expected_crc ^ bytes[i]) * MQTT_JSON_FNV1A_PRIME;
}
_bytes_written += written;
return written;
}
@@ -505,12 +642,33 @@ public:
_file.close();
_open = false;
#if defined(RP2040_PLATFORM)
File verify = _fs->open("/mqtt_prefs.tmp", "r");
File verify = _fs->open("/mqtt.json.tmp", "r");
#else
File verify = _fs->open("/mqtt_prefs.tmp");
File verify = _fs->open("/mqtt.json.tmp");
#endif
if (!verify) return false;
const bool complete = verify.size() == _bytes_written;
uint32_t actual_crc = MQTT_JSON_FNV1A_OFFSET_BASIS;
size_t actual_size = 0;
bool read_failed = false;
uint8_t buf[64];
while (verify.available() > 0) {
// Arduino File implementations normally return a byte count, but some
// Stream implementations use -1 for a read error. Keep that sentinel
// signed so it cannot become a huge size_t and overrun this buffer.
const int count = static_cast<int>(verify.read(buf, sizeof(buf)));
if (count <= 0) {
read_failed = count < 0;
break;
}
actual_size += static_cast<size_t>(count);
for (int i = 0; i < count; ++i) {
actual_crc = (actual_crc ^ buf[i]) * MQTT_JSON_FNV1A_PRIME;
}
}
const bool complete = !read_failed &&
verify.size() == _bytes_written &&
actual_size == _bytes_written &&
actual_crc == _expected_crc;
verify.close();
if (!complete) return false;
_finished = true;
@@ -523,25 +681,33 @@ public:
// recoverable backup first, then publish temp into the now-empty primary.
// Never remove either image after a failed boundary; boot recovery selects
// the completed temp or restores the backup.
if (_fs->exists("/mqtt_prefs.bak")) return false;
if (_fs->exists("/mqtt_prefs") && !_fs->rename("/mqtt_prefs", "/mqtt_prefs.bak")) {
if (_fs->exists("/mqtt.json.bak")) return false;
if (_fs->exists("/mqtt.json") && !_fs->rename("/mqtt.json", "/mqtt.json.bak")) {
return false;
}
if (!_fs->rename("/mqtt_prefs.tmp", "/mqtt_prefs")) return false;
if (!_fs->rename("/mqtt.json.tmp", "/mqtt.json")) return false;
// Cleanup failure is non-fatal: the new primary is published and recovery
// will remove a known-good stale backup on a later boot.
if (_fs->exists("/mqtt_prefs.bak")) _fs->remove("/mqtt_prefs.bak");
if (_fs->exists("/mqtt.json.bak")) _fs->remove("/mqtt.json.bak");
return true;
}
void discardFinishedTemp() {
if (_open) _file.close();
_open = false;
if (_owns_temp && _fs->exists("/mqtt.json.tmp")) _fs->remove("/mqtt.json.tmp");
_finished = false;
_owns_temp = false;
}
void abort() {
if (_open) _file.close();
_open = false;
// Once finish() has verified the temp, commit may already have moved the
// primary to .bak. Keep the temp on a commit failure so recovery can
// publish it (or fall back to .bak) after reset.
if (_owns_temp && !_finished && _fs->exists("/mqtt_prefs.tmp")) {
_fs->remove("/mqtt_prefs.tmp");
if (_owns_temp && !_finished && _fs->exists("/mqtt.json.tmp")) {
_fs->remove("/mqtt.json.tmp");
}
_finished = false;
_owns_temp = false;
@@ -554,31 +720,90 @@ private:
bool _finished = false;
bool _owns_temp = false;
size_t _bytes_written = 0;
uint32_t _expected_crc = MQTT_JSON_FNV1A_OFFSET_BASIS;
};
class MQTTPrefsStoreStream : public Stream {
public:
explicit MQTTPrefsStoreStream(MQTTPrefsJsonFileStore* store) : _store(store) {}
size_t write(uint8_t byte) override { return write(&byte, 1); }
size_t write(const uint8_t* buffer, size_t size) override {
if (!_ok || _store == nullptr) return 0;
const size_t written = _store->write(buffer, size);
if (written != size) _ok = false;
return written;
}
int available() override { return 0; }
int read() override { return -1; }
int peek() override { return -1; }
bool ok() const { return _ok; }
private:
MQTTPrefsJsonFileStore* _store;
bool _ok = true;
};
#endif // WITH_MQTT_BRIDGE
#ifdef WITH_MQTT_BRIDGE
static const char* mqttPrefsSaveResultName(MQTTPrefsAtomicStore::Result result) {
switch (result) {
case MQTTPrefsAtomicStore::Result::BeginFailed: return "begin";
case MQTTPrefsAtomicStore::Result::HeaderWriteFailed: return "header write";
case MQTTPrefsAtomicStore::Result::PayloadWriteFailed: return "payload write";
case MQTTPrefsAtomicStore::Result::FinishFailed: return "close";
case MQTTPrefsAtomicStore::Result::CommitFailed: return "rename";
case MQTTPrefsAtomicStore::Result::Committed: return "committed";
}
return "unknown";
}
void CommonCLI::loadMQTTPrefs(
FILESYSTEM* fs, MQTTPrefsAtomicStore::LegacyUpgradeGate* legacy_upgrade) {
setMQTTPrefsDefaults(&_mqtt_prefs);
_mqtt_prefs_hold = recoverMqttJsonFiles(fs);
if (_mqtt_prefs_hold && !fs->exists("/mqtt.json") &&
(fs->exists("/mqtt.json.tmp") || fs->exists("/mqtt.json.bak"))) {
_legacy_tail.valid = false;
MESH_DEBUG_PRINTLN("MQTT: unresolved /mqtt.json recovery files; using defaults (files preserved)");
return;
}
// The JSON file is authoritative once it exists. Never fall back to the
// stale binary snapshot when JSON is corrupt, unreadable, or from a future
// schema: preserve it and run defaults until an operator resolves it.
if (fs->exists("/mqtt.json")) {
MQTTPrefs* scratch = new (std::nothrow) MQTTPrefs;
if (scratch == nullptr) {
_mqtt_prefs_hold = true;
_legacy_tail.valid = false;
MESH_DEBUG_PRINTLN("MQTT: no memory to validate /mqtt.json; source preserved");
return;
}
const JsonPrefsLoadResult json_result = loadMqttJsonFile(fs, "/mqtt.json", scratch);
if (json_result == JsonPrefsLoadResult::Loaded ||
json_result == JsonPrefsLoadResult::LoadedWithRepairs) {
memcpy(&_mqtt_prefs, scratch, sizeof(_mqtt_prefs));
delete scratch;
_legacy_tail.valid = false;
if (json_result == JsonPrefsLoadResult::LoadedWithRepairs) {
MESH_DEBUG_PRINTLN("MQTT: repaired out-of-range values in /mqtt.json");
if (!_mqtt_prefs_hold && !saveMQTTPrefs(fs)) {
_mqtt_prefs_hold = true;
MESH_DEBUG_PRINTLN("MQTT: could not persist /mqtt.json repairs; source held");
}
}
return;
}
delete scratch;
_mqtt_prefs_hold = true;
_legacy_tail.valid = false;
if (json_result == JsonPrefsLoadResult::UnsupportedVersion) {
MESH_DEBUG_PRINTLN("MQTT: /mqtt.json uses a future version; using defaults (file preserved)");
} else if (json_result == JsonPrefsLoadResult::FutureClaimed) {
MESH_DEBUG_PRINTLN(
"MQTT: /mqtt.json claims a future version but uses unknown grammar; "
"using defaults (file preserved)");
} else {
MESH_DEBUG_PRINTLN("MQTT: /mqtt.json is invalid or unreadable; using defaults (file preserved)");
}
return;
}
// Complete or preserve an interrupted SPIFFS transaction before decoding.
// A failed recovery leaves the artifacts untouched and blocks this boot from
// replacing them with defaults through a later CLI save.
_mqtt_prefs_hold = recoverMqttPrefsFiles(fs);
_mqtt_prefs_hold = _mqtt_prefs_hold || recoverMqttPrefsFiles(fs);
bool has_observer_fields = false;
bool mqtt_rewrite_pending = false;
bool migrated_legacy_mqtt = false;
@@ -600,24 +825,34 @@ void CommonCLI::loadMQTTPrefs(
} else if (plan.source == MQTTPrefsCodec::Source::Current) {
file = openMqttPrefsRead(fs);
MQTTPrefsHeader header;
if (!file || file.read((uint8_t *)&header, sizeof(header)) != sizeof(header) ||
file.read((uint8_t *)&_mqtt_prefs, plan.payload_len) != plan.payload_len) {
LegacyV1MQTTPrefs* old_prefs = new (std::nothrow) LegacyV1MQTTPrefs;
if (old_prefs) memset(old_prefs, 0, sizeof(*old_prefs));
if (!old_prefs || !file || file.read((uint8_t *)&header, sizeof(header)) != sizeof(header) ||
file.read((uint8_t *)old_prefs, plan.payload_len) != plan.payload_len) {
setMQTTPrefsDefaults(&_mqtt_prefs);
_mqtt_prefs_hold = true;
MESH_DEBUG_PRINTLN("MQTT: /mqtt_prefs read failed, using defaults (file preserved)");
} else if (!MQTTPrefsCodec::isPlausibleV1(*old_prefs, plan.payload_len)) {
setMQTTPrefsDefaults(&_mqtt_prefs);
_mqtt_prefs_hold = true;
MESH_DEBUG_PRINTLN("MQTT: /mqtt_prefs v1 content failed plausibility checks; source preserved");
} else {
MQTTPrefsCodec::migrateV1(*old_prefs, plan.payload_len, &_mqtt_prefs);
has_observer_fields = plan.observer_fields_present;
mqtt_rewrite_pending = true;
migrated_legacy_mqtt = true;
// Written by a later build with appended fields. Everything this
// binary knows loaded normally; say so, because the next `set` will
// rewrite the file at this length and drop the newer settings.
if (file_size - sizeof(MQTTPrefsHeader) > plan.payload_len) {
MESH_DEBUG_PRINTLN(
"MQTT: /mqtt_prefs written by newer firmware (%u > %u bytes); "
"config loaded, newer settings ignored and dropped on next save",
"known settings loaded; newer binary fields remain in the rollback snapshot",
(unsigned)(file_size - sizeof(MQTTPrefsHeader)),
(unsigned)plan.payload_len);
}
}
delete old_prefs;
if (file) file.close();
} else if (plan.rewrite_legacy) {
bool migrated = false;
@@ -674,16 +909,18 @@ void CommonCLI::loadMQTTPrefs(
case MQTTPrefsCodec::Source::LegacySixSlotAudience:
case MQTTPrefsCodec::Source::LegacySixSlotAudienceRx:
case MQTTPrefsCodec::Source::LegacySixSlot: {
Legacy6SlotMQTTPrefs old_prefs = {};
if (file.read((uint8_t *)&old_prefs, plan.payload_len) == plan.payload_len) {
Legacy6SlotMQTTPrefs* old_prefs = new (std::nothrow) Legacy6SlotMQTTPrefs;
if (old_prefs) memset(old_prefs, 0, sizeof(*old_prefs));
if (old_prefs && file.read((uint8_t *)old_prefs, plan.payload_len) == plan.payload_len) {
if (MQTTPrefsCodec::isPlausibleLegacy(plan.source,
(const uint8_t *)&old_prefs, plan.payload_len)) {
MQTTPrefsCodec::migrateLegacySixSlot(old_prefs, plan.source, &_mqtt_prefs);
(const uint8_t *)old_prefs, plan.payload_len)) {
MQTTPrefsCodec::migrateLegacySixSlot(*old_prefs, plan.source, &_mqtt_prefs);
migrated = true;
} else {
MESH_DEBUG_PRINTLN("MQTT: /mqtt_prefs legacy content failed plausibility checks");
}
}
delete old_prefs;
break;
}
default:
@@ -742,9 +979,9 @@ void CommonCLI::loadMQTTPrefs(
if (mqtt_rewrite_pending) {
legacy_upgrade->requireMqttRewrite();
if (migrated_legacy_mqtt) {
MESH_DEBUG_PRINTLN("MQTT: Migrating headerless /mqtt_prefs to versioned layout");
MESH_DEBUG_PRINTLN("MQTT: Migrating binary /mqtt_prefs to /mqtt.json");
} else {
MESH_DEBUG_PRINTLN("MQTT: Persisting observer tail into /mqtt_prefs before /com_prefs compaction");
MESH_DEBUG_PRINTLN("MQTT: Persisting observer tail into /mqtt.json before /com_prefs compaction");
}
if (saveMQTTPrefs(fs)) {
legacy_upgrade->recordMqttSave(true);
@@ -754,7 +991,7 @@ void CommonCLI::loadMQTTPrefs(
// untouched; the next boot can recover the tail and retry the transaction.
_mqtt_prefs_hold = true;
legacy_upgrade->recordMqttSave(false);
MESH_DEBUG_PRINTLN("MQTT: /mqtt_prefs migration save failed; legacy files preserved and held");
MESH_DEBUG_PRINTLN("MQTT: /mqtt.json migration save failed; legacy files preserved and held");
}
}
}
@@ -763,26 +1000,71 @@ bool CommonCLI::saveMQTTPrefs(FILESYSTEM* fs) {
if (_mqtt_prefs_hold) {
// Loading deliberately preserved the source file. Do not replace it with this
// boot's defaults after an unsupported, corrupt, or temporarily failed read.
MESH_DEBUG_PRINTLN("MQTT: /mqtt_prefs held, not overwriting");
MESH_DEBUG_PRINTLN("MQTT: observer preference source held, not overwriting /mqtt.json");
return false;
}
// Write header and payload sequentially so the transaction needs no second
// full-size (2.8 KiB) staging buffer on constrained targets. The length is
// the shortest that still round-trips this config, so a node with default
// packet filters keeps writing a payload older firmware can read.
const size_t payload_len = MQTTPrefsCodec::payloadLenFor(_mqtt_prefs);
const MQTTPrefsHeader header = MQTTPrefsCodec::makeHeader(payload_len);
MQTTPrefsFileStore store(fs);
const MQTTPrefsAtomicStore::Result result = MQTTPrefsAtomicStore::write(
store, (const uint8_t *)&header, sizeof(header),
(const uint8_t *)&_mqtt_prefs, payload_len);
if (!MQTTPrefsAtomicStore::committed(result)) {
MESH_DEBUG_PRINTLN("MQTT: atomic /mqtt_prefs save failed at %s; source preserved",
mqttPrefsSaveResultName(result));
MQTTPrefs* repair_defaults = new (std::nothrow) MQTTPrefs;
if (repair_defaults == nullptr) {
MESH_DEBUG_PRINTLN("MQTT: no memory to normalize observer settings before save");
return false;
}
return true;
setMQTTPrefsDefaults(repair_defaults);
MQTTPrefsSerializer serializer(&_mqtt_prefs, repair_defaults);
// The serializer hierarchy copies the default values it needs. Release this
// large temporary before file I/O and the independent verification scratch.
delete repair_defaults;
bool repaired = false;
if (!serializer.normalize(&repaired)) return false;
if (repaired) MESH_DEBUG_PRINTLN("MQTT: normalized out-of-range observer settings before save");
MQTTPrefsJsonFileStore store(fs);
bool verify_oom = false;
const MQTTPrefsAtomicStore::VerifiedImageResult result =
MQTTPrefsAtomicStore::writeVerifiedImage(
store,
[&]() -> bool {
MQTTPrefsStoreStream stream(&store);
return serializer.saveSerial(stream) && stream.ok();
},
[&]() -> bool {
MQTTPrefs* verify = new (std::nothrow) MQTTPrefs;
if (verify == nullptr) {
verify_oom = true;
return false;
}
const JsonPrefsLoadResult verify_result =
loadMqttJsonFile(fs, "/mqtt.json.tmp", verify);
delete verify;
// saveSerial() emits already-normalized values. Needing another
// repair here means save/load is not idempotent.
return verify_result == JsonPrefsLoadResult::Loaded;
});
switch (result) {
case MQTTPrefsAtomicStore::VerifiedImageResult::Committed:
return true;
case MQTTPrefsAtomicStore::VerifiedImageResult::BeginFailed:
MESH_DEBUG_PRINTLN("MQTT: atomic /mqtt.json save failed at begin; source preserved");
break;
case MQTTPrefsAtomicStore::VerifiedImageResult::WriteFailed:
MESH_DEBUG_PRINTLN("MQTT: atomic /mqtt.json save failed during write; source preserved");
break;
case MQTTPrefsAtomicStore::VerifiedImageResult::FinishFailed:
MESH_DEBUG_PRINTLN("MQTT: atomic /mqtt.json save failed during checksum verification; source preserved");
break;
case MQTTPrefsAtomicStore::VerifiedImageResult::VerifyFailed:
if (verify_oom) {
MESH_DEBUG_PRINTLN("MQTT: no memory to validate /mqtt.json temp; source preserved");
} else {
MESH_DEBUG_PRINTLN("MQTT: generated /mqtt.json temp failed schema validation; source preserved");
}
break;
case MQTTPrefsAtomicStore::VerifiedImageResult::CommitFailed:
MESH_DEBUG_PRINTLN("MQTT: atomic /mqtt.json save failed during rename; recovery files preserved");
break;
}
return false;
}
#endif
@@ -1419,6 +1701,15 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, "Error: delay must be between 0-10000 ms");
}
} else if (memcmp(config, "bridge.source ", 14) == 0) {
#ifdef WITH_MQTT_BRIDGE
MQTTPrefs* observer_rollback = new (std::nothrow) MQTTPrefs;
if (observer_rollback == nullptr) {
strcpy(reply, "Error: insufficient memory to update observer setting");
return;
}
memcpy(observer_rollback, &_mqtt_prefs, sizeof(*observer_rollback));
const uint8_t old_bridge_pkt_src = _prefs->bridge_pkt_src;
#endif
_prefs->bridge_pkt_src = memcmp(&config[14], "rx", 2) == 0;
#ifdef WITH_MQTT_BRIDGE
if (_prefs->bridge_pkt_src == 1) {
@@ -1428,6 +1719,15 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
_mqtt_prefs.mqtt_rx_enabled = 0;
_mqtt_prefs.mqtt_tx_enabled = 1;
}
_observer_prefs_rollback = observer_rollback;
if (!persistObserverPrefs(reply)) {
_prefs->bridge_pkt_src = old_bridge_pkt_src;
_observer_prefs_rollback = nullptr;
delete observer_rollback;
return;
}
_observer_prefs_rollback = nullptr;
delete observer_rollback;
#endif
savePrefs();
strcpy(reply, "OK");