feat: second radio preset with cross-profile policy and timed wake

This commit is contained in:
github-actions[bot] committed 2026-11-09 16:16:34 -06:00
1 parent a666e748d9
commit 0c3a0ce810
27 files changed
+4048 -32

No files matched your search

+1889
View File
File diff suppressed because it is too large. Load diff
+5 -2
View File
@@ -200,7 +200,7 @@ CliEnqueue CliScriptRunner::parse(const char* text, CliScriptMeta* meta) {
}
CliEnqueue CliScriptRunner::enqueue(const char* text, const uint8_t* chan_secret,
uint8_t chan_hash) {
uint8_t chan_hash, uint8_t radio_profile) {
CliScriptMeta meta;
CliEnqueue rc = parse(text, &meta);
if (rc == CLI_ENQUEUE_NO_ID) { noid++; return rc; }
@@ -219,6 +219,7 @@ CliEnqueue CliScriptRunner::enqueue(const char* text, const uint8_t* chan_secret
strcpy(slot->key, meta.key); // validated by validKey()
slot->ack = meta.ack;
slot->body_off = meta.body_off;
slot->radio_profile = radio_profile;
if (chan_secret != NULL) {
memcpy(slot->chan_secret, chan_secret, sizeof(slot->chan_secret));
slot->chan_hash = chan_hash;
@@ -229,7 +230,7 @@ CliEnqueue CliScriptRunner::enqueue(const char* text, const uint8_t* chan_secret
bool CliScriptRunner::enqueueValidated(const char* text, const char* key, uint8_t ack,
uint16_t body_off, const uint8_t* chan_secret,
uint8_t chan_hash) {
uint8_t chan_hash, uint8_t radio_profile) {
if (pending_count >= FLEET_CLI_QUEUE_DEPTH) return false;
if (strlen(key) > FLEET_CLI_KEY_LEN) return false; // defensive; callers pass parsed keys
CliPendingScript* slot = &pending[pending_count++];
@@ -238,6 +239,7 @@ bool CliScriptRunner::enqueueValidated(const char* text, const char* key, uint8_
strcpy(slot->key, key);
slot->ack = ack;
slot->body_off = body_off;
slot->radio_profile = radio_profile;
if (chan_secret != NULL) {
memcpy(slot->chan_secret, chan_secret, sizeof(slot->chan_secret));
slot->chan_hash = chan_hash;
@@ -338,6 +340,7 @@ bool CliScriptRunner::run(CliExecFn fn, void* ctx, CliRunResult* out) {
out->error = slot->first_err[0] != 0;
memcpy(out->chan_secret, slot->chan_secret, sizeof(out->chan_secret));
out->chan_hash = slot->chan_hash;
out->radio_profile = slot->radio_profile;
}
pending_count--;
+6 -2
View File
@@ -98,6 +98,7 @@ struct CliRunResult {
bool error; // at least one command line replied "Err ..."
uint8_t chan_secret[PUB_KEY_SIZE]; // the captured channel, echoed back
uint8_t chan_hash;
uint8_t radio_profile; // captured origin profile
};
// One queued script: the full message text plus the key string, which is only
@@ -117,6 +118,7 @@ struct CliPendingScript {
// signed-difference comparison in run()
uint8_t chan_secret[PUB_KEY_SIZE]; // captured channel (zero-padded secret)
uint8_t chan_hash; // its 1-byte on-air hash
uint8_t radio_profile; // captured origin profile
// reply-summary accumulation, updated as lines execute
uint16_t ran_count; // command lines executed so far
char last_reply[FLEET_REPLY_SUMMARY_LEN]; // reply of the most recent line
@@ -171,7 +173,8 @@ public:
// authoritative parser, and the parse cost of a 184-byte message is noise
// next to the radio.)
CliEnqueue enqueue(const char* text, const uint8_t* chan_secret = NULL,
uint8_t chan_hash = 0);
uint8_t chan_hash = 0,
uint8_t radio_profile = RADIO_PROFILE_PRIMARY);
// Queue an already-parsed script (a scheduled script firing) without
// touching the seen ring — its key was marked when the job was first
@@ -180,7 +183,8 @@ public:
// Returns false when the queue is full; the caller keeps the script and
// retries.
bool enqueueValidated(const char* text, const char* key, uint8_t ack, uint16_t body_off,
const uint8_t* chan_secret, uint8_t chan_hash);
const uint8_t* chan_secret, uint8_t chan_hash,
uint8_t radio_profile = RADIO_PROFILE_PRIMARY);
// Is a script with this key queued or sleeping right now? The manager checks
// this (and its armed store) so a forgotten key cannot run twice at once.
+13 -8
View File
@@ -179,11 +179,12 @@ void FleetManager::onGroupData(const mesh::Packet* packet, uint8_t type,
if (inFlight(meta.key)) { runner.noteDup(); return; }
if (meta.scheduled) {
admitScheduled(text, meta, channel);
admitScheduled(text, meta, channel, packet->getRxProfile());
} else {
// mark-at-enqueue happens inside; refusals are counted there too. Nothing
// executes in the receive path — runScripts() drains later.
runner.enqueue(text, channel.secret, channel.hash[0]);
// executes in the receive path — runScripts() drains later. The origin
// profile rides along so the acknowledgement goes back the same way.
runner.enqueue(text, channel.secret, channel.hash[0], packet->getRxProfile());
}
}
@@ -195,7 +196,7 @@ bool FleetManager::inFlight(const char* key) const {
}
void FleetManager::admitScheduled(const char* text, const CliScriptMeta& meta,
const mesh::GroupChannel& chan) {
const mesh::GroupChannel& chan, uint8_t radio_profile) {
// the runner stays clock-free: staleness and clock-floor refusals are
// manager decisions, made with the node RTC
// A key already seen is a duplicate whatever the clock says: the job ran (or
@@ -219,6 +220,7 @@ void FleetManager::admitScheduled(const char* text, const CliScriptMeta& meta,
s->due_epoch = meta.due_epoch;
memcpy(s->chan_secret, chan.secret, sizeof(s->chan_secret));
s->chan_hash = chan.hash[0];
s->radio_profile = radio_profile;
runner.markKeySeen(meta.key);
}
@@ -233,6 +235,7 @@ void FleetManager::scheduleAckIfNeeded(const CliRunResult& res) {
memcpy(r->summary, res.summary, FLEET_REPLY_SUMMARY_LEN);
memcpy(r->chan_secret, res.chan_secret, sizeof(r->chan_secret));
r->chan_hash = res.chan_hash;
r->radio_profile = res.radio_profile;
// uniform-random jitter against reply storms, measured from when the script
// finished; without an injected RNG the reply goes out immediately
uint32_t jitter = jitter_fn ? jitter_fn(jitter_ctx, reply_window_ms) : 0;
@@ -262,7 +265,7 @@ void FleetManager::runScripts(CliExecFn fn, void* exec_ctx) {
if ((int32_t)(now - sched[i].due_epoch) < 0) { i++; continue; }
if (!runner.enqueueValidated(sched[i].text, sched[i].key, sched[i].ack,
sched[i].body_off, sched[i].chan_secret,
sched[i].chan_hash)) {
sched[i].chan_hash, sched[i].radio_profile)) {
break; // run queue full: keep the script armed, retry next pass
}
memmove(&sched[i], &sched[i + 1], (sched_count - i - 1) * sizeof(sched[0]));
@@ -340,7 +343,7 @@ void FleetManager::serviceReplies() {
continue;
}
bool sent = send_fn(send_ctx, r.chan_secret, r.chan_hash, r.tx_ts, r.sender_name,
body.c_str(), NULL);
body.c_str(), r.radio_profile, NULL);
if (!sent) {
// packet pool refused the retry: it was not sent, so retain the slot and
// try again after the same bounded backoff as an initial-send refusal
@@ -365,7 +368,7 @@ void FleetManager::serviceReplies() {
uint32_t ts = time_fn ? time_fn(time_ctx) : 0;
uint8_t hash[MAX_HASH_SIZE];
bool sent = send_fn(send_ctx, r.chan_secret, r.chan_hash, ts, r.sender_name,
body.c_str(), hash);
body.c_str(), r.radio_profile, hash);
if (!sent) {
// packet pool refused the send: no attempt used, try again shortly. The
// attempts are capped: a reply that can never be sent must not hold its
@@ -415,7 +418,9 @@ bool FleetManager::sendAlert(const char* body) {
if (!enabled || psk_len == 0 || send_fn == NULL) return false;
uint32_t ts = time_fn ? time_fn(time_ctx) : 0;
const char* name = name_fn ? name_fn(name_ctx) : "";
return send_fn(send_ctx, psk, chan_hash, ts, name, body, NULL); // one-shot: no retry
// unsolicited alerts are locally originated: primary profile
return send_fn(send_ctx, psk, chan_hash, ts, name, body,
RADIO_PROFILE_PRIMARY, NULL); // one-shot: no retry
}
// ---------------------------------------------------------------- relay side
+4 -2
View File
@@ -49,7 +49,7 @@ typedef uint32_t (*FleetJitterFn)(void* ctx, uint32_t window);
typedef const char* (*FleetNameFn)(void* ctx);
typedef bool (*FleetSendFn)(void* ctx, const uint8_t* chan_secret, uint8_t chan_hash,
uint32_t ts, const char* sender_name, const char* body,
uint8_t* out_pkt_hash);
uint8_t radio_profile, uint8_t* out_pkt_hash);
// ---------------------------------------------------------------- /fleet_cfg
@@ -106,6 +106,7 @@ class FleetManager {
uint16_t body_off; // command-body offset from the parse
uint8_t chan_secret[PUB_KEY_SIZE]; // captured channel of arrival
uint8_t chan_hash;
uint8_t radio_profile; // captured origin profile
uint32_t due_epoch; // unix seconds UTC
};
FleetSched sched[FLEET_SCHED_STORE];
@@ -128,6 +129,7 @@ class FleetManager {
char summary[FLEET_REPLY_SUMMARY_LEN];
uint8_t chan_secret[PUB_KEY_SIZE];
uint8_t chan_hash;
uint8_t radio_profile; // captured origin profile
uint32_t deadline_ms; // awaiting==0: jitter deadline;
// awaiting==1: retry deadline
uint32_t tx_ts; // frozen group-text timestamp, so the
@@ -278,7 +280,7 @@ private:
// scheduled-script admission (staleness, clock floor, store capacity) and
// the acknowledgement machinery behind runScripts()
void admitScheduled(const char* text, const CliScriptMeta& meta,
const mesh::GroupChannel& chan);
const mesh::GroupChannel& chan, uint8_t radio_profile);
void scheduleAckIfNeeded(const CliRunResult& res);
// a script with this key is armed or queued: a re-send must not run it twice
bool inFlight(const char* key) const;
+103 -7
View File
@@ -433,6 +433,12 @@ void MyMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, ui
}
bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
// A policy drop is a deliberate routing decision, evaluated before the
// battery/filter gates and counted on its own.
if (!rx_forward_allowed) {
radio2.notePolicyDrop();
return false;
}
// Fleet-channel packets bypass the battery gate (fleet.checkForward returns
// false for them, which short-circuits before the gate is consulted, so a
// fleet packet is never counted as a battery drop and relays even while
@@ -520,6 +526,11 @@ void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
}
void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
// logRx() runs before onRecvPacket(): stamp and count the profile recvRaw()
// just read from, so the observer and later hooks see the origin.
const uint8_t rx = radio2.currentProfile();
pkt->setRxProfile(rx);
radio2.noteRx(rx);
#ifdef WITH_MQTT_OBSERVER
mqttObserver.capture(pkt, score);
#endif
@@ -551,6 +562,7 @@ void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
}
void MyMesh::logTx(mesh::Packet *pkt, int len) {
radio2.noteTx(pkt->getTxProfile());
#ifdef WITH_MQTT_OBSERVER
mqttObserver.captureTx(pkt);
#endif
@@ -605,6 +617,15 @@ uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
}
mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) {
// The scanner's current profile is the one recvRaw() just read from.
const uint8_t rx_profile = radio2.currentProfile();
const Radio2Action rx_action = radio2.actionFor(rx_profile, pkt);
rx_forward_allowed = rx_action != RADIO2_ACTION_DROP;
pkt->setRxProfile(rx_profile);
pkt->setTxProfile(radio2.targetFor(rx_action, rx_profile));
if (rx_profile == RADIO_PROFILE_PRIMARY) radio2.notePrimaryPacket();
if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
} else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
@@ -622,11 +643,35 @@ mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) {
// core decides to do in between — including returning early or never reaching
// the forwarding hook at all.
filter.clearContentVerdict();
// Replies created anywhere below (core ACK/path return, CLI, fleet) inherit
// the origin profile through obtainNewPacket().
const uint8_t previous_default = getDefaultTxProfile();
setDefaultTxProfile(radio2.replyProfile(rx_profile));
mesh::DispatcherAction action = Mesh::onRecvPacket(pkt);
setDefaultTxProfile(previous_default);
filter.clearContentVerdict();
if (rx_action == RADIO2_ACTION_BOTH &&
action != ACTION_RELEASE && action != ACTION_MANUAL_HOLD) {
radio2QueueDuplicate(pkt, action, rx_profile);
}
return action;
}
void MyMesh::radio2QueueDuplicate(mesh::Packet* pkt, mesh::DispatcherAction action,
uint8_t origin) {
uint8_t priority = (uint8_t)((action >> 24) - 1);
uint32_t delay = action & 0xFFFFFF;
mesh::Packet* copy = obtainNewPacket();
if (!copy) { radio2.noteBothDrop(); return; }
*copy = *pkt;
copy->setTxProfile(origin ^ 1);
sendPacket(copy, priority, delay);
radio2.noteBoth();
}
void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
uint8_t *data, size_t len) {
if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
@@ -926,6 +971,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
region_map(key_store), temp_map(key_store),
_cli(board, rtc, sensors, region_map, acl, &_prefs, this),
radio2(radio2_device),
telemetry(MAX_PACKET_PAYLOAD - 4),
discover_limiter(4, 120), // max 4 every 2 minutes
anon_limiter(4, 180) // max 4 every 3 minutes
@@ -1037,7 +1083,7 @@ static const char* fleetNodeName(void* ctx) {
// retry reproduces the exact same packet (hash).
static bool fleetReplySend(void* ctx, const uint8_t* chan_secret, uint8_t chan_hash,
uint32_t ts, const char* sender_name, const char* body,
uint8_t* out_pkt_hash) {
uint8_t radio_profile, uint8_t* out_pkt_hash) {
MyMesh* m = (MyMesh*)ctx;
mesh::GroupChannel chan;
memset(&chan, 0, sizeof(chan));
@@ -1056,6 +1102,7 @@ static bool fleetReplySend(void* ctx, const uint8_t* chan_secret, uint8_t chan_h
mesh::Packet* pkt = m->createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, chan, msg,
5 + strlen((char*)&msg[5]));
if (!pkt) return false; // pool empty: FleetManager retries later
pkt->setTxProfile(radio_profile);
if (out_pkt_hash) pkt->calculatePacketHash(out_pkt_hash);
// flood is the only reply route (group texts carry no pubkey); the hook
// method applies the repeater's configured path-hash size and its default
@@ -1091,6 +1138,8 @@ void MyMesh::begin(FILESYSTEM *fs) {
_fs = fs;
// load persisted prefs
_cli.loadPrefs(_fs);
radio2.begin(_fs);
radio_driver.setProfileControl(&radio2);
#ifdef WITH_MQTT_OBSERVER
mqttObserver.begin(_fs, &self_id, _prefs.node_name, board.getManufacturerName(),
FIRMWARE_VERSION, _prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
@@ -1139,6 +1188,9 @@ void MyMesh::begin(FILESYSTEM *fs) {
powerApplyRadioProfile(_prefs);
radio_driver.setTxPower(_prefs.tx_power_dbm);
radio2.setPrimary(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
radio2.start(_prefs.rxps.enabled, _prefs.extra_sf[0] != 0);
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled");
@@ -1191,14 +1243,31 @@ bool MyMesh::formatFileSystem() {
void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
mesh::Packet *pkt = createSelfAdvert();
if (pkt) {
if (flood) {
sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
} else {
sendZeroHop(pkt, delay_millis);
if (!pkt) {
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
return;
}
// Copy before queueing the first packet: the queued packet stays valid, but
// copying first keeps the two independent from the start.
mesh::Packet* copy = NULL;
if (radio2.advertBoth()) {
copy = obtainNewPacket();
if (copy) *copy = *pkt;
}
if (flood) {
sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
if (copy) {
copy->setTxProfile(RADIO_PROFILE_SECONDARY);
sendFloodScoped(default_scope, copy, delay_millis, _prefs.path_hash_mode + 1);
}
} else {
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
sendZeroHop(pkt, delay_millis);
if (copy) {
copy->setTxProfile(RADIO_PROFILE_SECONDARY);
sendZeroHop(copy, delay_millis);
}
}
}
@@ -1466,6 +1535,23 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
const char* sub = command + 5;
while (*sub == ' ') sub++;
fleetCLI(fleet, sub, reply);
} else if (memcmp(command, "radio2", 6) == 0 && (command[6] == 0 || command[6] == ' ')) {
const char* sub = command + 6;
while (*sub == ' ') sub++;
// Preset/off changes wait for a temporary primary to revert; read-only and
// policy/advert commands are safe at any time.
bool changes_rf = (*sub != 0 && strcmp(sub, "off") == 0) || strchr(sub, ',') != NULL;
if (changes_rf && (set_radio_at || revert_radio_at)) {
strcpy(reply, "Err - tempradio active; wait for it to revert");
} else {
radio2CLI(radio2, _prefs.rxps.enabled, _prefs.extra_sf[0] != 0, sub, reply);
}
} else if ((radio2.isEnabled() || radio2.isScanning()) &&
cliStartsWith(command, "set radio.rxps ") &&
strncmp(command + 15, "off", 3) != 0) {
// radio.rxps and radio2 are mutually exclusive; turning RXPS off stays
// available so the operator can recover, and `get radio.rxps` is read-only.
strcpy(reply, "Err - radio2 is on; set radio2 off first");
} else if (memcmp(command, "clock mesh", 10) == 0 && (command[10] == 0 || command[10] == ' ')) {
// before the common CLI's bare "clock" prefix match, which would swallow it
char now[32];
@@ -1503,6 +1589,8 @@ void MyMesh::loop() {
mesh::Mesh::loop();
radio2.loop(_fs, _mgr->getOutboundTotal() == 0);
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
mesh::Packet *pkt = createSelfAdvert();
uint32_t delay_millis = 0;
@@ -1519,8 +1607,10 @@ void MyMesh::loop() {
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
set_radio_at = 0; // clear timer
radio2.pauseForPrimaryChange();
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
powerApplyRadioProfile(_prefs, pending_sf, pending_bw);
radio2.setPrimary(pending_freq, pending_bw, pending_sf, pending_cr);
MESH_DEBUG_PRINTLN("Temp radio params");
}
@@ -1528,6 +1618,8 @@ void MyMesh::loop() {
revert_radio_at = 0; // clear timer
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
powerApplyRadioProfile(_prefs);
radio2.setPrimary(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
radio2.resumeAfterPrimaryChange(_prefs.rxps.enabled, _prefs.extra_sf[0] != 0);
MESH_DEBUG_PRINTLN("Radio params restored");
}
@@ -1560,6 +1652,10 @@ void MyMesh::loop() {
last_millis = now;
}
uint32_t MyMesh::getSleepMs() {
return radio2.getSleepMs();
}
// To check if there is pending work
bool MyMesh::hasPendingWork() const {
#if defined(WITH_BRIDGE)
+25
View File
@@ -40,6 +40,7 @@
#include "BatteryGate.h"
#include "FleetManager.h"
#include "MeshClockSync.h"
#include "Radio2.h"
#ifdef WITH_MQTT_OBSERVER
#include "../mqtt_observer/MQTTObserver.h"
#endif
@@ -85,6 +86,23 @@ struct NeighbourInfo {
#define PACKET_LOG_FILE "/packet_log"
// Thin adapter over the board's radio driver: keeps the radio2 scheduler free
// of any variant/radio-family knowledge.
class Radio2DeviceImpl : public Radio2Device {
public:
bool retune(float freq, float bw, uint8_t sf, uint8_t cr,
bool abort_receive = false) override {
return radio_driver.retune(freq, bw, sf, cr, abort_receive);
}
bool hasCompletedReceive() const override { return radio_driver.hasCompletedReceive(); }
bool isReceiveInProgress() override { return radio_driver.isReceiveInProgress(); }
bool isInRecvMode() const override { return radio_driver.isInRecvMode(); }
int getNoiseFloor() const override { return radio_driver.getNoiseFloor(); }
float captureCostSymbols() const override {
return radio_driver.rxPowerSavingCaptureCostSymbols();
}
};
class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
FILESYSTEM* _fs;
uint32_t last_millis;
@@ -107,6 +125,9 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
BatteryGate battGate;
FleetManager fleet;
MeshClockSync meshClock;
Radio2DeviceImpl radio2_device;
Radio2 radio2;
bool rx_forward_allowed = true;
#ifdef WITH_MQTT_OBSERVER
MQTTObserver mqttObserver;
// supplies the observer's status-message stats from live node state
@@ -142,6 +163,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
File openAppend(const char* fname);
bool isLooped(const mesh::Packet* packet, const uint8_t max_counters[]);
void radio2QueueDuplicate(mesh::Packet* pkt, mesh::DispatcherAction action, uint8_t origin);
protected:
float getAirtimeBudgetFactor() const override {
@@ -276,6 +298,9 @@ public:
// To check if there is pending work
bool hasPendingWork() const;
// Timed sleep deadline for powersaving (0 = no radio2 scan deadline).
uint32_t getSleepMs();
bool setRxBoostedGain(bool enable) override;
#if defined(USE_LR2021)
+774
View File
@@ -0,0 +1,774 @@
// Radio2.cpp — second radio preset: config, policy, scheduler and CLI.
// Fork-owned; see RADIO2.md.
#include "Radio2.h"
#include <math.h>
#include <string.h>
#include <Utils.h>
#include "CliUtil.h"
// ---------------------------------------------------------------- helpers
static const char* actionName(uint8_t a) {
switch (a) {
case RADIO2_ACTION_SAME: return "same";
case RADIO2_ACTION_OTHER: return "other";
case RADIO2_ACTION_BOTH: return "both";
case RADIO2_ACTION_DROP: return "drop";
}
return "same";
}
static bool actionFromName(const char* s, uint8_t* out) {
for (uint8_t i = 0; i <= RADIO2_ACTION_DROP; i++) {
if (strcmp(s, actionName(i)) == 0) { *out = i; return true; }
}
return false;
}
static const char* conflictName(Radio2Conflict c) {
switch (c) {
case RADIO2_CONFLICT_RXPS: return "radio.rxps";
case RADIO2_CONFLICT_EXTRA_SF: return "extra.sf";
case RADIO2_CONFLICT_PRESET: return "preset";
case RADIO2_CONFLICT_TIMING: return "timing";
case RADIO2_CONFLICT_SWITCH: return "switch";
default: return "none";
}
}
static bool validTuple(float freq, float bw, uint8_t sf, uint8_t cr) {
if (!isfinite(freq) || !isfinite(bw)) return false;
return freq >= 150.0f && freq <= 2500.0f &&
bw >= 7.0f && bw <= 500.0f &&
sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8;
}
static bool overlaps(const Radio2Profile& a, const Radio2Profile& b) {
if (a.bw <= 0 || b.bw <= 0) return false;
// freq is MHz, bandwidth and the guard are kHz.
return fabsf(a.freq - b.freq) * 1000.0f <
(a.bw + b.bw) / 2.0f + RADIO2_OVERLAP_GUARD_KHZ;
}
static uint32_t toUs(float v) {
if (!(v > 0.0f)) return 0;
if (v > 4000000000.0f) return 0xFFFFFFFFUL;
return (uint32_t)(v + 0.5f);
}
// capture/bound from RADIO2.md §9.3, with the preamble length mirroring
// RadioLibWrapper::preambleLengthForSF().
static void profileTiming(const Radio2Profile& p, float capture_symbols,
uint32_t* capture_us, uint32_t* bound_us) {
uint32_t preamble_symbols = p.sf <= 8 ? 32 : 16;
float symbol_us = ((float)(1UL << p.sf) * 1000.0f) / p.bw;
float capture = capture_symbols * symbol_us;
float bound = ((float)preamble_symbols - capture_symbols) * symbol_us
- 2.0f * (float)RADIO2_SWITCH_US - (float)RADIO2_LOOP_MARGIN_US;
*capture_us = toUs(capture);
*bound_us = toUs(bound);
}
static uint32_t maxUs(uint32_t a, uint32_t b) { return a > b ? a : b; }
static uint32_t usToMs(uint32_t us) { return (us + 999) / 1000; }
// ---------------------------------------------------------------- lifecycle
Radio2::Radio2(Radio2Device& dev) : device(dev) {
resetToDefaults();
}
void Radio2::resetToDefaults() {
memset(&cfg, 0, sizeof(cfg));
memcpy(cfg.magic, RADIO2_CFG_MAGIC, 4);
cfg.version = RADIO2_CFG_VERSION;
cfg.enabled = 0;
cfg.policy_primary = RADIO2_ACTION_SAME;
cfg.policy_secondary = RADIO2_ACTION_SAME;
cfg.advert = RADIO2_ADVERT_PRIMARY;
memset(&primary, 0, sizeof(primary));
memset(&secondary, 0, sizeof(secondary));
active = false;
paused = false;
pending_apply = false;
pending_apply_at_ms = 0;
conflict_state = RADIO2_CONFLICT_NONE;
phase = PHASE_PRIMARY;
current = RADIO_PROFILE_PRIMARY;
phase_end_ms = 0;
last_primary_packet_ms = 0;
switch_failures = 0;
rx_primary = rx_secondary = tx_primary = tx_secondary = 0;
both = both_drop = policy_drop = aborts = 0;
switches = switch_errors = 0;
save_flag.reset();
}
void Radio2::begin(FILESYSTEM* fs) {
load(fs);
}
void Radio2::setPrimary(float freq, float bw, uint8_t sf, uint8_t cr) {
primary.freq = freq;
primary.bw = bw;
primary.sf = sf;
primary.cr = cr;
}
bool Radio2::start(bool rxps_enabled, bool extra_sf_enabled) {
active = false;
paused = false;
pending_apply = false;
if (!cfg.enabled) {
conflict_state = RADIO2_CONFLICT_NONE;
return false;
}
conflict_state = evaluate(rxps_enabled, extra_sf_enabled);
if (conflict_state != RADIO2_CONFLICT_NONE) return false;
active = true;
current = RADIO_PROFILE_PRIMARY;
phase = PHASE_PRIMARY;
switch_failures = 0;
last_primary_packet_ms = millis(); // start in active mode for the first 30 s
scheduleFromNow();
return true;
}
void Radio2::pauseForPrimaryChange() {
paused = true;
if (active && current != RADIO_PROFILE_PRIMARY) {
switchTo(RADIO_PROFILE_PRIMARY, false); // loop() retries if busy
}
}
void Radio2::resumeAfterPrimaryChange(bool rxps_enabled, bool extra_sf_enabled) {
paused = false;
if (!cfg.enabled) {
active = false;
return;
}
conflict_state = evaluate(rxps_enabled, extra_sf_enabled);
if (conflict_state != RADIO2_CONFLICT_NONE) {
active = false;
return;
}
if (!active) {
active = true;
current = RADIO_PROFILE_PRIMARY;
phase = PHASE_PRIMARY;
last_primary_packet_ms = millis();
}
switch_failures = 0;
scheduleFromNow();
}
// ---------------------------------------------------------------- policy
static bool radio2Crossable(const mesh::Packet* pkt) {
switch (pkt->getPayloadType()) {
case PAYLOAD_TYPE_ADVERT:
return true;
case PAYLOAD_TYPE_GRP_TXT:
case PAYLOAD_TYPE_GRP_DATA:
return pkt->isRouteFlood();
default:
return false;
}
}
Radio2Action Radio2::actionFor(uint8_t origin, const mesh::Packet* pkt) const {
Radio2Action configured = origin == RADIO_PROFILE_SECONDARY
? (Radio2Action)cfg.policy_secondary : (Radio2Action)cfg.policy_primary;
if (!radio2Crossable(pkt) && configured != RADIO2_ACTION_DROP) {
return RADIO2_ACTION_SAME;
}
return configured;
}
uint8_t Radio2::targetFor(Radio2Action action, uint8_t origin) const {
switch (action) {
case RADIO2_ACTION_OTHER: return origin ^ 1;
case RADIO2_ACTION_SAME:
case RADIO2_ACTION_BOTH:
case RADIO2_ACTION_DROP:
default: return origin;
}
}
uint8_t Radio2::replyProfile(uint8_t origin) const {
return origin == RADIO_PROFILE_SECONDARY ? RADIO_PROFILE_SECONDARY
: RADIO_PROFILE_PRIMARY;
}
// ---------------------------------------------------------------- timing
bool Radio2::timing(Radio2Timing* out) const {
if (out == NULL) return false;
memset(out, 0, sizeof(*out));
if (!validTuple(primary.freq, primary.bw, primary.sf, primary.cr)) return false;
if (!validTuple(secondary.freq, secondary.bw, secondary.sf, secondary.cr)) return false;
float capture_symbols = device.captureCostSymbols();
profileTiming(primary, capture_symbols, &out->primary_capture_us, &out->primary_bound_us);
profileTiming(secondary, capture_symbols, &out->secondary_capture_us, &out->secondary_bound_us);
out->usable = out->secondary_capture_us <= out->primary_bound_us &&
out->primary_capture_us <= out->secondary_bound_us;
out->active_mode = usesActiveMode();
out->primary_visit_us = primaryVisitUs(*out);
out->secondary_visit_us = secondaryVisitUs(*out);
out->secondary_lossy = out->active_mode &&
out->primary_visit_us > out->secondary_bound_us;
return out->usable;
}
bool Radio2::usesActiveMode() const {
return (uint32_t)(millis() - last_primary_packet_ms) < RADIO2_ACTIVE_HOLD_MS;
}
uint32_t Radio2::primaryVisitUs(const Radio2Timing& t) const {
if (!t.active_mode) return maxUs(t.primary_capture_us, RADIO2_MIN_VISIT_US);
uint32_t sv = maxUs(t.secondary_capture_us, RADIO2_MIN_VISIT_US);
return maxUs(t.primary_capture_us, RADIO2_ACTIVE_SECONDARY_DIV * sv);
}
uint32_t Radio2::secondaryVisitUs(const Radio2Timing& t) const {
if (!t.active_mode) return t.primary_bound_us; // the maximum safe share
return maxUs(t.secondary_capture_us, RADIO2_MIN_VISIT_US);
}
// ---------------------------------------------------------------- scheduler
void Radio2::scheduleFromNow() {
Radio2Timing t;
if (!timing(&t)) return;
phase = current == RADIO_PROFILE_SECONDARY ? PHASE_SECONDARY : PHASE_PRIMARY;
phase_end_ms = millis() + usToMs(current == RADIO_PROFILE_SECONDARY
? secondaryVisitUs(t) : primaryVisitUs(t));
}
bool Radio2::switchTo(uint8_t profile, bool abort_receive, bool force) {
if (profile == current && !force) return true;
if (profile == RADIO_PROFILE_SECONDARY && !cfg.enabled) return false;
// A complete packet is never abandoned: let core read it first.
if (device.hasCompletedReceive()) return false;
// A receive in progress is only abandoned when the caller explicitly asks.
if (!abort_receive && device.isReceiveInProgress()) return false;
const Radio2Profile& p = profile == RADIO_PROFILE_PRIMARY ? primary : secondary;
if (!device.retune(p.freq, p.bw, p.sf, p.cr, abort_receive)) {
switch_failures++;
switch_errors++;
if (switch_failures >= RADIO2_MAX_SWITCH_FAILURES) {
active = false; // stay primary; a config change re-enables attempts
conflict_state = RADIO2_CONFLICT_SWITCH;
}
return false;
}
switch_failures = 0;
conflict_state = RADIO2_CONFLICT_NONE;
current = profile;
switches++;
return true;
}
bool Radio2::selectTxProfile(uint8_t profile) {
// Off (or disabled after failures): only the primary radio is valid. A
// secondary-target packet falls back to it; while a retune back is pending,
// wait so nothing is ever transmitted on the wrong preset.
if (!active) return current == RADIO_PROFILE_PRIMARY;
if (current == profile) return true;
if (device.hasCompletedReceive() || device.isReceiveInProgress()) return false;
if (!switchTo(profile, false)) return current == profile; // busy or failed: retry
scheduleFromNow();
return true;
}
void Radio2::loop(FILESYSTEM* fs, bool quiet) {
if (save_flag.due()) save(fs);
uint32_t now = millis();
if (pending_apply && quiet && (int32_t)(now - pending_apply_at_ms) >= 0) {
if (applyPending()) pending_apply = false;
}
if (paused) {
if (current != RADIO_PROFILE_PRIMARY) switchTo(RADIO_PROFILE_PRIMARY, false);
return;
}
if (!active) {
// A disabled scanner still has to get the radio back to primary, unless a
// deferred apply is deliberately waiting for the command reply to go out.
if (!pending_apply && current != RADIO_PROFILE_PRIMARY) {
switchTo(RADIO_PROFILE_PRIMARY, false);
}
return;
}
if (!device.isInRecvMode()) return; // TX (or idle): never abort it
if (device.hasCompletedReceive()) return; // let core read the packet
if ((int32_t)(now - phase_end_ms) < 0) return;
Radio2Timing t;
if (!timing(&t)) {
active = false;
conflict_state = RADIO2_CONFLICT_TIMING;
return;
}
if (phase == PHASE_PRIMARY) {
if (device.isReceiveInProgress()) { // primary wins
phase_end_ms = now + 1;
return;
}
if (switchTo(RADIO_PROFILE_SECONDARY, false)) {
phase = PHASE_SECONDARY;
phase_end_ms = now + usToMs(secondaryVisitUs(t));
} else if (active) {
phase_end_ms = now + RADIO2_SWITCH_RETRY_MS;
}
return;
}
// PHASE_SECONDARY
if (device.isReceiveInProgress()) {
if (t.active_mode) {
// Primary is busy: abandon the secondary receive rather than miss it.
if (switchTo(RADIO_PROFILE_PRIMARY, true)) {
noteAbort();
phase = PHASE_PRIMARY;
phase_end_ms = now + usToMs(primaryVisitUs(t));
} else if (active) {
phase_end_ms = now + RADIO2_SWITCH_RETRY_MS;
}
} else {
// Primary is idle: let the long secondary packet finish.
phase_end_ms = now + RADIO2_HOLD_POLL_MS;
}
return;
}
if (switchTo(RADIO_PROFILE_PRIMARY, false)) {
phase = PHASE_PRIMARY;
phase_end_ms = now + usToMs(primaryVisitUs(t));
} else if (active) {
phase_end_ms = now + RADIO2_SWITCH_RETRY_MS;
}
}
bool Radio2::applyPending() {
if (!cfg.enabled) {
active = false;
conflict_state = RADIO2_CONFLICT_NONE;
return true; // the !active branch retunes to primary when quiet
}
Radio2Timing t;
if (!timing(&t)) {
conflict_state = RADIO2_CONFLICT_TIMING;
active = false;
return true;
}
conflict_state = RADIO2_CONFLICT_NONE;
bool was_active = active;
active = true;
switch_failures = 0;
if (current == RADIO_PROFILE_SECONDARY &&
!switchTo(RADIO_PROFILE_SECONDARY, false, true)) {
active = was_active;
return false; // busy: retry on a later loop pass
}
last_primary_packet_ms = millis();
scheduleFromNow();
return true;
}
uint32_t Radio2::getSleepMs() {
if (!active || paused || pending_apply) return 0;
if (!device.isInRecvMode() || device.hasCompletedReceive() ||
device.isReceiveInProgress()) {
return 1; // wake soon; never sleep through a packet
}
int32_t delta = (int32_t)(phase_end_ms - millis());
if (delta <= 0) return 1;
return (uint32_t)delta < RADIO2_SLEEP_MAX_MS ? (uint32_t)delta : RADIO2_SLEEP_MAX_MS;
}
// ---------------------------------------------------------------- counters
void Radio2::notePrimaryPacket() {
last_primary_packet_ms = millis();
}
void Radio2::noteRx(uint8_t profile) {
if (profile == RADIO_PROFILE_SECONDARY) rx_secondary++;
else rx_primary++;
}
void Radio2::noteTx(uint8_t profile) {
if (profile == RADIO_PROFILE_SECONDARY) tx_secondary++;
else tx_primary++;
}
// ---------------------------------------------------------------- config
Radio2Conflict Radio2::evaluate(bool rxps_enabled, bool extra_sf_enabled) const {
if (rxps_enabled) return RADIO2_CONFLICT_RXPS;
if (extra_sf_enabled) return RADIO2_CONFLICT_EXTRA_SF;
if (!validTuple(secondary.freq, secondary.bw, secondary.sf, secondary.cr)) {
return RADIO2_CONFLICT_PRESET;
}
if (overlaps(primary, secondary)) return RADIO2_CONFLICT_PRESET;
Radio2Timing t;
return timing(&t) ? RADIO2_CONFLICT_NONE : RADIO2_CONFLICT_TIMING;
}
Radio2SetResult Radio2::setPreset(float freq, float bw, uint8_t sf, uint8_t cr) {
Radio2Profile candidate = { freq, bw, sf, cr };
if (!validTuple(freq, bw, sf, cr)) return RADIO2_SET_BAD_PRESET;
if (overlaps(primary, candidate)) return RADIO2_SET_OVERLAP;
// Validate the pair off to the side: a refused preset leaves the live one
// byte-for-byte unchanged.
Radio2Profile saved = secondary;
secondary = candidate;
Radio2Timing t;
bool usable = timing(&t);
secondary = saved;
if (!usable) return RADIO2_SET_UNSCANNABLE;
secondary = candidate;
cfg.enabled = 1;
cfg.freq_mhz = freq;
cfg.bw_khz = bw;
cfg.sf = sf;
cfg.cr = cr;
switch_failures = 0;
pending_apply = true;
pending_apply_at_ms = millis() + RADIO2_APPLY_DELAY_MS;
markDirty();
return RADIO2_SET_OK;
}
void Radio2::setEnabled(bool on) {
cfg.enabled = on ? 1 : 0;
switch_failures = 0;
pending_apply = true;
pending_apply_at_ms = millis() + RADIO2_APPLY_DELAY_MS;
markDirty();
}
void Radio2::setPolicy(uint8_t primary, uint8_t secondary) {
uint8_t pa = primary <= RADIO2_ACTION_DROP ? primary : RADIO2_ACTION_SAME;
uint8_t sa = secondary <= RADIO2_ACTION_DROP ? secondary : RADIO2_ACTION_SAME;
if (cfg.policy_primary == pa && cfg.policy_secondary == sa) return;
cfg.policy_primary = pa;
cfg.policy_secondary = sa;
markDirty();
}
void Radio2::setAdvert(uint8_t advert) {
uint8_t a = advert == RADIO2_ADVERT_BOTH ? RADIO2_ADVERT_BOTH : RADIO2_ADVERT_PRIMARY;
if (cfg.advert == a) return;
cfg.advert = a;
markDirty();
}
// ---------------------------------------------------------------- persistence
static bool radio2ValidateRecord(const Radio2CfgRecord& rec) {
if (memcmp(rec.magic, RADIO2_CFG_MAGIC, 4) != 0) return false;
if (rec.version != RADIO2_CFG_VERSION) return false;
if (rec.enabled > 1) return false;
if (rec.policy_primary > RADIO2_ACTION_DROP ||
rec.policy_secondary > RADIO2_ACTION_DROP) return false;
if (rec.advert > RADIO2_ADVERT_BOTH) return false;
bool zero = rec.freq_mhz == 0.0f && rec.bw_khz == 0.0f && rec.sf == 0 && rec.cr == 0;
if (rec.enabled) {
return validTuple(rec.freq_mhz, rec.bw_khz, rec.sf, rec.cr);
}
return zero || validTuple(rec.freq_mhz, rec.bw_khz, rec.sf, rec.cr);
}
static bool radio2WriteFile(File& f, void* ctx) {
Radio2& r = *(Radio2*)ctx;
Radio2CfgRecord rec;
memset(&rec, 0, sizeof(rec));
memcpy(rec.magic, RADIO2_CFG_MAGIC, 4);
rec.version = RADIO2_CFG_VERSION;
rec.enabled = r.isEnabled() ? 1 : 0;
rec.policy_primary = r.getPolicyPrimary();
rec.policy_secondary = r.getPolicySecondary();
rec.advert = r.getAdvert();
const Radio2Profile& p = r.getSecondaryProfile();
rec.freq_mhz = p.freq;
rec.bw_khz = p.bw;
rec.sf = p.sf;
rec.cr = p.cr;
uint8_t buf[RADIO2_CFG_RECORD_BYTES];
memcpy(buf, &rec, RADIO2_CFG_PAYLOAD_BYTES);
uint16_t crc = crc16_ccitt(buf, RADIO2_CFG_PAYLOAD_BYTES);
memcpy(&buf[RADIO2_CFG_PAYLOAD_BYTES], &crc, 2);
return f.write(buf, RADIO2_CFG_RECORD_BYTES) == RADIO2_CFG_RECORD_BYTES;
}
static bool radio2ValidateFile(File& f, void* ctx) {
(void)ctx;
uint8_t buf[RADIO2_CFG_RECORD_BYTES];
if (f.read(buf, RADIO2_CFG_RECORD_BYTES) != RADIO2_CFG_RECORD_BYTES) return false;
uint16_t stored, computed;
memcpy(&stored, &buf[RADIO2_CFG_PAYLOAD_BYTES], 2);
computed = crc16_ccitt(buf, RADIO2_CFG_PAYLOAD_BYTES);
if (stored != computed) return false;
Radio2CfgRecord rec;
memcpy(&rec, buf, sizeof(rec));
return radio2ValidateRecord(rec);
}
void Radio2::save(FILESYSTEM* fs) {
bool ok = saveStaged(fs, RADIO2_CFG_FILE, radio2WriteFile, this,
radio2ValidateFile, NULL, radio2ValidateFile, NULL);
if (ok) save_flag.clear();
else save_flag.retryLater();
}
void Radio2::load(FILESYSTEM* fs) {
resetToDefaults();
save_flag.reset();
char path[64];
PersistLoadSource src = chooseConfigToLoad(fs, RADIO2_CFG_FILE, radio2ValidateFile, NULL,
path, sizeof(path));
if (src == PERSIST_LOAD_NONE) return;
File file = fsOpenRead(fs, path);
if (!file) return;
uint8_t buf[RADIO2_CFG_RECORD_BYTES];
if (file.read(buf, RADIO2_CFG_RECORD_BYTES) != RADIO2_CFG_RECORD_BYTES) {
file.close();
return;
}
file.close();
uint16_t stored, computed;
memcpy(&stored, &buf[RADIO2_CFG_PAYLOAD_BYTES], 2);
computed = crc16_ccitt(buf, RADIO2_CFG_PAYLOAD_BYTES);
if (stored != computed) return;
Radio2CfgRecord rec;
memcpy(&rec, buf, sizeof(rec));
if (!radio2ValidateRecord(rec)) return;
cfg = rec;
secondary.freq = rec.freq_mhz;
secondary.bw = rec.bw_khz;
secondary.sf = rec.sf;
secondary.cr = rec.cr;
if (src == PERSIST_LOAD_RECOVERED) markDirty();
}
// ---------------------------------------------------------------- CLI
#define RADIO2_USAGE \
"Err - usage: status|timing|<freq>,<bw>,<sf>,<cr>|off|policy [a] [b]|advert primary|both"
static void radio2Status(Radio2& r, char* reply) {
if (!r.isEnabled()) {
snprintf(reply, CLI_REPLY_MAX, "off");
return;
}
if (!r.isScanning()) {
if (r.hasPendingApply()) {
snprintf(reply, CLI_REPLY_MAX, "on; apply=pending; at=%s",
r.currentProfile() == RADIO_PROFILE_SECONDARY ? "radio2" : "primary");
} else if (r.isPaused()) {
snprintf(reply, CLI_REPLY_MAX, "off; paused");
} else {
snprintf(reply, CLI_REPLY_MAX, "off; conflict=%s", conflictName(r.conflict()));
}
return;
}
Radio2Timing t;
bool usable = r.timing(&t);
unsigned pct = 50;
if (usable) {
uint32_t total = t.primary_visit_us + t.secondary_visit_us;
if (total > 0) pct = (unsigned)((uint64_t)t.primary_visit_us * 100 / total);
}
char line[256];
CliBuf buf(line, sizeof(line));
buf.add("on");
if (r.hasPendingApply()) buf.add("; apply=pending");
buf.add("; at=%s", r.currentProfile() == RADIO_PROFILE_SECONDARY ? "radio2" : "primary");
buf.add("; mode=%s", t.active_mode ? "active" : "idle");
if (t.secondary_lossy) buf.add("; lossy");
buf.add("; split=%u/%u", pct, 100 - pct);
buf.add("; nf=%d", r.getNoiseFloor());
buf.add("; sw=%lu; swf=%lu", (unsigned long)r.getSwitchCount(),
(unsigned long)r.getSwitchErrors());
buf.add("; rx=%lu/%lu", (unsigned long)r.getRxPrimary(),
(unsigned long)r.getRxSecondary());
buf.add("; tx=%lu/%lu", (unsigned long)r.getTxPrimary(),
(unsigned long)r.getTxSecondary());
buf.add("; both=%lu; bdrop=%lu; drop=%lu; abrt=%lu", (unsigned long)r.getBoth(),
(unsigned long)r.getBothDrop(), (unsigned long)r.getPolicyDrop(),
(unsigned long)r.getAborts());
cliCutReply(reply, CLI_REPLY_MAX, line);
}
static void radio2TimingReply(Radio2& r, char* reply) {
Radio2Timing t;
if (!r.timing(&t)) {
snprintf(reply, CLI_REPLY_MAX,
"unusable: secondary capture %lums > primary-safe %lums",
(unsigned long)(t.secondary_capture_us / 1000),
(unsigned long)(t.primary_bound_us / 1000));
return;
}
uint32_t total = t.primary_visit_us + t.secondary_visit_us;
unsigned pct = total > 0
? (unsigned)((uint64_t)t.primary_visit_us * 100 / total) : 50;
snprintf(reply, CLI_REPLY_MAX,
"primary=%lums; secondary=%lums; split=%u/%u; switch=%lums; mode=%s",
(unsigned long)(t.primary_visit_us / 1000),
(unsigned long)(t.secondary_visit_us / 1000), pct, 100 - pct,
(unsigned long)(RADIO2_SWITCH_US / 1000),
t.active_mode ? "active" : "idle");
}
static bool parseFloatToken(const char* tok, float* out) {
if (tok == NULL || tok[0] == 0) return false;
errno = 0;
char* end;
float v = strtof(tok, &end);
if (end == tok || *end != 0 || errno == ERANGE || !isfinite(v)) return false;
*out = v;
return true;
}
static void radio2SetPreset(Radio2& r, const char* tuple, bool rxps_enabled,
bool extra_sf_enabled, char* reply) {
char scratch[48];
if (!cliCopyCommand(scratch, sizeof(scratch), tuple)) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 preset must be <freq>,<bw>,<sf>,<cr>");
return;
}
const char* parts[4];
int n = mesh::Utils::parseTextParts(scratch, parts, 4);
if (n != 4) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 preset must be <freq>,<bw>,<sf>,<cr>");
return;
}
float freq, bw;
long sf, cr;
if (!parseFloatToken(parts[0], &freq) || !parseFloatToken(parts[1], &bw) ||
!parseIntRange(parts[2], 5, 12, &sf) || !parseIntRange(parts[3], 5, 8, &cr)) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 preset must be <freq>,<bw>,<sf>,<cr>");
return;
}
if (rxps_enabled) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio.rxps is on; set radio.rxps off first");
return;
}
if (extra_sf_enabled) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 conflicts with extra.sf; clear extra SF first");
return;
}
switch (r.setPreset(freq, bw, (uint8_t)sf, (uint8_t)cr)) {
case RADIO2_SET_OK: {
const Radio2Profile& p = r.getSecondaryProfile();
snprintf(reply, CLI_REPLY_MAX, "OK - radio2 %g,%g,%u,%u",
p.freq, p.bw, (unsigned)p.sf, (unsigned)p.cr);
break;
}
case RADIO2_SET_OVERLAP:
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 overlaps radio");
break;
case RADIO2_SET_UNSCANNABLE:
snprintf(reply, CLI_REPLY_MAX,
"Err - radio2 preset cannot be scanned without degrading radio");
break;
default:
snprintf(reply, CLI_REPLY_MAX,
"Err - radio2 preset must be <freq>,<bw>,<sf>,<cr>");
break;
}
}
void radio2CLI(Radio2& r, bool rxps_enabled, bool extra_sf_enabled,
const char* command, char* reply) {
char scratch[128];
if (!cliPrepare(command, scratch, sizeof(scratch), reply)) return;
char* p = scratch;
char* sub = nextToken(&p);
if (sub == NULL || strcmp(sub, "status") == 0) {
if (!cliNoExtra(p, reply, RADIO2_USAGE)) return;
radio2Status(r, reply);
return;
}
if (strcmp(sub, "timing") == 0) {
if (!cliNoExtra(p, reply, RADIO2_USAGE)) return;
radio2TimingReply(r, reply);
return;
}
if (strcmp(sub, "off") == 0) {
if (!cliNoExtra(p, reply, RADIO2_USAGE)) return;
r.setEnabled(false);
snprintf(reply, CLI_REPLY_MAX, "OK - radio2 off");
return;
}
if (strcmp(sub, "policy") == 0) {
char* a = nextToken(&p);
if (a == NULL) {
snprintf(reply, CLI_REPLY_MAX, "> primary=%s,secondary=%s",
actionName(r.getPolicyPrimary()), actionName(r.getPolicySecondary()));
return;
}
char* b = nextToken(&p);
uint8_t pa, sa;
if (!actionFromName(a, &pa) || (b != NULL && !actionFromName(b, &sa))) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 policy must be same|other|both|drop");
return;
}
if (b == NULL) sa = pa;
if (!cliNoExtra(p, reply, RADIO2_USAGE)) return;
r.setPolicy(pa, sa);
snprintf(reply, CLI_REPLY_MAX, "OK - radio2 policy primary=%s,secondary=%s",
actionName(pa), actionName(sa));
return;
}
if (strcmp(sub, "advert") == 0) {
char* a = nextToken(&p);
if (a == NULL) {
snprintf(reply, CLI_REPLY_MAX, "> %s",
r.getAdvert() == RADIO2_ADVERT_BOTH ? "both" : "primary");
return;
}
if (strcmp(a, "primary") != 0 && strcmp(a, "both") != 0) {
snprintf(reply, CLI_REPLY_MAX, "Err - radio2 advert must be primary|both");
return;
}
if (!cliNoExtra(p, reply, RADIO2_USAGE)) return;
r.setAdvert(strcmp(a, "both") == 0 ? RADIO2_ADVERT_BOTH : RADIO2_ADVERT_PRIMARY);
snprintf(reply, CLI_REPLY_MAX, "OK - radio2 advert %s", a);
return;
}
// Anything else is a preset tuple. nextToken() only split on spaces, so the
// token still holds the whole comma list.
radio2SetPreset(r, sub, rxps_enabled, extra_sf_enabled, reply);
}
+195
View File
@@ -0,0 +1,195 @@
// Radio2.h — the repeater's second LoRa preset: config, policy, scheduler and
// CLI. Fork-owned; see RADIO2.md for the user-facing model.
//
// The feature is host-testable: Radio2Device is the only radio surface it
// touches, so the policy and scheduler run against a fake in the native tests.
#ifndef _RADIO2_H
#define _RADIO2_H
#include <Arduino.h>
#include <stdint.h>
#include <Packet.h>
#include <helpers/radiolib/RadioProfileControl.h>
#include "PersistUtil.h"
#include "Radio2Config.h"
enum Radio2Action : uint8_t {
RADIO2_ACTION_SAME = 0,
RADIO2_ACTION_OTHER = 1,
RADIO2_ACTION_BOTH = 2,
RADIO2_ACTION_DROP = 3,
};
enum Radio2Advert : uint8_t {
RADIO2_ADVERT_PRIMARY = 0,
RADIO2_ADVERT_BOTH = 1,
};
enum Radio2Conflict : uint8_t {
RADIO2_CONFLICT_NONE = 0,
RADIO2_CONFLICT_RXPS,
RADIO2_CONFLICT_EXTRA_SF,
RADIO2_CONFLICT_PRESET, // overlap / bad tuple
RADIO2_CONFLICT_TIMING, // unsafe to scan this pair
RADIO2_CONFLICT_SWITCH, // too many retune failures
};
enum Radio2SetResult : uint8_t {
RADIO2_SET_OK = 0,
RADIO2_SET_BAD_PRESET,
RADIO2_SET_OVERLAP,
RADIO2_SET_UNSCANNABLE,
};
struct Radio2Profile {
float freq;
float bw;
uint8_t sf;
uint8_t cr;
};
struct Radio2Timing {
bool usable;
bool active_mode;
bool secondary_lossy;
uint32_t primary_capture_us;
uint32_t secondary_capture_us;
uint32_t primary_bound_us;
uint32_t secondary_bound_us;
uint32_t primary_visit_us;
uint32_t secondary_visit_us;
};
// The radio surface Radio2 needs. MyMesh supplies a thin adapter over
// radio_driver; the native tests supply a fake.
class Radio2Device {
public:
virtual ~Radio2Device() = default;
virtual bool retune(float freq, float bw, uint8_t sf, uint8_t cr,
bool abort_receive = false) = 0;
virtual bool hasCompletedReceive() const = 0;
virtual bool isReceiveInProgress() = 0;
virtual bool isInRecvMode() const = 0;
virtual int getNoiseFloor() const = 0;
virtual float captureCostSymbols() const = 0;
};
class Radio2 : public RadioProfileControl {
public:
explicit Radio2(Radio2Device& device);
// RadioProfileControl: the dispatcher asks before every transmission.
bool selectTxProfile(uint8_t profile) override;
void begin(FILESYSTEM* fs); // load persisted config
void loop(FILESYSTEM* fs, bool quiet); // scheduler + lazy save
// Evaluate the current config against the environment and start (or not).
// Returns true when scanning is active.
bool start(bool rxps_enabled, bool extra_sf_enabled);
void setPrimary(float freq, float bw, uint8_t sf, uint8_t cr);
// tempradio: stop scanning while a temporary primary is active, revalidate
// once it reverts.
void pauseForPrimaryChange();
void resumeAfterPrimaryChange(bool rxps_enabled, bool extra_sf_enabled);
bool isEnabled() const { return cfg.enabled != 0; }
bool isScanning() const { return active; }
bool isPaused() const { return paused; }
bool hasPendingApply() const { return pending_apply; }
uint8_t currentProfile() const { return current; }
Radio2Conflict conflict() const { return conflict_state; }
// policy
Radio2Action actionFor(uint8_t origin, const mesh::Packet* pkt) const;
uint8_t targetFor(Radio2Action action, uint8_t origin) const;
uint8_t replyProfile(uint8_t origin) const;
bool advertBoth() const { return cfg.advert == RADIO2_ADVERT_BOTH && active; }
uint8_t getPolicyPrimary() const { return cfg.policy_primary; }
uint8_t getPolicySecondary() const { return cfg.policy_secondary; }
uint8_t getAdvert() const { return cfg.advert; }
// CLI mutations. The preset/enable changes persist immediately but defer
// the RF apply so a remote admin's reply goes out on the old config.
Radio2SetResult setPreset(float freq, float bw, uint8_t sf, uint8_t cr);
void setEnabled(bool on);
void setPolicy(uint8_t primary, uint8_t secondary);
void setAdvert(uint8_t advert);
const Radio2Profile& getSecondaryProfile() const { return secondary; }
// timing/status
bool timing(Radio2Timing* out) const;
uint32_t getSleepMs();
// counters
void notePrimaryPacket();
void noteRx(uint8_t profile);
void noteTx(uint8_t profile);
void noteBoth() { both++; }
void noteBothDrop() { both_drop++; }
void notePolicyDrop() { policy_drop++; }
void noteAbort() { aborts++; }
// status read-outs
int getNoiseFloor() const { return device.getNoiseFloor(); }
uint32_t getSwitchCount() const { return switches; }
uint32_t getSwitchErrors() const { return switch_errors; }
uint32_t getRxPrimary() const { return rx_primary; }
uint32_t getRxSecondary() const { return rx_secondary; }
uint32_t getTxPrimary() const { return tx_primary; }
uint32_t getTxSecondary() const { return tx_secondary; }
uint32_t getBoth() const { return both; }
uint32_t getBothDrop() const { return both_drop; }
uint32_t getPolicyDrop() const { return policy_drop; }
uint32_t getAborts() const { return aborts; }
// persistence
void save(FILESYSTEM* fs);
void load(FILESYSTEM* fs);
void markDirty() { save_flag.markDirty(); }
private:
enum Phase : uint8_t { PHASE_PRIMARY, PHASE_SECONDARY };
Radio2Device& device;
Radio2CfgRecord cfg;
Radio2Profile primary;
Radio2Profile secondary;
bool active = false;
bool paused = false;
bool pending_apply = false;
uint32_t pending_apply_at_ms = 0;
Radio2Conflict conflict_state = RADIO2_CONFLICT_NONE;
Phase phase = PHASE_PRIMARY;
uint8_t current = RADIO_PROFILE_PRIMARY;
uint32_t phase_end_ms = 0;
uint32_t last_primary_packet_ms = 0;
uint8_t switch_failures = 0;
uint32_t rx_primary = 0, rx_secondary = 0;
uint32_t tx_primary = 0, tx_secondary = 0;
uint32_t both = 0, both_drop = 0, policy_drop = 0, aborts = 0;
uint32_t switches = 0, switch_errors = 0;
LazySave save_flag;
void resetToDefaults();
bool applyPending();
bool switchTo(uint8_t profile, bool abort_receive, bool force = false);
bool usesActiveMode() const;
uint32_t primaryVisitUs(const Radio2Timing& t) const;
uint32_t secondaryVisitUs(const Radio2Timing& t) const;
void scheduleFromNow();
Radio2Conflict evaluate(bool rxps_enabled, bool extra_sf_enabled) const;
};
// `command` is everything after the "radio2" verb.
void radio2CLI(Radio2& radio2, bool rxps_enabled, bool extra_sf_enabled,
const char* command, char* reply);
#endif // _RADIO2_H
+46
View File
@@ -0,0 +1,46 @@
// Radio2Config.h — constants for the repeater's second radio preset.
// Fork-owned; see RADIO2.md for the user-facing model.
#ifndef _RADIO2_CONFIG_H
#define _RADIO2_CONFIG_H
#include <stdint.h>
#define RADIO2_CFG_FILE "/radio2_cfg"
#define RADIO2_CFG_VERSION 1
#define RADIO2_CFG_MAGIC "R2CF"
// The persisted payload is 20 B; the file appends a 2 B CRC-16.
#define RADIO2_CFG_PAYLOAD_BYTES 20
#define RADIO2_CFG_RECORD_BYTES 22
struct Radio2CfgRecord {
char magic[4]; // "R2CF"
uint8_t version; // 1
uint8_t enabled; // 0/1
uint8_t policy_primary; // Radio2Action
uint8_t policy_secondary; // Radio2Action
uint8_t advert; // Radio2Advert
uint8_t sf;
uint8_t cr;
float freq_mhz;
float bw_khz;
};
static_assert(sizeof(Radio2CfgRecord) == RADIO2_CFG_PAYLOAD_BYTES,
"Radio2CfgRecord payload is frozen at 20 B");
// Scheduler timing. RADIO2_SWITCH_US is a conservative default; measure on
// hardware before tightening it.
#define RADIO2_ACTIVE_HOLD_MS 30000UL
#define RADIO2_SWITCH_US 3000UL
#define RADIO2_LOOP_MARGIN_US 2000UL
#define RADIO2_MIN_VISIT_US 5000UL
#define RADIO2_ACTIVE_SECONDARY_DIV 4U
#define RADIO2_HOLD_POLL_MS 5UL
#define RADIO2_SLEEP_MAX_MS 1000UL
#define RADIO2_APPLY_DELAY_MS 2000UL
#define RADIO2_MAX_SWITCH_FAILURES 10U
#define RADIO2_SWITCH_RETRY_MS 1000UL
#define RADIO2_OVERLAP_GUARD_KHZ 6.0f
#endif // _RADIO2_CONFIG_H
+5 -2
View File
@@ -206,11 +206,14 @@ void loop() {
external_watchdog.loop();
#endif
if (the_mesh.getNodePrefs()->powersaving_enabled && !the_mesh.hasPendingWork()) {
uint32_t sleep_ms = the_mesh.getSleepMs();
#if defined(NRF52_PLATFORM)
board.sleep(0); // nrf ignores seconds param, sleeps whenever possible
if (sleep_ms) board.sleepMs(sleep_ms);
else board.sleep(0); // nrf ignores seconds param, sleeps whenever possible
#else
if (the_mesh.millisHasNowPassed(POWERSAVING_FIRSTSLEEP_SECS * 1000)) { // To check if it is time to sleep
board.sleep(30); // Sleep. Wake up after a while or when receiving a LoRa packet
if (sleep_ms) board.sleepMs(sleep_ms);
else board.sleep(30); // Sleep. Wake up after a while or when receiving a LoRa packet
}
#endif
}
+30
View File
@@ -178,6 +178,7 @@ test_ignore =
test_mesh_clock
test_rx_power_saving
test_mqtt_observer
test_radio2
build_src_filter =
-<*>
+<../src/Utils.cpp>
@@ -306,6 +307,29 @@ build_src_filter =
lib_deps =
google/googletest @ 1.17.0
; Native tests for the second radio preset (fork-owned
; examples/simple_repeater/Radio2*). Pure policy/timing/scheduler against a
; fake Radio2Device, plus the core profile byte and outbound peek.
[env:native_radio2]
platform = native
test_framework = googletest
build_flags = -std=c++17
-I src
-I test/mocks
-I examples/simple_repeater
-include test/test_packet_filter/NativeShim.h
test_build_src = yes
test_filter = test_radio2
build_src_filter =
-<*>
+<../src/Utils.cpp>
+<../src/Packet.cpp>
+<../src/Dispatcher.cpp>
+<../src/helpers/StaticPoolPacketManager.cpp>
+<../examples/simple_repeater/Radio2.cpp>
lib_deps =
google/googletest @ 1.17.0
; Native tests for MQTT observer formatting, config, and live-only queue policy.
; Native tests for the RX power saving guard math and `radio.rxps` CLI
; (fork-owned src/helpers/radiolib/RXPowerSaving*). Pure policy: no Arduino,
@@ -388,3 +412,9 @@ extends = env:native_mesh_clock
build_flags =
${env:native_mesh_clock.build_flags}
-g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer
[env:native_radio2_san]
extends = env:native_radio2
build_flags =
${env:native_radio2.build_flags}
-g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer
+10 -3
View File
@@ -273,8 +273,13 @@ void Dispatcher::processRecvPacket(Packet* pkt) {
}
void Dispatcher::checkSend() {
if (_mgr->getOutboundCount(_ms->getMillis()) == 0) return;
const uint32_t now = _ms->getMillis();
if (_mgr->getOutboundCount(now) == 0) return;
Packet* next = _mgr->peekNextOutbound(now);
if (!next) return;
if (!_radio->selectTxProfile(next->getTxProfile())) return;
updateTxBudget();
uint32_t est_airtime = _radio->getEstAirtimeFor(MAX_TRANS_UNIT);
@@ -304,7 +309,7 @@ void Dispatcher::checkSend() {
}
cad_busy_start = 0; // reset busy state
outbound = _mgr->getNextOutbound(_ms->getMillis());
outbound = _mgr->getNextOutbound(now);
if (outbound) {
int len = 0;
uint8_t raw[MAX_TRANS_UNIT];
@@ -360,6 +365,8 @@ Packet* Dispatcher::obtainNewPacket() {
} else {
pkt->payload_len = pkt->path_len = 0;
pkt->_snr = 0;
pkt->setTxProfile(_default_tx_profile);
pkt->setRxProfile(RADIO_PROFILE_UNKNOWN);
}
return pkt;
}
+12
View File
@@ -38,6 +38,13 @@ public:
virtual float packetScore(float snr, int packet_len) = 0;
/**
* \brief select the profile the next transmission will use.
* \returns false when it is not safe to retune yet; try again next loop.
* Default: no profile support.
*/
virtual bool selectTxProfile(uint8_t profile) { (void)profile; return true; }
/**
* \brief starts the raw packet send. (no wait)
* \param bytes the raw packet data
@@ -90,6 +97,7 @@ public:
virtual void free(Packet* packet) = 0;
virtual void queueOutbound(Packet* packet, uint8_t priority, uint32_t scheduled_for) = 0;
virtual Packet* peekNextOutbound(uint32_t now) = 0; // same pick as getNextOutbound(), without removing
virtual Packet* getNextOutbound(uint32_t now) = 0; // by priority
virtual int getOutboundCount(uint32_t now) const = 0;
virtual int getOutboundTotal() const = 0;
@@ -128,6 +136,7 @@ class Dispatcher {
unsigned long tx_budget_ms;
unsigned long last_budget_update;
unsigned long duty_cycle_window_ms;
uint8_t _default_tx_profile = 0;
void processRecvPacket(Packet* pkt);
void updateTxBudget();
@@ -180,6 +189,9 @@ public:
void releasePacket(Packet* packet);
void sendPacket(Packet* packet, uint8_t priority, uint32_t delay_millis=0);
void setDefaultTxProfile(uint8_t p) { _default_tx_profile = p & 0x03; }
uint8_t getDefaultTxProfile() const { return _default_tx_profile; }
unsigned long getTotalAirTime() const { return total_air_time; }
unsigned long getReceiveAirTime() const {return rx_air_time; }
unsigned long getRemainingTxBudget() const { return tx_budget_ms; }
+3
View File
@@ -59,6 +59,9 @@ public:
virtual void onBootComplete() { /* no op */ }
virtual uint32_t getIRQGpio() { return -1; } // not supported. Returns DIO1 (SX1262) and DIO0 (SX127x)
virtual void sleep(uint32_t secs) { /* no op */ }
// Sleep for at most `ms` milliseconds, waking on the timer or a radio
// interrupt. Default preserves the old whole-second behaviour.
virtual void sleepMs(uint32_t ms) { sleep((ms + 999) / 1000); }
virtual uint32_t getGpio() { return 0; }
virtual void setGpio(uint32_t values) {}
virtual uint8_t getStartupReason() const = 0;
+21
View File
@@ -36,6 +36,10 @@ namespace mesh {
#define PAYLOAD_VER_3 0x02 // FUTURE
#define PAYLOAD_VER_4 0x03 // FUTURE
#define RADIO_PROFILE_PRIMARY 0
#define RADIO_PROFILE_SECONDARY 1
#define RADIO_PROFILE_UNKNOWN 3
/**
* \brief The fundamental transmission unit.
*/
@@ -50,6 +54,20 @@ public:
uint8_t payload[MAX_PACKET_PAYLOAD];
int8_t _snr;
// Local-only routing metadata. Never written on air, never hashed.
// bits 0-1: TX target profile (0 primary, 1 secondary)
// bits 2-3: RX origin profile (0 primary, 1 secondary, 3 unknown/local)
uint8_t radio_profiles = 0;
uint8_t getTxProfile() const { return radio_profiles & 0x03; }
void setTxProfile(uint8_t p) {
radio_profiles = (uint8_t)((radio_profiles & ~0x03) | (p & 0x03));
}
uint8_t getRxProfile() const { return (radio_profiles >> 2) & 0x03; }
void setRxProfile(uint8_t p) {
radio_profiles = (uint8_t)((radio_profiles & ~0x0C) | ((p & 0x03) << 2));
}
/**
* \brief calculate the hash of payload + type
* \param dest_hash destination to store the hash (must be MAX_HASH_SIZE bytes)
@@ -111,4 +129,7 @@ public:
bool readFrom(const uint8_t src[], uint8_t len);
};
static_assert(sizeof(Packet) == 260,
"Packet must stay 260 bytes: the profile byte lives in tail padding");
}
+6 -3
View File
@@ -73,7 +73,7 @@ public:
return P_LORA_DIO_1; // default for SX1262
}
void sleep(uint32_t secs) override {
void sleepUs(uint64_t us) {
// Skip if not allow to sleep
if (inhibit_sleep) {
delay(1); // Give MCU to OTA to run
@@ -84,8 +84,8 @@ public:
gpio_num_t wakeupPin = (gpio_num_t)getIRQGpio();
// Configure timer wakeup
if (secs > 0) {
esp_sleep_enable_timer_wakeup(secs * 1000000ULL); // Wake up periodically to do scheduled jobs
if (us > 0) {
esp_sleep_enable_timer_wakeup(us); // Wake up periodically to do scheduled jobs
}
// Disable CPU interrupt servicing
@@ -113,6 +113,9 @@ public:
portEXIT_CRITICAL(&sleepMux);
}
void sleep(uint32_t secs) override { sleepUs((uint64_t)secs * 1000000ULL); }
void sleepMs(uint32_t ms) override { sleepUs((uint64_t)ms * 1000ULL); }
uint8_t getStartupReason() const override { return startup_reason; }
#if defined(P_LORA_TX_LED)
+70
View File
@@ -268,6 +268,20 @@ bool NRF52Board::isExternalPowered() {
}
}
// RTC2 is unused by the Adafruit core and the SoftDevice (RTC0), so it can
// supply a one-shot low-power deadline without disturbing millis()/FreeRTOS
// (RTC1). The interrupt only marks the event: the loop below owns clearing it.
#if defined(NRF_RTC2) && defined(RTC2_IRQn)
static volatile bool rtc2_fired = false;
extern "C" void RTC2_IRQHandler(void) {
if (NRF_RTC2->EVENTS_COMPARE[0]) {
NRF_RTC2->EVENTS_COMPARE[0] = 0;
rtc2_fired = true;
}
}
#endif
void NRF52Board::sleep(uint32_t secs) {
// Clear FPU interrupt flags to avoid insomnia
// see errata 87 for details https://docs.nordicsemi.com/bundle/errata_nRF52840_Rev3/page/ERR/nRF52840/Rev3/latest/anomaly_840_87.html
@@ -294,6 +308,62 @@ void NRF52Board::sleep(uint32_t secs) {
}
}
void NRF52Board::sleepMs(uint32_t ms) {
if (ms == 0) {
sleep(0); // event-driven only: no deadline to arm
return;
}
// Clear FPU interrupt flags to avoid insomnia (errata 87, as sleep())
#if (__FPU_USED == 1)
__set_FPSCR(__get_FPSCR() & ~(0x0000009F));
(void) __get_FPSCR();
NVIC_ClearPendingIRQ(FPU_IRQn);
#endif
#if defined(NRF_RTC2) && defined(RTC2_IRQn)
if (!rtc2_initialised) {
NRF_RTC2->TASKS_STOP = 1;
NRF_RTC2->TASKS_CLEAR = 1;
NRF_RTC2->PRESCALER = 0; // 32768 Hz
NVIC_SetPriority(RTC2_IRQn, 6); // SoftDevice reserves the top priorities
NVIC_EnableIRQ(RTC2_IRQn);
rtc2_initialised = true;
}
// RTC compare is 24-bit; radio2 caps a sleep at 1000 ms, well inside it.
uint32_t ticks = (uint32_t)(((uint64_t)ms * 32768ULL + 999ULL) / 1000ULL);
if (ticks == 0) ticks = 1;
if (ticks > 0xFFFFFFUL) ticks = 0xFFFFFFUL;
rtc2_fired = false;
NRF_RTC2->TASKS_CLEAR = 1;
NRF_RTC2->CC[0] = ticks;
NRF_RTC2->EVENTS_COMPARE[0] = 0;
NRF_RTC2->INTENSET = RTC_INTENSET_COMPARE0_Msk;
NRF_RTC2->TASKS_START = 1;
uint8_t sd_enabled = 0;
sd_softdevice_is_enabled(&sd_enabled);
while (!rtc2_fired) {
if (sd_enabled) {
sd_app_evt_wait();
} else {
__SEV();
__WFE();
__WFE();
}
}
NRF_RTC2->INTENCLR = RTC_INTENCLR_COMPARE0_Msk;
NRF_RTC2->EVENTS_COMPARE[0] = 0;
#else
// No free timer on this part: correct, but not low power.
MESH_DEBUG_PRINTLN("NRF52Board: no RTC2, sleepMs() falls back to delay()");
delay(ms);
#endif
}
// Temperature from NRF52 MCU
float NRF52Board::getMCUTemperature() {
uint8_t sd_enabled = 0;
+2
View File
@@ -28,6 +28,7 @@ struct PowerMgtConfig {
class NRF52Board : public mesh::MainBoard {
private:
bool pwrmgt_initialised = false;
bool rtc2_initialised = false;
protected:
uint8_t startup_reason;
@@ -57,6 +58,7 @@ public:
virtual bool getBootloaderVersion(char* version, size_t max_len) override;
virtual bool startOTAUpdate(const char *id, char reply[]) override;
virtual void sleep(uint32_t secs) override;
virtual void sleepMs(uint32_t ms) override;
bool isExternalPowered() override;
void attachDynamicPrefs(KeyValueStore* prefs) { } // no-op
+20 -1
View File
@@ -19,7 +19,7 @@ int PacketQueue::countBefore(uint32_t now) const {
return n;
}
mesh::Packet* PacketQueue::get(uint32_t now) {
int PacketQueue::findBest(uint32_t now) const {
uint8_t min_pri = 0xFF;
int best_idx = -1;
for (int j = 0; j < _num; j++) {
@@ -29,6 +29,16 @@ mesh::Packet* PacketQueue::get(uint32_t now) {
best_idx = j;
}
}
return best_idx;
}
mesh::Packet* PacketQueue::peek(uint32_t now) const {
int best_idx = findBest(now);
return best_idx < 0 ? NULL : _table[best_idx];
}
mesh::Packet* PacketQueue::get(uint32_t now) {
int best_idx = findBest(now);
if (best_idx < 0) return NULL; // empty, or all items are still in the future
mesh::Packet* top = _table[best_idx];
@@ -75,12 +85,21 @@ StaticPoolPacketManager::StaticPoolPacketManager(int pool_size): unused(pool_siz
}
}
StaticPoolPacketManager::~StaticPoolPacketManager() {
// Each packet lives in exactly one queue. The repeater keeps this manager for
// its lifetime; the destructor exists so host tests can own one without leaks.
for (int i = 0; i < unused.count(); i++) delete unused.itemAt(i);
for (int i = 0; i < send_queue.count(); i++) delete send_queue.itemAt(i);
for (int i = 0; i < rx_queue.count(); i++) delete rx_queue.itemAt(i);
}
mesh::Packet* StaticPoolPacketManager::allocNew() {
return unused.removeByIdx(0); // just get first one (returns NULL if empty)
}
void StaticPoolPacketManager::free(mesh::Packet* packet) {
if (packet == NULL) return;
packet->radio_profiles = 0;
if (!unused.add(packet, 0, 0)) {
MESH_DEBUG_PRINTLN("free: unused queue full, possible double-free detected");
}
+8
View File
@@ -8,8 +8,12 @@ class PacketQueue {
uint32_t* _schedule_table;
int _size, _num;
int findBest(uint32_t now) const;
public:
PacketQueue(int max_entries);
~PacketQueue() { delete[] _table; delete[] _pri_table; delete[] _schedule_table; }
mesh::Packet* peek(uint32_t now) const;
mesh::Packet* get(uint32_t now);
bool add(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for);
int count() const { return _num; }
@@ -26,10 +30,14 @@ class StaticPoolPacketManager : public mesh::PacketManager {
public:
StaticPoolPacketManager(int pool_size);
~StaticPoolPacketManager();
mesh::Packet* allocNew() override;
void free(mesh::Packet* packet) override;
void queueOutbound(mesh::Packet* packet, uint8_t priority, uint32_t scheduled_for) override;
mesh::Packet* peekNextOutbound(uint32_t now) override {
return send_queue.peek(now);
}
mesh::Packet* getNextOutbound(uint32_t now) override;
int getOutboundCount(uint32_t now) const override;
int getOutboundTotal() const override;
+29
View File
@@ -538,3 +538,32 @@ RxPowerSavingStatus RadioLibWrapper::getRxPowerSavingStatus() const {
status.effective_sleep_us = _rx_ps_eff_sleep_us;
return status;
}
// ---------------------------------------------------------------------------
// Fork: radio profile switching (radio2). Additive to upstream's wrapper.
// ---------------------------------------------------------------------------
bool RadioLibWrapper::hasCompletedReceive() const {
return (state & STATE_INT_READY) != 0;
}
bool RadioLibWrapper::isReceiveInProgress() {
return isReceivingPacket();
}
bool RadioLibWrapper::retune(float freq, float bw, uint8_t sf, uint8_t cr,
bool abort_receive) {
// RADIO2.md: retune() is never valid while RXPS is armed. Radio2 refuses to
// start with RXPS on; treat a broken invariant as a busy radio, not a
// silently re-armed duty cycle.
if (_rx_ps_enabled) return false;
if (hasCompletedReceive()) return false;
if ((state & ~STATE_INT_READY) == STATE_TX_WAIT) return false;
if (!abort_receive && isReceiveInProgress()) return false;
idle(); // stops RXPS if armed, standby, state = IDLE
setParams(freq, bw, sf, cr);
int16_t err = startReceiveMode();
if (err != RADIOLIB_ERR_NONE) return false;
state = STATE_RX;
return true;
}
+22
View File
@@ -4,6 +4,7 @@
#include <RadioLib.h>
// PowerSaving variant
#include "RXPowerSaving.h"
#include "RadioProfileControl.h"
#ifdef USE_CC310_HW_CRYPTO
#include <Adafruit_nRFCrypto.h>
@@ -43,6 +44,8 @@ protected:
uint32_t n_rx_ps_arm_failures;
RxPowerSavingArmRetryState _rx_ps_arm_retry;
RadioProfileControl* _profile_control = nullptr;
bool _nf_calib_active;
unsigned long _nf_last_calib;
unsigned long _nf_calib_deadline;
@@ -119,6 +122,25 @@ public:
return isChannelActive();
}
void setProfileControl(RadioProfileControl* control) { _profile_control = control; }
bool selectTxProfile(uint8_t profile) override {
return _profile_control ? _profile_control->selectTxProfile(profile) : true;
}
// True when a complete packet is waiting to be read by recvRaw().
// Defined in RadioLibWrappers.cpp: `state` is file-static.
bool hasCompletedReceive() const;
// True while a preamble/header/payload is being received.
bool isReceiveInProgress();
// Stop RX, apply a new preset, restart continuous RX. Returns false if a
// complete packet is pending, if a receive is in progress and
// `abort_receive` is false, or if the radio rejects the change.
bool retune(float freq, float bw, uint8_t sf, uint8_t cr,
bool abort_receive = false);
virtual void setParams(float freq, float bw, uint8_t sf, uint8_t cr) = 0;
uint32_t getRngSeed();
void setTxPower(int8_t dbm);
@@ -0,0 +1,11 @@
#pragma once
#include <stdint.h>
// Lets a feature own the radio's profile scheduling while the dispatcher only
// asks it to select the profile the next transmission needs. Fork-owned.
class RadioProfileControl {
public:
virtual ~RadioProfileControl() = default;
virtual bool selectTxProfile(uint8_t profile) = 0;
};
@@ -72,6 +72,7 @@ public:
mesh::Packet* allocNew() override { return nullptr; }
void free(mesh::Packet*) override {}
void queueOutbound(mesh::Packet*, uint8_t, uint32_t) override {}
mesh::Packet* peekNextOutbound(uint32_t) override { return nullptr; }
mesh::Packet* getNextOutbound(uint32_t) override { return nullptr; }
int getOutboundCount(uint32_t) const override { return 0; }
int getOutboundTotal() const override { return 0; }
+18 -2
View File
@@ -1128,8 +1128,10 @@ static mesh::Packet makeGroupPacket(uint8_t type, uint8_t hash, const GroupTextP
// deliver a decrypted group message to the hook the way MyMesh does
static void groupRecv(FleetManager& f, uint8_t type, const mesh::GroupChannel& c,
const GroupTextPayload& p) {
const GroupTextPayload& p,
uint8_t radio_profile = RADIO_PROFILE_PRIMARY) {
mesh::Packet pkt = makeGroupPacket(type, c.hash[0], p);
pkt.setRxProfile(radio_profile);
f.onGroupData(&pkt, type, c, p.data, p.len);
}
@@ -1145,6 +1147,7 @@ static void hearRepeat(FleetManager& f, const mesh::Packet& sent, uint8_t hops =
struct SentReply {
uint8_t secret[PUB_KEY_SIZE];
uint8_t hash; // channel hash
uint8_t radio_profile = RADIO_PROFILE_PRIMARY;
uint32_t ts = 0; // group-text timestamp
std::string name; // the sender name the reply carried
std::string body;
@@ -1170,12 +1173,14 @@ struct HookEnv {
}
static const char* nameFn(void* ctx) { return ((HookEnv*)ctx)->name.c_str(); }
static bool sendFn(void* ctx, const uint8_t* secret, uint8_t hash, uint32_t ts,
const char* sender_name, const char* body, uint8_t* out_pkt_hash) {
const char* sender_name, const char* body, uint8_t radio_profile,
uint8_t* out_pkt_hash) {
auto* e = (HookEnv*)ctx;
if (e->next_send_fails) { e->next_send_fails = false; return false; }
if (e->send_failures > 0) { e->send_failures--; return false; }
SentReply r;
r.hash = hash;
r.radio_profile = radio_profile;
r.ts = ts;
r.name = sender_name;
r.body = body;
@@ -1309,6 +1314,17 @@ TEST_F(FleetHooksTest, AckAlwaysRepliesJitteredInChannel) {
EXPECT_EQ(env.last_window, (uint32_t)FLEET_REPLY_WINDOW_MS);
}
TEST_F(FleetHooksTest, AckKeepsSecondaryOrigin) {
GroupTextPayload p = makeGroupText("alice", "!id k2\n!ack\nfilter stats");
groupRecv(fleet, PAYLOAD_TYPE_GRP_TXT, chan, p, RADIO_PROFILE_SECONDARY);
ASSERT_TRUE(pass());
g_mock_millis += env.jitter;
fleet.runScripts(ExecRecorder::fn, &env.rec);
ASSERT_EQ(env.sent.size(), (size_t)1);
EXPECT_EQ(env.sent[0].radio_profile, RADIO_PROFILE_SECONDARY);
}
// The jitter deadline crosses the millis() rollover: the reply is still due
// exactly when it should be (signed-difference comparison), not held for 49
// days.
+720
View File
@@ -0,0 +1,720 @@
// Behavior-level tests for the repeater's second radio preset (Radio2*):
// core profile metadata, policy matrix, timing, scheduler, persistence and CLI.
// Reached the same way a user or the firmware reaches the code.
#include <gtest/gtest.h>
#include <Arduino.h>
#include <algorithm>
#include <vector>
#include <helpers/StaticPoolPacketManager.h>
#include "CliUtil.h"
#include "Radio2.h"
namespace {
class FakeDevice : public Radio2Device {
public:
bool in_recv = true;
bool completed = false;
bool in_progress = false;
bool retune_ok = true;
float capture = 6.0f; // SX126x
int noise = -117;
int retunes = 0;
bool retune(float, float, uint8_t, uint8_t, bool) override {
retunes++;
return retune_ok;
}
bool hasCompletedReceive() const override { return completed; }
bool isReceiveInProgress() override { return in_progress; }
bool isInRecvMode() const override { return in_recv; }
int getNoiseFloor() const override { return noise; }
float captureCostSymbols() const override { return capture; }
};
void setPrimary(Radio2& r) {
r.setPrimary(910.525f, 125.0f, 10, 5);
}
// Scheduler tests drive loop() with a real (in-memory) store: a dirty config
// may fall due while the mock clock advances.
NativeFS scheduler_fs;
mesh::Packet makePacket(uint8_t payload_type, uint8_t route_type) {
mesh::Packet p;
p.header = (uint8_t)((payload_type << PH_TYPE_SHIFT) | route_type);
return p;
}
// Records the order of the calls checkSend() must make: select the TX profile
// before estimating airtime and before the CAD/receive check.
class OrderRadio : public mesh::Radio {
public:
std::vector<int> order;
bool select_ok = true;
bool started = false;
uint8_t selected = 0xff;
int recvRaw(uint8_t*, int) override { order.push_back(0); return 0; }
bool selectTxProfile(uint8_t profile) override {
order.push_back(1);
selected = profile;
return select_ok;
}
uint32_t getEstAirtimeFor(int) override { order.push_back(2); return 100; }
bool isReceiving() override { order.push_back(3); return false; }
float packetScore(float, int) override { return 1.0f; }
bool startSendRaw(const uint8_t*, int) override { started = true; return true; }
bool isSendComplete() override { return true; }
void onSendFinished() override {}
bool isInRecvMode() const override { return true; }
};
class FixedClock : public mesh::MillisecondClock {
public:
unsigned long now = 1;
unsigned long getMillis() override { return now; }
};
class TestDispatcher : public mesh::Dispatcher {
public:
TestDispatcher(mesh::Radio& r, mesh::MillisecondClock& ms, mesh::PacketManager& m)
: Dispatcher(r, ms, m) {}
mesh::DispatcherAction onRecvPacket(mesh::Packet*) override { return ACTION_RELEASE; }
};
} // namespace
// ---------------------------------------------------------------- core packet
TEST(PacketProfile, SizeStays260) {
EXPECT_EQ(sizeof(mesh::Packet), 260u);
}
TEST(PacketProfile, BitIsolation) {
mesh::Packet p;
EXPECT_EQ(p.getTxProfile(), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(p.getRxProfile(), RADIO_PROFILE_PRIMARY);
p.setTxProfile(RADIO_PROFILE_SECONDARY);
p.setRxProfile(2); // unknown-ish value still fits the 2-bit field
EXPECT_EQ(p.getTxProfile(), RADIO_PROFILE_SECONDARY);
EXPECT_EQ(p.getRxProfile(), 2u);
p.setRxProfile(RADIO_PROFILE_UNKNOWN);
EXPECT_EQ(p.getTxProfile(), RADIO_PROFILE_SECONDARY);
EXPECT_EQ(p.getRxProfile(), RADIO_PROFILE_UNKNOWN);
}
TEST(PacketProfile, WireFormatAndHashIgnoreProfile) {
mesh::Packet a;
a.header = (PAYLOAD_TYPE_ADVERT << PH_TYPE_SHIFT) | ROUTE_TYPE_FLOOD;
a.payload_len = 3;
a.payload[0] = 1; a.payload[1] = 2; a.payload[2] = 3;
a.setTxProfile(1);
a.setRxProfile(1);
mesh::Packet b = a;
b.setTxProfile(0);
b.setRxProfile(0);
uint8_t ha[MAX_HASH_SIZE], hb[MAX_HASH_SIZE];
a.calculatePacketHash(ha);
b.calculatePacketHash(hb);
EXPECT_EQ(memcmp(ha, hb, MAX_HASH_SIZE), 0);
uint8_t raw[64];
uint8_t len = a.writeTo(raw);
mesh::Packet c;
ASSERT_TRUE(c.readFrom(raw, len));
EXPECT_EQ(c.getTxProfile(), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(c.getRxProfile(), RADIO_PROFILE_PRIMARY);
}
TEST(PacketQueue, PeekDoesNotRemove) {
PacketQueue q(4);
mesh::Packet low, high;
low.header = 0;
high.header = 0;
ASSERT_TRUE(q.add(&low, 5, 0));
ASSERT_TRUE(q.add(&high, 1, 0));
EXPECT_EQ(q.peek(0), &high);
EXPECT_EQ(q.count(), 2);
EXPECT_EQ(q.get(0), &high);
EXPECT_EQ(q.count(), 1);
EXPECT_EQ(q.peek(0), &low);
}
TEST(PacketQueue, FutureEntriesAreInvisibleToPeek) {
PacketQueue q(2);
mesh::Packet p;
ASSERT_TRUE(q.add(&p, 1, 100));
EXPECT_EQ(q.peek(0), nullptr);
EXPECT_EQ(q.peek(100), &p);
}
TEST(DispatcherProfiles, SelectsBeforeAirtimeAndCad) {
OrderRadio radio;
FixedClock clock;
StaticPoolPacketManager mgr(4);
TestDispatcher d(radio, clock, mgr);
d.begin();
clock.now = 2;
mesh::Packet* p = d.obtainNewPacket();
ASSERT_NE(p, nullptr);
p->header = (PAYLOAD_TYPE_ADVERT << PH_TYPE_SHIFT) | ROUTE_TYPE_FLOOD;
p->setTxProfile(RADIO_PROFILE_SECONDARY);
d.sendPacket(p, 1, 0);
d.loop();
EXPECT_EQ(radio.selected, RADIO_PROFILE_SECONDARY);
EXPECT_TRUE(radio.started);
auto select = std::find(radio.order.begin(), radio.order.end(), 1);
auto airtime = std::find(radio.order.begin(), radio.order.end(), 2);
auto cad = std::find(radio.order.begin(), radio.order.end(), 3);
ASSERT_NE(select, radio.order.end());
ASSERT_NE(airtime, radio.order.end());
ASSERT_NE(cad, radio.order.end());
EXPECT_LT(select, airtime);
EXPECT_LT(airtime, cad);
d.loop(); // complete and release the outbound packet
}
TEST(DispatcherProfiles, SelectFailureLeavesPacketQueued) {
OrderRadio radio;
FixedClock clock;
StaticPoolPacketManager mgr(4);
TestDispatcher d(radio, clock, mgr);
d.begin();
clock.now = 2;
mesh::Packet* p = d.obtainNewPacket();
ASSERT_NE(p, nullptr);
p->header = (PAYLOAD_TYPE_ADVERT << PH_TYPE_SHIFT) | ROUTE_TYPE_FLOOD;
p->setTxProfile(RADIO_PROFILE_SECONDARY);
d.sendPacket(p, 1, 0);
radio.select_ok = false;
d.loop();
EXPECT_FALSE(radio.started);
EXPECT_EQ(mgr.getOutboundTotal(), 1);
}
TEST(DispatcherProfiles, ObtainNewPacketUsesDefault) {
OrderRadio radio;
FixedClock clock;
StaticPoolPacketManager mgr(4);
TestDispatcher d(radio, clock, mgr);
d.setDefaultTxProfile(RADIO_PROFILE_SECONDARY);
mesh::Packet* p = d.obtainNewPacket();
ASSERT_NE(p, nullptr);
EXPECT_EQ(p->getTxProfile(), RADIO_PROFILE_SECONDARY);
EXPECT_EQ(p->getRxProfile(), RADIO_PROFILE_UNKNOWN);
d.releasePacket(p);
}
TEST(PacketPool, FreeResetsProfileByte) {
StaticPoolPacketManager mgr(1);
mesh::Packet* p = mgr.allocNew();
ASSERT_NE(p, nullptr);
p->setTxProfile(RADIO_PROFILE_SECONDARY);
p->setRxProfile(RADIO_PROFILE_SECONDARY);
mgr.free(p);
mesh::Packet* again = mgr.allocNew();
ASSERT_EQ(again, p);
EXPECT_EQ(again->radio_profiles, 0);
mgr.free(again);
}
// ---------------------------------------------------------------- policy
TEST(Radio2Policy, MatrixTargets) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
mesh::Packet advert = makePacket(PAYLOAD_TYPE_ADVERT, ROUTE_TYPE_FLOOD);
r.setPolicy(RADIO2_ACTION_SAME, RADIO2_ACTION_SAME);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &advert), RADIO2_ACTION_SAME);
EXPECT_EQ(r.targetFor(RADIO2_ACTION_SAME, RADIO_PROFILE_PRIMARY), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(r.targetFor(RADIO2_ACTION_SAME, RADIO_PROFILE_SECONDARY), RADIO_PROFILE_SECONDARY);
r.setPolicy(RADIO2_ACTION_OTHER, RADIO2_ACTION_OTHER);
EXPECT_EQ(r.targetFor(RADIO2_ACTION_OTHER, RADIO_PROFILE_PRIMARY), RADIO_PROFILE_SECONDARY);
EXPECT_EQ(r.targetFor(RADIO2_ACTION_OTHER, RADIO_PROFILE_SECONDARY), RADIO_PROFILE_PRIMARY);
r.setPolicy(RADIO2_ACTION_BOTH, RADIO2_ACTION_BOTH);
EXPECT_EQ(r.targetFor(RADIO2_ACTION_BOTH, RADIO_PROFILE_PRIMARY), RADIO_PROFILE_PRIMARY);
r.setPolicy(RADIO2_ACTION_DROP, RADIO2_ACTION_DROP);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &advert), RADIO2_ACTION_DROP);
}
TEST(Radio2Policy, OnlyBroadcastFloodCrosses) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPolicy(RADIO2_ACTION_OTHER, RADIO2_ACTION_OTHER);
mesh::Packet advert = makePacket(PAYLOAD_TYPE_ADVERT, ROUTE_TYPE_FLOOD);
mesh::Packet grp_txt = makePacket(PAYLOAD_TYPE_GRP_TXT, ROUTE_TYPE_FLOOD);
mesh::Packet grp_data = makePacket(PAYLOAD_TYPE_GRP_DATA, ROUTE_TYPE_FLOOD);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &advert), RADIO2_ACTION_OTHER);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &grp_txt), RADIO2_ACTION_OTHER);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &grp_data), RADIO2_ACTION_OTHER);
mesh::Packet direct_grp = makePacket(PAYLOAD_TYPE_GRP_TXT, ROUTE_TYPE_DIRECT);
mesh::Packet unicast_flood = makePacket(PAYLOAD_TYPE_TXT_MSG, ROUTE_TYPE_FLOOD);
mesh::Packet ack = makePacket(PAYLOAD_TYPE_ACK, ROUTE_TYPE_FLOOD);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &direct_grp), RADIO2_ACTION_SAME);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &unicast_flood), RADIO2_ACTION_SAME);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &ack), RADIO2_ACTION_SAME);
// A non-crossable packet keeps an explicit drop.
r.setPolicy(RADIO2_ACTION_DROP, RADIO2_ACTION_DROP);
EXPECT_EQ(r.actionFor(RADIO_PROFILE_PRIMARY, &direct_grp), RADIO2_ACTION_DROP);
}
TEST(Radio2Policy, RepliesFollowOrigin) {
FakeDevice dev;
Radio2 r(dev);
EXPECT_EQ(r.replyProfile(RADIO_PROFILE_PRIMARY), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(r.replyProfile(RADIO_PROFILE_SECONDARY), RADIO_PROFILE_SECONDARY);
EXPECT_EQ(r.replyProfile(RADIO_PROFILE_UNKNOWN), RADIO_PROFILE_PRIMARY);
}
// ---------------------------------------------------------------- timing
TEST(Radio2Timing, KnownPresetMath) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
Radio2Timing t;
ASSERT_TRUE(r.timing(&t));
EXPECT_EQ(t.primary_capture_us, 49152u);
EXPECT_EQ(t.secondary_capture_us, 49152u);
EXPECT_EQ(t.primary_bound_us, 73920u);
EXPECT_EQ(t.secondary_bound_us, 73920u);
EXPECT_TRUE(t.usable);
}
TEST(Radio2Timing, ActiveAndIdleShares) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
ASSERT_TRUE(r.start(false, false)); // active mode from boot
Radio2Timing t;
ASSERT_TRUE(r.timing(&t));
EXPECT_TRUE(t.active_mode);
EXPECT_EQ(t.secondary_visit_us, 49152u);
EXPECT_EQ(t.primary_visit_us, 4 * 49152u);
EXPECT_TRUE(t.secondary_lossy);
g_mock_millis += RADIO2_ACTIVE_HOLD_MS + 1;
ASSERT_TRUE(r.timing(&t));
EXPECT_FALSE(t.active_mode);
EXPECT_EQ(t.primary_visit_us, 49152u);
EXPECT_EQ(t.secondary_visit_us, t.primary_bound_us);
}
TEST(Radio2Timing, UnsafePairRejected) {
FakeDevice dev;
Radio2 r(dev);
r.setPrimary(910.0f, 500.0f, 5, 5); // fast, wide: tiny primary bound
EXPECT_EQ(r.setPreset(915.0f, 125.0f, 12, 5), RADIO2_SET_UNSCANNABLE);
// The refused preset was not committed, so the live pair is still unset.
Radio2Timing t;
EXPECT_FALSE(r.timing(&t));
EXPECT_EQ(r.getSecondaryProfile().freq, 0.0f);
}
TEST(Radio2Timing, OverlapRejected) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
EXPECT_EQ(r.setPreset(910.6f, 125.0f, 10, 5), RADIO2_SET_OVERLAP);
// A rejected preset leaves the previous one unchanged.
EXPECT_EQ(r.getSecondaryProfile().freq, 0.0f);
}
TEST(Radio2Timing, SleepDeadline) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
r.start(false, false);
EXPECT_GT(r.getSleepMs(), 0u);
EXPECT_LE(r.getSleepMs(), RADIO2_SLEEP_MAX_MS);
dev.completed = true;
EXPECT_EQ(r.getSleepMs(), 1u);
dev.completed = false;
r.setEnabled(false);
EXPECT_EQ(r.getSleepMs(), 0u);
}
// ---------------------------------------------------------------- scheduler
TEST(Radio2Scheduler, DisabledDoesNotStart) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.setAdvert(RADIO2_ADVERT_BOTH);
r.setEnabled(false);
EXPECT_FALSE(r.start(false, false));
EXPECT_FALSE(r.isScanning());
EXPECT_FALSE(r.advertBoth()); // a disabled scanner must not duplicate adverts
r.loop(&scheduler_fs, true);
EXPECT_FALSE(r.isScanning());
}
TEST(Radio2Scheduler, AlternatesProfiles) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
g_mock_millis += 200; // past the active primary visit
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_SECONDARY);
EXPECT_EQ(dev.retunes, 1);
g_mock_millis += 50; // past the active secondary visit
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(dev.retunes, 2);
}
TEST(Radio2Scheduler, PrimaryInProgressDefers) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
dev.in_progress = true;
g_mock_millis += 200;
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_PRIMARY);
dev.in_progress = false;
g_mock_millis += 2;
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_SECONDARY);
}
TEST(Radio2Scheduler, ActiveAbortsSecondaryReceive) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
g_mock_millis += 200;
r.loop(&scheduler_fs, true);
ASSERT_EQ(r.currentProfile(), RADIO_PROFILE_SECONDARY);
dev.in_progress = true;
g_mock_millis += 50;
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(r.getAborts(), 1u);
}
TEST(Radio2Scheduler, IdleHoldsSecondaryReceive) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
g_mock_millis += RADIO2_ACTIVE_HOLD_MS + 1; // idle
r.loop(&scheduler_fs, true); // primary -> secondary
ASSERT_EQ(r.currentProfile(), RADIO_PROFILE_SECONDARY);
dev.in_progress = true;
g_mock_millis += 100;
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_SECONDARY); // held
EXPECT_EQ(r.getAborts(), 0u);
}
TEST(Radio2Scheduler, TxBlocksSwitching) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
dev.in_recv = false; // TX in progress
g_mock_millis += 200;
r.loop(&scheduler_fs, true);
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(dev.retunes, 0);
}
TEST(Radio2Scheduler, SwitchFailureDisablesScanning) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
dev.retune_ok = false;
for (uint32_t i = 0; i < RADIO2_MAX_SWITCH_FAILURES + 2; i++) {
g_mock_millis += RADIO2_SWITCH_RETRY_MS + 100;
r.loop(&scheduler_fs, true);
}
EXPECT_FALSE(r.isScanning());
EXPECT_EQ(r.currentProfile(), RADIO_PROFILE_PRIMARY);
EXPECT_EQ(r.getSwitchErrors(), RADIO2_MAX_SWITCH_FAILURES);
}
TEST(Radio2Scheduler, PrimaryPacketStartsActiveMode) {
g_mock_millis = 0;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
r.setPreset(915.0f, 125.0f, 10, 5);
ASSERT_TRUE(r.start(false, false));
g_mock_millis += RADIO2_ACTIVE_HOLD_MS + 1;
Radio2Timing t;
r.timing(&t);
EXPECT_FALSE(t.active_mode);
r.notePrimaryPacket();
r.timing(&t);
EXPECT_TRUE(t.active_mode);
}
// ---------------------------------------------------------------- persistence
TEST(Radio2Persistence, Roundtrip) {
NativeFS fs;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.setPolicy(RADIO2_ACTION_OTHER, RADIO2_ACTION_DROP);
r.setAdvert(RADIO2_ADVERT_BOTH);
r.save(&fs);
Radio2 loaded(dev);
loaded.begin(&fs);
EXPECT_TRUE(loaded.isEnabled());
EXPECT_EQ(loaded.getSecondaryProfile().freq, 915.0f);
EXPECT_EQ(loaded.getSecondaryProfile().bw, 125.0f);
EXPECT_EQ(loaded.getSecondaryProfile().sf, 10);
EXPECT_EQ(loaded.getSecondaryProfile().cr, 5);
EXPECT_EQ(loaded.getPolicyPrimary(), RADIO2_ACTION_OTHER);
EXPECT_EQ(loaded.getPolicySecondary(), RADIO2_ACTION_DROP);
EXPECT_EQ(loaded.getAdvert(), RADIO2_ADVERT_BOTH);
}
TEST(Radio2Persistence, DisabledKeepsPreset) {
NativeFS fs;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.setEnabled(false);
r.save(&fs);
Radio2 loaded(dev);
loaded.begin(&fs);
EXPECT_FALSE(loaded.isEnabled());
EXPECT_EQ(loaded.getSecondaryProfile().freq, 915.0f);
}
TEST(Radio2Persistence, TruncatedRejected) {
NativeFS fs;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.save(&fs);
fs.files[RADIO2_CFG_FILE].resize(10);
Radio2 loaded(dev);
loaded.begin(&fs);
EXPECT_FALSE(loaded.isEnabled());
EXPECT_EQ(loaded.getSecondaryProfile().freq, 0.0f);
}
TEST(Radio2Persistence, BadCrcRejected) {
NativeFS fs;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.save(&fs);
fs.files[RADIO2_CFG_FILE][5] ^= 0xFF;
Radio2 loaded(dev);
loaded.begin(&fs);
EXPECT_FALSE(loaded.isEnabled());
}
TEST(Radio2Persistence, BackupRecovery) {
NativeFS fs;
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
ASSERT_EQ(r.setPreset(915.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.save(&fs); // canonical: 915
ASSERT_EQ(r.setPreset(916.0f, 125.0f, 10, 5), RADIO2_SET_OK);
r.save(&fs); // canonical: 916, backup: 915
ASSERT_TRUE(fs.exists("/radio2_cfg.bak"));
fs.files[RADIO2_CFG_FILE].resize(3);
Radio2 loaded(dev);
loaded.begin(&fs);
EXPECT_TRUE(loaded.isEnabled());
EXPECT_EQ(loaded.getSecondaryProfile().freq, 915.0f);
}
// ---------------------------------------------------------------- CLI
TEST(Radio2Cli, StatusOff) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
char reply[CLI_REPLY_MAX];
radio2CLI(r, false, false, "", reply);
EXPECT_STREQ(reply, "off");
}
TEST(Radio2Cli, SetPresetAndStatus) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
char reply[CLI_REPLY_MAX];
radio2CLI(r, false, false, "915,125,10,5", reply);
EXPECT_STREQ(reply, "OK - radio2 915,125,10,5");
EXPECT_TRUE(r.isEnabled());
radio2CLI(r, false, false, "status", reply);
EXPECT_NE(strstr(reply, "apply=pending"), nullptr);
g_mock_millis += RADIO2_APPLY_DELAY_MS;
r.loop(&scheduler_fs, true);
EXPECT_TRUE(r.isScanning());
radio2CLI(r, false, false, "status", reply);
EXPECT_NE(strstr(reply, "on; "), nullptr);
EXPECT_NE(strstr(reply, "at="), nullptr);
EXPECT_LE(strlen(reply), (size_t)CLI_REPLY_MAX - 1);
}
TEST(Radio2Cli, PolicyAndAdvert) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
char reply[CLI_REPLY_MAX];
radio2CLI(r, false, false, "policy", reply);
EXPECT_STREQ(reply, "> primary=same,secondary=same");
radio2CLI(r, false, false, "policy other", reply);
EXPECT_STREQ(reply, "OK - radio2 policy primary=other,secondary=other");
radio2CLI(r, false, false, "policy other drop", reply);
EXPECT_STREQ(reply, "OK - radio2 policy primary=other,secondary=drop");
radio2CLI(r, false, false, "policy nope", reply);
EXPECT_STREQ(reply, "Err - radio2 policy must be same|other|both|drop");
radio2CLI(r, false, false, "advert", reply);
EXPECT_STREQ(reply, "> primary");
radio2CLI(r, false, false, "advert both", reply);
EXPECT_STREQ(reply, "OK - radio2 advert both");
radio2CLI(r, false, false, "advert nope", reply);
EXPECT_STREQ(reply, "Err - radio2 advert must be primary|both");
}
TEST(Radio2Cli, Off) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
char reply[CLI_REPLY_MAX];
radio2CLI(r, false, false, "915,125,10,5", reply);
radio2CLI(r, false, false, "off", reply);
EXPECT_STREQ(reply, "OK - radio2 off");
EXPECT_FALSE(r.isEnabled());
g_mock_millis += RADIO2_APPLY_DELAY_MS;
r.loop(&scheduler_fs, true);
EXPECT_FALSE(r.isScanning());
}
TEST(Radio2Cli, Errors) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
char reply[CLI_REPLY_MAX];
radio2CLI(r, false, false, "915,125", reply);
EXPECT_STREQ(reply, "Err - radio2 preset must be <freq>,<bw>,<sf>,<cr>");
radio2CLI(r, false, false, "915,125,10,5", reply);
EXPECT_STREQ(reply, "OK - radio2 915,125,10,5");
radio2CLI(r, false, false, "910.6,125,10,5", reply);
EXPECT_STREQ(reply, "Err - radio2 overlaps radio");
radio2CLI(r, true, false, "916,125,10,5", reply);
EXPECT_STREQ(reply, "Err - radio.rxps is on; set radio.rxps off first");
radio2CLI(r, false, true, "916,125,10,5", reply);
EXPECT_STREQ(reply, "Err - radio2 conflicts with extra.sf; clear extra SF first");
radio2CLI(r, false, false, "status junk", reply);
EXPECT_EQ(strncmp(reply, "Err - usage:", 12), 0);
EXPECT_LE(strlen(reply), (size_t)CLI_REPLY_MAX - 1);
}
TEST(Radio2Cli, Timing) {
FakeDevice dev;
Radio2 r(dev);
setPrimary(r);
char reply[CLI_REPLY_MAX];
radio2CLI(r, false, false, "915,125,10,5", reply);
radio2CLI(r, false, false, "timing", reply);
EXPECT_NE(strstr(reply, "primary="), nullptr);
EXPECT_NE(strstr(reply, "secondary="), nullptr);
EXPECT_LE(strlen(reply), (size_t)CLI_REPLY_MAX - 1);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}