mirror of
https://github.com/jhuebert/MeshCore.git
synced 2026-12-03 19:04:19 +00:00
feat: add ham mode with per-packet TX power and station ID (#16)
* feat: add ham mode with per-packet TX power and station ID Adapted from NebraskaMesh/MeshCore-Ham by KF0WXX and the Nebraska Mesh community (MIT licensed), whose original implementation is commit 6e716038. The public/private classification model, hardcoded Public key and hashtag derivation, activation gate, per-packet TX power hook, command names and counters come from that work. This is a rewrite into the repeater-filter architecture, not a copy. Adds a fork-owned HamMode to the repeater. Publicly readable traffic uses the new 'ham tx' power; encrypted traffic keeps using 'set tx'. The gate requires ham on, a callsign, and that callsign as a whole word in the node name. A timer-driven zero-hop advert identifies the station at least every 10 minutes. Settings persist in /ham_cfg with a CRC-16 and staged save; a load failure keeps ham mode off. Default off, with the upstream path untouched when disabled. The only upstream edit is the virtual Dispatcher::onBeforeTransmit() hook. Includes HAM.md, the README feature section, AGENTS.md updates, the native_ham_mode and _san suites, and the promotion-gate entry. * docs: correct fleet ACK power and widen antenna-gain warning Fleet ACKs are GRP_TXT datagrams encrypted with the private fleet PSK, not PAYLOAD_TYPE_ACK, so they use set tx like all other fleet traffic. The previous HAM.md text copied the source plan's incorrect claim that they were public ACKs. Add a test that pins fleet ACK classification and power to private. Add links to the NebraskaMesh/MeshCore-Ham repository and commit 6e716038 in the acknowledgement, and state that a high-gain antenna can exceed radiated power limits on any board, not only amplified ones like G2 and G3. * fix: address adversarial review findings in ham mode Fix a stale applied-power cache: the set tx CLI is handled by CommonRadioPrefs, which writes the radio directly and never reaches MyMesh::setTxPower(). Dispatch that command explicitly so ham.noteRadioPower() resyncs the cache, preventing a public packet from going out at private power and avoiding a redundant radio write when ham is off. Fix three CLI gaps: channel add and remove with no name returned no reply at all; a quoted or tabbed callsign was accepted despite the one-word rule; an unknown channel subcommand ignored trailing tokens. Factor the one-word check into a shared helper and add regression tests for all three plus the set tx cache sequence. Correct two HAM.md inaccuracies: the admin check lives in MyMesh::onPeerDataRecv(), and the ID countdown is 0s until the first advert is queued then about 598s, not 300s. * fix: block ham transmissions on unconfirmed power changes Honor radio power errors in the per-packet hook, including restoration after disable. Check the actual advert name budget, accept zero as a valid ID deadline, and validate persisted one-word settings. Cover radio vetoes and use independent wire fixtures for the channel checks. --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
b9464d62c9
commit
e4d3e8964b
21 files changed
+1899
-14
No files matched your search
@@ -91,7 +91,8 @@ jobs:
|
||||
return;
|
||||
}
|
||||
const gate = spawnSync('pio', ['test', '-e', 'native', '-e', 'native_kiss_modem',
|
||||
'-e', 'native_packet_filter', '-e', 'native_battery_gate', '-e', 'native_fleet',
|
||||
'-e', 'native_packet_filter', '-e', 'native_battery_gate',
|
||||
'-e', 'native_ham_mode', '-e', 'native_fleet',
|
||||
'-e', 'native_fleet_noack', '-e', 'native_mesh_clock',
|
||||
'-e', 'native_rx_power_saving', '-e', 'native_radio2',
|
||||
'-e', 'native_mqtt_observer', '-e', 'native_ota'],
|
||||
|
||||
@@ -57,6 +57,12 @@ should not need to explore beyond them before making a change.
|
||||
rules, the active/idle visit scheduler, the full CLI reference, feature
|
||||
interactions (RXPS, `extra.sf`, tempradio, filter, battery/fleet, powersaving)
|
||||
and tradeoffs.
|
||||
- `HAM.md`: ham mode user manual: the Part 97 / Part 15 power split, the
|
||||
public/private classification table, the callsign gate and the 10-minute
|
||||
station-ID timer, the `ham` CLI, persistence in `/ham_cfg`, the deliberate
|
||||
decoupling from the filter, the credit to NebraskaMesh/MeshCore-Ham, and
|
||||
the operator's responsibility for power levels and identification. First
|
||||
stop for any ham-mode question.
|
||||
- LoRa OTA: the over-the-air firmware update for repeaters (branch
|
||||
`lora-ota`; not merged to `repeater-filter` yet). The user manual, the
|
||||
Android/Linux app and the hardware bench live in the `MeshCoreRepeaterManager` repo
|
||||
@@ -123,6 +129,11 @@ commit**. The guides are user-facing API documentation, not optional docs.
|
||||
primary, the policy matrix, the active/idle visit scheduler, the deferred
|
||||
apply, and `radio2CLI`. `Radio2Device` is its only radio surface, so the
|
||||
native suite drives a fake; MyMesh supplies the adapter over `radio_driver`.
|
||||
- `HamMode.h/.cpp`, `HamModeConfig.h`: ham mode: per-packet public/private TX
|
||||
power selection, the 10-minute station-ID advert timer, the `ham` CLI and
|
||||
the `/ham_cfg` record (v1, magic "HAMC", CRC-16). Uses `CliUtil.h` and
|
||||
`PersistUtil.h`. The one upstream hook is `Dispatcher::onBeforeTransmit()`.
|
||||
Kept fully decoupled from the filter.
|
||||
- `OtaUpdate.h/.cpp`: the LoRa OTA engine: the `ota` CLI (`stage`, `status`,
|
||||
`apply`, `abort`, `rollback`), the `/ota_pend` boot-health marker with its
|
||||
attempt counter, the boot-time verdict (`earlyBootCheck`) that rolls back a
|
||||
@@ -197,7 +208,9 @@ reached through the same entry points a user or the firmware would:
|
||||
upgrades, CLI surface, TinyRegex, PatternMatch), `test/test_fleet/` (runner
|
||||
grammar, tag targeting, acknowledgements, scheduling, persistence, CLI surface,
|
||||
the battery exemption contract), `test/test_battery_gate/` (suspension
|
||||
behavior, persistence, CLI), `test/test_mesh_clock/` (sample collection, quorum
|
||||
behavior, persistence, CLI), `test/test_ham_mode/` (classification, callsign
|
||||
gate, station-ID timing, CLI and persistence), `test/test_mesh_clock/` (sample
|
||||
collection, quorum
|
||||
decision, persistence, CLI), `test/test_rx_power_saving/` (the duty-cycle
|
||||
level ladders and preamble guard, timer-condition validation, config
|
||||
normalisation, presets/raw parsing and the `get radio.rxps` report),
|
||||
@@ -211,12 +224,14 @@ status/packet/raw JSON schema). Test-only shims:
|
||||
`FilterTestHelpers.h`, `CliReplyHelper.h`.
|
||||
|
||||
**Build & CI:** `pio test -e native_packet_filter` / `-e
|
||||
native_battery_gate` / `-e native_fleet` / `-e native_fleet_noack` (the fleet
|
||||
native_battery_gate` / `-e native_ham_mode` / `-e native_fleet` /
|
||||
`-e native_fleet_noack` (the fleet
|
||||
suite with `FLEET_ACK_RETRY=0`, whose test bodies live in `#else` branches no
|
||||
other env compiles) / `-e native_mesh_clock` / `-e native_rx_power_saving` / `-e
|
||||
native_radio2` / `-e native_mqtt_observer`
|
||||
(host-native, no hardware), plus `-e
|
||||
native_packet_filter_san` / `-e native_battery_gate_san` / `-e native_fleet_san` /
|
||||
native_packet_filter_san` / `-e native_battery_gate_san` / `-e native_ham_mode_san` /
|
||||
`-e native_fleet_san` /
|
||||
`-e native_mesh_clock_san` / `-e native_rx_power_saving_san` / `-e
|
||||
native_radio2_san` / `-e
|
||||
native_mqtt_observer_san` for ASan+UBSan;
|
||||
@@ -577,6 +592,7 @@ FILTER.md:
|
||||
```
|
||||
pio test -e native_packet_filter # filter + PatternMatch + TinyRegex + CLI + persistence
|
||||
pio test -e native_battery_gate # battery gate
|
||||
pio test -e native_ham_mode # ham mode (classification, gate, ID, CLI, persistence)
|
||||
pio test -e native_fleet # fleet manager + runner + CLI + persistence
|
||||
pio test -e native_fleet_noack # the same, with FLEET_ACK_RETRY=0 (the off switch)
|
||||
pio test -e native_mesh_clock # mesh clock sync
|
||||
@@ -589,7 +605,7 @@ All green, and every touched line required, together with the full host-env
|
||||
run, since the generic envs are where a broken selection shows up:
|
||||
|
||||
```
|
||||
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_radio2 -e native_mqtt_observer -e native_ota -e native_ota_san
|
||||
pio test -e native -e native_kiss_modem -e native_packet_filter -e native_battery_gate -e native_ham_mode -e native_fleet -e native_fleet_noack -e native_mesh_clock -e native_rx_power_saving -e native_radio2 -e native_mqtt_observer -e native_ota -e native_ota_san
|
||||
```
|
||||
|
||||
Touching firmware-hook or persistence code additionally warrants compile checks
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# Ham mode: User Guide
|
||||
|
||||
Ham mode lets a licensed amateur radio operator send traffic that anyone can
|
||||
read at amateur power, while encrypted traffic stays at a lower unlicensed
|
||||
power. The repeater chooses the power for each packet just before it transmits.
|
||||
Packets are not changed, so stock nodes and apps see nothing different. Ham
|
||||
mode is **off by default**: a fresh install, or any failure loading its config,
|
||||
behaves like stock repeater firmware.
|
||||
|
||||
## What it does
|
||||
|
||||
There are two transmit powers:
|
||||
|
||||
- `set tx` is the normal, unlicensed power. Every encrypted packet uses it.
|
||||
- `ham tx` is the amateur power. Only publicly readable packets use it, and
|
||||
only while ham mode is active.
|
||||
|
||||
A packet is publicly readable only when this firmware can positively identify
|
||||
it as such. Everything else gets `set tx`. Group classification uses the
|
||||
protocol's one-byte channel hash and two-byte MAC. Both must match, but
|
||||
these short fields cannot rule out a collision.
|
||||
|
||||
| Public (uses `ham tx`) | Encrypted (uses `set tx`) |
|
||||
|---|---|
|
||||
| Adverts (signed plaintext, carries the station ID) | Direct messages, requests and responses |
|
||||
| ACKs (a checksum, no message content) | Anonymous requests, returned paths, raw custom packets, unknown types |
|
||||
| Traces and control packets (plaintext) | Group traffic that does not match a known public key |
|
||||
| Multipart ACKs (low nibble is ACK) | Non-ACK multipart packets |
|
||||
| Group text or data whose MAC verifies against the Public channel or one of your listed hashtag channels | |
|
||||
|
||||
What does **not** change: packet contents, on-air formats, the node's name in
|
||||
adverts, the normal advert schedule, routing and forwarding, and how other
|
||||
nodes or apps behave. Only the transmit power of each physical transmission
|
||||
differs. With ham mode off, no power switching happens at all.
|
||||
|
||||
## Before you enable it
|
||||
|
||||
- You must hold an amateur radio license and operate within its privileges.
|
||||
This firmware is a tool, not a license and not legal advice.
|
||||
- Amateur privileges do not allow obscuring the meaning of messages
|
||||
(47 CFR 97.113(a)(4)). Ham mode therefore gives higher power only to
|
||||
traffic anyone can read. Encrypted traffic always stays at `set tx`.
|
||||
- FCC 97.119(a) requires your call sign to be transmitted at least every
|
||||
10 minutes during a communication. This firmware schedules an ID on
|
||||
activation and on a 10-minute timer. The call sign travels in the node name.
|
||||
Check it on a receiver: the scheduler cannot guarantee when a packet airs.
|
||||
- Part 15 devices are limited to 1 W (30 dBm) conducted output, with a
|
||||
dB-for-dB reduction above 6 dBi of antenna gain (47 CFR 15.247(b)(3)-(4)).
|
||||
A high-gain antenna can push radiated power over that limit on any board,
|
||||
not just an amplified one. On boards with a power amplifier, the `set tx`
|
||||
number is often a drive level rather than measured output; Station G2 and G3
|
||||
use a `LORA_TX_POWER` of 7 dBm to drive the PA. Measure your real output with
|
||||
your actual antenna and choose both powers yourself. This fork enforces no
|
||||
ceiling and claims no compliance.
|
||||
|
||||
## Quick start
|
||||
|
||||
Run these commands over serial or as an admin over the mesh. The powers
|
||||
are examples: substitute drive levels appropriate for your board and
|
||||
antenna. In particular, 22 dBm exceeds the Station G2's 19 dBm maximum drive.
|
||||
|
||||
```
|
||||
ham callsign N0CALL
|
||||
set name N0CALL Test
|
||||
set tx 7
|
||||
ham tx 22
|
||||
ham on
|
||||
```
|
||||
|
||||
`ham` should now report an active state like:
|
||||
|
||||
```
|
||||
on - call N0CALL, ham tx 22, set tx 7, tags 0, next ID 0s
|
||||
```
|
||||
|
||||
The `next ID` value counts down in seconds. It is 0 while the first ID is due,
|
||||
then about 598s once that advert has been queued (10 minutes less the 1.5 s
|
||||
send delay). The first ID is eligible for transmission after that delay.
|
||||
|
||||
## How it behaves
|
||||
|
||||
**Callsign gate.** Ham mode is active only when all three are true: you ran
|
||||
`ham on`, a callsign is set, and that callsign appears as a whole word in the
|
||||
live node name. Whole word means the characters around it are not letters or
|
||||
digits, so `N0CALL` matches `N0CALL Test` but not `N0CALLS Test`. Matching is
|
||||
case insensitive. `set name` takes effect immediately because the current name
|
||||
is checked on every use. The whole callsign must fit in the transmitted UTF-8
|
||||
name: 31 bytes without position, 23 with position. Put the callsign first if
|
||||
the full name contains it but `ham` reports `waiting`.
|
||||
|
||||
**Three status words.** `ham` reports `on` when active, `off` when ham mode is
|
||||
disabled, or `waiting` when it is enabled but not yet gated on. `waiting`
|
||||
either says `no callsign` or tells you which callsign the node name must
|
||||
include. While off or waiting, every packet uses `set tx`.
|
||||
|
||||
**Dynamic power switching.** When active, public packets use `ham tx` and
|
||||
encrypted packets use the live `set tx`. Changing `set tx` immediately changes
|
||||
the power of encrypted traffic, even while ham mode is on; public traffic keeps
|
||||
using `ham tx`. The radio is only reprogrammed when the chosen power actually
|
||||
changes, which avoids needless duty-cycle churn when RXPS is armed. If the
|
||||
radio rejects a power switch, that packet is dropped. The next send must
|
||||
successfully set power, even if you disabled ham mode after the failure.
|
||||
|
||||
**Station ID.** Activation makes the first ID due immediately. Creating a local
|
||||
advert, including a scheduled advert or `advert.zerohop`, restarts the timer.
|
||||
This happens before transmission: other queued traffic can go first, a busy
|
||||
radio can delay the ID, and a failed transmission can leave a gap longer than
|
||||
10 minutes. Relaying someone else's advert does not restart the timer. The
|
||||
ID is an ordinary signed zero-hop advert with your callsign in the name, so it
|
||||
feeds mesh clock sync like any other advert.
|
||||
|
||||
**Hashtag channels.** Add a publicly known channel with `ham channel add #name`.
|
||||
The name must match the app exactly, including case. It is at most 14
|
||||
characters after the `#`, the same limit MeshCore puts on hashtag channels.
|
||||
An unlisted hashtag is treated as encrypted and gets `set tx`.
|
||||
|
||||
## Command reference
|
||||
|
||||
All commands take the `ham` prefix and are handled by the same dispatcher as
|
||||
`filter`, `battery`, `fleet` and `radio2`. Any `ham` command arriving over the
|
||||
mesh is accepted only from an admin client, via the core's `isAdmin()` check in
|
||||
`MyMesh::onPeerDataRecv()`, which is the only mesh path into `handleCommand()`.
|
||||
Serial and fleet-script commands run with serial privilege. Replies are bounded
|
||||
to 157 bytes.
|
||||
|
||||
Usage, printed for `ham help` and for an unknown or malformed command:
|
||||
|
||||
```
|
||||
Err - usage: ham | ham on | ham off | ham callsign [CALL] | ham tx [N] | ham channel add|remove|list [#name] | ham channels | ham stats
|
||||
```
|
||||
|
||||
### `ham` / `ham status`
|
||||
|
||||
Reports the current state. Active:
|
||||
|
||||
```
|
||||
on - call N0CALL, ham tx 22, set tx 7, tags 2, next ID 598s
|
||||
```
|
||||
|
||||
Off: `off - all packets use normal tx power`.
|
||||
Waiting: `waiting - no callsign` or `waiting - node name must include N0CALL`.
|
||||
|
||||
### `ham on` / `ham off`
|
||||
|
||||
Enables or disables ham mode: `OK - ham on` or `OK - ham off`. `ham on` stores
|
||||
the enabled flag; activation still needs a valid callsign in the node name.
|
||||
|
||||
### `ham callsign [CALL]`
|
||||
|
||||
With no value, shows `callsign is N0CALL` or `no callsign set`. With a value,
|
||||
stores it uppercased. The value must be one word of 3 to 15 characters:
|
||||
|
||||
```
|
||||
OK - callsign set to N0CALL
|
||||
Err - callsign must be one word, 3..15 chars
|
||||
```
|
||||
|
||||
The reply adds a warning when the node name is over 23 bytes, the name budget
|
||||
in adverts that include position.
|
||||
|
||||
### `ham tx [N]`
|
||||
|
||||
Shows or sets the power for publicly readable traffic, from -9 to 30 dBm:
|
||||
|
||||
```
|
||||
ham tx is 22 dBm
|
||||
OK - ham tx set to 22 dBm
|
||||
Err - ham tx must be a number from -9 to 30
|
||||
```
|
||||
|
||||
This never changes `set tx`, the power for encrypted traffic.
|
||||
|
||||
### `ham channel add|remove|list [#name]`
|
||||
|
||||
`add` takes one word, adds a leading `#` if needed, rejects duplicates and
|
||||
allows at most 8 names. `remove` takes the exact name. `list` shows `Public`
|
||||
first, then your names. `ham channels` is an alias for `ham channel list`.
|
||||
|
||||
```
|
||||
OK - #test now uses ham power
|
||||
OK - #test removed
|
||||
Public, #test, #Nebraska
|
||||
Err - channel name must be one word, max 14 characters after #
|
||||
Err - #test is already on the list
|
||||
Err - #test is not on the list
|
||||
Err - channel list full (max 8); remove one first
|
||||
```
|
||||
|
||||
### `ham stats`
|
||||
|
||||
RAM-only counts of packets classified for transmission since boot, plus the
|
||||
last driver-confirmed power setting (`unknown` after a failed power write)
|
||||
and ID countdown. These are attempts, not confirmed transmissions; the power
|
||||
setting is not a measurement of radiated power.
|
||||
|
||||
```
|
||||
12 public, 34 private; applied 7 dBm; next ID 598s
|
||||
```
|
||||
|
||||
## Interactions with other features
|
||||
|
||||
- **Filter:** fully decoupled. Ham mode has its own channel list and never
|
||||
reads `/filter_cfg`; the filter does not know ham mode exists. You may list
|
||||
the same hashtag in both, but each list is edited separately.
|
||||
- **Radio2:** one power pair covers both presets. Radio2 has no per-preset
|
||||
power, and ham mode adds none. The dispatcher selects the preset before the
|
||||
power hook runs.
|
||||
- **RXPS:** allowed. Because power is only written when the class changes,
|
||||
duty-cycle re-arming is kept to a minimum. Radio2 and RXPS remain mutually
|
||||
exclusive.
|
||||
- **Battery gate:** independent. Ham ID adverts still fire while forwarding is
|
||||
suspended, so disable ham mode on battery-critical nodes if you do not want
|
||||
that RF activity.
|
||||
- **Fleet:** fleet traffic and its acknowledgements are group texts encrypted
|
||||
with the fleet channel's private PSK. Ham classification checks group traffic
|
||||
against the Public channel and your listed hashtag channels, so neither fleet
|
||||
datagrams nor fleet ACKs match and both use `set tx`.
|
||||
- **Observer:** capture happens before forwarding policy and only TX power
|
||||
changes, so there is no schema change.
|
||||
- **OTA:** update operations ride inside requests and responses, so they are
|
||||
encrypted and use `set tx`. A low private power slows updates.
|
||||
- **Mesh clock:** ID adverts are ordinary signed adverts and feed clock sync
|
||||
like any other.
|
||||
|
||||
## Persistence and defaults
|
||||
|
||||
Settings live in `/ham_cfg`, a fixed 152-byte record plus a 2-byte CRC-16,
|
||||
written with a staged save that keeps a `.bak` copy. If the main record is
|
||||
missing or invalid, a valid backup can restore its settings, including `on`.
|
||||
Without a usable record the defaults are: ham mode off,
|
||||
no callsign, `ham tx` at the board's `LORA_TX_POWER`, and no tags. Counters and
|
||||
the ID timer are RAM-only and reset on boot.
|
||||
|
||||
This is a new format. Settings from the source fork's `/ham_prefs` are not read
|
||||
or migrated; a node coming from that firmware starts with ham mode off and you
|
||||
must re-enter its settings here.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- `ham` says `waiting - no callsign`: run `ham callsign <CALL>`.
|
||||
- `ham` says `waiting - node name must include <CALL>`: run
|
||||
`set name <CALL> Test` with the same callsign as a whole word.
|
||||
- Wrong power level: remember that `ham tx` is public power and `set tx` is
|
||||
private power. `ham` shows both. A public message and a direct message should
|
||||
show two distinct levels on a meter or SDR.
|
||||
- A hashtag message still uses private power: the name must be listed with
|
||||
`ham channel add`, match exactly including case, and the sender must use the
|
||||
same channel key.
|
||||
- Reported power looks low, or the link seems too strong: on amplified boards
|
||||
like G2 and G3 the numbers are PA drive levels, not measured watts. On any
|
||||
board a high-gain antenna raises radiated power. Measure conducted output with
|
||||
the real antenna and check the antenna-gain rule before choosing either power.
|
||||
- To verify: check that `ham` says `on`, watch for a zero-hop advert after
|
||||
activation, send one public and one direct message, and confirm `ham stats`
|
||||
increments both counters.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This feature adapts the ham capability built and published by **KF0WXX and the
|
||||
Nebraska Mesh community** in
|
||||
[NebraskaMesh/MeshCore-Ham](https://github.com/NebraskaMesh/MeshCore-Ham)
|
||||
(MIT licensed), whose original implementation is
|
||||
[commit `6e716038`](https://github.com/NebraskaMesh/MeshCore-Ham/commit/6e716038).
|
||||
The public/private classification
|
||||
model and its fail-safe rule, the hardcoded Public key and hashtag derivation,
|
||||
the activation gate, the per-packet TX power hook, the command names and the
|
||||
public/private counters all come from that work. This fork rewrites it into the
|
||||
repeater-filter architecture with fork-owned files, CRC-protected settings,
|
||||
native tests, whole-word callsign validation and a timer-driven station ID.
|
||||
|
||||
## For developers
|
||||
|
||||
The feature is `examples/simple_repeater/HamMode.h/.cpp` plus `HamModeConfig.h`.
|
||||
The `Dispatcher::onBeforeTransmit()` hook can veto a transmit if the radio
|
||||
driver reports that the power switch failed.
|
||||
Behavior is pinned by the `test/test_ham_mode/` native suite (`native_ham_mode`
|
||||
and `native_ham_mode_san`). See the code map in AGENTS.md for the other fork
|
||||
features and their guides.
|
||||
@@ -1,7 +1,7 @@
|
||||
# MeshCore — Repeater Firmware with a Remote-Configurable Packet Filter
|
||||
|
||||
This is a feature fork of [MeshCore](https://github.com/meshcore-dev/MeshCore).
|
||||
It tracks upstream `main` releases and adds nine repeater-focused capabilities
|
||||
It tracks upstream `main` releases and adds ten repeater-focused capabilities
|
||||
on top of stock firmware. Everything else — supported boards, clients,
|
||||
protocols, build system — is identical to upstream;
|
||||
see the
|
||||
@@ -65,6 +65,23 @@ like stock firmware.
|
||||
→ Full guide, including the policy recipes, CLI reference and tradeoffs:
|
||||
**[RADIO2.md](./RADIO2.md)**
|
||||
|
||||
### 📢 Ham mode (licensed amateur operators)
|
||||
|
||||
For licensed operators who want more range on traffic anyone can read. With
|
||||
ham mode on, publicly readable traffic (the Public channel, the #hashtag
|
||||
channels you list, adverts, ACKs and traces) goes out at the power you set
|
||||
with `ham tx`, while encrypted traffic keeps using the normal `set tx` power.
|
||||
The node schedules a zero-hop callsign advert if it has not scheduled a local
|
||||
advert in the last 10 minutes. Actual air time depends on the radio and queue.
|
||||
Packets themselves are unchanged, so stock nodes and apps are unaffected.
|
||||
Off by default: with ham mode off the node behaves like stock firmware.
|
||||
|
||||
Adapted from [NebraskaMesh/MeshCore-Ham](https://github.com/NebraskaMesh/MeshCore-Ham)
|
||||
by KF0WXX for the Nebraska Mesh community; see the Acknowledgements in HAM.md.
|
||||
|
||||
→ Full guide, including the classification table, setup and the legal notes:
|
||||
**[HAM.md](./HAM.md)**
|
||||
|
||||
### 🕒 Mesh clock sync
|
||||
|
||||
A repeater with no GPS, NTP, or battery-backed RTC can estimate UTC from signed
|
||||
@@ -159,6 +176,9 @@ fork is for operators who want policy and resilience at the node:
|
||||
set of towers) and push settings to all of them with one broadcast message
|
||||
instead of one admin session each: radio preset cutovers, advert hygiene,
|
||||
filter policy, rollouts and rollbacks.
|
||||
- **Licensed amateur operators**: send publicly readable traffic at amateur
|
||||
power while encrypted traffic stays at unlicensed power, with the callsign
|
||||
included in adverts on a 10-minute ID timer.
|
||||
|
||||
## Getting the firmware
|
||||
|
||||
@@ -177,6 +197,7 @@ Flash as you would stock firmware, then follow
|
||||
[FILTER.md](./FILTER.md) to set your first rules over the CLI,
|
||||
[FLEET.md](./FLEET.md) if you are running a fleet,
|
||||
[POWER.md](./POWER.md) if the node runs on solar or battery,
|
||||
[RADIO2.md](./RADIO2.md) if it should listen on a second preset, or
|
||||
[RADIO2.md](./RADIO2.md) if it should listen on a second preset,
|
||||
[HAM.md](./HAM.md) if you are a licensed operator using dual TX power, or
|
||||
[MQTT_OBSERVER.md](./MQTT_OBSERVER.md) if you flashed an observer build.
|
||||
Observer builds ship in the same releases as the plain repeater firmware.
|
||||
@@ -0,0 +1,504 @@
|
||||
// HamMode.cpp: dual Part 97 / Part 15 TX power for the repeater.
|
||||
// Fork-owned; see HAM.md.
|
||||
|
||||
#include "HamMode.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <Utils.h>
|
||||
#include <helpers/UTF8Helpers.h>
|
||||
|
||||
#include "CliUtil.h"
|
||||
#include "KeyedChannel.h"
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
static size_t boundedLen(const char* s, size_t cap) {
|
||||
size_t n = 0;
|
||||
while (n < cap && s[n]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
static bool isWordChar(unsigned char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
|
||||
(c >= '0' && c <= '9');
|
||||
}
|
||||
|
||||
// nextToken() keeps spaces inside double quotes and does not treat tabs as
|
||||
// separators, so a quoted or tabbed value must be rejected explicitly before
|
||||
// it is stored as a "one word" callsign or channel name.
|
||||
static bool isOneWord(const char* s) {
|
||||
if (s == NULL || s[0] == 0) return false;
|
||||
for (const char* p = s; *p; p++) {
|
||||
if (isspace((unsigned char)*p)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// A callsign identifies the station only when it stands alone in the node
|
||||
// name. A bare substring would let N0CALL activate on "N0CALLS".
|
||||
static bool containsCallWord(HamAdvertName advert, const char* call) {
|
||||
const char* name = advert.text;
|
||||
size_t n = strlen(call);
|
||||
size_t m = mesh::validUtf8PrefixLength(name, advert.budget);
|
||||
if (n == 0 || n > m) return false;
|
||||
for (size_t p = 0; p + n <= m; p++) {
|
||||
if (p > 0 && isWordChar((unsigned char)name[p - 1])) continue;
|
||||
if (isWordChar((unsigned char)name[p + n])) continue;
|
||||
size_t i = 0;
|
||||
while (i < n && tolower((unsigned char)name[p + i]) ==
|
||||
tolower((unsigned char)call[i])) i++;
|
||||
if (i == n) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- lifecycle
|
||||
|
||||
HamMode::HamMode() {
|
||||
resetToDefaults();
|
||||
}
|
||||
|
||||
void HamMode::resetToDefaults() {
|
||||
memset(&cfg, 0, sizeof(cfg));
|
||||
memcpy(cfg.magic, HAM_CFG_MAGIC, 4);
|
||||
cfg.version = HAM_CFG_VERSION;
|
||||
cfg.enabled = 0;
|
||||
cfg.ham_dbm = (int8_t)HAM_TX_POWER;
|
||||
cfg.callsign[0] = 0;
|
||||
private_dbm = HAM_TX_POWER;
|
||||
applied_dbm = HAM_TX_POWER;
|
||||
power_known = restore_power = false;
|
||||
n_public = 0;
|
||||
n_private = 0;
|
||||
next_id_at = 0;
|
||||
was_active = false;
|
||||
rebuildKeys();
|
||||
}
|
||||
|
||||
void HamMode::rebuildKeys() {
|
||||
memset(&public_key, 0, sizeof(public_key));
|
||||
mesh::Utils::fromHex(public_key.secret, 16, MESHCORE_PUBLIC_PSK_HEX);
|
||||
mesh::Utils::sha256(&public_key.hash, 1, public_key.secret, 16);
|
||||
public_key.used = true;
|
||||
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
memset(&tag_keys[i], 0, sizeof(tag_keys[i]));
|
||||
if (cfg.tags[i][0]) {
|
||||
deriveChannelKey(cfg.tags[i], tag_keys[i].secret, &tag_keys[i].hash);
|
||||
tag_keys[i].used = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- gate
|
||||
|
||||
const char* HamMode::inactiveReason(HamAdvertName node_name) const {
|
||||
if (!cfg.enabled) return "disabled";
|
||||
if (cfg.callsign[0] == 0) return "no callsign";
|
||||
if (!containsCallWord(node_name, cfg.callsign)) return "name lacks callsign";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool HamMode::isActive(HamAdvertName node_name) const {
|
||||
return inactiveReason(node_name) == NULL;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- classification
|
||||
|
||||
bool HamMode::tryKnownKey(const KnownKey& key, uint8_t hash,
|
||||
const uint8_t* payload, size_t len) const {
|
||||
if (!key.used || hash != key.hash) return false;
|
||||
// A 1-byte hash collides with private channels about 1 in 256 times, so the
|
||||
// 2-byte message MAC has to verify before traffic gets the higher power.
|
||||
// matchesKnownKey() has already checked the minimum group payload length.
|
||||
memset(hmac_secret, 0, sizeof(hmac_secret));
|
||||
memcpy(hmac_secret, key.secret, 16);
|
||||
return mesh::Utils::MACThenDecrypt(hmac_secret, decrypt_scratch,
|
||||
payload, (int)len) > 0;
|
||||
}
|
||||
|
||||
bool HamMode::matchesKnownKey(const uint8_t* payload, size_t len) const {
|
||||
// group wire form: channel hash(1) | MAC(2) | ciphertext (block aligned)
|
||||
if (len < 1 + CIPHER_MAC_SIZE + CIPHER_BLOCK_SIZE) return false;
|
||||
uint8_t hash = payload[0];
|
||||
const uint8_t* body = payload + 1;
|
||||
size_t body_len = len - 1;
|
||||
if (tryKnownKey(public_key, hash, body, body_len)) return true;
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
if (tryKnownKey(tag_keys[i], hash, body, body_len)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
HamTxClass HamMode::classify(const mesh::Packet* pkt) const {
|
||||
switch (pkt->getPayloadType()) {
|
||||
case PAYLOAD_TYPE_ADVERT: // signed plaintext, carries the station ID
|
||||
case PAYLOAD_TYPE_ACK: // checksum only, obscures nothing
|
||||
case PAYLOAD_TYPE_TRACE: // plaintext tag plus SNR list
|
||||
case PAYLOAD_TYPE_CONTROL: // plaintext discovery
|
||||
return HAM_TX_PUBLIC;
|
||||
|
||||
case PAYLOAD_TYPE_MULTIPART: // only a multipart ACK is public
|
||||
return (pkt->payload_len >= 1 &&
|
||||
(pkt->payload[0] & 0x0F) == PAYLOAD_TYPE_ACK)
|
||||
? HAM_TX_PUBLIC : HAM_TX_ENCRYPTED;
|
||||
|
||||
case PAYLOAD_TYPE_GRP_TXT:
|
||||
case PAYLOAD_TYPE_GRP_DATA:
|
||||
return matchesKnownKey(pkt->payload, pkt->payload_len)
|
||||
? HAM_TX_PUBLIC : HAM_TX_ENCRYPTED;
|
||||
|
||||
default: // REQ, RESPONSE, TXT_MSG, ANON_REQ, PATH, RAW_CUSTOM, unknown
|
||||
return HAM_TX_ENCRYPTED;
|
||||
}
|
||||
}
|
||||
|
||||
int8_t HamMode::selectPower(const mesh::Packet* pkt, HamAdvertName node_name,
|
||||
int8_t default_dbm) {
|
||||
return isActive(node_name) ? activePower(pkt, default_dbm) : default_dbm;
|
||||
}
|
||||
|
||||
int8_t HamMode::activePower(const mesh::Packet* pkt, int8_t default_dbm) {
|
||||
if (classify(pkt) == HAM_TX_PUBLIC) {
|
||||
n_public++;
|
||||
return cfg.ham_dbm;
|
||||
}
|
||||
n_private++;
|
||||
return default_dbm;
|
||||
}
|
||||
|
||||
void HamMode::noteRadioPower(int8_t dbm, bool ok) {
|
||||
private_dbm = dbm;
|
||||
power_known = ok;
|
||||
if (ok) {
|
||||
applied_dbm = dbm;
|
||||
restore_power = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- station ID
|
||||
|
||||
void HamMode::noteAdvertOnAir(uint32_t now) {
|
||||
if (!was_active) return;
|
||||
// The send is delayed by HAM_ID_SEND_DELAY_MS, so arm short by that much to
|
||||
// allow for that delay when scheduling the next ID.
|
||||
next_id_at = now + HAM_ID_INTERVAL_MS - HAM_ID_SEND_DELAY_MS;
|
||||
}
|
||||
|
||||
bool HamMode::idDue(uint32_t now) const {
|
||||
// Unsigned subtraction gives the right answer across a millis() wrap for any
|
||||
// deadline within the 10-minute window.
|
||||
return was_active &&
|
||||
(uint32_t)(now - next_id_at) < 0x80000000UL;
|
||||
}
|
||||
|
||||
uint32_t HamMode::secondsToId(uint32_t now) const {
|
||||
if (!was_active) return 0;
|
||||
uint32_t remaining = (uint32_t)(next_id_at - now);
|
||||
if (remaining > HAM_ID_INTERVAL_MS) return 0; // past due
|
||||
return remaining / 1000UL;
|
||||
}
|
||||
|
||||
void HamMode::loop(uint32_t now, FILESYSTEM* fs, HamAdvertName node_name) {
|
||||
if (save_flag.due()) save(fs);
|
||||
|
||||
// Activation is a transition, not a command: `ham on`, a stored config at
|
||||
// boot, and `set name` after the callsign was set all take the same path.
|
||||
bool active = isActive(node_name);
|
||||
if (active && !was_active) {
|
||||
next_id_at = now; // schedule an ID on this pass
|
||||
} else if (!active && was_active) {
|
||||
next_id_at = 0;
|
||||
}
|
||||
was_active = active;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- settings
|
||||
|
||||
int HamMode::getTagCount() const {
|
||||
int n = 0;
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) if (cfg.tags[i][0]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
int HamMode::findTag(const char* name) const {
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
if (cfg.tags[i][0] && strcmp(cfg.tags[i], name) == 0) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void HamMode::setEnabled(bool on) {
|
||||
if (cfg.enabled == (uint8_t)(on ? 1 : 0)) return;
|
||||
cfg.enabled = on ? 1 : 0;
|
||||
markDirty();
|
||||
}
|
||||
|
||||
void HamMode::setCallsign(const char* call) {
|
||||
strncpy(cfg.callsign, call, HAM_CALLSIGN_MAX_LEN - 1);
|
||||
cfg.callsign[HAM_CALLSIGN_MAX_LEN - 1] = 0;
|
||||
markDirty();
|
||||
}
|
||||
|
||||
void HamMode::setHamDbm(int8_t dbm) {
|
||||
if (dbm < -9 || dbm > 30) return;
|
||||
cfg.ham_dbm = dbm;
|
||||
markDirty();
|
||||
}
|
||||
|
||||
bool HamMode::addTag(const char* name) {
|
||||
if (findTag(name) >= 0) return false;
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
if (!cfg.tags[i][0]) {
|
||||
strncpy(cfg.tags[i], name, HAM_TAG_MAX_LEN - 1);
|
||||
cfg.tags[i][HAM_TAG_MAX_LEN - 1] = 0;
|
||||
rebuildKeys();
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false; // full
|
||||
}
|
||||
|
||||
bool HamMode::removeTag(const char* name) {
|
||||
int i = findTag(name);
|
||||
if (i < 0) return false;
|
||||
cfg.tags[i][0] = 0;
|
||||
rebuildKeys();
|
||||
markDirty();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- persistence
|
||||
|
||||
static bool hamValidateRecord(const HamCfgRecord& rec) {
|
||||
if (memcmp(rec.magic, HAM_CFG_MAGIC, 4) != 0) return false;
|
||||
if (rec.version != HAM_CFG_VERSION) return false;
|
||||
if (rec.enabled > 1) return false;
|
||||
if (rec.ham_dbm < -9 || rec.ham_dbm > 30) return false;
|
||||
size_t len = boundedLen(rec.callsign, HAM_CALLSIGN_MAX_LEN);
|
||||
if (len && (len < 3 || len == HAM_CALLSIGN_MAX_LEN || !isOneWord(rec.callsign))) return false;
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
if (!rec.tags[i][0]) continue;
|
||||
if (rec.tags[i][0] != '#') return false;
|
||||
size_t n = boundedLen(rec.tags[i], HAM_TAG_MAX_LEN);
|
||||
if (n < 2 || n >= HAM_TAG_MAX_LEN || !isOneWord(rec.tags[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool hamWriteFile(File& f, void* ctx) {
|
||||
HamMode& ham = *(HamMode*)ctx;
|
||||
uint8_t buf[HAM_CFG_RECORD_BYTES];
|
||||
memcpy(buf, &ham.getRecord(), HAM_CFG_PAYLOAD_BYTES);
|
||||
uint16_t crc = crc16_ccitt(buf, HAM_CFG_PAYLOAD_BYTES);
|
||||
memcpy(&buf[HAM_CFG_PAYLOAD_BYTES], &crc, 2);
|
||||
return f.write(buf, HAM_CFG_RECORD_BYTES) == HAM_CFG_RECORD_BYTES;
|
||||
}
|
||||
|
||||
static bool hamValidateFile(File& f, void* ctx) {
|
||||
(void)ctx;
|
||||
uint8_t buf[HAM_CFG_RECORD_BYTES];
|
||||
if (f.read(buf, HAM_CFG_RECORD_BYTES) != HAM_CFG_RECORD_BYTES) return false;
|
||||
uint8_t extra;
|
||||
if (f.read(&extra, 1) != 0) return false; // reject an overlong record
|
||||
uint16_t stored, computed;
|
||||
memcpy(&stored, &buf[HAM_CFG_PAYLOAD_BYTES], 2);
|
||||
computed = crc16_ccitt(buf, HAM_CFG_PAYLOAD_BYTES);
|
||||
if (stored != computed) return false;
|
||||
HamCfgRecord rec;
|
||||
memcpy(&rec, buf, sizeof(rec));
|
||||
return hamValidateRecord(rec);
|
||||
}
|
||||
|
||||
void HamMode::save(FILESYSTEM* fs) {
|
||||
bool ok = saveStaged(fs, HAM_CFG_FILE, hamWriteFile, this,
|
||||
hamValidateFile, NULL, hamValidateFile, NULL);
|
||||
if (ok) save_flag.clear();
|
||||
else save_flag.retryLater();
|
||||
}
|
||||
|
||||
void HamMode::load(FILESYSTEM* fs) {
|
||||
resetToDefaults(); // a load failure always leaves the node looking stock
|
||||
save_flag.reset();
|
||||
|
||||
char path[64];
|
||||
PersistLoadSource src = chooseConfigToLoad(fs, HAM_CFG_FILE, hamValidateFile,
|
||||
NULL, path, sizeof(path));
|
||||
if (src == PERSIST_LOAD_NONE) return;
|
||||
File file = fsOpenRead(fs, path);
|
||||
if (!file) return;
|
||||
uint8_t buf[HAM_CFG_RECORD_BYTES];
|
||||
bool got = file.read(buf, HAM_CFG_RECORD_BYTES) == HAM_CFG_RECORD_BYTES;
|
||||
file.close();
|
||||
if (!got) return;
|
||||
|
||||
uint16_t stored, computed;
|
||||
memcpy(&stored, &buf[HAM_CFG_PAYLOAD_BYTES], 2);
|
||||
computed = crc16_ccitt(buf, HAM_CFG_PAYLOAD_BYTES);
|
||||
if (stored != computed) return;
|
||||
HamCfgRecord rec;
|
||||
memcpy(&rec, buf, sizeof(rec));
|
||||
if (!hamValidateRecord(rec)) return;
|
||||
|
||||
applyRecord(rec);
|
||||
if (src == PERSIST_LOAD_RECOVERED) markDirty();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- CLI
|
||||
|
||||
#define HAM_USAGE \
|
||||
"Err - usage: ham | ham on | ham off | ham callsign [CALL] | ham tx [N] | " \
|
||||
"ham channel add|remove|list [#name] | ham channels | ham stats"
|
||||
|
||||
static void cliListChannels(HamMode& ham, char* reply) {
|
||||
CliBuf buf(reply, CLI_REPLY_MAX);
|
||||
buf.addStr("Public");
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
if (ham.getTag(i)[0]) buf.add(", %s", ham.getTag(i));
|
||||
}
|
||||
}
|
||||
|
||||
static void cliStatus(HamMode& ham, HamAdvertName node_name, uint32_t now, char* reply) {
|
||||
CliBuf buf(reply, CLI_REPLY_MAX);
|
||||
if (!ham.isEnabled()) {
|
||||
buf.addStr("off - all packets use normal tx power");
|
||||
} else if (ham.getCallsign()[0] == 0) {
|
||||
buf.addStr("waiting - no callsign");
|
||||
} else if (!ham.isActive(node_name)) {
|
||||
buf.add("waiting - node name must include %s", ham.getCallsign());
|
||||
} else {
|
||||
buf.add("on - call %s, ham tx %d, set tx %d, tags %d, next ID %lus",
|
||||
ham.getCallsign(), ham.getHamDbm(), ham.getPrivateDbm(),
|
||||
ham.getTagCount(), (unsigned long)ham.secondsToId(now));
|
||||
}
|
||||
}
|
||||
|
||||
void hamCLI(HamMode& ham, HamAdvertName node_name, const char* command, char* reply) {
|
||||
char scratch[MAX_PACKET_PAYLOAD + 1];
|
||||
if (!cliPrepare(command, scratch, sizeof(scratch), reply)) return;
|
||||
char* p = scratch;
|
||||
char* cmd = nextToken(&p);
|
||||
|
||||
if (cmd == NULL || strcmp(cmd, "status") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
cliStatus(ham, node_name, millis(), reply);
|
||||
} else if (strcmp(cmd, "help") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
snprintf(reply, CLI_REPLY_MAX, "%s", HAM_USAGE);
|
||||
} else if (strcmp(cmd, "on") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
ham.setEnabled(true);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - ham on");
|
||||
} else if (strcmp(cmd, "off") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
ham.setEnabled(false);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - ham off");
|
||||
} else if (strcmp(cmd, "callsign") == 0) {
|
||||
char* tok = nextToken(&p);
|
||||
if (tok == NULL) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
if (ham.getCallsign()[0]) snprintf(reply, CLI_REPLY_MAX, "callsign is %s", ham.getCallsign());
|
||||
else snprintf(reply, CLI_REPLY_MAX, "no callsign set");
|
||||
} else {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
size_t n = strlen(tok);
|
||||
if (!isOneWord(tok) || n < 3 || n > HAM_CALLSIGN_MAX_LEN - 1) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - callsign must be one word, 3..15 chars");
|
||||
return;
|
||||
}
|
||||
char up[HAM_CALLSIGN_MAX_LEN];
|
||||
for (size_t i = 0; i < n; i++) up[i] = (char)toupper((unsigned char)tok[i]);
|
||||
up[n] = 0;
|
||||
ham.setCallsign(up);
|
||||
CliBuf buf(reply, CLI_REPLY_MAX);
|
||||
buf.add("OK - callsign set to %s", up);
|
||||
// With lat/lon the advert name budget is 23 bytes. Warn when the live
|
||||
// name is over that, whatever the current position setting.
|
||||
if (strlen(node_name.text) > 23) {
|
||||
buf.addStr("; warning: name over 23 bytes may be cut from adverts with lat/lon");
|
||||
}
|
||||
}
|
||||
} else if (strcmp(cmd, "tx") == 0) {
|
||||
char* tok = nextToken(&p);
|
||||
if (tok == NULL) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
snprintf(reply, CLI_REPLY_MAX, "ham tx is %d dBm", ham.getHamDbm());
|
||||
} else {
|
||||
long v;
|
||||
if (!parseIntRange(tok, -9, 30, &v)) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - ham tx must be a number from -9 to 30");
|
||||
return;
|
||||
}
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
ham.setHamDbm((int8_t)v);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - ham tx set to %ld dBm", v);
|
||||
}
|
||||
} else if (strcmp(cmd, "channels") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
cliListChannels(ham, reply);
|
||||
} else if (strcmp(cmd, "channel") == 0) {
|
||||
char* sub = nextToken(&p);
|
||||
if (sub == NULL || strcmp(sub, "list") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
cliListChannels(ham, reply);
|
||||
return;
|
||||
}
|
||||
bool add = strcmp(sub, "add") == 0;
|
||||
bool remove = strcmp(sub, "remove") == 0;
|
||||
if (!add && !remove) {
|
||||
if (cliNoExtra(p, reply, HAM_USAGE)) snprintf(reply, CLI_REPLY_MAX, "%s", HAM_USAGE);
|
||||
return;
|
||||
}
|
||||
char* tok = nextToken(&p);
|
||||
if (tok == NULL) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "%s", HAM_USAGE);
|
||||
return;
|
||||
}
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
|
||||
size_t tlen = strlen(tok);
|
||||
size_t want = (tok[0] == '#') ? tlen : tlen + 1;
|
||||
if (!isOneWord(tok) || want < 2 || want > HAM_TAG_MAX_LEN - 1) {
|
||||
snprintf(reply, CLI_REPLY_MAX,
|
||||
"Err - channel name must be one word, max 14 characters after #");
|
||||
return;
|
||||
}
|
||||
char name[HAM_TAG_MAX_LEN];
|
||||
size_t n = 0;
|
||||
if (tok[0] != '#') name[n++] = '#';
|
||||
memcpy(name + n, tok, tlen);
|
||||
name[n + tlen] = 0;
|
||||
|
||||
if (add) {
|
||||
if (ham.findTag(name) >= 0) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - %s is already on the list", name);
|
||||
} else if (ham.getTagCount() >= HAM_MAX_TAGS) {
|
||||
snprintf(reply, CLI_REPLY_MAX,
|
||||
"Err - channel list full (max %d); remove one first", HAM_MAX_TAGS);
|
||||
} else {
|
||||
ham.addTag(name);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - %s now uses ham power", name);
|
||||
}
|
||||
} else {
|
||||
if (ham.removeTag(name)) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - %s removed", name);
|
||||
} else {
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - %s is not on the list", name);
|
||||
}
|
||||
}
|
||||
} else if (strcmp(cmd, "stats") == 0) {
|
||||
if (!cliNoExtra(p, reply, HAM_USAGE)) return;
|
||||
CliBuf buf(reply, CLI_REPLY_MAX);
|
||||
buf.add("%lu public, %lu private; applied ",
|
||||
(unsigned long)ham.getPublicCount(), (unsigned long)ham.getPrivateCount());
|
||||
if (ham.powerKnown()) buf.add("%d dBm", ham.getAppliedDbm());
|
||||
else buf.addStr("unknown");
|
||||
buf.add("; next ID %lus", (unsigned long)ham.secondsToId(millis()));
|
||||
} else {
|
||||
snprintf(reply, CLI_REPLY_MAX, "%s", HAM_USAGE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// HamMode.h: dual Part 97 / Part 15 transmit power for the repeater.
|
||||
// Fork-owned; see HAM.md for the user-facing model.
|
||||
//
|
||||
// Ham mode never changes a packet. It only picks a TX power just before the
|
||||
// dispatcher starts a physical transmit. Anything not positively identified as
|
||||
// publicly readable by the packet classifier stays at normal power.
|
||||
//
|
||||
// The live node name is passed in at every entry point instead of stored, so a
|
||||
// `set name` takes effect on the activation gate without a refresh hook.
|
||||
|
||||
#ifndef _HAM_MODE_H
|
||||
#define _HAM_MODE_H
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Packet.h>
|
||||
#include <helpers/IdentityStore.h> // FILESYSTEM typedef
|
||||
#include "PersistUtil.h"
|
||||
#include "HamModeConfig.h"
|
||||
|
||||
enum HamTxClass : uint8_t {
|
||||
HAM_TX_ENCRYPTED = 0,
|
||||
HAM_TX_PUBLIC = 1,
|
||||
};
|
||||
|
||||
// CommonCLI adverts spend one flag byte and, when sharing position, two
|
||||
// 32-bit coordinates before the UTF-8 name.
|
||||
struct HamAdvertName {
|
||||
const char* text;
|
||||
size_t budget;
|
||||
HamAdvertName(const char* name, bool with_position = false)
|
||||
: text(name), budget(MAX_ADVERT_DATA_SIZE - 1 - (with_position ? 8 : 0)) {}
|
||||
};
|
||||
|
||||
class HamMode {
|
||||
public:
|
||||
HamMode();
|
||||
|
||||
void load(FILESYSTEM* fs);
|
||||
void save(FILESYSTEM* fs);
|
||||
// Flushes lazy saves and watches the active-state transition. Does not transmit.
|
||||
void loop(uint32_t now, FILESYSTEM* fs, HamAdvertName node_name);
|
||||
|
||||
// Pure function of packet type and payload bytes. Public for host tests.
|
||||
HamTxClass classify(const mesh::Packet* pkt) const;
|
||||
|
||||
// The only place that decides public versus private. `default_dbm` is the
|
||||
// live `set tx` value, returned for every encrypted packet and whenever the
|
||||
// activation gate is not satisfied.
|
||||
int8_t selectPower(const mesh::Packet* pkt, HamAdvertName node_name, int8_t default_dbm);
|
||||
|
||||
bool isActive(HamAdvertName node_name) const;
|
||||
const char* inactiveReason(HamAdvertName node_name) const;
|
||||
|
||||
// Result of the normal power write at boot or from `set tx`.
|
||||
void noteRadioPower(int8_t dbm, bool ok);
|
||||
// The applied-power cache: only write the radio when the chosen class really
|
||||
// changes, so RXPS duty cycle is not torn down on every packet.
|
||||
template<class Radio>
|
||||
bool prepareTransmit(Radio& radio, const mesh::Packet* pkt, HamAdvertName name, int8_t normal) {
|
||||
bool active = isActive(name);
|
||||
if (!active && !restore_power) return true;
|
||||
int8_t dbm = active ? activePower(pkt, normal) : normal;
|
||||
if (power_known && dbm == applied_dbm) return true;
|
||||
radio.setTxPower(dbm);
|
||||
power_known = radio.lastTxPowerOk();
|
||||
// Even a failed PA write may have partially configured the chip. Restore
|
||||
// private power before allowing another send, including after `ham off`.
|
||||
restore_power = !power_known || dbm != normal;
|
||||
if (power_known) applied_dbm = dbm;
|
||||
return power_known;
|
||||
}
|
||||
|
||||
// Station ID timer. `loop()` arms it on a false-to-true active transition;
|
||||
// creating a local advert pushes it out another interval.
|
||||
bool idDue(uint32_t now) const;
|
||||
void noteAdvertOnAir(uint32_t now);
|
||||
uint32_t secondsToId(uint32_t now) const;
|
||||
|
||||
// Read-outs used by the CLI and the host suite.
|
||||
bool isEnabled() const { return cfg.enabled != 0; }
|
||||
const char* getCallsign() const { return cfg.callsign; }
|
||||
int8_t getHamDbm() const { return cfg.ham_dbm; }
|
||||
int8_t getPrivateDbm() const { return private_dbm; }
|
||||
int8_t getAppliedDbm() const { return applied_dbm; }
|
||||
bool powerKnown() const { return power_known; }
|
||||
int getTagCount() const;
|
||||
const char* getTag(int i) const { return cfg.tags[i]; }
|
||||
int findTag(const char* name) const;
|
||||
uint32_t getPublicCount() const { return n_public; }
|
||||
uint32_t getPrivateCount() const { return n_private; }
|
||||
|
||||
// Mutations. The CLI validates input before calling these.
|
||||
void setEnabled(bool on);
|
||||
void setCallsign(const char* call);
|
||||
void setHamDbm(int8_t dbm);
|
||||
bool addTag(const char* name); // false on duplicate or a full list
|
||||
bool removeTag(const char* name); // false when the name is not listed
|
||||
void markDirty() { save_flag.markDirty(); }
|
||||
|
||||
// Used only by the staged-save callbacks in HamMode.cpp.
|
||||
const HamCfgRecord& getRecord() const { return cfg; }
|
||||
void applyRecord(const HamCfgRecord& rec) { cfg = rec; rebuildKeys(); }
|
||||
|
||||
private:
|
||||
struct KnownKey {
|
||||
uint8_t secret[16];
|
||||
uint8_t hash;
|
||||
bool used;
|
||||
};
|
||||
|
||||
HamCfgRecord cfg;
|
||||
KnownKey public_key;
|
||||
KnownKey tag_keys[HAM_MAX_TAGS];
|
||||
// One shared zero-padded secret and one shared decrypt scratch keep the
|
||||
// per-packet frame small and predictable; classify() is const, so mutable.
|
||||
mutable uint8_t hmac_secret[PUB_KEY_SIZE];
|
||||
mutable uint8_t decrypt_scratch[MAX_PACKET_PAYLOAD];
|
||||
|
||||
int8_t private_dbm;
|
||||
int8_t applied_dbm;
|
||||
bool power_known, restore_power;
|
||||
uint32_t n_public;
|
||||
uint32_t n_private;
|
||||
|
||||
uint32_t next_id_at;
|
||||
bool was_active;
|
||||
|
||||
LazySave save_flag;
|
||||
|
||||
void resetToDefaults();
|
||||
int8_t activePower(const mesh::Packet* pkt, int8_t normal);
|
||||
void rebuildKeys();
|
||||
bool tryKnownKey(const KnownKey& key, uint8_t hash, const uint8_t* payload, size_t len) const;
|
||||
bool matchesKnownKey(const uint8_t* payload, size_t len) const;
|
||||
};
|
||||
|
||||
// `command` is everything after the "ham" verb.
|
||||
void hamCLI(HamMode& ham, HamAdvertName node_name, const char* command, char* reply);
|
||||
|
||||
#endif // _HAM_MODE_H
|
||||
@@ -0,0 +1,58 @@
|
||||
// HamModeConfig.h: tunables and persisted record for the repeater's ham mode.
|
||||
// Fork-owned; see HAM.md for the user-facing model.
|
||||
|
||||
#ifndef _HAM_MODE_CONFIG_H
|
||||
#define _HAM_MODE_CONFIG_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define HAM_CFG_FILE "/ham_cfg"
|
||||
#define HAM_CFG_VERSION 1
|
||||
#define HAM_CFG_MAGIC "HAMC"
|
||||
|
||||
// A self-contained list of publicly known hashtag channels. The well-known
|
||||
// Public channel is hardcoded in KeyedChannel.h and takes no slot here.
|
||||
#define HAM_MAX_TAGS 8
|
||||
#define HAM_TAG_MAX_LEN 16 // '#' + up to 14 chars + NUL, as parseChannelSpec
|
||||
#define HAM_CALLSIGN_MAX_LEN 16 // room for an /indicator suffix
|
||||
|
||||
// 47 CFR 97.119(a): the call sign must be sent at least every 10 minutes.
|
||||
// The interval is fixed, so there is no config field and no CLI to change it.
|
||||
#define HAM_ID_INTERVAL_MS (10UL * 60UL * 1000UL)
|
||||
// Same delay the zero-hop advert CLI uses. Arming subtracts it so the on-air
|
||||
// spacing, not the scheduling spacing, is 10 minutes.
|
||||
#define HAM_ID_SEND_DELAY_MS 1500UL
|
||||
|
||||
// Default for `ham tx`, the power used by publicly readable traffic. The
|
||||
// board's compiled LORA_TX_POWER is the right fresh-install value when one is
|
||||
// present; the fallback keeps host builds independent of a board variant.
|
||||
#ifdef LORA_TX_POWER
|
||||
#define HAM_TX_POWER LORA_TX_POWER
|
||||
#else
|
||||
#define HAM_TX_POWER 20
|
||||
#endif
|
||||
|
||||
// Persisted payload: 4 + 1 + 1 + 1 + 1 + 16 + 8*16 = 152 B. The file appends a
|
||||
// 2-byte CRC-16, so the record on disk is 154 B. Names are stored; the compact
|
||||
// key cache is derived on load and on every add/remove.
|
||||
#define HAM_CFG_PAYLOAD_BYTES 152
|
||||
#define HAM_CFG_RECORD_BYTES 154
|
||||
|
||||
struct HamCfgRecord {
|
||||
char magic[4]; // offset 0, "HAMC"
|
||||
uint8_t version; // offset 4
|
||||
uint8_t enabled; // offset 5
|
||||
uint8_t reserved; // offset 6
|
||||
int8_t ham_dbm; // offset 7
|
||||
char callsign[HAM_CALLSIGN_MAX_LEN]; // offset 8
|
||||
char tags[HAM_MAX_TAGS][HAM_TAG_MAX_LEN]; // offset 24
|
||||
};
|
||||
static_assert(sizeof(HamCfgRecord) == 152,
|
||||
"HamCfgRecord payload is frozen at 152 B");
|
||||
static_assert(offsetof(HamCfgRecord, callsign) == 8,
|
||||
"HamCfgRecord callsign offset is frozen at 8");
|
||||
static_assert(offsetof(HamCfgRecord, tags) == 24,
|
||||
"HamCfgRecord tags offset is frozen at 24");
|
||||
|
||||
#endif // _HAM_MODE_CONFIG_H
|
||||
@@ -28,6 +28,10 @@ inline bool validChannelName(const char* name) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// The well-known MeshCore Public channel PSK (16 bytes); sha256()[0] is 0x11.
|
||||
// Both the filter and ham mode need it, so it lives here once.
|
||||
#define MESHCORE_PUBLIC_PSK_HEX "8b3387e9c5cdea6ac9e5edbaa115cd72"
|
||||
|
||||
// Derive a hashtag channel's 16-byte secret and its 1-byte on-air hash from
|
||||
// the name (including the leading '#'), per the companion protocol.
|
||||
inline void deriveChannelKey(const char* name, uint8_t* secret, uint8_t* hash) {
|
||||
|
||||
@@ -1248,6 +1248,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
#endif
|
||||
acl.load(_fs, self_id);
|
||||
filter.begin(fs);
|
||||
ham.load(_fs);
|
||||
battGate.begin(fs);
|
||||
ota.begin(fs, &battGate, &board, FIRMWARE_VERSION, getRNG());
|
||||
ota.setSender(otaSend, this);
|
||||
@@ -1291,6 +1292,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
powerApplyRadioProfile(_prefs);
|
||||
radio_driver.setTxPower(_prefs.tx_power_dbm);
|
||||
ham.noteRadioPower(_prefs.tx_power_dbm, radio_driver.lastTxPowerOk());
|
||||
|
||||
radio2.setPrimary(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
|
||||
radio2.start(_prefs.rxps.enabled, _prefs.extra_sf[0] != 0);
|
||||
@@ -1358,6 +1360,9 @@ void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
|
||||
// (a remote `advert` command arrives on one preset, but the node's own
|
||||
// advert is primary by default).
|
||||
pkt->setTxProfile(RADIO_PROFILE_PRIMARY);
|
||||
// One reset for every advert path (scheduled, CLI zero-hop, radio2 both and
|
||||
// the ham ID itself); the ham timer early-returns while ham mode is off.
|
||||
ham.noteAdvertOnAir(millis());
|
||||
|
||||
// Copy before queueing the first packet: the queued packet stays valid, but
|
||||
// copying first keeps the two independent from the start.
|
||||
@@ -1416,6 +1421,11 @@ void MyMesh::dumpLogFile() {
|
||||
|
||||
void MyMesh::setTxPower(int8_t power_dbm) {
|
||||
radio_driver.setTxPower(power_dbm);
|
||||
ham.noteRadioPower(power_dbm, radio_driver.lastTxPowerOk());
|
||||
}
|
||||
|
||||
bool MyMesh::onBeforeTransmit(mesh::Packet* pkt) {
|
||||
return ham.prepareTransmit(radio_driver, pkt, hamAdvertName(), _prefs.tx_power_dbm);
|
||||
}
|
||||
|
||||
bool MyMesh::setRxBoostedGain(bool enable) {
|
||||
@@ -1642,6 +1652,10 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
const char* sub = command + 7;
|
||||
while (*sub == ' ') sub++;
|
||||
batteryCLI(battGate, board, sub, reply);
|
||||
} else if (memcmp(command, "ham", 3) == 0 && (command[3] == ' ' || command[3] == 0)) {
|
||||
const char* sub = command + 3;
|
||||
while (*sub == ' ') sub++;
|
||||
hamCLI(ham, hamAdvertName(), sub, reply);
|
||||
} else if (memcmp(command, "fleet", 5) == 0 && (command[5] == ' ' || command[5] == 0)) {
|
||||
const char* sub = command + 5;
|
||||
while (*sub == ' ') sub++;
|
||||
@@ -1678,6 +1692,13 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
const char* sub = command + 10;
|
||||
while (*sub == ' ') sub++;
|
||||
meshClockCLI(meshClock, now, sub, reply);
|
||||
} else if (memcmp(command, "set tx ", 7) == 0) {
|
||||
// CommonRadioPrefs writes the radio directly and only updates the prefs
|
||||
// value, so this command never reaches MyMesh::setTxPower(). Sync ham's
|
||||
// applied-power cache here, or the next public packet could be sent at the
|
||||
// new private power.
|
||||
_cli.handleCommand(sender_timestamp, command, reply);
|
||||
ham.noteRadioPower(_prefs.tx_power_dbm, radio_driver.lastTxPowerOk());
|
||||
} else{
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
@@ -1719,6 +1740,11 @@ void MyMesh::loop() {
|
||||
? &radio2 : nullptr);
|
||||
}
|
||||
|
||||
// Watches the active-state transition (arming the ID timer) and flushes a
|
||||
// pending config save. Runs before the advert branches so the ID decision
|
||||
// below sees this pass's state.
|
||||
ham.loop(millis(), _fs, hamAdvertName());
|
||||
|
||||
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
|
||||
sendSelfAdvertisement(0, true);
|
||||
|
||||
@@ -1728,6 +1754,10 @@ void MyMesh::loop() {
|
||||
sendSelfAdvertisement(0, false);
|
||||
|
||||
updateAdvertTimer(); // schedule next local advert
|
||||
} else if (ham.idDue(millis())) {
|
||||
// A station ID is an ordinary zero-hop advert. The ID timer is independent
|
||||
// of the normal advert schedule, which is left untouched.
|
||||
sendSelfAdvertisement(HAM_ID_SEND_DELAY_MS, false);
|
||||
}
|
||||
|
||||
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
#include "ChatBot.h"
|
||||
#include "MeshClockSync.h"
|
||||
#include "Radio2.h"
|
||||
#include "HamMode.h"
|
||||
#include "OtaUpdate.h"
|
||||
#ifdef WITH_MQTT_OBSERVER
|
||||
#include "../mqtt_observer/MQTTObserver.h"
|
||||
@@ -131,6 +132,10 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
|
||||
OtaUpdate ota;
|
||||
Radio2DeviceImpl radio2_device;
|
||||
Radio2 radio2;
|
||||
HamMode ham;
|
||||
HamAdvertName hamAdvertName() const {
|
||||
return HamAdvertName(_prefs.node_name, _prefs.advert_loc_policy != ADVERT_LOC_NONE);
|
||||
}
|
||||
bool rx_forward_allowed = true;
|
||||
#ifdef WITH_MQTT_OBSERVER
|
||||
MQTTObserver mqttObserver;
|
||||
@@ -183,6 +188,9 @@ protected:
|
||||
void logRx(mesh::Packet* pkt, int len, float score) override;
|
||||
void logTx(mesh::Packet* pkt, int len) override;
|
||||
void logTxFail(mesh::Packet* pkt, int len) override;
|
||||
// Pick public or private TX power for this one physical transmit. The radio2
|
||||
// profile has already been selected by the dispatcher at this point.
|
||||
bool onBeforeTransmit(mesh::Packet* pkt) override;
|
||||
int calcRxDelay(float score, uint32_t air_time) const override;
|
||||
|
||||
uint32_t getRetransmitDelay(const mesh::Packet* packet) override;
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
#include "KeyedChannel.h"
|
||||
#include <helpers/TxtDataHelpers.h>
|
||||
|
||||
// The well-known Public channel PSK (16 bytes); its sha256()[0] air hash is 0x11.
|
||||
#define FILTER_PUBLIC_PSK_HEX "8b3387e9c5cdea6ac9e5edbaa115cd72"
|
||||
#define FILTER_CFG_FILE "/filter_cfg"
|
||||
#define FILTER_CFG_VERSION 7 // v7: all payload types typeable (type_mask_hi
|
||||
// joins the record), capacity growth (32 rules /
|
||||
@@ -73,7 +71,7 @@ void FilterRules::begin(FILESYSTEM* fs) {
|
||||
|
||||
// pre-provision the well-known Public channel on a fresh node
|
||||
if (fresh && findChannel("Public") == NULL) {
|
||||
addChannel("Public", FILTER_PUBLIC_PSK_HEX);
|
||||
addChannel("Public", MESHCORE_PUBLIC_PSK_HEX);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -177,6 +177,7 @@ test_ignore =
|
||||
test_kiss_modem
|
||||
test_packet_filter
|
||||
test_battery_gate
|
||||
test_ham_mode
|
||||
test_fleet
|
||||
test_mesh_clock
|
||||
test_bot
|
||||
@@ -357,6 +358,31 @@ build_src_filter =
|
||||
lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
; Native tests for ham mode (fork-owned HamMode.*). Real SHA-256 and HMAC are
|
||||
; required: the suite pins the Public PSK's 0x11 air hash and the #test digest,
|
||||
; so test/test_ham_mode/SHA256.h (a real implementation) must shadow the mock
|
||||
; in test/mocks. Include order matters: -I src first so <Utils.h> is the real
|
||||
; crypto, then -I test/test_ham_mode before -I test/mocks for <SHA256.h>.
|
||||
[env:native_ham_mode]
|
||||
platform = native
|
||||
test_framework = googletest
|
||||
build_flags = -std=c++17
|
||||
-I src
|
||||
-I test/test_ham_mode
|
||||
-I test/test_packet_filter
|
||||
-I test/mocks
|
||||
-I examples/simple_repeater
|
||||
-include test/test_packet_filter/NativeShim.h
|
||||
test_build_src = yes
|
||||
test_filter = test_ham_mode
|
||||
build_src_filter =
|
||||
-<*>
|
||||
+<../src/Utils.cpp>
|
||||
+<../src/Packet.cpp>
|
||||
+<../examples/simple_repeater/HamMode.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,
|
||||
@@ -482,3 +508,9 @@ extends = env:native_radio2
|
||||
build_flags =
|
||||
${env:native_radio2.build_flags}
|
||||
-g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer
|
||||
|
||||
[env:native_ham_mode_san]
|
||||
extends = env:native_ham_mode
|
||||
build_flags =
|
||||
${env:native_ham_mode.build_flags}
|
||||
-g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer
|
||||
+2
-2
@@ -331,7 +331,7 @@ void Dispatcher::checkSend() {
|
||||
|
||||
uint32_t max_airtime = _radio->getEstAirtimeFor(len)*3/2;
|
||||
outbound_start = _ms->getMillis();
|
||||
bool success = _radio->startSendRaw(raw, len);
|
||||
bool success = onBeforeTransmit(outbound) && _radio->startSendRaw(raw, len);
|
||||
if (!success) {
|
||||
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): ERROR: send start failed!", getLogDateTime());
|
||||
|
||||
@@ -394,4 +394,4 @@ unsigned long Dispatcher::futureMillis(int millis_from_now) const {
|
||||
return _ms->getMillis() + millis_from_now;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,7 @@ protected:
|
||||
virtual void logRx(Packet* packet, int len, float score) { } // hooks for custom logging
|
||||
virtual void logTx(Packet* packet, int len) { }
|
||||
virtual void logTxFail(Packet* packet, int len) { }
|
||||
virtual bool onBeforeTransmit(Packet* packet) { return true; }
|
||||
virtual const char* getLogDateTime() { return ""; }
|
||||
|
||||
virtual float getAirtimeBudgetFactor() const;
|
||||
|
||||
@@ -59,7 +59,7 @@ uint32_t ESPNOWRadio::getRngSeed() {
|
||||
}
|
||||
|
||||
void ESPNOWRadio::setTxPower(uint8_t dbm) {
|
||||
esp_wifi_set_max_tx_power(dbm * 4);
|
||||
_tx_power_ok = esp_wifi_set_max_tx_power(dbm * 4) == ESP_OK;
|
||||
}
|
||||
|
||||
uint32_t ESPNOWRadio::intID() {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
class ESPNOWRadio : public mesh::Radio {
|
||||
protected:
|
||||
uint32_t n_recv, n_sent, n_recv_errors;
|
||||
bool _tx_power_ok = false;
|
||||
|
||||
public:
|
||||
ESPNOWRadio() { n_recv = n_sent = n_recv_errors = 0; }
|
||||
@@ -43,6 +44,7 @@ public:
|
||||
|
||||
uint32_t intID();
|
||||
void setTxPower(uint8_t dbm);
|
||||
bool lastTxPowerOk() const { return _tx_power_ok; }
|
||||
};
|
||||
|
||||
#if ESPNOW_DEBUG_LOGGING && ARDUINO
|
||||
|
||||
@@ -71,7 +71,7 @@ void RadioLibWrapper::setTxPower(int8_t dbm) {
|
||||
|
||||
idle();
|
||||
#endif
|
||||
_radio->setOutputPower(dbm);
|
||||
_tx_power_ok = _radio->setOutputPower(dbm) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
void RadioLibWrapper::idle() {
|
||||
|
||||
@@ -27,6 +27,7 @@ protected:
|
||||
float _last_rssi, _last_snr;
|
||||
bool _last_metrics_valid;
|
||||
bool _cad_enabled;
|
||||
bool _tx_power_ok = false;
|
||||
uint16_t _num_floor_samples;
|
||||
int32_t _floor_sample_sum;
|
||||
uint8_t _preamble_sf;
|
||||
@@ -144,6 +145,7 @@ public:
|
||||
virtual void setParams(float freq, float bw, uint8_t sf, uint8_t cr) = 0;
|
||||
uint32_t getRngSeed();
|
||||
void setTxPower(int8_t dbm);
|
||||
bool lastTxPowerOk() const { return _tx_power_ok; }
|
||||
|
||||
virtual float getCurrentRSSI() =0;
|
||||
virtual uint8_t getSpreadingFactor() const { return LORA_SF; }
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
#pragma once
|
||||
|
||||
// Real SHA-256 for the ham-mode native suite. The suite pins real digests (the
|
||||
// Public PSK's 0x11 air hash and the #test channel secret), so the
|
||||
// deterministic mock in test/mocks/SHA256.h cannot be used here. The include
|
||||
// order in [env:native_ham_mode] puts this header ahead of test/mocks.
|
||||
//
|
||||
// HMAC-SHA256 is included because Utils::encryptThenMAC()/MACThenDecrypt()
|
||||
// use it; keeping both in one small header means the suite links the same real
|
||||
// crypto the firmware uses rather than a shortcut that always verifies.
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
static const uint32_t HAM_SHA256_K[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
};
|
||||
|
||||
class SHA256 {
|
||||
uint32_t _h[8];
|
||||
uint8_t _buf[64];
|
||||
size_t _len;
|
||||
uint64_t _total;
|
||||
uint8_t _ipad[64], _opad[64];
|
||||
|
||||
static uint32_t rotr(uint32_t x, unsigned n) {
|
||||
return (x >> n) | (x << (32 - n));
|
||||
}
|
||||
|
||||
void compress(const uint8_t* p) {
|
||||
uint32_t w[64];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
w[i] = ((uint32_t)p[4 * i] << 24) | ((uint32_t)p[4 * i + 1] << 16) |
|
||||
((uint32_t)p[4 * i + 2] << 8) | (uint32_t)p[4 * i + 3];
|
||||
}
|
||||
for (int i = 16; i < 64; i++) {
|
||||
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
uint32_t a = _h[0], b = _h[1], c = _h[2], d = _h[3];
|
||||
uint32_t e = _h[4], f = _h[5], g = _h[6], hh = _h[7];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
uint32_t ch = (e & f) ^ (~e & g);
|
||||
uint32_t t1 = hh + S1 + ch + HAM_SHA256_K[i] + w[i];
|
||||
uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
uint32_t t2 = S0 + maj;
|
||||
hh = g; g = f; f = e; e = d + t1;
|
||||
d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
_h[0] += a; _h[1] += b; _h[2] += c; _h[3] += d;
|
||||
_h[4] += e; _h[5] += f; _h[6] += g; _h[7] += hh;
|
||||
}
|
||||
|
||||
void finishInto(uint8_t out[32]) {
|
||||
uint64_t bits = _total * 8;
|
||||
uint8_t one = 0x80, zero = 0;
|
||||
update(&one, 1);
|
||||
while (_len != 56) update(&zero, 1);
|
||||
uint8_t tail[8];
|
||||
for (int i = 0; i < 8; i++) tail[i] = (uint8_t)(bits >> (56 - 8 * i));
|
||||
update(tail, 8);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out[4 * i] = (uint8_t)(_h[i] >> 24);
|
||||
out[4 * i + 1] = (uint8_t)(_h[i] >> 16);
|
||||
out[4 * i + 2] = (uint8_t)(_h[i] >> 8);
|
||||
out[4 * i + 3] = (uint8_t)(_h[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void baseReset() {
|
||||
static const uint32_t init[8] = {
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
||||
};
|
||||
memcpy(_h, init, sizeof(_h));
|
||||
_len = 0;
|
||||
_total = 0;
|
||||
}
|
||||
|
||||
public:
|
||||
SHA256() { baseReset(); }
|
||||
|
||||
void reset() { baseReset(); }
|
||||
|
||||
void update(const void* data, size_t len) {
|
||||
const uint8_t* p = (const uint8_t*)data;
|
||||
_total += len;
|
||||
while (len) {
|
||||
size_t take = 64 - _len;
|
||||
if (take > len) take = len;
|
||||
memcpy(_buf + _len, p, take);
|
||||
_len += take;
|
||||
p += take;
|
||||
len -= take;
|
||||
if (_len == 64) { compress(_buf); _len = 0; }
|
||||
}
|
||||
}
|
||||
|
||||
void finalize(uint8_t* hash, size_t hashLen) {
|
||||
uint8_t out[32];
|
||||
finishInto(out);
|
||||
memcpy(hash, out, hashLen);
|
||||
}
|
||||
|
||||
void resetHMAC(const uint8_t* key, size_t keyLen) {
|
||||
uint8_t k[64];
|
||||
memset(k, 0, sizeof(k));
|
||||
if (keyLen > sizeof(k)) {
|
||||
SHA256 inner;
|
||||
inner.update(key, keyLen);
|
||||
inner.finalize(k, 32);
|
||||
} else {
|
||||
memcpy(k, key, keyLen);
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(k); i++) {
|
||||
_ipad[i] = (uint8_t)(k[i] ^ 0x36);
|
||||
_opad[i] = (uint8_t)(k[i] ^ 0x5c);
|
||||
}
|
||||
baseReset();
|
||||
update(_ipad, sizeof(_ipad));
|
||||
}
|
||||
|
||||
void finalizeHMAC(const uint8_t* key, size_t keyLen, uint8_t* hash, size_t hashLen) {
|
||||
(void)key; (void)keyLen; // pads were captured by resetHMAC()
|
||||
uint8_t inner[32], out[32];
|
||||
finishInto(inner);
|
||||
baseReset();
|
||||
update(_opad, sizeof(_opad));
|
||||
update(inner, sizeof(inner));
|
||||
finishInto(out);
|
||||
memcpy(hash, out, hashLen);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,623 @@
|
||||
// test_ham_mode.cpp: native tests for ham mode (examples/simple_repeater/HamMode.*).
|
||||
// Built by [env:native_ham_mode]; see that env for the shim and include-order
|
||||
// notes. Every check drives the same entry points the firmware uses:
|
||||
// classify(), selectPower(), loop()/idDue(), hamCLI() and load()/save().
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Packet.h>
|
||||
#include <Utils.h>
|
||||
|
||||
#include "CliReplyHelper.h"
|
||||
#include "HamMode.h"
|
||||
#include "KeyedChannel.h"
|
||||
#include "PersistUtil.h"
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
static void publicKey(uint8_t out[16]) {
|
||||
ASSERT_TRUE(mesh::Utils::fromHex(out, 16, MESHCORE_PUBLIC_PSK_HEX));
|
||||
}
|
||||
|
||||
// Independent wire fixtures: channel hash, HMAC-SHA256 prefix, AES-128-ECB
|
||||
// ciphertext. The shared native AES stub does not write an encrypted block.
|
||||
static const char PUBLIC_HELLO[] = "11e6878045e59184851776e1afe5da9ca76f9b";
|
||||
static void makeGroup(mesh::Packet& pkt, uint8_t type, const char* hex) {
|
||||
memset(&pkt, 0, sizeof(pkt));
|
||||
pkt.header = (uint8_t)(type << PH_TYPE_SHIFT);
|
||||
pkt.payload_len = strlen(hex) / 2;
|
||||
ASSERT_TRUE(mesh::Utils::fromHex(pkt.payload, pkt.payload_len, hex));
|
||||
}
|
||||
|
||||
static void plainPacket(mesh::Packet& pkt, uint8_t type) {
|
||||
memset(&pkt, 0, sizeof(pkt));
|
||||
pkt.header = (uint8_t)(type << PH_TYPE_SHIFT);
|
||||
}
|
||||
|
||||
static void writeRecord(NativeFS& fs, const char* path, const HamCfgRecord& rec,
|
||||
bool good_crc = true) {
|
||||
uint8_t buf[HAM_CFG_RECORD_BYTES];
|
||||
memcpy(buf, &rec, HAM_CFG_PAYLOAD_BYTES);
|
||||
uint16_t crc = crc16_ccitt(buf, HAM_CFG_PAYLOAD_BYTES);
|
||||
if (!good_crc) crc ^= 0x0001;
|
||||
memcpy(&buf[HAM_CFG_PAYLOAD_BYTES], &crc, 2);
|
||||
fs.files[path] = std::vector<uint8_t>(buf, buf + HAM_CFG_RECORD_BYTES);
|
||||
}
|
||||
|
||||
static HamCfgRecord defaultRecord() {
|
||||
HamCfgRecord rec;
|
||||
memset(&rec, 0, sizeof(rec));
|
||||
memcpy(rec.magic, HAM_CFG_MAGIC, 4);
|
||||
rec.version = HAM_CFG_VERSION;
|
||||
rec.ham_dbm = HAM_TX_POWER;
|
||||
return rec;
|
||||
}
|
||||
|
||||
static std::string cli(HamMode& ham, const char* name, const char* command,
|
||||
CliReplyBuf& buf) {
|
||||
// hamCLI() takes the command after the "ham" verb, as MyMesh's dispatch does.
|
||||
const char* sub = command;
|
||||
if (strncmp(command, "ham", 3) == 0) {
|
||||
sub = command + 3;
|
||||
while (*sub == ' ') sub++;
|
||||
}
|
||||
buf.reply()[0] = 0;
|
||||
hamCLI(ham, name, sub, buf.reply());
|
||||
buf.check(command);
|
||||
return std::string(buf.reply());
|
||||
}
|
||||
|
||||
class HamTest : public ::testing::Test {
|
||||
protected:
|
||||
NativeFS fs;
|
||||
HamMode ham;
|
||||
|
||||
void SetUp() override {
|
||||
g_mock_millis = 0;
|
||||
ham.load(&fs); // no file: disabled defaults
|
||||
ham.noteRadioPower(7, true); // stand in for `set tx 7`
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================ crypto linkage
|
||||
|
||||
TEST(HamCrypto, RealDigestsAreLinked) {
|
||||
uint8_t psk[16];
|
||||
publicKey(psk);
|
||||
uint8_t air;
|
||||
mesh::Utils::sha256(&air, 1, psk, 16);
|
||||
EXPECT_EQ(air, 0x11);
|
||||
|
||||
uint8_t secret[16], hash;
|
||||
deriveChannelKey("#test", secret, &hash);
|
||||
char hex[33];
|
||||
mesh::Utils::toHex(hex, secret, 16);
|
||||
EXPECT_STREQ(hex, "9CD8FCF22A47333B591D96A2B848B73F");
|
||||
}
|
||||
|
||||
// ============================================================ classification
|
||||
|
||||
TEST_F(HamTest, PlaintextTypesArePublic) {
|
||||
const uint8_t types[] = {PAYLOAD_TYPE_ADVERT, PAYLOAD_TYPE_ACK,
|
||||
PAYLOAD_TYPE_TRACE, PAYLOAD_TYPE_CONTROL};
|
||||
for (uint8_t t : types) {
|
||||
mesh::Packet pkt;
|
||||
plainPacket(pkt, t);
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_PUBLIC) << "type " << (int)t;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(HamTest, EncryptedTypesArePrivate) {
|
||||
for (int t = 0; t < 16; t++) {
|
||||
switch (t) {
|
||||
case PAYLOAD_TYPE_ADVERT: case PAYLOAD_TYPE_ACK:
|
||||
case PAYLOAD_TYPE_TRACE: case PAYLOAD_TYPE_CONTROL:
|
||||
case PAYLOAD_TYPE_MULTIPART:
|
||||
case PAYLOAD_TYPE_GRP_TXT: case PAYLOAD_TYPE_GRP_DATA:
|
||||
continue;
|
||||
}
|
||||
mesh::Packet pkt;
|
||||
plainPacket(pkt, (uint8_t)t);
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED) << "type " << t;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(HamTest, OnlyMultipartAckIsPublic) {
|
||||
mesh::Packet pkt;
|
||||
plainPacket(pkt, PAYLOAD_TYPE_MULTIPART);
|
||||
pkt.payload_len = 5;
|
||||
pkt.payload[0] = (uint8_t)((2 << 4) | PAYLOAD_TYPE_ACK);
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_PUBLIC);
|
||||
pkt.payload[0] = (uint8_t)((2 << 4) | PAYLOAD_TYPE_TXT_MSG);
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED);
|
||||
pkt.payload_len = 0;
|
||||
pkt.payload[0] = PAYLOAD_TYPE_ACK;
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, GroupOnPublicIsPublic) {
|
||||
mesh::Packet pkt;
|
||||
makeGroup(pkt, PAYLOAD_TYPE_GRP_TXT, PUBLIC_HELLO);
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_PUBLIC);
|
||||
makeGroup(pkt, PAYLOAD_TYPE_GRP_DATA, PUBLIC_HELLO);
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_PUBLIC);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, GroupOnListedTagIsPublic) {
|
||||
ASSERT_TRUE(ham.addTag("#test"));
|
||||
mesh::Packet pkt;
|
||||
makeGroup(pkt, PAYLOAD_TYPE_GRP_TXT, "d9bed6a701b632727a6cfbac453cf1e90ce7bb");
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_PUBLIC);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, GroupOnUnlistedTagIsPrivate) {
|
||||
ham.addTag("#test");
|
||||
mesh::Packet pkt;
|
||||
makeGroup(pkt, PAYLOAD_TYPE_GRP_TXT, "15adad728c558cba643041c902735368c65d46");
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, GroupOnPrivatePskIsPrivate) {
|
||||
mesh::Packet pkt;
|
||||
makeGroup(pkt, PAYLOAD_TYPE_GRP_TXT, "9013c11a84d77efa71c62379230415f2f3f10c");
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, FleetAckUsesPrivatePower) {
|
||||
// Fleet ACKs are not PAYLOAD_TYPE_ACK: MyMesh builds them as GRP_TXT on the
|
||||
// fleet channel's private PSK. That key is not in the ham list, so even an
|
||||
// active node must send them at `set tx`.
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.setHamDbm(22);
|
||||
mesh::Packet ack;
|
||||
makeGroup(ack, PAYLOAD_TYPE_GRP_TXT, "1c8503429e455100bcd914fb7328737a8395c1");
|
||||
EXPECT_EQ(ham.classify(&ack), HAM_TX_ENCRYPTED);
|
||||
EXPECT_EQ(ham.selectPower(&ack, "N0CALL Test", 7), 7);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, HashMatchWithoutMacIsNotEnough) {
|
||||
uint8_t psk[16];
|
||||
publicKey(psk);
|
||||
uint8_t air;
|
||||
mesh::Utils::sha256(&air, 1, psk, 16);
|
||||
mesh::Packet pkt;
|
||||
plainPacket(pkt, PAYLOAD_TYPE_GRP_TXT);
|
||||
pkt.payload[0] = air; // right hash
|
||||
pkt.payload_len = 19;
|
||||
memset(&pkt.payload[1], 0xAA, 18); // garbage MAC and ciphertext
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, ShortGroupPayloadIsPrivate) {
|
||||
uint8_t psk[16];
|
||||
publicKey(psk);
|
||||
uint8_t air;
|
||||
mesh::Utils::sha256(&air, 1, psk, 16);
|
||||
mesh::Packet pkt;
|
||||
plainPacket(pkt, PAYLOAD_TYPE_GRP_TXT);
|
||||
pkt.payload[0] = air;
|
||||
pkt.payload_len = 18; // one byte short of hash+MAC+block
|
||||
EXPECT_EQ(ham.classify(&pkt), HAM_TX_ENCRYPTED);
|
||||
}
|
||||
|
||||
// ============================================================ activation gate
|
||||
|
||||
TEST_F(HamTest, DisabledByDefault) {
|
||||
EXPECT_FALSE(ham.isActive("N0CALL Test"));
|
||||
EXPECT_STREQ(ham.inactiveReason("N0CALL Test"), "disabled");
|
||||
}
|
||||
|
||||
TEST_F(HamTest, NeedsCallsign) {
|
||||
ham.setEnabled(true);
|
||||
EXPECT_STREQ(ham.inactiveReason("N0CALL Test"), "no callsign");
|
||||
}
|
||||
|
||||
TEST_F(HamTest, WholeWordCaseInsensitiveGate) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
EXPECT_TRUE(ham.isActive("N0CALL Test"));
|
||||
EXPECT_TRUE(ham.isActive("net n0call"));
|
||||
EXPECT_FALSE(ham.isActive("N0CALLS Test")); // substring false positive
|
||||
EXPECT_FALSE(ham.isActive("XN0CALL Test"));
|
||||
EXPECT_STREQ(ham.inactiveReason("Other Node"), "name lacks callsign");
|
||||
}
|
||||
|
||||
TEST_F(HamTest, NameChangeAfterCallsign) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
EXPECT_FALSE(ham.isActive("Other Node"));
|
||||
EXPECT_TRUE(ham.isActive("N0CALL Node")); // the live name is passed in
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CallsignMustFitOnAirAndBeAWholeWordInTheLiveName) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
const char* name = "12345678901234567 N0CALL";
|
||||
EXPECT_TRUE(ham.isActive(HamAdvertName(name, false)));
|
||||
EXPECT_FALSE(ham.isActive(HamAdvertName(name, true))); // last byte is cut
|
||||
EXPECT_TRUE(ham.isActive(HamAdvertName("1234567890123456 N0CALL", true)));
|
||||
EXPECT_FALSE(ham.isActive(HamAdvertName("1234567890123456 N0CALLS", true)));
|
||||
}
|
||||
|
||||
// ============================================================ power selection
|
||||
|
||||
TEST_F(HamTest, DisabledReturnsSetTxForEveryClass) {
|
||||
mesh::Packet pub;
|
||||
makeGroup(pub, PAYLOAD_TYPE_GRP_TXT, PUBLIC_HELLO);
|
||||
mesh::Packet ack;
|
||||
plainPacket(ack, PAYLOAD_TYPE_ACK);
|
||||
EXPECT_EQ(ham.selectPower(&pub, "N0CALL Test", 7), 7);
|
||||
EXPECT_EQ(ham.selectPower(&ack, "N0CALL Test", 7), 7);
|
||||
EXPECT_EQ(ham.getPublicCount(), 0u);
|
||||
EXPECT_EQ(ham.getPrivateCount(), 0u);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, PublicUsesHamTxEncryptedUsesSetTx) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.setHamDbm(22);
|
||||
mesh::Packet pub;
|
||||
makeGroup(pub, PAYLOAD_TYPE_GRP_TXT, PUBLIC_HELLO);
|
||||
mesh::Packet dm;
|
||||
plainPacket(dm, PAYLOAD_TYPE_TXT_MSG);
|
||||
EXPECT_EQ(ham.selectPower(&pub, "N0CALL Test", 7), 22);
|
||||
EXPECT_EQ(ham.selectPower(&dm, "N0CALL Test", 7), 7);
|
||||
EXPECT_EQ(ham.getPublicCount(), 1u);
|
||||
EXPECT_EQ(ham.getPrivateCount(), 1u);
|
||||
// Changing `set tx` takes effect immediately for encrypted traffic.
|
||||
ham.noteRadioPower(10, true);
|
||||
EXPECT_EQ(ham.selectPower(&dm, "N0CALL Test", 10), 10);
|
||||
EXPECT_EQ(ham.selectPower(&pub, "N0CALL Test", 10), 22);
|
||||
}
|
||||
|
||||
struct PowerRadio {
|
||||
std::vector<int> writes;
|
||||
bool ok = true;
|
||||
void setTxPower(int8_t dbm) { writes.push_back(dbm); }
|
||||
bool lastTxPowerOk() const { return ok; }
|
||||
};
|
||||
|
||||
TEST_F(HamTest, SetTxResyncsCacheAfterPublicTraffic) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.setHamDbm(22);
|
||||
PowerRadio radio;
|
||||
mesh::Packet pub;
|
||||
makeGroup(pub, PAYLOAD_TYPE_GRP_TXT, PUBLIC_HELLO);
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &pub, "N0CALL Test", 7));
|
||||
|
||||
// `set tx 10` writes the radio directly through CommonRadioPrefs, which
|
||||
// bypasses MyMesh::setTxPower(). The CLI dispatch calls noteRadioPower() to
|
||||
// resync the cache; without it the next public packet would stay at 10 dBm.
|
||||
ham.noteRadioPower(10, true);
|
||||
EXPECT_EQ(ham.getPrivateDbm(), 10);
|
||||
EXPECT_EQ(ham.getAppliedDbm(), 10);
|
||||
mesh::Packet dm;
|
||||
plainPacket(dm, PAYLOAD_TYPE_TXT_MSG);
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &dm, "N0CALL Test", 10));
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &pub, "N0CALL Test", 10));
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &pub, "N0CALL Test", 10));
|
||||
EXPECT_EQ(radio.writes, (std::vector<int>{22, 22}));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, FailedPrivatePowerBlocksSendEvenAfterDisable) {
|
||||
PowerRadio radio;
|
||||
mesh::Packet pub, dm;
|
||||
makeGroup(pub, PAYLOAD_TYPE_GRP_TXT, PUBLIC_HELLO);
|
||||
plainPacket(dm, PAYLOAD_TYPE_TXT_MSG);
|
||||
ham.noteRadioPower(7, false);
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &dm, "N0CALL", 7)); // stock off path
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.setHamDbm(22);
|
||||
ASSERT_TRUE(ham.prepareTransmit(radio, &pub, "N0CALL", 7));
|
||||
radio.ok = false;
|
||||
ham.noteRadioPower(10, false); // rejected `set tx`
|
||||
EXPECT_FALSE(ham.prepareTransmit(radio, &dm, "N0CALL", 10));
|
||||
ham.setEnabled(false);
|
||||
EXPECT_FALSE(ham.prepareTransmit(radio, &dm, "N0CALL", 10));
|
||||
EXPECT_FALSE(ham.powerKnown());
|
||||
CliReplyBuf reply;
|
||||
EXPECT_NE(cli(ham, "N0CALL", "stats", reply).find("applied unknown"), std::string::npos);
|
||||
radio.ok = true;
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &dm, "N0CALL", 10));
|
||||
EXPECT_TRUE(ham.prepareTransmit(radio, &dm, "N0CALL", 10));
|
||||
EXPECT_EQ(radio.writes, (std::vector<int>{22, 10, 10, 10}));
|
||||
}
|
||||
|
||||
// ============================================================ CLI
|
||||
|
||||
TEST_F(HamTest, CliStatusAndOnOff) {
|
||||
CliReplyBuf b;
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "ham", b), "off - all packets use normal tx power");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "status", b), "off - all packets use normal tx power");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "on", b), "OK - ham on");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "ham", b), "waiting - no callsign");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign N0CALL", b), "OK - callsign set to N0CALL");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "ham", b),
|
||||
"on - call N0CALL, ham tx 20, set tx 7, tags 0, next ID 0s");
|
||||
EXPECT_EQ(cli(ham, "Other Node", "ham", b), "waiting - node name must include N0CALL");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "off", b), "OK - ham off");
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliCallsignRules) {
|
||||
CliReplyBuf b;
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign", b), "no callsign set");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign n0call", b), "OK - callsign set to N0CALL");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign", b), "callsign is N0CALL");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign AB", b),
|
||||
"Err - callsign must be one word, 3..15 chars");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign ABCDEF1234567890", b),
|
||||
"Err - callsign must be one word, 3..15 chars");
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "callsign OK extra", b).find("usage"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliCallsignWarnsWhenNameExceedsAdvertBudget) {
|
||||
CliReplyBuf b;
|
||||
std::string r = cli(ham, "N0CALL A Very Long Node Name Over Twenty Three Bytes",
|
||||
"callsign N0CALL", b);
|
||||
EXPECT_NE(r.find("OK - callsign set to N0CALL"), std::string::npos);
|
||||
EXPECT_NE(r.find("warning"), std::string::npos);
|
||||
EXPECT_NE(r.find("23 bytes"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliRejectsMalformedArguments) {
|
||||
CliReplyBuf b;
|
||||
// A missing mandatory argument must still produce a usage reply, not silence.
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel add", b).find("usage"), std::string::npos);
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel remove", b).find("usage"), std::string::npos);
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel bogus extra", b).find("usage"), std::string::npos);
|
||||
|
||||
// Quoted and tabbed values are not one word, so they must be refused whole.
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign \"N0 CALL\"", b),
|
||||
"Err - callsign must be one word, 3..15 chars");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "callsign N0\tCALL", b),
|
||||
"Err - callsign must be one word, 3..15 chars");
|
||||
EXPECT_STREQ(ham.getCallsign(), "");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channel add \"#two words\"", b),
|
||||
"Err - channel name must be one word, max 14 characters after #");
|
||||
EXPECT_EQ(ham.getTagCount(), 0);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliTxShowsAndSetsOnlyPublicPower) {
|
||||
CliReplyBuf b;
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "tx", b), "ham tx is 20 dBm");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "tx 22", b), "OK - ham tx set to 22 dBm");
|
||||
EXPECT_EQ(ham.getHamDbm(), 22);
|
||||
EXPECT_EQ(ham.getPrivateDbm(), 7); // set tx untouched
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "tx -9", b), "OK - ham tx set to -9 dBm");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "tx 31", b), "Err - ham tx must be a number from -9 to 30");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "tx abc", b), "Err - ham tx must be a number from -9 to 30");
|
||||
// No legacy power verbs from the source fork.
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "public 22", b).find("usage"), std::string::npos);
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "private 7", b).find("usage"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliChannelRules) {
|
||||
CliReplyBuf b;
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channels", b), "Public");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channel add test", b), "OK - #test now uses ham power");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channel add #Nebraska", b), "OK - #Nebraska now uses ham power");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channels", b), "Public, #test, #Nebraska");
|
||||
// Duplicate, one word, length, case sensitivity.
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel add #test", b).find("already"), std::string::npos);
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel add \"#two words\"", b).find("one word"), std::string::npos);
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel add #123456789012345", b).find("max 14"), std::string::npos);
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channel add #nebraska", b), "OK - #nebraska now uses ham power");
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "channel remove #test", b), "OK - #test removed");
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel remove #test", b).find("not on the list"), std::string::npos);
|
||||
// The ham list is self-contained: no filter config file is touched.
|
||||
EXPECT_FALSE(fs.exists("/filter_cfg"));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliChannelFullList) {
|
||||
CliReplyBuf b;
|
||||
for (int i = 0; i < HAM_MAX_TAGS; i++) {
|
||||
char cmd[32];
|
||||
snprintf(cmd, sizeof(cmd), "channel add #t%d", i);
|
||||
ASSERT_NE(cli(ham, "N0CALL Test", cmd, b).find("OK"), std::string::npos);
|
||||
}
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "channel add #ninth", b).find("full"), std::string::npos);
|
||||
EXPECT_EQ(ham.getTagCount(), HAM_MAX_TAGS);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, CliStatsAndUsage) {
|
||||
CliReplyBuf b;
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "help", b).substr(0, 12), std::string("Err - usage:"));
|
||||
EXPECT_NE(cli(ham, "N0CALL Test", "bogus", b).find("usage"), std::string::npos);
|
||||
EXPECT_EQ(cli(ham, "N0CALL Test", "stats", b),
|
||||
"0 public, 0 private; applied 7 dBm; next ID 0s");
|
||||
}
|
||||
|
||||
// ============================================================ persistence
|
||||
|
||||
TEST_F(HamTest, SaveLoadRoundtrip) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.setHamDbm(22);
|
||||
ham.addTag("#test");
|
||||
ham.save(&fs);
|
||||
ASSERT_TRUE(fs.exists(HAM_CFG_FILE));
|
||||
|
||||
HamMode fresh;
|
||||
fresh.load(&fs);
|
||||
EXPECT_TRUE(fresh.isEnabled());
|
||||
EXPECT_STREQ(fresh.getCallsign(), "N0CALL");
|
||||
EXPECT_EQ(fresh.getHamDbm(), 22);
|
||||
EXPECT_EQ(fresh.getTagCount(), 1);
|
||||
EXPECT_STREQ(fresh.getTag(0), "#test");
|
||||
EXPECT_TRUE(fresh.isActive("N0CALL Test"));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, BadRecordsKeepDisabledDefaults) {
|
||||
HamCfgRecord rec = defaultRecord();
|
||||
rec.enabled = 1;
|
||||
strcpy(rec.callsign, "N0CALL");
|
||||
rec.ham_dbm = 22;
|
||||
|
||||
writeRecord(fs, HAM_CFG_FILE, rec, false); // bad CRC
|
||||
HamMode a; a.load(&fs);
|
||||
EXPECT_FALSE(a.isEnabled());
|
||||
EXPECT_STREQ(a.getCallsign(), "");
|
||||
|
||||
rec.magic[0] = 'X';
|
||||
writeRecord(fs, HAM_CFG_FILE, rec);
|
||||
HamMode b; b.load(&fs);
|
||||
EXPECT_FALSE(b.isEnabled());
|
||||
|
||||
rec = defaultRecord();
|
||||
rec.version = 2;
|
||||
writeRecord(fs, HAM_CFG_FILE, rec);
|
||||
HamMode c; c.load(&fs);
|
||||
EXPECT_FALSE(c.isEnabled());
|
||||
|
||||
// Overlong record: valid bytes plus a trailing byte is refused.
|
||||
rec = defaultRecord();
|
||||
rec.enabled = 1;
|
||||
uint8_t buf[HAM_CFG_RECORD_BYTES + 1];
|
||||
memcpy(buf, &rec, HAM_CFG_PAYLOAD_BYTES);
|
||||
uint16_t crc = crc16_ccitt(buf, HAM_CFG_PAYLOAD_BYTES);
|
||||
memcpy(&buf[HAM_CFG_PAYLOAD_BYTES], &crc, 2);
|
||||
buf[HAM_CFG_RECORD_BYTES] = 0;
|
||||
fs.files[HAM_CFG_FILE] = std::vector<uint8_t>(buf, buf + sizeof(buf));
|
||||
HamMode d; d.load(&fs);
|
||||
EXPECT_FALSE(d.isEnabled());
|
||||
}
|
||||
|
||||
TEST_F(HamTest, LazySaveTiming) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
EXPECT_FALSE(fs.exists(HAM_CFG_FILE));
|
||||
ham.loop(0, &fs, "N0CALL Test");
|
||||
EXPECT_FALSE(fs.exists(HAM_CFG_FILE)); // not due yet
|
||||
|
||||
g_mock_millis = LAZY_SAVE_DELAY_MS - 1;
|
||||
ham.loop(g_mock_millis, &fs, "N0CALL Test");
|
||||
EXPECT_FALSE(fs.exists(HAM_CFG_FILE));
|
||||
|
||||
g_mock_millis = LAZY_SAVE_DELAY_MS;
|
||||
ham.loop(g_mock_millis, &fs, "N0CALL Test");
|
||||
EXPECT_TRUE(fs.exists(HAM_CFG_FILE));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, InvalidStoredCallsignCannotActivate) {
|
||||
HamCfgRecord rec = defaultRecord();
|
||||
rec.enabled = 1;
|
||||
strcpy(rec.callsign, "N0 CALL");
|
||||
writeRecord(fs, HAM_CFG_FILE, rec);
|
||||
ham.load(&fs);
|
||||
EXPECT_FALSE(ham.isActive("N0 CALL"));
|
||||
EXPECT_FALSE(ham.isEnabled());
|
||||
|
||||
strcpy(rec.callsign, "N0CALL");
|
||||
strcpy(rec.tags[0], "#two words");
|
||||
writeRecord(fs, HAM_CFG_FILE, rec);
|
||||
ham.load(&fs);
|
||||
EXPECT_FALSE(ham.isEnabled());
|
||||
}
|
||||
|
||||
TEST_F(HamTest, RecoversFromBackup) {
|
||||
HamCfgRecord rec = defaultRecord();
|
||||
rec.enabled = 1;
|
||||
strcpy(rec.callsign, "N0CALL");
|
||||
writeRecord(fs, HAM_CFG_FILE, rec);
|
||||
HamMode seeded; seeded.load(&fs);
|
||||
|
||||
// A save rotates the good canonical into .bak before promoting the new one.
|
||||
seeded.setEnabled(false);
|
||||
seeded.save(&fs);
|
||||
ASSERT_TRUE(fs.exists("/ham_cfg.bak"));
|
||||
|
||||
// A torn canonical falls back to the backup.
|
||||
fs.files[HAM_CFG_FILE].resize(3);
|
||||
HamMode recovered;
|
||||
recovered.load(&fs);
|
||||
EXPECT_TRUE(recovered.isEnabled());
|
||||
EXPECT_STREQ(recovered.getCallsign(), "N0CALL");
|
||||
}
|
||||
|
||||
// ============================================================ station ID timer
|
||||
|
||||
TEST_F(HamTest, ArmsOnActivationAndResetsOnAirEveryAdvert) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.loop(1000, &fs, "N0CALL Test"); // false-to-true transition
|
||||
EXPECT_TRUE(ham.idDue(1000)); // immediately due
|
||||
EXPECT_EQ(ham.secondsToId(1000), 0u);
|
||||
|
||||
ham.noteAdvertOnAir(1000);
|
||||
uint32_t next = 1000 + HAM_ID_INTERVAL_MS - HAM_ID_SEND_DELAY_MS;
|
||||
EXPECT_FALSE(ham.idDue(next - 1));
|
||||
EXPECT_TRUE(ham.idDue(next));
|
||||
EXPECT_EQ(ham.secondsToId(1000), (HAM_ID_INTERVAL_MS - HAM_ID_SEND_DELAY_MS) / 1000);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, ArmsFromBootPrefsOnFirstLoop) {
|
||||
HamCfgRecord rec = defaultRecord();
|
||||
rec.enabled = 1;
|
||||
strcpy(rec.callsign, "N0CALL");
|
||||
writeRecord(fs, HAM_CFG_FILE, rec);
|
||||
HamMode booted;
|
||||
booted.load(&fs);
|
||||
booted.loop(5000, &fs, "N0CALL Test");
|
||||
EXPECT_TRUE(booted.idDue(5000));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, RearmsWhenNameStartsMatching) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.loop(1000, &fs, "Other Node"); // inactive
|
||||
EXPECT_FALSE(ham.idDue(1000));
|
||||
ham.loop(2000, &fs, "N0CALL Test"); // name changed, now active
|
||||
EXPECT_TRUE(ham.idDue(2000));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, DeactivationStopsAndReactivationRearms) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.loop(1000, &fs, "N0CALL Test");
|
||||
ham.noteAdvertOnAir(1000);
|
||||
|
||||
ham.setEnabled(false);
|
||||
ham.loop(2000, &fs, "N0CALL Test");
|
||||
EXPECT_FALSE(ham.idDue(2000 + HAM_ID_INTERVAL_MS));
|
||||
|
||||
ham.setEnabled(true);
|
||||
ham.loop(3000, &fs, "N0CALL Test");
|
||||
EXPECT_TRUE(ham.idDue(3000));
|
||||
}
|
||||
|
||||
TEST_F(HamTest, MillisWrapIsHandled) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
g_mock_millis = 0xFFFFFFF0u;
|
||||
ham.loop(g_mock_millis, &fs, "N0CALL Test");
|
||||
ham.noteAdvertOnAir(g_mock_millis);
|
||||
uint32_t next = g_mock_millis + HAM_ID_INTERVAL_MS - HAM_ID_SEND_DELAY_MS;
|
||||
EXPECT_FALSE(ham.idDue(next - 1));
|
||||
EXPECT_TRUE(ham.idDue(next));
|
||||
EXPECT_EQ(ham.secondsToId(g_mock_millis),
|
||||
(HAM_ID_INTERVAL_MS - HAM_ID_SEND_DELAY_MS) / 1000);
|
||||
}
|
||||
|
||||
TEST_F(HamTest, ZeroIsAValidActiveDeadline) {
|
||||
ham.setEnabled(true);
|
||||
ham.setCallsign("N0CALL");
|
||||
ham.loop(0, &fs, "N0CALL");
|
||||
EXPECT_TRUE(ham.idDue(0));
|
||||
uint32_t now = uint32_t(0) - uint32_t(HAM_ID_INTERVAL_MS - HAM_ID_SEND_DELAY_MS);
|
||||
ham.noteAdvertOnAir(now);
|
||||
EXPECT_GT(ham.secondsToId(now), 0u);
|
||||
EXPECT_FALSE(ham.idDue(UINT32_MAX));
|
||||
EXPECT_TRUE(ham.idDue(0));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -196,6 +196,29 @@ TEST(DispatcherProfiles, SelectsBeforeAirtimeAndCad) {
|
||||
d.loop(); // complete and release the outbound packet
|
||||
}
|
||||
|
||||
TEST(DispatcherTransmit, RejectedPreparationDoesNotStartRadioAndReleasesPacket) {
|
||||
struct RejectPower : TestDispatcher {
|
||||
using TestDispatcher::TestDispatcher;
|
||||
bool failed = false;
|
||||
bool onBeforeTransmit(mesh::Packet*) override { return false; }
|
||||
void logTxFail(mesh::Packet*, int) override { failed = true; }
|
||||
};
|
||||
OrderRadio radio;
|
||||
FixedClock clock;
|
||||
StaticPoolPacketManager mgr(1);
|
||||
RejectPower d(radio, clock, mgr);
|
||||
d.begin();
|
||||
clock.now = 2;
|
||||
auto pkt = d.obtainNewPacket();
|
||||
ASSERT_NE(pkt, nullptr);
|
||||
pkt->header = (PAYLOAD_TYPE_TXT_MSG << PH_TYPE_SHIFT) | ROUTE_TYPE_DIRECT;
|
||||
d.sendPacket(pkt, 1, 0);
|
||||
d.loop();
|
||||
EXPECT_TRUE(d.failed);
|
||||
EXPECT_FALSE(radio.started);
|
||||
EXPECT_EQ(mgr.getFreeCount(), 1);
|
||||
}
|
||||
|
||||
TEST(DispatcherProfiles, SelectFailureLeavesPacketQueued) {
|
||||
OrderRadio radio;
|
||||
FixedClock clock;
|
||||
|
||||
Reference in new issue
Block a user