feat(display): add R8 observer TFT dashboard, touch toggle and display.timeout

Replace the sparse Heltec V4 R8 observer home screen with a padded dark
analytics dashboard, add manual display control, and make blanking a runtime
setting.

Dashboard (DISPLAY_ACTIVITY_DASHBOARD, the four R8 TFT observer envs):

- RadioActivityWindow: 20 one-minute buckets of valid RX packets, no heap.
  The caller's 32-bit millis() is extended to a monotonic 64-bit clock, so
  nothing downstream has a rollover case; an always-on node passes 2^32 ms
  after ~49.7 days, which would otherwise re-enter warm-up and divide 20
  minutes of traffic by seconds. Rates use 19 whole minutes plus the elapsed
  part of the current one rather than a fixed 1200 s.
- ObserverDashboard: header, radio strip, headline totals, a 20-bar
  packets-per-minute graph and RF/status footers, with separate portrait and
  landscape layouts. A text row is a fixed 16 px, which is 3.2 logical units
  in portrait but 4.27 in landscape, so one shared grid would overlap.
  Text is trimmed by character budget, not measured width: getTextWidth()
  reports an over-long string at the portrait driver's fallback scale, so
  DisplayDriver::drawTextEllipsized() under-trims and the row renders at half
  height.
- Six per-row signatures computed from what is actually drawn, so only the
  rows whose pixels changed repaint. No startFrame(), no whole-screen clear.
  Link state moved out of the full-frame signature, so a DHCP renewal or WiFi
  flap repaints one footer row instead of the panel.
- Dark theme by retuning the UIColor statics at runtime, which needs no
  display-driver edit and carries boot, setup, reboot and power-off with it.

Touch and button (DISPLAY_TOUCH_TOGGLE):

- CHSC6X at I2C 0x2E, polled; TP_INT is unusable (optional R13, and GPIO 43
  is U0TXD). The point-count byte is tested against a valid count, never
  against non-zero: an idle read returns 0xFF, which reads as a finger held
  down forever and latches the tap detector after one event.
- turnOff() no longer parks PIN_TFT_RST low on this board. GPIO 21 is a
  shared LCD_RST/TP_RST net, so doing that held the touch controller in
  reset for as long as the display was off. Verified against Heltec's
  expansion-board and mainboard schematics and the V4-R8 datasheet pinout,
  which also correct the pin comment in HeltecV4R8Board.cpp.
- The USER button click now toggles the display too; it previously did
  nothing whenever the display was already on.

display.timeout:

- `set display.timeout <secs>` / `get display.timeout`, 0 = stay on, 60 s
  default, 3600 max. Read live, so a change applies without a reboot and
  restarts the countdown rather than firing on the old deadline.
- Stored in MQTTPrefs (/mqtt.json), keeping NodePrefs aligned with upstream.
  Runtime-only: LegacyV1MQTTPrefs and the four frozen binary payload sizes
  are unchanged. No JSON format-version bump - the loader skips keys no
  def() claims, so older firmware reads newer files and this firmware reads
  older ones with the default applied. Both directions are covered by tests.
- Joins the observer atomic-setter contract, so a failed save rolls the live
  value back instead of only claiming to.

New periodic work uses a wrap-safe deadline check; `millis() >= deadline`
fires every loop for a whole interval before each rollover.

Adds test_radio_activity_window, test_observer_dashboard (driving the real
renderer against a recording DisplayDriver in both orientation profiles) and
test_touch_tap_detector. 440 native cases pass.
This commit is contained in:
agessaman committed 2026-08-28 13:39:16 -07:00
1 parent fc361ca94b
commit fcd92e985f
27 files changed
+2709 -25

No files matched your search

+3
View File
@@ -38,6 +38,9 @@ does not reflect the GoogleTest count — run the built binary directly
| `test_mqtt_prefs_serializer` | `src/helpers/MQTTPrefsSerializer.h`, `src/helpers/ConfigSerializer.*` | semantic nested `/mqtt.json` round trips; numeric slot keys; required/future version handling; strict length/overflow/duplicate rejection; safe semantic repair; scratch-before-live loading |
| `test_mqtt_prefs_atomic_store` | `src/helpers/MQTTPrefsAtomicStore.h`, `src/helpers/MQTTPrefsRecovery.h` | production JSON begin/write/checksum-finish/schema-verify/commit orchestration; first-migration and rename-boundary recovery; legacy `/node_prefs` handoff; failure cleanup and original-file preservation |
| `test_mqtt_payload_builder` | `src/helpers/MQTTPayloadBuilder.cpp` | status/packet/raw JSON contracts; optional fields; escaping; RX metrics and path; score handling; exact buffer bounds; maximum representative payloads |
| `test_radio_activity_window` | `src/helpers/RadioActivityWindow.h` | 20-minute minute-bucketed RX window: totals and derived rates; bucket rotation and oldest-to-newest ordering; expiry at the boundary; ring clear after 20 minutes of silence; warm-up versus steady-state denominators; peak minute; last-packet age and staleness; counter saturation; `millis()` rollover, including the minute boundary a `now_ms / 60000` quotient would corrupt |
| `test_observer_dashboard` | `src/helpers/ui/ObserverDashboard.h` | R8 TFT observer dashboard against a recording `DisplayDriver` in both orientation profiles: compact number/byte/age formatting and the 5 s age quantisation; per-row character budgets; on-panel and inside-the-margin bounds; no silent portrait scale fallback; non-overlapping row rectangles and each row's repaint covering everything it draws; 20-bar graph scaling, ordering and empty/spike cases; per-row signatures and the partial-repaint policy |
| `test_touch_tap_detector` | `src/helpers/ui/TouchTapDetector.h` | debounced rising-edge detection for the polled Expansion Kit touch panel: idle quiet; one tap per touch; long presses do not repeat; sub-debounce blips ignored; contact bounce still counts once; minimum gap between accepted taps; `millis()` rollover; reset semantics |
| `test_utils` | `src/Utils.cpp` | `Utils::toHex` (upstream) |
## Conventions (and how to add a suite)
@@ -78,6 +78,7 @@ static MQTTPrefs defaults() {
prefs.alert_mqtt_minutes = 240;
prefs.alert_min_interval_min = 60;
prefs.mqtt_neighbors_interval = MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS;
prefs.display_timeout_secs = DISPLAY_TIMEOUT_DEFAULT_SECS;
strcpy(prefs.snmp_community, "public");
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
strcpy(prefs.mqtt_slot_preset[i], "none");
@@ -375,6 +376,72 @@ TEST(MQTTPrefsSerializer, SaveNormalizationIsIdempotentAgainstKnownDefaults) {
EXPECT_FALSE(repaired) << output.text();
}
TEST(MQTTPrefsSerializer, DisplayTimeoutRoundTrips) {
for (uint16_t secs : {(uint16_t)0, (uint16_t)45, DISPLAY_TIMEOUT_MAX_SECS}) {
MQTTPrefs source = defaults();
source.display_timeout_secs = secs;
OutputStream output;
MQTTPrefsSerializer writer(&source);
ASSERT_TRUE(writer.saveSerial(output)) << secs;
MQTTPrefs loaded = defaults();
InputStream input(output.text());
MQTTPrefsSerializer reader(&loaded);
ASSERT_TRUE(reader.loadSerial(input)) << secs;
bool repaired = false;
ASSERT_TRUE(reader.apply(&repaired)) << secs;
EXPECT_FALSE(repaired) << secs;
EXPECT_EQ(secs, loaded.display_timeout_secs);
}
}
TEST(MQTTPrefsSerializer, RepairsDisplayTimeoutOutOfRange) {
MQTTPrefs prefs = defaults();
InputStream input("{version:1,display:{timeout_s:99999}}");
MQTTPrefsSerializer serializer(&prefs);
ASSERT_TRUE(serializer.loadSerial(input));
bool repaired = false;
ASSERT_TRUE(serializer.apply(&repaired));
EXPECT_TRUE(repaired);
EXPECT_EQ(DISPLAY_TIMEOUT_DEFAULT_SECS, prefs.display_timeout_secs);
prefs = defaults();
InputStream negative("{version:1,display:{timeout_s:-5}}");
MQTTPrefsSerializer negative_serializer(&prefs);
ASSERT_TRUE(negative_serializer.loadSerial(negative));
repaired = false;
ASSERT_TRUE(negative_serializer.apply(&repaired));
EXPECT_TRUE(repaired);
EXPECT_EQ(DISPLAY_TIMEOUT_DEFAULT_SECS, prefs.display_timeout_secs);
}
TEST(MQTTPrefsSerializer, PrefsWrittenBeforeTheDisplayGroupStillLoad) {
// Upgrade path: a /mqtt.json from firmware without the display group must
// load cleanly and keep the default rather than collapsing to 0 ("stay on").
MQTTPrefs prefs = defaults();
InputStream input("{version:1,radio:{watchdog_min:5}}");
MQTTPrefsSerializer serializer(&prefs);
ASSERT_TRUE(serializer.loadSerial(input));
bool repaired = false;
ASSERT_TRUE(serializer.apply(&repaired));
EXPECT_EQ(DISPLAY_TIMEOUT_DEFAULT_SECS, prefs.display_timeout_secs);
}
TEST(MQTTPrefsSerializer, UnknownGroupsAreIgnoredSoAppendedKeysAreDowngradeSafe) {
// The mirror of the case above, and the reason appending `display` needed no
// MQTT_PREFS_JSON_FORMAT_VERSION bump: firmware that predates a group skips
// it rather than failing the load.
MQTTPrefs prefs = defaults();
InputStream input(
"{version:1,display:{timeout_s:45},future:{thing:1,nested:{x:2}}}");
MQTTPrefsSerializer serializer(&prefs);
ASSERT_TRUE(serializer.loadSerial(input));
bool repaired = false;
ASSERT_TRUE(serializer.apply(&repaired));
EXPECT_EQ(45, prefs.display_timeout_secs);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
+122
View File
@@ -0,0 +1,122 @@
#pragma once
#include "helpers/ui/DisplayDriver.h"
#include "helpers/ui/DisplayViewport.h"
#include <string>
#include <vector>
// A DisplayDriver that records physical-pixel draw calls instead of pushing
// them at a panel, reproducing the two real ST7789LCDDisplay coordinate and
// text-metric profiles:
//
// portrait (ST7789_PORTRAIT_PROFILE) 240x320, DisplayViewport mapping,
// physical text scale = logical * 2
// landscape (default) 320x240, x * 2.5 / y * 3.75,
// physical text scale = (int)(logical * 2.5)
//
// Text extents are recorded at the size the layout *asked* for, so a row that
// only fits because the driver would silently shrink or clip it still shows up
// as an out-of-bounds op.
class MockDisplay : public DisplayDriver {
public:
enum Mode { PORTRAIT, LANDSCAPE };
struct Op {
enum Kind { FILL, RECT, TEXT } kind;
int x, y, w, h; // physical pixels
ColorVal color;
std::string text;
int logical_size;
bool scale_fallback; // portrait driver would have shrunk this string
};
explicit MockDisplay(Mode mode)
: DisplayDriver(128, 64), _mode(mode), _on(true), _color(0), _size(1), _cx(0), _cy(0) {}
std::vector<Op> ops;
int panelWidth() const { return _mode == PORTRAIT ? 240 : 320; }
int panelHeight() const { return _mode == PORTRAIT ? 320 : 240; }
void reset() { ops.clear(); }
// --- DisplayDriver ---
bool isOn() override { return _on; }
void turnOn() override { _on = true; }
void turnOff() override { _on = false; }
void clear() override { ops.clear(); }
void startFrame(ColorVal bkg = UIColor::window_bkg) override {
ops.clear();
ops.push_back(Op{Op::FILL, 0, 0, panelWidth(), panelHeight(), bkg, "", 1, false});
_size = 1;
}
void setTextSize(int sz) override { _size = sz > 0 ? sz : 1; }
void setColor(ColorVal c) override { _color = c; }
void setCursor(int x, int y) override { _cx = x; _cy = y; }
void print(const char* str) override {
if (!str || !*str) return;
int n = (int)strlen(str);
int scale = physicalScale(_size);
int px = mapX(_cx), py = mapY(_cy);
bool fallback = false;
if (_mode == PORTRAIT) {
int available = panelWidth() - px;
if (n * 6 * scale > available) {
fallback = true; // the real driver drops to the minimum scale here
}
}
ops.push_back(Op{Op::TEXT, px, py, n * 6 * scale, 8 * scale, _color, std::string(str), _size,
fallback});
_cx += (int)((n * 6 * scale) / xScale());
}
void fillRect(int x, int y, int w, int h) override {
ops.push_back(Op{Op::FILL, mapX(x), mapY(y), spanX(x, w), spanY(y, h), _color, "", _size,
false});
}
void drawRect(int x, int y, int w, int h) override {
ops.push_back(Op{Op::RECT, mapX(x), mapY(y), spanX(x, w), spanY(y, h), _color, "", _size,
false});
}
void drawXbm(int, int, const uint8_t*, int, int) override {}
void endFrame() override {}
uint16_t getTextWidth(const char* str) override {
if (!str) return 0;
int n = (int)strlen(str);
int scale = physicalScale(_size);
if (_mode == PORTRAIT) {
// Mirrors ST7789LCDDisplay::getTextWidth(): measure at the scale the
// driver would pick, clamp to the panel, convert back to logical.
if (n * 6 * scale > panelWidth()) scale = _size;
int w = n * 6 * scale;
if (w > panelWidth()) w = panelWidth();
DisplayViewport::Geometry g{128, 64, 240, 320};
return g.logicalWidthForPhysical((uint16_t)w);
}
return (uint16_t)((n * 6 * scale) / 2.5f);
}
private:
Mode _mode;
bool _on;
ColorVal _color;
int _size, _cx, _cy;
float xScale() const { return _mode == PORTRAIT ? (240.0f / 128.0f) : 2.5f; }
int physicalScale(int logical) const {
return _mode == PORTRAIT ? logical * 2 : (int)(uint8_t)(logical * 2.5f);
}
int mapX(int x) const {
return _mode == PORTRAIT ? (int)((int32_t)x * 240 / 128) : (int)(x * 2.5f);
}
int mapY(int y) const {
return _mode == PORTRAIT ? (int)((int32_t)y * 320 / 64) : (int)(y * 3.75f);
}
int spanX(int x, int w) const { return mapX(x + w) - mapX(x); }
int spanY(int y, int h) const { return mapY(y + h) - mapY(y); }
};
@@ -0,0 +1,581 @@
#include "MockDisplay.h"
#include "helpers/ui/ObserverDashboard.h"
#include <gtest/gtest.h>
// UIColor's slots live in whichever display driver a firmware target links; the
// host build supplies its own.
ColorVal UIColor::window_bkg = 0;
ColorVal UIColor::title_bkg = 0;
ColorVal UIColor::title_txt = 0;
ColorVal UIColor::primary_txt = 0;
ColorVal UIColor::secondary_txt = 0;
ColorVal UIColor::warning_txt = 0;
ColorVal UIColor::popup_bkg = 0;
ColorVal UIColor::popup_txt = 0;
ColorVal UIColor::corp_blue = 0;
using namespace ObserverDashboard;
namespace {
const int N = RADIO_ACTIVITY_BUCKETS;
struct Profile {
MockDisplay::Mode mode;
Layout layout;
const char* name;
int panel_w, panel_h;
int margin_left, margin_right; // physical
};
Profile portrait() { return {MockDisplay::PORTRAIT, portraitLayout(), "portrait", 240, 320, 7, 232}; }
Profile landscape() { return {MockDisplay::LANDSCAPE, landscapeLayout(), "landscape", 320, 240, 10, 310}; }
Context makeContext(const char* name = "Ridgeline North") {
Context c;
c.node_name = name;
c.role_label = "REPEATER";
c.freq = 910.525f;
c.sf = 7;
c.bw = 62.5f;
c.link_up = true;
return c;
}
// A busy but plausible 20 minutes: 1843 packets, a peak minute of 214.
RadioActivitySnapshot makeBusy() {
RadioActivityWindow w;
w.reset(0);
const uint16_t per_minute[RADIO_ACTIVITY_BUCKETS] = {12, 40, 8, 0, 97, 133, 71, 3, 214, 65,
19, 88, 44, 27, 0, 150, 92, 61, 7, 35};
for (int m = 0; m < N; m++) {
for (int i = 0; i < per_minute[m]; i++) {
w.recordPacket((uint32_t)m * RADIO_ACTIVITY_BUCKET_MS + 1000 + i, 48, 120, 26, -103);
}
}
RadioActivitySnapshot s;
w.snapshot((uint32_t)(N - 1) * RADIO_ACTIVITY_BUCKET_MS + 30000, &s);
return s;
}
RadioActivitySnapshot makeEmpty() {
RadioActivityWindow w;
w.reset(0);
RadioActivitySnapshot s;
w.snapshot(7 * RADIO_ACTIVITY_BUCKET_MS, &s);
return s;
}
bool insideRect(const MockDisplay::Op& op, int x, int y, int w, int h) {
return op.x >= x && op.y >= y && op.x + op.w <= x + w && op.y + op.h <= y + h;
}
} // namespace
// ------------------------------------------------------------- formatting ---
TEST(ObserverDashboardFormat, CompactCountsStayShortAtEveryMagnitude) {
char b[24];
struct { uint32_t v; const char* want; } cases[] = {
{0, "0"}, {7, "7"}, {9999, "9999"}, {10000, "10.0k"},
{12345, "12.3k"}, {99999, "99.9k"}, {100000, "100k"}, {999999, "999k"},
{1000000, "1.0M"},{12345678, "12.3M"},{100000000, "100M"}};
for (auto& c : cases) {
formatCompactCount(b, sizeof(b), c.v);
EXPECT_STREQ(c.want, b) << "value " << c.v;
EXPECT_LE(strlen(b), 5u) << "value " << c.v;
}
}
TEST(ObserverDashboardFormat, CompactBytesPickSensibleUnits) {
char b[24];
struct { uint32_t v; const char* want; } cases[] = {
{0, "0 B"}, {1023, "1023 B"}, {1024, "1.0 KB"},
{10240, "10.0 KB"}, {145408, "142 KB"}, {1048576, "1.0 MB"},
{15728640, "15.0 MB"}};
for (auto& c : cases) {
formatCompactBytes(b, sizeof(b), c.v);
EXPECT_STREQ(c.want, b) << "value " << c.v;
}
}
TEST(ObserverDashboardFormat, TenthsAndSignedTenths) {
char b[24];
formatTenths(b, sizeof(b), 0); EXPECT_STREQ("0.0", b);
formatTenths(b, sizeof(b), 34); EXPECT_STREQ("3.4", b);
formatTenths(b, sizeof(b), 999); EXPECT_STREQ("99.9", b);
formatTenths(b, sizeof(b), 1000); EXPECT_STREQ("100", b);
formatSignedTenths(b, sizeof(b), 72); EXPECT_STREQ("+7.2", b);
formatSignedTenths(b, sizeof(b), 0); EXPECT_STREQ("+0.0", b);
formatSignedTenths(b, sizeof(b), -115); EXPECT_STREQ("-11.5", b);
}
TEST(ObserverDashboardFormat, AgeIsQuantisedToTheFiveSecondCadence) {
EXPECT_EQ(0u, quantizeAgeSecs(0));
EXPECT_EQ(0u, quantizeAgeSecs(4999));
EXPECT_EQ(5u, quantizeAgeSecs(5000));
EXPECT_EQ(5u, quantizeAgeSecs(9999));
char b[24];
formatAge(b, sizeof(b), 0, false); EXPECT_STREQ("--", b);
formatAge(b, sizeof(b), 0, true); EXPECT_STREQ("now", b);
formatAge(b, sizeof(b), 4999, true); EXPECT_STREQ("now", b);
formatAge(b, sizeof(b), 12000, true); EXPECT_STREQ("10s", b);
formatAge(b, sizeof(b), 59999, true); EXPECT_STREQ("55s", b);
formatAge(b, sizeof(b), 60000, true); EXPECT_STREQ("1m", b);
formatAge(b, sizeof(b), 3599999, true); EXPECT_STREQ("59m", b);
formatAge(b, sizeof(b), 3600000, true); EXPECT_STREQ("1h", b);
}
TEST(ObserverDashboardFormat, EmptyWindowNeverProducesNanOrInfinity) {
RadioActivitySnapshot s = makeEmpty();
Context ctx = makeContext();
for (int r = 0; r < ROW_COUNT; r++) {
if (r == ROW_GRAPH) continue;
RowText t;
composeRow((Row)r, ctx, s, &t);
for (const char* p : {t.left, t.right}) {
EXPECT_EQ(nullptr, strstr(p, "nan")) << p;
EXPECT_EQ(nullptr, strstr(p, "inf")) << p;
}
}
// Unmeasurable values read as "--"; measured zeroes read as real zeroes.
RowText headline, rate, rf, status;
composeRow(ROW_HEADLINE, ctx, s, &headline);
composeRow(ROW_RATE, ctx, s, &rate);
composeRow(ROW_RF, ctx, s, &rf);
composeRow(ROW_STATUS, ctx, s, &status);
EXPECT_STREQ("No RF yet", headline.left);
EXPECT_STREQ("0 B", rate.left);
EXPECT_STREQ("0.0/min", rate.right);
EXPECT_STREQ("SNR --", rf.left);
EXPECT_STREQ("AIR 0.0%", rf.right);
EXPECT_STREQ("RX --", status.left);
}
TEST(ObserverDashboardFormat, EveryRowFitsTheCharacterBudget) {
for (const Profile& p : {portrait(), landscape()}) {
for (const RadioActivitySnapshot& s : {makeBusy(), makeEmpty()}) {
for (int r = 0; r < ROW_COUNT; r++) {
if (r == ROW_GRAPH) continue;
RowText t;
composeRow((Row)r, makeContext(), s, &t);
int budget = (r == ROW_HEADLINE) ? p.layout.max_chars_big : p.layout.max_chars;
int used = (int)strlen(t.left) + (int)strlen(t.right);
if (t.left[0] && t.right[0]) used += 1; // separating space
EXPECT_LE(used, budget) << p.name << " row " << r << ": '" << t.left << "' / '" << t.right << "'";
}
}
}
}
TEST(ObserverDashboardFormat, RadioStripDropsADeadBandwidthDecimal) {
char b[32];
formatRadioStrip(b, sizeof(b), 910.525f, 7, 62.5f);
EXPECT_STREQ("910.525 SF7 BW62.5", b);
formatRadioStrip(b, sizeof(b), 869.618f, 8, 250.0f);
EXPECT_STREQ("869.618 SF8 BW250", b);
formatRadioStrip(b, sizeof(b), 433.125f, 12, 125.0f);
EXPECT_STREQ("433.125 SF12 BW125", b);
}
TEST(ObserverDashboardFormat, RadioStripFitsEveryOrientationsBudget) {
// The widest realistic combination must not be ellipsized away.
const struct { float freq; uint8_t sf; float bw; } cases[] = {
{910.525f, 7, 62.5f}, {869.618f, 8, 250.0f}, {433.125f, 12, 125.0f},
{915.000f, 11, 500.0f}, {868.000f, 9, 41.7f}};
for (const Profile& p : {portrait(), landscape()}) {
for (const auto& c : cases) {
char b[32];
formatRadioStrip(b, sizeof(b), c.freq, c.sf, c.bw);
EXPECT_LE((int)strlen(b), p.layout.max_chars) << p.name << " '" << b << "'";
}
}
}
TEST(ObserverDashboardLayout, HeaderTextStaysInsideTheHeaderBar) {
for (const Profile& p : {portrait(), landscape()}) {
MockDisplay d(p.mode);
drawHeader(d, p.layout, makeContext());
ASSERT_FALSE(d.ops.empty());
const auto& bar = d.ops.front();
ASSERT_EQ(MockDisplay::Op::FILL, bar.kind) << p.name;
for (size_t i = 1; i < d.ops.size(); i++) {
EXPECT_TRUE(insideRect(d.ops[i], bar.x, bar.y, bar.w, bar.h))
<< p.name << " '" << d.ops[i].text << "'";
}
}
}
TEST(ObserverDashboardLayout, PortraitHeaderShowsTheWholeNodeName) {
// A 16-character name must survive intact: on a 240 px panel the role label
// moves to a second header line rather than eating the name.
MockDisplay d(MockDisplay::PORTRAIT);
Context ctx = makeContext("Ridgeline North");
drawHeader(d, portraitLayout(), ctx);
bool saw_name = false, saw_role = false;
for (const auto& op : d.ops) {
if (op.text == "Ridgeline North") saw_name = true;
if (op.text == "REPEATER") saw_role = true;
}
EXPECT_TRUE(saw_name) << "node name was ellipsized";
EXPECT_TRUE(saw_role);
}
TEST(ObserverDashboardFormat, TextIsAsciiOnly) {
// The driver's UTF-8 fallback collapses every non-ASCII byte to a full block,
// so any stray multi-byte character would render as a solid glyph.
for (const RadioActivitySnapshot& s : {makeBusy(), makeEmpty()}) {
for (int r = 0; r < ROW_COUNT; r++) {
if (r == ROW_GRAPH) continue;
RowText t;
composeRow((Row)r, makeContext(), s, &t);
for (const char* p : {t.left, t.right}) {
for (const char* c = p; *c; c++) {
EXPECT_GE((unsigned char)*c, 32u) << "row " << r;
EXPECT_LE((unsigned char)*c, 126u) << "row " << r;
}
}
}
}
}
// ----------------------------------------------------------------- layout ---
TEST(ObserverDashboardLayout, EveryDrawnPixelStaysOnThePanel) {
for (const Profile& p : {portrait(), landscape()}) {
MockDisplay d(p.mode);
drawFull(d, p.layout, makeContext(), makeBusy());
ASSERT_FALSE(d.ops.empty());
for (const auto& op : d.ops) {
EXPECT_GE(op.x, 0) << p.name;
EXPECT_GE(op.y, 0) << p.name;
EXPECT_LE(op.x + op.w, p.panel_w) << p.name << " '" << op.text << "'";
EXPECT_LE(op.y + op.h, p.panel_h) << p.name << " '" << op.text << "'";
}
}
}
TEST(ObserverDashboardLayout, AllTextIsPaddedInsideTheMargins) {
for (const Profile& p : {portrait(), landscape()}) {
for (const RadioActivitySnapshot& s : {makeBusy(), makeEmpty()}) {
MockDisplay d(p.mode);
drawFull(d, p.layout, makeContext(), s);
for (const auto& op : d.ops) {
if (op.kind != MockDisplay::Op::TEXT) continue;
EXPECT_GE(op.x, p.margin_left) << p.name << " '" << op.text << "'";
EXPECT_LE(op.x + op.w, p.margin_right) << p.name << " '" << op.text << "'";
}
}
}
}
TEST(ObserverDashboardLayout, NoTextSilentlyShrinksToTheFallbackScale) {
// The portrait driver halves the glyph size rather than clipping. A row that
// only fits because of that would break the grid, so it must never happen.
for (const RadioActivitySnapshot& s : {makeBusy(), makeEmpty()}) {
MockDisplay d(MockDisplay::PORTRAIT);
drawFull(d, portraitLayout(), makeContext(), s);
for (const auto& op : d.ops) {
EXPECT_FALSE(op.scale_fallback) << "'" << op.text << "'";
}
}
}
TEST(ObserverDashboardLayout, ContentClearsTheTopAndBottomEdges) {
for (const Profile& p : {portrait(), landscape()}) {
MockDisplay d(p.mode);
drawFull(d, p.layout, makeContext(), makeBusy());
int lowest = 0;
for (const auto& op : d.ops) lowest = std::max(lowest, op.y + op.h);
EXPECT_GE(p.panel_h - lowest, 8) << p.name << ": bottom margin too small";
}
}
TEST(ObserverDashboardLayout, RowRectanglesDoNotOverlap) {
for (const Profile& p : {portrait(), landscape()}) {
MockDisplay d(p.mode);
for (int a = 0; a < ROW_COUNT; a++) {
for (int b = a + 1; b < ROW_COUNT; b++) {
int ay = p.layout.margin_x, unused = ay;
(void)unused;
int a_top = rowY(p.layout, (Row)a), a_bot = a_top + rowH(p.layout, (Row)a);
int b_top = rowY(p.layout, (Row)b), b_bot = b_top + rowH(p.layout, (Row)b);
bool overlap = a_top < b_bot && b_top < a_bot;
EXPECT_FALSE(overlap) << p.name << ": rows " << a << " and " << b;
}
}
// ...and the header and radio strip sit above the first row.
EXPECT_LT(p.layout.header_h, p.layout.radio_y) << p.name;
EXPECT_LT(p.layout.radio_y + p.layout.text_h, rowY(p.layout, ROW_WINDOW) + 1) << p.name;
}
}
TEST(ObserverDashboardLayout, EachRowRepaintCoversEverythingThatRowDraws) {
// The no-flash invariant: a partial repaint clears one row rectangle and then
// redraws inside it. Anything drawn outside that rectangle would leave stale
// pixels behind or scribble on a neighbouring row.
for (const Profile& p : {portrait(), landscape()}) {
for (const RadioActivitySnapshot& s : {makeBusy(), makeEmpty()}) {
for (int r = 0; r < ROW_COUNT; r++) {
MockDisplay d(p.mode);
drawRow(d, p.layout, (Row)r, makeContext(), s, true);
ASSERT_FALSE(d.ops.empty()) << p.name << " row " << r;
const auto& clear = d.ops.front();
ASSERT_EQ(MockDisplay::Op::FILL, clear.kind) << p.name << " row " << r;
EXPECT_EQ(BG, clear.color) << p.name << " row " << r;
for (size_t i = 1; i < d.ops.size(); i++) {
EXPECT_TRUE(insideRect(d.ops[i], clear.x, clear.y, clear.w, clear.h))
<< p.name << " row " << r << " op " << i << " '" << d.ops[i].text << "'";
}
}
}
}
}
// ------------------------------------------------------------------ graph ---
TEST(ObserverDashboardGraph, DrawsExactlyTwentyNonOverlappingBars) {
for (const Profile& p : {portrait(), landscape()}) {
RadioActivitySnapshot s = makeBusy();
for (int i = 0; i < N; i++) s.buckets[i] = (uint16_t)(i + 1);
s.peak_per_min = N;
MockDisplay d(p.mode);
drawGraph(d, p.layout, s);
// First op is the baseline, then one bar per non-empty bucket.
ASSERT_GE(d.ops.size(), 1u);
std::vector<MockDisplay::Op> bars(d.ops.begin() + 1, d.ops.end());
ASSERT_EQ((size_t)N, bars.size()) << p.name;
for (size_t i = 1; i < bars.size(); i++) {
EXPECT_GE(bars[i].x, bars[i - 1].x + bars[i - 1].w) << p.name << " bar " << i << " overlaps";
EXPECT_GE(bars[i].h, bars[i - 1].h) << p.name << " bar " << i << " not monotonic";
}
EXPECT_EQ(BAR_NOW, bars.back().color) << p.name << ": current minute must stand out";
EXPECT_EQ(BAR, bars.front().color) << p.name;
}
}
TEST(ObserverDashboardGraph, BarsStayInsideTheGraphRectangle) {
for (const Profile& p : {portrait(), landscape()}) {
RadioActivitySnapshot s = makeBusy();
MockDisplay probe(p.mode);
probe.setColor(0);
probe.fillRect(p.layout.margin_x, p.layout.graph_y, p.layout.right_x - p.layout.margin_x,
p.layout.graph_h);
MockDisplay::Op rect = probe.ops.front();
MockDisplay d(p.mode);
drawGraph(d, p.layout, s);
for (const auto& op : d.ops) {
EXPECT_TRUE(insideRect(op, rect.x, rect.y, rect.w, rect.h)) << p.name;
}
}
}
TEST(ObserverDashboardGraph, AllZeroWindowDrawsOnlyTheBaseline) {
for (const Profile& p : {portrait(), landscape()}) {
MockDisplay d(p.mode);
drawGraph(d, p.layout, makeEmpty());
ASSERT_EQ(1u, d.ops.size()) << p.name << ": empty minutes must not draw one-pixel activity";
EXPECT_EQ(GRID, d.ops.front().color) << p.name;
}
}
TEST(ObserverDashboardGraph, SingleSpikeFillsTheGraphAndLeavesTheRestEmpty) {
for (const Profile& p : {portrait(), landscape()}) {
RadioActivitySnapshot s = makeEmpty();
s.buckets[5] = 400;
s.peak_per_min = 400;
s.packets = 400;
uint8_t h[RADIO_ACTIVITY_BUCKETS];
barHeights(p.layout, s, h);
EXPECT_EQ(p.layout.graph_h - 1, h[5]) << p.name;
for (int i = 0; i < N; i++) {
if (i != 5) EXPECT_EQ(0, h[i]) << p.name << " bucket " << i;
}
MockDisplay d(p.mode);
drawGraph(d, p.layout, s);
EXPECT_EQ(2u, d.ops.size()) << p.name; // baseline + one bar
}
}
TEST(ObserverDashboardGraph, AnyTrafficRoundsUpToAVisibleBar) {
for (const Profile& p : {portrait(), landscape()}) {
RadioActivitySnapshot s = makeEmpty();
s.buckets[0] = 1;
s.buckets[19] = 5000;
s.peak_per_min = 5000;
uint8_t h[RADIO_ACTIVITY_BUCKETS];
barHeights(p.layout, s, h);
EXPECT_EQ(1, h[0]) << p.name << ": a single packet must still be visible";
EXPECT_EQ(p.layout.graph_h - 1, h[19]) << p.name;
}
}
// ------------------------------------------------------------- signatures ---
TEST(ObserverDashboardSignature, IdenticallyFormattedDataDoesNotRepaint) {
Layout l = portraitLayout();
Context ctx = makeContext();
RadioActivitySnapshot a = makeEmpty();
a.packets = 100000;
RadioActivitySnapshot b = a;
b.packets = 100999; // both render as "100k pkt"
EXPECT_EQ(rowSignature(l, ROW_HEADLINE, ctx, a), rowSignature(l, ROW_HEADLINE, ctx, b));
b.packets = 101500; // renders as "101k pkt"
EXPECT_NE(rowSignature(l, ROW_HEADLINE, ctx, a), rowSignature(l, ROW_HEADLINE, ctx, b));
}
TEST(ObserverDashboardSignature, AGraphChangeTouchesOnlyTheGraphRow) {
Layout l = portraitLayout();
Context ctx = makeContext();
RadioActivitySnapshot a = makeBusy();
RadioActivitySnapshot b = a;
b.buckets[N - 1] = (uint16_t)(a.buckets[N - 1] + 40); // the current minute grows
uint32_t sa[ROW_COUNT], sb[ROW_COUNT];
allRowSignatures(l, ctx, a, sa);
allRowSignatures(l, ctx, b, sb);
for (int r = 0; r < ROW_COUNT; r++) {
if (r == ROW_GRAPH) {
EXPECT_NE(sa[r], sb[r]) << "graph row must notice the new bar height";
} else {
EXPECT_EQ(sa[r], sb[r]) << "row " << r << " must not repaint";
}
}
}
TEST(ObserverDashboardSignature, DataChangesBelowTheGraphResolutionDoNotRepaint) {
// Signatures are computed from bar heights, not from the packet counts behind
// them, so a busy minute ticking up by one costs nothing on screen.
Layout l = portraitLayout();
Context ctx = makeContext();
RadioActivitySnapshot a = makeBusy();
RadioActivitySnapshot b = a;
b.buckets[N - 1] = (uint16_t)(a.buckets[N - 1] + 1);
uint8_t ha[RADIO_ACTIVITY_BUCKETS], hb[RADIO_ACTIVITY_BUCKETS];
barHeights(l, a, ha);
barHeights(l, b, hb);
ASSERT_EQ(ha[N - 1], hb[N - 1]) << "test needs a change smaller than one bar unit";
EXPECT_EQ(rowSignature(l, ROW_GRAPH, ctx, a), rowSignature(l, ROW_GRAPH, ctx, b));
}
TEST(ObserverDashboardSignature, LinkStateOnlyTouchesTheStatusRow) {
Layout l = portraitLayout();
RadioActivitySnapshot s = makeBusy();
Context up = makeContext();
Context down = makeContext();
down.link_up = false;
uint32_t sa[ROW_COUNT], sb[ROW_COUNT];
allRowSignatures(l, up, s, sa);
allRowSignatures(l, down, s, sb);
for (int r = 0; r < ROW_COUNT; r++) {
if (r == ROW_STATUS) {
EXPECT_NE(sa[r], sb[r]);
} else {
EXPECT_EQ(sa[r], sb[r]) << "row " << r;
}
}
}
TEST(ObserverDashboardSignature, PartialRepaintDrawsOnlyTheChangedRow) {
Profile p = portrait();
Context ctx = makeContext();
RadioActivitySnapshot a = makeBusy();
uint32_t sigs[ROW_COUNT];
allRowSignatures(p.layout, ctx, a, sigs);
RadioActivitySnapshot b = a;
b.buckets[N - 1] = (uint16_t)(a.buckets[N - 1] + 40);
MockDisplay d(p.mode);
EXPECT_TRUE(drawChangedRows(d, p.layout, ctx, b, sigs));
// One clear plus the graph contents, all inside the graph rectangle.
ASSERT_FALSE(d.ops.empty());
const auto& clear = d.ops.front();
EXPECT_EQ(BG, clear.color);
for (const auto& op : d.ops) {
EXPECT_TRUE(insideRect(op, clear.x, clear.y, clear.w, clear.h));
}
// Nothing left to do on a second pass with the same data.
MockDisplay d2(p.mode);
EXPECT_FALSE(drawChangedRows(d2, p.layout, ctx, b, sigs));
EXPECT_TRUE(d2.ops.empty());
}
TEST(ObserverDashboardSignature, LongNodeNameIsTrimmedInsideTheHeader) {
for (const Profile& p : {portrait(), landscape()}) {
MockDisplay d(p.mode);
Context ctx = makeContext("A Very Long Repeater Node Name That Cannot Possibly Fit");
drawHeader(d, p.layout, ctx);
bool saw_role = false, saw_ellipsis = false;
for (const auto& op : d.ops) {
if (op.kind != MockDisplay::Op::TEXT) continue;
EXPECT_GE(op.x, p.margin_left) << p.name;
EXPECT_LE(op.x + op.w, p.margin_right) << p.name << " '" << op.text << "'";
EXPECT_FALSE(op.scale_fallback) << p.name << " '" << op.text << "'";
if (op.text == "REPEATER") saw_role = true;
if (op.text.size() >= 3 && op.text.compare(op.text.size() - 3, 3, "...") == 0)
saw_ellipsis = true;
}
EXPECT_TRUE(saw_role) << p.name << ": the role label must survive a long node name";
EXPECT_TRUE(saw_ellipsis) << p.name << ": the name must be visibly truncated";
}
}
TEST(ObserverDashboardSignature, FitToCharsRespectsItsBudget) {
char b[32];
fitToChars(b, sizeof(b), "short", 18); EXPECT_STREQ("short", b);
fitToChars(b, sizeof(b), "exactly-18-chars!", 17); EXPECT_STREQ("exactly-18-chars!", b);
fitToChars(b, sizeof(b), "Ridgeline North Ridge", 18);
EXPECT_STREQ("Ridgeline North...", b);
EXPECT_EQ(18u, strlen(b));
fitToChars(b, sizeof(b), "abcdef", 3); EXPECT_STREQ("abc", b);
fitToChars(b, sizeof(b), "abcdef", 0); EXPECT_STREQ("", b);
fitToChars(b, sizeof(b), "", 18); EXPECT_STREQ("", b);
}
TEST(ObserverDashboardSignature, DarkPaletteRetunesTheSharedColourSlots) {
applyDarkPalette();
EXPECT_EQ(BG, UIColor::window_bkg);
EXPECT_EQ(TEXT, UIColor::primary_txt);
EXPECT_EQ(HEADER_BG, UIColor::title_bkg);
EXPECT_EQ(ACCENT, UIColor::corp_blue);
// The setup portal's highlight must stay legible on the dark background.
EXPECT_NE(UIColor::window_bkg, UIColor::warning_txt);
EXPECT_NE(UIColor::window_bkg, UIColor::primary_txt);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,376 @@
#include "helpers/RadioActivityWindow.h"
#include <gtest/gtest.h>
namespace {
const uint32_t MINUTE = RADIO_ACTIVITY_BUCKET_MS;
const int N = RADIO_ACTIVITY_BUCKETS;
// Representative packet: 32 wire bytes, 100 ms airtime, +7.0 dB SNR, -95 dBm.
void recordTypical(RadioActivityWindow& w, uint32_t at_ms, uint16_t bytes = 32) {
w.recordPacket(at_ms, bytes, 100, 28, -95);
}
RadioActivitySnapshot snapshotAt(RadioActivityWindow& w, uint32_t at_ms) {
RadioActivitySnapshot s;
w.snapshot(at_ms, &s);
return s;
}
} // namespace
TEST(RadioActivityWindow, EmptySnapshotHasNoTotalsAndNoDivisionByZero) {
RadioActivityWindow w;
w.reset(0);
RadioActivitySnapshot s = snapshotAt(w, 0);
EXPECT_TRUE(s.isEmpty());
EXPECT_EQ(0u, s.packets);
EXPECT_EQ(0u, s.wire_bytes);
EXPECT_EQ(0u, s.window_ms);
EXPECT_FALSE(s.has_last_packet);
EXPECT_EQ(0u, s.peak_per_min);
// Every derived value must be defined with a zero denominator.
EXPECT_EQ(0u, s.packetsPerMinuteX10());
EXPECT_EQ(0u, s.bytesPerSecondX10());
EXPECT_EQ(0u, s.avgBytesPerPacket());
EXPECT_EQ(0u, s.airtimePercentX10());
EXPECT_EQ(0, s.avgSnrX10());
EXPECT_EQ(0, s.avgRssi());
for (int i = 0; i < N; i++) EXPECT_EQ(0u, s.buckets[i]);
}
TEST(RadioActivityWindow, SingleEventProducesExactTotalsAndRates) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000);
RadioActivitySnapshot s = snapshotAt(w, 2000);
EXPECT_EQ(1u, s.packets);
EXPECT_EQ(32u, s.wire_bytes);
EXPECT_EQ(100u, s.airtime_ms);
EXPECT_EQ(2000u, s.window_ms);
EXPECT_EQ(2000u, s.tracking_ms);
EXPECT_EQ(300u, s.packetsPerMinuteX10()); // 30.0 packets/min
EXPECT_EQ(160u, s.bytesPerSecondX10()); // 16.0 B/s
EXPECT_EQ(32u, s.avgBytesPerPacket());
EXPECT_EQ(50u, s.airtimePercentX10()); // 5.0 %
EXPECT_EQ(70, s.avgSnrX10()); // +7.0 dB
EXPECT_EQ(-95, s.avgRssi());
EXPECT_TRUE(s.has_last_packet);
EXPECT_EQ(1000u, s.last_packet_age_ms);
// The current minute is the rightmost bucket.
EXPECT_EQ(1u, s.buckets[N - 1]);
for (int i = 0; i < N - 1; i++) EXPECT_EQ(0u, s.buckets[i]);
}
TEST(RadioActivityWindow, MultipleEventsInOneMinuteAccumulate) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000, 10);
recordTypical(w, 2000, 20);
recordTypical(w, 3000, 30);
RadioActivitySnapshot s = snapshotAt(w, 4000);
EXPECT_EQ(3u, s.packets);
EXPECT_EQ(60u, s.wire_bytes);
EXPECT_EQ(300u, s.airtime_ms);
EXPECT_EQ(20u, s.avgBytesPerPacket());
EXPECT_EQ(3u, s.buckets[N - 1]);
EXPECT_EQ(3u, s.peak_per_min);
EXPECT_EQ(1000u, s.last_packet_age_ms);
}
TEST(RadioActivityWindow, EventsRotateIntoTheNextBucketAtTheMinuteBoundary) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 30000); // minute 0
recordTypical(w, MINUTE); // exactly on the boundary: minute 1
recordTypical(w, MINUTE + 5000); // minute 1
RadioActivitySnapshot s = snapshotAt(w, MINUTE + 10000);
EXPECT_EQ(3u, s.packets);
EXPECT_EQ(2u, s.buckets[N - 1]); // current minute
EXPECT_EQ(1u, s.buckets[N - 2]); // previous minute
EXPECT_EQ(2u, s.peak_per_min);
}
TEST(RadioActivityWindow, BucketsAreOrderedOldestToNewest) {
RadioActivityWindow w;
w.reset(0);
// Minute m gets (m + 1) packets.
for (int m = 0; m < N; m++) {
for (int i = 0; i <= m; i++) recordTypical(w, m * MINUTE + 1000 + i);
}
RadioActivitySnapshot s = snapshotAt(w, (N - 1) * MINUTE + 30000);
for (int i = 0; i < N; i++) {
EXPECT_EQ((uint16_t)(i + 1), s.buckets[i]) << "bucket " << i;
}
EXPECT_EQ((uint16_t)N, s.peak_per_min);
EXPECT_EQ((uint32_t)(N * (N + 1) / 2), s.packets);
}
TEST(RadioActivityWindow, OldestBucketExpiresOnceItLeavesTheWindow) {
RadioActivityWindow w;
w.reset(0);
for (int m = 0; m < N; m++) recordTypical(w, m * MINUTE + 1000);
// Still inside the window: all 20 minutes are represented.
RadioActivitySnapshot before = snapshotAt(w, (N - 1) * MINUTE + 59999);
EXPECT_EQ((uint32_t)N, before.packets);
EXPECT_EQ(1u, before.buckets[0]);
// One tick past the boundary: the oldest minute is gone, and the new current
// minute is empty.
RadioActivitySnapshot after = snapshotAt(w, N * MINUTE);
EXPECT_EQ((uint32_t)(N - 1), after.packets);
EXPECT_EQ(1u, after.buckets[0]); // what was minute 1
EXPECT_EQ(0u, after.buckets[N - 1]); // the fresh current minute
}
TEST(RadioActivityWindow, MoreThanTwentyMinutesOfSilenceClearsTheRing) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000);
uint32_t now = 21 * MINUTE;
RadioActivitySnapshot s = snapshotAt(w, now);
EXPECT_TRUE(s.isEmpty());
for (int i = 0; i < N; i++) EXPECT_EQ(0u, s.buckets[i]);
// Tracking restarts at the current minute, so the window reports itself as
// warming up again rather than claiming 20 minutes of empty coverage.
EXPECT_EQ(0u, s.tracking_ms);
EXPECT_EQ(0u, s.window_ms);
EXPECT_TRUE(s.isWarmingUp());
// The last-packet age survives the ring clear: it is still the most useful
// thing to show when nothing is arriving.
EXPECT_TRUE(s.has_last_packet);
EXPECT_EQ(now - 1000, s.last_packet_age_ms);
}
TEST(RadioActivityWindow, LastPacketAgeIsDroppedOnceItGoesStale) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000);
RadioActivitySnapshot fresh = snapshotAt(w, 1000 + RADIO_ACTIVITY_MAX_AGE_MS);
EXPECT_TRUE(fresh.has_last_packet);
RadioActivitySnapshot stale = snapshotAt(w, 1000 + RADIO_ACTIVITY_MAX_AGE_MS + 1);
EXPECT_FALSE(stale.has_last_packet);
}
TEST(RadioActivityWindow, WarmupUsesObservedDurationNotAFixedTwentyMinutes) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 30000);
// Five minutes in, rates are computed against five minutes, not twenty.
RadioActivitySnapshot warm = snapshotAt(w, 5 * MINUTE);
EXPECT_TRUE(warm.isWarmingUp());
EXPECT_EQ(5u, warm.warmupMinutes());
EXPECT_EQ(5 * MINUTE, warm.window_ms);
// 1 packet over 5 minutes is 0.2/min. Against a fixed 1200 s denominator the
// same data would round away to 0.0/min.
EXPECT_EQ(2u, warm.packetsPerMinuteX10());
}
TEST(RadioActivityWindow, SteadyStateWindowNeverClaimsMoreCoverageThanTheRingHas) {
RadioActivityWindow w;
w.reset(0);
for (int m = 0; m < 25; m++) recordTypical(w, m * MINUTE + 1000);
// 19 whole minutes plus the elapsed part of the current one - never 20:00.
RadioActivitySnapshot at_start = snapshotAt(w, 25 * MINUTE);
EXPECT_FALSE(at_start.isWarmingUp());
EXPECT_EQ(19 * MINUTE, at_start.window_ms);
RadioActivitySnapshot mid = snapshotAt(w, 25 * MINUTE + 30000);
EXPECT_EQ(19 * MINUTE + 30000, mid.window_ms);
RadioActivitySnapshot late = snapshotAt(w, 25 * MINUTE + 59999);
EXPECT_EQ(19 * MINUTE + 59999, late.window_ms);
EXPECT_LT(late.window_ms, (uint32_t)N * MINUTE);
}
TEST(RadioActivityWindow, PeakIsTheBusiestVisibleMinute) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000);
for (int i = 0; i < 7; i++) recordTypical(w, MINUTE + 1000 + i);
recordTypical(w, 2 * MINUTE + 1000);
EXPECT_EQ(7u, snapshotAt(w, 2 * MINUTE + 30000).peak_per_min);
// Once the busy minute ages out of the ring, so does the peak.
EXPECT_EQ(1u, snapshotAt(w, 21 * MINUTE).peak_per_min);
}
TEST(RadioActivityWindow, SurvivesMillisRollover) {
const uint32_t base = 0xFFFFF000u; // ~4 s before the 32-bit wrap
RadioActivityWindow w;
w.reset(base);
recordTypical(w, base + 1000);
// 65 s later, which is 60904 in wrapped millis().
uint32_t after_wrap = (uint32_t)(base + 65000);
ASSERT_LT(after_wrap, base) << "test setup must actually cross the wrap";
recordTypical(w, after_wrap);
RadioActivitySnapshot s = snapshotAt(w, after_wrap + 1000);
EXPECT_EQ(2u, s.packets);
EXPECT_EQ(1u, s.buckets[N - 1]); // the post-wrap minute
EXPECT_EQ(1u, s.buckets[N - 2]); // the pre-wrap minute
EXPECT_EQ(66000u, s.window_ms);
EXPECT_EQ(1000u, s.last_packet_age_ms);
}
TEST(RadioActivityWindow, RolloverDoesNotCorruptTheMinuteBoundary) {
// A boundary derived from now_ms / BUCKET_MS would misplace a minute here,
// because 2^32 is not a whole number of 60000 ms buckets.
const uint32_t base = 0xFFFFFFFFu - 30000u;
RadioActivityWindow w;
w.reset(base);
for (int m = 0; m < 5; m++) recordTypical(w, (uint32_t)(base + m * MINUTE + 1000));
RadioActivitySnapshot s = snapshotAt(w, (uint32_t)(base + 4 * MINUTE + 30000));
EXPECT_EQ(5u, s.packets);
for (int i = 0; i < 5; i++) {
EXPECT_EQ(1u, s.buckets[N - 1 - i]) << "minute -" << i;
}
EXPECT_EQ(1u, s.peak_per_min);
}
TEST(RadioActivityWindow, SurvivesAFullMillisCycleOfContinuousUptime) {
// The always-on dashboard services the tracker every few seconds forever. Past
// 2^32 ms (~49.7 days) a 32-bit tracker age wraps back to a small value, which
// would drop the window into warm-up and divide 20 minutes of traffic by
// seconds - inflating every rate on screen.
RadioActivityWindow w;
w.reset(0);
const uint32_t STEP = 30000; // two packets per minute bucket
uint32_t now = 0;
for (uint64_t elapsed = 0; elapsed < 0x100000000ull + 10 * MINUTE; elapsed += STEP) {
recordTypical(w, now);
RadioActivitySnapshot tick;
w.snapshot(now, &tick);
now += STEP;
}
RadioActivitySnapshot s = snapshotAt(w, now);
EXPECT_FALSE(s.isWarmingUp()) << "must not fall back into warm-up after the wrap";
EXPECT_GE(s.window_ms, 19 * MINUTE);
EXPECT_LE(s.window_ms, (uint32_t)N * MINUTE);
// 19 whole minutes at two packets each, plus however much of the current
// minute has elapsed.
EXPECT_GE(s.packets, 38u);
EXPECT_LE(s.packets, 41u);
// Two packets a minute, and it must still read as two.
EXPECT_GE(s.packetsPerMinuteX10(), 15u);
EXPECT_LE(s.packetsPerMinuteX10(), 25u);
EXPECT_TRUE(s.has_last_packet);
EXPECT_EQ(STEP, s.last_packet_age_ms);
}
TEST(RadioActivityWindow, StaleLastPacketDoesNotComeBackAfterTheWrap) {
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000);
// Serviced continuously, but silent, for more than one full 32-bit cycle.
uint32_t now = 0;
const uint32_t STEP = 60000;
for (uint64_t elapsed = 0; elapsed < 0x100000000ull + 10 * MINUTE; elapsed += STEP) {
RadioActivitySnapshot tick;
w.snapshot(now, &tick);
if (elapsed > RADIO_ACTIVITY_MAX_AGE_MS) {
ASSERT_FALSE(tick.has_last_packet) << "a stale age must never look fresh again";
}
now += STEP;
}
RadioActivitySnapshot s = snapshotAt(w, now);
EXPECT_TRUE(s.isEmpty());
EXPECT_FALSE(s.has_last_packet);
}
TEST(RadioActivityWindow, SaturatedMinuteDropsFurtherEventsWhole) {
RadioActivityWindow w;
w.reset(0);
for (uint32_t i = 0; i < 65535; i++) w.recordPacket(1000, 10, 1, 4, -100);
RadioActivitySnapshot full = snapshotAt(w, 2000);
EXPECT_EQ(65535u, full.packets);
EXPECT_EQ(655350u, full.wire_bytes);
// Past saturation nothing is counted, so bytes-per-packet stays truthful.
w.recordPacket(1500, 10, 1, 4, -100);
RadioActivitySnapshot after = snapshotAt(w, 2000);
EXPECT_EQ(65535u, after.packets);
EXPECT_EQ(655350u, after.wire_bytes);
EXPECT_EQ(10u, after.avgBytesPerPacket());
}
TEST(RadioActivityWindow, AnOlderTimestampDoesNotExpireTheWindow) {
// recordPacket() and snapshot() read millis() at slightly different moments;
// a reading that arrives out of order must cost nothing.
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 5000);
RadioActivitySnapshot ahead = snapshotAt(w, 10000);
ASSERT_EQ(1u, ahead.packets);
recordTypical(w, 9000); // stale reading, 1 s behind the last snapshot
RadioActivitySnapshot s = snapshotAt(w, 10000);
EXPECT_EQ(2u, s.packets) << "the ring must not have been cleared";
EXPECT_EQ(2u, s.buckets[N - 1]);
EXPECT_EQ(10000u, s.window_ms);
}
TEST(RadioActivityWindow, AveragesHandleNegativeSnrAndMixedSigns) {
RadioActivityWindow w;
w.reset(0);
w.recordPacket(1000, 40, 50, 28, -80); // +7.0 dB
w.recordPacket(1100, 40, 50, -28, -120); // -7.0 dB
RadioActivitySnapshot s = snapshotAt(w, 2000);
EXPECT_EQ(0, s.avgSnrX10());
EXPECT_EQ(-100, s.avgRssi());
}
TEST(RadioActivityWindow, StaysWithinItsMemoryBudget) {
EXPECT_LE(sizeof(RadioActivityWindow), 1024u);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,123 @@
#include "helpers/ui/TouchTapDetector.h"
#include <gtest/gtest.h>
namespace {
// Drives the detector at the firmware's 50 ms poll cadence.
const uint32_t POLL = 50;
// Holds `pressed` for `ms`, returning how many taps were accepted.
int hold(TouchTapDetector& d, uint32_t& now, bool pressed, uint32_t ms) {
int taps = 0;
for (uint32_t t = 0; t < ms; t += POLL) {
if (d.update(now, pressed)) taps++;
now += POLL;
}
return taps;
}
} // namespace
TEST(TouchTapDetector, IdlePanelNeverTaps) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(0, hold(d, now, false, 5000));
EXPECT_FALSE(d.isTouched());
}
TEST(TouchTapDetector, OneTouchProducesExactlyOneTap) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 300));
EXPECT_TRUE(d.isTouched());
EXPECT_EQ(0, hold(d, now, false, 300));
EXPECT_FALSE(d.isTouched());
}
TEST(TouchTapDetector, HoldingAFingerDownDoesNotRepeat) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 100));
EXPECT_EQ(0, hold(d, now, true, 10000)) << "a long press must not toggle repeatedly";
}
TEST(TouchTapDetector, ContactShorterThanTheDebounceWindowIsIgnored) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
// A single 30 ms blip, below TOUCH_TAP_DEBOUNCE_MS.
EXPECT_FALSE(d.update(now, true));
now += 30;
EXPECT_FALSE(d.update(now, false));
now += 30;
EXPECT_EQ(0, hold(d, now, false, 500));
}
TEST(TouchTapDetector, BounceOnContactStillCountsAsOneTap) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
int taps = 0;
for (int i = 0; i < 6; i++) { // chattering edge
if (d.update(now, i % 2 == 0)) taps++;
now += 10;
}
taps += hold(d, now, true, 200); // then settles down
EXPECT_EQ(1, taps);
}
TEST(TouchTapDetector, SecondTapTooSoonIsSuppressed) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 100));
EXPECT_EQ(0, hold(d, now, false, 100));
EXPECT_EQ(0, hold(d, now, true, 100)) << "inside TOUCH_TAP_MIN_GAP_MS";
}
TEST(TouchTapDetector, DeliberateSecondTapIsAccepted) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 100));
EXPECT_EQ(0, hold(d, now, false, 600)); // past the min gap
EXPECT_EQ(1, hold(d, now, true, 100));
}
TEST(TouchTapDetector, SurvivesMillisRollover) {
TouchTapDetector d;
const uint32_t start = 0xFFFFFF9Bu; // ~100 ms short of the 32-bit wrap
uint32_t now = start;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 200)); // the touch itself crosses the wrap
ASSERT_LT(now, start) << "test setup must actually wrap";
EXPECT_EQ(0, hold(d, now, false, 600));
EXPECT_EQ(1, hold(d, now, true, 200));
}
TEST(TouchTapDetector, ResetClearsPendingState) {
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 200));
d.reset(now);
EXPECT_FALSE(d.isTouched());
EXPECT_EQ(1, hold(d, now, true, 200)) << "a fresh probe starts clean";
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}