feat: integrate R8 observer and companion updates

This commit is contained in:
mikecarper committed 2026-08-28 18:39:26 -07:00
1 parent 89c12d416e
commit da61c48e7b
54 files changed
+5471 -158

No files matched your search

+7 -2
View File
@@ -37,8 +37,13 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_mqtt_packet_queue_policy` | `src/helpers/MQTTPacketQueuePolicy.h` | queue-full eviction; stale-disconnect flush; adaptive drain limits; bounded QoS0 retries; exact timing boundaries and 32-bit `millis()` rollover |
| `test_mqtt_packet_filter` | `src/helpers/MQTTPacketFilter.h` | per-slot 0-15 allowlist parsing/formatting, numeric and named spellings; exact bounds; membership; candidate/eligible split and retry-completion policy; pre-queue union gate; default-mask detection |
| `test_mqtt_runtime_buffer_lifecycle` | `src/helpers/MQTTRuntimeBufferLifecycle.h` | idempotent allocation/release; partial-allocation degradation; retry of only missing buffers |
| `test_mqtt_prefs_codec` | `src/helpers/MQTTPrefsStorage.h`, `src/helpers/MQTTPrefsCodec.h` | binary pre-slot/3-slot/6-slot migration fixtures; v1 header integrity; downgrade preservation; shortest-payload write policy (default filters stay downgrade-readable) |
| `test_mqtt_prefs_codec` | `src/helpers/MQTTPrefsStorage.h`, `src/helpers/MQTTPrefsCodec.h`, `src/helpers/CompanionMqttPrefsNvs.h` | binary pre-slot/3-slot/6-slot and display-tail migration fixtures; v1 header integrity; fixed Companion rollback/recovery shapes; downgrade preservation; shortest-payload write policy |
| `test_mqtt_prefs_atomic_store` | `src/helpers/MQTTPrefsAtomicStore.h` | transactional MQTT writes and legacy `/node_prefs` handoff; exact short-write detection; begin/finish/rename failure cleanup; original-file preservation |
| `test_mqtt_prefs_json_import` | `src/helpers/MQTTPrefsJsonImport.h`, `src/helpers/MQTTPrefsSerializer.h` | one-time observer `/mqtt.json` v1 import grammar, strict schema/repair rules, binary-first precedence, future/artifact preservation, display-tail encoding, and atomic commit failure routing |
| `test_display_viewport` | `src/helpers/ui/DisplayViewport.h`, `src/helpers/ui/DisplayFrameSignature.h` | portrait logical-to-physical mapping, span coverage, fitted-width conversion, text scaling, and visible-frame signatures |
| `test_radio_activity_window` | `src/helpers/RadioActivityWindow.h` | rolling minute buckets, derived rates, expiry, warm-up, silence, saturation, and `millis()` rollover |
| `test_observer_dashboard` | `src/helpers/ui/ObserverDashboard.h` | landscape and portrait dashboard layout bounds, compact formatting, graph scaling, row signatures, and partial repaint policy |
| `test_touch_tap_detector` | `src/helpers/ui/TouchTapDetector.h` | debounced one-shot taps, bounce and long-press handling, minimum gaps, reset, and `millis()` rollover |
| `test_prefs_save_routing` | `src/helpers/PrefsSaveRouting.h` | runtime common/observer setters write only their owning preference image; mixed-owner setters and migrations can deliberately write both |
| `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_telemetry_history` | `src/helpers/TelemetryHistory.h`, `ExternalVoltageHistory.h` | 30-minute rings; seven-day temperature/battery and four-day multi-channel I2C voltage retention; exact 1 C temperature/status and 0.02 V packed voltage encodings; zero-only channel omission; Base64 pages and raw chunks; GPS differentials, resize preservation, heap budgets, and paging bounds |
@@ -49,7 +54,7 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_gps_time_validation` | `src/helpers/sensors/GpsTimeValidation.h` | complete NMEA UTC validation; leap years and calendar bounds; rejection of receiver-default and signed-32-bit-out-of-range dates |
| `test_identity_generation` | `src/helpers/IdentityGeneration.h` | reserved-prefix rejection; bounded retries; final provisioned attempt; fail-closed exhaustion |
| `test_remote_cli_reply_cache` | `src/helpers/RemoteCliReplyCache.h`, `src/helpers/RemoteCliRequest.h`, `src/helpers/RemoteCliTimeout.h` | authenticated logical-request matching; bounded recent-reply history; backward-compatible retry identity; 300% response timeout; empty-response completion; on-air truncation and clearing |
| `test_companion_frame_queue` | `src/helpers/CompanionFrameQueue.h` | response/required/best-effort classification; reserved capacity; stable priority; safe eviction; message-waiting coalescing |
| `test_companion_frame_queue` | `src/helpers/CompanionFrameQueue.h`, `src/helpers/CompanionHardwareCommandCompat.h` | response/required/best-effort classification; reserved capacity; stable priority; safe eviction; message-waiting coalescing; command `0x42` framed-CLI disambiguation and deprecated hardware-alias mapping |
| `test_companion_status_response` | `src/helpers/CompanionStatusResponse.h` | request-tag correlation and minimum status-response length, including rejection of the three-entry ACL payload that previously masqueraded as status |
| `test_serial_mode_switch` | `src/helpers/ArduinoSerialInterface.cpp`, `src/helpers/MultiSerialInterface.h` | terminal/seeder control-sequence recognition, single-TTY logging transitions, and USB/TCP ownership; queued/atomic USB output under backpressure and short writes; partial-frame busy state; requester-affine replies, locked contact streams, and Bluetooth-only pairing routing |
| `test_ble_tx_stall_watchdog` | `src/helpers/BleTxStallWatchdog.h` | exact BLE fragment progress; blocked-reply timeout; rollover-safe elapsed time; disconnect recovery retry and completion |
@@ -1,6 +1,7 @@
#include <gtest/gtest.h>
#include <helpers/CompanionFrameQueue.h>
#include <helpers/CompanionHardwareCommandCompat.h>
namespace {
@@ -125,6 +126,35 @@ TEST(CompanionFrameQueue, ResponseDoesNotEvictAnotherResponse) {
EXPECT_EQ(0x06, queue[2].buf[0]);
}
TEST(CompanionHardwareCommandCompat, Command66TextWinsOverBareLegacyGet) {
EXPECT_FALSE(mesh::companion::isRunCliFrame(0x42, 1));
EXPECT_TRUE(mesh::companion::isFemRxGainGet(0x42));
EXPECT_TRUE(mesh::companion::isRunCliFrame(0x42, 2));
EXPECT_FALSE(mesh::companion::isRunCliFrame(0x41, 2));
}
TEST(CompanionHardwareCommandCompat, BothShippedAliasBlocksRemainInbound) {
EXPECT_TRUE(mesh::companion::isFemRxGainGet(0x42));
EXPECT_TRUE(mesh::companion::isFemRxGainGet(0x78));
EXPECT_TRUE(mesh::companion::isFemRxGainSet(0x43));
EXPECT_TRUE(mesh::companion::isFemRxGainSet(0x79));
EXPECT_TRUE(mesh::companion::isRadioRxGainGet(0x44));
EXPECT_TRUE(mesh::companion::isRadioRxGainGet(0x7A));
EXPECT_TRUE(mesh::companion::isRadioRxGainSet(0x45));
EXPECT_TRUE(mesh::companion::isRadioRxGainSet(0x7B));
EXPECT_TRUE(mesh::companion::isWiFiPowerSaveGet(0x46));
EXPECT_TRUE(mesh::companion::isWiFiPowerSaveGet(0x7C));
EXPECT_TRUE(mesh::companion::isWiFiPowerSaveSet(0x47));
EXPECT_TRUE(mesh::companion::isWiFiPowerSaveSet(0x7D));
EXPECT_TRUE(mesh::companion::isBluetoothNameGet(0x48));
EXPECT_TRUE(mesh::companion::isBluetoothNameGet(0x7E));
EXPECT_TRUE(mesh::companion::isBluetoothNameSet(0x49));
EXPECT_TRUE(mesh::companion::isBluetoothNameSet(0x7F));
EXPECT_FALSE(mesh::companion::isRadioRxGainGet(0x78));
EXPECT_FALSE(mesh::companion::isWiFiPowerSaveSet(0x7F));
}
} // namespace
int main(int argc, char** argv) {
@@ -189,6 +189,34 @@ TEST(ConfigSerializer, LoadSerial_MissingCommas) {
EXPECT_FALSE(success);
}
TEST(ConfigSerializer, LoadSerial_MissingCommaAfterObject) {
MockInputStream s("{radio:{} bridge:{}}");
TestStruct data;
EXPECT_FALSE(data.loadSerial(s));
}
TEST(ConfigSerializer, LoadSerial_RequiresOneCompleteRootObject) {
for (const char* text : {
"",
" \r\n\t ",
"{age:" TEST_INT_S ",}",
"{age:" TEST_INT_S "},",
"{age:" TEST_INT_S "}garbage",
"{age:" TEST_INT_S "}{flags:1}"}) {
MockInputStream s(text);
TestStruct data;
EXPECT_FALSE(data.loadSerial(s)) << text;
}
}
TEST(ConfigSerializer, LoadSerial_AcceptsEmptyObject) {
MockInputStream s("{} \r\n\t");
TestStruct data;
EXPECT_TRUE(data.loadSerial(s));
}
TEST(ConfigSerializer, LoadSerial_IgnoreUnknowns) {
MockInputStream s("{age:" TEST_INT_S ",xxx:" TEST_INT_S ",name:\"Scott\"}");
TestStruct data;
@@ -0,0 +1,83 @@
#include "helpers/ui/DisplayFrameSignature.h"
#include "helpers/ui/DisplayViewport.h"
#include <gtest/gtest.h>
namespace {
const DisplayViewport::Geometry kPortrait{ 128, 64, 240, 320 };
} // namespace
TEST(DisplayViewport, MapsLogicalBoundsToPortraitPanel) {
EXPECT_EQ(0, kPortrait.mapX(0));
EXPECT_EQ(240, kPortrait.mapX(128));
EXPECT_EQ(0, kPortrait.mapY(0));
EXPECT_EQ(320, kPortrait.mapY(64));
}
TEST(DisplayViewport, MapsObserverRowsAcrossPortraitHeight) {
EXPECT_EQ(0, kPortrait.mapY(0));
EXPECT_EQ(70, kPortrait.mapY(14));
EXPECT_EQ(100, kPortrait.mapY(20));
EXPECT_EQ(120, kPortrait.mapY(24));
EXPECT_EQ(150, kPortrait.mapY(30));
EXPECT_EQ(200, kPortrait.mapY(40));
EXPECT_EQ(240, kPortrait.mapY(48));
EXPECT_EQ(250, kPortrait.mapY(50));
}
TEST(DisplayViewport, FractionalHorizontalSpansHaveNoGapsOrOverlaps) {
int16_t previous_end = 0;
int total_width = 0;
for (int x = 0; x < 128; ++x) {
int16_t start = kPortrait.mapX(x);
int16_t end = kPortrait.mapX(x + 1);
EXPECT_EQ(previous_end, start);
EXPECT_TRUE(end - start == 1 || end - start == 2);
total_width += end - start;
previous_end = end;
}
EXPECT_EQ(240, previous_end);
EXPECT_EQ(240, total_width);
}
TEST(DisplayViewport, ConvertsFittedPhysicalWidthBackToLogicalWidth) {
EXPECT_EQ(0, kPortrait.logicalWidthForPhysical(0));
EXPECT_EQ(64, kPortrait.logicalWidthForPhysical(120));
EXPECT_EQ(122, kPortrait.logicalWidthForPhysical(228));
EXPECT_EQ(128, kPortrait.logicalWidthForPhysical(240));
}
TEST(DisplayViewport, SelectsPreferredTextScaleOnlyWhenItFits) {
EXPECT_EQ(2, DisplayViewport::selectTextScale(114, 2, 1, 240));
EXPECT_EQ(1, DisplayViewport::selectTextScale(150, 2, 1, 240));
EXPECT_EQ(1, DisplayViewport::selectTextScale(192, 2, 1, 229));
EXPECT_EQ(1, DisplayViewport::selectTextScale(300, 2, 1, 240));
}
TEST(DisplayFrameSignature, ChangesWithVisibleContent) {
uint32_t initial = DisplayFrameSignature::INITIAL;
uint32_t home = DisplayFrameSignature::append(initial, "home");
EXPECT_EQ(home, DisplayFrameSignature::append(initial, "home"));
EXPECT_NE(home, DisplayFrameSignature::append(initial, "setup"));
EXPECT_NE(DisplayFrameSignature::append(home, "10.0.0.1"), DisplayFrameSignature::append(home, "10.0.0.2"));
}
TEST(DisplayFrameSignature, KeepsAdjacentFieldsDistinct) {
uint32_t first = DisplayFrameSignature::append(DisplayFrameSignature::INITIAL, "ab");
first = DisplayFrameSignature::append(first, "c");
uint32_t second = DisplayFrameSignature::append(DisplayFrameSignature::INITIAL, "a");
second = DisplayFrameSignature::append(second, "bc");
EXPECT_NE(first, second);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -4,6 +4,7 @@
#include <vector>
#define WITH_MQTT_BRIDGE 1
#include "helpers/CompanionMqttPrefsNvs.h"
#include "helpers/MQTTPrefsCodec.h"
#include "helpers/MQTTPacketFilter.h"
@@ -28,6 +29,8 @@ MQTTPrefs defaults() {
prefs.alert_wifi_minutes = 30;
prefs.alert_mqtt_minutes = 240;
prefs.alert_min_interval_min = 60;
prefs.display_timeout_secs = DISPLAY_TIMEOUT_DEFAULT_SECS;
prefs.display_flip = 0;
return prefs;
}
@@ -237,6 +240,8 @@ TEST(MQTTPrefsCodec, CurrentVersionedPayloadRoundTripsExactly) {
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
source.mqtt_slot_packet_filter[i] = static_cast<uint16_t>(1u << i);
}
source.display_timeout_secs = 300;
source.display_flip = 1;
std::vector<uint8_t> bytes(Codec::kEncodedSize);
ASSERT_EQ(Codec::kEncodedSize, Codec::encode(source, bytes.data(), bytes.size()));
@@ -251,8 +256,8 @@ TEST(MQTTPrefsCodec, CurrentVersionedPayloadRoundTripsExactly) {
// /mqtt_prefs also carries the WiFi credentials, so a payload older firmware
// rejects strands a downgraded node with no network and no way to save. The
// filter tail is only written once it actually holds something.
TEST(MQTTPrefsCodec, DefaultFiltersKeepTheDowngradeReadablePayloadLength) {
// optional tails are written only once they actually hold something.
TEST(MQTTPrefsCodec, DefaultFiltersAndDisplayKeepTheDowngradeReadablePayloadLength) {
MQTTPrefs source = defaults();
strncpy(source.wifi_ssid, "home-net", sizeof(source.wifi_ssid) - 1);
strncpy(source.mqtt_slot_preset[0], "analyzer-us", sizeof(source.mqtt_slot_preset[0]) - 1);
@@ -292,12 +297,15 @@ TEST(MQTTPrefsCodec, AnyNonDefaultFilterOptsIntoTheLongerPayload) {
static_cast<uint16_t>(1u << 4),
static_cast<uint16_t>(MQTTPacketFilter::kAllPacketTypes & ~1u)}) {
source.mqtt_slot_packet_filter[slot] = mask;
ASSERT_EQ(Codec::kV1BaselinePayloadSize, Codec::payloadLenFor(source)) << slot;
ASSERT_EQ(Codec::kV1PreDisplayPayloadSize, Codec::payloadLenFor(source)) << slot;
std::vector<uint8_t> bytes(Codec::kEncodedSize);
ASSERT_EQ(Codec::kEncodedSize, Codec::encode(source, bytes.data(), bytes.size()));
const size_t written = Codec::encode(source, bytes.data(), bytes.size());
ASSERT_EQ(sizeof(MQTTPrefsHeader) + Codec::kV1PreDisplayPayloadSize,
written);
bytes.resize(written);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::kV1BaselinePayloadSize, plan.payload_len);
ASSERT_EQ(Codec::kV1PreDisplayPayloadSize, plan.payload_len);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
@@ -322,10 +330,71 @@ TEST(MQTTPrefsCodec, EncodeRefusesAnOutputBufferShorterThanItsChosenPayload) {
// A buffer that fits the short payload is not enough for the long one.
MQTTPrefs longest = defaults();
longest.mqtt_slot_packet_filter[0] = 0;
longest.display_flip = 1;
EXPECT_EQ(0u, Codec::encode(longest, bytes.data(), short_size));
EXPECT_EQ(Codec::kEncodedSize, Codec::encode(longest, bytes.data(), bytes.size()));
}
TEST(MQTTPrefsCodec, EitherNonDefaultDisplayControlOptsIntoTheFullTail) {
for (int scenario = 0; scenario < 2; ++scenario) {
MQTTPrefs source = defaults();
if (scenario == 0) {
source.display_timeout_secs = 0;
} else {
source.display_flip = 1;
}
ASSERT_EQ(Codec::kV1BaselinePayloadSize, Codec::payloadLenFor(source));
std::vector<uint8_t> bytes(Codec::kEncodedSize);
ASSERT_EQ(Codec::kEncodedSize,
Codec::encode(source, bytes.data(), bytes.size()));
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_EQ(Codec::kV1BaselinePayloadSize, plan.payload_len);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_EQ(source.display_timeout_secs, loaded.display_timeout_secs);
EXPECT_EQ(source.display_flip, loaded.display_flip);
}
}
TEST(MQTTPrefsCodec, PreDisplayPayloadPreservesFiltersAndDefaultsDisplayTail) {
MQTTPrefs source = defaults();
source.mqtt_slot_packet_filter[2] = 0;
source.display_timeout_secs = 900;
source.display_flip = 1;
std::vector<uint8_t> bytes(
sizeof(MQTTPrefsHeader) + Codec::kV1PreDisplayPayloadSize, 0);
writeHeader(&bytes, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1PreDisplayPayloadSize));
memcpy(bytes.data() + sizeof(MQTTPrefsHeader), &source,
Codec::kV1PreDisplayPayloadSize);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_EQ(Codec::kV1PreDisplayPayloadSize, plan.payload_len);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_EQ(0, loaded.mqtt_slot_packet_filter[2]);
EXPECT_EQ(DISPLAY_TIMEOUT_DEFAULT_SECS, loaded.display_timeout_secs);
EXPECT_EQ(0, loaded.display_flip);
}
TEST(MQTTPrefsCodec, RepairsInvalidDisplayTailValues) {
MQTTPrefs prefs = defaults();
EXPECT_FALSE(Codec::repairDisplayPrefs(&prefs));
EXPECT_FALSE(Codec::repairDisplayPrefs(nullptr));
prefs.display_timeout_secs = DISPLAY_TIMEOUT_MAX_SECS + 1;
prefs.display_flip = 7;
EXPECT_TRUE(Codec::repairDisplayPrefs(&prefs));
EXPECT_EQ(DISPLAY_TIMEOUT_DEFAULT_SECS, prefs.display_timeout_secs);
EXPECT_EQ(0, prefs.display_flip);
EXPECT_FALSE(Codec::repairDisplayPrefs(&prefs));
}
TEST(MQTTPrefsCodec, PreFilterV1PayloadDefaultsEverySlotToAllTypes) {
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "pre-filter-node", sizeof(source.mqtt_origin) - 1);
@@ -491,7 +560,9 @@ TEST(MQTTPrefsCodec, LegacyPlausibilityRejectsHighEntropyBytesAtEveryWhitelisted
TEST(MQTTPrefsCodec, UnsupportedHeaderlessSizesArePreserved) {
// 3024 was produced briefly before versioning, but repository history says
// that raw observer-tail form was not shipped. Preserve it rather than guess.
for (const size_t size : {size_t(471), size_t(473), size_t(1465), size_t(2905), size_t(3024)}) {
for (const size_t size : {size_t(471), size_t(473), size_t(1465),
size_t(2879), size_t(2880), size_t(2905),
size_t(3024)}) {
std::vector<uint8_t> bytes(size, 0);
const Codec::DecodePlan plan = classify(bytes);
EXPECT_EQ(Codec::Source::Corrupt, plan.source) << size;
@@ -525,6 +596,8 @@ TEST(MQTTPrefsCodec, LongerSameVersionPayloadLoadsTheBaselineAndIgnoresTheTail)
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
source.mqtt_slot_packet_filter[i] = static_cast<uint16_t>(1u << i);
}
source.display_timeout_secs = 120;
source.display_flip = 1;
// Baseline image plus a 40-byte tail of fields this build has never heard of.
const size_t kTail = 40;
@@ -551,6 +624,8 @@ TEST(MQTTPrefsCodec, LongerSameVersionPayloadLoadsTheBaselineAndIgnoresTheTail)
EXPECT_STREQ("meshrank", loaded.mqtt_slot_preset[0]);
EXPECT_EQ(1u, loaded.mqtt_neighbors_enabled);
EXPECT_EQ(1u, loaded.mqtt_slot_packet_filter[0]);
EXPECT_EQ(120, loaded.display_timeout_secs);
EXPECT_EQ(1, loaded.display_flip);
}
// The rule has to hold for any appended size, including a single byte and a
@@ -579,6 +654,23 @@ TEST(MQTTPrefsCodec, LongerDeclaredLengthWithoutTheBytesIsStillCorrupt) {
EXPECT_TRUE(plan.preserve_file);
}
TEST(CompanionMqttPrefsNvs, WritesRollbackReadableShapeAndAcceptsRecoveryShape) {
EXPECT_EQ(MQTT_PREFS_V1_PRE_DISPLAY_PAYLOAD_SIZE,
CompanionMqttPrefsNvs::kWriteSize);
EXPECT_LT(CompanionMqttPrefsNvs::kWriteSize, sizeof(MQTTPrefs));
EXPECT_TRUE(CompanionMqttPrefsNvs::accepts(
MQTT_PREFS_VERSION, CompanionMqttPrefsNvs::kWriteSize));
EXPECT_TRUE(CompanionMqttPrefsNvs::accepts(
MQTT_PREFS_VERSION, CompanionMqttPrefsNvs::kRecoverySize));
EXPECT_EQ(2880u, CompanionMqttPrefsNvs::kRecoverySize);
EXPECT_LE(CompanionMqttPrefsNvs::kRecoverySize, sizeof(MQTTPrefs));
EXPECT_FALSE(CompanionMqttPrefsNvs::accepts(
MQTT_PREFS_VERSION + 1, CompanionMqttPrefsNvs::kWriteSize));
EXPECT_FALSE(CompanionMqttPrefsNvs::accepts(
MQTT_PREFS_VERSION, CompanionMqttPrefsNvs::kWriteSize - 1));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
@@ -0,0 +1,371 @@
#include <gtest/gtest.h>
#include <cstring>
#include <string>
#include <vector>
#define WITH_MQTT_BRIDGE 1
#define PROGMEM
#include "helpers/MQTTPrefsAtomicStore.h"
#include "helpers/MQTTPrefsCodec.h"
#include "helpers/MQTTPrefsJsonImport.h"
namespace Import = MQTTPrefsJsonImport;
namespace Atomic = MQTTPrefsAtomicStore;
namespace {
class InputStream : public Stream {
public:
explicit InputStream(const std::string& text) : _text(text) {}
int available() override { return static_cast<int>(_text.size() - _pos); }
int read() override {
return _pos < _text.size()
? static_cast<unsigned char>(_text[_pos++]) : -1;
}
int peek() override {
return _pos < _text.size()
? static_cast<unsigned char>(_text[_pos]) : -1;
}
private:
std::string _text;
size_t _pos = 0;
};
bool validPreset(const char* preset) {
return strcmp(preset, "analyzer-us") == 0 ||
strcmp(preset, "analyzer-eu") == 0;
}
MQTTPrefs makeDefaults(uint8_t wifi_power_save = 1) {
MQTTPrefs prefs = {};
prefs.mqtt_status_enabled = 1;
prefs.mqtt_packets_enabled = 1;
prefs.mqtt_tx_enabled = 2;
prefs.mqtt_rx_enabled = 1;
prefs.mqtt_status_interval = 300000;
prefs.wifi_power_save = wifi_power_save;
prefs.timezone_offset = -7;
prefs.radio_watchdog_minutes = 5;
prefs.alert_wifi_minutes = 30;
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");
prefs.mqtt_slot_packet_filter[i] = 0xffff;
}
return prefs;
}
Import::Result decodeText(const std::string& text,
const MQTTPrefs& defaults,
MQTTPrefs* candidate) {
InputStream stream(text);
return Import::decode(stream, defaults, candidate, validPreset);
}
class CommitStore {
public:
explicit CommitStore(bool commit_ok) : _commit_ok(commit_ok) {
primary = {'o', 'l', 'd'};
}
bool begin() {
staging.clear();
open = true;
return true;
}
size_t write(const uint8_t* data, size_t size) {
if (!open) return 0;
staging.insert(staging.end(), data, data + size);
return size;
}
bool finish() {
open = false;
finished = true;
return true;
}
bool commit() {
if (!_commit_ok) return false;
primary = staging;
finished = false;
return true;
}
void abort() {
open = false;
if (!finished) staging.clear();
finished = false;
}
std::vector<uint8_t> primary;
std::vector<uint8_t> staging;
bool open = false;
bool finished = false;
private:
bool _commit_ok;
};
Atomic::Result commitPrefs(CommitStore* store, const MQTTPrefs& prefs) {
std::vector<uint8_t> encoded(MQTTPrefsCodec::kEncodedSize);
const size_t encoded_size =
MQTTPrefsCodec::encode(prefs, encoded.data(), encoded.size());
EXPECT_GT(encoded_size, sizeof(MQTTPrefsHeader));
return Atomic::write(
*store, encoded.data(), sizeof(MQTTPrefsHeader),
encoded.data() + sizeof(MQTTPrefsHeader),
encoded_size - sizeof(MQTTPrefsHeader));
}
} // namespace
TEST(MQTTPrefsJsonImport, BinaryAndRecoveryArtifactsAlwaysTakePrecedence) {
using D = Import::Decision;
EXPECT_EQ(D::BinaryAuthoritative,
Import::select(false, true, false, false, true, false, false));
EXPECT_EQ(D::BinaryAuthoritative,
Import::select(true, false, false, false, true, false, false));
EXPECT_EQ(D::BinaryAuthoritative,
Import::select(false, false, true, false, true, false, false));
EXPECT_EQ(D::BinaryAuthoritative,
Import::select(false, false, false, true, true, false, false));
EXPECT_EQ(D::BinaryAuthoritative,
Import::select(false, true, false, false, false, true, true));
}
TEST(MQTTPrefsJsonImport, ImportsOnlyCleanPrimaryAndHoldsJsonArtifacts) {
using D = Import::Decision;
EXPECT_EQ(D::ImportPrimary,
Import::select(false, false, false, false, true, false, false));
EXPECT_EQ(D::NoJsonSource,
Import::select(false, false, false, false, false, false, false));
EXPECT_EQ(D::HoldJsonArtifacts,
Import::select(false, false, false, false, true, true, false));
EXPECT_EQ(D::HoldJsonArtifacts,
Import::select(false, false, false, false, false, false, true));
}
TEST(MQTTPrefsJsonImport, DecodesEveryObserverGroupAndDisplayTail) {
const MQTTPrefs defaults = makeDefaults();
MQTTPrefs candidate = defaults;
const char* text =
"{version:1,"
"wifi:{ssid:\"mesh-net\",password:\"p\\\\\\\"ass\\nword\",power_save:2},"
"time:{timezone:\"MST7MDT\",utc_offset:-6,ntp_server:\"time.example\"},"
"mqtt:{origin:\"observer-one\",iata:\"sea\",packets_enabled:1,"
"raw_enabled:1,tx_enabled:1,rx_enabled:0,"
"status:{enabled:1,interval_ms:60000},"
"neighbors:{enabled:1,interval_ms:43200000},"
"owner:{public_key:\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\","
"email:\"owner@example.com\"},"
"slot1:{preset:\"analyzer-us\",host:\"broker.example\",port:1883,"
"username:\"user\",password:\"secret\",token:\"token\","
"topic:\"mesh/{iata}\",audience:\"aud\",packet_filter:32769},"
"slot6:{preset:\"custom\",host:\"six.example\",port:65535,"
"username:\"u6\",password:\"p6\",token:\"t6\",topic:\"six\","
"audience:\"a6\",packet_filter:0}},"
"snmp:{enabled:1,community:\"private\"},radio:{watchdog_min:120},"
"alert:{enabled:1,psk_hex:\"0123456789abcdef0123456789abcdef\","
"wifi_minutes:45,mqtt_minutes:300,rate_limit_min:90,"
"hashtag:\"#ops\",region:\"PNW\"},"
"display:{timeout_s:45,flip:1}}";
EXPECT_EQ(Import::Result::LoadedWithRepairs,
decodeText(text, defaults, &candidate));
EXPECT_STREQ("mesh-net", candidate.wifi_ssid);
EXPECT_STREQ("p\\\"ass\nword", candidate.wifi_password);
EXPECT_EQ(2, candidate.wifi_power_save);
EXPECT_EQ(-6, candidate.timezone_offset);
EXPECT_STREQ("time.example", candidate.mqtt_ntp_server);
EXPECT_STREQ("observer-one", candidate.mqtt_origin);
EXPECT_STREQ("SEA", candidate.mqtt_iata);
EXPECT_EQ(1, candidate.mqtt_raw_enabled);
EXPECT_EQ(0, candidate.mqtt_rx_enabled);
EXPECT_EQ(60000u, candidate.mqtt_status_interval);
EXPECT_EQ(MQTT_NEIGHBORS_MIN_INTERVAL_MS,
candidate.mqtt_neighbors_interval);
EXPECT_STREQ("analyzer-us", candidate.mqtt_slot_preset[0]);
EXPECT_EQ(1883, candidate.mqtt_slot_port[0]);
EXPECT_EQ(32769, candidate.mqtt_slot_packet_filter[0]);
EXPECT_STREQ("custom", candidate.mqtt_slot_preset[5]);
EXPECT_EQ(65535, candidate.mqtt_slot_port[5]);
EXPECT_EQ(0, candidate.mqtt_slot_packet_filter[5]);
EXPECT_EQ(1, candidate.snmp_enabled);
EXPECT_STREQ("private", candidate.snmp_community);
EXPECT_EQ(120, candidate.radio_watchdog_minutes);
EXPECT_EQ(1, candidate.alert_enabled);
EXPECT_STREQ("#ops", candidate.alert_hashtag);
EXPECT_EQ(45, candidate.display_timeout_secs);
EXPECT_EQ(1, candidate.display_flip);
}
TEST(MQTTPrefsJsonImport, MissingFieldsRetainCurrentBuildDefaults) {
MQTTPrefs defaults = makeDefaults(0);
strcpy(defaults.mqtt_iata, "PDX");
defaults.display_timeout_secs = 60;
MQTTPrefs candidate = defaults;
EXPECT_EQ(Import::Result::Loaded,
decodeText("{version:1,mqtt:{origin:\"changed\"},display:{}}",
defaults, &candidate));
EXPECT_STREQ("changed", candidate.mqtt_origin);
EXPECT_STREQ("PDX", candidate.mqtt_iata);
EXPECT_EQ(0, candidate.wifi_power_save);
EXPECT_EQ(300000u, candidate.mqtt_status_interval);
EXPECT_EQ(60, candidate.display_timeout_secs);
}
TEST(MQTTPrefsJsonImport, SemanticRepairsUseSchemaAndCurrentWifiDefaults) {
MQTTPrefs defaults = makeDefaults(0);
MQTTPrefs candidate = defaults;
const char* text =
"{version:1,wifi:{power_save:9},time:{utc_offset:99,ntp_server:\"bad/host\"},"
"mqtt:{iata:\"bad!\",packets_enabled:-1,raw_enabled:2,tx_enabled:9,"
"rx_enabled:2,status:{enabled:3,interval_ms:10},"
"neighbors:{enabled:2,interval_ms:100},"
"slot1:{preset:\"bogus\",port:-1,packet_filter:70000}},"
"snmp:{enabled:2},radio:{watchdog_min:121},"
"alert:{enabled:3,psk_hex:\"bad\",wifi_minutes:-1,mqtt_minutes:10081,"
"rate_limit_min:1,hashtag:\"#stale\"},"
"display:{timeout_s:99999,flip:7}}";
ASSERT_EQ(Import::Result::LoadedWithRepairs,
decodeText(text, defaults, &candidate));
EXPECT_EQ(0, candidate.wifi_power_save);
EXPECT_EQ(-7, candidate.timezone_offset);
EXPECT_STREQ("", candidate.mqtt_ntp_server);
EXPECT_STREQ("", candidate.mqtt_iata);
EXPECT_EQ(1, candidate.mqtt_packets_enabled);
EXPECT_EQ(0, candidate.mqtt_raw_enabled);
EXPECT_EQ(2, candidate.mqtt_tx_enabled);
EXPECT_EQ(1, candidate.mqtt_rx_enabled);
EXPECT_EQ(300000u, candidate.mqtt_status_interval);
EXPECT_EQ(MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS,
candidate.mqtt_neighbors_interval);
EXPECT_STREQ("none", candidate.mqtt_slot_preset[0]);
EXPECT_EQ(0, candidate.mqtt_slot_port[0]);
EXPECT_EQ(0xffff, candidate.mqtt_slot_packet_filter[0]);
EXPECT_EQ(0, candidate.snmp_enabled);
EXPECT_EQ(5, candidate.radio_watchdog_minutes);
EXPECT_EQ(0, candidate.alert_enabled);
EXPECT_STREQ("", candidate.alert_psk_hex);
EXPECT_STREQ("", candidate.alert_hashtag);
EXPECT_EQ(DISPLAY_TIMEOUT_DEFAULT_SECS, candidate.display_timeout_secs);
EXPECT_EQ(0, candidate.display_flip);
}
TEST(MQTTPrefsJsonImport, RejectsKnownTypeDuplicateLengthAndOverflowErrors) {
const MQTTPrefs defaults = makeDefaults();
for (const char* text : {
"{version:\"1\"}",
"{version:true}",
"{version:1.0}",
"{version:1,version:1}",
"{version:1,wifi:{ssid:\"one\"},wifi:{password:\"two\"}}",
"{version:1,wifi:{ssid:meshnet}}",
"{version:1,wifi:{ssid:\"12345678901234567890123456789012\"}}",
"{version:1,mqtt:{slot1:{port:999999999999}}}",
"{version:{x:1}}",
"{version:1,mqtt:1}",
"{version:1,mqtt:{slot1:1}}",
"{version:1,mqtt:{status:{enabled:1},status:{interval_ms:60000}}}"}) {
MQTTPrefs candidate = defaults;
EXPECT_FALSE(Import::loaded(decodeText(text, defaults, &candidate))) << text;
}
std::string embedded_nul = "{version:1,wifi:{ssid:\"before";
embedded_nul.push_back('\0');
embedded_nul += "after\"}}";
MQTTPrefs candidate = defaults;
EXPECT_EQ(Import::Result::InvalidSyntax,
decodeText(embedded_nul, defaults, &candidate));
}
TEST(MQTTPrefsJsonImport, RejectsTrailingMaterialAndMissingObjectSeparators) {
const MQTTPrefs defaults = makeDefaults();
for (const char* text : {
"{version:1}garbage",
"{version:1},",
"{version:1,}",
"{version:1,wifi:{ssid:\"x\",}}",
"{version:1,wifi:{} mqtt:{}}"}) {
MQTTPrefs candidate = defaults;
EXPECT_EQ(Import::Result::InvalidSyntax,
decodeText(text, defaults, &candidate)) << text;
}
MQTTPrefs candidate = defaults;
EXPECT_EQ(Import::Result::Loaded,
decodeText("{version:1,wifi:{}} \r\n\t", defaults, &candidate));
}
TEST(MQTTPrefsJsonImport, AcceptsSafelyParseableAppendOnlyUnknownFields) {
const MQTTPrefs defaults = makeDefaults();
MQTTPrefs candidate = defaults;
EXPECT_EQ(
Import::Result::Loaded,
decodeText(
"{version:1,display:{timeout_s:45},future:{thing:1,nested:{x:2}}}",
defaults, &candidate));
EXPECT_EQ(45, candidate.display_timeout_secs);
}
TEST(MQTTPrefsJsonImport, FutureVersionIsOpaqueEvenWithFutureGrammar) {
const MQTTPrefs defaults = makeDefaults();
MQTTPrefs candidate = defaults;
EXPECT_EQ(Import::Result::UnsupportedVersion,
decodeText("{version:2,future:[1]}", defaults, &candidate));
candidate = defaults;
EXPECT_EQ(Import::Result::InvalidSchema,
decodeText("{version:0}", defaults, &candidate));
candidate = defaults;
EXPECT_EQ(Import::Result::InvalidSchema,
decodeText("{wifi:{ssid:\"x\"}}", defaults, &candidate));
}
TEST(MQTTPrefsJsonImport, ParseFailureNeverTouchesLivePreferences) {
const MQTTPrefs defaults = makeDefaults();
MQTTPrefs live = defaults;
strcpy(live.wifi_ssid, "live-network");
MQTTPrefs scratch = defaults;
EXPECT_EQ(Import::Result::InvalidSyntax,
decodeText("{version:1,wifi:{ssid:\"uncommitted\"}",
defaults, &scratch));
EXPECT_STREQ("live-network", live.wifi_ssid);
}
TEST(MQTTPrefsJsonImport, ParsedDisplayPrefsRouteThroughFullAtomicBinaryCommit) {
const MQTTPrefs defaults = makeDefaults();
MQTTPrefs candidate = defaults;
ASSERT_EQ(Import::Result::Loaded,
decodeText("{version:1,display:{timeout_s:45,flip:1}}",
defaults, &candidate));
EXPECT_EQ(MQTT_PREFS_V1_FULL_PAYLOAD_SIZE,
MQTTPrefsCodec::payloadLenFor(candidate));
CommitStore store(true);
ASSERT_EQ(Atomic::Result::Committed, commitPrefs(&store, candidate));
ASSERT_EQ(sizeof(MQTTPrefsHeader) + MQTT_PREFS_V1_FULL_PAYLOAD_SIZE,
store.primary.size());
MQTTPrefsHeader header = {};
memcpy(&header, store.primary.data(), sizeof(header));
EXPECT_EQ(MQTT_PREFS_V1_FULL_PAYLOAD_SIZE, header.payload_len);
}
TEST(MQTTPrefsJsonImport, FailedAtomicPublishPreservesPreviousBinaryImage) {
const MQTTPrefs defaults = makeDefaults();
MQTTPrefs candidate = defaults;
ASSERT_EQ(Import::Result::Loaded,
decodeText("{version:1,wifi:{ssid:\"new\"}}",
defaults, &candidate));
CommitStore store(false);
const std::vector<uint8_t> old_primary = store.primary;
EXPECT_EQ(Atomic::Result::CommitFailed, commitPrefs(&store, candidate));
EXPECT_EQ(old_primary, store.primary);
EXPECT_FALSE(store.staging.empty());
}
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();
}
@@ -129,6 +129,48 @@ TEST(ValueFits, RejectsNullOrZeroBuffer) {
EXPECT_FALSE(mqttValueFits("abc", 0));
}
// ---- display CLI values --------------------------------------------------
TEST(DisplayTimeout, AcceptsOnlyCompleteBoundedDecimalValues) {
uint16_t value = 9999;
EXPECT_TRUE(observerParseBoundedUint16("0", 3600, &value));
EXPECT_EQ(0, value);
EXPECT_TRUE(observerParseBoundedUint16("60", 3600, &value));
EXPECT_EQ(60, value);
EXPECT_TRUE(observerParseBoundedUint16("3600", 3600, &value));
EXPECT_EQ(3600, value);
for (const char* invalid : {"", "3601", "-1", "+1", " 60", "60 ",
"60s", "99999999999999999999"}) {
value = 123;
EXPECT_FALSE(observerParseBoundedUint16(invalid, 3600, &value)) << invalid;
EXPECT_EQ(123, value) << invalid;
}
EXPECT_FALSE(observerParseBoundedUint16(nullptr, 3600, &value));
EXPECT_FALSE(observerParseBoundedUint16("60", 3600, nullptr));
}
TEST(DisplayFlip, AcceptsOnlyExactDocumentedTokens) {
uint8_t value = 7;
for (const char* off : {"0", "off"}) {
value = 7;
EXPECT_TRUE(observerParseDisplayFlip(off, &value));
EXPECT_EQ(0, value);
}
for (const char* on : {"1", "on"}) {
value = 7;
EXPECT_TRUE(observerParseDisplayFlip(on, &value));
EXPECT_EQ(1, value);
}
for (const char* invalid : {"", "2", "ON", "Off", "on ", "1x", "true"}) {
value = 7;
EXPECT_FALSE(observerParseDisplayFlip(invalid, &value)) << invalid;
EXPECT_EQ(7, value) << invalid;
}
EXPECT_FALSE(observerParseDisplayFlip(nullptr, &value));
EXPECT_FALSE(observerParseDisplayFlip("on", nullptr));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
@@ -0,0 +1,393 @@
#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, AGapLongerThanHalfTheMillisRangeStillExpiresTheRing) {
// Display off and no traffic for ~25 days: the elapsed time passes the signed
// halfway mark, which must not be mistaken for an out-of-order reading, or a
// month-old packet would still be sitting in the "last 20 minutes".
RadioActivityWindow w;
w.reset(0);
recordTypical(w, 1000);
ASSERT_EQ(1u, snapshotAt(w, 2000).packets);
const uint32_t twenty_five_days = 25UL * 24 * 3600 * 1000;
ASSERT_GT(twenty_five_days, 0x80000000u) << "gap must cross the halfway mark";
RadioActivitySnapshot s = snapshotAt(w, twenty_five_days);
EXPECT_TRUE(s.isEmpty());
EXPECT_FALSE(s.has_last_packet);
}
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,139 @@
#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, 200));
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, 200));
EXPECT_EQ(0, hold(d, now, false, 150)); // release long enough to be confirmed
EXPECT_EQ(0, hold(d, now, true, 200)) << "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, 200));
EXPECT_EQ(0, hold(d, now, false, 600)); // past the min gap
EXPECT_EQ(1, hold(d, now, true, 200));
}
TEST(TouchTapDetector, ASingleBadSampleDuringATouchDoesNotFakeARelease) {
// A NACK or short read reports "not pressed" for that poll. One of those must
// not confirm a release, or recovery reads as a second tap and the display
// toggles twice on one touch.
TouchTapDetector d;
uint32_t now = 1000;
d.reset(now);
EXPECT_EQ(1, hold(d, now, true, 200));
EXPECT_FALSE(d.update(now, false));
now += POLL;
EXPECT_TRUE(d.isTouched()) << "one bad sample must not confirm a release";
EXPECT_EQ(0, hold(d, now, true, 2000)) << "and must not produce a second tap";
}
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, 250)); // 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, 250));
}
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();
}