#pragma once // CUSTOM (TeTeHacko): "stats bundle" -- ONE binary request that answers a whole // monitoring scrape (status + telemetry + sensors (CayenneLPP) + 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 #include #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, SB_ENV_LPP = 42 /* CayenneLPP bytes of the node's sensors, channel 1 (the node itself) left out */, }; #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) // Longest env record body: what is left of a page after the 2 B header, the 2 rule // CRC records that open every page after the first (<= 12 B) and the record header. #define SB_ENV_MAX 128 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 uint8_t* env; // SB_ENV_LPP body (see sbLppExclude), NULL / 0 = no sensors uint8_t env_len; 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; } }; // Data size of a CayenneLPP type, 0 = unknown (a walk cannot continue past it). inline uint8_t sbLppSize(uint8_t type) { switch (type) { case 0: case 1: case 102: case 104: case 120: case 142: return 1; case 2: case 3: case 101: case 103: case 115: case 116: case 117: case 121: case 125: case 128: case 132: return 2; case 135: return 3; case 100: case 118: case 130: case 131: case 133: return 4; case 113: case 134: return 6; case 136: return 9; default: return 0; } } // Copies the readings of a CayenneLPP buffer [channel][type][data] except those on // channel `skip` into out (at most `max` bytes, whole readings only). Stops at an // unknown type. Returns the length written. inline int sbLppExclude(const uint8_t* in, int n, uint8_t skip, uint8_t* out, int max) { int p = 0, o = 0; while (p + 2 <= n) { uint8_t sz = sbLppSize(in[p + 1]); if (sz == 0 || p + 2 + sz > n) break; if (in[p] != skip) { if (o + 2 + sz > max) break; memcpy(&out[o], &in[p], 2 + sz); o += 2 + sz; } p += 2 + sz; } return o; } 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); } const bool env = in.env && in.env_len && in.env_len <= SB_ENV_MAX; if (!in.admin && env) w.blob(SB_ENV_LPP, in.env, in.env_len); 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); // sensors ahead of the counters and rules: page 0 is read every scrape if (env) w.blob(SB_ENV_LPP, in.env, in.env_len); 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; uint8_t env[SB_ENV_MAX]; // SB_ENV_LPP of this page uint8_t env_len; // 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_ENV_LPP) { if (bl > SB_ENV_MAX) return false; memcpy(o->env, body, bl); o->env_len = (uint8_t)bl; } 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 StatsRegion { const char* name; const char* parent; uint8_t flood; // 1 = flood allowed, 0 = denied }; 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; // regions (serialization v2): home region name ("*" / "" / NULL = none) and // the whole map; parent "" = child of the root, "?" = parent id not found const char* home; const struct StatsRegion* regions; uint8_t n_regions; }; inline uint32_t sbRound1000(float x) { double d = (double)x * 1000.0; return (uint32_t)(d + 0.5); } // Region names in the canonical form: one leading '#' dropped, "*" (the root) // and NULL = empty, at most 31 bytes. struct SbName { const uint8_t* p; uint8_t n; }; inline SbName sbCanonName(const char* s) { SbName r = { (const uint8_t*)"", 0 }; if (!s) return r; if (*s == '#') s++; if (s[0] == '*' && s[1] == 0) return r; size_t n = 0; while (n < 31 && s[n]) n++; r.p = (const uint8_t*)s; r.n = (uint8_t)n; return r; } inline uint16_t sbCrcName(uint16_t crc, const SbName& a) { crc = flowCrc16(crc, &a.n, 1); return a.n ? flowCrc16(crc, a.p, a.n) : crc; } // bytewise (name, then parent), as Python's sorted() on bytes inline int sbRegionCmp(const StatsRegion& a, const StatsRegion& b) { SbName x = sbCanonName(a.name), y = sbCanonName(b.name); for (int k = 0; k < 2; k++) { uint8_t m = x.n < y.n ? x.n : y.n; int c = m ? memcmp(x.p, y.p, m) : 0; if (c) return c; if (x.n != y.n) return x.n < y.n ? -1 : 1; x = sbCanonName(a.parent); y = sbCanonName(b.parent); } return 0; } #define SB_REGIONS_MAX 255 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++] = 2; // 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; uint16_t crc = flowCrc16(0xFFFF, b, (size_t)n); // regions: home, count, then every region ordered by (name, parent) crc = sbCrcName(crc, sbCanonName(p.home)); uint8_t cnt = p.n_regions > SB_REGIONS_MAX ? SB_REGIONS_MAX : p.n_regions; if (!p.regions) cnt = 0; crc = flowCrc16(crc, &cnt, 1); uint8_t idx[SB_REGIONS_MAX]; for (uint8_t i = 0; i < cnt; i++) { // insertion sort of the indices uint8_t j = i; while (j > 0 && sbRegionCmp(p.regions[idx[j - 1]], p.regions[i]) > 0) { idx[j] = idx[j - 1]; j--; } idx[j] = i; } for (uint8_t i = 0; i < cnt; i++) { const StatsRegion& r = p.regions[idx[i]]; crc = sbCrcName(crc, sbCanonName(r.name)); crc = sbCrcName(crc, sbCanonName(r.parent)); uint8_t fl = r.flood ? 1 : 0; crc = flowCrc16(crc, &fl, 1); } return crc; }