Loading files
// ============================================================================
// bee_counter_wire.h — parsing the HiveTraffic measurement characteristic
// ============================================================================
//
// Pure logic, free of Arduino / NimBLE / ArduinoJson, so the wire contract can
// be exercised on a host compiler against captured documents — see
// test-data/test_bee_counter_wire.cpp. bee_counter_client.cpp owns the GATT
// session and calls in here for the bytes.
//
// ---------------------------------------------------------------------------
// Two revisions, both live at once
// ---------------------------------------------------------------------------
// The counter stamps every document with "fw", the revision of the document
// format (NOT its firmware version — that is "ver", and the two move
// independently). This parser reads "fw" first and branches:
//
// fw <= 2 the healthy-expander count is named "gates_healthy";
// uptime_s and glitches are 16-bit on the device, so they arrive
// clamped at 65535 / pinned at 65535 respectively.
// fw >= 3 the same count is named "mcps_healthy"; uptime_s and glitches are
// 32-bit.
// fw >= 4 adds "idle_s" and status bit 0x80: the counter can be told to stop
// sensing for a bounded period (night mode) and now says when it
// has. Purely additive, so this parser would have read a v4 document
// correctly before it knew the field existed — it skips unknown
// keys. What it could not do is tell a suspended counter from a
// broken one, which is the point of reading it.
// fw >= 5 adds "banks": which of the counter's three emitter MOSFETs are
// enabled. Additive in the same way, and needed for the same reason
// — a bank switched off produces a permanently flat third of the
// totals, character for character what a dead FET produces. A
// counter too old to report it is running all three banks, which is
// why bank_mask defaults to ALL rather than to zero: the absence of
// the field means "everything is on", never "nothing is".
//
// Both must keep working, and not as a courtesy: a counter in the field reports
// fw:2 until it is updated over the air, and HiveHub's OTA relay has to read
// this very characteristic before it can update anything. A parser that
// understood only fw:3 would strand exactly the devices that need updating.
//
// The widths are only a statement about what the device can produce. Nothing
// here is width-limited: a v2 document simply never carries a value above
// 65535, so it is parsed into the same uint32_t fields and needs no special
// case. Only the field NAME actually differs, and that is what the branch is
// for.
//
// ---------------------------------------------------------------------------
// Why a hand-written reader rather than ArduinoJson
// ---------------------------------------------------------------------------
// The document is generated by a single snprintf in HiveTraffic's
// measurement_json.h: a flat object of ten fixed keys, no nesting, no arrays,
// no escapes, ~191 bytes at its widest. A full JSON parser buys nothing for
// that shape and costs a heap-allocating JsonDocument on every GATT read — and,
// more importantly here, it cannot be linked into a host test, which is how
// this contract stopped being checkable in the first place.
//
// The reader is correspondingly strict: it accepts one flat object and refuses
// anything else (see parseMeasurement), rather than silently returning defaults
// for a document it did not understand. If the counter ever grows a nested
// field this must be revisited in the same revision that adds it.
// ============================================================================
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace beecnt {
namespace wire {
// First protocol revision that names the expander count "mcps_healthy".
constexpr uint8_t REV_MCPS_HEALTHY = 3;
// First protocol revision carrying "idle_s" and the night-mode status bit.
constexpr uint8_t REV_NIGHT_MODE = 4;
// First protocol revision carrying "banks", and therefore the first that
// understands the SET_BANKS control opcode. bee_counter_client.cpp gates the
// write on it rather than writing hopefully: an older counter ignores the
// opcode and logs it, which would print every cycle forever.
constexpr uint8_t REV_LED_BANKS = 5;
// All three emitter banks enabled — the mask a counter runs unless told
// otherwise, the mask it returns to after any reset, and what this parser
// reports for a counter too old to carry the field. Mirrors
// beecounter_proto::BANK_MASK_ALL in the HiveTraffic repo; duplicated for the
// same reason STATUS_NIGHT_IDLE is, and pinned by the same test.
constexpr uint8_t BANK_MASK_ALL = 0x07;
// Status bit 0x80: the counter is deliberately not sensing. Mirrors
// beecounter_proto::STATUS_NIGHT_IDLE in the HiveTraffic repo; duplicated
// rather than shared because the two firmwares have no common header, and
// pinned by test-data/test_bee_counter_wire.cpp so the pair cannot drift apart
// silently.
constexpr uint8_t STATUS_NIGHT_IDLE = 0x80;
// One decoded measurement document. Field names are HiveHub's, normalized
// across both revisions; `protocol_version` records which revision produced it.
struct Measurement {
uint8_t protocol_version = 0; // "fw"
char version[16] = {0}; // "ver", empty when the counter is too old
// Local name the counter calls itself ("name"), e.g. "HiveTraffic-8A3F".
// Empty on every counter firmware that does not report one, which is what
// makes it worth having: two counters on one HiveHub are otherwise
// indistinguishable in the dashboard. Truncated rather than rejected if a
// counter ever sends something longer than this buffer — a shortened name
// still tells two counters apart, and dropping the reading over it would
// not.
char device_name[24] = {0};
uint8_t status_flags = 0; // "status"
uint32_t uptime_s = 0;
uint8_t num_gates = 0;
// MCP23017 expanders answering on the counter's I2C bus, 0..3 — NOT gates,
// of which there are num_gates (24); each healthy expander covers eight.
// Read from "mcps_healthy" (fw >= 3) or "gates_healthy" (fw <= 2).
//
// This is LIVE health as of HiveTraffic PR #12, not the boot-time snapshot
// it once was: a chip that dies mid-deployment drops out of the count (and
// clears its status bit), and one that recovers is counted again. Nothing
// may assume it is constant after boot.
uint8_t mcps_healthy = 0;
uint32_t total_in = 0; // lifetime totals, saturating at UINT32_MAX
uint32_t total_out = 0;
uint32_t glitch_count = 0; // "glitches", saturating
// Seconds of night-mode suspension still to run; 0 while counting, and 0
// on any counter older than fw:4. Non-zero means the zeros in total_in /
// total_out for this interval are deliberate: HiveHub asked the counter to
// stop, because honey bees do not fly at night. Without it that is
// indistinguishable from failed emitters.
uint32_t idle_s = 0;
// Which of the counter's three emitter MOSFETs are enabled: bit 0 = gates
// 00..07, bit 1 = 10..17, bit 2 = 20..27. Read from "banks" (fw >= 5).
//
// Defaults to ALL, not to 0. A counter too old to report the field is
// running its whole entrance, and a zero default would make every pre-v5
// counter look like it had been switched off entirely — the exact
// misreading that would then be written into stored history.
uint8_t bank_mask = BANK_MASK_ALL;
};
// How many gates this counter is actually watching, given its bank mask. The
// counter keeps reporting num_gates as what is WIRED (24), because that is a
// fact about the board; this is what is being counted right now.
inline uint8_t activeGates(const Measurement& m) {
uint8_t banks = 0;
for (uint8_t bit = 1; bit; bit = static_cast<uint8_t>(bit << 1)) {
if (m.bank_mask & bit) banks++;
}
return static_cast<uint8_t>(banks * 8U);
}
// Is any bank switched off? The flat totals that follow are then deliberate,
// in exactly the way isNightIdle() means for a whole counter.
inline bool hasDisabledBank(const Measurement& m) {
return (m.bank_mask & BANK_MASK_ALL) != BANK_MASK_ALL;
}
// Is this counter currently suspended? Reads the countdown rather than the
// status bit, because the countdown is the value the firmware derives at
// serialization time and therefore the one that cannot lag the other.
inline bool isNightIdle(const Measurement& m) {
return m.idle_s > 0;
}
namespace detail {
inline bool isSpace(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
// Advance past whitespace. Returns the index of the first non-space character,
// or `len` if the rest is blank.
inline size_t skipSpace(const char* s, size_t len, size_t i) {
while (i < len && isSpace(s[i])) ++i;
return i;
}
// Scan a JSON string starting at the opening quote. On success `begin`/`end`
// bracket the contents (exclusive of the quotes) and the return value is the
// index just past the closing quote; on failure the return value is `len`.
// Backslash escapes are skipped over so an escaped quote does not end the
// string early — the contents are not unescaped, which is correct for the only
// string this document carries (a dotted version number).
inline size_t scanString(const char* s, size_t len, size_t i,
size_t& begin, size_t& end) {
if (i >= len || s[i] != '"') return len;
begin = ++i;
while (i < len) {
if (s[i] == '\\') { i += 2; continue; }
if (s[i] == '"') { end = i; return i + 1; }
++i;
}
return len;
}
// Skip one value of any type, returning the index just past it, or `len` if the
// document is malformed. Nested objects/arrays are skipped whole, so an
// unexpected nested field cannot desynchronize the key scan.
inline size_t skipValue(const char* s, size_t len, size_t i) {
i = skipSpace(s, len, i);
if (i >= len) return len;
if (s[i] == '"') {
size_t b = 0, e = 0;
return scanString(s, len, i, b, e);
}
if (s[i] == '{' || s[i] == '[') {
int depth = 0;
while (i < len) {
const char c = s[i];
if (c == '"') {
size_t b = 0, e = 0;
i = scanString(s, len, i, b, e);
if (i == len) return len;
continue;
}
if (c == '{' || c == '[') ++depth;
if (c == '}' || c == ']') {
--depth;
if (depth == 0) return i + 1;
}
++i;
}
return len;
}
// A bare literal: number, true, false or null. Runs to the next separator.
while (i < len && s[i] != ',' && s[i] != '}' && s[i] != ']' &&
!isSpace(s[i])) {
++i;
}
return i;
}
// Parse an unsigned decimal integer, saturating at UINT32_MAX rather than
// wrapping. The counter's own counters saturate; a reader that wrapped where
// they saturate would reintroduce exactly the backwards-going total the device
// takes care to avoid. A leading '-' is refused (there are no signed fields).
inline bool parseU32(const char* s, size_t begin, size_t end, uint32_t& out) {
if (begin >= end) return false;
uint32_t v = 0;
for (size_t i = begin; i < end; ++i) {
const char c = s[i];
if (c < '0' || c > '9') return false;
const uint32_t digit = static_cast<uint32_t>(c - '0');
if (v > (UINT32_MAX - digit) / 10U) { out = UINT32_MAX; return true; }
v = v * 10U + digit;
}
out = v;
return true;
}
inline void assignU8(uint8_t& dst, uint32_t v) {
dst = v > 255U ? 255U : static_cast<uint8_t>(v);
}
} // namespace detail
// Decode `json` (`len` bytes, not necessarily NUL-terminated) into `out`.
//
// Returns false — leaving `out` untouched apart from fields already assigned —
// when the buffer is not a single well-formed flat JSON object, or when it
// carries no "fw" key. Every counter firmware has always emitted "fw", so its
// absence means this is not a measurement document, and reporting a snapshot
// full of zeros for one would look exactly like a healthy counter that has
// never seen a bee.
//
// Unknown keys are skipped, so a future revision that only ADDS fields still
// parses here. Known keys missing from the document keep their defaults.
inline bool parseMeasurement(const char* json, size_t len, Measurement& out) {
if (json == nullptr) return false;
size_t i = detail::skipSpace(json, len, 0);
if (i >= len || json[i] != '{') return false;
++i;
// Collected first, resolved once "fw" is known: the key carrying the
// expander count depends on the revision, and JSON gives no ordering
// guarantee that would let us assume "fw" is read first.
bool haveFw = false;
bool haveGatesHealthy = false, haveMcpsHealthy = false;
uint32_t gatesHealthy = 0, mcpsHealthy = 0;
bool closed = false;
while (i < len) {
i = detail::skipSpace(json, len, i);
if (i < len && json[i] == '}') { closed = true; ++i; break; }
if (i < len && json[i] == ',') { ++i; continue; }
size_t kb = 0, ke = 0;
i = detail::scanString(json, len, i, kb, ke);
if (i >= len) return false;
i = detail::skipSpace(json, len, i);
if (i >= len || json[i] != ':') return false;
++i;
i = detail::skipSpace(json, len, i);
if (i >= len) return false;
const size_t vb = i;
const size_t klen = ke - kb;
const char* key = json + kb;
// "ver" and "name" are the string fields; everything else is an
// unsigned integer. A key we do not know is skipped whole, nesting
// included.
char* strField = nullptr;
size_t strCap = 0;
if (klen == 3 && memcmp(key, "ver", 3) == 0) {
strField = out.version;
strCap = sizeof(out.version);
} else if (klen == 4 && memcmp(key, "name", 4) == 0) {
strField = out.device_name;
strCap = sizeof(out.device_name);
}
if (strField != nullptr) {
size_t sb = 0, se = 0;
const size_t after = detail::scanString(json, len, i, sb, se);
// scanString returns len on malformed input, and a well-formed
// string can never end exactly at len either: the object's closing
// '}' has to follow it.
if (after >= len) return false;
size_t n = se - sb;
if (n >= strCap) n = strCap - 1;
memcpy(strField, json + sb, n);
strField[n] = '\0';
i = after;
continue;
}
const size_t after = detail::skipValue(json, len, i);
if (after >= len) return false;
uint32_t value = 0;
const bool numeric = detail::parseU32(json, vb, after, value);
i = after;
if (!numeric) continue; // a non-numeric value for a numeric key
if (klen == 2 && memcmp(key, "fw", 2) == 0) {
detail::assignU8(out.protocol_version, value);
haveFw = true;
} else if (klen == 6 && memcmp(key, "status", 6) == 0) {
detail::assignU8(out.status_flags, value);
} else if (klen == 8 && memcmp(key, "uptime_s", 8) == 0) {
out.uptime_s = value;
} else if (klen == 9 && memcmp(key, "num_gates", 9) == 0) {
detail::assignU8(out.num_gates, value);
} else if (klen == 13 && memcmp(key, "gates_healthy", 13) == 0) {
gatesHealthy = value;
haveGatesHealthy = true;
} else if (klen == 12 && memcmp(key, "mcps_healthy", 12) == 0) {
mcpsHealthy = value;
haveMcpsHealthy = true;
} else if (klen == 8 && memcmp(key, "total_in", 8) == 0) {
out.total_in = value;
} else if (klen == 9 && memcmp(key, "total_out", 9) == 0) {
out.total_out = value;
} else if (klen == 8 && memcmp(key, "glitches", 8) == 0) {
out.glitch_count = value;
} else if (klen == 6 && memcmp(key, "idle_s", 6) == 0) {
out.idle_s = value;
} else if (klen == 5 && memcmp(key, "banks", 5) == 0) {
// Masked to the three banks this hardware has, so a counter on a
// future four-FET board cannot report a bank HiveHub would then
// try to switch. A value of 0 is stored as read: it is not a thing
// the counter can be in (it refuses an all-off mask), so seeing one
// means something is wrong and flattening it to ALL would hide it.
detail::assignU8(out.bank_mask,
value & static_cast<uint32_t>(BANK_MASK_ALL));
}
// else: unknown key, already skipped.
}
if (!closed || !haveFw) return false;
// The revision decides which name is authoritative. Falling back to the
// other one when the expected key is absent costs nothing and means a
// counter that bumped "fw" ahead of renaming the field (or vice versa) is
// read correctly rather than reported as zero healthy expanders — which
// would look like a completely dead counter.
const bool v3 = out.protocol_version >= REV_MCPS_HEALTHY;
if (v3 && haveMcpsHealthy) {
detail::assignU8(out.mcps_healthy, mcpsHealthy);
} else if (!v3 && haveGatesHealthy) {
detail::assignU8(out.mcps_healthy, gatesHealthy);
} else if (haveMcpsHealthy) {
detail::assignU8(out.mcps_healthy, mcpsHealthy);
} else if (haveGatesHealthy) {
detail::assignU8(out.mcps_healthy, gatesHealthy);
}
return true;
}
} // namespace wire
} // namespace beecnt
695b4ef90This file is pinned to the selected release. Download the original to open it in your design tool.