From 5f56a80a78c3f9b97441e17cec8d620f8d63441d Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Mon, 21 Sep 2026 19:13:38 +0200 Subject: [PATCH] =?UTF-8?q?feat(advert):=20stav=20baterie=20jako=20ikonka?= =?UTF-8?q?=20na=20konci=20advertovan=C3=A9ho=20jm=C3=A9na?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5 --- docs/cli_commands.md | 42 +++++++ platformio.ini | 2 + src/helpers/BatteryIcon.h | 88 +++++++++++++++ src/helpers/CommonCLI.cpp | 78 ++++++++++++- src/helpers/CommonCLI.h | 11 ++ test/mocks/Arduino.h | 3 + test/test_battery_icon/test_battery_icon.cpp | 110 +++++++++++++++++++ 7 files changed, 331 insertions(+), 3 deletions(-) create mode 100644 src/helpers/BatteryIcon.h create mode 100644 test/test_battery_icon/test_battery_icon.cpp diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 81bb6c08..283f78c9 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -360,6 +360,48 @@ 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. + +**Usage:** +- `get batt.icon` +- `set batt.icon on|off` + +**Default:** `off` + +**Icons:** `☀️` above the threshold, `🪫` below it. + +**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:** 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. + +--- + +#### Battery threshold for the name icon +**Usage:** +- `get batt.icon.mv` +- `set batt.icon.mv ` + +**Set by build flag:** `BATT_ICON_LOW_MV` + +**Default:** `3700` (roughly 44 % of a 1S Li-Ion cell) + +**Parameters:** +- `millivolts`: `3000`..`4200`, or `0` to use the build default + +--- + #### View or change this node's latitude **Usage:** - `get lat` diff --git a/platformio.ini b/platformio.ini index 1af9addc..52064631 100644 --- a/platformio.ini +++ b/platformio.ini @@ -201,6 +201,7 @@ build_src_filter = -<*> +<../src/Utils.cpp> +<../src/Packet.cpp> + +<../src/helpers/AdvertDataHelpers.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> +<../src/helpers/FairnessLimiter.cpp> @@ -240,6 +241,7 @@ build_src_filter = -<*> +<../src/Utils.cpp> +<../src/Packet.cpp> + +<../src/helpers/AdvertDataHelpers.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> +<../src/helpers/FairnessLimiter.cpp> diff --git a/src/helpers/BatteryIcon.h b/src/helpers/BatteryIcon.h new file mode 100644 index 00000000..dd1bc036 --- /dev/null +++ b/src/helpers/BatteryIcon.h @@ -0,0 +1,88 @@ +#pragma once + +// CUSTOM (TeTeHacko): battery state as an icon appended to the advertised +// node name. +// +// Why at all: the node already reports its battery in telemetry, but only +// someone who can log into it gets to read that. An icon in the advert reaches +// everyone who hears the node, and costs a handful of bytes of app_data. +// +// 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: +// +// U+2600 U+FE0F (sun, emoji presentation) 6 bytes -- the variation +// selector is half of it +// U+1FAAB (low battery) 4 bytes +// +// 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. + +#include +#include +#include + +#ifndef BATT_ICON_OK + #define BATT_ICON_OK "\u2600\uFE0F" // sun, 6 bytes +#endif +#ifndef BATT_ICON_LOW + #define BATT_ICON_LOW "\U0001FAAB" // low battery, 4 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 +#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_HYST_MV + #define BATT_ICON_HYST_MV 100 +#endif + +namespace mesh { + +// 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. +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); +} + +// 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; +} + +// On sampling: one analogRead per decision is deliberate. +// +// 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 +// roughly 50/50. A median over five samples was tried and does NOT help +// (spread 420 mV raw vs 380 mV median): it is not an outlier to reject, it is +// VBAT floating against the charger with nothing to clamp it. +// +// 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. + +} diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 22e93d3f..6d794342 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -2,6 +2,7 @@ #include "CommonCLI.h" #include "TxtDataHelpers.h" #include "AdvertDataHelpers.h" +#include "BatteryIcon.h" #include "TxtDataHelpers.h" #include #include @@ -174,15 +175,37 @@ 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. +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); + + 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); + return _adv_name; +} + uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) { if (_prefs->advert_loc_policy == ADVERT_LOC_NONE) { - AdvertDataBuilder builder(node_type, _prefs->node_name); + AdvertDataBuilder builder(node_type, advertName(false)); return builder.encodeTo(app_data); } else if (_prefs->advert_loc_policy == ADVERT_LOC_SHARE) { - AdvertDataBuilder builder(node_type, _prefs->node_name, _sensors->node_lat, _sensors->node_lon); + AdvertDataBuilder builder(node_type, advertName(true), _sensors->node_lat, _sensors->node_lon); return builder.encodeTo(app_data); } else { - AdvertDataBuilder builder(node_type, _prefs->node_name, _prefs->node_lat, _prefs->node_lon); + AdvertDataBuilder builder(node_type, advertName(true), _prefs->node_lat, _prefs->node_lon); return builder.encodeTo(app_data); } } @@ -780,6 +803,31 @@ 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) { + int mv = atoi(&config[13]); + if (mv != 0 && (mv < 3000 || mv > 4200)) { + strcpy(reply, "Error: expected 3000..4200, or 0 for default"); + } else { + _prefs->batt_icon_mv = mv; + savePrefs(); + sprintf(reply, "OK - low below %d mV", mv ? mv : BATT_ICON_LOW_MV); + } + } else if (memcmp(config, "batt.icon ", 10) == 0) { + _prefs->batt_icon = memcmp(&config[10], "on", 2) == 0 ? 1 : 0; + savePrefs(); + if (!_prefs->batt_icon) { + strcpy(reply, "off"); + } else if (!mesh::battIconFits(strlen(_prefs->node_name), + _prefs->advert_loc_policy != ADVERT_LOC_NONE)) { + // Say so now rather than let the operator wonder why nothing shows up: + // the icon is dropped whole when it doesn't fit. + 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))); + } else { + strcpy(reply, "on - shows on next advert"); + } } else if (memcmp(config, "adc.multiplier ", 15) == 0) { _prefs->adc_multiplier = atof(&config[15]); if (_board->setAdcMultiplier(_prefs->adc_multiplier)) { @@ -836,6 +884,30 @@ 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", 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". + 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); + } 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 { + // 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); + } } else if (memcmp(config, "name", 4) == 0) { sprintf(reply, "> %s", _prefs->node_name); } else if (memcmp(config, "repeat", 6) == 0) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index dc7990a8..1bfd93b4 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -77,6 +77,10 @@ public: // just leave them at defaults. uint8_t fairness_enabled = 0; // FairnessLimiter runtime kill switch char filter_deny[128]; // channel-filter deny list, comma-separated node names + // 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 // 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; @@ -179,6 +183,8 @@ private: void structure() override { 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); } public: PowerPrefs(NodePrefs* parent) : _parent(parent) { } @@ -321,8 +327,13 @@ class CommonCLI { RegionMap* _region_map; ClientACL* _acl; char tmp[PRV_KEY_SIZE*2 + 4]; + // 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 mesh::RTCClock* getRTCClock() { return _rtc; } + const char* advertName(bool with_loc); void savePrefs(); void loadPrefsInt(FILESYSTEM* _fs, const char* filename); diff --git a/test/mocks/Arduino.h b/test/mocks/Arduino.h index 77499fe4..fa412774 100644 --- a/test/mocks/Arduino.h +++ b/test/mocks/Arduino.h @@ -2,6 +2,9 @@ #include #include +// Real Arduino.h pulls stdio in; code under test (AdvertTimeHelper) relies on +// sprintf being available in the global namespace from this header alone. +#include #include "Stream.h" inline uint32_t g_mock_millis = 0; diff --git a/test/test_battery_icon/test_battery_icon.cpp b/test/test_battery_icon/test_battery_icon.cpp new file mode 100644 index 00000000..9f38a853 --- /dev/null +++ b/test/test_battery_icon/test_battery_icon.cpp @@ -0,0 +1,110 @@ +#include + +#include +#include +#include + +// 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 +} + +TEST(BatteryIcon, BudgetMatchesAdvertLayout) { + EXPECT_EQ(23u, mesh::advertNameBudget(true)); // 32 - 1 flags - 8 lat/lon + EXPECT_EQ(31u, mesh::advertNameBudget(false)); +} + +// The real names of the three nodes this was written for. +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)); +} + +TEST(BatteryIcon, DroppingPositionBuysEightBytes) { + EXPECT_FALSE(mesh::battIconFits(strlen("tth-mast-repeater-one"), true)); + EXPECT_TRUE(mesh::battIconFits(strlen("tth-mast-repeater-one"), false)); +} + +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); + } +} + +// 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); + ASSERT_EQ(23u, strlen(name)); + + uint8_t app_data[MAX_ADVERT_DATA_SIZE]; + AdvertDataBuilder builder(ADV_TYPE_REPEATER, name, 50.38, 12.82); + uint8_t len = builder.encodeTo(app_data); + + AdvertDataParser parser(app_data, len); + ASSERT_TRUE(parser.isValid()); + ASSERT_TRUE(parser.hasName()); + EXPECT_STREQ(name, parser.getName()); + 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); + ASSERT_EQ(27u, strlen(name)); + ASSERT_FALSE(mesh::battIconFits(strlen("tth-mast-repeater-one"), true)); + + uint8_t app_data[MAX_ADVERT_DATA_SIZE]; + AdvertDataBuilder builder(ADV_TYPE_REPEATER, name, 50.38, 12.82); + uint8_t len = builder.encodeTo(app_data); + + AdvertDataParser parser(app_data, len); + ASSERT_TRUE(parser.isValid()); + EXPECT_STREQ("tth-mast-repeater-one", parser.getName()); // icon 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)); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}