Repeater: one request returns status, telemetry, filter counters and config checksums
Changelog-cs: Repeater: jeden požadavek vrátí stav, telemetrii, čítače filtrů a kontrolní součty konfigurace Changelog-topic: stats-bundle Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e49c76999c
commit
86351f2d41
9 files changed
+2640
No files matched your search
@@ -0,0 +1,199 @@
|
||||
# Stats bundle -- one request per scrape (repeater)
|
||||
|
||||
> [!WARNING]
|
||||
> Part of an experimental fork, not meant for regular users. The request is
|
||||
> not part of upstream's protocol.
|
||||
|
||||
A monitoring scrape used to cost a login (when the session had expired),
|
||||
`REQ_TYPE_GET_STATUS`, `REQ_TYPE_GET_TELEMETRY_DATA` and, for the filter
|
||||
counters, more CLI round trips -- up to 6 packets over several hops. The
|
||||
**stats bundle** answers all of it in **one request and one reply**.
|
||||
|
||||
Code: `src/helpers/StatsBundle.h` (encoder, decoder, prefs CRC; native tests in
|
||||
`test/test_stats_bundle`), glue in `examples/simple_repeater/MyMesh.cpp`
|
||||
(`handleRequest`). Reference implementation in Python and test vectors:
|
||||
`test/vectors/gen_stats_bundle_vectors.py` -> `test/vectors/stats_bundle_vectors.json`
|
||||
(`--check` verifies the JSON). Python 3 stdlib only, meant to be lifted into
|
||||
the exporter and the Ansible collection as it is.
|
||||
|
||||
## Request
|
||||
|
||||
A normal logged-in `REQ` (like `GET_STATUS`); the first payload byte is the type.
|
||||
|
||||
| byte | meaning |
|
||||
|---|---|
|
||||
| 0 | `REQ_TYPE_STATS_BUNDLE = 0xF1` (our private range next to `REQ_TYPE_FW_OTA = 0xF0`; both outside upstream's 0x01..0x09) |
|
||||
| 1 | `page`, optional, default 0 |
|
||||
|
||||
An unknown page gets no reply. A build without the bundle ignores the type
|
||||
(upstream firmware answers nothing to an unknown type): a reader that gets no
|
||||
reply to page 0 falls back to `GET_STATUS` + `GET_TELEMETRY_DATA`.
|
||||
|
||||
**Who may read what.** An **admin** gets everything. A guest or read-only login
|
||||
gets exactly what `GET_STATUS` and the base telemetry give it today -- status
|
||||
and telemetry records (ids 1..21), one page, nothing else.
|
||||
|
||||
## Reply
|
||||
|
||||
The reply carries the 4-byte tag of the request, then at most **150 B** of
|
||||
bundle (the same budget as the OTA reply: tag + 150 B pads to 160 B and the
|
||||
companion's push frame must stay within `MAX_FRAME_SIZE` 176).
|
||||
|
||||
```
|
||||
[ver = 1][page << 4 | pages] record record ...
|
||||
```
|
||||
|
||||
`pages` is the total number of pages (1..15), `page` the one in this reply.
|
||||
|
||||
**Record** = key byte `(id << 2) | wire_type`, id 0..63:
|
||||
|
||||
| wire type | value |
|
||||
|---|---|
|
||||
| 0 | varint: LEB128, unsigned 32 bit (low 7 bits first, bit 7 = more). Signed values are **zigzag** `(x << 1) ^ (x >> 31)` |
|
||||
| 1 | length (varint) + that many bytes |
|
||||
| 2, 3 | reserved; a reader that meets one drops the page |
|
||||
|
||||
A reader **skips ids it does not know** (wt 0: read the varint; wt 1: skip the
|
||||
length), so ids can be added without a version bump. The version byte changes
|
||||
only when an existing id changes meaning. Only **non-zero** counters are sent;
|
||||
an absent counter is 0. Always sent for an admin: ids 32, 33, 34 (see below).
|
||||
|
||||
### Ids
|
||||
|
||||
| id | name | value |
|
||||
|---|---|---|
|
||||
| 1 | `batt_mv` | mV |
|
||||
| 2 | `temp_dc` | MCU temperature, 0.1 C, zigzag (absent when the board has none; sent even when 0) |
|
||||
| 3 | `uptime` | s |
|
||||
| 4 / 5 | `air_tx` / `air_rx` | total TX / RX airtime, s |
|
||||
| 6 / 7 | `noise` / `rssi` | dBm, zigzag |
|
||||
| 8 | `snr4` | SNR x 4, zigzag |
|
||||
| 9 | `tx_queue` | packets in the outbound queue |
|
||||
| 10 / 11 | `recv` / `sent` | packets |
|
||||
| 12 / 13 | `sent_flood` / `sent_direct` | |
|
||||
| 14 / 15 | `recv_flood` / `recv_direct` | |
|
||||
| 16 | `err_events` | error flag bits |
|
||||
| 17 / 18 | `direct_dups` / `flood_dups` | |
|
||||
| 19 | `recv_errors` | |
|
||||
| 20 / 21 | `tx_start_fail` / `tx_timeout` | |
|
||||
| | *the fields of `RepeaterStats` plus telemetry; ids 1..21 are all a guest sees* | |
|
||||
| 24 | `fair_group` | FairnessLimiter drops, channel (group) bucket |
|
||||
| 25 | `fair_sender` | sender bucket |
|
||||
| 26 | `fair_advert` | advert bucket |
|
||||
| 27 | `fair_window` | per-origin advert window |
|
||||
| 32 | `rules_auto` | `count << 16 \| crc16` of the `auto` `filter flow` rules |
|
||||
| 33 | `rules_static` | the same for the static ones |
|
||||
| 34 | `prefs_crc` | `prefs_crc16`, below |
|
||||
| 35 | `pwr_flags` | adaptive battery power save (`set pwr.rxgain` / `set pwr.rxps`): bit 0 rxgain stage active, bit 1 rxps stage active, bit 2 rxgain configured, bit 3 rxps configured |
|
||||
| 36 | `n_counters` | number of flow slots with a non-zero counter (see "Pages") |
|
||||
| 40 (wt 1) | `counters` | a run of triples `slot, dropped, passed`, each a varint |
|
||||
| 41 (wt 1) | `rule` | one rule, below |
|
||||
|
||||
`rules_auto` / `rules_static` are the `crc16` values of `filter flow`
|
||||
(CRC-16/CCITT-FALSE over the canonical serialization, see
|
||||
[tth-commands.md](tth-commands.md#forward-deny-rules----filter-flow-every-repeater)
|
||||
and `test/vectors/flow_rules_vectors.json`), with the entry count above them.
|
||||
An empty set is `0x0000FFFF`.
|
||||
|
||||
**Rule record** (id 41): `slot` (varint) `kind` (1 B, ASCII) `klen` (1 B)
|
||||
`key` (klen B) `mf` (1 B) then, in this order and only when flagged,
|
||||
`secs` (varint, mode throttle), `expires` (varint, absolute unix),
|
||||
`left` (varint, seconds to expiry by the two clocks of `filter flow`).
|
||||
`mf`: bits 0-1 mode (0 block, 1 throttle, 2 dry), bit 2 `auto`, bit 3 has
|
||||
`expires`, bit 4 has `left`.
|
||||
|
||||
### Pages
|
||||
|
||||
`slot_id` is the index in the **sorted** rule table of `filter flow`
|
||||
((kind, key) order) and **moves on `add` / `del` / expiry**.
|
||||
|
||||
* **Page 0** is what is read every scrape: ids 1..21, fairness, ids 32..36 and
|
||||
as many `(slot, dropped, passed)` as fit in the 150 B -- for every slot with a
|
||||
non-zero counter, in slot order. A realistic node (2 rules, a few fairness
|
||||
drops, the full status) needs about 116 B including the rule records; all 16
|
||||
slots with counters do not fit, so the rest of the triples spills to page 1.
|
||||
* **Pages 1..** hold, in this order, the **spilled counter triples** (id 40, the
|
||||
slots that did not fit on page 0, still in slot order) and then the **rule
|
||||
metadata** (id 41), one record per slot in slot order. A record is never
|
||||
split; a page is closed when the next record does not fit. Every page after
|
||||
the first starts with the records `rules_auto` and `rules_static` (8 B).
|
||||
* `n_counters` (id 36) tells how many slots have counters. When the triples on
|
||||
page 0 are fewer than `n_counters`, the rest is on pages 1.. -- read them.
|
||||
|
||||
### Reader rule (pairing)
|
||||
|
||||
`(slot_id, dropped, passed)` means nothing without the table that numbered the
|
||||
slots. So:
|
||||
|
||||
1. Fetch page 0. Compare `rules_auto` and `rules_static` with the values of the
|
||||
previous scrape (the reader keeps its `slot_id -> rule` map and the CRCs it
|
||||
was built from).
|
||||
2. **If either CRC changed** (or the reader has no map yet): fetch pages 1.. **first**,
|
||||
build the new map from the rule records, and only then pair the page 0
|
||||
triples with it. Spilled counter triples (id 40 on pages 1..) are read in the
|
||||
same pass.
|
||||
3. If `n_counters` is greater than the triples on page 0 but the CRCs did not
|
||||
change, fetch the pages 1.. for the spilled counters as well.
|
||||
4. **Every page 1.. opens with the two CRC records (ids 32, 33) of page 0.** If
|
||||
the pair on any later page differs from page 0, the table changed between the
|
||||
requests (a concurrent `add`, an expiry): **drop this scrape's counters** and
|
||||
try the next scrape. Never assign numbers to old keys.
|
||||
|
||||
When the CRCs are unchanged and nothing spilled, the reader needs no page 1.. at
|
||||
all: one request, one reply. The drift check against the signed inventory (#44) compares
|
||||
`rules_static` and `prefs_crc` with the values computed from it; the agent
|
||||
(#43) does the same for `rules_auto`.
|
||||
|
||||
## `prefs_crc16`
|
||||
|
||||
CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflection, no final xor;
|
||||
check value of "123456789" is 0x29B1) over the canonical serialization of the
|
||||
prefs that Ansible manages. All integers big-endian.
|
||||
|
||||
| # | bytes | field | encoding |
|
||||
|---|---|---|---|
|
||||
| 1 | 1 | serialization version | `1` |
|
||||
| 2 | 4 | radio frequency | MHz x 1000 rounded: `round(869.432 * 1000)` = 869432 |
|
||||
| 3 | 4 | bandwidth | kHz x 1000 rounded (62.5 -> 62500) |
|
||||
| 4 | 1 | `sf` | |
|
||||
| 5 | 1 | `cr` | |
|
||||
| 6 | 1 | TX power | dBm, two's complement |
|
||||
| 7 | 1 + n | node name | length (<= 31) + the UTF-8 bytes as stored |
|
||||
| 8 | 1 | advert interval | the stored value (`advert_interval`, minutes / 2) |
|
||||
| 9 | 1 | flood advert interval | hours |
|
||||
| 10 | 1 | `flood.max` | |
|
||||
| 11 | 1 | `flood.max` unscoped | |
|
||||
| 12 | 1 | `flood.max` advert | |
|
||||
| 13 | 1 | path hash mode | |
|
||||
| 14 | 1 | `repeat` | the stored `disable_fwd` (1 = repeating off) |
|
||||
| 15 | 1 | `powersaving` | 0 / 1 |
|
||||
| 16 | 1 | `radio.rxgain` | `rx_boosted_gain` 0 / 1 |
|
||||
| 17 | 1 | `rxps` enabled | 0 / 1 (all `rxps` bytes 0 in a build without `WITH_RX_POWERSAVING`) |
|
||||
| 18 | 4 | `rxps` RX time | microseconds |
|
||||
| 19 | 4 | `rxps` sleep time | microseconds |
|
||||
| 20 | 1 | `rxps` level | |
|
||||
| 21 | 1 | `rxps` preamble | |
|
||||
| 22 | 1 | bridge | `bridge.enabled` 0 / 1 |
|
||||
|
||||
Reference: `prefs_canonical()` in `test/vectors/gen_stats_bundle_vectors.py`;
|
||||
test vectors (canonical bytes and CRC for two nodes) in
|
||||
`test/vectors/stats_bundle_vectors.json`.
|
||||
|
||||
**Not in it:** the `filter flow` rules (they have `rules_auto` /
|
||||
`rules_static`), `filter` age and dry-run, FairnessLimiter caps, passwords,
|
||||
guest and ACL entries, regions (the region map is persisted in its own file, not
|
||||
in the prefs -- extending the CRC to it needs a canonical order of the map; open),
|
||||
the adaptive battery thresholds (`pwr.*`, their own files) and GPS settings.
|
||||
Adding a field means a new serialization version byte (and a new vector).
|
||||
|
||||
## Sizes
|
||||
|
||||
| case | page 0 |
|
||||
|---|---|
|
||||
| guest (status + telemetry) | 60 B |
|
||||
| admin, empty table, short status | 18 B |
|
||||
| admin, 2 rules, a few fairness drops, full status | 116 B (one page) |
|
||||
| admin, 16 rules with counters | 149 B + 145 B + 150 B + 70 B (4 pages) |
|
||||
|
||||
The boundary cases (149 / 150 B fit, 151 B moves the last record to page 1)
|
||||
are in the vectors.
|
||||
@@ -197,6 +197,16 @@ clock reads before 2026; a clock running ahead makes everything look old.
|
||||
|---|---|
|
||||
| `filter dryrun [on\|off]` | count every `filter` verdict (sender, flow, age) but forward anyway -- try a rule on a live node before it bites; without an argument shows the state. Default: off |
|
||||
|
||||
## Stats bundle -- one request per scrape (repeater)
|
||||
|
||||
A binary request (`0xF1`, not a console command) that returns status, telemetry,
|
||||
FairnessLimiter drops, per-rule `filter flow` counters, the rule CRCs
|
||||
(`rules_crc16`, auto and static), `prefs_crc16` and the adaptive power save
|
||||
stage in one reply of at most 150 B, paged when it does not fit. Admin gets
|
||||
everything, a guest what `GET_STATUS` gives. Byte format, ids, paging, the
|
||||
pairing rule for `slot_id` and the `prefs_crc16` field list:
|
||||
[stats-bundle.md](stats-bundle.md).
|
||||
|
||||
## Radio watchdogs and board upkeep (all)
|
||||
|
||||
Details: [cli_commands.md](cli_commands.md), "Radio silence watchdog", "TX
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <helpers/CliArgs.h>
|
||||
#include <helpers/sensors/LPPDataHelpers.h>
|
||||
#include <helpers/UTF8Helpers.h>
|
||||
#include <helpers/StatsBundle.h>
|
||||
|
||||
/* ------------------------------ Config -------------------------------- */
|
||||
|
||||
@@ -576,6 +577,66 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
|
||||
return n > 0 ? 4 + n : 0;
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): stats bundle (REQ_TYPE_STATS_BUNDLE = 0xF1) -- status,
|
||||
// telemetry, fairness drops, `filter flow` counters and CRCs in one reply
|
||||
// (docs/stats-bundle.md). Guests get what GET_STATUS gives them (status and
|
||||
// base telemetry, one page); the rest is admin only. 150 B budget as for 0xF0.
|
||||
if (payload[0] == REQ_TYPE_STATS_BUNDLE) {
|
||||
extern uint8_t maintPwrSaveFlags();
|
||||
StatsBundleIn in;
|
||||
memset(&in, 0, sizeof(in));
|
||||
in.admin = sender->isAdmin();
|
||||
in.v[SB_BATT_MV] = board.getBattMilliVolts();
|
||||
float temperature = board.getMCUTemperature();
|
||||
if (!isnan(temperature)) { in.has_temp = true; in.v[SB_TEMP_DC] = (uint32_t)(int32_t)lroundf(temperature * 10.0f); }
|
||||
in.v[SB_UPTIME] = uptime_millis / 1000;
|
||||
in.v[SB_AIR_TX] = getTotalAirTime() / 1000;
|
||||
in.v[SB_AIR_RX] = getReceiveAirTime() / 1000;
|
||||
in.v[SB_NOISE] = (uint32_t)(int32_t)(int16_t)_radio->getNoiseFloor();
|
||||
in.v[SB_RSSI] = (uint32_t)(int32_t)(int16_t)radio_driver.getLastRSSI();
|
||||
in.v[SB_SNR4] = (uint32_t)(int32_t)(int16_t)(radio_driver.getLastSNR() * 4);
|
||||
in.v[SB_TX_QUEUE] = _mgr->getOutboundTotal();
|
||||
in.v[SB_RECV] = radio_driver.getPacketsRecv();
|
||||
in.v[SB_SENT] = radio_driver.getPacketsSent();
|
||||
in.v[SB_SENT_FLOOD] = getNumSentFlood();
|
||||
in.v[SB_SENT_DIRECT] = getNumSentDirect();
|
||||
in.v[SB_RECV_FLOOD] = getNumRecvFlood();
|
||||
in.v[SB_RECV_DIRECT] = getNumRecvDirect();
|
||||
in.v[SB_ERR_EVENTS] = _err_flags;
|
||||
in.v[SB_DIRECT_DUPS] = ((SimpleMeshTables *)getTables())->getNumDirectDups();
|
||||
in.v[SB_FLOOD_DUPS] = ((SimpleMeshTables *)getTables())->getNumFloodDups();
|
||||
in.v[SB_RECV_ERRORS] = radio_driver.getPacketsRecvErrors();
|
||||
in.v[SB_TX_START_FAIL] = getNumTxStartFail();
|
||||
in.v[SB_TX_TIMEOUT] = getNumTxTimeout();
|
||||
if (in.admin) {
|
||||
in.fair[0] = fairness_limiter.deniedGroup();
|
||||
in.fair[1] = fairness_limiter.deniedSenderNormal();
|
||||
in.fair[2] = fairness_limiter.deniedSenderLow();
|
||||
in.fair[3] = fairness_limiter.deniedWindow();
|
||||
in.pwr_flags = maintPwrSaveFlags();
|
||||
in.flow = &flow_table;
|
||||
in.now_ms = _ms->getMillis();
|
||||
in.now_unix = getRTCClock()->getCurrentTime();
|
||||
StatsPrefs sp;
|
||||
memset(&sp, 0, sizeof(sp));
|
||||
sp.freq_mhz = _prefs.freq; sp.bw_khz = _prefs.bw; sp.sf = _prefs.sf; sp.cr = _prefs.cr;
|
||||
sp.tx_dbm = _prefs.tx_power_dbm; sp.name = _prefs.node_name;
|
||||
sp.advert_interval = _prefs.advert_interval; sp.flood_advert_interval = _prefs.flood_advert_interval;
|
||||
sp.flood_max = _prefs.flood_max; sp.flood_max_unscoped = _prefs.flood_max_unscoped;
|
||||
sp.flood_max_advert = _prefs.flood_max_advert; sp.path_hash_mode = _prefs.path_hash_mode;
|
||||
sp.disable_fwd = _prefs.disable_fwd; sp.powersaving = _prefs.powersaving_enabled;
|
||||
sp.rx_boosted_gain = _prefs.rx_boosted_gain; sp.bridge_enabled = _prefs.bridge_enabled;
|
||||
#ifdef WITH_RX_POWERSAVING
|
||||
sp.rxps_enabled = _prefs.rxps.enabled; sp.rxps_rx_us = _prefs.rxps.rx_us;
|
||||
sp.rxps_sleep_us = _prefs.rxps.sleep_us; sp.rxps_level = _prefs.rxps.level;
|
||||
sp.rxps_preamble = _prefs.rxps.preamble;
|
||||
#endif
|
||||
in.prefs_crc = sbPrefsCrc(sp);
|
||||
}
|
||||
int n = sbEncode(in, payload_len >= 2 ? payload[1] : 0, &reply_data[4], SB_PAGE_MAX);
|
||||
return n > 0 ? 4 + n : 0;
|
||||
}
|
||||
|
||||
if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
|
||||
RepeaterStats stats;
|
||||
stats.batt_milli_volts = board.getBattMilliVolts();
|
||||
|
||||
@@ -658,6 +658,9 @@ int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply,
|
||||
return maint.handleRequest(admin, req, len, reply, reply_max);
|
||||
}
|
||||
|
||||
// CUSTOM (TeTeHacko): power save stages for the stats bundle (REQ_TYPE_STATS_BUNDLE).
|
||||
uint8_t maintPwrSaveFlags() { return maint.pwrSaveFlags(); }
|
||||
|
||||
#ifdef RADIO_DIAG
|
||||
// CUSTOM (TeTeHacko): `radiostat` / `radiokick` -- see RadioLibWrappers.cpp.
|
||||
// On the masts since 2. 11. 2026: mast-three came up deaf after a BLE OTA (recv 0,
|
||||
|
||||
@@ -82,6 +82,14 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
// Adaptive power save state for the stats bundle (helpers/StatsBundle.h,
|
||||
// SB_PWR_*): 1 rxgain stage active, 2 rxps stage active, 4 rxgain configured,
|
||||
// 8 rxps configured.
|
||||
uint8_t pwrSaveFlags() const {
|
||||
return (_pwr_save.rxgainActive() ? 1 : 0) | (_pwr_save.rxpsActive() ? 2 : 0) |
|
||||
(_pwr_save.rxgainLow() ? 4 : 0) | (_pwr_save.rxpsLow() ? 8 : 0);
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t radioActivity() const { return _radio.getPacketsRecv() + _radio.getPacketsRecvErrors(); }
|
||||
void silenceLoad(uint8_t* backoff);
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
#pragma once
|
||||
|
||||
// CUSTOM (TeTeHacko): "stats bundle" -- ONE binary request that answers a whole
|
||||
// monitoring scrape (status + telemetry + fairness drops + `filter flow`
|
||||
// counters + rule/prefs CRCs) instead of login + req_status + req_telemetry +
|
||||
// CLI round trips (tth #42, epic #45). Header-only and free of mesh/Arduino
|
||||
// types so encoder and decoder run in the native tests; the glue (reading the
|
||||
// live node into StatsBundleIn) is MyMesh::handleRequest in simple_repeater.
|
||||
// Byte format, ids, paging and the prefs CRC: docs/stats-bundle.md.
|
||||
//
|
||||
// REQUEST [REQ_TYPE_STATS_BUNDLE = 0xF1][page] (page optional, default 0)
|
||||
// REPLY [ver=1][page<<4 | pages] then records, at most `max` bytes (150)
|
||||
// RECORD first byte = (id << 2) | wire type, id 0..63
|
||||
// wt 0: varint (LEB128, u32; signed values zigzag)
|
||||
// wt 1: length (varint) + that many bytes
|
||||
// Unknown ids are skippable, so the format grows without breaking readers.
|
||||
// Only non-zero counters are sent. The CRC records (admin) are always sent.
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include "FlowRules.h"
|
||||
|
||||
#define SB_VERSION 1
|
||||
#define REQ_TYPE_STATS_BUNDLE 0xF1
|
||||
#define SB_PAGE_MAX 150 // reply budget after the 4 B tag (see MyMesh::handleRequest)
|
||||
#define SB_MAX_PAGES 15
|
||||
|
||||
// Scalar ids (wt 0). 1..21 = status + telemetry (a guest may read these).
|
||||
enum {
|
||||
SB_BATT_MV = 1, SB_TEMP_DC = 2 /* zigzag, 0.1 C */, SB_UPTIME = 3, SB_AIR_TX = 4, SB_AIR_RX = 5,
|
||||
SB_NOISE = 6 /* zigzag dBm */, SB_RSSI = 7 /* zigzag */, SB_SNR4 = 8 /* zigzag, x4 */, SB_TX_QUEUE = 9,
|
||||
SB_RECV = 10, SB_SENT = 11, SB_SENT_FLOOD = 12, SB_SENT_DIRECT = 13, SB_RECV_FLOOD = 14,
|
||||
SB_RECV_DIRECT = 15, SB_ERR_EVENTS = 16, SB_DIRECT_DUPS = 17, SB_FLOOD_DUPS = 18,
|
||||
SB_RECV_ERRORS = 19, SB_TX_START_FAIL = 20, SB_TX_TIMEOUT = 21,
|
||||
// admin only
|
||||
SB_FAIR_GROUP = 24, SB_FAIR_SENDER = 25, SB_FAIR_ADVERT = 26, SB_FAIR_WINDOW = 27,
|
||||
SB_RULES_AUTO = 32 /* count << 16 | crc16 */, SB_RULES_STATIC = 33, SB_PREFS_CRC = 34,
|
||||
SB_PWR_FLAGS = 35, SB_N_COUNTERS = 36,
|
||||
// wt 1
|
||||
SB_COUNTERS = 40 /* run of (slot, dropped, passed) varints */, SB_RULE = 41,
|
||||
};
|
||||
#define SB_LAST_STATUS_ID 21
|
||||
|
||||
#define SB_PWR_RXGAIN_ACTIVE 0x01
|
||||
#define SB_PWR_RXPS_ACTIVE 0x02
|
||||
#define SB_PWR_RXGAIN_SET 0x04
|
||||
#define SB_PWR_RXPS_SET 0x08
|
||||
|
||||
#define SB_BODY_MAX (FLOW_MAX * 11)
|
||||
|
||||
struct StatsBundleIn {
|
||||
bool admin;
|
||||
uint32_t v[SB_LAST_STATUS_ID + 1]; // by id; signed ones as int32 cast, zigzagged on the wire
|
||||
bool has_temp;
|
||||
uint32_t fair[4]; // group, sender, advert, window
|
||||
uint8_t pwr_flags;
|
||||
uint16_t prefs_crc;
|
||||
const FlowTable* flow;
|
||||
uint32_t now_ms, now_unix;
|
||||
};
|
||||
|
||||
// -- encoding ---------------------------------------------------------------
|
||||
|
||||
inline uint8_t sbVarint(uint32_t x, uint8_t* o) {
|
||||
uint8_t n = 0;
|
||||
while (x >= 0x80) { o[n++] = (uint8_t)(x | 0x80); x >>= 7; }
|
||||
o[n++] = (uint8_t)x;
|
||||
return n;
|
||||
}
|
||||
inline uint8_t sbVarSize(uint32_t x) { uint8_t t[5]; return sbVarint(x, t); }
|
||||
inline uint32_t sbZigzag(int32_t x) { return ((uint32_t)x << 1) ^ (uint32_t)(x >> 31); }
|
||||
inline int32_t sbUnzigzag(uint32_t x) { return (int32_t)(x >> 1) ^ -(int32_t)(x & 1); }
|
||||
|
||||
class SbWriter {
|
||||
public:
|
||||
uint8_t* out;
|
||||
int max, target, cur, used, tlen; // tlen = length of the target page
|
||||
uint8_t pre[10]; // opens every page after the first (the rule CRCs)
|
||||
int pre_len;
|
||||
SbWriter(uint8_t* o, int m, int t) : out(o), max(m), target(t), cur(0), used(2), tlen(-1), pre_len(0) {}
|
||||
void brk() {
|
||||
if (cur == target) tlen = used;
|
||||
cur++;
|
||||
used = 2;
|
||||
if (cur == target && pre_len) memcpy(&out[used], pre, pre_len);
|
||||
used += pre_len;
|
||||
}
|
||||
// Whole record; starts a new page when it does not fit (never splits one).
|
||||
void add(const uint8_t* rec, int n) {
|
||||
if (used + n > max && used > 2 + pre_len) brk();
|
||||
if (cur == target && used + n <= max) memcpy(&out[used], rec, n);
|
||||
used += n;
|
||||
}
|
||||
void scalar(uint8_t id, uint32_t val) {
|
||||
uint8_t r[6];
|
||||
r[0] = (uint8_t)(id << 2);
|
||||
add(r, 1 + sbVarint(val, &r[1]));
|
||||
}
|
||||
void blob(uint8_t id, const uint8_t* b, int n) {
|
||||
uint8_t h[6];
|
||||
h[0] = (uint8_t)((id << 2) | 1);
|
||||
int hl = 1 + sbVarint((uint32_t)n, &h[1]);
|
||||
if (used + hl + n > max && used > 2 + pre_len) brk();
|
||||
if (cur == target && used + hl + n <= max) { memcpy(&out[used], h, hl); memcpy(&out[used + hl], b, n); }
|
||||
used += hl + n;
|
||||
}
|
||||
bool fits(int body) const { return used + 1 + sbVarSize((uint32_t)body) + body <= max; }
|
||||
int pages() const { return cur + 1; }
|
||||
int finish() { if (cur == target) tlen = used; return tlen; }
|
||||
};
|
||||
|
||||
inline uint8_t sbRuleRecord(const FlowTable& t, int i, uint32_t now_ms, uint32_t now_unix, uint8_t* o) {
|
||||
const FlowRule& r = t.e[i].r;
|
||||
uint8_t n = 0;
|
||||
n += sbVarint((uint32_t)i, &o[n]);
|
||||
o[n++] = r.kind;
|
||||
o[n++] = r.klen;
|
||||
memcpy(&o[n], r.key, r.klen);
|
||||
n += r.klen;
|
||||
uint32_t left = 0;
|
||||
bool has_left = t.remaining(i, now_ms, now_unix, &left);
|
||||
bool has_exp = r.expires != 0;
|
||||
o[n++] = (uint8_t)((r.mode & 3) | ((r.flags & FLOW_FLAG_AUTO) ? 4 : 0) | (has_exp ? 8 : 0) | (has_left ? 16 : 0));
|
||||
if (r.mode == FLOW_THROTTLE) n += sbVarint(r.secs, &o[n]);
|
||||
if (has_exp) n += sbVarint(r.expires, &o[n]);
|
||||
if (has_left) n += sbVarint(left, &o[n]);
|
||||
return n;
|
||||
}
|
||||
|
||||
// Page `page` of the bundle into out[0..max). Returns its length, or -1 when
|
||||
// the page does not exist. Page 0 holds status, telemetry, fairness, CRCs,
|
||||
// power state and as many (slot, dropped, passed) as fit; what does not fit
|
||||
// spills to pages 1.. ahead of the rule metadata (SB_N_COUNTERS tells how many
|
||||
// slots have counters, so a reader sees a spill). Every page after the first
|
||||
// opens with the two rule CRC records of page 0. A guest gets status and
|
||||
// telemetry only, one page.
|
||||
inline int sbEncode(const StatsBundleIn& in, uint8_t page, uint8_t* out, int max) {
|
||||
if (max < 40) return -1;
|
||||
SbWriter w(out, max, page);
|
||||
static const uint8_t zz[] = {SB_TEMP_DC, SB_NOISE, SB_RSSI, SB_SNR4};
|
||||
for (uint8_t id = 1; id <= SB_LAST_STATUS_ID; id++) {
|
||||
if (id == SB_TEMP_DC && !in.has_temp) continue;
|
||||
uint32_t x = in.v[id];
|
||||
bool z = false;
|
||||
for (uint8_t k = 0; k < sizeof(zz); k++) if (zz[k] == id) z = true;
|
||||
if (z) x = sbZigzag((int32_t)x);
|
||||
if (x != 0 || (id == SB_TEMP_DC && in.has_temp)) w.scalar(id, x);
|
||||
}
|
||||
if (in.admin) {
|
||||
for (uint8_t k = 0; k < 4; k++) if (in.fair[k]) w.scalar(SB_FAIR_GROUP + k, in.fair[k]);
|
||||
int ca = 0, cs = 0;
|
||||
uint16_t ra = in.flow->crc(true, &ca), rs = in.flow->crc(false, &cs);
|
||||
w.scalar(SB_RULES_AUTO, ((uint32_t)ca << 16) | ra);
|
||||
w.scalar(SB_RULES_STATIC, ((uint32_t)cs << 16) | rs);
|
||||
// the same two records open every further page, so a reader can tell
|
||||
// whether the table changed between page 0 and that page
|
||||
w.pre[0] = (uint8_t)(SB_RULES_AUTO << 2);
|
||||
w.pre_len = 1 + sbVarint(((uint32_t)ca << 16) | ra, &w.pre[1]);
|
||||
w.pre[w.pre_len] = (uint8_t)(SB_RULES_STATIC << 2);
|
||||
w.pre_len += 1 + sbVarint(((uint32_t)cs << 16) | rs, &w.pre[w.pre_len + 1]);
|
||||
w.scalar(SB_PREFS_CRC, in.prefs_crc);
|
||||
if (in.pwr_flags) w.scalar(SB_PWR_FLAGS, in.pwr_flags);
|
||||
int nc = 0;
|
||||
for (uint8_t i = 0; i < in.flow->n; i++) if (in.flow->e[i].dropped || in.flow->e[i].passed) nc++;
|
||||
if (nc) w.scalar(SB_N_COUNTERS, (uint32_t)nc);
|
||||
uint8_t body[SB_BODY_MAX];
|
||||
int bl = 0;
|
||||
for (uint8_t i = 0; i < in.flow->n; i++) {
|
||||
const FlowEntry& x = in.flow->e[i];
|
||||
if (!x.dropped && !x.passed) continue;
|
||||
uint8_t t[16], tl = 0;
|
||||
tl += sbVarint(i, &t[tl]);
|
||||
tl += sbVarint(x.dropped, &t[tl]);
|
||||
tl += sbVarint(x.passed, &t[tl]);
|
||||
if (bl > 0 && !w.fits(bl + tl)) { w.blob(SB_COUNTERS, body, bl); bl = 0; }
|
||||
memcpy(&body[bl], t, tl);
|
||||
bl += tl;
|
||||
}
|
||||
if (bl > 0) w.blob(SB_COUNTERS, body, bl);
|
||||
for (uint8_t i = 0; i < in.flow->n; i++) {
|
||||
uint8_t r[32];
|
||||
uint8_t rl = sbRuleRecord(*in.flow, i, in.now_ms, in.now_unix, r);
|
||||
w.blob(SB_RULE, r, rl);
|
||||
}
|
||||
}
|
||||
int pages = w.pages();
|
||||
int tl = w.finish();
|
||||
if (page >= pages || pages > SB_MAX_PAGES) return -1;
|
||||
out[0] = SB_VERSION;
|
||||
out[1] = (uint8_t)((page << 4) | pages);
|
||||
return tl;
|
||||
}
|
||||
|
||||
// -- decoding ---------------------------------------------------------------
|
||||
|
||||
struct SbCounter { uint8_t slot; uint32_t dropped, passed; };
|
||||
struct SbRule {
|
||||
uint8_t slot, kind, klen, key[FLOW_KEY_MAX], mode;
|
||||
bool is_auto, has_expires, has_left;
|
||||
uint16_t secs;
|
||||
uint32_t expires, left;
|
||||
};
|
||||
struct SbScalar { uint8_t id; uint32_t v; };
|
||||
|
||||
#define SB_DEC_MAX_SCALARS 40
|
||||
struct StatsBundleOut {
|
||||
uint8_t ver, page, pages;
|
||||
SbScalar sc[SB_DEC_MAX_SCALARS];
|
||||
uint8_t n_sc;
|
||||
SbCounter ctr[FLOW_MAX];
|
||||
uint8_t n_ctr;
|
||||
SbRule rule[FLOW_MAX];
|
||||
uint8_t n_rule;
|
||||
// Value of scalar `id`, `dflt` when absent (an absent counter is 0).
|
||||
uint32_t get(uint8_t id, uint32_t dflt = 0) const {
|
||||
for (uint8_t i = 0; i < n_sc; i++) if (sc[i].id == id) return sc[i].v;
|
||||
return dflt;
|
||||
}
|
||||
bool has(uint8_t id) const {
|
||||
for (uint8_t i = 0; i < n_sc; i++) if (sc[i].id == id) return true;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
inline bool sbReadVar(const uint8_t* b, int len, int* pos, uint32_t* v) {
|
||||
uint32_t x = 0;
|
||||
for (int s = 0; s < 35; s += 7) {
|
||||
if (*pos >= len) return false;
|
||||
uint8_t c = b[(*pos)++];
|
||||
x |= (uint32_t)(c & 0x7F) << s;
|
||||
if (!(c & 0x80)) { *v = x; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool sbDecodeRule(const uint8_t* b, int len, SbRule* r) {
|
||||
int p = 0;
|
||||
uint32_t v;
|
||||
memset(r, 0, sizeof(*r));
|
||||
if (!sbReadVar(b, len, &p, &v) || v >= FLOW_MAX) return false;
|
||||
r->slot = (uint8_t)v;
|
||||
if (p + 2 > len) return false;
|
||||
r->kind = b[p++];
|
||||
r->klen = b[p++];
|
||||
if (r->klen > FLOW_KEY_MAX || p + r->klen + 1 > len) return false;
|
||||
memcpy(r->key, &b[p], r->klen);
|
||||
p += r->klen;
|
||||
uint8_t mf = b[p++];
|
||||
r->mode = mf & 3; r->is_auto = (mf & 4) != 0; r->has_expires = (mf & 8) != 0; r->has_left = (mf & 16) != 0;
|
||||
if (r->mode == FLOW_THROTTLE) {
|
||||
if (!sbReadVar(b, len, &p, &v) || v > 65535) return false;
|
||||
r->secs = (uint16_t)v;
|
||||
}
|
||||
if (r->has_expires && !sbReadVar(b, len, &p, &r->expires)) return false;
|
||||
if (r->has_left && !sbReadVar(b, len, &p, &r->left)) return false;
|
||||
return p == len;
|
||||
}
|
||||
|
||||
// false on a malformed or unknown-version page. Unknown ids are skipped.
|
||||
inline bool sbDecode(const uint8_t* b, int len, StatsBundleOut* o) {
|
||||
memset(o, 0, sizeof(*o));
|
||||
if (len < 2 || b[0] != SB_VERSION) return false;
|
||||
o->ver = b[0];
|
||||
o->page = b[1] >> 4;
|
||||
o->pages = b[1] & 15;
|
||||
if (o->pages == 0 || o->page >= o->pages) return false;
|
||||
int p = 2;
|
||||
while (p < len) {
|
||||
uint8_t rk = b[p++];
|
||||
uint8_t id = rk >> 2, wt = rk & 3;
|
||||
uint32_t v;
|
||||
if (wt == 0) {
|
||||
if (!sbReadVar(b, len, &p, &v) || o->n_sc >= SB_DEC_MAX_SCALARS) return false;
|
||||
o->sc[o->n_sc].id = id;
|
||||
o->sc[o->n_sc].v = v;
|
||||
o->n_sc++;
|
||||
} else if (wt == 1) {
|
||||
uint32_t bl;
|
||||
if (!sbReadVar(b, len, &p, &bl) || bl > (uint32_t)(len - p)) return false;
|
||||
const uint8_t* body = &b[p];
|
||||
if (id == SB_COUNTERS) {
|
||||
int q = 0;
|
||||
while (q < (int)bl) {
|
||||
uint32_t s, d, pa;
|
||||
if (!sbReadVar(body, (int)bl, &q, &s) || !sbReadVar(body, (int)bl, &q, &d) ||
|
||||
!sbReadVar(body, (int)bl, &q, &pa)) return false;
|
||||
if (o->n_ctr >= FLOW_MAX || s >= FLOW_MAX) return false;
|
||||
o->ctr[o->n_ctr].slot = (uint8_t)s;
|
||||
o->ctr[o->n_ctr].dropped = d;
|
||||
o->ctr[o->n_ctr].passed = pa;
|
||||
o->n_ctr++;
|
||||
}
|
||||
} else if (id == SB_RULE) {
|
||||
if (o->n_rule >= FLOW_MAX || !sbDecodeRule(body, (int)bl, &o->rule[o->n_rule])) return false;
|
||||
o->n_rule++;
|
||||
}
|
||||
p += (int)bl;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// -- prefs CRC --------------------------------------------------------------
|
||||
// CRC-16/CCITT-FALSE over the canonical serialization (docs/stats-bundle.md).
|
||||
|
||||
struct StatsPrefs {
|
||||
float freq_mhz, bw_khz;
|
||||
uint8_t sf, cr;
|
||||
int8_t tx_dbm;
|
||||
const char* name;
|
||||
uint8_t advert_interval, flood_advert_interval, flood_max, flood_max_unscoped, flood_max_advert;
|
||||
uint8_t path_hash_mode, disable_fwd, powersaving, rx_boosted_gain;
|
||||
uint8_t rxps_enabled, rxps_level, rxps_preamble;
|
||||
uint32_t rxps_rx_us, rxps_sleep_us;
|
||||
uint8_t bridge_enabled;
|
||||
};
|
||||
|
||||
inline uint32_t sbRound1000(float x) { double d = (double)x * 1000.0; return (uint32_t)(d + 0.5); }
|
||||
|
||||
inline uint16_t sbPrefsCrc(const StatsPrefs& p) {
|
||||
uint8_t b[96];
|
||||
int n = 0;
|
||||
uint32_t f = sbRound1000(p.freq_mhz), w = sbRound1000(p.bw_khz);
|
||||
b[n++] = 1; // serialization version
|
||||
for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(f >> (8 * i));
|
||||
for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(w >> (8 * i));
|
||||
b[n++] = p.sf; b[n++] = p.cr; b[n++] = (uint8_t)p.tx_dbm;
|
||||
size_t nl = 0;
|
||||
while (p.name && nl < 31 && p.name[nl]) nl++;
|
||||
b[n++] = (uint8_t)nl;
|
||||
memcpy(&b[n], p.name, nl);
|
||||
n += (int)nl;
|
||||
b[n++] = p.advert_interval; b[n++] = p.flood_advert_interval;
|
||||
b[n++] = p.flood_max; b[n++] = p.flood_max_unscoped; b[n++] = p.flood_max_advert;
|
||||
b[n++] = p.path_hash_mode; b[n++] = p.disable_fwd; b[n++] = p.powersaving; b[n++] = p.rx_boosted_gain;
|
||||
b[n++] = p.rxps_enabled;
|
||||
for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(p.rxps_rx_us >> (8 * i));
|
||||
for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(p.rxps_sleep_us >> (8 * i));
|
||||
b[n++] = p.rxps_level; b[n++] = p.rxps_preamble;
|
||||
b[n++] = p.bridge_enabled;
|
||||
return flowCrc16(0xFFFF, b, (size_t)n);
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <string>
|
||||
#include "helpers/StatsBundle.h"
|
||||
|
||||
// Cases and expected bytes mirror test/vectors/stats_bundle_vectors.json
|
||||
// (test/vectors/gen_stats_bundle_vectors.py); keep the two in step.
|
||||
|
||||
static std::string hex(const uint8_t* b, int n) {
|
||||
std::string s;
|
||||
char t[3];
|
||||
for (int i = 0; i < n; i++) { snprintf(t, sizeof(t), "%02x", b[i]); s += t; }
|
||||
return s;
|
||||
}
|
||||
|
||||
static void fillStatus(StatsBundleIn& in) {
|
||||
memset(&in, 0, sizeof(in));
|
||||
in.v[SB_BATT_MV] = 3987; in.v[SB_TEMP_DC] = 215; in.has_temp = true; in.v[SB_UPTIME] = 1234567;
|
||||
in.v[SB_AIR_TX] = 842; in.v[SB_AIR_RX] = 51234; in.v[SB_NOISE] = (uint32_t)-113; in.v[SB_RSSI] = (uint32_t)-97;
|
||||
in.v[SB_SNR4] = (uint32_t)-22; in.v[SB_RECV] = 148233; in.v[SB_SENT] = 9120; in.v[SB_SENT_FLOOD] = 8011;
|
||||
in.v[SB_SENT_DIRECT] = 1109; in.v[SB_RECV_FLOOD] = 130011; in.v[SB_RECV_DIRECT] = 18222;
|
||||
in.v[SB_DIRECT_DUPS] = 412; in.v[SB_FLOOD_DUPS] = 20991; in.v[SB_RECV_ERRORS] = 3071; in.v[SB_TX_TIMEOUT] = 2;
|
||||
}
|
||||
|
||||
static FlowRule R(uint8_t kind, uint32_t k, uint8_t klen, uint8_t mode, uint16_t secs, bool au, uint32_t exp,
|
||||
uint32_t remain) {
|
||||
FlowRule r;
|
||||
memset(&r, 0, sizeof(r));
|
||||
r.kind = kind; r.klen = klen;
|
||||
for (int i = 0; i < klen; i++) r.key[i] = (uint8_t)(k >> (8 * (klen - 1 - i)));
|
||||
r.mode = mode; r.secs = secs; r.flags = au ? FLOW_FLAG_AUTO : 0; r.expires = exp; r.remain = remain;
|
||||
return r;
|
||||
}
|
||||
|
||||
static void many(FlowTable& t, int n, uint32_t dropped, uint32_t passed) {
|
||||
t.clearAll();
|
||||
for (int i = 0; i < n; i++) {
|
||||
t.add(R('a', 0x11000000u + i, 4, FLOW_THROTTLE, 1800, i % 2 == 0, 1800000000u + i, 3600u * (i + 1)), 0);
|
||||
}
|
||||
for (int i = 0; i < n; i++) { t.e[i].dropped = dropped + i; t.e[i].passed = passed; }
|
||||
}
|
||||
|
||||
static void twoRules(FlowTable& t) {
|
||||
t.clearAll();
|
||||
t.add(R('c', 0x2e, 1, FLOW_THROTTLE, 1800, false, 0, 604800), 0);
|
||||
t.add(R('r', 0x8b2c, 2, FLOW_BLOCK, 0, true, 1800000000u, 0), 0);
|
||||
t.e[0].dropped = 416; t.e[0].passed = 14; t.e[1].dropped = 37;
|
||||
}
|
||||
|
||||
static int enc(const StatsBundleIn& in, int page, uint8_t* o, int max = SB_PAGE_MAX) {
|
||||
return sbEncode(in, (uint8_t)page, o, max);
|
||||
}
|
||||
|
||||
static uint16_t crc(const uint8_t* b, int n) { return flowCrc16(0xFFFF, b, n); }
|
||||
|
||||
TEST(StatsBundle, VarintAndZigzag) {
|
||||
uint8_t b[6];
|
||||
EXPECT_EQ(1, sbVarint(0, b)); EXPECT_EQ(1, sbVarint(127, b)); EXPECT_EQ(2, sbVarint(128, b));
|
||||
EXPECT_EQ(5, sbVarint(0xFFFFFFFFu, b));
|
||||
int p = 0; uint32_t v;
|
||||
EXPECT_TRUE(sbReadVar(b, 5, &p, &v)); EXPECT_EQ(0xFFFFFFFFu, v);
|
||||
EXPECT_EQ(0u, sbZigzag(0)); EXPECT_EQ(1u, sbZigzag(-1)); EXPECT_EQ(2u, sbZigzag(1));
|
||||
EXPECT_EQ(-113, sbUnzigzag(sbZigzag(-113)));
|
||||
uint8_t bad[6] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x01}; // too long
|
||||
p = 0; EXPECT_FALSE(sbReadVar(bad, 6, &p, &v));
|
||||
}
|
||||
|
||||
TEST(StatsBundle, AdminEmptyBytesMatchVector) {
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
memset(in.v, 0, sizeof(in.v)); in.has_temp = false;
|
||||
in.v[SB_BATT_MV] = 4012; in.v[SB_UPTIME] = 90;
|
||||
FlowTable t; in.admin = true; in.flow = &t; in.prefs_crc = 0x1234;
|
||||
uint8_t o[200];
|
||||
int n = enc(in, 0, o);
|
||||
EXPECT_EQ("010104ac1f0c5a80ffff0384ffff0388b424", hex(o, n));
|
||||
EXPECT_EQ(-1, enc(in, 1, o));
|
||||
}
|
||||
|
||||
TEST(StatsBundle, GuestGetsStatusOnly) {
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
FlowTable t; twoRules(t);
|
||||
in.admin = false; in.flow = &t; in.prefs_crc = 1; in.fair[0] = 9; in.pwr_flags = 3;
|
||||
uint8_t o[200];
|
||||
int n = enc(in, 0, o);
|
||||
EXPECT_EQ(60, n); EXPECT_EQ(0x71F2, crc(o, n));
|
||||
StatsBundleOut d; ASSERT_TRUE(sbDecode(o, n, &d));
|
||||
EXPECT_EQ(1, d.pages);
|
||||
EXPECT_FALSE(d.has(SB_RULES_AUTO)); EXPECT_FALSE(d.has(SB_FAIR_GROUP)); EXPECT_FALSE(d.has(SB_PREFS_CRC));
|
||||
EXPECT_EQ(0, d.n_ctr); EXPECT_EQ(0, d.n_rule);
|
||||
EXPECT_EQ(3987u, d.get(SB_BATT_MV)); EXPECT_EQ(215, sbUnzigzag(d.get(SB_TEMP_DC)));
|
||||
EXPECT_EQ(-113, sbUnzigzag(d.get(SB_NOISE)));
|
||||
EXPECT_FALSE(d.has(SB_TX_QUEUE)); // zero counters are not sent
|
||||
EXPECT_EQ(-1, enc(in, 1, o));
|
||||
}
|
||||
|
||||
TEST(StatsBundle, TwoRulesRealisticPage0) {
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
FlowTable t; twoRules(t);
|
||||
in.admin = true; in.flow = &t; in.prefs_crc = 0xBEEF; in.pwr_flags = SB_PWR_RXPS_ACTIVE;
|
||||
in.fair[0] = 31; in.fair[1] = 4; in.fair[3] = 120;
|
||||
uint8_t o[200];
|
||||
int n = enc(in, 0, o);
|
||||
EXPECT_EQ(116, n); EXPECT_EQ(0x21A1, crc(o, n));
|
||||
StatsBundleOut d; ASSERT_TRUE(sbDecode(o, n, &d));
|
||||
EXPECT_EQ(1, d.pages);
|
||||
int ca, cs;
|
||||
uint16_t ra = t.crc(true, &ca), rs = t.crc(false, &cs);
|
||||
EXPECT_EQ(((uint32_t)ca << 16) | ra, d.get(SB_RULES_AUTO));
|
||||
EXPECT_EQ(((uint32_t)cs << 16) | rs, d.get(SB_RULES_STATIC));
|
||||
EXPECT_EQ(0xBEEFu, d.get(SB_PREFS_CRC));
|
||||
EXPECT_EQ(2u, d.get(SB_N_COUNTERS));
|
||||
ASSERT_EQ(2, d.n_ctr);
|
||||
EXPECT_EQ(0, d.ctr[0].slot); EXPECT_EQ(416u, d.ctr[0].dropped); EXPECT_EQ(14u, d.ctr[0].passed);
|
||||
EXPECT_EQ(1, d.ctr[1].slot); EXPECT_EQ(37u, d.ctr[1].dropped); EXPECT_EQ(0u, d.ctr[1].passed);
|
||||
ASSERT_EQ(2, d.n_rule);
|
||||
EXPECT_EQ('c', d.rule[0].kind); EXPECT_EQ(FLOW_THROTTLE, d.rule[0].mode); EXPECT_EQ(1800, d.rule[0].secs);
|
||||
EXPECT_TRUE(d.rule[0].has_left); EXPECT_EQ(604800u, d.rule[0].left); EXPECT_FALSE(d.rule[0].is_auto);
|
||||
EXPECT_EQ('r', d.rule[1].kind); EXPECT_TRUE(d.rule[1].is_auto); EXPECT_EQ(1800000000u, d.rule[1].expires);
|
||||
EXPECT_FALSE(d.rule[1].has_left);
|
||||
EXPECT_EQ(SB_PWR_RXPS_ACTIVE, d.get(SB_PWR_FLAGS));
|
||||
}
|
||||
|
||||
TEST(StatsBundle, SixteenRulesPageAcrossPages) {
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
FlowTable t; many(t, 16, 100000, 7);
|
||||
in.admin = true; in.flow = &t; in.prefs_crc = 0xBEEF; in.pwr_flags = 3;
|
||||
in.fair[0] = 31; in.fair[1] = 4; in.fair[3] = 120;
|
||||
uint8_t o[200];
|
||||
const int len[4] = {149, 145, 150, 70};
|
||||
const uint16_t c[4] = {0xF751, 0x6A00, 0xC955, 0xA64D};
|
||||
StatsBundleOut all[4];
|
||||
for (int p = 0; p < 4; p++) {
|
||||
int n = enc(in, p, o);
|
||||
EXPECT_EQ(len[p], n); EXPECT_EQ(c[p], crc(o, n));
|
||||
ASSERT_TRUE(sbDecode(o, n, &all[p]));
|
||||
EXPECT_EQ(4, all[p].pages); EXPECT_EQ(p, all[p].page);
|
||||
// every page carries the rule CRCs of page 0 (a change between pages is visible)
|
||||
EXPECT_EQ(all[0].get(SB_RULES_AUTO), all[p].get(SB_RULES_AUTO));
|
||||
EXPECT_EQ(all[0].get(SB_RULES_STATIC), all[p].get(SB_RULES_STATIC));
|
||||
EXPECT_TRUE(all[p].has(SB_RULES_AUTO));
|
||||
}
|
||||
EXPECT_EQ(-1, enc(in, 4, o));
|
||||
// every slot's counters and metadata arrive exactly once, in slot order
|
||||
int seen_ctr = 0, seen_rule = 0;
|
||||
for (int p = 0; p < 4; p++) {
|
||||
for (int i = 0; i < all[p].n_ctr; i++) { EXPECT_EQ(seen_ctr, all[p].ctr[i].slot); seen_ctr++; }
|
||||
for (int i = 0; i < all[p].n_rule; i++) { EXPECT_EQ(seen_rule, all[p].rule[i].slot); seen_rule++; }
|
||||
}
|
||||
EXPECT_EQ(16, seen_ctr); EXPECT_EQ(16, seen_rule);
|
||||
EXPECT_EQ(16u, all[0].get(SB_N_COUNTERS));
|
||||
EXPECT_LT(all[0].n_ctr, 16); // a spill: page 0 says 16, carries fewer
|
||||
}
|
||||
|
||||
TEST(StatsBundle, BoundaryLengths149_150_151) {
|
||||
struct Case { int n; uint32_t dropped, passed, fair; int unlimited; int len0; uint16_t crc0; int pages; };
|
||||
const Case cs[] = {
|
||||
{3, 1, 0, 200, 149, 149, 0xA57C, 1}, // fits with 1 B to spare
|
||||
{3, 1, 0, 20000, 150, 150, 0x68D9, 1}, // fits exactly
|
||||
{3, 1, 200, 5, 151, 132, 0x4BF7, 2}, // one byte too many: the last record moves to page 1
|
||||
};
|
||||
for (const Case& k : cs) {
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
FlowTable t; many(t, k.n, k.dropped, k.passed);
|
||||
in.admin = true; in.flow = &t; in.prefs_crc = 0xBEEF; in.pwr_flags = 3; in.fair[0] = k.fair; in.fair[1] = 12;
|
||||
uint8_t big[1200], o[200];
|
||||
int u = sbEncode(in, 0, big, 1200); // unlimited budget: how long would page 0 be?
|
||||
EXPECT_EQ(k.unlimited, u);
|
||||
int n = enc(in, 0, o);
|
||||
EXPECT_EQ(k.len0, n); EXPECT_EQ(k.crc0, crc(o, n));
|
||||
EXPECT_LE(n, SB_PAGE_MAX);
|
||||
StatsBundleOut d; ASSERT_TRUE(sbDecode(o, n, &d));
|
||||
EXPECT_EQ(k.pages, d.pages);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(StatsBundle, NeverExceedsBudget) {
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
FlowTable t; many(t, 16, 4000000000u, 4000000000u);
|
||||
for (int i = 0; i < 16; i++) t.e[i].r.expires = 4000000000u;
|
||||
in.admin = true; in.flow = &t; in.prefs_crc = 0xFFFF; in.pwr_flags = 15;
|
||||
for (int k = 0; k < 4; k++) in.fair[k] = 0xFFFFFFFFu;
|
||||
for (int id = 1; id <= SB_LAST_STATUS_ID; id++) {
|
||||
if (id != SB_NOISE && id != SB_RSSI && id != SB_SNR4) in.v[id] = 0xFFFFFFFFu;
|
||||
}
|
||||
uint8_t o[200];
|
||||
StatsBundleOut d;
|
||||
int total_ctr = 0, total_rule = 0;
|
||||
for (int p = 0; p < SB_MAX_PAGES; p++) {
|
||||
int n = enc(in, p, o);
|
||||
if (n < 0) break;
|
||||
EXPECT_LE(n, SB_PAGE_MAX);
|
||||
ASSERT_TRUE(sbDecode(o, n, &d));
|
||||
total_ctr += d.n_ctr; total_rule += d.n_rule;
|
||||
}
|
||||
EXPECT_EQ(16, total_ctr); EXPECT_EQ(16, total_rule);
|
||||
}
|
||||
|
||||
TEST(StatsBundle, DecoderSkipsUnknownIdsAndRejectsJunk) {
|
||||
uint8_t b[] = {1, 0x01, (62 << 2), 0x05, (61 << 2) | 1, 0x02, 0xAA, 0xBB, (SB_BATT_MV << 2), 0x94, 0x1D};
|
||||
StatsBundleOut d;
|
||||
ASSERT_TRUE(sbDecode(b, sizeof(b), &d));
|
||||
EXPECT_EQ(3732u, d.get(SB_BATT_MV));
|
||||
uint8_t v2[] = {2, 0x01};
|
||||
EXPECT_FALSE(sbDecode(v2, 2, &d)); // unknown version
|
||||
uint8_t trunc[] = {1, 0x01, (61 << 2) | 1, 0x05, 0xAA};
|
||||
EXPECT_FALSE(sbDecode(trunc, sizeof(trunc), &d)); // length past the end
|
||||
uint8_t wt[] = {1, 0x01, (3 << 2) | 2, 0};
|
||||
EXPECT_FALSE(sbDecode(wt, sizeof(wt), &d)); // reserved wire type
|
||||
uint8_t pg[] = {1, 0x21};
|
||||
EXPECT_FALSE(sbDecode(pg, 2, &d)); // page 2 of 1
|
||||
}
|
||||
|
||||
TEST(StatsBundle, RuleChangeMovesSlots) {
|
||||
// The rule CRC on page 0 tracks the table; slot ids move on add/del.
|
||||
StatsBundleIn in;
|
||||
fillStatus(in);
|
||||
FlowTable t; twoRules(t);
|
||||
in.admin = true; in.flow = &t;
|
||||
uint8_t o[200]; StatsBundleOut a, b;
|
||||
int n = enc(in, 0, o); ASSERT_TRUE(sbDecode(o, n, &a));
|
||||
t.add(R('a', 0x11223344u, 4, FLOW_DRY, 0, true, 0, 0), 0);
|
||||
n = enc(in, 0, o); ASSERT_TRUE(sbDecode(o, n, &b));
|
||||
EXPECT_NE(a.get(SB_RULES_AUTO), b.get(SB_RULES_AUTO));
|
||||
EXPECT_EQ(a.get(SB_RULES_STATIC), b.get(SB_RULES_STATIC));
|
||||
EXPECT_EQ('a', b.rule[0].kind); EXPECT_EQ(0, b.rule[0].slot); // 'a' sorts first: the old slots shifted
|
||||
EXPECT_EQ('c', b.rule[1].kind); EXPECT_EQ(1, b.rule[1].slot);
|
||||
}
|
||||
|
||||
static StatsPrefs P1() {
|
||||
StatsPrefs p;
|
||||
memset(&p, 0, sizeof(p));
|
||||
p.freq_mhz = 869.432f; p.bw_khz = 62.5f; p.sf = 8; p.cr = 8; p.tx_dbm = 22; p.name = "mast-three";
|
||||
p.flood_max = 8; p.flood_max_advert = 3; p.path_hash_mode = 1; p.powersaving = 1; p.rx_boosted_gain = 1;
|
||||
return p;
|
||||
}
|
||||
|
||||
TEST(StatsPrefsCrc, MatchesPythonReference) {
|
||||
EXPECT_EQ(0x8A04, sbPrefsCrc(P1()));
|
||||
StatsPrefs q;
|
||||
memset(&q, 0, sizeof(q));
|
||||
q.freq_mhz = 869.432f; q.bw_khz = 62.5f; q.sf = 8; q.cr = 8; q.tx_dbm = -9; q.name = "x1-\xc4\x8d" "e" "\xc5\xa1";
|
||||
q.advert_interval = 120; q.flood_advert_interval = 12; q.flood_max = 64; q.flood_max_unscoped = 64;
|
||||
q.flood_max_advert = 64; q.path_hash_mode = 2; q.disable_fwd = 1; q.rxps_enabled = 1; q.rxps_rx_us = 7500;
|
||||
q.rxps_sleep_us = 30000; q.rxps_level = 2; q.rxps_preamble = 16; q.bridge_enabled = 1;
|
||||
EXPECT_EQ(0xADE6, sbPrefsCrc(q));
|
||||
}
|
||||
|
||||
TEST(StatsPrefsCrc, EveryFieldMatters) {
|
||||
uint16_t base = sbPrefsCrc(P1());
|
||||
StatsPrefs p = P1(); p.sf = 9; EXPECT_NE(base, sbPrefsCrc(p));
|
||||
p = P1(); p.freq_mhz = 869.525f; EXPECT_NE(base, sbPrefsCrc(p));
|
||||
p = P1(); p.name = "tth-ltn"; EXPECT_NE(base, sbPrefsCrc(p));
|
||||
p = P1(); p.disable_fwd = 1; EXPECT_NE(base, sbPrefsCrc(p));
|
||||
p = P1(); p.bridge_enabled = 1; EXPECT_NE(base, sbPrefsCrc(p));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reference encoder/decoder + generator of test/vectors/stats_bundle_vectors.json.
|
||||
|
||||
Wire format of the "stats bundle" request (REQ_TYPE_STATS_BUNDLE 0xF1, see
|
||||
src/helpers/StatsBundle.h and docs/stats-bundle.md) and the `prefs_crc16`
|
||||
canonical serialization. test/test_stats_bundle hard-codes the same cases and
|
||||
expected bytes; keep the two in step. `--check` verifies that the JSON on disk
|
||||
is what this script would write. Python 3 stdlib only, so the Ansible collection
|
||||
and the exporter can lift the functions as they are.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
VERSION = 1
|
||||
PAGE_MAX = 150
|
||||
MODE = {"block": 0, "throttle": 1, "dry": 2}
|
||||
KIND_ORDER = "acnpr" # sorted by ASCII letter anyway
|
||||
|
||||
STATUS_IDS = {
|
||||
"batt_mv": 1, "temp_dc": 2, "uptime": 3, "air_tx": 4, "air_rx": 5, "noise": 6, "rssi": 7,
|
||||
"snr4": 8, "tx_queue": 9, "recv": 10, "sent": 11, "sent_flood": 12, "sent_direct": 13,
|
||||
"recv_flood": 14, "recv_direct": 15, "err_events": 16, "direct_dups": 17, "flood_dups": 18,
|
||||
"recv_errors": 19, "tx_start_fail": 20, "tx_timeout": 21,
|
||||
}
|
||||
ZIGZAG = {"temp_dc", "noise", "rssi", "snr4"}
|
||||
FAIR_IDS = {"group": 24, "sender": 25, "advert": 26, "window": 27}
|
||||
ID_RULES_AUTO, ID_RULES_STATIC, ID_PREFS_CRC, ID_PWR, ID_N_COUNTERS = 32, 33, 34, 35, 36
|
||||
ID_COUNTERS, ID_RULE = 40, 41
|
||||
|
||||
|
||||
def crc16_ccitt_false(data: bytes) -> int:
|
||||
crc = 0xFFFF
|
||||
for b in data:
|
||||
crc ^= b << 8
|
||||
for _ in range(8):
|
||||
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
|
||||
return crc
|
||||
|
||||
|
||||
# ---- varint ----------------------------------------------------------------
|
||||
|
||||
def varint(x: int) -> bytes:
|
||||
out = bytearray()
|
||||
while x >= 0x80:
|
||||
out.append((x & 0x7F) | 0x80)
|
||||
x >>= 7
|
||||
out.append(x)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def zigzag(x: int) -> int:
|
||||
return ((x << 1) ^ (x >> 31)) & 0xFFFFFFFF
|
||||
|
||||
|
||||
def unzigzag(x: int) -> int:
|
||||
return (x >> 1) ^ -(x & 1)
|
||||
|
||||
|
||||
def read_varint(b: bytes, pos: int):
|
||||
x = 0
|
||||
for shift in range(0, 35, 7):
|
||||
c = b[pos]
|
||||
pos += 1
|
||||
x |= (c & 0x7F) << shift
|
||||
if not c & 0x80:
|
||||
return x, pos
|
||||
raise ValueError("varint too long")
|
||||
|
||||
|
||||
# ---- flow rules (same canonical order and CRC as flow_rules_vectors) -------
|
||||
|
||||
def sort_key(e):
|
||||
return (ord(e["kind"]), bytes.fromhex(e["key"]))
|
||||
|
||||
|
||||
def canonical(e) -> bytes:
|
||||
key = bytes.fromhex(e["key"])
|
||||
secs = e.get("secs", 0) if e["mode"] == "throttle" else 0
|
||||
return (e["kind"].encode() + bytes([len(key)]) + key + bytes([MODE[e["mode"]]])
|
||||
+ secs.to_bytes(2, "big") + e.get("expires", 0).to_bytes(4, "big"))
|
||||
|
||||
|
||||
def rules_crc(entries, auto: bool):
|
||||
sel = sorted((e for e in entries if bool(e.get("auto", False)) == auto), key=sort_key)
|
||||
return len(sel), crc16_ccitt_false(b"".join(canonical(e) for e in sel))
|
||||
|
||||
|
||||
# ---- encoder ---------------------------------------------------------------
|
||||
|
||||
def scalar(id_: int, val: int) -> bytes:
|
||||
return bytes([id_ << 2]) + varint(val)
|
||||
|
||||
|
||||
def blob(id_: int, body: bytes) -> bytes:
|
||||
return bytes([(id_ << 2) | 1]) + varint(len(body)) + body
|
||||
|
||||
|
||||
def rule_record(slot: int, e) -> bytes:
|
||||
key = bytes.fromhex(e["key"])
|
||||
left = e.get("remain", 0) # vectors run with an invalid clock: left = remain
|
||||
mf = MODE[e["mode"]] | (4 if e.get("auto") else 0) | (8 if e.get("expires") else 0) | (16 if left else 0)
|
||||
b = varint(slot) + e["kind"].encode() + bytes([len(key)]) + key + bytes([mf])
|
||||
if e["mode"] == "throttle":
|
||||
b += varint(e["secs"])
|
||||
if e.get("expires"):
|
||||
b += varint(e["expires"])
|
||||
if left:
|
||||
b += varint(left)
|
||||
return b
|
||||
|
||||
|
||||
def records(case):
|
||||
"""The ordered record stream of one bundle; (bytes, splittable_counters) pieces."""
|
||||
recs = []
|
||||
for name, id_ in STATUS_IDS.items():
|
||||
if name == "temp_dc":
|
||||
if "temp_dc" in case["status"]:
|
||||
recs.append(scalar(id_, zigzag(case["status"]["temp_dc"])))
|
||||
continue
|
||||
v = case["status"].get(name, 0)
|
||||
if v:
|
||||
recs.append(scalar(id_, zigzag(v) if name in ZIGZAG else v))
|
||||
if not case["admin"]:
|
||||
return recs, []
|
||||
for name, id_ in FAIR_IDS.items():
|
||||
v = case.get("fair", {}).get(name, 0)
|
||||
if v:
|
||||
recs.append(scalar(id_, v))
|
||||
entries = sorted(case["rules"], key=sort_key)
|
||||
ca, ra = rules_crc(entries, True)
|
||||
cs, rs = rules_crc(entries, False)
|
||||
recs.append(scalar(ID_RULES_AUTO, (ca << 16) | ra))
|
||||
recs.append(scalar(ID_RULES_STATIC, (cs << 16) | rs))
|
||||
recs.append(scalar(ID_PREFS_CRC, case["prefs_crc"]))
|
||||
if case.get("pwr"):
|
||||
recs.append(scalar(ID_PWR, case["pwr"]))
|
||||
trip = [varint(i) + varint(e.get("dropped", 0)) + varint(e.get("passed", 0))
|
||||
for i, e in enumerate(entries) if e.get("dropped", 0) or e.get("passed", 0)]
|
||||
if trip:
|
||||
recs.append(scalar(ID_N_COUNTERS, len(trip)))
|
||||
return recs, (trip, [blob(ID_RULE, rule_record(i, e)) for i, e in enumerate(entries)])
|
||||
|
||||
|
||||
def encode_pages(case, max_len=PAGE_MAX):
|
||||
"""All pages (list of bytes) of a bundle, `max_len` bytes at most each."""
|
||||
recs, rest = records(case)
|
||||
pages = [[]]
|
||||
used = [2]
|
||||
pre = b""
|
||||
if case["admin"]:
|
||||
ents = sorted(case["rules"], key=sort_key)
|
||||
ca, ra = rules_crc(ents, True)
|
||||
cs, rs = rules_crc(ents, False)
|
||||
# opens every page after the first, so a reader sees a change between pages
|
||||
pre = scalar(ID_RULES_AUTO, (ca << 16) | ra) + scalar(ID_RULES_STATIC, (cs << 16) | rs)
|
||||
|
||||
def add(rec):
|
||||
if used[-1] + len(rec) > max_len and used[-1] > 2 + len(pre):
|
||||
pages.append([pre] if pre else [])
|
||||
used.append(2 + len(pre))
|
||||
pages[-1].append(rec)
|
||||
used[-1] += len(rec)
|
||||
|
||||
for r in recs:
|
||||
add(r)
|
||||
if rest:
|
||||
trip, meta = rest
|
||||
body = b""
|
||||
for t in trip:
|
||||
n = len(body) + len(t)
|
||||
fits = used[-1] + 1 + len(varint(n)) + n <= max_len
|
||||
if body and not fits:
|
||||
add(blob(ID_COUNTERS, body))
|
||||
body = b""
|
||||
body += t
|
||||
if body:
|
||||
add(blob(ID_COUNTERS, body))
|
||||
for m in meta:
|
||||
add(m)
|
||||
n = len(pages)
|
||||
return [bytes([VERSION, (i << 4) | n]) + b"".join(p) for i, p in enumerate(pages)]
|
||||
|
||||
|
||||
# ---- decoder ---------------------------------------------------------------
|
||||
|
||||
def decode_page(b: bytes):
|
||||
if len(b) < 2 or b[0] != VERSION:
|
||||
raise ValueError("bad version")
|
||||
out = {"page": b[1] >> 4, "pages": b[1] & 15, "scalars": {}, "counters": [], "rules": []}
|
||||
pos = 2
|
||||
while pos < len(b):
|
||||
key = b[pos]
|
||||
pos += 1
|
||||
id_, wt = key >> 2, key & 3
|
||||
if wt == 0:
|
||||
v, pos = read_varint(b, pos)
|
||||
out["scalars"][id_] = v
|
||||
elif wt == 1:
|
||||
n, pos = read_varint(b, pos)
|
||||
body = b[pos:pos + n]
|
||||
pos += n
|
||||
if id_ == ID_COUNTERS:
|
||||
q = 0
|
||||
while q < len(body):
|
||||
s, q = read_varint(body, q)
|
||||
d, q = read_varint(body, q)
|
||||
p, q = read_varint(body, q)
|
||||
out["counters"].append((s, d, p))
|
||||
elif id_ == ID_RULE:
|
||||
out["rules"].append(decode_rule(body))
|
||||
else:
|
||||
raise ValueError("bad wire type")
|
||||
return out
|
||||
|
||||
|
||||
def decode_rule(b: bytes):
|
||||
slot, q = read_varint(b, 0)
|
||||
kind, klen = chr(b[q]), b[q + 1]
|
||||
q += 2
|
||||
key = b[q:q + klen].hex()
|
||||
q += klen
|
||||
mf = b[q]
|
||||
q += 1
|
||||
r = {"slot": slot, "kind": kind, "key": key, "mode": ["block", "throttle", "dry"][mf & 3], "auto": bool(mf & 4)}
|
||||
if mf & 3 == 1:
|
||||
r["secs"], q = read_varint(b, q)
|
||||
if mf & 8:
|
||||
r["expires"], q = read_varint(b, q)
|
||||
if mf & 16:
|
||||
r["left"], q = read_varint(b, q)
|
||||
assert q == len(b)
|
||||
return r
|
||||
|
||||
|
||||
# ---- prefs CRC -------------------------------------------------------------
|
||||
|
||||
def round1000(x: float) -> int:
|
||||
return int(x * 1000.0 + 0.5)
|
||||
|
||||
|
||||
def prefs_canonical(p) -> bytes:
|
||||
name = p["name"].encode()[:31]
|
||||
u32 = lambda v: v.to_bytes(4, "big") # noqa: E731
|
||||
return (bytes([1]) + u32(round1000(p["freq_mhz"])) + u32(round1000(p["bw_khz"]))
|
||||
+ bytes([p["sf"], p["cr"], p["tx_dbm"] & 0xFF, len(name)]) + name
|
||||
+ bytes([p["advert_interval"], p["flood_advert_interval"], p["flood_max"],
|
||||
p["flood_max_unscoped"], p["flood_max_advert"], p["path_hash_mode"],
|
||||
p["disable_fwd"], p["powersaving"], p["rx_boosted_gain"], p["rxps_enabled"]])
|
||||
+ u32(p["rxps_rx_us"]) + u32(p["rxps_sleep_us"])
|
||||
+ bytes([p["rxps_level"], p["rxps_preamble"], p["bridge_enabled"]]))
|
||||
|
||||
|
||||
PREFS_CASES = [
|
||||
("cz_repeater", dict(freq_mhz=869.432, bw_khz=62.5, sf=8, cr=8, tx_dbm=22, name="mast-three",
|
||||
advert_interval=0, flood_advert_interval=0, flood_max=8, flood_max_unscoped=0,
|
||||
flood_max_advert=3, path_hash_mode=1, disable_fwd=0, powersaving=1, rx_boosted_gain=1,
|
||||
rxps_enabled=0, rxps_rx_us=0, rxps_sleep_us=0, rxps_level=0, rxps_preamble=0,
|
||||
bridge_enabled=0)),
|
||||
("rxps_node", dict(freq_mhz=869.432, bw_khz=62.5, sf=8, cr=8, tx_dbm=-9, name="x1-češ",
|
||||
advert_interval=120, flood_advert_interval=12, flood_max=64, flood_max_unscoped=64,
|
||||
flood_max_advert=64, path_hash_mode=2, disable_fwd=1, powersaving=0, rx_boosted_gain=0,
|
||||
rxps_enabled=1, rxps_rx_us=7500, rxps_sleep_us=30000, rxps_level=2, rxps_preamble=16,
|
||||
bridge_enabled=1)),
|
||||
]
|
||||
|
||||
# ---- cases -----------------------------------------------------------------
|
||||
|
||||
STATUS = {"batt_mv": 3987, "temp_dc": 215, "uptime": 1234567, "air_tx": 842, "air_rx": 51234, "noise": -113,
|
||||
"rssi": -97, "snr4": -22, "tx_queue": 0, "recv": 148233, "sent": 9120, "sent_flood": 8011,
|
||||
"sent_direct": 1109, "recv_flood": 130011, "recv_direct": 18222, "err_events": 0, "direct_dups": 412,
|
||||
"flood_dups": 20991, "recv_errors": 3071, "tx_start_fail": 0, "tx_timeout": 2}
|
||||
|
||||
TWO_RULES = [
|
||||
{"kind": "c", "key": "2e", "mode": "throttle", "secs": 1800, "dropped": 416, "passed": 14, "remain": 604800},
|
||||
{"kind": "r", "key": "8b2c", "mode": "block", "auto": True, "expires": 1800000000, "dropped": 37},
|
||||
]
|
||||
|
||||
|
||||
def many_rules(n, dropped, passed=0):
|
||||
return [{"kind": "a", "key": "%08x" % (0x11000000 + i), "mode": "throttle", "secs": 1800, "auto": i % 2 == 0,
|
||||
"expires": 1800000000 + i, "remain": 3600 * (i + 1), "dropped": dropped + i, "passed": passed}
|
||||
for i in range(n)]
|
||||
|
||||
|
||||
def boundary_cases():
|
||||
"""Page 0 of exactly 149/150/151 B (as if unlimited) -- found by search."""
|
||||
want = {149, 150, 151}
|
||||
found = {}
|
||||
for n in range(1, 17):
|
||||
for dropped in (1, 130, 20000, 3000000):
|
||||
for passed in (0, 1, 200):
|
||||
for fair in (0, 5, 200, 20000):
|
||||
case = {"admin": True, "status": STATUS, "fair": {"group": fair, "sender": 12},
|
||||
"prefs_crc": 0xBEEF, "pwr": 3, "rules": many_rules(n, dropped, passed)}
|
||||
length = len(encode_pages(case, 10000)[0])
|
||||
if length in want and length not in found:
|
||||
found[length] = (n, dropped, passed, fair)
|
||||
return found
|
||||
|
||||
|
||||
def cases():
|
||||
out = [
|
||||
("guest", {"admin": False, "status": STATUS, "rules": TWO_RULES, "prefs_crc": 1}),
|
||||
("admin_empty", {"admin": True, "status": {"batt_mv": 4012, "uptime": 90}, "prefs_crc": 0x1234,
|
||||
"rules": []}),
|
||||
("admin_two_rules", {"admin": True, "status": STATUS, "fair": {"group": 31, "sender": 4, "window": 120},
|
||||
"prefs_crc": 0xBEEF, "pwr": 2, "rules": TWO_RULES}),
|
||||
("admin_16_rules", {"admin": True, "status": STATUS, "fair": {"group": 31, "sender": 4, "window": 120},
|
||||
"prefs_crc": 0xBEEF, "pwr": 3, "rules": many_rules(16, 100000, 7)}),
|
||||
]
|
||||
for length, (n, d, p, f) in sorted(boundary_cases().items()):
|
||||
out.append((f"boundary_{length}", {"admin": True, "status": STATUS, "fair": {"group": f, "sender": 12},
|
||||
"prefs_crc": 0xBEEF, "pwr": 3, "rules": many_rules(n, d, p),
|
||||
"unlimited_page0_len": length}))
|
||||
return out
|
||||
|
||||
|
||||
def build():
|
||||
out = {
|
||||
"format": {"version": VERSION, "page_max": PAGE_MAX, "request": "F1 <page>"},
|
||||
"ids": {"status": STATUS_IDS, "fair": FAIR_IDS, "rules_auto": ID_RULES_AUTO, "rules_static": ID_RULES_STATIC,
|
||||
"prefs_crc": ID_PREFS_CRC, "pwr": ID_PWR, "n_counters": ID_N_COUNTERS, "counters": ID_COUNTERS,
|
||||
"rule": ID_RULE},
|
||||
"prefs": [],
|
||||
"cases": [],
|
||||
}
|
||||
for name, p in PREFS_CASES:
|
||||
blob_ = prefs_canonical(p)
|
||||
out["prefs"].append({"name": name, "prefs": p, "canonical": blob_.hex(),
|
||||
"crc16": f"{crc16_ccitt_false(blob_):04X}"})
|
||||
for name, case in cases():
|
||||
pages = encode_pages(case) if case["admin"] else encode_pages(case)
|
||||
out["cases"].append({
|
||||
"name": name, "input": case,
|
||||
"pages": [{"len": len(p), "hex": p.hex(), "crc16": f"{crc16_ccitt_false(p):04X}"} for p in pages],
|
||||
"decoded": [decode_page(p) for p in pages],
|
||||
})
|
||||
return json.loads(json.dumps(out)) # tuple/int-key normalisation for stable output
|
||||
|
||||
|
||||
def selftest():
|
||||
for name, case in cases():
|
||||
pages = encode_pages(case)
|
||||
assert all(len(p) <= PAGE_MAX for p in pages), name
|
||||
for p in pages:
|
||||
decode_page(p)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
selftest()
|
||||
path = pathlib.Path(__file__).with_name("stats_bundle_vectors.json")
|
||||
text = json.dumps(build(), indent=1, sort_keys=True) + "\n"
|
||||
if "--check" in sys.argv:
|
||||
sys.exit(0 if path.read_text() == text else 1)
|
||||
path.write_text(text)
|
||||
print(path)
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user