diff --git a/RADIO2.md b/RADIO2.md new file mode 100644 index 00000000..6532011e --- /dev/null +++ b/RADIO2.md @@ -0,0 +1,1889 @@ +# RADIO2 — second radio preset for the repeater filter fork + +Status: **implemented**. This document is both the implementation contract and +the user manual; the code lives in `examples/simple_repeater/Radio2*` and the +core enabler is behaviour-neutral when radio2 is off. Native coverage is the +`native_radio2` / `native_radio2_san` suites. + +Scope: `examples/simple_repeater/` only. The core changes are generic and +behaviour-neutral when radio2 is off. No companion/room/sensor role gets the +feature. + +--- + +## 1. Summary + +Add a second LoRa preset to the repeater. One transceiver time-shares between +the primary preset (`radio`) and the secondary preset (`radio2`). + +The feature must: + +- keep the primary profile protected; +- treat the secondary profile as a bonus; +- work with `powersaving` enabled (MCU light sleep), because solar repeaters + need it; +- allow the operator to choose how a packet heard on one profile is handled; +- cross profiles only for **broadcast flood** traffic; +- keep direct, ACK, path-return and unicast-flood DM traffic on the profile it + was heard on; +- send replies on the profile the request arrived on; +- apply the existing packet filter to both profiles equally in v1; +- use its own persisted config file; +- keep the upstream diff small and generic. + +RXPS (`radio.rxps`) and radio2 are mutually exclusive. `powersaving` and radio2 +are compatible and required. + +--- + +## 2. Non-goals + +Do not implement in v1: + +- cross-profile direct messages, ACKs, path returns, traces, anonymous requests, + or unicast flood DMs; +- a bridge flow table / ACK matching / return-path state; +- foreign protocols (Meshtext, Ethernet, KISS, media); +- temporary radio2 leases (`tempradio2`); +- on-chip LR2021 multi-SF scanning; +- per-profile noise floors; +- per-profile filter rules (phase 2 only); +- simultaneous RX on two presets (impossible on one transceiver); +- partial packet transmission (never possible; TX is atomic). + +--- + +## 3. Terms + +| Term | Meaning | +|---|---| +| primary | The existing `radio` preset, stored in `/com_prefs`. | +| secondary | The new `radio2` preset, stored in `/radio2_cfg`. | +| profile | A frequency/bandwidth/SF/CR tuple. | +| broadcast flood | A flood packet with no unicast destination: advert, group text, group data. | +| unicast flood | A DM/request/response sent with flood routing. It is **not** crossable. | +| active mode | Primary has been heard recently; primary gets priority. | +| idle mode | Primary has been quiet long enough; secondary gets the maximum safe share. | +| visit | A contiguous period listening on one profile. | +| hold | In idle mode, finishing a secondary packet that is already in progress at the visit deadline. | +| abort | In active mode, retuning away from an in-progress secondary receive; the packet is dropped, never transmitted partially. | + +--- + +## 4. User-visible behaviour + +### 4.1 Defaults + +- radio2 is **off**. +- policy: `primary=same`, `secondary=same` (isolated two-network repeater). +- advert: `primary`. +- replies: always the origin profile. +- filters: apply to both profiles equally. +- RXPS: must be off while radio2 is enabled. +- powersaving: may be on; radio2 uses it. + +### 4.2 Policy matrix + +Each origin has one action: + +| Action | Meaning | +|---|---| +| `same` | Repeat only on the profile it was heard on. | +| `other` | Repeat only on the other profile. | +| `both` | Transmit two copies, one on each profile. | +| `drop` | Do not repeat; still process locally. | + +The complete matrix: + +| Heard on | `same` | `other` | `both` | `drop` | +|---|---|---|---|---| +| primary | TX primary | TX secondary | TX both | no TX | +| secondary | TX secondary | TX primary | TX both | no TX | + +`both` is two sequential transmissions, not simultaneous. It consumes two +packet-pool slots while queued, two airtime charges, and shares the same +duty-cycle budget. + +### 4.3 Packet classes + +Cross-profile actions (`other`, `both`) apply only to **broadcast flood**: + +- `PAYLOAD_TYPE_ADVERT` (adverts, including zero-hop adverts) +- `PAYLOAD_TYPE_GRP_TXT` when `isRouteFlood()` +- `PAYLOAD_TYPE_GRP_DATA` when `isRouteFlood()` + +Everything else is **not crossable**: + +- direct/transport-direct packets +- ACKs +- path returns +- traces +- anonymous requests +- unicast flood DMs (`REQ`, `RESPONSE`, `TXT_MSG`, `PATH`, `ANON_REQ`, etc.) +- control packets +- raw custom packets + +For a non-crossable packet, the effective action is: + +- `drop` if the configured action is `drop`; +- otherwise `same`. + +This is the rule that avoids the flooded-DM ACK/path trap. A unicast flood DM +stays on its origin profile; its ACK/path return therefore also stays there. + +### 4.4 Replies + +Replies to a received packet are always sent on the profile the request arrived +on. This includes: + +- CLI replies +- ACKs generated by the core +- path returns +- control/discover responses +- fleet acknowledgements + +There is no `radio2.reply` setting. Origin is the rule. + +Locally originated, non-reply traffic: + +- adverts: `radio2 advert primary|both` (default `primary`) +- battery/fleet alerts: primary +- scheduled fleet scripts: primary unless the script is a reply to a received + fleet message, in which case the captured origin profile is used + +### 4.5 Adverts + +`radio2 advert primary` (default): local adverts go on primary only. + +`radio2 advert both`: local adverts are transmitted once on each profile. + +Received adverts follow the policy matrix (they are broadcast flood). + +### 4.6 Filters + +v1: the existing filter applies to both profiles equally. A packet heard on +either profile goes through the same rule list. + +Phase 2: add a per-rule `radio=any|primary|secondary` predicate. Default `any`. +See §14. + +### 4.7 RXPS and powersaving + +- `radio.rxps` and radio2 are mutually exclusive. +- `set radio2 ...` refuses while RXPS is enabled. +- `set radio.rxps on/...` refuses while radio2 is enabled. +- `set radio.rxps off` is always allowed. +- If both are somehow persisted, radio2 does not start; primary RXPS continues; + `radio2` status reports the conflict. +- `powersaving` is allowed and required on nRF52 and ESP32. radio2 provides a + timed wake deadline so the MCU can sleep between visits: ESP32 uses light + sleep with a timer expiry; nRF52 uses an RTC2 one-shot (with a `delay()` + fallback on a part that has no RTC2). +- Other board families have no sub-second timed wake: they do not override + `sleep()`, so the default `sleepMs()` also does nothing. radio2 stays correct + there — the main loop polls between visits — but `powersaving` saves no + power. Use nRF52 or ESP32 when the repeater is solar/battery powered. + +### 4.8 Noise floor + +There is one shared noise floor, as today. No per-profile floor. `radio2` +status may show the current value. If `int.thresh` is enabled, the value is a +blend while scanning; this is accepted. + +--- + +## 5. Architecture + +Two layers: + +1. **Generic core enabler** (small upstream diff): + - one local-only profile byte on `mesh::Packet`; + - `PacketManager::peekNextOutbound()`; + - `Radio::selectTxProfile()`; + - `Dispatcher` selects the TX profile before airtime/CAD; + - `Dispatcher::default_tx_profile` for reply routing; + - `MainBoard::sleepMs()` for timed wake. + +2. **Fork-owned radio2 feature**: + - config, persistence, CLI, policy, scheduler, status; + - a `Radio2Device` interface so the policy/scheduler is host-testable; + - a `RadioProfileControl` implementation the radio wrapper calls. + +The core never knows what “radio2” means. It only knows a packet has a target +profile 0/1 and a radio can select it. + +--- + +## 6. Core changes + +### 6.1 `src/Packet.h` — one local profile byte + +`Packet` is currently 260 bytes. The last field `_snr` is at offset 258; there +is one byte of tail padding at offset 259. Add one byte there. `sizeof(Packet)` +must stay 260. + +Add after `_snr`: + +```cpp + // 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)); + } +``` + +Add constants near the top of `Packet.h` or in `MeshCore.h`: + +```cpp +#define RADIO_PROFILE_PRIMARY 0 +#define RADIO_PROFILE_SECONDARY 1 +#define RADIO_PROFILE_UNKNOWN 3 +``` + +Add after the class: + +```cpp +static_assert(sizeof(mesh::Packet) == 260, + "Packet must stay 260 bytes: the profile byte lives in tail padding"); +``` + +Do **not** add the byte to `writeTo()`/`readFrom()`. It is local metadata. +`calculatePacketHash()` must not include it, so dedup works across profiles. + +`Packet::Packet()` does not need an explicit assignment because the NSDMI +initialises it to 0. `StaticPoolPacketManager::free()` must reset it (see +§6.6). + +### 6.2 `src/Dispatcher.h` — peek and default TX profile + +Add to `PacketManager`: + +```cpp + virtual Packet* peekNextOutbound(uint32_t now) = 0; +``` + +Add to `Radio`: + +```cpp + // Select the profile the next transmission will use. Returning false means + // "not safe to retune yet; try again next loop". Default: no profile support. + virtual bool selectTxProfile(uint8_t profile) { (void)profile; return true; } +``` + +Add to `Dispatcher` private state: + +```cpp + uint8_t _default_tx_profile = 0; +``` + +Add public accessors: + +```cpp + void setDefaultTxProfile(uint8_t p) { _default_tx_profile = p & 0x03; } + uint8_t getDefaultTxProfile() const { return _default_tx_profile; } +``` + +`obtainNewPacket()` must tag new packets: + +```cpp +Packet* Dispatcher::obtainNewPacket() { + auto pkt = _mgr->allocNew(); + if (pkt == NULL) { + _err_flags |= ERR_EVENT_FULL; + } else { + pkt->payload_len = pkt->path_len = 0; + pkt->_snr = 0; + pkt->setTxProfile(_default_tx_profile); + pkt->setRxProfile(RADIO_PROFILE_UNKNOWN); + } + return pkt; +} +``` + +`checkRecv()` uses `_mgr->allocNew()` directly; `MyMesh::onRecvPacket()` sets +both profile fields after parsing. + +### 6.3 `src/Dispatcher.cpp` — select before airtime/CAD + +Current `checkSend()` checks the channel before it pops the packet. Change it +to peek first, select the profile, then do the budget/CAD checks, then pop. + +At the top of `checkSend()`: + +```cpp +void Dispatcher::checkSend() { + 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); + // ... existing budget check ... + if (!millisHasNowPassed(next_tx_time)) return; + // ... existing isReceiving()/CAD check ... + cad_busy_start = 0; + + outbound = _mgr->getNextOutbound(now); + // ... existing send path ... +} +``` + +Notes: + +- `selectTxProfile()` must run before `getEstAirtimeFor()` and before + `isReceiving()`/CAD, so the estimate and channel check use the TX profile. +- If `selectTxProfile()` returns false, return and retry next loop. The packet + stays queued. +- `peekNextOutbound()` and `getNextOutbound()` must select the same packet. + Refactor `PacketQueue` so both use one `findBest(now)` helper. +- When radio2 is off, `selectTxProfile()` is the default no-op and the + behaviour is identical to today. + +### 6.4 `src/helpers/StaticPoolPacketManager.h/.cpp` — peek and reset + +Add to `PacketQueue`: + +```cpp + int findBest(uint32_t now) const; + mesh::Packet* peek(uint32_t now) const; +``` + +`get()` becomes: + +```cpp +mesh::Packet* PacketQueue::get(uint32_t now) { + int i = findBest(now); + return i < 0 ? NULL : removeByIdx(i); +} +``` + +`peek()` returns `_table[findBest(now)]` without removing. + +Add to `StaticPoolPacketManager`: + +```cpp + mesh::Packet* peekNextOutbound(uint32_t now) override { + return send_queue.peek(now); + } +``` + +In `StaticPoolPacketManager::free()`, reset the local profile byte before +returning the packet to the unused pool: + +```cpp +void StaticPoolPacketManager::free(mesh::Packet* packet) { + if (packet == NULL) return; + packet->radio_profiles = 0; + if (!unused.add(packet, 0, 0)) { ... } +} +``` + +Update `test/test_empty_contact_slots/test_empty_contact_slots.cpp`'s +`DummyPacketManager` with: + +```cpp + mesh::Packet* peekNextOutbound(uint32_t) override { return nullptr; } +``` + +### 6.5 `src/helpers/radiolib/RadioProfileControl.h` — new fork-owned interface + +Create: + +```cpp +#pragma once +#include + +class RadioProfileControl { +public: + virtual ~RadioProfileControl() = default; + virtual bool selectTxProfile(uint8_t profile) = 0; +}; +``` + +### 6.6 `src/helpers/radiolib/RadioLibWrappers.h/.cpp` — retune and control + +Add to `RadioLibWrapper`: + +```cpp + RadioProfileControl* _profile_control = nullptr; + +public: + 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(). + // Declared here, 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. + // `abort_receive=true` is used only by the scheduler's active-mode + // secondary deadline: it abandons an in-progress secondary receive. + bool retune(float freq, float bw, uint8_t sf, uint8_t cr, + bool abort_receive = false); +``` + +Implementation in `RadioLibWrappers.cpp`: + +```cpp +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) { + if (hasCompletedReceive()) 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; +} +``` + +`idle()` and `startReceiveMode()` are protected members of the base, so this +method belongs in the base. `setParams()` is the existing virtual implemented by +every family wrapper. `state` is the file-static ISR flag in +`RadioLibWrappers.cpp`, which is why the two predicates are defined there rather +than inline in the header. + +Do not call `retune()` while `_rx_ps_enabled` is true. Radio2 refuses to start +with RXPS on; if that invariant is ever broken, `retune()` should return false +rather than silently re-arm RXPS. + +### 6.7 `src/MeshCore.h` — timed sleep + +Add to `MainBoard`: + +```cpp + // 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); } +``` + +### 6.8 `src/helpers/ESP32Board.h` — millisecond light sleep + +Refactor the existing `sleep(uint32_t secs)` into a common microsecond helper: + +```cpp + void sleepUs(uint64_t us) { + if (inhibit_sleep) { delay(1); return; } + gpio_num_t wakeupPin = (gpio_num_t)getIRQGpio(); + if (us > 0) esp_sleep_enable_timer_wakeup(us); + portENTER_CRITICAL(&sleepMux); + if (gpio_get_level(wakeupPin) == HIGH) { + portEXIT_CRITICAL(&sleepMux); + delay(1); + return; + } + esp_sleep_enable_gpio_wakeup(); + gpio_wakeup_enable(wakeupPin, GPIO_INTR_HIGH_LEVEL); + esp_light_sleep_start(); + gpio_wakeup_disable(wakeupPin); + gpio_set_intr_type(wakeupPin, GPIO_INTR_POSEDGE); + 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); } +``` + +Preserve `inhibit_sleep`, the DIO check, the critical section and the GPIO +wake configuration exactly. + +### 6.9 `src/helpers/NRF52Board.cpp/.h` — timed wake + +`NRF52Board::sleep()` currently ignores `secs` and wakes on any interrupt. Add +`sleepMs(uint32_t ms)` that arms a one-shot low-power timer for `ms`, then uses +the existing `sd_app_evt_wait()` / `__WFE()` path. + +Implementation: + +- Use RTC2 (`NRF_RTC2`, prescaler 0, compare channel 0) as the one-shot + low-power deadline. RTC0 belongs to the SoftDevice and RTC1 is not disturbed, + so `millis()`/FreeRTOS and Bluefruit are unaffected. +- A small `RTC2_IRQHandler` only sets a flag; the sleep loop clears the compare + event after waking. The loop re-enters `sd_app_evt_wait()` / `__WFE()` on + spurious wakeups and exits only on the timer, so radio DIO and SoftDevice + events still wake it immediately. +- If the part has no RTC2, fall back to `delay(ms)` (correct but not low power) + and log a debug message. Do not silently sleep without a deadline. +- Keep the existing FPU errata workaround. + +This is the highest-risk platform piece. Validate on `RAK_4631_repeater` and +at least one other nRF52 target. + +### 6.10 `examples/simple_repeater/main.cpp` — use the deadline + +Replace the sleep block with: + +```cpp + if (the_mesh.getNodePrefs()->powersaving_enabled && !the_mesh.hasPendingWork()) { + uint32_t sleep_ms = the_mesh.getSleepMs(); +#if defined(NRF52_PLATFORM) + if (sleep_ms) board.sleepMs(sleep_ms); + else board.sleep(0); +#else + if (the_mesh.millisHasNowPassed(POWERSAVING_FIRSTSLEEP_SECS * 1000)) { + if (sleep_ms) board.sleepMs(sleep_ms); + else board.sleep(30); + } +#endif + } +``` + +`MyMesh::getSleepMs()` returns 0 when radio2 is off/paused, so existing +behaviour is unchanged. When radio2 is scanning it returns a positive deadline +(see §9.7). + +--- + +## 7. Fork-owned files + +Create: + +- `examples/simple_repeater/Radio2Config.h` — constants, record, defaults. +- `examples/simple_repeater/Radio2.h/.cpp` — config, policy, scheduler, CLI, + persistence, status. +- `test/test_radio2/` — native tests. +- `RADIO2.md` — this document. + +Optional split if `Radio2.cpp` becomes too large: + +- `examples/simple_repeater/Radio2Timing.h/.cpp` — pure timing math. +- `examples/simple_repeater/Radio2Policy.h/.cpp` — pure policy classification. + +The runtime must be host-testable. Do not include `target.h` in the policy/timing +units. `Radio2.cpp` may `#include ` for `millis()` exactly as +`FleetManager.cpp` does; the native env supplies `test/mocks/Arduino.h` +(`g_mock_millis`). Use a `Radio2Device` interface: + +```cpp +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; +}; +``` + +`MyMesh` provides a tiny adapter over `radio_driver`: + +```cpp +class Radio2DeviceImpl : public Radio2Device { +public: + bool retune(float f, float bw, uint8_t sf, uint8_t cr, + bool abort_receive = false) override { + return radio_driver.retune(f, 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(); + } +}; +``` + +`Radio2` implements `RadioProfileControl`: + +```cpp +class Radio2 : public RadioProfileControl { +public: + bool selectTxProfile(uint8_t profile) override; + // ... +}; +``` + +`MyMesh` calls `radio_driver.setProfileControl(&radio2)` in `begin()`. + +--- + +## 8. Policy implementation + +### 8.1 Types + +```cpp +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, +}; +``` + +### 8.2 Crossable classification + +```cpp +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; + } +} +``` + +### 8.3 Effective action + +```cpp +Radio2Action Radio2::actionFor(uint8_t origin, const mesh::Packet* pkt) const { + Radio2Action configured = origin == RADIO_PROFILE_PRIMARY + ? policy_primary : policy_secondary; + if (!radio2Crossable(pkt) && configured != RADIO2_ACTION_DROP) { + return RADIO2_ACTION_SAME; + } + return configured; +} +``` + +### 8.4 Target profile + +```cpp +uint8_t Radio2::targetFor(Radio2Action action, uint8_t origin) const { + switch (action) { + case RADIO2_ACTION_SAME: return origin; + case RADIO2_ACTION_OTHER: return origin ^ 1; + case RADIO2_ACTION_BOTH: return origin; // copy gets origin ^ 1 + case RADIO2_ACTION_DROP: return origin; // unused + } + return origin; +} +``` + +### 8.5 `MyMesh::onRecvPacket` + +Add members to `MyMesh`: + +```cpp + uint8_t rx_profile = RADIO_PROFILE_PRIMARY; + Radio2Action rx_action = RADIO2_ACTION_SAME; + bool rx_forward_allowed = true; +``` + +Modify: + +```cpp +mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) { + 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(); + + // ... existing region selection ... + filter.clearContentVerdict(); + + 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 && radio2IsRetransmit(action)) { + radio2QueueDuplicate(pkt, action, rx_profile); + } + return action; +} +``` + +Helpers: + +```cpp +static bool radio2IsRetransmit(mesh::DispatcherAction action) { + return action != ACTION_RELEASE && action != ACTION_MANUAL_HOLD; +} + +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(); +} +``` + +`sendPacket()` validates and queues. The original is queued by +`Dispatcher::processRecvPacket()` after `onRecvPacket()` returns. + +### 8.6 `MyMesh::allowPacketForward` + +At the very top: + +```cpp +bool MyMesh::allowPacketForward(const mesh::Packet* packet) { + if (!rx_forward_allowed) { + radio2.notePolicyDrop(); + return false; + } + // ... existing fleet/battery/filter/stock checks ... +} +``` + +Rationale: a policy `drop` is a deliberate routing decision, not a battery or +filter drop. It is evaluated before the battery/filter gates and has its own +counter. The filter still sees group content in `onGroupDataRecv()`; it does not +see non-group packets that the policy drops. Document this in `RADIO2.md`. + +### 8.7 Counters + +`Radio2` exposes: + +- `notePrimaryPacket()` +- `noteRx(uint8_t profile)` +- `noteTx(uint8_t profile)` +- `noteBoth()` +- `noteBothDrop()` +- `notePolicyDrop()` +- `noteAbort()` +- `noteSwitch()` +- `noteSwitchFailure()` + +`MyMesh::logRx()` stamps and counts the scanner's current profile (see §12.7; +`logRx()` runs before `onRecvPacket()` sets the packet's RX profile). +`MyMesh::logTx()` calls `radio2.noteTx(pkt->getTxProfile())`. + +--- + +## 9. Scheduler + +### 9.1 Goals + +- Primary is the home profile. +- Primary traffic always wins. +- When primary is active, secondary gets a small share and may lose packets. +- When primary is idle, secondary gets the maximum share that still keeps + primary capture bounded. +- In idle mode, a secondary packet already in progress may finish. +- In active mode, a secondary packet in progress at the deadline is aborted + (RX abandoned; no partial TX). +- TX is never aborted; the scanner waits for it. + +### 9.2 Constants + +Put in `Radio2Config.h`: + +```cpp +#define RADIO2_ACTIVE_HOLD_MS 30000UL // primary active for 30 s after a packet +#define RADIO2_SWITCH_US 3000UL // one retune, conservative default +#define RADIO2_LOOP_MARGIN_US 2000UL // main-loop jitter allowance +#define RADIO2_MIN_VISIT_US 5000UL // avoid absurdly short visits +#define RADIO2_ACTIVE_SECONDARY_DIV 4U // active: primary visit = 4x secondary +#define RADIO2_HOLD_POLL_MS 5UL // idle hold re-check interval +#define RADIO2_SLEEP_MAX_MS 1000UL // cap one board sleep +#define RADIO2_APPLY_DELAY_MS 2000UL // deferred RF apply after CLI +#define RADIO2_MAX_SWITCH_FAILURES 10U +#define RADIO2_SWITCH_RETRY_MS 1000UL +#define RADIO2_OVERLAP_GUARD_KHZ 6.0f +``` + +`RADIO2_SWITCH_US` should be measured on hardware. A boot self-test is optional; +if implemented, use the measured maximum plus 10%, and report it in +`radio2 timing`. Until measured, 3000 us is the conservative default. + +### 9.3 Profile timing + +For a profile: + +```text +symbol_us = 2^SF * 1000 / BW_kHz +preamble_symbols = (SF <= 8) ? 32 : 16 +capture_us = capture_symbols * symbol_us +bound_us = (preamble_symbols - capture_symbols) * symbol_us + - 2 * switch_us - loop_margin_us +``` + +`capture_symbols` comes from +`radio_driver.rxPowerSavingCaptureCostSymbols()` (6 on SX126x, 8 on LR11x0). +`preamble_symbols` mirrors `RadioLibWrapper::preambleLengthForSF()`. + +Definitions: + +- `primary_capture_us` = minimum primary visit to latch a primary preamble. +- `secondary_capture_us` = minimum secondary visit to latch a secondary preamble. +- `primary_bound_us` = maximum secondary visit that still lets a primary + preamble survive to the next primary visit. +- `secondary_bound_us` = maximum primary visit that still lets a secondary + preamble survive to the next secondary visit. + +Validation: + +```text +secondary_capture_us <= primary_bound_us +primary_capture_us <= secondary_bound_us +``` + +If either fails, the preset pair cannot be scanned without risking primary. +Reject radio2 with a clear error and keep primary unchanged. + +Use `int64_t` for the multiplications; clamp to `uint32_t`. + +### 9.4 Active mode + +Trigger: `now - last_primary_packet_ms < RADIO2_ACTIVE_HOLD_MS`. + +```text +secondary_visit = max(secondary_capture_us, RADIO2_MIN_VISIT_US) +primary_visit = max(primary_capture_us, + RADIO2_ACTIVE_SECONDARY_DIV * secondary_visit) +``` + +If `primary_visit > secondary_bound_us`, secondary preambles will not survive +the primary visit. That is accepted in active mode: secondary only catches +packets that start during its visit. Mark `secondary_lossy = true` for status. + +Primary is protected: the secondary visit is at most `primary_bound_us` by +validation, and a primary packet in progress defers the visit. + +### 9.5 Idle mode + +Trigger: `now - last_primary_packet_ms >= RADIO2_ACTIVE_HOLD_MS`. + +```text +primary_visit = max(primary_capture_us, RADIO2_MIN_VISIT_US) +secondary_visit = primary_bound_us +``` + +This gives secondary the maximum safe share. Both capture bounds hold by +validation. For symmetric presets this is roughly 62% secondary / 38% primary; +for asymmetric presets it follows the bounds. + +If `secondary_visit < secondary_capture_us`, validation would have failed. + +### 9.6 State machine + +State: + +```cpp +enum Phase { PHASE_PRIMARY, PHASE_SECONDARY }; +Phase phase = PHASE_PRIMARY; +uint8_t current = RADIO_PROFILE_PRIMARY; +uint32_t phase_end_ms = 0; +uint32_t last_primary_packet_ms = 0; +bool paused = false; +bool pending_apply = false; +uint32_t pending_apply_at_ms = 0; +``` + +`begin()` sets `last_primary_packet_ms = millis()` so the node starts in active +mode for the first 30 s. + +`loop(fs, quiet)`: + +1. If (disabled or paused) and `!pending_apply`: if current != primary, + `switchTo(PRIMARY, false)`; return. (A complete packet is never abandoned; + the switch retries next loop.) `pending_apply` is excluded so a deferred + `radio2 off` still lets the command reply go out on the old secondary + config before the radio moves. +2. If `pending_apply` and `!paused` and `quiet` and `now >= pending_apply_at_ms`: + apply the saved config. If the current profile is secondary and the new + config is still enabled, retune it with `switchTo(SECONDARY, false, true)` + (force, because the profile number did not change but the RF tuple did). If + the new config is disabled and the current profile is secondary, switch to + primary. If the required retune succeeds, clear pending, set `phase` to + match `current`, and set `phase_end_ms` to the current mode's visit for that + profile; otherwise keep pending and retry. Return. +3. If `!device.isInRecvMode()`: return (TX or idle; wait for RX). +4. If `device.hasCompletedReceive()`: return (let core read it). +5. If `now < phase_end_ms`: return. +6. Compute mode and visits from `last_primary_packet_ms`. +7. If `phase == PHASE_PRIMARY`: + - If `device.isReceiveInProgress()`: defer; set `phase_end_ms = now + 1`; + return. Primary wins. + - `switchTo(SECONDARY, false)`; on success set phase secondary, + `phase_end_ms = now + secondary_visit`. +8. If `phase == PHASE_SECONDARY`: + - If `device.isReceiveInProgress()`: + - active mode: on `switchTo(PRIMARY, true)` success (abort RX), call + `noteAbort()`, set phase primary, `phase_end_ms = now + primary_visit`. + On failure, keep phase secondary and retry. + - idle mode: hold; set `phase_end_ms = now + RADIO2_HOLD_POLL_MS`; return. + - Else on `switchTo(PRIMARY, false)` success, set phase primary, + `phase_end_ms = now + primary_visit`. + +`switchTo(profile, abort_receive, force = false)`: + +```cpp +bool Radio2::switchTo(uint8_t profile, bool abort_receive, bool force = false) { + if (profile == current && !force) return true; + if (profile == RADIO_PROFILE_SECONDARY && !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)) { + noteSwitchFailure(); + return false; + } + current = profile; + noteSwitch(); + return true; +} +``` + +A `false` return from `switchTo()` is either "busy" (a packet is pending or in +progress) or a real retune failure. Busy retries next loop. A real failure sets +`phase_end_ms = millis() + RADIO2_SWITCH_RETRY_MS`; after +`RADIO2_MAX_SWITCH_FAILURES`, disable scanning (stay primary) and report +`error=switch` in status. A config change re-enables attempts. + +### 9.7 `getSleepMs()` + +`MyMesh::getSleepMs()` returns `radio2.getSleepMs()`. + +`Radio2::getSleepMs()`: + +- 0 if disabled or paused. +- 1 if `!device.isInRecvMode()`, `hasCompletedReceive()`, or + `isReceiveInProgress()` (wake soon; do not sleep through a packet). +- Otherwise `delta = phase_end_ms - now`; if `delta <= 0` return 1; else + `min(delta, RADIO2_SLEEP_MAX_MS)`. + +This is what lets `main.cpp` sleep between visits while the radio stays in RX. + +### 9.8 TX interaction + +- `selectTxProfile(profile)` is called by `Dispatcher::checkSend()` before TX. +- If `profile == current`, return true. +- If radio2 is off/paused and `profile == secondary`, fall back to primary and + return true (count fallback). +- If `hasCompletedReceive()` or `isReceiveInProgress()`, return false; the + dispatcher retries next loop. +- Otherwise `switchTo(profile, false)`; on success also set `phase` to match + `profile` and `phase_end_ms = millis() + ` so the + scanner does not immediately undo the TX retune. Return true. +- TX is never aborted by the scheduler. `Radio2::loop()` sees + `!isInRecvMode()` during TX and returns. +- After TX, the scanner resumes from the current profile; the next `loop()` + computes the next visit. Do not try to “catch up” missed visits. + +### 9.9 Primary activity + +`MyMesh::onRecvPacket()` calls `radio2.notePrimaryPacket()` when +`rx_profile == RADIO_PROFILE_PRIMARY`. This updates +`last_primary_packet_ms` for every parsed primary packet, including packets the +filter or policy later drops. + +A primary packet in progress at a secondary visit deadline defers the visit. +A primary packet that arrives during a secondary visit is not heard; the visit +bound ensures its preamble survives to the next primary visit. + +### 9.10 Idle hold tradeoff + +In idle mode, a secondary packet in progress at the visit deadline is allowed +to finish. This can extend primary blind time beyond `primary_bound_us`. It is +the only way to receive long secondary packets. The 30 s idle threshold makes +it rare. If a primary packet arrives during the hold, it can be missed. This is +the explicit tradeoff for “secondary should not drop when primary is idle.” + +If strict primary protection is ever required, add a `radio2 strict` option +that disables the idle hold. Do not make it the default. + +--- + +## 10. Persistence + +### 10.1 File + +`/radio2_cfg`, version 1, CRC-16 over the payload, staged save, `.bak` recovery. + +### 10.2 Record + +```cpp +#define RADIO2_CFG_FILE "/radio2_cfg" +#define RADIO2_CFG_VERSION 1 +#define RADIO2_CFG_MAGIC "R2CF" + +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) == 20, + "Radio2CfgRecord payload is frozen at 20 B"); +#define RADIO2_CFG_PAYLOAD_BYTES 20 +#define RADIO2_CFG_RECORD_BYTES 22 // payload + 2 B CRC-16 +``` + +Field order is deliberate: the byte fields come before the floats so there is +only one padding byte and the size is 20. Do not reorder without a version bump. + +### 10.3 Validation + +`radio2ValidateFile(File&, void*)`: + +- read exactly `RADIO2_CFG_RECORD_BYTES`; +- magic == `R2CF`; +- version == 1; +- enabled <= 1; +- policy values <= 3; +- advert <= 1; +- sf 5..12, cr 5..8; +- freq/bw finite and in the accepted range; +- CRC matches. + +`load()`: + +- reset to defaults (off, same/same, advert primary, preset zero); +- `chooseConfigToLoad()`; +- if recovered from `.bak`, mark dirty for a repair save; +- if invalid, keep defaults. + +`save()`: + +- `saveStaged()` with write/validate callbacks; +- clear `LazySave` only on success; `retryLater()` on failure. + +### 10.4 Defaults + +```cpp +enabled = 0; +policy_primary = RADIO2_ACTION_SAME; +policy_secondary = RADIO2_ACTION_SAME; +advert = RADIO2_ADVERT_PRIMARY; +freq_mhz = 0; bw_khz = 0; sf = 0; cr = 0; +``` + +`set radio2 off` keeps the preset and policy; only `enabled` changes. + +### 10.5 Future versions + +Append new fields after `bw_khz` and bump `RADIO2_CFG_VERSION`; keep the v1 +prefix byte-identical. Add migration in `load()`. Add a `static_assert` for the +new size. + +--- + +## 11. CLI + +### 11.1 Dispatch + +In `MyMesh::handleCommand()`, before `_cli.handleCommand()`: + +```cpp +else if (memcmp(command, "radio2", 6) == 0 && + (command[6] == 0 || command[6] == ' ')) { + const char* sub = command + 6; + while (*sub == ' ') sub++; + radio2CLI(radio2, sub, reply); +} +``` + +The command is the bare `radio2` verb, matching `filter`/`battery`/`fleet`. +There is deliberately no `get radio2` / `set radio2` alias: one parser, one +surface. + +### 11.2 Commands + +```text +radio2 +radio2 status +radio2 timing +radio2 ,,, +radio2 off +radio2 policy +radio2 policy [] +radio2 advert primary|both +``` + +- `radio2` with no args = status. +- `radio2 policy` with no args = current policy. +- `radio2 policy X` sets both origins to X. +- `radio2 policy X Y` sets primary=X, secondary=Y. +- `radio2 advert` with no args = current advert policy. +- `radio2 ` enables radio2 and sets the preset. +- `radio2 off` disables radio2, keeps the preset. + +### 11.3 Replies + +Set: + +```text +OK - radio2 910.525,125,10,5 +OK - radio2 off +OK - radio2 policy primary=same,secondary=other +OK - radio2 advert both +``` + +Value readouts use the same bare form as the other fork CLIs. + +Policy (`radio2 policy`): + +```text +primary=same,secondary=same +``` + +Advert (`radio2 advert`): + +```text +primary +``` + +Status (`radio2` or `radio2 status`, one line, bounded by `CLI_REPLY_MAX`): + +```text +on; at=radio2; mode=idle; split=38/62; nf=-117; sw=12; swf=0; rx=4/9; tx=1/6; both=0; bdrop=0; drop=0; abrt=0 +``` + +`mode=active; lossy` marks an active-mode primary visit long enough that a +secondary preamble would not survive it. + +When off: + +```text +off +``` + +When a conflict prevents start: + +```text +off; conflict=radio.rxps +``` + +When a change is pending: + +```text +on; apply=pending; at=primary +``` + +Timing: + +```text +primary=49ms; secondary=82ms; split=38/62; switch=3ms; mode=idle +``` + +If unusable: + +```text +unusable: secondary capture 49ms > primary-safe 20ms +``` + +### 11.4 Errors + +Keep replies short and actionable: + +```text +Err - usage: radio2 | radio2 status | radio2 timing | radio2 ,,, | radio2 off | radio2 policy [ []] | radio2 advert primary|both +Err - radio2 preset must be ,,, +Err - radio2 policy must be same|other|both|drop +Err - radio2 advert must be primary|both +Err - radio2 overlaps radio +Err - radio2 preset cannot be scanned without degrading radio +Err - radio.rxps is on; set radio.rxps off first +Err - radio2 is on; set radio2 off first +Err - radio2 conflicts with extra.sf; clear extra SF first +Err - tempradio active; wait for it to revert +``` + +The usage line may exceed 157 bytes; if so, shorten it or split the command +surface into a short usage plus `radio2 status` details. Never write past +`CLI_REPLY_MAX`. + +### 11.5 Parsing + +Use `CliUtil.h`: + +- `cliPrepare()` for quote balance and command length; +- `nextToken()` for subcommands; +- `mesh::Utils::parseTextParts()` for the comma tuple; +- `parseIntRange()` for SF/CR; +- `strtof()` with an end pointer for freq/bw, rejecting trailing bytes and + non-finite values. + +Validation ranges match `set radio`: + +- freq 150..2500 MHz +- bw 7..500 kHz +- sf 5..12 +- cr 5..8 + +Reject a preset that overlaps the primary: + +```text +abs(freq2 - freq1) < (bw1 + bw2) / 2 + RADIO2_OVERLAP_GUARD_KHZ +``` + +Reject if the timing validation in §9.3 fails. + +### 11.6 Deferred apply + +`set radio2` / `radio2 off` persist immediately but defer the RF change: + +- set `pending_apply = true`, `pending_apply_at_ms = millis() + RADIO2_APPLY_DELAY_MS`; +- `Radio2::loop(fs, quiet)` applies when `quiet` is true and the deadline has + passed; +- `quiet` is `_mgr->getOutboundTotal() == 0` from `MyMesh::loop()`; +- this lets a remote admin on the secondary profile receive the command reply + on the old secondary config before the radio changes. + +`radio2 policy` and `radio2 advert` do not change RF; apply immediately. + +### 11.7 RXPS conflict dispatch + +In `MyMesh::handleCommand()`, before `_cli.handleCommand()`: + +```cpp +else if (radio2.isEnabled() && + memcmp(command, "set radio.rxps ", 15) == 0 && + strncmp(command + 15, "off", 3) != 0) { + strcpy(reply, "Err - radio2 is on; set radio2 off first"); +} +``` + +`set radio.rxps off` and `get radio.rxps` continue to the core. + +`radio2CLI` checks `_prefs.rxps.enabled` before enabling/setting a preset and +replies with the RXPS error. + +--- + +## 12. `MyMesh` integration + +### 12.1 Members + +Add to `MyMesh.h`: + +```cpp + Radio2DeviceImpl radio2_device; + Radio2 radio2; + bool rx_forward_allowed = true; // read by allowPacketForward() +``` + +`radio2_device` must be declared before `radio2` so it is constructed first. +`rx_profile` / `rx_action` are locals in `onRecvPacket()`: only the forwarding +decision has to outlive the packet (`allowPacketForward()` reads it). + +### 12.2 `begin()` + +Order: + +1. `mesh::Mesh::begin()` (existing). +2. `_fs = fs`. +3. `_cli.loadPrefs(_fs)` (primary + RXPS loaded). +4. `radio2.begin(_fs, &_prefs)` (load `/radio2_cfg`, validate, do not start). +5. `radio_driver.setProfileControl(&radio2)`. +6. existing `acl/filter/battGate/fleet/meshClock/region` loads. +7. `radio_driver.setParams(primary)` and `powerApplyRadioProfile`. +8. `radio2.setPrimary(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr)`. +9. `radio2.start()` (if enabled and no conflict; sets current primary and + `last_primary_packet_ms = millis()`). + +If `radio2.start()` finds a conflict (RXPS, extra_sf, overlap, timing), it +leaves runtime off and records the reason. Primary is untouched. + +### 12.3 `loop()` + +After `mesh::Mesh::loop()` and before adverts: + +```cpp + radio2.loop(_fs, _mgr->getOutboundTotal() == 0); +``` + +Then existing adverts/temp radio/saves/fleet. The scanner may retune to +secondary; local send hooks below force the correct profile. + +### 12.4 `handleCommand()` + +Add the `radio2` dispatch and the RXPS conflict check from §11. + +### 12.5 `onRecvPacket()` + +Implement §8.5. + +### 12.6 `allowPacketForward()` + +Implement §8.6. + +### 12.7 `logRx()` / `logTx()` + +`logRx()` runs in `Dispatcher::checkRecv()` **before** `onRecvPacket()`, so the +packet's RX profile has not been set yet. Use the scanner's current profile, +which is the profile `recvRaw()` just read from, and stamp it on the packet so +the observer and later hooks see it: + +```cpp +void MyMesh::logRx(mesh::Packet* pkt, int len, float score) { + const uint8_t rx = radio2.currentProfile(); + pkt->setRxProfile(rx); + radio2.noteRx(rx); + // ... existing ... +} + +void MyMesh::logTx(mesh::Packet* pkt, int len) { + radio2.noteTx(pkt->getTxProfile()); + // ... existing ... +} +``` + +`onRecvPacket()` re-stamps `pkt->setRxProfile(rx_profile)`; the two values must +agree. `logTxFail()` may also call `noteTx` if desired; not required. + +### 12.8 Adverts + +Modify `MyMesh::sendSelfAdvertisement()`: + +- create the advert packet as today; +- send it on primary (default target 0); +- if `radio2.advertBoth()`, create a copy with `obtainNewPacket()`, copy the + packet, set target secondary, and send it with the same flood/zero-hop path. + +For flood: + +```cpp +mesh::Packet* pkt = createSelfAdvert(); +if (pkt) { + sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); + if (radio2.advertBoth()) { + mesh::Packet* copy = obtainNewPacket(); + if (copy) { + *copy = *pkt; // pkt has already been sent/released? See note. + copy->setTxProfile(RADIO_PROFILE_SECONDARY); + sendFloodScoped(default_scope, copy, delay_millis, _prefs.path_hash_mode + 1); + } + } +} +``` + +Important: `sendFloodScoped()` queues the packet; it does not release it +immediately. The packet is still valid until the dispatcher sends it. Copy +before or after queueing is fine as long as the pointer is valid. To avoid +aliasing, create the copy **before** sending the first packet: + +```cpp +mesh::Packet* pkt = createSelfAdvert(); +if (!pkt) return; +mesh::Packet* copy = nullptr; +if (radio2.advertBoth()) { + copy = obtainNewPacket(); + if (copy) *copy = *pkt; +} +sendFloodScoped(default_scope, pkt, delay_millis, ...); +if (copy) { + copy->setTxProfile(RADIO_PROFILE_SECONDARY); + sendFloodScoped(default_scope, copy, delay_millis, ...); +} +``` + +For zero-hop, use `sendZeroHop()` similarly. + +`sendNodeDiscoverReq()` is a control request, not an advert; leave primary. + +### 12.9 Fleet replies + +`FleetSendFn` gains a profile argument: + +```cpp +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 radio_profile, uint8_t* out_pkt_hash); +``` + +`MyMesh::fleetReplySend()` sets `pkt->setTxProfile(radio_profile)` before +`sendFleetReply(pkt)`. + +`FleetManager` changes: + +- `FleetSched` add `uint8_t radio_profile;` +- `FleetReply` add `uint8_t radio_profile;` +- `CliPendingScript` add `uint8_t radio_profile;` +- `CliRunResult` add `uint8_t radio_profile;` +- `CliScriptRunner::enqueue(..., uint8_t radio_profile = RADIO_PROFILE_PRIMARY)` +- `CliScriptRunner::enqueueValidated(..., uint8_t radio_profile)` +- `CliScriptRunner::run()` copies `slot->radio_profile` to `out->radio_profile`. +- `FleetManager::onGroupData()` passes `packet->getRxProfile()` to + `enqueue`/`admitScheduled`. +- `admitScheduled()` stores it in `FleetSched`. +- `runScripts()` passes `sched[i].radio_profile` to `enqueueValidated`. +- `scheduleAckIfNeeded()` copies `res.radio_profile` to `FleetReply`. +- `serviceReplies()` passes `r.radio_profile` to `send_fn`. +- `sendAlert()` passes `RADIO_PROFILE_PRIMARY` (unsolicited alert). + +This keeps fleet acknowledgements on the profile the script arrived on, even +after a `!delay` or `!at` wait. + +### 12.10 Temp radio + +In `MyMesh::loop()`: + +- before applying `set_radio_at`: `radio2.pauseForPrimaryChange();` +- after `radio_driver.setParams(pending...)`: `radio2.setPrimary(pending...)`; +- before/after revert: `radio2.setPrimary(_prefs...)`; +- after revert: `radio2.resumeAfterPrimaryChange();` + +`pauseForPrimaryChange()` stops scanning and retunes primary if needed. +`resumeAfterPrimaryChange()` revalidates the secondary against the new primary; +if invalid, disables runtime and reports. + +`set radio2` while `set_radio_at`/`revert_radio_at` is pending: reject with +`Err - tempradio active; wait for it to revert`. + +### 12.11 `hasPendingWork()` / `getSleepMs()` + +`hasPendingWork()` stays as today (bridge, observer, outbound). Do **not** add +radio2 scanning to it; otherwise powersaving never sleeps. + +Add: + +```cpp +uint32_t MyMesh::getSleepMs() { + return radio2.getSleepMs(); +} +``` + +Declare in `MyMesh.h`. + +### 12.12 Status noise floor + +`radio2CLI` needs the current noise floor. Pass it from `MyMesh`: + +```cpp +radio2CLI(radio2, _radio->getNoiseFloor(), sub, reply); +``` + +or expose it through `Radio2Device::getNoiseFloor()` and let `Radio2` read it. +The latter keeps the CLI signature simple. + +--- + +## 13. Conflicts and capabilities + +### 13.1 RXPS + +- radio2 refuses to start if `_prefs.rxps.enabled`. +- `set radio2` refuses if RXPS enabled. +- `set radio.rxps on/...` refuses if radio2 enabled. +- `set radio.rxps off` allowed. +- If both persisted, radio2 off; primary RXPS runs; status reports conflict. + +### 13.2 `extra.sf` side detectors + +If `_prefs.extra_sf[0] != 0`, radio2 refuses to start and `set radio2` refuses. +Side detectors are primary-only in v1. Clear them with the core command before +enabling radio2. + +### 13.3 `tempradio` + +Pause radio2 while a temporary primary is active. Revalidate on revert. + +### 13.4 `set radio` (primary) + +`set radio` only takes effect on reboot. At boot, validate the secondary +against the new primary. If it overlaps or is unscannable, radio2 stays off and +reports the reason. Do not modify the primary to accommodate radio2. + +### 13.5 `cad` / `int.thresh` + +`cad` works because `selectTxProfile()` runs before `checkSend()`'s channel +check. `int.thresh` uses the shared noise floor; it may be approximate while +scanning. No per-profile floor in v1. + +### 13.6 `powersaving` + +Allowed and required. `getSleepMs()` provides the deadline. If `powersaving` +is off, radio2 polls; higher power, still correct. + +### 13.7 Bridge / MQTT observer + +No special handling. The observer captures both profiles; `Packet::getRxProfile()` +is available if a future schema wants it. Bridge traffic is local; primary +unless a future policy says otherwise. + +### 13.8 Battery / fleet + +Battery gate and fleet hooks are unchanged. Policy `drop` is evaluated before +the battery/filter gates; fleet `onGroupData` still runs. Fleet replies use the +captured origin profile. + +--- + +## 14. Filter phase 2 (not v1) + +v1: filters apply to both profiles equally. + +Phase 2: add a per-rule origin predicate. + +- `FilterRule` has a reserved byte at offset 187, format-guaranteed zero in v7. +- Bump `FILTER_CFG_VERSION` to 8 and use that byte as `radio_mask`: + - bit 0 = primary + - bit 1 = secondary + - 0 = any (default) +- v7 migration sets `radio_mask = 0`. +- `checkPacket()` and `checkContent()` already receive the `Packet*`; read + `pkt->getRxProfile()` and match the mask. No signature change. +- CLI: `filter add radio=any|primary|secondary ...`; `filter get` renders it. +- Default rules (no `radio=`) apply to both. +- A filter rule cannot override the capability rules: direct/ACK/unicast flood + DMs still cannot cross. +- Add tests for v7→v8 migration, roundtrip, CLI, and matching. + +Do not fold this into v1; it is a persisted-layout change and needs its own +migration/tests. + +--- + +## 15. Upstream diff map + +Keep these edits minimal and generic. + +| File | Change | +|---|---| +| `src/Packet.h` | one profile byte, accessors, `static_assert(sizeof==260)` | +| `src/Dispatcher.h` | `peekNextOutbound`, `selectTxProfile`, `_default_tx_profile` + accessors | +| `src/Dispatcher.cpp` | `checkSend` peek/select; `obtainNewPacket` tags | +| `src/helpers/StaticPoolPacketManager.h/.cpp` | `peek`; reset profile byte on free | +| `src/helpers/radiolib/RadioProfileControl.h` | new interface | +| `src/helpers/radiolib/RadioLibWrappers.h/.cpp` | control pointer, `selectTxProfile`, `retune`, `hasCompletedReceive`, `isReceiveInProgress` | +| `src/MeshCore.h` | `MainBoard::sleepMs` | +| `src/helpers/ESP32Board.h` | `sleepMs` via common `sleepUs` | +| `src/helpers/NRF52Board.cpp/.h` | `sleepMs` timed wake | +| `examples/simple_repeater/main.cpp` | use `getSleepMs()` | +| `examples/simple_repeater/MyMesh.h/.cpp` | radio2 member, begin/loop/CLI, receive policy, duplicate, replies, adverts, temp radio, sleep | +| `test/test_empty_contact_slots/test_empty_contact_slots.cpp` | `DummyPacketManager::peekNextOutbound` | + +Behaviour-neutral requirements: + +- `selectTxProfile()` default returns true. +- `peekNextOutbound()` returns the same packet `getNextOutbound()` would. +- `_default_tx_profile` defaults 0. +- `Packet` profile byte is ignored by `writeTo`/`readFrom`/hash. +- `sleepMs()` default falls back to `sleep()`. +- Existing native suites must pass unchanged. + +Add a merge-playbook row to `AGENTS.md` only after the user approves; do not +edit `AGENTS.md` as part of the implementation without asking. + +--- + +## 16. Implementation order + +1. **Core enabler** + - `Packet` byte + static assert. + - `PacketManager::peekNextOutbound` + `PacketQueue::findBest`. + - `Radio::selectTxProfile` + `Dispatcher::checkSend` peek/select. + - `Dispatcher::default_tx_profile` + `obtainNewPacket`. + - `StaticPoolPacketManager::free` reset. + - Update `DummyPacketManager`. + - Run existing native suites; prove behaviour-neutral. + +2. **Radio2 config/persistence/CLI** + - `Radio2Config.h`, record, CRC, staged save. + - `Radio2` skeleton, `Radio2Device` interface, `RadioProfileControl`. + - CLI parsing/status/timing. + - Native tests for config/CLI/persistence. + +3. **Policy and replies** + - `actionFor`, `targetFor`, crossable classification. + - `MyMesh::onRecvPacket` tagging, `allowPacketForward` drop, duplicate. + - `default_tx_profile` reply routing. + - Fleet origin profile plumbing. + - Advert `both`. + - Native tests for policy matrix, duplicate, reply tags. + +4. **Scheduler** + - Timing math, active/idle modes, state machine. + - `RadioLibWrapper::retune`, `selectTxProfile`. + - `MyMesh::loop` call, temp radio pause. + - Native tests for timing/state transitions with a fake device. + +5. **Powersaving** + - `MainBoard::sleepMs`, ESP32/nRF52. + - `main.cpp` deadline. + - `getSleepMs`. + - On-target validation. + +6. **Filter phase 2** (separate change) + - v8 `radio_mask`, migration, CLI, tests. + +7. **Docs** + - `RADIO2.md` user manual sections (this document can be split into design + and user manual if desired). + - Update `AGENTS.md` only with approval. + +--- + +## 17. Test plan + +### 17.1 Native `native_radio2` + +Add a PlatformIO env modeled on `native_fleet`: + +```ini +[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> + +<../examples/simple_repeater/Radio2.cpp> + +<../examples/simple_repeater/Radio2Timing.cpp> + +<../examples/simple_repeater/Radio2Policy.cpp> +lib_deps = + google/googletest @ 1.17.0 +``` + +Add `native_radio2_san` with ASan+UBSan. + +Test cases: + +**Packet/core** +- `sizeof(mesh::Packet) == 260`. +- `getTxProfile`/`setTxProfile`/`getRxProfile`/`setRxProfile` bit isolation. +- `writeTo`/`readFrom` do not carry the profile byte. +- `calculatePacketHash` ignores the profile byte. +- `PacketQueue::peek` returns the same packet `get` would, without removing. +- `Dispatcher::checkSend` calls `selectTxProfile` before `getEstAirtimeFor` + and `isReceiving` (fake radio records order). +- `selectTxProfile` false leaves the packet queued. +- `obtainNewPacket` applies `default_tx_profile`. +- `StaticPoolPacketManager::free` resets the profile byte. + +**Policy** +- For each origin and action, `actionFor`/`targetFor` produce the expected + target. +- Non-crossable packets with `other`/`both` fall back to `same`. +- `drop` remains `drop` for non-crossable packets. +- Crossable classification: advert, group text flood, group data flood; + direct/ACK/unicast flood DM not crossable. +- `both` duplicate: same priority/delay, target other, original target origin. +- Pool exhaustion: duplicate dropped, original still queued, counter increments. +- Policy drop: `allowPacketForward` false, counter increments, filter/battery + not consulted. + +**Replies** +- `default_tx_profile` set to origin during `Mesh::onRecvPacket`; restored after. +- Core ACK created during receive gets origin target. +- Fleet reply stores origin through `!delay`/`!at` and sends on it. +- Advert `both` creates two packets with targets 0 and 1. + +**Timing** +- Symbol/preamble/capture math for known presets. +- Active mode: primary 4x secondary, secondary lossy flag when applicable. +- Idle mode: primary capture floor, secondary max safe, both bounds hold. +- Invalid pairs rejected: secondary capture > primary bound, primary capture > + secondary bound, fast presets. +- Asymmetric presets. +- `millis()` wrap in phase deadlines. +- `getSleepMs` returns 1 when a packet is pending/in progress, 0 when off, + bounded by `RADIO2_SLEEP_MAX_MS`. + +**Scheduler state** +- Fake device: primary -> secondary -> primary transitions. +- Primary packet in progress defers secondary visit. +- Active mode aborts secondary in-progress packet at deadline. +- Idle mode holds secondary in-progress packet. +- TX (`isInRecvMode` false) blocks switching. +- Switch failure retries and eventually disables. +- `last_primary_packet_ms` updates on primary receive; mode changes after 30 s. + +**Persistence** +- v1 roundtrip. +- Truncated file rejected. +- Bad magic/version/CRC rejected. +- `.bak` recovery and repair save. +- Disabled with saved preset retains preset. +- `static_assert` record size. + +**CLI** +- `radio2` status off/on/conflict/pending. +- `radio2 ` valid/invalid/overlap/unscannable. +- `radio2 off`. +- `radio2 policy` one/two args, invalid. +- `radio2 advert`. +- `radio2 timing`. +- RXPS conflict both directions. +- `extra.sf` conflict. +- Reply length <= `CLI_REPLY_MAX`. +- `get radio2`/`set radio2` aliases if implemented. + +### 17.2 Existing suites + +Run unchanged: + +```sh +pio test -e native -e native_kiss_modem -e native_packet_filter \ + -e native_battery_gate -e native_fleet -e native_fleet_noack \ + -e native_mesh_clock -e native_rx_power_saving -e native_mqtt_observer +``` + +Plus `native_radio2` and `native_radio2_san`. + +Clean native envs after changing `Packet`/`NativeShim` structs: + +```sh +pio run -e native_packet_filter -t clean +pio run -e native_radio2 -t clean +``` + +### 17.3 Firmware compile + +Compile-check every filesystem family: + +```sh +bash build.sh build-firmware Xiao_S3_WIO_repeater +bash build.sh build-firmware RAK_4631_repeater +bash build.sh build-firmware PicoW_repeater +bash build.sh build-firmware wio-e5_repeater +``` + +Also compile an LR2021 target if available (side detectors/`setParams` path). +Check flash/RAM against the baseline in `opportunities.md`; the STM32 target is +the tightest. + +### 17.4 On-air validation + +- Two transmitters, one on each preset. +- `same/same`: each network repeats on its own profile; no cross. +- `other/same`: one-way bridge for broadcast flood only. +- `both`: duplicate broadcast flood; no duplicate loops. +- `drop`: no TX on that origin. +- Direct/ACK/unicast flood DM: never cross. +- Replies: remote CLI from secondary gets its reply on secondary. +- Advert `both`: node visible on both. +- RXPS conflict: both commands refuse with clear errors. +- Powersaving: `get radio2 status` shows scanning; measure current and confirm + the MCU sleeps between visits; verify no missed scan deadlines. +- `cad` on: TX checks the selected profile. +- `tempradio`: radio2 pauses and resumes. +- Long secondary packet: active mode aborts; idle mode finishes. +- Primary traffic: secondary visits defer/skip; primary remains reliable. + +--- + +## 18. Defaults and constants + +| Setting | Default | +|---|---| +| radio2 enabled | off | +| policy primary | same | +| policy secondary | same | +| advert | primary | +| replies | origin (fixed) | +| filters | both (v1) | +| RXPS | must be off | +| powersaving | allowed | +| active hold | 30 s | +| switch time | 3 ms (measure) | +| loop margin | 2 ms | +| active secondary share | 1/5 (primary visit = 4x secondary) | +| idle mode | max safe secondary | +| sleep cap | 1000 ms | +| apply delay | 2000 ms | +| overlap guard | 6 kHz | + +--- + +## 19. Risks and open items + +1. **nRF52 timed wake** is the highest-risk piece. Validate on hardware; keep a + correct fallback if the timer cannot be armed. +2. **Retune time** varies by radio family/board. Measure; the 3 ms default is + conservative. A boot self-test is optional. +3. **Idle hold** can miss a primary packet after a long primary silence. This is + the explicit tradeoff for long secondary packets. A future `radio2 strict` + can disable it. +4. **Cross-profile broadcast flood** can create duplicate traffic if multiple + bridges use `both`. Dedup/hop limits bound loops; recommend one-way `other` + or a single bridge. +5. **STM32 flash** is already exhausted on `wio-e5_repeater` in the upstream + tree: the baseline overflows `FLASH` by 184 bytes before this feature is + added. Per the repo rule, an upstream-failing target is not patched as part + of a fork change; the release ships without that asset. The other required + filesystem families (`Xiao_S3_WIO_repeater`, `RAK_4631_repeater`, + `PicoW_repeater`) compile with radio2. If that target's flash is ever fixed, + radio2 fits the same way it does on the others — no build flag is compiled + in today. +6. **Upstream sync** now touches `Packet`, `Dispatcher`, `StaticPool`, + `RadioLibWrappers`, `MainBoard`, and board files. Keep the edits generic and + behaviour-neutral; add a merge-playbook row only with approval. +7. **No per-profile noise floor** means `int.thresh` is approximate while + scanning. Accepted; status shows the shared value. +8. **Filter phase 2** is a separate persisted-layout change; do not mix it into + the radio2 core change. + +--- + +## 20. Acceptance criteria + +The feature is done when: + +- radio2 can be enabled with its own preset and config file; +- primary remains the default and is protected under traffic; +- secondary gets the maximum safe share when primary is idle; +- powersaving works with radio2 on nRF52 and ESP32; +- RXPS and radio2 cannot both be enabled; +- policy `same/other/both/drop` works per origin; +- only broadcast flood crosses profiles; +- direct/ACK/unicast flood DMs stay on origin; +- replies go to the origin profile; +- adverts can be primary-only or both; +- filters apply to both profiles equally; +- all existing native suites pass unchanged; +- `native_radio2` and sanitizer suites pass; +- the four required firmware targets compile; +- on-air tests confirm the policy and powersaving behaviour; +- `RADIO2.md` documents the user-facing commands and the tradeoffs. diff --git a/examples/simple_repeater/CliScript.cpp b/examples/simple_repeater/CliScript.cpp index c0233bd9..8a930c58 100644 --- a/examples/simple_repeater/CliScript.cpp +++ b/examples/simple_repeater/CliScript.cpp @@ -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--; diff --git a/examples/simple_repeater/CliScript.h b/examples/simple_repeater/CliScript.h index 6b5f81f3..9e2b219e 100644 --- a/examples/simple_repeater/CliScript.h +++ b/examples/simple_repeater/CliScript.h @@ -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. diff --git a/examples/simple_repeater/FleetManager.cpp b/examples/simple_repeater/FleetManager.cpp index d6b5f146..9aa25136 100644 --- a/examples/simple_repeater/FleetManager.cpp +++ b/examples/simple_repeater/FleetManager.cpp @@ -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 diff --git a/examples/simple_repeater/FleetManager.h b/examples/simple_repeater/FleetManager.h index b7bbe728..21f5c99b 100644 --- a/examples/simple_repeater/FleetManager.h +++ b/examples/simple_repeater/FleetManager.h @@ -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; diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 86050b02..12c7026e 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -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) diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 775bff99..1f781112 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -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) diff --git a/examples/simple_repeater/Radio2.cpp b/examples/simple_repeater/Radio2.cpp new file mode 100644 index 00000000..4005793b --- /dev/null +++ b/examples/simple_repeater/Radio2.cpp @@ -0,0 +1,774 @@ +// Radio2.cpp — second radio preset: config, policy, scheduler and CLI. +// Fork-owned; see RADIO2.md. + +#include "Radio2.h" + +#include +#include + +#include + +#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|,,,|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 ,,,"); + 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 ,,,"); + 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 ,,,"); + 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 ,,,"); + 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); +} + diff --git a/examples/simple_repeater/Radio2.h b/examples/simple_repeater/Radio2.h new file mode 100644 index 00000000..7b2998cc --- /dev/null +++ b/examples/simple_repeater/Radio2.h @@ -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 +#include + +#include +#include + +#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 diff --git a/examples/simple_repeater/Radio2Config.h b/examples/simple_repeater/Radio2Config.h new file mode 100644 index 00000000..9216e7d5 --- /dev/null +++ b/examples/simple_repeater/Radio2Config.h @@ -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 + +#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 diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index d475b13d..953af62b 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -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 } diff --git a/platformio.ini b/platformio.ini index 2df12313..bad4afd8 100644 --- a/platformio.ini +++ b/platformio.ini @@ -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 diff --git a/src/Dispatcher.cpp b/src/Dispatcher.cpp index c0610b7f..cad67477 100644 --- a/src/Dispatcher.cpp +++ b/src/Dispatcher.cpp @@ -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; } diff --git a/src/Dispatcher.h b/src/Dispatcher.h index aad6cba3..172ca492 100644 --- a/src/Dispatcher.h +++ b/src/Dispatcher.h @@ -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; } diff --git a/src/MeshCore.h b/src/MeshCore.h index b9cfb418..1ad0be50 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -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; diff --git a/src/Packet.h b/src/Packet.h index c19d9e9d..86cccf70 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -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"); + } diff --git a/src/helpers/ESP32Board.h b/src/helpers/ESP32Board.h index cd274cd9..2033f658 100644 --- a/src/helpers/ESP32Board.h +++ b/src/helpers/ESP32Board.h @@ -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) diff --git a/src/helpers/NRF52Board.cpp b/src/helpers/NRF52Board.cpp index f2fa7743..f987a3fe 100644 --- a/src/helpers/NRF52Board.cpp +++ b/src/helpers/NRF52Board.cpp @@ -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; diff --git a/src/helpers/NRF52Board.h b/src/helpers/NRF52Board.h index 43944b5f..478327af 100644 --- a/src/helpers/NRF52Board.h +++ b/src/helpers/NRF52Board.h @@ -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 diff --git a/src/helpers/StaticPoolPacketManager.cpp b/src/helpers/StaticPoolPacketManager.cpp index 8a8eefe8..fcbe174e 100644 --- a/src/helpers/StaticPoolPacketManager.cpp +++ b/src/helpers/StaticPoolPacketManager.cpp @@ -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"); } diff --git a/src/helpers/StaticPoolPacketManager.h b/src/helpers/StaticPoolPacketManager.h index f63700e5..33e25b06 100644 --- a/src/helpers/StaticPoolPacketManager.h +++ b/src/helpers/StaticPoolPacketManager.h @@ -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; diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index 14bc1b4f..27626035 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -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; +} diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 509d9dd0..3f65fa22 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -4,6 +4,7 @@ #include // PowerSaving variant #include "RXPowerSaving.h" +#include "RadioProfileControl.h" #ifdef USE_CC310_HW_CRYPTO #include @@ -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); diff --git a/src/helpers/radiolib/RadioProfileControl.h b/src/helpers/radiolib/RadioProfileControl.h new file mode 100644 index 00000000..f57f1665 --- /dev/null +++ b/src/helpers/radiolib/RadioProfileControl.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +// 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; +}; diff --git a/test/test_empty_contact_slots/test_empty_contact_slots.cpp b/test/test_empty_contact_slots/test_empty_contact_slots.cpp index cb4d5912..fdc6e81a 100644 --- a/test/test_empty_contact_slots/test_empty_contact_slots.cpp +++ b/test/test_empty_contact_slots/test_empty_contact_slots.cpp @@ -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; } diff --git a/test/test_fleet/test_fleet.cpp b/test/test_fleet/test_fleet.cpp index 2a98df6f..e5c34ec8 100644 --- a/test/test_fleet/test_fleet.cpp +++ b/test/test_fleet/test_fleet.cpp @@ -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. diff --git a/test/test_radio2/test_radio2.cpp b/test/test_radio2/test_radio2.cpp new file mode 100644 index 00000000..50e93429 --- /dev/null +++ b/test/test_radio2/test_radio2.cpp @@ -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 + +#include + +#include +#include + +#include + +#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 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 ,,,"); + + 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(); +}