Fix release size regressions and calibration test fixtures

This commit is contained in:
mikecarper committed 2026-10-22 19:53:31 -07:00
1 parent ab6412e73c
commit 2d35a291fa
46 files changed
+1048 -373

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <cstddef>
#include <helpers/CLICommandUtils.h>
// These dispatch fixtures exercise another command family. Calibration and
// its checked persistence have their own production-code test suites.
namespace mesh { namespace power {
template <typename Board>
bool handleStoredBatteryCalibrationCommand(Board&, const char*, char*, size_t) {
return false;
}
}}
+8
View File
@@ -131,11 +131,19 @@ void commands() {
"delete beacon 1 extra", "set beacon 1 unknown 1 Hello",
"set beacon 1 meshcore nan,62.5,7,5,14 Hello", "set beacon 1 meshcore inf,62.5,7,5,14 Hello",
"set beacon 1 meshcore 906.5,nan,7,5,14 Hello", "set beacon 1 meshcore 906.5,62.5,256,5,14 Hello",
"set beacon 1 meshcore 9.065e2,62.5,7,5,14 Hello", "set beacon 1 meshcore 0x1.c54p9,62.5,7,5,14 Hello",
"set beacon 1 meshcore 906.5,6.25e1,7,5,14 Hello", "set beacon 1 meshcore 906.5,62.5junk,7,5,14 Hello",
"set beacon 1 meshcore -906.5,62.5,7,5,14 Hello", "set beacon 1 meshcore 2501,62.5,7,5,14 Hello",
"set beacon 1 meshcore 906.5,-62.5,7,5,14 Hello", "set beacon 1 meshcore 906.5,501,7,5,14 Hello",
"set beacon 1 meshcore 906.5,62.5,7,5,128 Hello", "set beacon 1 meshcore 906.5,62.5,7,5,23 Hello",
"set beacon 1 meshcore 906.5,62.5,7,5,14,7 Hello", "set beacon 1 meshcore 906.5,62.5,7,5,14,65536 Hello",
"set beacon 1 meshcore 906.5,62.5,7,5,14,32,1 Hello", "set beacon 1 meshcore 906.5,62.5,7,5,14",
"set beacon 1 meshtext bad LongFast 14 Hello", "set beacon 1 meshtext US bad 14 Hello",
"set beacon 1 meshtext US LongFast 128 Hello"}) f.cmd(command, false);
for (const char* tuple : {"906.500,62.5", "+906.5,+62.500", "00906.500,062.5"}) {
f.cmd(std::string("set beacon 1 meshcore ") + tuple + ",7,5,14 Hello");
assert(std::strstr(f.cmd("get beacon 1"), "906.5"));
}
f.cmd("set beacon 1 meshcore 906.5,62.5,7,5,14 " + std::string(80, 'A'));
assert(std::strstr(f.cmd("get beacon 1"), std::string(80, 'A').c_str()));
f.cmd("set beacon 1 meshcore 906.5,62.5,7,5,14 " + std::string(81, 'A'), false);
+2
View File
@@ -29,7 +29,9 @@
#define PAYLOAD_TYPE_RESPONSE 1
#define ONE_KEY_DM_ID_SIZE 8
#include "production_constants.inc"
#include "battery_calibration_cli_stub.h"
struct BatteryBoard {} board;
namespace mesh {
struct Identity { uint8_t pub_key[PUB_KEY_SIZE] = {}; };
struct GroupChannel { uint8_t secret[16] = {}; };
+1
View File
@@ -1,4 +1,5 @@
#include <assert.h>
#include <helpers/CLICommandUtils.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
+1
View File
@@ -1,4 +1,5 @@
#include <cassert>
#include <helpers/CLICommandUtils.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
+1
View File
@@ -1,5 +1,6 @@
// Compile the real card-maintenance CLI around its side-effect boundaries.
// No filesystem, flash, bootloader, or radio hardware is accessed here.
#include <helpers/CLICommandUtils.h>
#include <cassert>
#include <cstdint>
#include <cstdio>
+149
View File
@@ -123,6 +123,155 @@ int main() {
class BatteryCalibrationStoreTests(unittest.TestCase):
def test_policy_only_recipe_loads_policy_before_application_store(self):
recipe = (ROOT / "variants/rak4631/platformio.ini").read_text(encoding="ascii")
board = (ROOT / "variants/rak4631/RAK4631Board.cpp").read_text(encoding="ascii")
nrf52 = (ROOT / "src/helpers/NRF52Board.cpp").read_text()
self.assertIn("-D NRF52_POWER_MANAGEMENT", recipe)
self.assertIn("-D BATTERY_CALIBRATION_VOLTAGE_POLICY_ONLY=1", recipe)
begin = board[board.index("void RAK4631Board::begin() {"):]
self.assertIn("checkBootVoltage(&power_config);", begin)
self.assertIn("mesh::power::loadVoltagePolicyAtBoot(config->voltage_bootlock);", nrf52)
def test_nrf52_typed_policy_setter_retains_record_cli_and_failure_behavior(self):
with tempfile.TemporaryDirectory(prefix="battery-calibration-policy-") as temp:
work = Path(temp)
(work / "helpers").mkdir()
mock = ROOT / "test/fixtures/radio_profiles/mocks/helpers/IdentityStore.h"
(work / "helpers/IdentityStore.h").write_text(mock.read_text(encoding="ascii"), encoding="ascii")
(work / "InternalFileSystem.h").write_text(r'''
#pragma once
#include <helpers/IdentityStore.h>
struct lfs_config {};
class Adafruit_LittleFS : public MemoryFS {
public:
bool mount_ok = true;
bool begin(struct lfs_config* = nullptr) { return mount_ok; }
void end() {}
};
Adafruit_LittleFS InternalFS;
''', encoding="ascii")
policy = (ROOT / "src/helpers/NRF52VoltagePolicy.cpp").read_text(encoding="ascii")
for header in ("NRF52VoltagePolicy.h", "IdentityStore.h", "AtomicFileWriter.h",
"PersistentStoreFormat.h", "CLICommandUtils.h"):
policy = policy.replace(f'#include "{header}"', f'#include <helpers/{header}>')
(work / "policy_under_test.cpp").write_text(policy, encoding="ascii")
store = (ROOT / "src/helpers/BatteryCalibrationStore.cpp").read_text(encoding="ascii")
for header in ("BatteryCalibrationStore.h", "BatteryCalibration.h", "CheckedSettingsFile.h",
"CLICommandUtils.h", "PersistentStoreFormat.h", "AtomicFileWriter.h",
"NRF52VoltagePolicy.h"):
store = store.replace(f'#include "{header}"', f'#include <helpers/{header}>')
(work / "store_under_test.cpp").write_text(store, encoding="ascii")
(work / "test.cpp").write_text(r'''
#include <cassert>
#include <cmath>
#include <cstring>
#include <initializer_list>
#define ATOMIC_FILE_WRITER_IMPLEMENTATION
#include "policy_under_test.cpp"
#undef ATOMIC_FILE_WRITER_IMPLEMENTATION
#include "store_under_test.cpp"
struct PolicyBoard : mesh::MainBoard {
bool supportsBatteryCalibration() const override { return true; }
float getAdcMultiplier() const override { return mesh::power::configuredAdcPermille() / 1000.0f; }
uint16_t getBattMilliVolts() override {
return mesh::power::calibratedMillivolts(4000, mesh::power::configuredAdcPermille());
}
const char* getManufacturerName() const override { return "fixture"; }
uint8_t getStartupReason() const override { return 0; }
void reboot() override {}
void sleep(uint32_t) override {}
};
int main() {
using namespace mesh::power;
PolicyBoard board;
char reply[160];
InternalFS.files["/battery_cal"] = {0xde, 0xad};
const auto unused_record = InternalFS.files.at("/battery_cal");
// Neither a supplied filesystem nor no filesystem may silently select a
// second store before the tagged board has loaded its authoritative policy.
assert(!beginBatteryCalibrationStore(board, &InternalFS));
assert(!beginBatteryCalibrationStore(board, nullptr));
assert(!setStoredAdcMultiplier(board, 1.1f, reply, sizeof(reply)));
assert(strstr(reply, "unsupported"));
InternalFS.mount_ok = false;
loadVoltagePolicyAtBoot(3300);
assert(voltagePolicySupported() && configuredAdcPermille() == 1000);
assert(beginBatteryCalibrationStore(board, nullptr));
InternalFS.fail_write = true;
assert(!setStoredAdcMultiplier(board, 1.1f, reply, sizeof(reply)));
assert(configuredAdcPermille() == 1000);
InternalFS.fail_write = false;
InternalFS.mount_ok = true;
InternalFS.rename_replaces = true;
loadVoltagePolicyAtBoot(3300);
assert(beginBatteryCalibrationStore(board, &InternalFS));
assert(handleStoredBatteryCalibrationCommand(board, "battery calibrate 4.18", reply, sizeof(reply)));
assert(strstr(reply, "4.180 V") && strstr(reply, "(saved)"));
assert(configuredAdcPermille() == 1045);
const auto good = InternalFS.files.at("/pwrmgt_v1");
assert(good.size() == 20 && !memcmp(good.data(), "NVP2", 4));
assert(mesh::storage::readLE16(good.data() + 12) == 1045);
assert(mesh::storage::readLE32(good.data() + 16)
== mesh::storage::updateCRC32(0xffffffffUL, good.data(), 16));
loadVoltagePolicyAtBoot(3300);
assert(configuredAdcPermille() == 1045);
InternalFS.files["/pwrmgt_v1"][16] ^= 1;
loadVoltagePolicyAtBoot(3300);
assert(configuredAdcPermille() == 1000);
assert(beginBatteryCalibrationStore(board, nullptr));
assert(InternalFS.files.at("/battery_cal") == unused_record);
InternalFS.files["/pwrmgt_v1"] = good;
loadVoltagePolicyAtBoot(3300);
assert(configuredAdcPermille() == 1045);
assert(handleVoltagePolicyCommand("set adc.multiplier 1.1", reply, sizeof(reply)));
assert(!strcmp(reply, "OK - ADC multiplier 1.100 saved"));
assert(configuredAdcPermille() == 1100);
assert(setConfiguredAdcMultiplier(0, reply, sizeof(reply)));
assert(configuredAdcPermille() == 1000);
assert(setConfiguredAdcMultiplier(0.5f, reply, sizeof(reply)));
assert(configuredAdcPermille() == 500);
assert(setConfiguredAdcMultiplier(1.5f, reply, sizeof(reply)));
assert(configuredAdcPermille() == 1500);
const auto before_invalid = InternalFS.files.at("/pwrmgt_v1");
for (float invalid : {NAN, INFINITY, -INFINITY, -1.0f, 0.49f, 1.51f, 65536.0f}) {
assert(!setConfiguredAdcMultiplier(invalid, reply, sizeof(reply)));
assert(!strncmp(reply, "Error:", 6));
assert(configuredAdcPermille() == 1500);
assert(InternalFS.files.at("/pwrmgt_v1") == before_invalid);
}
InternalFS.fail_write = true;
assert(!setConfiguredAdcMultiplier(1.1f, reply, sizeof(reply)));
assert(strstr(reply, "could not be saved"));
assert(configuredAdcPermille() == 1500);
assert(InternalFS.files.at("/pwrmgt_v1") == before_invalid);
InternalFS.fail_write = false;
InternalFS.fail_rename = 1;
assert(!setConfiguredAdcMultiplier(1.1f, reply, sizeof(reply)));
assert(configuredAdcPermille() == 1500);
assert(InternalFS.files.at("/pwrmgt_v1") == before_invalid);
char bounded[4] = {'X', 'X', 'X', 'Z'};
assert(!setConfiguredAdcMultiplier(NAN, bounded, 3));
assert(bounded[2] == 0 && bounded[3] == 'Z');
assert(!setConfiguredAdcMultiplier(1, nullptr, sizeof(reply)));
assert(!setConfiguredAdcMultiplier(1, reply, 0));
assert(InternalFS.files.at("/battery_cal") == unused_record);
}
''', encoding="ascii")
binary = work / "policy"
built = subprocess.run([
os.environ.get("CXX", "g++"), "-std=c++17", "-O1", "-Wall", "-Wextra", "-Werror",
"-Wno-sign-compare", "-Wno-unused-parameter", "-fsanitize=address,undefined",
"-fno-sanitize-recover=all", "-fno-pie", "-no-pie",
"-DNRF52_PLATFORM", "-DNRF52_POWER_MANAGEMENT",
"-DBATTERY_CALIBRATION_VOLTAGE_POLICY_ONLY=1",
"-I" + str(work), "-I" + str(ROOT / "src"),
str(work / "test.cpp"), "-o", str(binary),
], capture_output=True, text=True, timeout=60)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_roundtrip_corruption_write_failure_reset_and_backup_recovery(self):
with tempfile.TemporaryDirectory(prefix="battery-calibration-store-") as temp:
work = Path(temp)
+7 -4
View File
@@ -314,6 +314,11 @@ namespace mesh { namespace power {
static bool policyAvailable = false;
static unsigned policyCalls = 0;
static bool voltagePolicySupported() { return policyAvailable; }
static bool setConfiguredAdcMultiplier(float, char* reply, size_t capacity) {
++policyCalls;
snprintf(reply, capacity, "%s", policyAvailable ? "OK - saved" : "Error: voltage policy unsupported");
return policyAvailable;
}
static bool handleVoltagePolicyCommand(const char*, char* reply, size_t capacity) {
++policyCalls;
snprintf(reply, capacity, "%s", policyAvailable ? "> policy" : "Error: voltage policy unsupported");
@@ -362,8 +367,6 @@ static bool handleVoltagePolicyCommand(const char*, char* reply, size_t capacity
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="ascii")
setter = extract_braced(source, "void CommonCLI::handleSetCmd(")
branch = extract_braced(setter, 'if (memcmp(config, "adc.multiplier ", 15) == 0)')
utils = (ROOT / "src/helpers/CLICommandUtils.h").read_text(encoding="ascii")
parser = extract_braced(utils, "inline bool parseDecimalStrict(")
prefix = self.runtime_prefix(r'''
struct Prefs { float adc_multiplier = 0.0f; } prefs;
Prefs* _prefs = &prefs;
@@ -373,7 +376,7 @@ static bool handleVoltagePolicyCommand(const char*, char* reply, size_t capacity
bool applyAndSaveAdcMultiplier(float multiplier, char* reply, size_t capacity);
void dispatchAdc(char* command, char* reply);
''')
prefix += "\n#include <math.h>\nnamespace mesh { namespace cli {\n" + parser + "\n}}\n"
prefix += "\n#include <math.h>\n#include <helpers/CLICommandUtils.h>\n"
prefix += extract_braced(source, "bool CommonCLI::applyAndSaveAdcMultiplier(") + "\n"
prefix += "void CommonCLI::dispatchAdc(char* command, char* reply) {\n"
prefix += "const char* config = &command[4];\n" + branch + "\n}\n"
@@ -411,7 +414,7 @@ static bool handleVoltagePolicyCommand(const char*, char* reply, size_t capacity
cli.prefsSaveOk = true;
char reset[] = "set adc.multiplier 0";
cli.dispatchAdc(reset, reply);
assert(strcmp(reply, "OK - using default board multiplier") == 0);
assert(strcmp(reply, "OK - defaults (saved)") == 0);
assert(cli.prefsSaves == 3 && board.reads == 3 && cli._battery_forward_state.percentage == 41);
assert(!cli.batteryAllowsForward(false));
''', prefix=prefix, flags=("-DESP32_PLATFORM",))
+36
View File
@@ -49,6 +49,42 @@ class BeaconManagerTest(unittest.TestCase):
def test_commands_and_bounds(self):
self.run_scenario("commands")
def test_plain_decimal_parser_matches_radio_grammar(self):
production = (ROOT / "src/helpers/BeaconManager.cpp").read_text(encoding="ascii")
parser = body(production, "bool floatValue(")
source = Path(self.work.name) / "decimal.cpp"
binary = Path(self.work.name) / "decimal"
source.write_text(r'''
#include <helpers/CLICommandUtils.h>
#include <cassert>
#include <math.h>
#include <cstring>
#include <initializer_list>
namespace mesh {
''' + parser + r'''
}
int main() {
float value = 0;
struct Valid { const char* text; float value; };
for (const Valid& input : {Valid{"906.875", 906.875f}, {"+62.5", 62.5f},
{"-.5", -0.5f}, {".5", 0.5f}, {"906.", 906.0f}, {"0", 0.0f}}) {
assert(mesh::floatValue(input.text, value) && value == input.value);
}
for (const char* invalid : {"", ".", "+", "nan", "inf", "-inf", "0x1.c54p9",
"9.06875e2", "906.875MHz", " 906.875", "906.875 ", "906.875\t", "4294967296"})
assert(!mesh::floatValue(invalid, value));
assert(!mesh::floatValue(nullptr, value));
}
''', encoding="ascii")
compiled = subprocess.run([
self.build_command[0], "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie",
"-I", str(ROOT / "src"), str(source), "-o", str(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)
def test_all_intervals_and_wrap(self):
self.run_scenario("schedule")
@@ -1,5 +1,6 @@
#include <gtest/gtest.h>
#include <array>
#include <string>
#include <helpers/CLICommandUtils.h>
@@ -27,6 +28,48 @@ TEST(CLICommandUtils, LabelsInboundDirectRouteAsRouted) {
EXPECT_STREQ("FLOOD", mesh::cli::terminalInboundRouteLabel(false));
}
TEST(CLICommandUtils, FormatErrorKeepsMessagePercentCharactersLiteral) {
char reply[160];
mesh::cli::formatError(reply, sizeof(reply), "use 50%-150%; literal %s %n %%");
EXPECT_STREQ("Error: use 50%-150%; literal %s %n %%", reply);
mesh::cli::formatError(reply, sizeof(reply), "");
EXPECT_STREQ("Error: ", reply);
}
TEST(CLICommandUtils, FormatErrorTruncatesAtEveryCapacityWithoutTouchingGuards) {
const char* message = "reference 50%-150% of reading; retain %s literally";
const std::string expected = std::string("Error: ") + message;
std::array<char, 160> storage;
for (size_t capacity = 0; capacity <= expected.size() + 2; ++capacity) {
SCOPED_TRACE(capacity);
storage.fill('@');
char* reply = storage.data() + 1;
mesh::cli::formatError(reply, capacity, message);
EXPECT_EQ('@', storage.front());
EXPECT_EQ(std::string(storage.size() - 1 - capacity, '@'),
std::string(reply + capacity, storage.size() - 1 - capacity));
if (capacity == 0) continue;
const size_t length = expected.size() < capacity ? expected.size() : capacity - 1;
EXPECT_EQ(expected.substr(0, length), std::string(reply));
EXPECT_EQ('\0', reply[length]);
}
// snprintf also permits a null destination when the capacity is zero.
mesh::cli::formatError(nullptr, 0, message);
}
TEST(CLICommandUtils, FormatErrorHonorsFull160ByteReplyBoundary) {
const std::string message = std::string(180, 'x') + "%n";
const std::string expected = std::string("Error: ") + message;
std::array<char, 162> storage;
storage.fill('@');
char* reply = storage.data() + 1;
mesh::cli::formatError(reply, 160, message.c_str());
EXPECT_EQ(expected.substr(0, 159), std::string(reply));
EXPECT_EQ('\0', reply[159]);
EXPECT_EQ('@', storage.front());
EXPECT_EQ('@', storage.back());
}
TEST(TerminalDisplayFilter, UsesQuietDefaultsWithEmergencyVisible) {
mesh::TerminalDisplayFilter filter;
+1 -1
View File
@@ -14,7 +14,7 @@ def compile_run(source, macros=()):
with tempfile.TemporaryDirectory(prefix='common-cli-save-') as directory:
work = Path(directory)
cpp, exe = work / 'test.cpp', work / 'test'
cpp.write_text(source, encoding='utf-8')
cpp.write_text('#include <helpers/CLICommandUtils.h>\n' + source, encoding='utf-8')
subprocess.run(['g++', '-std=c++17', '-Wall', '-Wextra', '-Werror',
'-fsanitize=address,undefined', '-fno-sanitize-recover=all',
'-fno-pie', '-no-pie', *['-D' + m + '=1' for m in macros],
@@ -20,6 +20,7 @@ HARNESS = r'''
#include <helpers/radiolib/RXPowerSaving.h>
#include <helpers/esp32/PowerTestControls.h>
#include "companion_fleet_dispatch.h"
#include "battery_calibration_cli_stub.h"
#include <sys/stat.h>
#include <limits>
#define constrain(value,low,high) ((value)<(low)?(low):((value)>(high)?(high):(value)))
@@ -58,6 +59,7 @@ struct Radio : mesh::Radio {
bool isInRecvMode() const override { return true; }
};
struct Sensors { double node_lat=0,node_lon=0; } sensors;
struct BatteryBoard {} board;
// Morse dispatch is independently executable in its own shared-handler suite;
// this legacy fixture keeps that optional branch inactive for tuple rollback.
namespace mesh {
+3
View File
@@ -288,6 +288,8 @@ int main() {
#include <cassert>
#include <cstring>
#include <string>
#include "battery_calibration_cli_stub.h"
struct BatteryBoard {} board;
struct Radio { bool active = false; };
namespace mesh {
bool morseTimingActive(const Radio* radio) { return radio && radio->active; }
@@ -348,6 +350,7 @@ int main() {
str(ROOT / "src/helpers/ota/OtaTinf.c"), "-o", str(obj)])
self.run_checked([cxx, "-std=c++17", "-Os", "-Wall", "-Wextra", "-Werror",
*flags, "-I" + str(ROOT / "src"), "-I" + str(FIXTURE),
"-I" + str(ROOT / "test/fixtures"),
str(generated), str(ROOT / "src/helpers/CompanionReader.cpp"),
str(obj), "-o", str(binary)])
self.run_checked([str(binary)])
+1
View File
@@ -14,6 +14,7 @@ from test_radio_receive_contract import method
ROOT = Path(__file__).resolve().parents[1]
PREFERENCE_HARNESS = r'''
#include <helpers/CLICommandUtils.h>
struct ConfigText : Stream {
std::string text;size_t offset=0;
int available() override{return int(text.size()-offset);}
+1 -1
View File
@@ -18,7 +18,7 @@ class EspNowDiagnosticCliTests(unittest.TestCase):
with tempfile.TemporaryDirectory(prefix="espnow-cli-") as directory:
source_path = Path(directory) / "main.cpp"
binary = Path(directory) / "check"
source_path.write_text(source, encoding="ascii")
source_path.write_text('#include <helpers/CLICommandUtils.h>\n' + source, encoding="ascii")
subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-fsanitize=address,undefined", "-fno-omit-frame-pointer",
"-I", str(ROOT / "src"), *flags, str(source_path),
+1
View File
@@ -9,6 +9,7 @@ from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <helpers/CLICommandUtils.h>
#include <cassert>
#include <cstdint>
#include <cstdio>
+1 -1
View File
@@ -143,7 +143,7 @@ local = mesh[local_start:local_end]
assert 'strcmp(command, "get companion.transport") == 0' in local
assert 'strncmp(command, "set companion.transport", 23) == 0' in local
assert '"OK - companion transport %s saved; reboot required"' in local
assert '"Error: failed to save companion transport"' in local
assert 'mesh::cli::formatError(reply, reply_size, "failed to save companion transport")' in local
help_start = mesh.index(' } else if (strcmp(command, "help") == 0) {')
help_end = mesh.index(' } else if (handleCommand(command, 0, local_reply))', help_start)
help_body = mesh[help_start:help_end]
+2
View File
@@ -24,6 +24,7 @@ PREAMBLE = r'''
#include <helpers/CompanionLostReply.h>
#include <helpers/CompanionTimezonePrefs.h>
#include "companion_fleet_dispatch.h"
#include "battery_calibration_cli_stub.h"
#define ESP32 1
#define WIFI_SSID "test"
#define WITH_MQTT_BRIDGE 1
@@ -409,6 +410,7 @@ int main() {
binary = Path(temp) / "test"
result = subprocess.run([
"c++", "-std=c++17", "-include", "initializer_list", "-x", "c++", "-",
"-include", str(ROOT / "src/helpers/CLICommandUtils.h"),
*SANITIZER_FLAGS, "-o", str(binary),
], input=code, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
@@ -21,6 +21,7 @@ class ManagementPasswordCommandsTest(unittest.TestCase):
companion = companion[start:end] + ' return false;\n}\n'
source = r'''
#include <helpers/esp32/ManagementPassword.h>
#include <helpers/CLICommandUtils.h>
#include <cassert>
#include <cstdio>
#include <cstring>
+10 -2
View File
@@ -31,6 +31,7 @@ def sampling_source(mutation=None):
#include <cstdint>
#include <string>
#include <vector>
#include <helpers/BatteryCalibration.h>
#define LOW 0
#define HIGH 1
#define AR_DEFAULT 10
@@ -60,7 +61,13 @@ int analogRead(int pin) {
assert(!events.empty() && events.back().name=="settle");
events.push_back({"sample",raw});return raw;
}
class Board { public: @METHOD@ };
class Board {
uint16_t calibrateBatteryMillivolts(uint16_t value) const {
return mesh::power::scaleBatteryMillivolts(value, 1.0f);
}
public:
@METHOD@
};
int main() {
Board board;
#ifdef BATTERY_PIN
@@ -100,7 +107,8 @@ class MeshTrackerX1BatteryTests(unittest.TestCase):
sanitizer = [] if os.name == "nt" else ["-fsanitize=address,undefined",
"-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
build = subprocess.run([compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror",
*sanitizer, *["-D"+flag for flag in defines], str(cpp), "-o", str(binary)],
*sanitizer, "-I", str(ROOT / "src"),
*["-D"+flag for flag in defines], str(cpp), "-o", str(binary)],
text=True, capture_output=True, timeout=30)
self.assertEqual(build.returncode, 0, build.stdout+build.stderr)
run = subprocess.run([str(binary)], text=True, capture_output=True, timeout=10)
+164 -5
View File
@@ -30,6 +30,10 @@ inline uint32_t micros() { return millis() * 1000U; }
#include <helpers/ManagementFeatureConfig.h>
#include <helpers/PacketFileLoggingConfig.h>
#include <helpers/SerialPacketLog.h>
#include "@PRODUCTION_UTILS@"
#define MAX_ROUTE_HASH_BYTES @ROUTE_HASH_LIMIT@
static const uint8_t FLOOD_RETRY_BRIDGE_OTHER_BUCKET = @BRIDGE_BUCKET_COUNT@;
@BUCKET_MASK_METHOD@
#include <algorithm>
#include <cassert>
#include <cstdarg>
@@ -64,6 +68,15 @@ namespace mesh {
bool logging_enabled = true;
bool isUsbLoggingEnabled() { return logging_enabled; }
Stream& usbLoggingPort() { return log_port; }
void Utils::toHex(char* destination, const uint8_t* source, size_t size) {
const char* digits = "0123456789ABCDEF";
while (size--) {
const uint8_t value = *source++;
*destination++ = digits[value >> 4];
*destination++ = digits[value & 15];
}
*destination = 0;
}
@PACKET_METHODS@
@@ -143,7 +156,18 @@ struct Callbacks {
};
inline uint8_t getRetryLogCodingRate(const mesh::Packet*, uint8_t fallback) { return fallback; }
inline uint16_t rxPowerSavingPreambleForParams(uint8_t, float) { return 16; }
unsigned direct_format_calls = 0;
void formatDirectRetryTarget(char* output, size_t size, const uint8_t*, uint8_t) {
++direct_format_calls;
std::snprintf(output, size, "01");
}
struct MyMesh : Callbacks {
struct { bool flood_retry_bridge_enabled = false; } _prefs;
struct FloodRetryBridgeState {
uint8_t source_mask = 0, target_mask = 0, progress_marker = 0;
};
mutable FloodRetryBridgeState retry_state;
bool has_retry_state = false;
bool _logging = false;
FakeFS fs;
FakeFS* _fs = &fs;
@@ -162,10 +186,15 @@ struct MyMesh : Callbacks {
void formatFloodRetryPath(char* output, size_t size, const mesh::Packet*) {
std::snprintf(output, size, "01");
}
bool formatFloodRetryHeard(char* output, size_t size, const mesh::Packet*) {
std::snprintf(output, size, "02");
return true;
bool formatFloodRetryHeard(char* output, size_t size, const mesh::Packet* packet) const;
FloodRetryBridgeState* floodRetryBridgeStateFor(const mesh::Packet*, bool) const {
return has_retry_state ? &retry_state : nullptr;
}
uint8_t floodRetryBucketMaskForPathHop(const uint8_t* prefix, uint8_t,
uint8_t, uint8_t) const { return *prefix; }
uint8_t floodRetryBridgeHeardMask(const mesh::Packet* packet,
uint8_t source_mask, uint8_t progress_marker) const;
bool hasFloodRetryHeard(const mesh::Packet* packet) const;
void refreshFloodRetryReachability(const mesh::Packet*) { ++refreshed; }
@INLINE_CALLBACKS@
void logRxRaw(float snr, float rssi, const uint8_t raw[], int len);
@@ -174,6 +203,10 @@ struct MyMesh : Callbacks {
void logTxFail(mesh::Packet* pkt, int len);
void onFloodRetryEvent(const char* event, const mesh::Packet* packet,
uint32_t delay_millis, uint8_t retry_attempt);
void onDirectRetryEvent(const char* event, const mesh::Packet* packet,
uint32_t delay_millis, uint8_t retry_attempt,
const uint8_t* target_hash, uint8_t target_hash_len,
int16_t payload_type);
};
@RX_METHOD@
@FILE_METHODS@
@@ -207,6 +240,13 @@ static mesh::Packet makePacket(bool maximum = false) {
}
int main() {
MyMesh direct_diagnostics;
direct_diagnostics.setLoggingOn(true);
direct_diagnostics.onDirectRetryEvent("good", nullptr, 12, 1, nullptr, 0, 3);
assert(direct_format_calls == unsigned(EXPECT_FILE_LOGGING));
assert(direct_diagnostics.fs.opens == unsigned(EXPECT_FILE_LOGGING));
if (EXPECT_FILE_LOGGING)
assert(direct_diagnostics.fs.output.find(": direct retry good") != std::string::npos);
MyMesh repeater;
// Actual inline callbacks and persistent packet emitters remain independent
// of live USB logging. The file-off control cannot be re-enabled at runtime.
@@ -239,6 +279,61 @@ int main() {
repeater.logTxFail(&stored, 42);
repeater.onFloodRetryEvent("good", &stored, 12, 1);
assert(repeater.refreshed == 2 && repeater.fs.opens == old_opens);
// The unlogged path must make the same routing decision as the textual
// formatter: a real target echo, excluding source and progress-marker hops.
MyMesh routing;
mesh::Packet heard = makePacket();
heard.header = (PAYLOAD_TYPE_GRP_DATA << PH_TYPE_SHIFT) | ROUTE_TYPE_FLOOD;
heard.setPathHashSizeAndCount(1, 3);
heard.path[0] = 1; heard.path[1] = 2; heard.path[2] = 4;
assert(routing.hasFloodRetryHeard(&heard));
assert(!routing.hasFloodRetryHeard(nullptr));
const uint8_t valid_path = heard.path_len;
heard.path_len = 0;
assert(!routing.hasFloodRetryHeard(&heard));
heard.path_len = 0xC1; // Reserved four-byte route-hash mode.
assert(!routing.hasFloodRetryHeard(&heard));
heard.path_len = valid_path;
routing._prefs.flood_retry_bridge_enabled = true;
assert(!routing.hasFloodRetryHeard(&heard)); // No pending bridge retry.
routing.has_retry_state = true;
routing.retry_state = {1, 4, 2};
assert(routing.hasFloodRetryHeard(&heard));
routing.onFloodRetryEvent("good", &heard, 12, 1);
assert(routing.refreshed == 1);
routing.retry_state.target_mask = 2; // Progress marker is not an echo.
assert(!routing.hasFloodRetryHeard(&heard));
routing.onFloodRetryEvent("good", &heard, 12, 1);
assert(routing.refreshed == 1);
routing.retry_state.target_mask = 1; // The source is not a target echo.
assert(!routing.hasFloodRetryHeard(&heard));
routing.retry_state = {0, 2, 0};
assert(routing.hasFloodRetryHeard(&heard));
routing.onFloodRetryEvent("queued", &heard, 12, 1);
routing.onFloodRetryEvent("failure", &heard, 12, 1);
assert(routing.refreshed == 1);
routing.onFloodRetryEvent("good", &heard, 12, 1);
assert(routing.refreshed == 2);
// Compare the production eligibility check with the production formatter's
// success result using its actual 96-byte caller buffer, including every
// source/target/progress combination for representative route-hash sizes.
for (unsigned hash_size = 1; hash_size <= MAX_ROUTE_HASH_BYTES; ++hash_size) {
heard.setPathHashSizeAndCount(hash_size, 3);
memset(heard.path, 0, sizeof(heard.path));
heard.path[0] = 1;
heard.path[hash_size] = 2;
heard.path[hash_size * 2] = uint8_t(1U << FLOOD_RETRY_BRIDGE_OTHER_BUCKET);
for (unsigned source = 0; source < 8; ++source)
for (unsigned target : {0U, 1U, 2U, 3U, 64U, 127U})
for (unsigned progress = 0; progress <= 3; ++progress) {
routing.retry_state = {uint8_t(source), uint8_t(target), uint8_t(progress)};
char formatted[96];
assert(routing.hasFloodRetryHeard(&heard)
== routing.formatFloodRetryHeard(formatted, sizeof(formatted), &heard));
}
}
const uint8_t raw[] = {0x00, 0xAB, 0xFF};
reset();
repeater.logRxRaw(2.5f, -92, raw, sizeof(raw));
@@ -339,7 +434,18 @@ class MiniRepeaterLoggingTest(unittest.TestCase):
"uint8_t Packet::writeTo(", "bool Packet::readFrom("))
dispatcher = (ROOT / "src/Dispatcher.cpp").read_text()
repeater = (ROOT / "examples/simple_repeater/MyMesh.cpp").read_text()
program = HARNESS.replace("@PACKET_METHODS@", packet_methods).replace(
route_hash_limit = re.search(r"^#define MAX_ROUTE_HASH_BYTES\s+(\d+)\s*$",
(ROOT / "src/helpers/SimpleMeshTables.h").read_text(), re.MULTILINE)
self.assertIsNotNone(route_hash_limit)
bridge_bucket_count = re.search(r"^\s*#define FLOOD_RETRY_BRIDGE_BUCKETS\s+(\d+)\s*$",
(ROOT / "src/helpers/CommonCLI.h").read_text(), re.MULTILINE)
self.assertIsNotNone(bridge_bucket_count)
program = HARNESS.replace("@ROUTE_HASH_LIMIT@", route_hash_limit.group(1))
program = program.replace("@PRODUCTION_UTILS@", str(ROOT / "src/Utils.h"))
program = program.replace("@BRIDGE_BUCKET_COUNT@", bridge_bucket_count.group(1))
program = program.replace("@BUCKET_MASK_METHOD@",
body(repeater, "static uint8_t floodRetryBucketMask("))
program = program.replace("@PACKET_METHODS@", packet_methods).replace(
"@TX_METHOD@", body(dispatcher, "bool Dispatcher::startOutboundTransmit()"))
program = program.replace("@RX_METHOD@", body(repeater, "void MyMesh::logRxRaw("))
header = (ROOT / "examples/simple_repeater/MyMesh.h").read_text()
@@ -347,7 +453,9 @@ class MiniRepeaterLoggingTest(unittest.TestCase):
"void setLoggingOn(", "void eraseLogFile()")))
program = program.replace("@FILE_METHODS@", "\n".join(body(repeater, signature) for signature in (
"void MyMesh::logRx(", "void MyMesh::logTx(", "void MyMesh::logTxFail(",
"void MyMesh::onFloodRetryEvent(")))
"void MyMesh::onFloodRetryEvent(", "bool MyMesh::hasFloodRetryHeard(",
"uint8_t MyMesh::floodRetryBridgeHeardMask(", "bool MyMesh::formatFloodRetryHeard(",
"void MyMesh::onDirectRetryEvent(")))
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
"-fno-pie", "-no-pie"] if sys.platform.startswith("linux") else [])
with tempfile.TemporaryDirectory(prefix="mini-experiment-logging-") as directory:
@@ -374,6 +482,57 @@ class MiniRepeaterLoggingTest(unittest.TestCase):
self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr)
self.assertIn("PASS: production compact repeater RX/TX", tested.stdout)
def test_timestamp_override_is_retained_for_every_actual_consumer(self):
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
self.assertIsNotNone(compiler, "a host C++17 compiler is required")
header = (ROOT / "examples/simple_repeater/MyMesh.h").read_text()
source = (ROOT / "examples/simple_repeater/MyMesh.cpp").read_text()
def guarded(text, signature):
start = text.index(signature)
guard = text.rfind("#if ", 0, start)
end = text.index("#endif", start) + len("#endif")
self.assertGreaterEqual(guard, 0)
return text[guard:end]
declaration = guarded(header, "const char* getLogDateTime() override;")
definition = guarded(source, "const char *MyMesh::getLogDateTime()")
blocks, checks = ["#include <cassert>\n#include <cstdint>\n#include <cstdio>\n#include <cstring>"], []
for index, (debug, files, packets, compact) in enumerate(itertools.product((0, 1), repeat=4)):
flags = dict(MESH_DEBUG=debug, MESH_ENABLE_PACKET_FILE_LOGGING=files,
MESH_PACKET_LOGGING=packets, MESH_PACKET_LOGGING_COMPACT=compact)
for name, value in flags.items():
blocks.append(f"#undef {name}\n#define {name} {value}")
blocks.append(f"namespace timestamp_variant_{index} {{")
blocks.append(r'''
struct Clock { uint32_t getCurrentTime() const { return 123; } };
struct DateTime {
explicit DateTime(uint32_t) {}
unsigned hour() const { return 3; } unsigned minute() const { return 4; }
unsigned second() const { return 5; } unsigned day() const { return 2; }
unsigned month() const { return 1; } unsigned year() const { return 2026; }
};
struct Base { virtual const char* getLogDateTime() { return "unused"; } };
struct MyMesh : Base {
Clock clock;
Clock* getRTCClock() { return &clock; }
''')
blocks.extend((declaration, "};", definition))
expected = ("03:04:05 - 2/1/2026 U" if debug or files or (packets and not compact)
else "unused")
blocks.append(f'void check() {{ MyMesh mesh; assert(!strcmp(mesh.getLogDateTime(), "{expected}")); }}\n}}')
checks.append(f"timestamp_variant_{index}::check();")
blocks.append("int main() {" + " ".join(checks) + "}")
with tempfile.TemporaryDirectory(prefix="mini-timestamp-consumers-") as directory:
path, executable = Path(directory) / "test.cpp", Path(directory) / "test"
path.write_text("\n".join(blocks), encoding="ascii")
built = subprocess.run([compiler, "-std=c++17", "-O1", "-Wall", "-Wextra",
"-Werror", str(path), "-o", str(executable)],
capture_output=True, text=True, timeout=60)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
tested = subprocess.run([str(executable)], capture_output=True, text=True, timeout=15)
self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr)
def test_baseline_storage_logging_host_cli_and_authentication_contracts_remain(self):
config = configparser.ConfigParser(interpolation=None, inline_comment_prefixes=(";",))
config.read(ROOT / "variants/wio-e5-mini/platformio.ini")
+1
View File
@@ -178,6 +178,7 @@ public:
explicit NRF52Board(const char* name) : ota_name(name) {}
virtual void begin() {}
virtual uint16_t getBattMilliVolts() = 0;
virtual bool supportsBatteryCalibration() const { return false; }
virtual const char* getManufacturerName() const = 0;
virtual void shutdownPeripherals() {}
};
+1 -1
View File
@@ -34,7 +34,7 @@ def build(testcase, source, defines=(), files=None, expect_success=True):
testcase.skipTest("a host C++17 compiler is required")
with tempfile.TemporaryDirectory(prefix="rak15002-") as folder:
work = Path(folder)
(work / "main.cpp").write_text(source, encoding="utf-8")
(work / "main.cpp").write_text('#include <helpers/CLICommandUtils.h>\n' + source, encoding="utf-8")
for name, content in (files or {}).items():
(work / name).write_text(content, encoding="utf-8")
sanitizer = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
+1
View File
@@ -8,6 +8,7 @@ from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <helpers/CLICommandUtils.h>
#include <cassert>
#include <cstdlib>
#include <cstdint>
+1 -1
View File
@@ -17,7 +17,7 @@ class Rs232DiagnosticCliTests(unittest.TestCase):
with tempfile.TemporaryDirectory(prefix="rs232-cli-") as directory:
source_path = Path(directory) / "main.cpp"
binary = Path(directory) / "check"
source_path.write_text(source, encoding="ascii")
source_path.write_text('#include <helpers/CLICommandUtils.h>\n' + source, encoding="ascii")
subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-fsanitize=address,undefined", "-fno-omit-frame-pointer",
"-I", str(ROOT / "src"), *flags, str(source_path),
@@ -148,6 +148,33 @@ TEST_F(SerialPacketLogTest, MarksTruncatedLines) {
EXPECT_EQ(1U, mesh::serialLogDroppedCount());
}
TEST_F(SerialPacketLogTest, CompactRxTxRetainExactBytesAndLfOnly) {
FakePort port;
const uint8_t raw[] = {0x00, 0xAB, 0xFF};
EXPECT_TRUE(mesh::serialLogCompactPacket(port, 'R', raw, sizeof(raw)));
EXPECT_TRUE(mesh::serialLogCompactPacket(port, 'T', raw, sizeof(raw)));
EXPECT_EQ("R00ABFF\nT00ABFF\n", port.written());
}
TEST_F(SerialPacketLogTest, CompactPacketRetainsStallBudgetAndRecoveryMarker) {
primePort();
FakePort wedged(64, 64);
wedged.wedgeAfter(64);
uint8_t raw[255];
memset(raw, 0xA5, sizeof(raw));
const uint32_t before = millis();
EXPECT_FALSE(mesh::serialLogCompactPacket(wedged, 'R', raw, sizeof(raw)));
EXPECT_GE(millis() - before, (uint32_t)SERIAL_LOG_WRITE_BUDGET_MS);
EXPECT_LE(millis() - before, (uint32_t)SERIAL_LOG_WRITE_BUDGET_MS + 2);
EXPECT_EQ(1U, mesh::serialLogDroppedCount());
FakePort recovered;
const uint8_t next[] = {0x00};
EXPECT_TRUE(mesh::serialLogCompactPacket(recovered, 'T', next, sizeof(next)));
EXPECT_EQ("DROP:1\r\nT00\n", recovered.written());
EXPECT_EQ(0U, mesh::serialLogDroppedCount());
}
} // namespace
int main(int argc, char** argv) {
+1
View File
@@ -19,6 +19,7 @@ FIXTURE = r'''
#include <cstring>
#include <initializer_list>
#include <helpers/PrefsSaveReplyGuard.h>
#include <helpers/CLICommandUtils.h>
#include "LoRaFEMControl.h"
#include "StationG3RadioSlot.h"
struct ESP32Board {
+1
View File
@@ -295,6 +295,7 @@ public:
virtual void applyLedPolicy() {}
virtual void onBeforeTransmit() {}
virtual void onAfterTransmit() {}
virtual bool supportsBatteryCalibration() const { return false; }
virtual bool getBatteryChargeTarget(uint16_t&) { return false; }
virtual bool supportsBatteryChargeTarget(uint16_t) { return false; }
virtual bool setBatteryChargeTarget(uint16_t) { return false; }
+1
View File
@@ -132,6 +132,7 @@ int main() {
with self.subTest(touch=touch), tempfile.TemporaryDirectory() as temp:
binary = Path(temp) / "touch_debug_cli"
compiled = subprocess.run(["c++", "-std=c++11", "-O1",
"-include", str(ROOT / "src/helpers/CLICommandUtils.h"),
"-fsanitize=address,undefined", "-fno-pie", "-no-pie",
*(["-DHAS_TOUCH=1"] if touch else []),
"-x", "c++", "-", "-o", str(binary)],
+1 -1
View File
@@ -28,7 +28,7 @@ class UDPBridgeConfigTests(unittest.TestCase):
flags = ["-DWITH_UDP_BRIDGE=1", "-DESP32_PLATFORM", "-DESP32", "-I", str(mocks)]
sources = [str(ROOT / "src/helpers/UDPBridgeSettings.cpp")]
main = work / "main.cpp"
main.write_text(source, encoding="ascii")
main.write_text('#include <helpers/CLICommandUtils.h>\n' + source, encoding="ascii")
binary = work / "check"
result = subprocess.run([compiler, "-std=c++17", "-O1", "-g", "-Wall", "-Wextra", "-Werror",
"-Wno-misleading-indentation", "-Wno-sign-compare", "-fsanitize=address,undefined",
+1
View File
@@ -120,6 +120,7 @@ public:
virtual void begin() {}
virtual void applyLedPolicy() {}
virtual uint16_t getBattMilliVolts() { return 0; }
virtual bool supportsBatteryCalibration() const { return false; }
virtual const char* getManufacturerName() const { return "host"; }
virtual void onBeforeTransmit() {}
virtual void onAfterTransmit() {}