feat(advert): osm úrovní baterie místo dvou stavů, blesk na externím napájení

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5 committed 2026-09-21 20:26:51 +02:00
1 parent 5f56a80a78
commit f2b952ec4a
5 files changed
+312 -152

No files matched your search

+27 -20
View File
@@ -362,9 +362,9 @@ in order of preference:
#### Show battery state as an icon on the advertised name
*(TeTeHacko fork)* Appends a battery icon to the name carried in adverts, so
anyone who hears the node can see its state without logging in for telemetry.
Off by default.
*(TeTeHacko fork)* Appends a solar marker and a charge level to the name
carried in adverts, so anyone who hears the node can see its state without
logging in for telemetry. Off by default.
**Usage:**
- `get batt.icon`
@@ -372,33 +372,40 @@ Off by default.
**Default:** `off`
**Icons:** `☀️` above the threshold, `🪫` below it.
**Glyphs:** `☀` permanently (solar node), then one of `▁▂▃▄▅▆▇█`
for the charge level -- or `⚡` instead of the level while the node runs on
external power (USB), where VBAT reads the charger rather than the cell.
**Note:** The icon costs name bytes, and the LONGER of the two is always
budgeted for -- `☀️` is 6 bytes (U+2600 plus an invisible variation
selector), `🪫` is 4. With a position in the advert that leaves 17
bytes of name. If the name is too long the icon is dropped whole rather than
truncated, and `get batt.icon` says so; it also reports the measured voltage
and the state the next advert would carry.
**Note:** The indicator costs 6 bytes of the name (3 + 3), which with a
position in the advert leaves 17. Unicode has only two battery emoji and no
"half full" one, and at 4 bytes each they do not fit -- hence block elements,
which are 3 bytes and come in eight steps. If the name is too long the whole
indicator is dropped rather than truncated, and both `set` and `get` say so.
**Note:** Switching is hysteretic (`BATT_ICON_HYST_MV`, default 100 mV) so the
icon does not follow the daily charge cycle of a solar node. A node drifting at
the measured 13 mV/day crosses a threshold about once a month, so the 25 h
flood advert interval is not a limitation here.
**Note:** Every level is the same byte width on purpose. A name that changed
length with the charge would be re-truncated at some steps and not others, and
every client that heard it would rewrite the contact.
**Note:** Switching is hysteretic (`BATT_ICON_HYST_MV`, default 50 mV) and
asymmetric -- the level drops as soon as the voltage crosses a boundary but
climbs only once clear of it. The measured daily swing of a solar node under
weak sun is 38-46 mV and the drift 13 mV/day, so at eight levels the name
changes roughly once a week.
---
#### Battery threshold for the name icon
#### Battery scale for the name icon
**Usage:**
- `get batt.icon.mv`
- `set batt.icon.mv <millivolts>`
- `get batt.icon.lo` / `set batt.icon.lo <millivolts>`
- `get batt.icon.hi` / `set batt.icon.hi <millivolts>`
**Set by build flag:** `BATT_ICON_LOW_MV`
**Set by build flag:** `BATT_ICON_LO_MV`, `BATT_ICON_HI_MV`
**Default:** `3700` (roughly 44 % of a 1S Li-Ion cell)
**Default:** `3300` and `4200` -- the same 1S Li-Ion scale the dashboards use,
so the icon and the Grafana percentage tell one story.
**Parameters:**
- `millivolts`: `3000`..`4200`, or `0` to use the build default
- `millivolts`: `2500`..`4500`, or `0` to use the build default
---
+112 -38
View File
@@ -9,69 +9,143 @@
//
// The budget is tight. app_data is MAX_ADVERT_DATA_SIZE (32) bytes, of which
// the flags take 1 and lat/lon another 8, leaving 23 bytes for the name on a
// node that advertises its position. The icons are not one byte each:
// node that advertises its position. The whole indicator has to fit in what
// the name leaves over -- for the deployed names that is 6 bytes.
//
// U+2600 U+FE0F (sun, emoji presentation) 6 bytes -- the variation
// selector is half of it
// U+1FAAB (low battery) 4 bytes
// Which rules out emoji for the level. Unicode has exactly TWO battery emoji,
// U+1F50B and U+1FAAB; there is no "half full" one, and at 4 bytes each a
// sun-plus-battery pair costs 7 bytes, one too many. Block elements live in
// the BMP, so they are 3 bytes rather than 4, and come in eight steps -- the
// most states for the fewest bytes:
//
// marker U+2600 3 B sun, permanent -- "this is a solar node".
// Deliberately WITHOUT the U+FE0F variation
// selector, which costs 3 more bytes and buys
// only a colour glyph.
// level U+2581..88 3 B eight steps of charge
//
// Sampling rate is a non-issue: a solar node drifts by about 13 mV/day
// (measured on mast-repeater-one over 30 days), so on a 3300-4200 mV scale a
// two-state icon flips roughly once a month. The flood advert interval of 25 h
// is far finer than the thing being measured.
// (measured on mast-repeater-one over 30 days), so even at eight steps the
// name changes roughly once a week. The flood advert interval of 25 h is far
// finer than the thing being measured.
#include <MeshCore.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifndef BATT_ICON_OK
#define BATT_ICON_OK "\u2600\uFE0F" // sun, 6 bytes
// Permanent marker, prepended to the level. Empty string disables it.
#ifndef BATT_ICON_MARKER
#define BATT_ICON_MARKER "☀" // sun, 3 bytes
#endif
#ifndef BATT_ICON_LOW
#define BATT_ICON_LOW "\U0001FAAB" // low battery, 4 bytes
// Level glyphs, low to high. All must be the same byte length.
#ifndef BATT_ICON_LEVELS
#define BATT_ICON_LEVELS "▁▂▃▄▅▆▇█"
#endif
#ifndef BATT_ICON_LEVEL_BYTES
#define BATT_ICON_LEVEL_BYTES 3
#endif
// Shown INSTEAD of the level while the node runs on external power, which
// nRF52 reports straight from VBUS detect (MainBoard::isExternalPowered()).
// That covers the bench, where a board with no cell reads a meaningless
// floating VBAT -- better to say "on USB" than to draw a charge level out of
// noise. It is 3 bytes like a level glyph, so the budget does not move.
#ifndef BATT_ICON_EXTERNAL
#define BATT_ICON_EXTERNAL "\u26A1" // high voltage, 3 bytes
#endif
// Threshold and hysteresis in millivolts, for a 1S Li-Ion/LiPo cell. 3700 mV
// is roughly 44 % on the curve the dashboards use, which on the measured slope
// leaves about a month of warning before the node browns out.
#ifndef BATT_ICON_LOW_MV
#define BATT_ICON_LOW_MV 3700
// Scale ends in millivolts for a 1S Li-Ion/LiPo cell -- the same 3300..4200
// the dashboards use, so the icon and the Grafana percentage tell one story.
#ifndef BATT_ICON_LO_MV
#define BATT_ICON_LO_MV 3300
#endif
// The daily swing of a solar node under weak sun was 38-46 mV (measured), so
// anything near that would make the icon flip with sunrise and sunset.
#ifndef BATT_ICON_HI_MV
#define BATT_ICON_HI_MV 4200
#endif
// Hysteresis per boundary. Has to clear the measured daily swing of a solar
// node under weak sun (38-46 mV) or the level would follow sunrise and
// sunset, and stay well under one step (112 mV at eight levels) or the level
// could never climb at all.
#ifndef BATT_ICON_HYST_MV
#define BATT_ICON_HYST_MV 100
#define BATT_ICON_HYST_MV 50
#endif
namespace mesh {
// Number of level glyphs.
inline uint8_t battIconLevels() {
return (uint8_t)((sizeof(BATT_ICON_LEVELS) - 1) / BATT_ICON_LEVEL_BYTES);
}
// Bytes the indicator adds to the name: marker plus one level glyph.
//
// Every level is the same width, and that is the point rather than a detail:
// a name whose length changed with the charge would be re-truncated by the
// UTF-8 clamp at some steps and not others, and every client that hears it
// would rewrite the contact.
inline size_t battIconWidth() {
const size_t lvl = BATT_ICON_LEVEL_BYTES;
const size_t ext = sizeof(BATT_ICON_EXTERNAL) - 1;
return (sizeof(BATT_ICON_MARKER) - 1) + (lvl > ext ? lvl : ext);
}
// Bytes of app_data left for the name. Mirrors AdvertDataBuilder::encodeTo():
// one byte of flags, plus 4+4 for lat/lon when a position is advertised.
inline size_t advertNameBudget(bool with_loc) {
return MAX_ADVERT_DATA_SIZE - 1 - (with_loc ? 8 : 0);
}
// Does the name still fit with an icon appended?
//
// This deliberately budgets for the LONGER of the two icons, never the one
// currently selected. Decide per state and a name that fits the 4-byte icon
// but not the 6-byte one would get silently truncated by the UTF-8 clamp in
// AdvertDataBuilder every time the battery crossed the threshold -- the name
// itself would change length, and every client would rewrite the contact.
// Does the name still fit with the indicator appended?
inline bool battIconFits(size_t name_len, bool with_loc) {
const size_t ok_len = sizeof(BATT_ICON_OK) - 1;
const size_t low_len = sizeof(BATT_ICON_LOW) - 1;
const size_t worst = ok_len > low_len ? ok_len : low_len;
return name_len + worst <= advertNameBudget(with_loc);
return name_len + battIconWidth() <= advertNameBudget(with_loc);
}
// Hysteresis: drop to "low" at the threshold, recover only hyst_mv above it.
inline bool battIconIsLow(bool prev_low, uint16_t mv, uint16_t low_mv, uint16_t hyst_mv) {
if (prev_low) return mv <= (uint32_t)low_mv + hyst_mv;
return mv < low_mv;
// Copy the glyph for `level` into dest, which must hold
// BATT_ICON_LEVEL_BYTES + 1 bytes.
inline void battIconGlyph(char dest[], uint8_t level) {
uint8_t n = battIconLevels();
if (n == 0) { dest[0] = 0; return; }
if (level >= n) level = n - 1;
const char* tbl = BATT_ICON_LEVELS;
memcpy(dest, tbl + (size_t)level * BATT_ICON_LEVEL_BYTES, BATT_ICON_LEVEL_BYTES);
dest[BATT_ICON_LEVEL_BYTES] = 0;
}
// On sampling: one analogRead per decision is deliberate.
// Charge level 0..n-1 for `mv`, with hysteresis against the previous level.
//
// Asymmetric on purpose: the level drops as soon as the voltage falls below a
// boundary, but climbs only once it is hyst_mv clear of one. Falling is the
// direction that matters -- an optimistic icon on a node that is browning out
// is worse than a pessimistic one on a node that is charging.
//
// Starting from 0 the climb loop walks up to wherever the voltage actually
// is, so a fresh boot settles on the right level (one hysteresis band low,
// the safe side) without needing a separate "unknown" state.
inline uint8_t battIconLevel(uint8_t prev, uint16_t mv, uint16_t lo_mv, uint16_t hi_mv,
uint8_t n, uint16_t hyst_mv) {
if (n <= 1 || hi_mv <= lo_mv) return 0;
if (prev >= n) prev = n - 1;
const uint32_t span = (uint32_t)hi_mv - lo_mv;
uint8_t lvl = prev;
// The boundary into level k sits at lo + k*span/n, for k = 1..n-1.
while (lvl + 1 < n) {
uint32_t edge = lo_mv + (uint32_t)(lvl + 1) * span / n;
if ((uint32_t)mv >= edge + hyst_mv) lvl++; else break;
}
while (lvl > 0) {
uint32_t edge = lo_mv + (uint32_t)lvl * span / n;
if ((uint32_t)mv < edge) lvl--; else break;
}
return lvl;
}
// On sampling: one analogRead per decision is deliberate, and it is the same
// call that feeds the battery metric (simple_repeater/MyMesh.cpp:482 for
// stats, :510 for telemetry). There is no smoothed copy of the voltage
// anywhere in the firmware to prefer instead -- what looks steady in Grafana
// is steady because the cell is.
//
// A cell-less XIAO on USB reads bimodally -- measured over 20 reads on x4:
// 4160 3760 4160 3760 4140 4150 3750 ... two levels ~390 mV apart, alternating
@@ -81,8 +155,8 @@ inline bool battIconIsLow(bool prev_low, uint16_t mv, uint16_t low_mv, uint16_t
//
// It is also not what a deployed node sees. mast-repeater-one, with a real
// cell, holds a max-min spread of 0-22 mV over 10-minute windows (queried
// from Prometheus), which the 100 mV hysteresis covers several times over.
// So the noise is a property of the bench, not of the firmware, and averaging
// it away here would only add code that the measurement says does nothing.
// from Prometheus). Against a 112 mV step and 50 mV of hysteresis that is
// quiet, so the noise is a property of the bench, not of the firmware.
// A bench board without a cell WILL step around; that is expected.
}
+60 -34
View File
@@ -175,25 +175,34 @@ void CommonCLI::savePrefs() {
_prefs->clearDirty();
}
// Name as it goes on the air: the configured name, with a battery icon
// appended when 'batt.icon' is on and there is room for it. Returns the bare
// name in every other case -- an icon that does not fit is dropped whole
// rather than letting the UTF-8 clamp eat it silently.
// Name as it goes on the air: the configured name, plus the solar marker and
// either a charge level or the external-power glyph. Returns the bare name in
// every other case -- an indicator that does not fit is dropped whole rather
// than letting the UTF-8 clamp eat half of it silently.
const char* CommonCLI::advertName(bool with_loc) {
if (!_prefs->batt_icon) return _prefs->node_name;
uint16_t mv = _board->getBattMilliVolts();
if (mv == 0) return _prefs->node_name; // board has no battery sense, or hasn't measured yet
size_t nlen = strlen(_prefs->node_name);
if (!mesh::battIconFits(nlen, with_loc)) return _prefs->node_name;
uint16_t low_mv = _prefs->batt_icon_mv ? _prefs->batt_icon_mv : BATT_ICON_LOW_MV;
_batt_low = mesh::battIconIsLow(_batt_low, mv, low_mv, BATT_ICON_HYST_MV);
char glyph[8];
if (_board->isExternalPowered()) {
// On USB the cell (if any) is being charged and VBAT reads the charger,
// not the battery -- a level drawn from it would be fiction.
StrHelper::strncpy(glyph, BATT_ICON_EXTERNAL, sizeof(glyph));
} else {
uint16_t mv = _board->getBattMilliVolts();
if (mv == 0) return _prefs->node_name; // board has no battery sense
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
_batt_level = mesh::battIconLevel(_batt_level, mv, lo, hi,
mesh::battIconLevels(), BATT_ICON_HYST_MV);
mesh::battIconGlyph(glyph, _batt_level);
}
StrHelper::strncpy(_adv_name, _prefs->node_name, sizeof(_adv_name));
strncat(_adv_name, _batt_low ? BATT_ICON_LOW : BATT_ICON_OK,
sizeof(_adv_name) - strlen(_adv_name) - 1);
strncat(_adv_name, BATT_ICON_MARKER, sizeof(_adv_name) - strlen(_adv_name) - 1);
strncat(_adv_name, glyph, sizeof(_adv_name) - strlen(_adv_name) - 1);
return _adv_name;
}
@@ -803,14 +812,23 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
savePrefs();
strcpy(reply, "OK");
#endif
} else if (memcmp(config, "batt.icon.mv ", 13) == 0) {
} else if (memcmp(config, "batt.icon.lo ", 13) == 0 || memcmp(config, "batt.icon.hi ", 13) == 0) {
bool is_lo = config[10] == 'l';
int mv = atoi(&config[13]);
if (mv != 0 && (mv < 3000 || mv > 4200)) {
strcpy(reply, "Error: expected 3000..4200, or 0 for default");
if (mv != 0 && (mv < 2500 || mv > 4500)) {
strcpy(reply, "Error: expected 2500..4500, or 0 for default");
} else {
_prefs->batt_icon_mv = mv;
if (is_lo) _prefs->batt_icon_lo = mv; else _prefs->batt_icon_hi = mv;
savePrefs();
sprintf(reply, "OK - low below %d mV", mv ? mv : BATT_ICON_LOW_MV);
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
if (hi <= lo) {
strcpy(reply, "OK - WARNING: hi <= lo, level will stay at 0");
} else {
sprintf(reply, "OK - scale %d..%d mV, %d levels, step %d mV",
(uint32_t)lo, (uint32_t)hi, (uint32_t)mesh::battIconLevels(),
(uint32_t)((hi - lo) / mesh::battIconLevels()));
}
}
} else if (memcmp(config, "batt.icon ", 10) == 0) {
_prefs->batt_icon = memcmp(&config[10], "on", 2) == 0 ? 1 : 0;
@@ -824,7 +842,7 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
sprintf(reply, "on - BUT name is %d B, max %d B with icon - icon omitted",
(int)strlen(_prefs->node_name),
(int)(mesh::advertNameBudget(_prefs->advert_loc_policy != ADVERT_LOC_NONE)
- (sizeof(BATT_ICON_OK) - 1)));
- mesh::battIconWidth()));
} else {
strcpy(reply, "on - shows on next advert");
}
@@ -884,29 +902,37 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
int len = _callbacks->getSelfId().writeTo(prv_key, PRV_KEY_SIZE);
mesh::Utils::toHex(tmp, prv_key, len);
sprintf(reply, "> %s", tmp);
} else if (memcmp(config, "batt.icon.mv", 12) == 0) {
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_mv ? _prefs->batt_icon_mv : BATT_ICON_LOW_MV));
} else if (memcmp(config, "batt.icon.lo", 12) == 0) {
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV));
} else if (memcmp(config, "batt.icon.hi", 12) == 0) {
sprintf(reply, "> %d", (uint32_t)(_prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV));
} else if (memcmp(config, "batt.icon", 9) == 0) {
// Report what actually goes on the air, not just the flag: the icon is
// dropped when the name leaves no room, and the measured voltage is the
// only way to tell "threshold not reached" from "board reads nothing".
// Report what actually goes on the air, not just the flag: the indicator
// is dropped when the name leaves no room, and the voltage is the only way
// to tell "not there yet" from "board reads nothing".
bool with_loc = _prefs->advert_loc_policy != ADVERT_LOC_NONE;
uint16_t mv = _board->getBattMilliVolts();
uint16_t low_mv = _prefs->batt_icon_mv ? _prefs->batt_icon_mv : BATT_ICON_LOW_MV;
if (!_prefs->batt_icon) {
sprintf(reply, "> off (%d mV)", (uint32_t)mv);
strcpy(reply, "> off");
} else if (!mesh::battIconFits(strlen(_prefs->node_name), with_loc)) {
strcpy(reply, "> on (omitted, name too long)");
} else if (mv == 0) {
strcpy(reply, "> on (omitted, no battery reading)");
} else if (_board->isExternalPowered()) {
strcpy(reply, "> on (external power)");
} else {
// What the NEXT advert would carry, not what the last one did. Reporting
// the stored flag had `get` saying "ok" moments before an advert went out
// with the empty icon, because the state only advances in advertName().
// Predicting is read-only: _batt_low is deliberately not updated here.
bool next_low = mesh::battIconIsLow(_batt_low, mv, low_mv, BATT_ICON_HYST_MV);
sprintf(reply, "> on (%s, %d mV, low below %d)",
next_low ? "low" : "ok", (uint32_t)mv, (uint32_t)low_mv);
uint16_t mv = _board->getBattMilliVolts();
if (mv == 0) {
strcpy(reply, "> on (omitted, no battery reading)");
} else {
// What the NEXT advert would carry, not what the last one did: the
// state only advances in advertName(), so reporting the stored level
// had `get` disagreeing with the advert that went out moments later.
// Predicting is read-only -- _batt_level is deliberately not updated.
uint16_t lo = _prefs->batt_icon_lo ? _prefs->batt_icon_lo : BATT_ICON_LO_MV;
uint16_t hi = _prefs->batt_icon_hi ? _prefs->batt_icon_hi : BATT_ICON_HI_MV;
uint8_t n = mesh::battIconLevels();
uint8_t next = mesh::battIconLevel(_batt_level, mv, lo, hi, n, BATT_ICON_HYST_MV);
sprintf(reply, "> on (level %d/%d, %d mV, scale %d..%d)",
(uint32_t)(next + 1), (uint32_t)n, (uint32_t)mv, (uint32_t)lo, (uint32_t)hi);
}
}
} else if (memcmp(config, "name", 4) == 0) {
sprintf(reply, "> %s", _prefs->node_name);
+5 -3
View File
@@ -80,7 +80,8 @@ public:
// Battery state as an icon on the advertised name (see BatteryIcon.h).
// Off by default: it costs bytes of the name, so it has to be asked for.
uint8_t batt_icon = 0; // boolean
uint16_t batt_icon_mv = 0; // low threshold in mV; 0 = BATT_ICON_LOW_MV
uint16_t batt_icon_lo = 0; // scale bottom in mV; 0 = BATT_ICON_LO_MV
uint16_t batt_icon_hi = 0; // scale top in mV; 0 = BATT_ICON_HI_MV
// FairnessLimiter runtime tuning; 0 = use the firmware build default.
uint8_t fair_group_cap = 0, fair_sender_cap = 0, fair_advert_cap = 0;
uint16_t fair_group_refill_s = 0, fair_sender_refill_s = 0, fair_advert_refill_s = 0;
@@ -184,7 +185,8 @@ private:
def("adc_mult", _parent->adc_multiplier);
def("pwr_sav_en", _parent->powersaving_enabled);
def("bicon", _parent->batt_icon);
def("bicon_mv", _parent->batt_icon_mv);
def("bicon_lo", _parent->batt_icon_lo);
def("bicon_hi", _parent->batt_icon_hi);
}
public:
PowerPrefs(NodePrefs* parent) : _parent(parent) { }
@@ -330,7 +332,7 @@ class CommonCLI {
// Name handed to AdvertDataBuilder, which keeps the pointer until encodeTo();
// it has to outlive buildAdvertData(), hence a member and not a local.
char _adv_name[sizeof(NodePrefs::node_name) + 8];
bool _batt_low = false; // hysteresis state, see BatteryIcon.h
uint8_t _batt_level = 0; // hysteresis state, see BatteryIcon.h
mesh::RTCClock* getRTCClock() { return _rtc; }
const char* advertName(bool with_loc);
+108 -57
View File
@@ -4,12 +4,14 @@
#include <helpers/AdvertDataHelpers.h>
#include <string.h>
// The icons are not one byte each, and the sun carries a variation selector
// that is invisible in an editor but costs three bytes. Pin both down: the
// whole budget math rests on these numbers.
TEST(BatteryIcon, IconsHaveTheExpectedByteLength) {
EXPECT_EQ(6u, strlen(BATT_ICON_OK)); // U+2600 + U+FE0F
EXPECT_EQ(4u, strlen(BATT_ICON_LOW)); // U+1FAAB
// The whole budget rests on these being 3 bytes, not 4. Block elements and
// U+2600/U+26A1 are BMP; battery emoji are not, which is why they lost.
TEST(BatteryIcon, GlyphsAreThreeBytesAndThereAreEightLevels) {
EXPECT_EQ(3u, strlen(BATT_ICON_MARKER)); // U+2600 sun, no variation selector
EXPECT_EQ(3u, strlen(BATT_ICON_EXTERNAL)); // U+26A1 high voltage
EXPECT_EQ(24u, strlen(BATT_ICON_LEVELS)); // 8 x 3 B
EXPECT_EQ(8, mesh::battIconLevels());
EXPECT_EQ(6u, mesh::battIconWidth()); // marker + one glyph
}
TEST(BatteryIcon, BudgetMatchesAdvertLayout) {
@@ -17,57 +19,103 @@ TEST(BatteryIcon, BudgetMatchesAdvertLayout) {
EXPECT_EQ(31u, mesh::advertNameBudget(false));
}
// The real names of the three nodes this was written for.
// The three deployed names, at 6 bytes of indicator.
TEST(BatteryIcon, FitsTheDeployedNames) {
EXPECT_TRUE(mesh::battIconFits(strlen("mast-rpt-two"), true)); // 12 + 6 = 18
EXPECT_TRUE(mesh::battIconFits(strlen("mast-repeater-one"), true)); // 17 + 6 = 23, exactly
EXPECT_TRUE(mesh::battIconFits(strlen("mast-rpt-three.cz"), true)); // 17 + 6 = 23, exactly
EXPECT_FALSE(mesh::battIconFits(strlen("tth-mast-repeater-one"), true)); // 21 + 6 = 27
}
// A name is only accepted when the LONGER icon fits. Budget for the current
// state instead and the name would change length as the battery crosses the
// threshold, rewriting the contact in every client that hears it.
TEST(BatteryIcon, BudgetsForTheLongerIconNotTheCurrentOne) {
// 18 bytes: the 4-byte low icon would fit (22), the 6-byte one would not (24).
EXPECT_FALSE(mesh::battIconFits(18, true));
EXPECT_TRUE(mesh::battIconFits(17, true));
EXPECT_TRUE(mesh::battIconFits(strlen("mast-rpt-two"), true)); // 12 + 6 = 18
EXPECT_TRUE(mesh::battIconFits(strlen("mast-repeater-one"), true)); // 17 + 6 = 23, exactly
EXPECT_TRUE(mesh::battIconFits(strlen("mast-rpt-three.cz"), true)); // 17 + 6 = 23, exactly
EXPECT_FALSE(mesh::battIconFits(18, true)); // one byte over
}
TEST(BatteryIcon, DroppingPositionBuysEightBytes) {
EXPECT_FALSE(mesh::battIconFits(strlen("tth-mast-repeater-one"), true));
EXPECT_TRUE(mesh::battIconFits(strlen("tth-mast-repeater-one"), false));
EXPECT_FALSE(mesh::battIconFits(strlen("tth-mast-repeater-one"), true)); // 21 + 6 = 27
EXPECT_TRUE(mesh::battIconFits(strlen("tth-mast-repeater-one"), false)); // 31 B budget
}
TEST(BatteryIcon, HysteresisNeedsARealRecoveryNotJustTheThreshold) {
const uint16_t low = 3700, hyst = 100;
EXPECT_FALSE(mesh::battIconIsLow(false, 3701, low, hyst)); // above, stays ok
EXPECT_TRUE(mesh::battIconIsLow(false, 3699, low, hyst)); // crosses down
EXPECT_TRUE(mesh::battIconIsLow(true, 3750, low, hyst)); // back above, but inside hysteresis
EXPECT_TRUE(mesh::battIconIsLow(true, 3800, low, hyst)); // still inside, boundary
EXPECT_FALSE(mesh::battIconIsLow(true, 3801, low, hyst)); // genuinely recovered
}
// The measured daily swing of a solar node under weak sun was 38-46 mV. The
// icon must not follow sunrise and sunset.
TEST(BatteryIcon, SurvivesTheMeasuredDailySwing) {
bool low = mesh::battIconIsLow(false, 3690, 3700, BATT_ICON_HYST_MV);
ASSERT_TRUE(low);
// night down, day up, +-23 mV around 3690 -- must stay low the whole time
for (int i = 0; i < 10; i++) {
low = mesh::battIconIsLow(low, 3667, 3700, BATT_ICON_HYST_MV);
EXPECT_TRUE(low);
low = mesh::battIconIsLow(low, 3713, 3700, BATT_ICON_HYST_MV);
EXPECT_TRUE(low);
// Every level must be the same width, or the name length would change with
// the charge and clients would rewrite the contact on each step.
TEST(BatteryIcon, EveryGlyphIsTheSameWidth) {
char g[8];
for (uint8_t i = 0; i < mesh::battIconLevels(); i++) {
mesh::battIconGlyph(g, i);
EXPECT_EQ(3u, strlen(g)) << "level " << (int)i;
}
}
TEST(BatteryIcon, GlyphIndexIsClampedNotWrapped) {
char lo[8], hi[8], over[8];
mesh::battIconGlyph(lo, 0);
mesh::battIconGlyph(hi, 7);
mesh::battIconGlyph(over, 99);
EXPECT_STREQ("▁", lo);
EXPECT_STREQ("█", hi);
EXPECT_STREQ(hi, over); // clamped to the top, not wrapped to 0
}
TEST(BatteryIcon, LevelSpansTheScale) {
const uint8_t n = 8;
// No hysteresis here: check the raw mapping across the 3300..4200 scale.
EXPECT_EQ(0, mesh::battIconLevel(0, 3300, 3300, 4200, n, 0));
EXPECT_EQ(0, mesh::battIconLevel(0, 3200, 3300, 4200, n, 0)); // below scale
EXPECT_EQ(7, mesh::battIconLevel(0, 4200, 3300, 4200, n, 0));
EXPECT_EQ(7, mesh::battIconLevel(0, 4500, 3300, 4200, n, 0)); // above scale
EXPECT_EQ(4, mesh::battIconLevel(0, 3750, 3300, 4200, n, 0)); // exactly on a boundary
EXPECT_EQ(3, mesh::battIconLevel(0, 3749, 3300, 4200, n, 0)); // one mV below it
}
// From a cold start the climb loop has to reach the right level on its own.
TEST(BatteryIcon, ColdStartClimbsToTheRightLevel) {
const uint8_t n = 8;
// mast-repeater-one as measured: 3794 mV on the 3300..4200 scale.
uint8_t lvl = mesh::battIconLevel(0, 3794, 3300, 4200, n, BATT_ICON_HYST_MV);
EXPECT_EQ(3, lvl); // step is 112 mV; 3794 sits in the 4th band
}
// Falls immediately, climbs only once clear of the boundary.
TEST(BatteryIcon, HysteresisIsAsymmetric) {
// POZOR na typy: `const uint8_t n = 8, lo = 3300, ...` by dalo uint8_t VŠEM
// a 3300/4200 by přeteklo na 228/104 -- funkce pak vrací 0 a test projde
// pro nic. Stalo se to tady 21. 9. 2026.
const uint8_t n = 8;
const uint16_t lo = 3300, hi = 4200, hyst = 50;
// Boundary into level 4 is 3300 + 4*900/8 = 3750.
EXPECT_EQ(3, mesh::battIconLevel(3, 3749, lo, hi, n, hyst)); // just under
EXPECT_EQ(3, mesh::battIconLevel(3, 3780, lo, hi, n, hyst)); // over, inside hysteresis
EXPECT_EQ(4, mesh::battIconLevel(3, 3800, lo, hi, n, hyst)); // clear of it -> climbs
EXPECT_EQ(4, mesh::battIconLevel(4, 3750, lo, hi, n, hyst)); // at boundary, holds
EXPECT_EQ(3, mesh::battIconLevel(4, 3749, lo, hi, n, hyst)); // below -> drops at once
}
// The measured daily swing of a solar node under weak sun was 38-46 mV. The
// level must not follow sunrise and sunset.
TEST(BatteryIcon, SurvivesTheMeasuredDailySwing) {
const uint8_t n = 8;
const uint16_t lo = 3300, hi = 4200;
// Park just under a boundary (3750) and swing +-23 mV around it all week.
uint8_t lvl = mesh::battIconLevel(0, 3740, lo, hi, n, BATT_ICON_HYST_MV);
const uint8_t settled = lvl;
for (int day = 0; day < 7; day++) {
lvl = mesh::battIconLevel(lvl, 3717, lo, hi, n, BATT_ICON_HYST_MV);
EXPECT_EQ(settled, lvl) << "night, day " << day;
lvl = mesh::battIconLevel(lvl, 3763, lo, hi, n, BATT_ICON_HYST_MV);
EXPECT_EQ(settled, lvl) << "day, day " << day;
}
}
TEST(BatteryIcon, DegenerateScalesDoNotDivideByZero) {
EXPECT_EQ(0, mesh::battIconLevel(3, 3800, 4200, 3300, 8, 50)); // hi <= lo
EXPECT_EQ(0, mesh::battIconLevel(3, 3800, 3300, 3300, 8, 50)); // empty span
EXPECT_EQ(0, mesh::battIconLevel(3, 3800, 3300, 4200, 1, 50)); // single level
EXPECT_EQ(7, mesh::battIconLevel(200, 4200, 3300, 4200, 8, 50)); // prev out of range
}
// End to end against the real encoder: a name sized to the budget keeps the
// icon intact, and the parser on the far side reads it back byte for byte.
TEST(BatteryIcon, EncoderKeepsTheIconOnAFittingName) {
char name[32];
snprintf(name, sizeof(name), "mast-repeater-one%s", BATT_ICON_OK);
// indicator intact, and the parser on the far side reads it back byte for byte.
TEST(BatteryIcon, EncoderKeepsTheIndicatorOnAFittingName) {
char glyph[8];
mesh::battIconGlyph(glyph, 3);
char name[40];
snprintf(name, sizeof(name), "mast-repeater-one%s%s", BATT_ICON_MARKER, glyph);
ASSERT_EQ(23u, strlen(name));
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
@@ -81,11 +129,13 @@ TEST(BatteryIcon, EncoderKeepsTheIconOnAFittingName) {
EXPECT_TRUE(parser.hasLatLon());
}
// And the failure mode we refuse to ship: one byte over and the clamp eats
// the icon whole, leaving a name that looks fine and silently lost its state.
TEST(BatteryIcon, EncoderSilentlyDropsAnIconThatDoesNotFit) {
char name[40];
snprintf(name, sizeof(name), "tth-mast-repeater-one%s", BATT_ICON_OK);
// The failure mode we refuse to ship: one byte over and the clamp eats the
// indicator, leaving a name that looks fine and silently lost its state.
TEST(BatteryIcon, EncoderSilentlyDropsAnIndicatorThatDoesNotFit) {
char glyph[8];
mesh::battIconGlyph(glyph, 3);
char name[48];
snprintf(name, sizeof(name), "tth-mast-repeater-one%s%s", BATT_ICON_MARKER, glyph);
ASSERT_EQ(27u, strlen(name));
ASSERT_FALSE(mesh::battIconFits(strlen("tth-mast-repeater-one"), true));
@@ -95,13 +145,14 @@ TEST(BatteryIcon, EncoderSilentlyDropsAnIconThatDoesNotFit) {
AdvertDataParser parser(app_data, len);
ASSERT_TRUE(parser.isValid());
EXPECT_STREQ("tth-mast-repeater-one", parser.getName()); // icon gone, no error
EXPECT_STREQ("tth-mast-repeater-one", parser.getName()); // indicator gone, no error
}
// Whatever the icons are changed to, they must survive `set name`'s filter.
TEST(BatteryIcon, IconsPassTheNameCharacterFilter) {
EXPECT_TRUE(AdvertDataParser::isValidName(BATT_ICON_OK));
EXPECT_TRUE(AdvertDataParser::isValidName(BATT_ICON_LOW));
// Whatever the glyphs are changed to, they must survive `set name`'s filter.
TEST(BatteryIcon, GlyphsPassTheNameCharacterFilter) {
EXPECT_TRUE(AdvertDataParser::isValidName(BATT_ICON_MARKER));
EXPECT_TRUE(AdvertDataParser::isValidName(BATT_ICON_EXTERNAL));
EXPECT_TRUE(AdvertDataParser::isValidName(BATT_ICON_LEVELS));
}
int main(int argc, char** argv) {