Share Companion hardware diagnostics and protect RXEN reconfiguration

This commit is contained in:
mikecarper committed 2026-10-23 08:57:51 -07:00
1 parent 04c4fdb240
commit 807343de8d
28 files changed
+1393 -277

No files matched your search

+218
View File
@@ -0,0 +1,218 @@
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <helpers/CompanionRadioDiagnostics.h>
constexpr int RADIOLIB_NC=-1;
constexpr int RADIOLIB_ERR_NONE=0;
constexpr uint8_t STATE_IDLE=0,STATE_RX=1,STATE_TX_WAIT=3;
struct CustomSX1262 {
bool disabled=false;
bool pending=false;
bool irq_during_standby=false;
int standby_result=RADIOLIB_ERR_NONE;
unsigned standby_calls=0,flag_writes=0;
int standby() {++standby_calls;if(irq_during_standby)pending=true;return standby_result;}
void setRxPowerSavingRfRxDisabled(bool value) {++flag_writes;disabled=value;}
bool isRxPowerSavingRfRxDisabled() const {return disabled;}
};
class RadioLibWrapper {
public:
CustomSX1262 physical;
CustomSX1262* _radio=&physical;
uint8_t state=STATE_RX;
bool _profile_repair_required=false,_profile_refresh_required=false;
bool _beacon_owned=false,_beacon_restoring=false,_cw_active=false;
bool _rx_hold_continuous=false,_rx_ps_armed=true;
bool chip_busy=false,receiving=false,rearm_fails=false,retry_pending=false;
bool _profile_rxps_suspended=false,_profile_saved_rxps=false;
bool _rx_ps_enabled=true;
uint32_t _rx_ps_rx_us=123456,_rx_ps_sleep_us=765432;
uint32_t n_recv=7,n_sent=9,n_recv_errors=3,n_wd_soft=11,n_wd_hard=13;
uint32_t last_rx=1234;
unsigned rearm_calls=0;
bool hasPendingRadioInterrupt() const {return physical.pending;}
void claimRadioInterrupt() {physical.pending=false;}
bool isChipBusy() const {return chip_busy;}
bool isReceivingPacket() const {return receiving;}
bool isCarrierWaveActive() const {return _cw_active;}
bool isBeaconRadioOwned() const {return _beacon_owned;}
void startRecv() {
++rearm_calls;
state=rearm_fails?STATE_IDLE:STATE_RX;
retry_pending=rearm_fails;
_rx_ps_armed=!rearm_fails&&_rx_ps_enabled;
}
uint8_t beginReconfigure();
void endReconfigure(bool);
bool isInRecvMode() const;
virtual bool supportsRxPowerSavingRfRxDisable() const {return false;}
virtual bool setRxPowerSavingRfRxDisabled(bool) {return false;}
virtual bool isRxPowerSavingRfRxDisabled() const {return false;}
uint32_t getRxPsWatchdogSoftCount() const {return n_wd_soft;}
uint32_t getRxPsWatchdogHardCount() const {return n_wd_hard;}
#include "production_radio_reset.inc"
};
#include "production_admission.inc"
struct Driver:RadioLibWrapper {
#include "production_rxen.inc"
};
struct Dispatcher {
uint32_t n_sent_flood=1,n_sent_direct=2,n_recv_flood=3,n_recv_direct=4;
uint16_t _err_flags=0x12;
uint32_t last_meshcore_rx=23456;
std::vector<int> outbound{42};
#include "production_dispatcher_reset.inc"
};
struct Tables {
uint32_t _direct_dups=8,_flood_dups=10;
std::vector<int> dedup_history{1,2,3};
#include "production_table_reset.inc"
};
struct Harness {
Driver driver;Dispatcher dispatcher;Tables tables;
unsigned clears=0;
bool command(const char* command,char* reply,size_t cap,bool available=true) {
return mesh::companion::handleRadioDiagnosticsCommand(driver,available,command,reply,cap,[this](){
++clears;driver.resetStats();dispatcher.resetStats();tables.resetStats();
});
}
};
static void bounds(Harness& h,const char* command,const std::string& expected,bool available=true) {
for(size_t cap=1;cap<=176;++cap) {
std::vector<unsigned char> bytes(cap+16,0xa5);
char* reply=reinterpret_cast<char*>(bytes.data()+8);
assert(h.command(command,reply,cap,available));
assert(std::string(reply)==expected.substr(0,cap-1));
for(size_t i=0;i<8;++i)assert(bytes[i]==0xa5);
for(size_t i=8+cap;i<bytes.size();++i)assert(bytes[i]==0xa5);
}
}
static void backend_guards() {
for(unsigned cause=0;cause<7;++cause) {
Driver d;
if(cause==0)d.chip_busy=true;
if(cause==1)d.physical.pending=true;
if(cause==2)d.receiving=true;
if(cause==3)d.state=STATE_TX_WAIT;
if(cause==4)d._cw_active=true;
if(cause==5)d.physical.irq_during_standby=true;
if(cause==6)d.physical.standby_result=-1;
assert(!d.setRxPowerSavingRfRxDisabled(true));
assert(!d.physical.disabled&&d.physical.flag_writes==0&&d.rearm_calls==0);
assert(d._rx_ps_enabled&&d._rx_ps_rx_us==123456&&d._rx_ps_sleep_us==765432);
if(cause==1||(cause==5&&d.supportsRxPowerSavingRfRxDisable()))assert(d.physical.pending);
}
#if MESH_ENABLE_TX_BEACONS
Driver beacon;beacon._beacon_owned=true;
assert(!beacon.setRxPowerSavingRfRxDisabled(true));
assert(beacon.physical.standby_calls==0&&beacon.physical.flag_writes==0);
#endif
Driver d;
#if defined(SX126X_RXEN) && SX126X_RXEN != -1
assert(d.setRxPowerSavingRfRxDisabled(true));
assert(d.physical.disabled&&d.rearm_calls==1&&d.physical.standby_calls==1);
assert(d._rx_ps_enabled&&d._rx_ps_armed&&d.state==STATE_RX);
d.rearm_fails=true;
assert(!d.setRxPowerSavingRfRxDisabled(false));
assert(d.physical.disabled&&d.state==STATE_IDLE&&d.retry_pending);
assert(d.physical.flag_writes==3); // Accepted true; failed false followed by true rollback.
assert(d._rx_ps_enabled&&d._rx_ps_rx_us==123456&&d._rx_ps_sleep_us==765432);
// Existing normal receive recovery reuses the restored old policy.
d.rearm_fails=false;d.startRecv();assert(d.isInRecvMode()&&d.physical.disabled);
d.state=STATE_IDLE;d._rx_ps_armed=false;
assert(d.setRxPowerSavingRfRxDisabled(false));assert(!d.physical.disabled);
#else
assert(!d.supportsRxPowerSavingRfRxDisable());
assert(!d.setRxPowerSavingRfRxDisabled(true));
assert(d.physical.standby_calls==0&&d.physical.flag_writes==0);
#endif
}
static void radio2_suspended_rxps() {
#if defined(SX126X_RXEN) && SX126X_RXEN != -1
Driver d;
d._rx_ps_enabled=false;d._rx_ps_armed=false;
d._profile_rxps_suspended=true;d._profile_saved_rxps=true;
auto retained=[&]() {
assert(!d._rx_ps_enabled&&!d._rx_ps_armed);
assert(d._profile_rxps_suspended&&d._profile_saved_rxps);
assert(d._rx_ps_rx_us==123456&&d._rx_ps_sleep_us==765432);
};
// Radio2 receives continuously while retaining the user's RXPS-on policy.
// Calling setRxPowerSaving(false,...) here would overwrite that saved policy.
assert(d.setRxPowerSavingRfRxDisabled(true));retained();
assert(d.isInRecvMode()&&d.physical.disabled);
d.chip_busy=true;
assert(!d.setRxPowerSavingRfRxDisabled(false));retained();
assert(d.physical.disabled);
d.chip_busy=false;d.rearm_fails=true;
assert(!d.setRxPowerSavingRfRxDisabled(false));retained();
assert(d.physical.disabled&&d.state==STATE_IDLE&&d.retry_pending);
d.rearm_fails=false;d.startRecv();retained();
assert(d.isInRecvMode()&&d.physical.disabled);
assert(d.setRxPowerSavingRfRxDisabled(false));retained();
assert(d.isInRecvMode()&&!d.physical.disabled);
#endif
}
int main() {
backend_guards();radio2_suspended_rxps();Harness h;char reply[160];
bounds(h,"get rxps.wd","> soft=11,hard=13");
#if defined(SX126X_RXEN) && SX126X_RXEN != -1
bounds(h,"get radio.rxps.rfrx_disabled","> off");
bounds(h,"get radio.rxps.rfrx_disabled","Error: radio unavailable",false);
assert(h.command("set radio.rxps.rfrx_disabled on",reply,sizeof(reply)));
assert(!strcmp(reply,"OK - radio.rxps.rfrx_disabled on")&&h.driver.physical.disabled);
h.driver.chip_busy=true;
assert(h.command("set radio.rxps.rfrx_disabled off",reply,sizeof(reply)));
assert(!strcmp(reply,"Error: radio busy or RXEN change failed")&&h.driver.physical.disabled);
h.driver.chip_busy=false;
h.driver.rearm_fails=true;
assert(h.command("set radio.rxps.rfrx_disabled off",reply,sizeof(reply)));
assert(!strcmp(reply,"Error: radio busy or RXEN change failed")&&h.driver.physical.disabled);
h.driver.rearm_fails=false;h.driver.startRecv();
assert(h.command("set radio.rxps.rfrx_disabled off",reply,sizeof(reply)));
assert(!h.driver.physical.disabled);
#else
bounds(h,"get radio.rxps.rfrx_disabled","Error: unsupported");
bounds(h,"set radio.rxps.rfrx_disabled on","Error: unsupported");
assert(h.driver.physical.flag_writes==0);
#endif
const unsigned writes=h.driver.physical.flag_writes;
for(const char* command:{"set radio.rxps.rfrx_disabled", "set radio.rxps.rfrx_disabled ",
"set radio.rxps.rfrx_disabled banana","set radio.rxps.rfrx_disabled on extra",
"set radio.rxps.rfrx_disabled\ton"}) {
assert(h.command(command,reply,sizeof(reply)));
assert(!strncmp(reply,"Error: use ",11));
}
for(const char* command:{"get rxps.wdx","get rxps.wd extra","get radio.rxps.rfrx_disabledx",
"set radio.rxps.rfrx_disabledx on","clear stats extra","clear stats ","CLEAR stats"}) {
memset(reply,'X',sizeof(reply));assert(!h.command(command,reply,sizeof(reply)));
for(char c:reply)assert(c=='X');
}
assert(h.driver.physical.flag_writes==writes);
assert(!h.command(nullptr,reply,sizeof(reply)));
assert(!h.command("clear stats",nullptr,sizeof(reply)));
assert(!h.command("clear stats",reply,0));assert(h.clears==0);
assert(h.command("clear stats",reply,sizeof(reply)));
assert(!strcmp(reply,"(OK - stats reset)")&&h.clears==1);
assert(h.driver.n_recv==0&&h.driver.n_sent==0&&h.driver.n_recv_errors==0);
assert(h.dispatcher.n_sent_flood==0&&h.dispatcher.n_sent_direct==0&&h.dispatcher.n_recv_flood==0&&h.dispatcher.n_recv_direct==0);
assert(h.dispatcher._err_flags==0&&h.tables._direct_dups==0&&h.tables._flood_dups==0);
assert(h.driver.n_wd_soft==11&&h.driver.n_wd_hard==13&&h.driver.last_rx==1234);
assert(h.dispatcher.last_meshcore_rx==23456&&h.dispatcher.outbound==std::vector<int>{42});
assert(h.tables.dedup_history==std::vector<int>({1,2,3}));
const std::string cad="radio.cad on, scan=auto(3500) ms, retry=auto ms, max=60000 ms, busy=4294967295";
for(size_t cap=1;cap<=176;++cap) {
std::vector<unsigned char> bytes(cap+16,0xa5);char* out=reinterpret_cast<char*>(bytes.data()+8);
mesh::companion::formatCadDiagnostics(out,cap,true,"auto(3500)","auto","60000",UINT32_MAX);
assert(std::string(out)==cad.substr(0,cap-1));
for(size_t i=0;i<8;++i)assert(bytes[i]==0xa5);
for(size_t i=8+cap;i<bytes.size();++i)assert(bytes[i]==0xa5);
}
mesh::companion::formatCadDiagnostics(nullptr,0,true,"a","b","c",1);
puts("Companion radio diagnostics cases passed");
}
+12 -5
View File
@@ -1,3 +1,4 @@
#include <helpers/SdCardCLI.h>
#include <cassert>
#include <cstdint>
#include <cstdio>
@@ -8,8 +9,11 @@ static uint32_t clock_ms = 500000;
static uint32_t millis() { return clock_ms; }
static const char* skipSpacesConst(const char* in) { while (*in == ' ' || *in == '\t') ++in; return in; }
static constexpr uint32_t SDCARD_ACTION_COOLDOWN_MILLIS = 300000;
struct Board {};
namespace mesh { class MainBoard {}; }
using Board = mesh::MainBoard;
namespace mesh { namespace ota {
[[maybe_unused]] static bool ethernet_owned = false;
[[maybe_unused]] static bool rak4631_ethernet_owns_spi() { return ethernet_owned; }
struct OtaStoreSdNrf52 {
int formats = 0, erases = 0, spaces = 0, lists = 0;
uint16_t page = 0;
@@ -53,10 +57,13 @@ static void formatStorageBytes(char* reply, size_t cap, uint64_t value) { snprin
struct CommonCLI {
Board board;
Board* _board = &board;
bool _sdcard_format_recorded = false, _sdcard_erase_recorded = false;
uint32_t _sdcard_format_at = 0, _sdcard_erase_at = 0;
bool handleSdCardSetCmd(const char*, char*);
bool handleSdCardGetCmd(const char*, char*);
mesh::cli::SdCardCLIState state;
bool handleSdCardSetCmd(const char* config, char* reply) {
return mesh::cli::handleSdCardSet(state, board, config, reply, 160);
}
bool handleSdCardGetCmd(const char* config, char* reply) {
return mesh::cli::handleSdCardGet(state, board, config, reply, 160);
}
};
@METHODS@
+11 -6
View File
@@ -1,3 +1,4 @@
#include <helpers/SdCardCLI.h>
// 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>
@@ -14,9 +15,12 @@ static const char* skipSpacesConst(const char* in) {
return in;
}
static constexpr uint32_t SDCARD_ACTION_COOLDOWN_MILLIS = 300000;
struct Board {};
namespace mesh { class MainBoard {}; }
using Board = mesh::MainBoard;
namespace mesh { namespace ota {
[[maybe_unused]] static bool ethernet_owned = false;
[[maybe_unused]] static bool rak4631_ethernet_owns_spi() { return ethernet_owned; }
struct OtaManager {
enum State { IDLE, FETCHING, COMPLETE, PAUSED, FAILED };
State state = IDLE;
@@ -66,9 +70,10 @@ static OtaContext& ota_ctx() { return context; }
struct CommonCLI {
Board board;
Board* _board = &board;
bool _sdcard_format_recorded = false, _sdcard_erase_recorded = false;
uint32_t _sdcard_format_at = 0, _sdcard_erase_at = 0;
bool handleSdCardSetCmd(const char*, char*);
mesh::cli::SdCardCLIState state;
bool handleSdCardSetCmd(const char* config, char* reply) {
return mesh::cli::handleSdCardSet(state, board, config, reply, 160);
}
};
@METHODS@
@@ -88,8 +93,8 @@ int main() {
CommonCLI cli;
// --force only bypasses the action cooldown, never store ownership.
if (strstr(command, "--force")) {
cli._sdcard_format_recorded = cli._sdcard_erase_recorded = true;
cli._sdcard_format_at = cli._sdcard_erase_at = clock_ms;
cli.state.format_recorded = cli.state.erase_recorded = true;
cli.state.format_at = cli.state.erase_at = clock_ms;
}
struct Reply { char text[160]; char guard[8] = "guarded"; } reply{};
assert(cli.handleSdCardSetCmd(command, reply.text));
+194
View File
@@ -0,0 +1,194 @@
"""Execute real Companion power formatting and the nRF52 hardware-state reader."""
from pathlib import Path
import os
import re
import subprocess
import tempfile
import unittest
from cpp_source import body
ROOT = Path(__file__).resolve().parents[1]
class CompanionPowerDiagnostics(unittest.TestCase):
def compile(self, source, flags=()):
with tempfile.TemporaryDirectory(prefix="companion-power-diagnostics-") as folder:
cpp, exe = Path(folder) / "test.cpp", Path(folder) / "test"
cpp.write_text(source, encoding="ascii")
result = subprocess.run([os.environ.get("CXX", "c++"), "-std=c++17",
"-Wall", "-Wextra", "-Werror", "-fsanitize=address,undefined",
"-fno-omit-frame-pointer", "-no-pie", "-I", str(ROOT / "src"),
*["-D" + flag for flag in flags], str(cpp), "-o", str(exe)],
capture_output=True, text=True, timeout=30)
self.assertEqual(result.returncode, 0, result.stderr)
run = subprocess.run([str(exe)], capture_output=True, text=True, timeout=10)
self.assertEqual(run.returncode, 0, run.stderr)
def test_actual_common_power_format_and_capability_gates(self):
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
common = body(source, '} else if (strcmp(command, "power") == 0)')
common = common[common.index("{") :]
fixture = r'''
#include <helpers/CompanionPowerDiagnostics.h>
#include <cassert>
struct Board {
bool pm=false, usb_cap=false, solar_cap=false;
bool usb=false, solar=false, external=false, charger=false;
bool watchdog_supported=true, watchdog_running=true;
unsigned batt_reads=0, boot_reads=0, source_reads=0, usb_reads=0, solar_reads=0;
bool supportsPowerManagement() const { return pm; }
bool hasUsbPowerDetect() const { return usb_cap; }
bool hasSolarChargerDetect() const { return solar_cap; }
bool isUsbPowered() { ++usb_reads; return usb; }
bool isSolarChargerActive() { ++solar_reads; return solar; }
bool isExternalPowered() { ++source_reads; return external; }
bool isChargerActive() { return charger; }
unsigned getBattMilliVolts() { ++batt_reads; return 4102; }
unsigned getBootVoltage() { ++boot_reads; return 3991; }
bool getSystemWatchdogRunning(bool& running) const {
running=watchdog_running; return watchdog_supported;
}
};
void commonPower(Board& board, char* reply) {
auto* _board=&board;
@COMMON@
}
void expect(Board& board,const char* command,const char* expected) {
char reply[160];
assert(mesh::companion::handlePowerDiagnosticsCommand(board,command,reply,sizeof(reply)));
assert(strcmp(reply,expected)==0);
}
int main() {
Board board;
expect(board,"get pwrmgt.support","> unsupported");
expect(board,"get pwrmgt.source","ERROR: Power management not supported");
expect(board,"get pwrmgt.bootmv","ERROR: Power management not supported");
assert(board.source_reads==0 && board.boot_reads==0);
board.pm=true;
expect(board,"get pwrmgt.support","> supported");
expect(board,"get pwrmgt.source","> battery");
board.external=true;
expect(board,"get pwrmgt.source","> external");
expect(board,"get pwrmgt.bootmv","> 3991 mV");
assert(board.boot_reads==1 && board.batt_reads==0);
for(unsigned bits=0;bits<64;++bits) {
board.usb_cap=bits&1;board.solar_cap=bits&2;board.usb=bits&4;
board.solar=bits&8;board.external=bits&16;board.charger=bits&32;
board.usb_reads=board.solar_reads=0;
char actual[160],expected[160];
assert(mesh::companion::handlePowerDiagnosticsCommand(board,"power",actual,sizeof(actual)));
assert(board.usb_reads==unsigned(board.usb_cap));
assert(board.solar_reads==unsigned(board.solar_cap));
commonPower(board,expected);
assert(strcmp(actual,expected)==0);
}
board.watchdog_supported=true;board.watchdog_running=false;
expect(board,"get system.watchdog","> off");
board.watchdog_running=true;expect(board,"get system.watchdog","> on");
board.watchdog_supported=false;
expect(board,"get system.watchdog","Error: unsupported on this platform");
for(const char* command:{"set system.watchdog on","set system.watchdog off","set system.watchdog","set system.watchdog invalid"}) {
expect(board,command,"Error: system watchdog control is unavailable in Companion");
assert(board.watchdog_running); // A setter must never pretend to stop it.
}
}
'''.replace("@COMMON@", common)
fixture = "#include <initializer_list>\n" + fixture
self.compile(fixture)
def test_actual_nrf_reader_reports_hardware_even_with_feeding_disabled(self):
source = (ROOT / "src/helpers/NRF52Board.cpp").read_text()
reader = body(source, "bool NRF52Board::getSystemWatchdogRunning(bool& running) const")
self.assertNotRegex(reader, r"feedWatchdog|serviceWatchdog|TASKS_START|RR\[")
fixture = r'''
#include <cassert>
#include <cstdint>
struct { volatile uint32_t RUNSTATUS=0; uint32_t untouched=0x1234; } registers;
#define NRF_WDT (&registers)
struct NRF52Board { bool getSystemWatchdogRunning(bool& running) const; };
@READER@
int main() {
const NRF52Board board;
bool running=true;
assert(board.getSystemWatchdogRunning(running) && !running);
registers.RUNSTATUS=1;
assert(board.getSystemWatchdogRunning(running) && running);
registers.RUNSTATUS=2;
assert(board.getSystemWatchdogRunning(running) && running);
assert(registers.RUNSTATUS==2 && registers.untouched==0x1234);
}
'''.replace("@READER@", reader)
self.compile(fixture, ["NRF52_WATCHDOG_TIMEOUT_SECONDS=0"])
self.compile(fixture, ["NRF52_WATCHDOG_TIMEOUT_SECONDS=60"])
def test_real_base_defaults_and_nrf_support_scope(self):
source = (ROOT / "src/MeshCore.h").read_text()
default_reader = body(source, "virtual bool getSystemWatchdogRunning(bool& running) const")
default_power = body(source, "virtual bool supportsPowerManagement() const")
nrf = (ROOT / "src/helpers/NRF52Board.h").read_text()
nrf_power = body(nrf, "bool supportsPowerManagement() const override")
preceding = nrf[:nrf.index("bool supportsPowerManagement() const override")]
active = []
for directive in re.findall(r"^\s*#\s*(if[^\n]*|endif)\s*$", preceding, re.MULTILINE):
if directive == "endif": active.pop()
else: active.append(directive)
self.assertIn("ifdef NRF52_POWER_MANAGEMENT", active)
fixture = r'''
#include <cassert>
struct MainBoard {
@READER@
@POWER@
};
struct ManagedBoard:MainBoard {
@NRF_POWER@
};
int main() {
MainBoard base;ManagedBoard managed;
bool running=true;
assert(!base.getSystemWatchdogRunning(running) && running);
assert(!base.supportsPowerManagement() && managed.supportsPowerManagement());
}
'''.replace("@READER@", default_reader).replace("@POWER@", default_power).replace("@NRF_POWER@", nrf_power)
self.compile(fixture)
def test_small_output_buffers_and_unknown_commands(self):
fixture = r'''
#include <helpers/CompanionPowerDiagnostics.h>
#include <cassert>
#include <initializer_list>
struct Board {
bool supportsPowerManagement()const{return true;}
bool hasUsbPowerDetect()const{return true;}
bool hasSolarChargerDetect()const{return true;}
bool isUsbPowered(){return true;}
bool isSolarChargerActive(){return true;}
bool isExternalPowered(){return true;}
bool isChargerActive(){return true;}
unsigned getBattMilliVolts(){return 12345;}
unsigned getBootVoltage(){return 54321;}
bool getSystemWatchdogRunning(bool& v)const{v=true;return true;}
};
int main() {
Board board;
for(const char* command:{"power","get pwrmgt.support","get pwrmgt.source","get pwrmgt.bootmv","get system.watchdog","set system.watchdog off"}) {
for(unsigned length=1;length<160;++length) {
char data[162];memset(data,'z',sizeof(data));
assert(mesh::companion::handlePowerDiagnosticsCommand(board,command,data+1,length));
assert(data[0]=='z' && data[length+1]=='z');
assert(memchr(data+1,0,length)!=nullptr);
}
}
char untouched[8]="stable";
for(const char* command:{"","get pwrmgt.support.extra","power extra","get system.watchdog off","set system.watchdog.extra off"}) {
assert(!mesh::companion::handlePowerDiagnosticsCommand(board,command,untouched,sizeof(untouched)));
assert(strcmp(untouched,"stable")==0);
}
assert(!mesh::companion::handlePowerDiagnosticsCommand(board,nullptr,untouched,sizeof(untouched)));
assert(!mesh::companion::handlePowerDiagnosticsCommand(board,"power",nullptr,sizeof(untouched)));
assert(!mesh::companion::handlePowerDiagnosticsCommand(board,"power",untouched,0));
}
'''
self.compile(fixture)
if __name__ == "__main__":unittest.main()
+51
View File
@@ -0,0 +1,51 @@
"""Real shared CLI plus RXEN admission/restoration and existing reset semantics."""
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
from cpp_source import body
ROOT=Path(__file__).resolve().parents[1]
class CompanionRadioDiagnosticsTests(unittest.TestCase):
def test_production_backend_admission_cli_bounds_and_reset_scope(self):
wrapper=(ROOT/'src/helpers/radiolib/CustomSX1262Wrapper.h').read_text()
radio=(ROOT/'src/helpers/radiolib/RadioLibWrappers.cpp').read_text()
header=(ROOT/'src/helpers/radiolib/RadioLibWrappers.h').read_text()
dispatcher=(ROOT/'src/Dispatcher.h').read_text()
tables=(ROOT/'src/helpers/SimpleMeshTables.h').read_text()
methods='\n'.join(body(wrapper,signature) for signature in (
'bool supportsRxPowerSavingRfRxDisable() const override',
'bool setRxPowerSavingRfRxDisabled(bool disabled) override',
'bool isRxPowerSavingRfRxDisabled() const override'))
admission='\n'.join(body(radio,signature) for signature in (
'uint8_t RadioLibWrapper::beginReconfigure()',
'void RadioLibWrapper::endReconfigure(bool resume_rx)',
'bool RadioLibWrapper::isInRecvMode() const'))
with tempfile.TemporaryDirectory(prefix='mesh-companion-radio-diagnostics-') as directory:
work=Path(directory)
for name,source in {
'production_rxen.inc':methods,
'production_admission.inc':admission,
'production_radio_reset.inc':body(header,'void resetStats()'),
'production_dispatcher_reset.inc':body(dispatcher,'void resetStats()'),
'production_table_reset.inc':body(tables,'void resetStats()'),
}.items():
(work/name).write_text(source)
for rxen,beacons in ((5,0),(5,1),(-1,1),(None,0)):
with self.subTest(rxen=rxen,beacons=beacons):
flags=['-DMESH_ENABLE_TX_BEACONS='+str(beacons)]
if rxen is not None:flags.append('-DSX126X_RXEN='+str(rxen))
exe=work/('test-'+str(rxen)+'-'+str(beacons))
command=[os.environ.get('CXX','g++'),'-std=c++17','-Wall','-Wextra','-Werror',
'-fsanitize=address,undefined','-fno-sanitize-recover=all','-fno-pie','-no-pie',
'-I'+str(ROOT/'src'),'-I'+str(work),*flags,
str(ROOT/'test/fixtures/companion_radio_diagnostics/test.cpp'),'-o',str(exe)]
result=subprocess.run(command,capture_output=True,text=True,timeout=60)
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
result=subprocess.run([str(exe)],capture_output=True,text=True,timeout=20)
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
self.assertIn('radio diagnostics cases passed',result.stdout)
if __name__=='__main__':unittest.main()
+5 -4
View File
@@ -200,10 +200,11 @@ int main() { EnvironmentSensorManager sensors; assert(sensors.detectWisBlockStor
build(self, harness, defines)
def test_sd_cli_cold_context_oom_validation_and_card_actions(self):
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
methods = "\n".join(extract_braced(source, signature) for signature in (
"static void formatSdCardElapsed(", "bool CommonCLI::handleSdCardSetCmd(",
"bool CommonCLI::handleSdCardGetCmd("))
source = (ROOT / "src/helpers/SdCardCLI.cpp").read_text()
methods = "namespace mesh { namespace cli {\n" + "\n".join(
extract_braced(source, signature) for signature in (
"static bool sdCardBusAvailable(", "static void formatSdCardElapsed(",
"bool handleSdCardSet(", "bool handleSdCardGet(")) + "\n} }\n"
fixture = (FIXTURES / "cli.cpp").read_text()
build(self, fixture.replace("@METHODS@", methods), ["NRF52_PLATFORM", "OTA_SD_STORE"])
+9 -17
View File
@@ -105,9 +105,11 @@ int main() {
class RakSdContextHandoffTests(unittest.TestCase):
def test_card_maintenance_preserves_non_sd_install_sessions(self):
source = (ROOT / 'src/helpers/CommonCLI.cpp').read_text()
methods = '\n'.join(extract_braced(source, signature) for signature in (
'static void formatSdCardElapsed(', 'bool CommonCLI::handleSdCardSetCmd('))
source = (ROOT / 'src/helpers/SdCardCLI.cpp').read_text()
methods = 'namespace mesh { namespace cli {\n' + '\n'.join(
extract_braced(source, signature) for signature in (
'static bool sdCardBusAvailable(', 'static void formatSdCardElapsed(',
'bool handleSdCardSet(')) + '\n} }\n'
fixture = (ROOT / 'test/fixtures/rak15002_sd_seeder/maintenance.cpp').read_text()
for profile in (
['OTA_RAK15002_SD_STORE', 'OTA_RAK_AUTO_STORE'],
@@ -137,7 +139,7 @@ class RakSdContextHandoffTests(unittest.TestCase):
build(self, harness, ['OTA_RAK15002_SD_STORE',
*(['OTA_SEEDER_ONLY'] if seeder else [])])
def test_companion_physical_ethernet_and_sd_commands_keep_failed_admission_off(self):
def test_companion_physical_ethernet_commands_keep_failed_admission_off(self):
source = (ROOT / 'examples/companion_radio/main.cpp').read_text()
method = extract_braced(source, 'bool handleRak4631PeripheralCommand(')
fixture = r'''
@@ -190,25 +192,15 @@ int main() {
ethernet_interface.state = "online";
assert(handleRak4631PeripheralCommand("get eth", reply, sizeof reply));
assert(strstr(reply, "eth=online"));
assert(handleRak4631PeripheralCommand("get sdcard free", reply, sizeof reply));
assert(strstr(reply, "Ethernet off") && !mesh::ota::acquires);
assert(handleRak4631PeripheralCommand("set eth off", reply, sizeof reply));
assert(strstr(reply, "eth=stopping") && ethernet_interface.active);
assert(handleRak4631PeripheralCommand("get sdcard", reply, sizeof reply));
assert(strstr(reply, "Ethernet off") && !mesh::ota::acquires);
ethernet_interface.active = false; ethernet_interface.state = "off";
assert(handleRak4631PeripheralCommand("get eth", reply, sizeof reply));
assert(strstr(reply, "eth=off"));
assert(!ethernet_interface.active);
mesh::ota::admission = false;
assert(handleRak4631PeripheralCommand("get sdcard", reply, sizeof reply));
assert(strstr(reply, "queue busy") && !mesh::ota::context.card.queries);
mesh::ota::admission = true;
assert(handleRak4631PeripheralCommand("get sdcard free", reply, sizeof reply));
assert(strstr(reply, "used=42 free=4096 bytes") && mesh::ota::context.card.queries == 1);
mesh::ota::context.card.okay = false;
assert(handleRak4631PeripheralCommand("get sdcard", reply, sizeof reply));
assert(strstr(reply, "no SD card"));
// SD command admission moved into the shared production handler, executed
// under all SD profiles by test_sdcard_cli_parity.py.
assert(!handleRak4631PeripheralCommand("get sdcard free", reply, sizeof reply));
}
'''.replace('@METHOD@', method)
build(self, fixture)
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Compile the shared production SD CLI against stateful storage boundaries."""
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
ARDUINO = r'''
#pragma once
#include <stdint.h>
extern uint32_t clock_ms;
inline uint32_t millis() { return clock_ms; }
'''
BOARD = '#pragma once\nnamespace mesh { class MainBoard {}; }\n'
CONTEXT = r'''
#pragma once
#include <MeshCore.h>
#include <stdint.h>
#include <stdio.h>
namespace mesh { namespace ota {
inline bool ethernet_owned = false;
inline bool rak4631_ethernet_owns_spi() { return ethernet_owned; }
struct OtaManager {
enum State { IDLE, FETCHING, COMPLETE };
State state = IDLE;
unsigned resets = 0;
State fetchState() const { return state; }
void reset_session() { ++resets; state = IDLE; }
void want(unsigned) {}
void want_mid(const uint8_t*) {}
};
struct FetchStore {
bool internal = false, sd = true;
uint32_t staged = 0;
bool usesInternal() const { return internal; }
bool usesSd() const { return sd; }
uint32_t staged_size() const { return staged; }
};
struct OtaStoreSdNrf52 {
unsigned formats = 0, erases = 0, spaces = 0, lists = 0;
uint16_t page = 0;
bool format_ok = true, erase_ok = true, read_ok = true;
bool formatCard(MainBoard&) { ++formats; return format_ok; }
bool eraseCard(MainBoard&) { ++erases; return erase_ok; }
bool getSpace(MainBoard&, uint64_t& used, uint64_t& free) {
++spaces; used = 12; free = 34; return read_ok;
}
bool listFiles(MainBoard&, uint16_t p, char* reply, size_t cap) {
++lists; page = p; snprintf(reply, cap, "> files page=%u", unsigned(p)); return read_ok;
}
const char* last_error() const { return "card unavailable"; }
};
struct OtaContext {
OtaManager manager;
FetchStore fetch_store;
OtaStoreSdNrf52 card;
bool apply_pending = false;
uint32_t session_started_ms = 1;
OtaManager::State prev_fstate = OtaManager::FETCHING;
unsigned prepares = 0, finishes = 0;
OtaStoreSdNrf52& sdStagingStore() { return card; }
void prepareSdCardReset() { ++prepares; }
void finishSdCardReset(uint32_t) { ++finishes; }
};
inline OtaContext context;
inline bool acquired = false, out_of_memory = false;
inline unsigned acquisitions = 0, accesses = 0;
inline bool ota_acquire_context(char* reply, size_t cap) {
++acquisitions;
if (out_of_memory) { snprintf(reply, cap, "ERR mOTA out of memory"); return false; }
acquired = true; return true;
}
inline OtaContext& ota_ctx() {
if (!acquired) __builtin_trap();
++accesses; return context;
}
} }
'''
HARNESS = r'''
#include <helpers/SdCardCLI.h>
#include <helpers/ota/OtaContext.h>
#include <cassert>
#include <cstring>
#include <initializer_list>
uint32_t clock_ms = 500000;
int main() {
using namespace mesh::ota;
mesh::MainBoard board;
mesh::cli::SdCardCLIState state;
struct Reply { char text[160]; char sentinel[8] = "guarded"; } reply{};
auto command = [&](const char* value) {
bool handled = mesh::cli::handleSdCardCommand(state, board, value, reply.text, sizeof(reply.text));
assert(strcmp(reply.sentinel, "guarded") == 0); return handled;
};
assert(!command("get sdcardoops"));
assert(!command("set unrelated"));
for (const char* value : {"get sdcard", "get sdcard *", "get sdcard format", "get sdcard erase"}) {
assert(command(value)); assert(strstr(reply.text, "never"));
}
for (const char* value : {"get sdcard invalid", "get sdcard ls 0", "get sdcard dir -1",
"get sdcard dir 65536", "get sdcard lsoops", "get sdcard dir 2 extra",
"set sdcard format unknown"}) {
assert(command(value)); assert(strncmp(reply.text, "Error:", 6) == 0);
}
assert(!acquisitions && !accesses);
#if defined(OTA_RAK15002_SD_STORE)
ethernet_owned = true;
for (const char* value : {"get sdcard free", "get sdcard ls", "set sdcard format --force", "set sdcard erase --force"}) {
assert(command(value)); assert(strstr(reply.text, "Ethernet off"));
assert(!acquisitions && !accesses && !context.prepares && !context.manager.resets);
}
ethernet_owned = false;
#endif
out_of_memory = true;
assert(command("get sdcard free")); assert(strstr(reply.text, "out of memory"));
assert(!accesses && !context.card.spaces);
out_of_memory = false;
assert(command("get sdcard free")); assert(strstr(reply.text, "12 B") && strstr(reply.text, "34 B"));
assert(command("get sdcard dir 65535")); assert(context.card.page == 65535);
context.card.read_ok = false;
assert(command("get sdcard free")); assert(strstr(reply.text, "card unavailable"));
assert(command("get sdcard ls")); assert(strstr(reply.text, "card unavailable"));
context.card.read_ok = true;
context.apply_pending = true;
assert(command("set sdcard format --force"));
assert(strstr(reply.text, "apply is pending") && !context.prepares && !context.card.formats);
context.apply_pending = false;
context.card.format_ok = false;
assert(command("set sdcard format"));
assert(strstr(reply.text, "format failed") && context.prepares == 1 && context.finishes == 1);
assert(!state.format_recorded);
context.card.format_ok = true;
assert(command("set sdcard format")); assert(state.format_recorded && state.format_at == clock_ms);
unsigned formats = context.card.formats;
assert(command("set sdcard format")); assert(strstr(reply.text, "--force") && context.card.formats == formats);
assert(command("set sdcard format --force")); assert(context.card.formats == formats + 1);
context.card.erase_ok = false;
assert(command("set sdcard erase")); assert(strstr(reply.text, "erase failed"));
assert(!state.erase_recorded && context.prepares == context.finishes);
context.card.erase_ok = true; context.card.format_ok = false;
assert(command("set sdcard erase")); assert(strstr(reply.text, "erased but format failed"));
assert(state.erase_recorded && context.prepares == context.finishes);
context.card.format_ok = true;
assert(command("set sdcard erase --force")); assert(strstr(reply.text, "erase and format complete"));
// uint32_t wrap must retain the same five-minute cooldown semantics.
state.format_recorded = true; state.format_at = 0xfffffff0u; clock_ms = 20;
formats = context.card.formats;
assert(command("set sdcard format")); assert(context.card.formats == formats);
clock_ms += 300000;
assert(command("set sdcard format")); assert(context.card.formats == formats + 1);
// Short framed replies are always bounded, including failed operations.
struct Tiny { char text[8]; char sentinel[8] = "guarded"; } tiny{};
assert(mesh::cli::handleSdCardCommand(state, board, "get sdcard *", tiny.text, sizeof(tiny.text)));
assert(tiny.text[7] == 0 && strcmp(tiny.sentinel, "guarded") == 0);
assert(mesh::cli::handleSdCardCommand(state, board, "set sdcard format --force", tiny.text, sizeof(tiny.text)));
assert(tiny.text[7] == 0 && strcmp(tiny.sentinel, "guarded") == 0);
assert(mesh::cli::handleSdCardCommand(state, board, "set sdcard erase --force", tiny.text, sizeof(tiny.text)));
assert(tiny.text[7] == 0 && strcmp(tiny.sentinel, "guarded") == 0);
assert(!mesh::cli::handleSdCardCommand(state, board, nullptr, reply.text, sizeof(reply.text)));
assert(!mesh::cli::handleSdCardCommand(state, board, "get sdcard", nullptr, 0));
}
'''
class SdCardCLIParityTests(unittest.TestCase):
def compile_and_run(self, defines):
compiler = os.environ.get('CXX') or shutil.which('g++') or shutil.which('clang++')
if not compiler:
self.skipTest('host C++17 compiler required')
with tempfile.TemporaryDirectory(prefix='sdcard-cli-') as folder:
work = Path(folder)
for name, text in {'Arduino.h': ARDUINO, 'MeshCore.h': BOARD,
'helpers/ota/OtaContext.h': CONTEXT,
'main.cpp': HARNESS}.items():
path = work / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text(text)
sanitizer = ['-fsanitize=address,undefined', '-fno-sanitize-recover=all',
'-fno-pie', '-no-pie'] if sys.platform.startswith('linux') else []
result = subprocess.run([compiler, '-std=c++17', '-Wall', '-Wextra', '-Werror',
*sanitizer, *['-D' + value for value in ['NRF52_PLATFORM', 'OTA_SD_STORE', *defines]],
'-I' + str(work), '-I' + str(ROOT / 'src'), str(ROOT / 'src/helpers/SdCardCLI.cpp'),
str(work / 'main.cpp'), '-o', str(work / 'test')], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
result = subprocess.run([str(work / 'test')], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_actual_shared_cpp_handles_legacy_sd_and_source_only_profiles(self):
for defines in ([], ['OTA_SEEDER_ONLY'], ['OTA_TOWER_AUTO_STORE'],
['OTA_RAK15002_SD_STORE', 'OTA_RAK_AUTO_STORE'],
['OTA_RAK15002_SD_STORE', 'OTA_SEEDER_ONLY']):
with self.subTest(defines=defines):
self.compile_and_run(defines)
def test_common_cli_delegates_to_same_implementation(self):
source = (ROOT / 'src/helpers/CommonCLI.cpp').read_text()
self.assertIn('handleSdCardSet(_sdcard_cli, *_board, config, reply, 160)', source)
self.assertIn('handleSdCardGet(_sdcard_cli, *_board, config, reply, 160)', source)
self.assertNotIn('context.prepareSdCardReset()', source)
header = (ROOT / 'src/helpers/CommonCLI.h').read_text()
self.assertIn('mesh::cli::SdCardCLIState _sdcard_cli;', header)
if __name__ == '__main__':
unittest.main()