Harden storage transactions and deferred radio settings
This commit is contained in:
1 parent
8f09daaad8
commit
b4315dabdb
26 files changed
+1770
-153
No files matched your search
Vendored
+5
@@ -75,6 +75,11 @@ public:
|
||||
Callbacks* _callbacks=&callbacks;
|
||||
Board* _board=&board;
|
||||
void savePrefs() { callbacks.savePrefs(); }
|
||||
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);
|
||||
callbacks.savePrefs(); return true;
|
||||
}
|
||||
void handleSetCmd(uint32_t, char* command, char* reply) {
|
||||
const char* config=command+4;
|
||||
@SET@
|
||||
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <Arduino.h>
|
||||
|
||||
enum { FILE_O_READ = 0, FILE_O_WRITE = 1, LFS_ERR_NOENT = -2 };
|
||||
class FakeFilesystem;
|
||||
class File {
|
||||
FakeFilesystem* fs = nullptr;
|
||||
std::string path;
|
||||
size_t position = 0;
|
||||
bool writing = false;
|
||||
public:
|
||||
File() = default;
|
||||
explicit File(FakeFilesystem& filesystem) : fs(&filesystem) {}
|
||||
File(FakeFilesystem* filesystem, const char* name, bool write)
|
||||
: fs(filesystem), path(name), writing(write) {}
|
||||
explicit operator bool() const { return fs != nullptr; }
|
||||
bool open(const char* name, uint8_t mode);
|
||||
size_t read(uint8_t* bytes, size_t length);
|
||||
size_t write(const uint8_t* bytes, size_t length);
|
||||
size_t size() const;
|
||||
void flush() {}
|
||||
void close() { fs = nullptr; }
|
||||
};
|
||||
|
||||
class FakeFilesystem {
|
||||
public:
|
||||
using Files = std::map<std::string, std::vector<uint8_t>>;
|
||||
Files files;
|
||||
size_t max_write = std::numeric_limits<size_t>::max();
|
||||
size_t max_read = std::numeric_limits<size_t>::max();
|
||||
std::string fail_open;
|
||||
int stat_error = 0;
|
||||
unsigned fail_rename = 0, renames = 0, writes = 0;
|
||||
std::vector<Files> snapshots;
|
||||
bool exists(const char* path) const {
|
||||
#if defined(ESP32_PLATFORM)
|
||||
if (fail_open == path) return false; // ESP32 VFS exists opens the file.
|
||||
#endif
|
||||
return files.count(path) != 0;
|
||||
}
|
||||
bool mkdir(const char*) { return true; }
|
||||
bool remove(const char* path) { return files.erase(path) != 0; }
|
||||
void _lockFS() {}
|
||||
void _unlockFS() {}
|
||||
FakeFilesystem* _getFS() { return this; }
|
||||
File open(const char* path, const char* mode = "r", bool = false) {
|
||||
if (fail_open == path) return File();
|
||||
if (*mode != 'r') {
|
||||
files[path].clear();
|
||||
return File(this, path, true);
|
||||
}
|
||||
return exists(path) ? File(this, path, false) : File();
|
||||
}
|
||||
bool rename(const char* from, const char* to) {
|
||||
++renames;
|
||||
if (renames == fail_rename || !exists(from)) return false;
|
||||
#if defined(ESP32_PLATFORM)
|
||||
if (exists(to)) return false;
|
||||
#endif
|
||||
files[to] = files.at(from);
|
||||
files.erase(from);
|
||||
snapshots.push_back(files);
|
||||
return true;
|
||||
}
|
||||
} filesystem;
|
||||
|
||||
bool File::open(const char* name, uint8_t mode) {
|
||||
if (!fs) return false;
|
||||
*this = fs->open(name, mode == FILE_O_WRITE ? "w" : "r");
|
||||
return static_cast<bool>(*this);
|
||||
}
|
||||
size_t File::read(uint8_t* bytes, size_t length) {
|
||||
if (!fs || writing) return 0;
|
||||
const auto& data = fs->files.at(path);
|
||||
const size_t count = std::min({length, fs->max_read,
|
||||
data.size() - std::min(position, data.size())});
|
||||
if (count) memcpy(bytes, data.data() + position, count);
|
||||
position += count;
|
||||
return count;
|
||||
}
|
||||
size_t File::write(const uint8_t* bytes, size_t length) {
|
||||
if (!fs || !writing) return 0;
|
||||
++fs->writes;
|
||||
const size_t count = std::min(length, fs->max_write);
|
||||
auto& data = fs->files[path];
|
||||
data.resize(position + count);
|
||||
if (count) memcpy(data.data() + position, bytes, count);
|
||||
position += count;
|
||||
fs->snapshots.push_back(fs->files);
|
||||
return count;
|
||||
}
|
||||
size_t File::size() const { return fs ? fs->files.at(path).size() : 0; }
|
||||
|
||||
#if defined(RP2040_PLATFORM)
|
||||
#include <FS.h>
|
||||
#define FILESYSTEM fs::FS
|
||||
#else
|
||||
#define FILESYSTEM FakeFilesystem
|
||||
#endif
|
||||
#include <helpers/ContactInfo.h>
|
||||
#include <helpers/PersistentStoreFormat.h>
|
||||
#include <helpers/ContactFileTransaction.h>
|
||||
#define ATOMIC_FILE_WRITER_IMPLEMENTATION
|
||||
#include <helpers/AtomicFileWriter.h>
|
||||
|
||||
struct stat {};
|
||||
int stat(const char* path, struct stat*) {
|
||||
assert(strncmp(path, "/spiffs", 7) == 0);
|
||||
errno = filesystem.stat_error;
|
||||
if (errno) return -1;
|
||||
if (filesystem.files.count(path + 7) == 0) { errno = ENOENT; return -1; }
|
||||
return 0;
|
||||
}
|
||||
struct lfs_info {};
|
||||
int lfs_stat(FakeFilesystem* fs, const char* path, lfs_info*) {
|
||||
if (fs->stat_error) return -5;
|
||||
return fs->files.count(path) != 0 ? 0 : LFS_ERR_NOENT;
|
||||
}
|
||||
|
||||
#if defined(STM32_PLATFORM)
|
||||
static const char* identity_path = "/_main.id";
|
||||
#else
|
||||
static const char* identity_path = "/identity/_main.id";
|
||||
#endif
|
||||
|
||||
struct Host {
|
||||
size_t capacity = 100;
|
||||
std::vector<ContactInfo> contacts;
|
||||
bool getContactForSave(uint32_t index, ContactInfo& c) {
|
||||
if (index >= contacts.size()) return false;
|
||||
c = contacts[index];
|
||||
return true;
|
||||
}
|
||||
bool onContactLoaded(const ContactInfo& c) {
|
||||
if (contacts.size() >= capacity) return false;
|
||||
contacts.push_back(c);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
using DataStoreHost = Host;
|
||||
|
||||
class DataStore {
|
||||
FakeFilesystem* _fs = &filesystem;
|
||||
bool _identity_creation_blocked = false;
|
||||
bool _channel_load_incomplete = false;
|
||||
bool _uncached_contact_load_incomplete = false;
|
||||
struct IdentityAdapter {
|
||||
bool load(const char*, mesh::LocalIdentity&) {
|
||||
File file = filesystem.open(identity_path);
|
||||
uint8_t data[96];
|
||||
return file && file.read(data, sizeof(data)) == sizeof(data);
|
||||
}
|
||||
bool save(const char*, const mesh::LocalIdentity&) {
|
||||
++filesystem.writes;
|
||||
return true;
|
||||
}
|
||||
} identity_store;
|
||||
public:
|
||||
FakeFilesystem* _getContactsChannelsFS() { return _fs; }
|
||||
File openRead(FakeFilesystem* fs, const char* path) { return fs->open(path); }
|
||||
bool loadMainIdentity(mesh::LocalIdentity&);
|
||||
bool canCreateMainIdentity() const;
|
||||
bool saveMainIdentity(const mesh::LocalIdentity&);
|
||||
void loadContacts(DataStoreHost*);
|
||||
bool saveContacts(DataStoreHost*, bool (*filter)(const ContactInfo&) = nullptr);
|
||||
bool hasIncompleteContactLoad() const;
|
||||
};
|
||||
#include "store_under_test.h"
|
||||
|
||||
static ContactInfo contact(uint8_t value) {
|
||||
ContactInfo c{};
|
||||
memset(c.id.pub_key, value, sizeof(c.id.pub_key));
|
||||
memset(c.name, 0, sizeof(c.name));
|
||||
c.name[0] = 'A' + value;
|
||||
c.type = 1;
|
||||
c.out_path_len = OUT_PATH_UNKNOWN;
|
||||
uint8_t path[64] = {};
|
||||
assert(c.setRawPath(path));
|
||||
return c;
|
||||
}
|
||||
|
||||
static void identity_checks() {
|
||||
filesystem = FakeFilesystem();
|
||||
DataStore fresh;
|
||||
mesh::LocalIdentity identity;
|
||||
assert(!fresh.loadMainIdentity(identity));
|
||||
assert(fresh.canCreateMainIdentity());
|
||||
assert(fresh.saveMainIdentity(identity));
|
||||
for (unsigned fault = 0; fault < 4; ++fault) {
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files[identity_path] = std::vector<uint8_t>(96, 7);
|
||||
if (fault == 0) filesystem.fail_open = identity_path;
|
||||
if (fault == 1) filesystem.max_read = 32;
|
||||
if (fault == 2) filesystem.files[identity_path].resize(32);
|
||||
if (fault == 3) filesystem.stat_error = EIO;
|
||||
#if defined(RP2040_PLATFORM)
|
||||
if (fault == 3) continue; // this backend exposes only bool stat/exists
|
||||
#endif
|
||||
const auto original = filesystem.files;
|
||||
DataStore store;
|
||||
assert(!store.loadMainIdentity(identity));
|
||||
assert(!store.canCreateMainIdentity());
|
||||
assert(!store.saveMainIdentity(identity));
|
||||
assert(filesystem.writes == 0 && filesystem.files == original);
|
||||
filesystem.fail_open.clear();
|
||||
filesystem.max_read = std::numeric_limits<size_t>::max();
|
||||
filesystem.stat_error = 0;
|
||||
filesystem.files[identity_path].resize(96);
|
||||
DataStore rebooted;
|
||||
assert(rebooted.loadMainIdentity(identity));
|
||||
assert(rebooted.canCreateMainIdentity());
|
||||
}
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> make_original() {
|
||||
filesystem = FakeFilesystem();
|
||||
DataStore store;
|
||||
Host host;
|
||||
host.contacts = {contact(1), contact(2)};
|
||||
assert(store.saveContacts(&host));
|
||||
return filesystem.files.at("/contacts3");
|
||||
}
|
||||
|
||||
static void contact_checks() {
|
||||
const auto original = make_original();
|
||||
{
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files["/contacts3"] = original;
|
||||
DataStore store;
|
||||
Host empty;
|
||||
assert(store.saveContacts(&empty));
|
||||
assert(filesystem.files.at("/contacts3").empty());
|
||||
store.loadContacts(&empty);
|
||||
assert(!store.hasIncompleteContactLoad() && empty.contacts.empty());
|
||||
}
|
||||
Host replacement;
|
||||
replacement.contacts = {contact(3), contact(4), contact(5)};
|
||||
for (unsigned fault = 0; fault < 5; ++fault) {
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files["/contacts3"] = original;
|
||||
if (fault == 0) filesystem.max_write = 2;
|
||||
if (fault == 1) filesystem.fail_open = "/contacts3.tmp";
|
||||
if (fault == 2) filesystem.max_read = 2;
|
||||
if (fault == 3) filesystem.fail_rename = 1;
|
||||
if (fault == 4) filesystem.fail_rename = 2;
|
||||
#if defined(STM32_PLATFORM)
|
||||
if (fault == 4) continue; // LittleFS atomically replaces in one rename
|
||||
#endif
|
||||
DataStore store;
|
||||
assert(!store.saveContacts(&replacement));
|
||||
assert(filesystem.files.at("/contacts3") == original);
|
||||
}
|
||||
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files["/contacts3"] = original;
|
||||
DataStore store;
|
||||
assert(store.saveContacts(&replacement));
|
||||
const auto updated = filesystem.files.at("/contacts3");
|
||||
assert(updated.size() == 3 * mesh::storage::CONTACT_RECORD_SIZE);
|
||||
// Reboot from every write/rename boundary of the actual transaction.
|
||||
const auto snapshots = filesystem.snapshots;
|
||||
for (const auto& snapshot : snapshots) {
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files = snapshot;
|
||||
DataStore rebooted;
|
||||
Host loaded;
|
||||
rebooted.loadContacts(&loaded);
|
||||
assert(!rebooted.hasIncompleteContactLoad());
|
||||
assert(loaded.contacts.size() == 2 || loaded.contacts.size() == 3);
|
||||
assert(filesystem.files.at("/contacts3") == original
|
||||
|| filesystem.files.at("/contacts3") == updated);
|
||||
}
|
||||
for (unsigned fault = 0; fault < 4; ++fault) {
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files["/contacts3"] = original;
|
||||
if (fault == 0) filesystem.fail_open = "/contacts3";
|
||||
if (fault == 1) filesystem.max_read = 16;
|
||||
if (fault == 2) filesystem.files["/contacts3"].pop_back();
|
||||
DataStore rebooted;
|
||||
Host loaded;
|
||||
if (fault == 3) loaded.capacity = 1;
|
||||
rebooted.loadContacts(&loaded);
|
||||
assert(rebooted.hasIncompleteContactLoad());
|
||||
const auto unchanged = filesystem.files;
|
||||
assert(!rebooted.saveContacts(&loaded));
|
||||
assert(filesystem.files == unchanged);
|
||||
}
|
||||
#if defined(ESP32_PLATFORM)
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files["/contacts3.bak"] = original;
|
||||
filesystem.fail_open = "/contacts3.bak";
|
||||
DataStore recovering;
|
||||
Host unavailable;
|
||||
recovering.loadContacts(&unavailable);
|
||||
assert(recovering.hasIncompleteContactLoad());
|
||||
assert(!recovering.saveContacts(&unavailable));
|
||||
assert(filesystem.files.at("/contacts3.bak") == original);
|
||||
#endif
|
||||
filesystem = FakeFilesystem();
|
||||
filesystem.files["/contacts3"] = original;
|
||||
DataStore filtered;
|
||||
assert(filtered.saveContacts(&replacement,
|
||||
[](const ContactInfo&) -> bool { return false; }));
|
||||
assert(filesystem.files.at("/contacts3").empty());
|
||||
}
|
||||
|
||||
int main() {
|
||||
identity_checks();
|
||||
contact_checks();
|
||||
}
|
||||
@@ -146,6 +146,11 @@ bool contactPathPresence(FakeFilesystem* fs, const char* path, bool& present) {
|
||||
present = fs->exists(path);
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
bool companionPathPresence(FakeFilesystem* fs, const char* path, bool& present) {
|
||||
present = fs->exists(path);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
// The narrow hardware adapter below supplies the same filesystem/host seams.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Exercise the actual common preference store and recovery after failed commits."""
|
||||
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]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <helpers/CommonPrefsRecovery.h>
|
||||
#include <helpers/MQTTPrefsAtomicStore.h>
|
||||
class MemoryFS;
|
||||
class File {
|
||||
MemoryFS* fs = nullptr;
|
||||
std::shared_ptr<std::vector<uint8_t>> bytes;
|
||||
bool valid = false;
|
||||
public:
|
||||
File() = default;
|
||||
File(MemoryFS* owner, std::shared_ptr<std::vector<uint8_t>> contents)
|
||||
: fs(owner), bytes(contents), valid(true) {}
|
||||
operator bool() const { return valid; }
|
||||
size_t write(const uint8_t*, size_t);
|
||||
size_t size() const { return valid ? bytes->size() : 0; }
|
||||
void close() { valid = false; }
|
||||
};
|
||||
class MemoryFS {
|
||||
public:
|
||||
std::map<std::string, std::shared_ptr<std::vector<uint8_t>>> files;
|
||||
std::set<std::string> faults;
|
||||
bool short_write = false;
|
||||
bool exists(const char* path) const { return files.count(path) != 0; }
|
||||
bool remove(const char* path) {
|
||||
if (faults.count(std::string("remove:") + path)) return false;
|
||||
return files.erase(path) != 0;
|
||||
}
|
||||
bool rename(const char* from, const char* to) {
|
||||
if (faults.count(std::string("rename:") + from + ":" + to)
|
||||
|| !exists(from) || exists(to)) return false;
|
||||
files[to] = files[from]; files.erase(from); return true;
|
||||
}
|
||||
File open(const char* path, const char* mode = "r", bool = false) {
|
||||
if (faults.count(std::string("open:") + mode + ":" + path)) return {};
|
||||
if (mode[0] == 'w') files[path] = std::make_shared<std::vector<uint8_t>>();
|
||||
if (!exists(path)) return {};
|
||||
return File(this, files[path]);
|
||||
}
|
||||
void put(const char* path, const std::vector<uint8_t>& image) {
|
||||
files[path] = std::make_shared<std::vector<uint8_t>>(image);
|
||||
}
|
||||
const std::vector<uint8_t>& get(const char* path) const { return *files.at(path); }
|
||||
};
|
||||
size_t File::write(const uint8_t* data, size_t count) {
|
||||
if (!valid) return 0;
|
||||
if (fs->short_write && count) --count;
|
||||
bytes->insert(bytes->end(), data, data + count);
|
||||
return count;
|
||||
}
|
||||
using FILESYSTEM = MemoryFS;
|
||||
@STORE@;
|
||||
class CommonCLI {
|
||||
public:
|
||||
bool recoverCommonPrefsFiles(FILESYSTEM*);
|
||||
};
|
||||
@RECOVERY@
|
||||
const std::vector<uint8_t> previous_image = {1, 2, 3, 4};
|
||||
const std::vector<uint8_t> candidate_image = {9, 8, 7, 6, 5};
|
||||
bool save(MemoryFS& fs) {
|
||||
CommonPrefsFileStore store(&fs);
|
||||
return MQTTPrefsAtomicStore::imageCommitted(MQTTPrefsAtomicStore::writeImage(
|
||||
store, [](CommonPrefsFileStore& out) {
|
||||
return out.write(candidate_image.data(), candidate_image.size()) == candidate_image.size();
|
||||
}));
|
||||
}
|
||||
void assertRecoveredPrevious(MemoryFS& fs) {
|
||||
CommonCLI cli;
|
||||
fs.faults.clear(); fs.short_write = false;
|
||||
assert(cli.recoverCommonPrefsFiles(&fs));
|
||||
assert(fs.get("/com_prefs") == previous_image);
|
||||
assert(!fs.exists("/com_prefs.tmp") && !fs.exists("/com_prefs.bak"));
|
||||
assert(save(fs));
|
||||
assert(cli.recoverCommonPrefsFiles(&fs));
|
||||
assert(fs.get("/com_prefs") == candidate_image);
|
||||
}
|
||||
int main() {
|
||||
unsigned scenarios = 0;
|
||||
for (const char* fault : {"open:w:/com_prefs.tmp", "open:r:/com_prefs.tmp",
|
||||
"rename:/com_prefs:/com_prefs.bak", "rename:/com_prefs.tmp:/com_prefs"}) {
|
||||
MemoryFS fs; fs.put("/com_prefs", previous_image); fs.faults.insert(fault);
|
||||
assert(!save(fs)); assertRecoveredPrevious(fs); ++scenarios;
|
||||
}
|
||||
{ MemoryFS fs; fs.put("/com_prefs", previous_image); fs.short_write = true;
|
||||
assert(!save(fs)); assertRecoveredPrevious(fs); ++scenarios; }
|
||||
for (bool restore_fails : {false, true}) {
|
||||
for (bool discard_fails : {false, true}) {
|
||||
MemoryFS fs; fs.put("/com_prefs", previous_image);
|
||||
fs.faults.insert("rename:/com_prefs.tmp:/com_prefs");
|
||||
if (restore_fails) fs.faults.insert("rename:/com_prefs.bak:/com_prefs");
|
||||
if (discard_fails) fs.faults.insert("remove:/com_prefs.tmp");
|
||||
assert(!save(fs));
|
||||
if (restore_fails) {
|
||||
CommonCLI cli;
|
||||
assert(!cli.recoverCommonPrefsFiles(&fs));
|
||||
assert(!fs.exists("/com_prefs"));
|
||||
assert(fs.get("/com_prefs.bak") == previous_image);
|
||||
}
|
||||
assertRecoveredPrevious(fs); ++scenarios;
|
||||
}
|
||||
}
|
||||
{ // Before a power cut publishes the candidate, backup remains authoritative.
|
||||
MemoryFS fs; fs.put("/com_prefs.bak", previous_image);
|
||||
fs.put("/com_prefs.tmp", candidate_image);
|
||||
assertRecoveredPrevious(fs); ++scenarios;
|
||||
}
|
||||
{ // After publication, cleanup failure cannot roll back the accepted image.
|
||||
MemoryFS fs; fs.put("/com_prefs", previous_image);
|
||||
fs.faults.insert("remove:/com_prefs.bak");
|
||||
assert(save(fs)); assert(fs.get("/com_prefs") == candidate_image);
|
||||
fs.faults.clear(); CommonCLI cli;
|
||||
assert(cli.recoverCommonPrefsFiles(&fs));
|
||||
assert(fs.get("/com_prefs") == candidate_image);
|
||||
assert(!fs.exists("/com_prefs.bak")); ++scenarios;
|
||||
}
|
||||
{ // A failed first save must not become a successful save on reboot.
|
||||
MemoryFS fs; fs.faults.insert("rename:/com_prefs.tmp:/com_prefs");
|
||||
fs.faults.insert("remove:/com_prefs.tmp");
|
||||
assert(!save(fs)); fs.faults.clear(); CommonCLI cli;
|
||||
assert(cli.recoverCommonPrefsFiles(&fs));
|
||||
assert(!fs.exists("/com_prefs") && !fs.exists("/com_prefs.tmp")); ++scenarios;
|
||||
}
|
||||
{ // Recovery cleanup can fail without losing the previous image.
|
||||
MemoryFS fs; fs.put("/com_prefs.bak", previous_image);
|
||||
fs.put("/com_prefs.tmp", candidate_image);
|
||||
fs.faults.insert("remove:/com_prefs.tmp"); CommonCLI cli;
|
||||
assert(!cli.recoverCommonPrefsFiles(&fs));
|
||||
assert(fs.get("/com_prefs") == previous_image);
|
||||
assertRecoveredPrevious(fs); ++scenarios;
|
||||
}
|
||||
printf("%u actual common preference commit/recovery scenarios passed\n", scenarios);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CommonPrefsCommitTest(unittest.TestCase):
|
||||
def test_actual_store_commit_and_recovery(self):
|
||||
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="utf-8")
|
||||
harness = HARNESS.replace("@STORE@", extract_braced(source, "class CommonPrefsFileStore"))
|
||||
harness = harness.replace("@RECOVERY@", extract_braced(
|
||||
source, "bool CommonCLI::recoverCommonPrefsFiles("))
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-common-commit-") as temp:
|
||||
cpp = Path(temp) / "test.cpp"
|
||||
exe = Path(temp) / ("test.exe" if os.name == "nt" else "test")
|
||||
cpp.write_text(harness, encoding="utf-8")
|
||||
subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17", "-Wall", "-Wextra",
|
||||
"-Werror", "-I", str(ROOT / "src"), str(cpp), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Exercise production infrastructure radio saves with real file transactions."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_replay_reset_integration import extract_braced
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <math.h>
|
||||
#include <cstring>
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include "ContactFileTransaction.h"
|
||||
#define ATOMIC_FILE_WRITER_IMPLEMENTATION
|
||||
#include <helpers/AtomicFileWriter.h>
|
||||
#include <helpers/PrefsSaveRouting.h>
|
||||
#define MESH_DEBUG_PRINTLN(...) ((void)0)
|
||||
#define MIN_LORA_TX_POWER -9
|
||||
#define MAX_LORA_TX_POWER 22
|
||||
#include <helpers/radiolib/RadioPowerLimits.h>
|
||||
struct NodePrefs { @FIELDS@ };
|
||||
void markDirectRetryPrefsValid(NodePrefs*) {}
|
||||
bool isValidLoRaBandwidth(float bw) { return bw==62.5f || bw==125; }
|
||||
namespace mesh { struct RadioProfiles { static constexpr unsigned MaxPreamble=65535; }; }
|
||||
struct Profiles {
|
||||
bool accepted=true;
|
||||
uint16_t saved=48;
|
||||
bool acceptsPrimary(float,float,uint8_t,uint8_t,uint16_t) const { return accepted; }
|
||||
void adoptPrimaryPreamble(uint16_t value) { saved=value; }
|
||||
};
|
||||
struct CommonCLI;
|
||||
struct Callbacks {
|
||||
CommonCLI* cli;
|
||||
void savePrefs(PrefsSaveRouting::Scope scope);
|
||||
};
|
||||
struct CommonCLI {
|
||||
MemoryFS fs;
|
||||
NodePrefs prefs{};
|
||||
NodePrefs* _prefs=&prefs;
|
||||
Profiles _radio_profiles;
|
||||
Callbacks callbacks{this};
|
||||
Callbacks* _callbacks=&callbacks;
|
||||
bool _common_save_result_known=false, _common_save_succeeded=false;
|
||||
CommonCLI() {
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
fs.rename_replaces=true;
|
||||
#endif
|
||||
prefs.freq=910; prefs.bw=62.5f; prefs.sf=7; prefs.cr=5;
|
||||
prefs.tx_power_dbm=30; prefs.primary_radio_preamble=48;
|
||||
prefs.rx_ps_rx_us=111; prefs.rx_ps_sleep_us=222;
|
||||
}
|
||||
void savePrefs(FILESYSTEM*,PrefsSaveRouting::Scope);
|
||||
bool saveCommonPrefs();
|
||||
bool savePrimaryRadioParams(float,float,uint8_t,uint8_t,uint16_t);
|
||||
static void recalculateRxPowerSavingFromLevel(NodePrefs* p) {
|
||||
p->rx_ps_rx_us=p->sf*100; p->rx_ps_sleep_us=p->cr*200;
|
||||
}
|
||||
uint16_t loadTail(std::vector<uint8_t> bytes) {
|
||||
fs.files["/tail"]=bytes;
|
||||
File file=fs.open("/tail");
|
||||
@TAIL@
|
||||
return prefs.primary_radio_preamble;
|
||||
}
|
||||
};
|
||||
void Callbacks::savePrefs(PrefsSaveRouting::Scope scope) { cli->savePrefs(&cli->fs,scope); }
|
||||
@METHODS@
|
||||
@SERIALIZER@
|
||||
struct Capture { std::vector<uint8_t> bytes;
|
||||
size_t write(const uint8_t* p,size_t n) { bytes.insert(bytes.end(),p,p+n);return n; }
|
||||
};
|
||||
int main() {
|
||||
CommonCLI cli;
|
||||
assert(cli.saveCommonPrefs());
|
||||
auto original=cli.fs.files["/com_prefs"];
|
||||
const size_t preamble_offset=original.size()-2;
|
||||
assert(preamble_offset>=864);
|
||||
assert(original[preamble_offset]==48 && original[preamble_offset+1]==0);
|
||||
Capture capture; assert(writeCommonPrefsImage(capture,&cli.prefs));
|
||||
assert(capture.bytes==original); // Both serializers retain the same layout.
|
||||
for (int fault : {0,1,2,3,4}) {
|
||||
const NodePrefs previous=cli.prefs;
|
||||
if(fault==0)cli.fs.fail_write=true;
|
||||
if(fault==1)cli.fs.fail_write_after=100;
|
||||
if(fault==2)cli.fs.fail_read_open=true;
|
||||
if(fault==3)cli.fs.fail_rename=1;
|
||||
if(fault==4)cli._radio_profiles.accepted=false;
|
||||
assert(!cli.savePrimaryRadioParams(920,125,9,6,96));
|
||||
assert(cli.prefs.freq==previous.freq && cli.prefs.bw==previous.bw);
|
||||
assert(cli.prefs.sf==previous.sf && cli.prefs.cr==previous.cr);
|
||||
assert(cli.prefs.tx_power_dbm==previous.tx_power_dbm);
|
||||
assert(cli.prefs.rx_ps_rx_us==previous.rx_ps_rx_us);
|
||||
assert(cli.prefs.rx_ps_sleep_us==previous.rx_ps_sleep_us);
|
||||
assert(cli.prefs.primary_radio_preamble==48 && cli._radio_profiles.saved==48);
|
||||
assert(cli.fs.files["/com_prefs"]==original);
|
||||
cli.fs.fail_write=false;cli.fs.fail_write_after=-1;
|
||||
cli.fs.fail_read_open=false;cli.fs.fail_rename=0;
|
||||
cli._radio_profiles.accepted=true;
|
||||
}
|
||||
assert(cli.savePrimaryRadioParams(920,125,9,6,96));
|
||||
auto committed=cli.fs.files["/com_prefs"];
|
||||
float freq=0,bw=0;memcpy(&freq,committed.data()+72,4);memcpy(&bw,committed.data()+116,4);
|
||||
assert(freq==920 && bw==125 && committed[112]==9 && committed[113]==6);
|
||||
assert(committed[preamble_offset]==96 && committed[preamble_offset+1]==0);
|
||||
assert(cli._radio_profiles.saved==96 && cli.prefs.tx_power_dbm==22);
|
||||
assert(cli.prefs.rx_ps_rx_us==900 && cli.prefs.rx_ps_sleep_us==1200);
|
||||
// Old and torn tails preserve the imported legacy preamble; valid tails win.
|
||||
assert(cli.loadTail({0})==96);
|
||||
assert(cli.loadTail({0,32})==96);
|
||||
assert(cli.loadTail({0,64,0})==64);
|
||||
assert(cli.loadTail({0,7,0})==64);
|
||||
assert(cli.loadTail({0,0,0})==0);
|
||||
for(float bad : {NAN,INFINITY,149.0f,2501.0f})
|
||||
assert(!cli.savePrimaryRadioParams(bad,125,9,6,0));
|
||||
assert(cli.fs.files["/com_prefs"]==committed);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CommonRadioPersistenceTest(unittest.TestCase):
|
||||
def test_production_transactions(self):
|
||||
source = (ROOT / 'src/helpers/CommonCLI.cpp').read_text(encoding='utf-8')
|
||||
header = (ROOT / 'src/helpers/CommonCLI.h').read_text(encoding='utf-8')
|
||||
fields = header.split('class NodePrefs :', 1)[1].split('private:', 1)[0]
|
||||
fields = '\n'.join(re.findall(
|
||||
r'^\s*(?:float|double|char|u?int(?:8|16|32)_t)\s+[^;]+;', fields, re.M))
|
||||
fields = re.sub(r'\s*=\s*[^,;]+', '', fields)
|
||||
for macro in set(re.findall(r'\bFLOOD_\w+', fields)):
|
||||
value = re.search(r'#define\s+' + macro + r'\s+(\d+)', header).group(1)
|
||||
fields = re.sub(r'\b'+macro+r'\b', value, fields)
|
||||
methods = '\n'.join(extract_braced(source, signature) for signature in (
|
||||
'void CommonCLI::savePrefs(FILESYSTEM*', 'bool CommonCLI::saveCommonPrefs(',
|
||||
'bool CommonCLI::savePrimaryRadioParams('))
|
||||
serializer = 'template<typename Writer>\n' + extract_braced(source, 'static bool writeCommonPrefsImage(')
|
||||
tail = extract_braced(source, 'if (file.available() >= (int)sizeof(_prefs->bridge_format))')
|
||||
code = HARNESS.replace('@FIELDS@',fields).replace('@METHODS@',methods)
|
||||
code = code.replace('@SERIALIZER@',serializer).replace('@TAIL@',tail)
|
||||
with tempfile.TemporaryDirectory(prefix='common-radio-save-') as directory:
|
||||
work = Path(directory)
|
||||
transaction = (ROOT / 'src/helpers/ContactFileTransaction.h').read_text()
|
||||
(work / 'ContactFileTransaction.h').write_text(transaction.replace(
|
||||
'#include "IdentityStore.h"', '#include <helpers/IdentityStore.h>'))
|
||||
(work / 'test.cpp').write_text(code, encoding='utf-8')
|
||||
for platform in ('NRF52_PLATFORM','STM32_PLATFORM','ESP32_PLATFORM','RP2040_PLATFORM'):
|
||||
with self.subTest(platform=platform):
|
||||
exe = work / 'test'
|
||||
built = subprocess.run(['g++','-std=c++17','-DENABLE_OTA=1','-D'+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/'src'),'-I'+str(ROOT/'src/helpers'),
|
||||
str(work/'test.cpp'),'-o',str(exe)],
|
||||
capture_output=True,text=True,timeout=60)
|
||||
self.assertEqual(built.returncode,0,built.stderr)
|
||||
tested = subprocess.run([str(exe)],capture_output=True,text=True,timeout=10)
|
||||
self.assertEqual(tested.returncode,0,tested.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,359 @@
|
||||
"""Run production OTA policy parsing, Companion commit/rollback, and filesystem storage."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_replay_reset_integration import extract_braced
|
||||
import test_ota_heap_context as heap_test
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cerrno>
|
||||
#include <sys/stat.h>
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#include <helpers/ota/CompanionOtaConfig.h>
|
||||
static MemoryFS* mounted_fs=nullptr;
|
||||
#if defined(ESP32_PLATFORM)
|
||||
extern "C" int stat(const char* path, struct stat*) noexcept {
|
||||
assert(mounted_fs && !strncmp(path, "/spiffs", 7));
|
||||
if (mounted_fs->stat_error) { errno=EIO; return -1; }
|
||||
if (!mounted_fs->files.count(path+7)) { errno=ENOENT; return -1; }
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
namespace mesh { namespace ota {
|
||||
struct Manager {
|
||||
uint8_t af=0, hops=3; uint16_t checkpoint=4, advert=1440;
|
||||
uint8_t autofetch() const { return af; }
|
||||
uint8_t max_hops() const { return hops; }
|
||||
uint16_t checkpoint_blocks() const { return checkpoint; }
|
||||
uint16_t advert_mins() const { return advert; }
|
||||
void set_autofetch(uint8_t v) { af=v; }
|
||||
void set_max_hops(uint8_t v) { hops=v; }
|
||||
void set_checkpoint_blocks(uint16_t v) { checkpoint=v; }
|
||||
void set_advert_mins(uint16_t v) { advert=v; }
|
||||
};
|
||||
struct OtaContext {
|
||||
static constexpr uint8_t AUTOINSTALL_OFF=0, AUTOINSTALL_TRUSTED=1;
|
||||
Manager manager; SignerAllowlist allow;
|
||||
uint8_t autoinstall=0; bool config_dirty=false;
|
||||
};
|
||||
static OtaContext context;
|
||||
static bool acquire_ok=true;
|
||||
static bool ota_acquire_context(char* reply, size_t cap) {
|
||||
if (!acquire_ok) snprintf(reply, cap, "ERR unavailable");
|
||||
return acquire_ok;
|
||||
}
|
||||
static OtaContext& ota_ctx() { return context; }
|
||||
static OtaContext* ota_context_if_active() { return &context; }
|
||||
static void formatSpeed(char* text, size_t) { strcpy(text, "1"); }
|
||||
@IS_CMD@
|
||||
static bool config(const char* rest, char* reply, OtaContext& c) {
|
||||
@CONFIG@
|
||||
return true;
|
||||
}
|
||||
static bool handle_ota_command(const char* command, char* reply, int) {
|
||||
if (!strcmp(command, "ota key add test-key")) {
|
||||
uint8_t key[32]={93};
|
||||
context.allow.add(key); context.config_dirty=true;
|
||||
strcpy(reply, "OK key added (saved)");
|
||||
return true;
|
||||
}
|
||||
const char* rest;
|
||||
if (!is_cmd(command + 4, "config|cfg|set", &rest)) return false;
|
||||
return config(rest, reply, context);
|
||||
}
|
||||
} }
|
||||
static bool companion(const char* command, char* reply, size_t reply_size) {
|
||||
int board=0;
|
||||
@WRAPPER@
|
||||
return false;
|
||||
}
|
||||
using namespace mesh::ota;
|
||||
struct Common {
|
||||
struct Prefs {
|
||||
uint8_t ota_autofetch=0, ota_autoinstall=0, ota_max_hops=3, ota_signer_count=0;
|
||||
uint16_t ota_checkpoint_blocks=4, ota_advert_interval=1440;
|
||||
uint8_t ota_signers[MAX_OTA_SIGNERS][32]={};
|
||||
} prefs;
|
||||
Prefs* _prefs=&prefs;
|
||||
struct Callbacks { bool isTempRadioActive() const { return true; } } callbacks;
|
||||
Callbacks* _callbacks=&callbacks;
|
||||
struct Profiles { bool secondaryTemporary() const { return false; } } _radio_profiles;
|
||||
int board=0; int* _board=&board;
|
||||
bool save_ok=true; int saves=0;
|
||||
bool otaCommandNeedsTempRadio(const char*) const { return false; }
|
||||
bool saveCommonPrefs() { ++saves; return save_ok; }
|
||||
void run(const char* command, char* reply) { @COMMON@ }
|
||||
};
|
||||
static void reboot(MemoryFS& fs) {
|
||||
context=OtaContext();
|
||||
mounted_fs=&fs;
|
||||
beginCompanionOtaConfig(&fs);
|
||||
OtaConfigState loaded;
|
||||
if (loadCompanionOtaConfig(loaded)) loaded.apply(context);
|
||||
}
|
||||
int main() {
|
||||
MemoryFS fs;
|
||||
char reply[160];
|
||||
auto command = [&](const std::string& text, const char* expected) {
|
||||
memset(reply, 0, sizeof reply);
|
||||
assert(companion(text.c_str(), reply, sizeof reply));
|
||||
if (strncmp(reply, expected, strlen(expected)))
|
||||
fprintf(stderr, "%s: expected %s, got %s\n", text.c_str(), expected, reply);
|
||||
assert(!strncmp(reply, expected, strlen(expected)));
|
||||
assert(!context.config_dirty);
|
||||
};
|
||||
reboot(fs);
|
||||
for (const auto* setting : {"hops", "checkpoint", "advert"}) {
|
||||
const auto before=OtaConfigState::capture(context);
|
||||
for (const auto* bad : {"", " ", "x", "-1", "1x", "1 2", "1.0", "4294967296", "9999999999999999999999"}) {
|
||||
command(std::string("ota config ")+setting+" "+bad, "ERR");
|
||||
assert(context.manager.hops==before.hops && context.manager.checkpoint==before.checkpoint
|
||||
&& context.manager.advert==before.advert && fs.files.empty());
|
||||
}
|
||||
command(std::string("ota config ")+setting, "ERR");
|
||||
}
|
||||
command("ota config hops 9", "ERR");
|
||||
command("ota config advert 10081", "ERR");
|
||||
command("ota config checkpoint 4097", "ERR");
|
||||
command("ota config unknown 7", "ERR");
|
||||
for (const auto* bad : {"", "anymore", "signedx", "off extra"})
|
||||
command(std::string("ota config autofetch ")+bad, "ERR");
|
||||
for (const auto* bad : {"", "trustedx", "off extra"})
|
||||
command(std::string("ota config autoinstall ")+bad, "ERR");
|
||||
assert(fs.files.empty());
|
||||
#if defined(OTA_SEEDER_ONLY)
|
||||
command("ota config autofetch any", "ERR");
|
||||
command("ota config autoinstall trusted", "ERR");
|
||||
#else
|
||||
command("ota config autofetch signed", "OK");
|
||||
command("ota config autoinstall trusted", "OK");
|
||||
#endif
|
||||
command("ota config hops 8", "OK");
|
||||
command("ota cfg advert 10080", "OK");
|
||||
command("ota set checkpoint 4096", "OK");
|
||||
uint8_t key[32]={42};
|
||||
context.allow.add(key);
|
||||
assert(saveCompanionOtaConfig(OtaConfigState::capture(context)));
|
||||
reboot(fs);
|
||||
assert(context.manager.hops==8 && context.manager.advert==10080
|
||||
&& context.manager.checkpoint==4096 && context.allow.contains(key));
|
||||
#if defined(OTA_SEEDER_ONLY)
|
||||
assert(context.manager.af==0 && context.autoinstall==0);
|
||||
#else
|
||||
assert(context.manager.af==2 && context.autoinstall==1);
|
||||
#endif
|
||||
const auto good=fs.files["/ota_config"];
|
||||
fs.fail_write=true;
|
||||
command("ota config hops 2", "ERR OTA settings save failed; settings unchanged");
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
fs.fail_write=false;
|
||||
fs.fail_write_after=10;
|
||||
command("ota config hops 2", "ERR");
|
||||
fs.fail_write_after=-1;
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
fs.fail_rename=2;
|
||||
command("ota config hops 2", "ERR");
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
reboot(fs);
|
||||
assert(context.manager.hops==8 && context.allow.contains(key));
|
||||
fs.fail_rename_from={"/ota_config.tmp", "/ota_config.bak"};
|
||||
command("ota config hops 2", "ERR");
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config.bak"]==good);
|
||||
command("ota config hops 2", "ERR"); // failed restoration is held
|
||||
fs.fail_rename_from.clear();
|
||||
reboot(fs);
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
fs.files["/ota_config.bak"]=good;
|
||||
fs.files.erase("/ota_config");
|
||||
reboot(fs); // reset between publication renames
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
fs.files["/ota_config.bak"]=good;
|
||||
fs.files.erase("/ota_config");
|
||||
fs.fail_rename=1;
|
||||
reboot(fs); // backup remains readable if repair is temporarily unavailable
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config.bak"]==good);
|
||||
command("ota config hops 2", "ERR");
|
||||
reboot(fs);
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
fs.fail_read_open=true;
|
||||
assert(!fs.exists("/ota_config")); // model ESP32's open-based exists()
|
||||
command("ota config hops 2", "ERR");
|
||||
fs.fail_read_open=false;
|
||||
command("ota config hops 2", "ERR"); // held until a clean reload
|
||||
assert(context.manager.hops==8 && fs.files["/ota_config"]==good);
|
||||
reboot(fs);
|
||||
fs.stat_error=true;
|
||||
command("ota config hops 2", "ERR");
|
||||
fs.stat_error=false;
|
||||
command("ota config hops 2", "ERR");
|
||||
assert(fs.files["/ota_config"]==good && context.manager.hops==8);
|
||||
reboot(fs);
|
||||
command("ota config hops 0", "OK");
|
||||
command("ota config advert 0", "OK");
|
||||
command("ota config checkpoint 0", "OK");
|
||||
reboot(fs);
|
||||
assert(context.manager.hops==0 && context.manager.advert==0 && context.manager.checkpoint==0);
|
||||
fs.files["/ota_config"][4]^=1;
|
||||
const auto damaged=fs.files["/ota_config"];
|
||||
reboot(fs);
|
||||
command("ota config hops 7", "ERR");
|
||||
assert(fs.files["/ota_config"]==damaged);
|
||||
fs.files.clear(); reboot(fs);
|
||||
acquire_ok=false;
|
||||
command("ota config hops 7", "ERR unavailable");
|
||||
assert(fs.files.empty());
|
||||
|
||||
acquire_ok=true; context=OtaContext();
|
||||
Common common;
|
||||
context.allow.add(key);
|
||||
common.run("ota config hops 7", reply);
|
||||
assert(!strncmp(reply, "OK", 2) && common.saves==1);
|
||||
assert(common.prefs.ota_max_hops==7 && common.prefs.ota_signer_count==1);
|
||||
assert(context.manager.hops==7 && !context.config_dirty);
|
||||
common.save_ok=false;
|
||||
common.run("ota config hops 2", reply);
|
||||
assert(!strncmp(reply, "ERR", 3) && common.saves==2);
|
||||
assert(common.prefs.ota_max_hops==7 && context.manager.hops==7 && !context.config_dirty);
|
||||
common.run("ota key add test-key", reply);
|
||||
assert(!strncmp(reply, "ERR", 3) && common.saves==3);
|
||||
assert(context.allow.count()==1 && common.prefs.ota_signer_count==1);
|
||||
assert(!memcmp(common.prefs.ota_signers[0], key, 32));
|
||||
const uint8_t zero[32]={};
|
||||
assert(!memcmp(common.prefs.ota_signers[1], zero, 32));
|
||||
common.save_ok=true;
|
||||
common.run("ota key add test-key", reply);
|
||||
assert(!strncmp(reply, "OK", 2) && common.saves==4);
|
||||
assert(context.allow.count()==2 && common.prefs.ota_signer_count==2);
|
||||
common.run("ota config hops bad", reply);
|
||||
assert(!strncmp(reply, "ERR", 3) && common.saves==4);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CompanionOtaConfigTest(unittest.TestCase):
|
||||
def test_production_commands_reboot_and_transaction_failures(self):
|
||||
cli = (ROOT / "src/helpers/ota/OtaCli.cpp").read_text()
|
||||
companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
||||
common = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
|
||||
config = extract_braced(cli, 'if (is_cmd(a, "config|cfg|set", &rest))')
|
||||
config = config[config.index("{") + 1:-1]
|
||||
wrapper = extract_braced(companion, 'if (strncmp(command, "ota", 3) == 0')
|
||||
common_wrapper = extract_braced(common, 'if (memcmp(command, "ota", 3) == 0')
|
||||
# The closing brace is shared with the ENABLE_OTA fallback branch.
|
||||
common_wrapper = common_wrapper.replace("#else", "")
|
||||
source = (HARNESS.replace("@IS_CMD@", extract_braced(cli, "static bool is_cmd("))
|
||||
.replace("@CONFIG@", config).replace("@WRAPPER@", wrapper)
|
||||
.replace("@COMMON@", common_wrapper))
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
self.assertIsNotNone(compiler)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
# Exercise production metadata probes independently from the
|
||||
# deliberately open-based exists() API in this faulting backend.
|
||||
mock = (ROOT / "test/fixtures/radio_profiles/mocks/helpers/IdentityStore.h").read_text()
|
||||
mock = mock.replace("bool fail_write = false;", "bool stat_error=false;\n bool fail_write = false;")
|
||||
mock = mock.replace("bool exists(const char* path) const { return files.count(path); }",
|
||||
"bool exists(const char* path) const { return !fail_read_open && files.count(path); }")
|
||||
mock = mock.replace("bool mkdir(const char*)", "void _lockFS() {}\n void _unlockFS() {}\n"
|
||||
" MemoryFS* _getFS() { return this; }\n"
|
||||
" File open(const char* path, uint8_t mode) { return open(path, mode ? \"w\" : \"r\"); }\n"
|
||||
" bool mkdir(const char*)")
|
||||
mock += ("\nstruct lfs_info {};\nconstexpr int LFS_ERR_NOENT=-2;\n"
|
||||
"inline int lfs_stat(MemoryFS* fs, const char* path, lfs_info*) {\n"
|
||||
" if (fs->stat_error) return -5;\n"
|
||||
" return fs->files.count(path) ? 0 : LFS_ERR_NOENT;\n}\n")
|
||||
mock_dir = Path(directory) / "helpers"
|
||||
mock_dir.mkdir()
|
||||
(mock_dir / "IdentityStore.h").write_text(mock)
|
||||
cpp = Path(directory) / "config.cpp"
|
||||
cpp.write_text(source)
|
||||
variants = [(platform, seeder, "-DCOMPANION_RADIO_FULL=1")
|
||||
for platform in ("ESP32_PLATFORM", "NRF52_PLATFORM", "STM32_PLATFORM")
|
||||
for seeder in ([], ["-DOTA_SEEDER_ONLY=1"])]
|
||||
variants.append(("ESP32_PLATFORM", [], "-DCOMPANION_FEATURE_OTA_CLI=1"))
|
||||
for platform, seeder, capability in variants:
|
||||
with self.subTest(platform=platform, seeder=seeder, capability=capability):
|
||||
binary = Path(directory) / "config"
|
||||
compiled = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", "-D"+platform+"=1", *seeder,
|
||||
"-DENABLE_OTA=1", capability, "-I", directory,
|
||||
"-I", str(ROOT / "test/fixtures/radio_profiles/mocks"),
|
||||
"-I", str(ROOT / "test/mocks"), "-I", str(ROOT / "src"),
|
||||
str(ROOT / "src/helpers/ota/CompanionOtaConfig.cpp"),
|
||||
str(cpp), "-o", str(binary),
|
||||
], text=True, capture_output=True)
|
||||
self.assertEqual(compiled.returncode, 0, compiled.stderr)
|
||||
ran = subprocess.run([str(binary)], text=True, capture_output=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
|
||||
def test_static_and_dynamic_load_wiring_does_not_allocate_on_registration(self):
|
||||
companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
||||
context = (ROOT / "src/helpers/ota/OtaContext.cpp").read_text()
|
||||
self.assertIn("ota_set_context_config_loader(mesh::ota::loadCompanionOtaConfig)", companion)
|
||||
loader = extract_braced(context, "void ota_set_context_config_loader(")
|
||||
self.assertIn("ota_context_if_active()", loader)
|
||||
self.assertNotIn("ota_acquire_context", loader)
|
||||
acquire = extract_braced(context, "bool ota_acquire_context(")
|
||||
self.assertIn("context_config_loader(restored)", acquire)
|
||||
self.assertIn("restored.apply(c)", acquire)
|
||||
|
||||
def test_executable_dynamic_loader_and_seeder_policy(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory)
|
||||
source = path / "loader.cpp"
|
||||
source.write_text(r'''
|
||||
#include <helpers/ota/OtaContext.h>
|
||||
#include <cassert>
|
||||
using namespace mesh::ota;
|
||||
namespace mesh { namespace ota {
|
||||
bool ota_self_firmware(SelfFwInfo& info) { info=SelfFwInfo(); return false; }
|
||||
} }
|
||||
static int calls=0;
|
||||
static bool readable=true;
|
||||
static OtaConfigState disk;
|
||||
static bool load(OtaConfigState& restored) {
|
||||
++calls;
|
||||
if (!readable) return false;
|
||||
restored=disk;
|
||||
return true;
|
||||
}
|
||||
static bool send(void*, const uint8_t*, uint16_t, bool) { return true; }
|
||||
int main() {
|
||||
disk.hops=7; disk.advert=17; disk.checkpoint=32;
|
||||
disk.autofetch=2; disk.autoinstall=1;
|
||||
uint8_t key[32]={71}; disk.allow.add(key);
|
||||
ota_set_context_config_loader(load);
|
||||
assert(calls==0 && !ota_context_if_active()); // no eager heap or queue claim
|
||||
ota_begin_context(123, send, nullptr, "test", nullptr);
|
||||
for (int i=0; i<3; ++i) {
|
||||
assert(ota_acquire_context(nullptr, 0));
|
||||
assert(calls==i+1 && ota_ctx().manager.max_hops()==7);
|
||||
assert(ota_ctx().manager.advert_mins()==17 && ota_ctx().manager.checkpoint_blocks()==32);
|
||||
assert(ota_ctx().allow.contains(key));
|
||||
assert(ota_ctx().manager.autofetch()==0 && ota_ctx().autoinstall==0);
|
||||
ota_release_context_if_idle(false);
|
||||
assert(!ota_context_if_active());
|
||||
}
|
||||
assert(ota_acquire_context(nullptr, 0));
|
||||
disk.hops=2;
|
||||
ota_set_context_config_loader(load); // existing/static-context registration path
|
||||
assert(ota_ctx().manager.max_hops()==2);
|
||||
readable=false;
|
||||
ota_set_context_config_loader(load);
|
||||
assert(ota_ctx().manager.max_hops()==2); // failed read does not partly apply defaults
|
||||
ota_release_context_if_idle(false);
|
||||
ota_set_context_config_loader(nullptr);
|
||||
}
|
||||
''')
|
||||
heap_test.OtaHeapTest().compile_and_run(path, source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -44,6 +44,7 @@ struct Radio { mesh::RadioProfiles config; mesh::RadioProfiles* profiles() { ret
|
||||
struct DataStore {
|
||||
FILESYSTEM fs;
|
||||
bool _channel_load_incomplete=false;
|
||||
bool _uncached_contact_load_incomplete=false;
|
||||
bool hasIncompleteContactLoad() const;
|
||||
FILESYSTEM* _getContactsChannelsFS() { return &fs; }
|
||||
File openRead(FILESYSTEM* fs, const char* name) { return fs->open(name,"r"); }
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the uncached Companion persistence paths against faulting filesystems."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_replay_reset_integration import extract_braced
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class CompanionUncachedStorageTest(unittest.TestCase):
|
||||
def test_esp32_uncached_storage(self):
|
||||
self.run_platform("ESP32_PLATFORM")
|
||||
|
||||
def test_stm32_uncached_storage(self):
|
||||
self.run_platform("STM32_PLATFORM")
|
||||
|
||||
def test_rp2040_uncached_storage(self):
|
||||
self.run_platform("RP2040_PLATFORM")
|
||||
|
||||
def run_platform(self, platform):
|
||||
source = (ROOT / "examples/companion_radio/DataStore.cpp").read_text()
|
||||
signatures = (
|
||||
"static bool companionPathPresence(",
|
||||
"bool DataStore::loadMainIdentity(",
|
||||
"bool DataStore::canCreateMainIdentity() const",
|
||||
"bool DataStore::saveMainIdentity(",
|
||||
"static bool deserializeContactRecord(",
|
||||
"void DataStore::loadContacts(",
|
||||
"bool DataStore::saveContacts(",
|
||||
"bool DataStore::hasIncompleteContactLoad() const",
|
||||
)
|
||||
packet = (ROOT / "src/Packet.cpp").read_text()
|
||||
generated = "namespace mesh {\n" + extract_braced(
|
||||
packet, "bool Packet::isValidPathLen(") + "\n}\n"
|
||||
generated += "\n".join(extract_braced(source, s) for s in signatures)
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-uncached-store-") as temp:
|
||||
temp = Path(temp)
|
||||
(temp / "store_under_test.h").write_text(generated)
|
||||
# IdentityStore.h only needs the platform filesystem declaration;
|
||||
# the concrete mock below implements the same file API.
|
||||
(temp / "FS.h").write_text(
|
||||
"#pragma once\nnamespace fs { using FS = FakeFilesystem; }\n"
|
||||
)
|
||||
binary = temp / "test"
|
||||
compiled = subprocess.run([
|
||||
"c++", "-std=c++17", "-O1", "-g", "-Wall", "-Wextra",
|
||||
"-Werror", "-Wno-unused-parameter", "-fsanitize=address,undefined", "-fno-pie", "-no-pie",
|
||||
"-DMESH_CONTACT_CACHE=0", "-D" + platform + "=1",
|
||||
"-I", str(temp),
|
||||
"-I", str(ROOT / "test/fixtures/contact_cache/mocks"),
|
||||
"-I", str(ROOT / "src"),
|
||||
"-I", str(ROOT / "lib/ed25519"),
|
||||
str(ROOT / "test/fixtures/companion_uncached_storage/test.cpp"),
|
||||
"-o", str(binary),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -640,10 +640,10 @@ TEST(MQTTPrefsAtomicStore, RecoveryNeverOverwritesOpaqueNewerLayout) {
|
||||
Recovery::FileState::Preserve));
|
||||
}
|
||||
|
||||
TEST(MQTTPrefsAtomicStore, CommonPrefsRecoveryUsesOnlyVerifiedTempWithBackup) {
|
||||
TEST(MQTTPrefsAtomicStore, CommonPrefsRecoveryPreservesLastPublishedImage) {
|
||||
EXPECT_EQ(CommonRecovery::Action::KeepPrimary,
|
||||
CommonRecovery::select(true, true, true));
|
||||
EXPECT_EQ(CommonRecovery::Action::PromoteTemp,
|
||||
EXPECT_EQ(CommonRecovery::Action::PromoteBackup,
|
||||
CommonRecovery::select(false, true, true));
|
||||
EXPECT_EQ(CommonRecovery::Action::PromoteBackup,
|
||||
CommonRecovery::select(false, false, true));
|
||||
|
||||
@@ -719,9 +719,10 @@ class Nrf52ExtraFsContractTest(unittest.TestCase):
|
||||
save_channels = function_body(
|
||||
store, "bool DataStore::saveChannels(DataStoreHost* host)"
|
||||
)
|
||||
self.assertIn("bool& incomplete = _contact_load_incomplete;", load_channels)
|
||||
self.assertLess(
|
||||
load_channels.index("if (_contact_load_incomplete)"),
|
||||
load_channels.index('openRead(_getContactsChannelsFS(), "/channels2")'),
|
||||
load_channels.index("if (incomplete) return;"),
|
||||
load_channels.index('openRead(contacts_fs, "/channels2")'),
|
||||
)
|
||||
self.assertLess(
|
||||
save_channels.index("if (_contact_load_incomplete) return false;"),
|
||||
|
||||
@@ -37,26 +37,67 @@ uint32_t millis() { return now_ms; }
|
||||
namespace mesh {
|
||||
struct Packet {};
|
||||
int clampLoRaTxPower(int power, float) { return power; }
|
||||
namespace lr2021 {
|
||||
bool storedSideDetectorCount(const uint8_t*, uint8_t& count) { count = 0; return true; }
|
||||
bool validateSideDetectorSFs(const uint8_t*, uint8_t, uint8_t, float) { return true; }
|
||||
}
|
||||
}
|
||||
struct CommonCLI {
|
||||
template <typename T> static void recalculateRxPowerSavingFromLevel(T*) {}
|
||||
};
|
||||
uint32_t nextRadioApplyRetryDelay(uint8_t& failures) { ++failures; return 100; }
|
||||
struct RadioDriver {
|
||||
void setRxBoostedGainMode(bool) {}
|
||||
void setTxPower(int) {}
|
||||
bool gain_supported = true, gain_success = true, power_success = true;
|
||||
bool side_detector_success = true;
|
||||
unsigned gain_calls = 0, power_calls = 0;
|
||||
bool active_gain = false;
|
||||
int active_power = 0;
|
||||
bool supportsRxBoostedGainMode() const { return gain_supported; }
|
||||
bool setRxBoostedGainMode(bool gain) {
|
||||
++gain_calls;
|
||||
if (!gain_success) return false;
|
||||
active_gain = gain;
|
||||
return true;
|
||||
}
|
||||
bool setTxPower(int power) {
|
||||
++power_calls;
|
||||
if (!power_success) return false;
|
||||
active_power = power;
|
||||
return true;
|
||||
}
|
||||
bool configSideDetectors(const uint8_t*, uint8_t, float) { return side_detector_success; }
|
||||
} radio_driver;
|
||||
struct RTC {
|
||||
uint32_t now = 100000;
|
||||
uint32_t getCurrentTime() const { return now; }
|
||||
};
|
||||
struct RadioPrefs {
|
||||
bool rx_watchdog_enabled = true, rx_boosted_gain = true;
|
||||
uint8_t advert_interval = 60, flood_advert_interval = 24, path_hash_mode = 0;
|
||||
float freq = 909.5f, bw = 62.5f;
|
||||
uint8_t sf = 7, cr = 5;
|
||||
uint8_t extra_sf[4] = {};
|
||||
int tx_power_dbm = 20;
|
||||
};
|
||||
struct Board { int reboots = 0; void reboot() { ++reboots; } };
|
||||
struct CLI {
|
||||
Board board; Board* getBoard() { return &board; }
|
||||
CLI& radioProfiles() { return *this; }
|
||||
bool preamble_save_success = true;
|
||||
unsigned preamble_saves = 0;
|
||||
bool savePrimaryPreamble(uint16_t) { ++preamble_saves; return preamble_save_success; }
|
||||
RadioPrefs* prefs = nullptr;
|
||||
int* saves = nullptr;
|
||||
bool save_success = true;
|
||||
unsigned save_attempts = 0;
|
||||
unsigned fail_on_save = 0;
|
||||
uint16_t saved_preamble = 0;
|
||||
bool savePrimaryRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, uint16_t preamble) {
|
||||
++save_attempts;
|
||||
if (!save_success || save_attempts == fail_on_save) return false;
|
||||
++*saves;
|
||||
prefs->freq = freq; prefs->bw = bw; prefs->sf = sf; prefs->cr = cr;
|
||||
saved_preamble = preamble;
|
||||
return true;
|
||||
}
|
||||
uint16_t primaryPreamble() const { return saved_preamble; }
|
||||
bool hasReplyMutation() const { return false; }
|
||||
bool finishReplyMutation(bool) { return true; }
|
||||
};
|
||||
@@ -72,13 +113,7 @@ struct ScheduledRadioSetting {
|
||||
};
|
||||
class MyMesh {
|
||||
public:
|
||||
struct Prefs {
|
||||
bool rx_watchdog_enabled = true, rx_boosted_gain = true;
|
||||
uint8_t advert_interval = 60, flood_advert_interval = 24, path_hash_mode = 0;
|
||||
float freq = 909.5f, bw = 62.5f;
|
||||
uint8_t sf = 7, cr = 5;
|
||||
int tx_power_dbm = 20;
|
||||
} _prefs;
|
||||
RadioPrefs _prefs;
|
||||
CLI _cli;
|
||||
Radio radio; Radio* _radio = &radio;
|
||||
uint32_t last_meshcore_rx = 0;
|
||||
@@ -108,14 +143,20 @@ public:
|
||||
int saves = 0, applies = 0, restores = 0, local_adverts = 0, flood_adverts = 0;
|
||||
int default_scope = 0;
|
||||
mesh::Packet packet;
|
||||
MyMesh() { now_ms = 1; updateAdvertTimer(); updateFloodAdvertTimer(); }
|
||||
MyMesh() {
|
||||
_cli.prefs = &_prefs; _cli.saves = &saves;
|
||||
radio_driver = {}; now_ms = 1; updateAdvertTimer(); updateFloodAdvertTimer();
|
||||
}
|
||||
RTC* getRTCClock() const { return const_cast<RTC*>(&rtc); }
|
||||
uint32_t futureMillis(uint32_t delay) const { return now_ms + delay; }
|
||||
bool millisHasNowPassed(uint32_t deadline) const { return (int32_t)(now_ms - deadline) >= 0; }
|
||||
bool hasOutbound() const { return outbound; }
|
||||
bool hasStartedScheduledTempRadio() const { return scheduled_temp_radio_started; }
|
||||
bool applyRadioParams(float, float, uint8_t, uint8_t, uint16_t = 0, bool = false) { ++applies; return apply_success; }
|
||||
bool applySavedRadioParams() { ++restores; return restore_success; }
|
||||
bool applyRadioParams(float, float, uint8_t, uint8_t, uint16_t = 0, bool temporary = false) {
|
||||
if (temporary) { ++applies; return apply_success; }
|
||||
++restores; return restore_success;
|
||||
}
|
||||
bool applySavedRadioParams();
|
||||
bool isValidScheduledRadioParams(float, float, uint8_t, uint8_t) { return true; }
|
||||
void savePrefs() { ++saves; }
|
||||
int getScheduledRadioSettingIndex(bool, int slot) const { return slot + 1; }
|
||||
@@ -162,6 +203,72 @@ static void startTemp(MyMesh& m, int minutes) {
|
||||
assert(m.temp_radio_applied);
|
||||
}
|
||||
int main() {
|
||||
for (unsigned failure = 0; failure <
|
||||
#ifdef USE_LR2021
|
||||
4
|
||||
#else
|
||||
3
|
||||
#endif
|
||||
; ++failure) {
|
||||
// A failure at any independent hardware step retains the saved recovery
|
||||
// work and its backoff until the complete configuration succeeds.
|
||||
MyMesh m;
|
||||
if (failure == 0) radio_driver.gain_success = false;
|
||||
if (failure == 1) m.restore_success = false;
|
||||
if (failure == 2) radio_driver.power_success = false;
|
||||
if (failure == 3) radio_driver.side_detector_success = false;
|
||||
m.queueSavedRadioApply();
|
||||
m.processScheduledRadioSettings();
|
||||
assert(m.saved_radio_apply_pending && m.scheduled_radio_retry_at);
|
||||
const unsigned gain_calls = radio_driver.gain_calls;
|
||||
const unsigned power_calls = radio_driver.power_calls;
|
||||
const unsigned restores = m.restores;
|
||||
for (unsigned i = 0; i < 10; ++i) m.processScheduledRadioSettings();
|
||||
assert(radio_driver.gain_calls == gain_calls);
|
||||
assert(radio_driver.power_calls == power_calls && m.restores == (int)restores);
|
||||
radio_driver.gain_success = radio_driver.power_success = true;
|
||||
radio_driver.side_detector_success = true;
|
||||
m.restore_success = true;
|
||||
m.advance(1); m.processScheduledRadioSettings();
|
||||
assert(!m.saved_radio_apply_pending && !m.scheduled_radio_retry_at);
|
||||
assert(radio_driver.active_gain == m._prefs.rx_boosted_gain);
|
||||
assert(radio_driver.active_power == m._prefs.tx_power_dbm);
|
||||
}
|
||||
{ // A later failed due entry must not undo an earlier durable change.
|
||||
MyMesh m;
|
||||
char reply[160];
|
||||
m.addScheduledRadioParams(false, 911, 250, 5, 5, m.rtc.now + 2, 0, reply, 48);
|
||||
m.addScheduledRadioParams(false, 912, 125, 6, 6, m.rtc.now + 3, 0, reply, 80);
|
||||
m._cli.fail_on_save = 2;
|
||||
m.advance(3); m.servicePostMeshLoop();
|
||||
assert(m._cli.save_attempts == 2 && m.saves == 1);
|
||||
assert(m.countScheduledRadioSettings(false) == 1);
|
||||
assert(m._prefs.freq == 911 && m._cli.saved_preamble == 48);
|
||||
assert(!m.saved_radio_apply_pending);
|
||||
m.advance(60); m.servicePostMeshLoop();
|
||||
assert(m._cli.save_attempts == 3 && m.saves == 2);
|
||||
assert(m.countScheduledRadioSettings(false) == 0);
|
||||
assert(m._prefs.freq == 912 && m._cli.saved_preamble == 80);
|
||||
assert(!m.saved_radio_apply_pending);
|
||||
}
|
||||
{ // Radios without boosted gain must not become stuck in recovery.
|
||||
MyMesh m;
|
||||
radio_driver.gain_supported = false;
|
||||
radio_driver.gain_success = false;
|
||||
m.queueSavedRadioApply();
|
||||
m.processScheduledRadioSettings();
|
||||
assert(!m.saved_radio_apply_pending && radio_driver.gain_calls == 0);
|
||||
assert(radio_driver.active_power == m._prefs.tx_power_dbm);
|
||||
}
|
||||
{ // Boot uses the same complete apply result to arm recovery.
|
||||
MyMesh m;
|
||||
radio_driver.power_success = false;
|
||||
m.saved_radio_apply_pending = !m.applySavedRadioParams();
|
||||
assert(m.saved_radio_apply_pending);
|
||||
radio_driver.power_success = true;
|
||||
m.processScheduledRadioSettings();
|
||||
assert(!m.saved_radio_apply_pending);
|
||||
}
|
||||
{ // Expiring one scheduled lease must retain a later temporary entry.
|
||||
MyMesh m;
|
||||
char reply[160];
|
||||
@@ -182,31 +289,33 @@ int main() {
|
||||
char reply[160];
|
||||
m.addScheduledRadioParams(false, 912.5, 250, 5, 5, m.rtc.now + 2, 0, reply, 48);
|
||||
assert(!strncmp(reply, "OK", 2));
|
||||
m._cli.preamble_save_success = false;
|
||||
m._cli.save_success = false;
|
||||
m.advance(2); m.servicePostMeshLoop();
|
||||
assert(m._cli.preamble_saves == 1 && m.saves == 0);
|
||||
assert(m._cli.save_attempts == 1 && m.saves == 0);
|
||||
assert(m.next_scheduled_radio_check_at == m.scheduled_radio_save_retry_at);
|
||||
assert(m._prefs.freq == 909.5f);
|
||||
assert(m._prefs.freq == 909.5f && m._cli.saved_preamble == 0);
|
||||
assert(m.countScheduledRadioSettings(false) == 1);
|
||||
for (unsigned i = 0; i < 10; ++i) m.servicePostMeshLoop();
|
||||
assert(m._cli.preamble_saves == 1); // storage backoff survives the scheduler's cleanup
|
||||
m._cli.preamble_save_success = true;
|
||||
assert(m._cli.save_attempts == 1); // storage backoff survives the scheduler's cleanup
|
||||
m._cli.save_success = true;
|
||||
m.advance(59); m.servicePostMeshLoop();
|
||||
assert(m._cli.preamble_saves == 1);
|
||||
assert(m._cli.save_attempts == 1);
|
||||
m.advance(1); m.servicePostMeshLoop();
|
||||
assert(m._cli.preamble_saves == 2 && m.saves == 1);
|
||||
assert(m._cli.save_attempts == 2 && m.saves == 1);
|
||||
assert(m._prefs.freq == 912.5f && !m.saved_radio_apply_pending);
|
||||
assert(m._cli.saved_preamble == 48 && m.countScheduledRadioSettings(false) == 0);
|
||||
}
|
||||
{ // Backing off a failed permanent save must not delay temporary start/end.
|
||||
MyMesh m;
|
||||
char reply[160];
|
||||
m.addScheduledRadioParams(false, 912.5, 250, 5, 5, m.rtc.now + 2, 0, reply, 48);
|
||||
m.addScheduledRadioParams(true, 911.5, 250, 5, 5, m.rtc.now + 30, m.rtc.now + 90, reply, 80);
|
||||
m._cli.preamble_save_success = false;
|
||||
m._cli.save_success = false;
|
||||
m.advance(2); m.servicePostMeshLoop();
|
||||
assert(m._cli.preamble_saves == 1);
|
||||
assert(m._cli.save_attempts == 1);
|
||||
m.advance(28); m.servicePostMeshLoop();
|
||||
assert(m.temp_radio_applied && m.radio_timing.isTemporary());
|
||||
assert(m._cli.preamble_saves == 1);
|
||||
assert(m._cli.save_attempts == 1);
|
||||
m.advance(60); m.servicePostMeshLoop();
|
||||
assert(!m.temp_radio_applied && !m.radio_timing.isTemporary());
|
||||
assert(m._prefs.freq == 909.5f);
|
||||
@@ -427,6 +536,7 @@ class RepeaterRadioTimingIntegrationTest(unittest.TestCase):
|
||||
"void MyMesh::updateAdvertTimer()",
|
||||
"void MyMesh::updateFloodAdvertTimer()",
|
||||
"void MyMesh::queueSavedRadioApply()",
|
||||
"bool MyMesh::applySavedRadioParams()",
|
||||
"void MyMesh::refreshScheduledRadioState()",
|
||||
"void MyMesh::processScheduledRadioSettings()",
|
||||
"void MyMesh::applyTempRadioParams(",
|
||||
@@ -442,7 +552,10 @@ class RepeaterRadioTimingIntegrationTest(unittest.TestCase):
|
||||
# The remaining service tail handles unrelated MQTT/OTA/peripheral work.
|
||||
post = post[:post.index("#if defined(WITH_MQTT_BRIDGE) && defined(OTA_MANIFEST_BASE)")] + "}\n"
|
||||
methods += "\n" + post
|
||||
self.compile_and_run(HARNESS.replace("@METHODS@", methods))
|
||||
for lr2021 in (False, True):
|
||||
with self.subTest(lr2021=lr2021):
|
||||
defines = "#define USE_LR2021 1\n" if lr2021 else ""
|
||||
self.compile_and_run(defines + HARNESS.replace("@METHODS@", methods))
|
||||
|
||||
def test_production_cli_replies_and_duration_validation(self):
|
||||
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="utf-8")
|
||||
|
||||
Reference in new issue
Block a user