Add packed noise-floor telemetry history for both radio profiles

This commit is contained in:
mikecarper committed 2026-10-22 16:50:31 -07:00
1 parent 52a36c89dc
commit f4ade738df
32 files changed
+2520 -53

No files matched your search

+303
View File
@@ -0,0 +1,303 @@
#include <helpers/NoiseFloorHistory.h>
#include <assert.h>
#include <limits>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
using mesh::NoiseFloorHistory;
static constexpr uint32_t BASE = 1700000100UL;
static const uint8_t SOURCE[8] = {1, 2, 3, 4, 5, 6, 7, 8};
static uint32_t little32(const uint8_t* bytes) {
return (uint32_t)bytes[0] | ((uint32_t)bytes[1] << 8)
| ((uint32_t)bytes[2] << 16) | ((uint32_t)bytes[3] << 24);
}
static std::vector<uint8_t> decode(const char* reply) {
assert(strncmp(reply, "> ", 2) == 0);
const char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::vector<uint8_t> bytes;
const std::string text = reply + 2;
assert(text.size() % 4 == 0);
uint32_t accumulator = 0;
unsigned bits = 0;
bool padding = false;
for (char ch : text) {
if (ch == '=') { padding = true; continue; }
assert(!padding);
const char* found = strchr(alphabet, ch);
assert(found != nullptr);
accumulator = (accumulator << 6) | (uint32_t)(found - alphabet);
bits += 6;
if (bits >= 8) {
bits -= 8;
bytes.push_back((uint8_t)(accumulator >> bits));
}
}
assert(bits == 0 || (accumulator & ((1U << bits) - 1U)) == 0);
return bytes;
}
static uint8_t code(const uint8_t* packed, size_t index) {
const size_t byte = index * 5U / 8U;
const unsigned shift = (unsigned)(index * 5U % 8U);
const uint16_t word = (uint16_t)((uint16_t)packed[byte] << 8)
| (shift > 3 ? packed[byte + 1] : 0);
return (uint8_t)((word >> (11U - shift)) & 31U);
}
static void collect(NoiseFloorHistory& history, uint32_t start,
float a, float b, float c, uint8_t profile = 0) {
history.advance(start);
assert(history.observe(profile, start + 1, a, (start + 1) * 1000U));
assert(history.observe(profile, start + 301, b, (start + 301) * 1000U));
assert(history.observe(profile, start + 601, c, (start + 601) * 1000U));
}
static uint8_t single(float a, float b, float c) {
NoiseFloorHistory history;
collect(history, BASE, a, b, c);
assert(history.sampleCount(0) == 0);
history.advance(BASE + 900);
assert(history.sampleCount(0) == 1);
return history.sampleCodeAtOffset(0, 0);
}
static void selection() {
assert(single(-120, -90, -60) == 0); // Low wins across the entire range.
assert(single(-119, -80, -90) == 1);
assert(single(-118, -117, -116) == 2);
assert(single(-119.1f, -110, -100) == 0);
assert(single(-118.1f, -110, -100) == 1);
assert(single(-117, -110, -100) == 2);
assert(single(-101, -90, -80) == 10); // Minimum rounds down to -102.
assert(single(-100, -90, -70) == 11); // Threshold is inclusive.
assert(single(-91, -90, -89) == 16); // Middle averages to -90.
assert(single(-91, -90, -90) == 16); // Average rounds nearest, not down.
assert(single(-99, -90, -80) == 21); // Maximum threshold is inclusive.
assert(single(-90, -79, -85) == 22); // Maximum rounds up to -78.
assert(single(-100.01f, -60, -60) == 10);
assert(single(-130, -150, -121) == 0);
assert(single(-70, -65, -90) == 29); // -65 rounds up to -64.
assert(single(-70, -64, -90) == 29);
assert(single(-70, -63.99f, -90) == NoiseFloorHistory::MAX);
assert(single(-20, -70, -80) == NoiseFloorHistory::MAX);
}
static void freshness() {
NoiseFloorHistory history;
assert(!history.observe(0, BASE, -110, 1)); // advance establishes RTC.
history.advance(BASE);
assert(history.observe(0, BASE + 1, -120, 1));
assert(!history.observe(0, BASE + 301, -90, 1)); // Same calibration is stale.
assert(!history.observe(0, BASE + 2, std::numeric_limits<float>::quiet_NaN(), 2));
assert(!history.observe(0, BASE + 2, std::numeric_limits<float>::infinity(), 2));
assert(!history.observe(0, BASE + 2, -201, 2));
assert(!history.observe(0, BASE + 2, 1, 2));
assert(!history.observe(2, BASE + 2, -90, 2));
assert(!history.observe(0, BASE - 1, -90, 2));
assert(!history.observe(0, BASE + 900, -90, 2));
assert(history.observe(0, BASE + 2, -110, 2)); // Latest in one slot replaces.
assert(!history.observe(0, BASE + 1, -120, 3)); // Older publication ignored.
assert(history.observe(0, BASE + 301, -90, 3));
assert(history.observe(0, BASE + 601, -80, 4));
history.advance(BASE + 900);
assert(history.sampleCodeAtOffset(0, 0) == 6); // -110, not superseded -120.
assert(history.sampleCodeAtOffset(1, 0) == NoiseFloorHistory::MISSING);
assert(history.hasValidSamples(0));
assert(!history.hasValidSamples(1));
assert(!history.observe(0, BASE + 601, -80, 4));
assert(!history.observe(0, BASE + 901, -80, 4)); // Watermark crosses bucket.
assert(history.observe(0, BASE + 901, -80, 5));
assert(history.observe(0, BASE + 1501, -80, 6));
history.advance(BASE + 1800); // Two subslots cannot masquerade as three.
assert(history.sampleCodeAtOffset(0, 0) == NoiseFloorHistory::MISSING);
assert(history.sampleCodeAtOffset(0, 1) == 6);
NoiseFloorHistory wrapped;
wrapped.advance(BASE);
assert(wrapped.observe(0, BASE + 1, -110, 0xFFFFFFFEUL));
assert(wrapped.observe(0, BASE + 1, -110, 1));
assert(!wrapped.observe(0, BASE + 1, -120, 0xFFFFFFFDUL));
assert(wrapped.observe(0, BASE + 301, -110, 300001));
assert(wrapped.observe(0, BASE + 601, -110, 600001));
wrapped.advance(BASE + 900);
assert(wrapped.sampleCodeAtOffset(0, 0) == 6);
}
static void invalidation() {
NoiseFloorHistory history;
collect(history, BASE, -120, -119, -118);
collect(history, BASE, -70, -71, -72, 1);
history.invalidateProfile(0);
assert(!history.observe(0, BASE + 601, -118, (BASE + 601) * 1000U));
history.advance(BASE + 900);
assert(history.sampleCodeAtOffset(0, 0) == NoiseFloorHistory::MISSING);
assert(history.sampleCodeAtOffset(1, 0) == 26);
collect(history, BASE + 900, -119, -118, -117);
history.advance(BASE + 1800);
history.invalidateProfile(0);
history.invalidateProfile(255);
assert(history.sampleCodeAtOffset(0, 0) == 1); // Completed data retained.
assert(history.sampleCount(255) == 0);
assert(!history.hasValidSamples(255));
}
static void rollover() {
NoiseFloorHistory history;
assert(history.storageBytes() == 960);
for (unsigned i = 0; i < 800; ++i) {
collect(history, BASE + i * 900U, -120.0f + (float)(i % 3), -90, -85);
history.advance(BASE + (i + 1U) * 900U);
}
assert(history.sampleCount(0) == 768);
assert(history.sampleCount(1) == 768);
for (unsigned offset = 0; offset < 768; ++offset) {
assert(history.sampleCodeAtOffset(0, (uint16_t)offset) == (799 - offset) % 3);
assert(history.sampleCodeAtOffset(1, (uint16_t)offset) == NoiseFloorHistory::MISSING);
}
assert(history.sampleCodeAtOffset(0, 768) == NoiseFloorHistory::MISSING);
char reply[160];
assert(history.formatPageReply(0, "5", reply));
const auto bytes = decode(reply);
assert(bytes[6] == 64);
assert(little32(bytes.data() + 1) == BASE + 32U * 900U);
for (unsigned i = 0; i < 64; ++i) assert(code(bytes.data() + 7, i) == (32 + i) % 3);
}
static void clockChanges() {
NoiseFloorHistory history;
collect(history, BASE, -119, -90, -90);
history.advance(BASE + 3600);
assert(history.sampleCount(0) == 4);
assert(history.sampleCodeAtOffset(0, 3) == 1);
for (unsigned i = 0; i < 3; ++i) assert(history.sampleCodeAtOffset(0, i) == 31);
history.advance(BASE + 3599); // Current bucket moves backwards.
assert(history.sampleCount(0) == 0);
assert(!history.hasValidSamples(0));
collect(history, BASE + 2700, -118, -90, -90);
history.advance(BASE + 3600);
assert(history.sampleCodeAtOffset(0, 0) == 2);
history.advance(BASE + 3600 + (768U + 1U) * 900U);
assert(history.sampleCount(0) == 0); // Huge jump is bounded and starts fresh.
const uint32_t high = 0xFFFFFFFFUL / 900U * 900U;
history.advance(high);
assert(history.sampleCount(0) == 0);
history.advance(0);
assert(history.sampleCount(0) == 0);
assert(history.observe(0, 1, -120, 1));
assert(history.observe(0, 301, -120, 2));
assert(history.observe(0, 601, -120, 3));
history.advance(900);
char reply[160];
assert(history.formatPageReply(0, "", reply));
assert(little32(decode(reply).data() + 1) == 0);
}
static void wire() {
NoiseFloorHistory history;
struct Guarded { char before; char reply[160]; char after; } guard;
memset(&guard, 0x5A, sizeof(guard));
assert(!history.formatPageReply(0, "", guard.reply));
assert(strstr(guard.reply, "empty") != nullptr);
assert(!history.formatPageReply(0, "1", nullptr));
assert(!history.formatPageReply(0, "1", guard.reply, 0));
for (unsigned i = 0; i < 300; ++i) {
collect(history, BASE + i * 900U, -120.0f + (float)(i % 3), -90, -90);
collect(history, BASE + i * 900U, -65, -70, -90, 1);
history.advance(BASE + (i + 1U) * 900U);
}
assert(history.formatPageReply(0, " 1 ", guard.reply));
assert(strlen(guard.reply) == 158);
assert(guard.before == 0x5A && guard.after == 0x5A);
auto bytes = decode(guard.reply);
assert(bytes.size() == 117 && bytes[0] == 0x15);
assert(little32(bytes.data() + 1) == BASE + 124U * 900U);
assert(bytes[5] == 15 && bytes[6] == 176);
for (unsigned i = 0; i < 176; ++i) assert(code(bytes.data() + 7, i) == (124 + i) % 3);
assert(history.formatPageReply(1, "2", guard.reply));
bytes = decode(guard.reply);
assert(bytes[0] == 0x16 && bytes[6] == 124);
assert(little32(bytes.data() + 1) == BASE);
for (unsigned i = 0; i < 124; ++i) assert(code(bytes.data() + 7, i) == 29);
assert((bytes.back() & 0x0FU) == 0); // Four final packing bits are padding.
assert(!history.formatPageReply(0, "3", guard.reply));
for (const char* arg : {"0", "6", "-1", "1x", "1 2", "9999999999999999999999"}) {
assert(!history.formatPageReply(0, arg, guard.reply));
}
assert(!history.formatPageReply(2, "", guard.reply));
assert(!history.formatPageReply(0, "1", guard.reply, 158));
assert(history.formatPageReply(0, "1", guard.reply, 159));
assert(guard.before == 0x5A && guard.after == 0x5A);
struct Correlated { char before; char reply[160]; char after; } correlated;
memset(&correlated, 0x5A, sizeof(correlated));
memcpy(correlated.reply, "ab|", 3);
assert(history.formatPageReply(0, "1", correlated.reply + 3, 157, false));
assert(strlen(correlated.reply) == 159);
assert(memcmp(correlated.reply, "ab|", 3) == 0);
assert(strcmp(correlated.reply + 3, guard.reply + 2) == 0);
assert(decode((std::string("> ") + (correlated.reply + 3)).c_str()) == decode(guard.reply));
assert(correlated.before == 0x5A && correlated.after == 0x5A);
struct Bare { char before; char reply[157]; char after; } bare;
memset(&bare, 0x5A, sizeof(bare));
assert(history.formatPageReply(0, "1", bare.reply, sizeof(bare.reply), false));
assert(strlen(bare.reply) == 156 && strcmp(bare.reply, guard.reply + 2) == 0);
assert(!history.formatPageReply(0, "1", bare.reply, 156, false));
assert(strncmp(bare.reply, "Err", 3) == 0);
assert(bare.before == 0x5A && bare.after == 0x5A);
uint8_t raw[186];
memset(raw, 0xA5, sizeof(raw));
assert(history.formatBinarySnapshot(0, SOURCE, raw + 1, 184) == 179);
assert(memcmp(raw + 1, "N1B1", 4) == 0 && memcmp(raw + 5, SOURCE, 8) == 0);
assert(little32(raw + 13) == BASE + 45U * 900U);
assert(raw[17] == 15 && raw[18] == 0 && raw[19] == 255);
for (unsigned i = 0; i < 255; ++i) assert(code(raw + 20, i) == (45 + i) % 3);
assert((raw[179] & 0x1FU) == 0); // 255*5 leaves five padding bits.
assert(raw[0] == 0xA5 && raw[180] == 0xA5 && raw[185] == 0xA5);
assert(history.formatBinarySnapshot(1, SOURCE, raw + 1, 20) == 20);
assert(memcmp(raw + 1, "N2B1", 4) == 0 && raw[19] == 1);
assert(code(raw + 20, 0) == 29);
assert(little32(raw + 13) == BASE + 299U * 900U);
assert(history.formatBinarySnapshot(0, SOURCE, raw, 19) == 0);
assert(history.formatBinarySnapshot(2, SOURCE, raw, sizeof(raw)) == 0);
assert(history.formatBinarySnapshot(0, nullptr, raw, sizeof(raw)) == 0);
assert(history.formatBinarySnapshot(0, SOURCE, nullptr, sizeof(raw)) == 0);
// Missing is an explicit usable code, including disabled-profile history.
NoiseFloorHistory missing;
missing.advance(BASE);
missing.advance(BASE + 900);
assert(missing.formatBinarySnapshot(1, SOURCE, raw, sizeof(raw)) == 20);
assert(raw[18] == 1 && code(raw + 19, 0) == 31);
assert(missing.formatPageReply(1, "", guard.reply));
bytes = decode(guard.reply);
assert(bytes.size() == 8 && code(bytes.data() + 7, 0) == 31);
assert(strchr(guard.reply, '=') != nullptr); // Standard padded Base64.
// Independent MSB-first wire vector: eight five-bit codes 0..7.
NoiseFloorHistory golden;
const float levels[] = {-120, -119, -118, -116, -114, -112, -110, -108};
for (unsigned i = 0; i < 8; ++i) {
collect(golden, BASE + i * 900U, levels[i], levels[i], levels[i]);
golden.advance(BASE + (i + 1U) * 900U);
}
assert(golden.formatBinarySnapshot(0, SOURCE, raw, sizeof(raw)) == 24);
const uint8_t expected[] = {0x00, 0x44, 0x32, 0x14, 0xC7};
assert(memcmp(raw + 19, expected, sizeof(expected)) == 0);
}
int main(int argc, char** argv) {
assert(argc == 2);
const std::string scenario(argv[1]);
if (scenario == "selection") selection();
else if (scenario == "freshness") freshness();
else if (scenario == "invalidation") invalidation();
else if (scenario == "rollover") rollover();
else if (scenario == "clock") clockChanges();
else if (scenario == "wire") wire();
else return 2;
puts("noise floor history: ok");
}
+297
View File
@@ -0,0 +1,297 @@
#include <helpers/NoiseFloorHistorySampler.h>
#include <assert.h>
#include <limits>
#include <stdio.h>
#include <string>
using mesh::NoiseFloorHistory;
using mesh::NoiseFloorHistorySampler;
static constexpr uint32_t BASE = 1700000100UL;
static constexpr uint32_t MILLIS_BASE = 100000;
struct FakeProfiles {
uint32_t generation[2] = {};
bool second = false;
bool enabled() const { return second; }
};
struct FakeRadio {
FakeProfiles config;
bool has_profiles = true;
bool valid[2] = {};
float dbm[2] = {};
uint32_t published[2] = {};
unsigned requests = 0;
unsigned reads[2] = {};
unsigned hardware_operations = 0;
const FakeProfiles* profiles() const { return has_profiles ? &config : nullptr; }
bool getNoiseFloorReading(uint8_t profile, float& floor, uint32_t& publication) {
assert(profile < 2);
++reads[profile];
if (!valid[profile]) return false;
floor = dbm[profile];
publication = published[profile];
return true;
}
void requestNoiseFloorMeasurement() { ++requests; }
void publish(uint8_t profile, uint32_t now_ms, float floor) {
assert(profile < 2);
valid[profile] = true;
dbm[profile] = floor;
published[profile] = now_ms;
}
};
static uint32_t ms(unsigned seconds) { return MILLIS_BASE + seconds * 1000UL; }
static void successful() {
FakeRadio radio;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
sampler.poll(radio, history, BASE, ms(0));
assert(radio.requests == 1);
for (unsigned offset : {4U, 304U, 604U}) {
if (offset != 4) {
sampler.poll(radio, history, BASE + offset - 4U, ms(offset - 4U));
}
radio.publish(0, ms(offset), offset == 4 ? -120 : offset == 304 ? -90 : -60);
sampler.poll(radio, history, BASE + offset, ms(offset));
const unsigned requests = radio.requests;
for (unsigned i = offset; i < offset + 10; ++i) {
sampler.poll(radio, history, BASE + i, ms(i));
}
assert(radio.requests == requests);
}
assert(radio.requests == 3 && history.sampleCount(0) == 0);
sampler.poll(radio, history, BASE + 900, ms(900));
assert(radio.requests == 4);
assert(history.sampleCount(0) == 1 && history.sampleCodeAtOffset(0, 0) == 0);
assert(history.sampleCodeAtOffset(1, 0) == 31);
assert(radio.reads[1] == 0 && radio.hardware_operations == 0);
}
static void cached() {
FakeRadio radio;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
radio.publish(0, ms(0), -110);
sampler.poll(radio, history, BASE, ms(0));
assert(radio.requests == 0);
// A recent cached result may be read repeatedly, but is one publication.
for (unsigned i = 1; i < 300; ++i) sampler.poll(radio, history, BASE + i, ms(i));
assert(radio.requests == 0);
sampler.poll(radio, history, BASE + 300, ms(300));
assert(radio.requests == 1);
for (unsigned i = 301; i < 600; ++i) sampler.poll(radio, history, BASE + i, ms(i));
assert(radio.requests == 1);
sampler.poll(radio, history, BASE + 600, ms(600));
assert(radio.requests == 2);
sampler.poll(radio, history, BASE + 900, ms(900));
assert(history.sampleCount(0) == 1 && history.sampleCodeAtOffset(0, 0) == 31);
assert(!history.hasValidSamples(0));
// Calibration completed just before a subslot boundary still belongs to
// that earlier subslot; it must not suppress the next measurement request.
NoiseFloorHistory second_history;
NoiseFloorHistorySampler second_sampler;
FakeRadio second;
second.publish(0, ms(299), -100);
second_sampler.poll(second, second_history, BASE + 300, ms(300));
assert(second.requests == 1);
}
static void rollover() {
for (uint32_t first_ms : {0UL, 0xFFFFF000UL}) {
FakeRadio radio;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
for (unsigned offset : {0U, 300U, 600U}) {
const uint32_t now = first_ms + offset * 1000UL;
radio.publish(0, now, -119);
sampler.poll(radio, history, BASE + offset, now);
}
assert(radio.requests == 0);
sampler.poll(radio, history, BASE + 900, first_ms + 900000UL);
assert(history.sampleCount(0) == 1 && history.sampleCodeAtOffset(0, 0) == 1);
assert(radio.requests == 1);
}
}
static void generations() {
FakeRadio radio;
radio.config.second = true;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
for (unsigned offset : {0U, 300U, 600U}) {
if (offset == 600) ++radio.config.generation[0];
radio.publish(0, ms(offset), -120);
radio.publish(1, ms(offset), -70);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
sampler.poll(radio, history, BASE + 900, ms(900));
assert(history.sampleCodeAtOffset(0, 0) == 31); // Pre-retune estimates discarded.
assert(history.sampleCodeAtOffset(1, 0) == 26);
for (unsigned offset : {904U, 1204U, 1504U}) {
radio.publish(0, ms(offset), -118);
radio.publish(1, ms(offset), -70);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
sampler.poll(radio, history, BASE + 1800, ms(1800));
assert(history.sampleCodeAtOffset(0, 0) == 2);
assert(history.sampleCodeAtOffset(1, 0) == 26);
// A fresh-reading API becoming invalid clears accumulated estimates even
// if generation is unchanged (gain/AGC recalibration).
for (unsigned offset : {1804U, 2104U}) {
radio.publish(0, ms(offset), -118);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
radio.valid[0] = false;
sampler.poll(radio, history, BASE + 2105, ms(2105));
radio.publish(0, ms(2404), -118);
sampler.poll(radio, history, BASE + 2404, ms(2404));
sampler.poll(radio, history, BASE + 2700, ms(2700));
assert(history.sampleCodeAtOffset(0, 0) == 31);
assert(history.sampleCodeAtOffset(0, 1) == 2); // Completed data stays intact.
}
static void enableDisable() {
FakeRadio radio;
radio.config.second = true;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
for (unsigned offset : {0U, 300U, 600U}) {
if (offset == 300) radio.config.second = false;
if (offset == 600) radio.config.second = true;
radio.publish(0, ms(offset), -119);
radio.publish(1, ms(offset), -70);
const unsigned secondary_reads = radio.reads[1];
sampler.poll(radio, history, BASE + offset, ms(offset));
if (offset == 300) assert(radio.reads[1] == secondary_reads);
}
sampler.poll(radio, history, BASE + 900, ms(900));
assert(history.sampleCodeAtOffset(0, 0) == 1);
assert(history.sampleCodeAtOffset(1, 0) == 31); // No mixing across enablement.
for (unsigned offset : {904U, 1204U, 1504U}) {
radio.publish(0, ms(offset), -119);
radio.publish(1, ms(offset), -70);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
sampler.poll(radio, history, BASE + 1800, ms(1800));
assert(history.sampleCodeAtOffset(1, 0) == 26);
radio.config.second = false;
sampler.poll(radio, history, BASE + 1801, ms(1801));
assert(history.sampleCodeAtOffset(1, 0) == 26); // Disabling retains old history.
}
static void clockChanges() {
FakeRadio radio;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
for (unsigned offset : {0U, 300U, 600U}) {
radio.publish(0, ms(offset), -118);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
radio.valid[0] = false;
sampler.poll(radio, history, BASE + 3600, ms(601));
assert(history.sampleCount(0) == 4);
assert(history.sampleCodeAtOffset(0, 3) == 2);
assert(history.sampleCodeAtOffset(0, 0) == 31);
sampler.poll(radio, history, BASE + 1800, ms(602));
assert(history.sampleCount(0) == 0);
for (unsigned offset : {0U, 300U, 600U}) {
radio.publish(0, ms(603 + offset), -119);
sampler.poll(radio, history, BASE + 1800 + offset, ms(603 + offset));
}
sampler.poll(radio, history, BASE + 2700, ms(1503));
assert(history.sampleCount(0) == 1 && history.sampleCodeAtOffset(0, 0) == 1);
sampler.poll(radio, history, BASE + 2700 + 769U * 900U, ms(1504));
assert(history.sampleCount(0) == 0);
}
static void unsupportedAndFresh() {
FakeRadio unsupported;
unsupported.has_profiles = false;
NoiseFloorHistory empty;
NoiseFloorHistorySampler no_hardware;
for (unsigned offset : {0U, 300U, 600U, 900U}) {
no_hardware.poll(unsupported, empty, BASE + offset, ms(offset));
}
assert(unsupported.requests == 4 && unsupported.reads[1] == 0);
assert(unsupported.hardware_operations == 0);
assert(empty.sampleCount(0) == 1 && !empty.hasValidSamples(0));
assert(!empty.hasValidSamples(1));
FakeRadio both;
both.config.second = true;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
for (unsigned offset : {0U, 300U, 600U, 900U}) {
both.publish(0, ms(offset), -119);
both.publish(1, ms(offset), -70);
sampler.poll(both, history, BASE + offset, ms(offset));
}
assert(both.requests == 0 && both.hardware_operations == 0);
assert(history.sampleCodeAtOffset(0, 0) == 1 && history.sampleCodeAtOffset(1, 0) == 26);
both.publish(0, ms(1200), -119);
sampler.poll(both, history, BASE + 1200, ms(1200));
assert(both.requests == 1); // Primary is fresh; secondary still needs a reading.
}
static void invalidReadings() {
const float invalid[] = {
std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity(), -200.01f, 0.01f
};
for (float value : invalid) {
FakeRadio radio;
radio.config.second = true;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
for (unsigned offset : {0U, 300U, 600U}) {
radio.publish(0, ms(offset), value);
radio.publish(1, ms(offset), -118);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
assert(radio.requests == 3); // Invalid values never suppress a request.
sampler.poll(radio, history, BASE + 900, ms(900));
assert(history.sampleCodeAtOffset(0, 0) == 31);
assert(history.sampleCodeAtOffset(1, 0) == 2);
}
// Invalid data appearing after a valid estimate clears that pending profile,
// rather than retaining a partial calibration across the invalid interval.
FakeRadio radio;
NoiseFloorHistory history;
NoiseFloorHistorySampler sampler;
radio.publish(0, ms(0), -120);
sampler.poll(radio, history, BASE, ms(0));
radio.publish(0, ms(1), invalid[0]);
sampler.poll(radio, history, BASE + 1, ms(1));
for (unsigned offset : {300U, 600U}) {
radio.publish(0, ms(offset), -120);
sampler.poll(radio, history, BASE + offset, ms(offset));
}
sampler.poll(radio, history, BASE + 900, ms(900));
assert(history.sampleCodeAtOffset(0, 0) == 31);
}
int main(int argc, char** argv) {
assert(argc == 2);
const std::string scenario(argv[1]);
if (scenario == "successful") successful();
else if (scenario == "cached") cached();
else if (scenario == "rollover") rollover();
else if (scenario == "generations") generations();
else if (scenario == "enable_disable") enableDisable();
else if (scenario == "clock") clockChanges();
else if (scenario == "unsupported_fresh") unsupportedAndFresh();
else if (scenario == "invalid") invalidReadings();
else return 2;
puts("noise floor sampler: ok");
}
+141
View File
@@ -10,6 +10,7 @@
#endif
#include <helpers/TelemetryHistory.h>
#include <helpers/ExternalVoltageHistory.h>
#include <helpers/NoiseFloorHistory.h>
#include <array>
#include <cassert>
#include <cstdio>
@@ -81,6 +82,9 @@ public:
struct Identity { uint8_t pub_key[32] = {}; } self_id;
mesh::TelemetryHistory telemetry_history;
mesh::ExternalVoltageHistory external_voltage_history;
mesh::NoiseFloorHistory noise_floor_history;
bool dual = false;
bool isDualRadioActive() const { return dual; }
bool telemetry_history_tx_prefs_healthy = false;
bool telemetry_history_tx_enabled = false;
uint8_t telemetry_history_tx_interval_days = 2;
@@ -93,12 +97,16 @@ public:
uint64_t uptime_millis = 0;
uint32_t last_millis = 0;
std::vector<mesh::Packet> packets;
std::vector<std::string> attempts;
std::string reject_magic;
unsigned rejected_sends = 0;
explicit MyMesh(FILESYSTEM& fs) : _fs(&fs) {}
void loadTelemetryHistoryTxPrefs();
bool saveTelemetryHistoryTxPrefs();
void serviceTelemetryHistoryTx();
bool sendTelemetryHistorySnapshot(mesh::TelemetryHistory::Series);
bool sendExternalVoltageHistorySnapshot(uint8_t, uint8_t);
bool sendNoiseFloorHistorySnapshot(uint8_t);
void formatTelemetryHistoryTxStatus(char*, size_t) const;
void handle(char*, char*, ClientInfo*);
// Radio queue boundary. Payload formatting and producer scheduling are real.
@@ -109,6 +117,11 @@ public:
return packet;
}
bool sendDirect(mesh::Packet* packet, const uint8_t* path, uint8_t length) {
const std::string magic(reinterpret_cast<char*>(packet->payload), 4);
attempts.push_back(magic);
if (magic == reject_magic && rejected_sends != 0) {
--rejected_sends; delete packet; return false;
}
packet->path_len = mesh::Packet::copyPath(packet->path, path, length);
packets.push_back(*packet); delete packet; return true;
}
@@ -163,6 +176,22 @@ struct Fixture {
node.telemetry_history.record(1000000 + i * 1800, 22, true, 3750, 0, 0, false);
}
}
void noiseHistory(uint16_t count = 300, bool missing = false) {
const uint32_t start = 999900;
node.noise_floor_history.advance(start);
for (uint32_t index = 0; index < count; ++index) {
for (uint8_t profile = 0; profile < 2; ++profile) {
for (uint8_t slot = 0; slot < 3; ++slot) {
if (missing) continue;
assert(node.noise_floor_history.observe(profile,
start + index * 900 + slot * 300, profile ? -66.0f : -119.0f,
index * 3 + slot));
}
}
node.noise_floor_history.advance(start + (index + 1) * 900);
}
assert(node.noise_floor_history.sampleCount(0) == count);
}
void expectFault() {
assert(!node.telemetry_history_tx_prefs_healthy);
const auto before = node.state();
@@ -531,6 +560,116 @@ static void checkRouteReadbackAndRetry() {
#endif
}
static uint32_t read32(const uint8_t* bytes) {
return uint32_t(bytes[0]) | uint32_t(bytes[1]) << 8
| uint32_t(bytes[2]) << 16 | uint32_t(bytes[3]) << 24;
}
static uint8_t packedNoiseCode(const mesh::Packet& packet, unsigned index) {
uint8_t value = 0;
for (unsigned bit = 0; bit < 5; ++bit) {
const unsigned at = index * 5 + bit;
value = uint8_t((value << 1)
| ((packet.payload[19 + at / 8] >> (7 - at % 8)) & 1));
}
return value;
}
static void verifyNoisePacket(const MyMesh& node, const mesh::Packet& packet,
unsigned profile, bool missing) {
assert(packet.payload_len == 19 + (255 * 5 + 7) / 8);
assert(!memcmp(packet.payload, profile ? "N2B1" : "N1B1", 4));
assert(!memcmp(packet.payload + 4, node.self_id.pub_key, 8));
assert(read32(packet.payload + 12) == 999900 + (300 - 255) * 900);
assert(packet.payload[16] == 15 && packet.payload[17] == 0);
assert(packet.payload[18] == 255);
for (unsigned i = 0; i < 255; ++i) {
assert(packedNoiseCode(packet, i) == (missing ? 31 : profile ? 28 : 1));
}
assert((packet.payload[packet.payload_len - 1] & 0x1f) == 0);
}
static void serviceDue(MyMesh& node) {
node.uptime_millis = node.telemetry_history_next_tx_uptime;
node.last_millis = test_millis;
node.serviceTelemetryHistoryTx();
}
static void finishPending(MyMesh& node) {
unsigned calls = 0;
while (node.telemetry_history_tx_pending != 0) {
assert(++calls < 20);
serviceDue(node);
}
}
static void checkNoiseHistoryTransmission() {
for (const bool manual : {false, true}) {
for (const bool dual : {false, true}) {
for (const bool missing : {false, true}) {
Fixture f; f.seed(current(!manual, 2)); f.history(); f.noiseHistory(300, missing);
f.node.dual = dual;
for (unsigned i = 0; i < 8; ++i) f.node.self_id.pub_key[i] = uint8_t(0x80 + i);
if (manual) {
const auto reply = f.node.command("send telemetry.tx now");
assert(reply.find(dual ? "noise=1/1" : "noise=1/0") != std::string::npos);
assert(f.node.telemetry_history_tx_pending == (dual ? 27 : 11));
assert(f.node.packets.empty());
} else {
f.node.serviceTelemetryHistoryTx();
assert(f.node.packets.size() == 1);
}
finishPending(f.node);
assert(f.node.packets.size() == (dual ? 4U : 3U));
assert(f.node.attempts.size() == f.node.packets.size());
assert(!memcmp(f.node.packets[0].payload, "TTB1", 4));
assert(!memcmp(f.node.packets[1].payload, "TVB1", 4));
verifyNoisePacket(f.node, f.node.packets[2], 0, missing);
if (dual) verifyNoisePacket(f.node, f.node.packets[3], 1, missing);
assert(!f.node.telemetry_history_tx_manual);
assert(bool(f.node.telemetry_history_next_tx_uptime) == !manual);
}
}
}
}
static void checkNoiseHistoryRetries() {
for (const bool second : {false, true}) {
Fixture f; f.seed(current(false, 2)); f.history(); f.noiseHistory();
f.node.dual = true;
f.node.reject_magic = second ? "N2B1" : "N1B1";
f.node.rejected_sends = 1;
assert(f.node.command("send telemetry.tx now").find("noise=1/1") != std::string::npos);
while (f.node.rejected_sends != 0) serviceDue(f.node);
const auto attempts = f.node.attempts;
const uint64_t retry = f.node.telemetry_history_next_tx_uptime;
assert(retry == f.node.uptime_millis + TELEMETRY_HISTORY_TX_RETRY_MILLIS);
assert(f.node.telemetry_history_tx_pending == (second ? 16 : 24));
f.node.uptime_millis = retry - 1;
f.node.serviceTelemetryHistoryTx();
assert(f.node.attempts == attempts); // failed packet waits for its retry deadline
finishPending(f.node);
const std::vector<std::string> expected = second
? std::vector<std::string>{"TTB1", "TVB1", "N1B1", "N2B1", "N2B1"}
: std::vector<std::string>{"TTB1", "TVB1", "N1B1", "N1B1", "N2B1"};
assert(f.node.attempts == expected);
assert(f.node.packets.size() == 4); // successful earlier packets were never resent
assert(!f.node.telemetry_history_next_tx_uptime && !f.node.telemetry_history_tx_manual);
}
Fixture disabled; disabled.seed(current(false, 2));
disabled.history(); disabled.noiseHistory(); disabled.node.dual = true;
disabled.node.reject_magic = "N2B1"; disabled.node.rejected_sends = 1;
assert(disabled.node.command("send telemetry.tx now").find("noise=1/1") != std::string::npos);
while (disabled.node.rejected_sends != 0) serviceDue(disabled.node);
assert(disabled.node.telemetry_history_tx_pending == TELEMETRY_HISTORY_TX_NOISE2);
const auto attempts = disabled.node.attempts;
disabled.node.dual = false;
serviceDue(disabled.node);
assert(!disabled.node.telemetry_history_tx_pending && disabled.node.attempts == attempts);
assert(!disabled.node.telemetry_history_next_tx_uptime && !disabled.node.telemetry_history_tx_manual);
assert(disabled.node.packets.size() == 3);
}
int main() {
checkFreshAndValid();
checkLoadFailures();
@@ -540,5 +679,7 @@ int main() {
checkAmbiguousPublicationAndServiceGate();
checkRoutePublicationAuthority();
checkRouteReadbackAndRetry();
checkNoiseHistoryTransmission();
checkNoiseHistoryRetries();
puts("telemetry persistence checks passed");
}
+204
View File
@@ -0,0 +1,204 @@
"""Run real noise CLI dispatch, prefix handling, and room/repeater permission gates."""
from pathlib import Path
import os
import re
import shutil
import subprocess
import tempfile
import unittest
from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <cassert>
#include <cstring>
#include <string>
#include <vector>
#include <helpers/NoiseFloorHistory.h>
#include <helpers/TelemetryHistory.h>
#include <helpers/ExternalVoltageHistory.h>
struct ClientInfo { bool admin=true; bool isAdmin() const { return admin; } };
class Repeater {
public:
mesh::NoiseFloorHistory noise_floor_history;
void handleCommand(char* command,char* reply,ClientInfo* sender) {
@REPEATER_PREFIX@
@REPEATER_NOISE@
strcpy(reply,"Err - unrecognized command");
}
};
class MyMesh {
public:
mesh::NoiseFloorHistory noise_floor_history;
mesh::TelemetryHistory telemetry_history;
mesh::ExternalVoltageHistory external_voltage_history;
bool handleTelemetryHistoryCommand(const char*,char*,size_t=160,bool=true);
void handleCommand(uint32_t sender_timestamp,char* command,char* reply,
int client_index=-1,uint8_t path_hash_size=1) {
(void)sender_timestamp; (void)client_index; (void)path_hash_size;
@ROOM_PREFIX@
@ROOM_DISPATCH@
strcpy(reply,"Err - unrecognized command");
}
void remote(ClientInfo* client,char* text,char* reply) {
uint8_t temp[165]={};
const uint32_t sender_timestamp=100;
const int i=0;
struct Packet {uint8_t getPathHashSize() const {return 1;}} real_packet;
Packet* packet=&real_packet;
@ROOM_GATE@
strcpy(reply,reinterpret_cast<char*>(&temp[5]));
}
};
@ROOM_HISTORY@
static void seed(mesh::NoiseFloorHistory& history) {
history.advance(999900);
for (uint32_t bucket=0;bucket<176;++bucket) {
for (uint8_t profile=0;profile<2;++profile) for (uint8_t slot=0;slot<3;++slot) {
assert(history.observe(profile,999900+bucket*900+slot*300,
profile ? -66.0f : -119.0f,bucket*3+slot));
}
history.advance(999900+(bucket+1)*900);
}
}
static std::vector<uint8_t> decode(const char* text) {
const char* alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::vector<uint8_t> result;
uint32_t bits=0;unsigned count=0;
for (;*text && *text!='=';++text) {
const char* found=strchr(alphabet,*text);assert(found);
bits=(bits<<6)|uint32_t(found-alphabet);count+=6;
if (count>=8) {count-=8;result.push_back(uint8_t(bits>>count));}
}
return result;
}
static void verify(const char* reply,unsigned profile,bool prefix) {
assert(strlen(reply)==(prefix ? 159U : 158U));
assert(!memcmp(reply,prefix ? "xy|" : "> ",prefix ? 3 : 2));
const auto bytes=decode(reply+(prefix ? 3 : 2));
assert(bytes.size()==7+110 && bytes[0]==(profile ? 0x16 : 0x15));
assert(bytes[1]==uint8_t(999900) && bytes[2]==uint8_t(999900>>8)
&& bytes[3]==uint8_t(999900>>16) && bytes[4]==uint8_t(999900>>24));
assert(bytes[5]==15 && bytes[6]==176);
for (unsigned sample=0;sample<176;++sample) {
uint8_t code=0;
for (unsigned bit=0;bit<5;++bit) {
const unsigned at=sample*5+bit;
code=uint8_t((code<<1)|((bytes[7+at/8]>>(7-at%8))&1));
}
assert(code==(profile ? 28 : 1));
}
}
template<class Invoke> static void bounded(const std::string& text,Invoke invoke,
bool success,unsigned profile,bool prefix) {
std::vector<char> storage(176,'~');
std::vector<char> command(text.begin(),text.end());command.push_back(0);
invoke(command.data(),storage.data()+8);
for (unsigned i=0;i<8;++i) assert(storage[i]=='~' && storage[168+i]=='~');
assert(memchr(storage.data()+8,0,160));
if (success) verify(storage.data()+8,profile,prefix);
else assert(strstr(storage.data()+8,"Err - "));
}
int main() {
Repeater repeater;MyMesh room;
seed(repeater.noise_floor_history);seed(room.noise_floor_history);
ClientInfo admin,denied;denied.admin=false;
for (unsigned profile:{0U,1U}) for (bool prefix:{false,true}) {
const std::string text=std::string(prefix ? "xy|" : "")
+(profile ? "get telemetry.noise2" : "get telemetry.noise");
for (const std::string& suffix:{std::string(),std::string(" 1")}) {
bounded(text+suffix,[&](char* command,char* reply) {
repeater.handleCommand(command,reply,nullptr);
},true,profile,prefix);
bounded(text+suffix,[&](char* command,char* reply) {
repeater.handleCommand(command,reply,&admin);
},true,profile,prefix);
bounded(text+suffix,[&](char* command,char* reply) {
room.handleCommand(0,command,reply);
},true,profile,prefix);
bounded(text+suffix,[&](char* command,char* reply) {
room.remote(&admin,command,reply);
},true,profile,prefix);
bounded(text+suffix,[&](char* command,char* reply) {
repeater.handleCommand(command,reply,&denied);
},false,profile,prefix);
bounded(text+suffix,[&](char* command,char* reply) {
room.remote(&denied,command,reply);
},false,profile,prefix);
}
}
for (const char* bad:{"get telemetry.noisefake","get telemetry.noise2fake",
"get telemetry.noise 0","get telemetry.noise2 6"}) {
bounded(std::string("xy|")+bad,[&](char* command,char* reply) {
repeater.handleCommand(command,reply,&admin);
},false,0,true);
bounded(std::string("xy|")+bad,[&](char* command,char* reply) {
room.remote(&admin,command,reply);
},false,0,true);
}
puts("noise CLI prefix, permission and payload checks passed");
}
'''
class NoiseFloorCLITests(unittest.TestCase):
def test_actual_prefix_dispatch_permissions_and_full_pages_fit_160_bytes(self):
repeater = (ROOT / "examples/simple_repeater/MyMesh.cpp").read_text()
room = (ROOT / "examples/simple_room_server/MyMesh.cpp").read_text()
repeater_handler = extract_braced(repeater, "void MyMesh::handleCommand(uint32_t sender_timestamp,")
room_handler = extract_braced(room, "void MyMesh::handleCommand(uint32_t sender_timestamp,")
def prefix(handler):
declaration = re.search(r"const bool prefixed_reply[^;]+;", handler).group()
return declaration + "\n" + extract_braced(handler, "if (strlen(command) > 4 && command[2] == '|')")
start = repeater_handler.index(' const char* noise_commands[]')
end = repeater_handler.index(' const char* telemetry_args', start)
receiver = extract_braced(room, "void MyMesh::onPeerDataRecv(")
gate = extract_braced(receiver[receiver.index("if (!handleClientPathCommand"):], "if (client->isAdmin())")
end_gate = receiver[receiver.index(gate) + len(gate):]
gate += " " + extract_braced(end_gate, "else")
gate = gate.replace("_cli.morseReply().beginCommand(client->id.pub_key);", "")
gate = gate.replace("_cli.morseReply().endCommand();", "")
replacements = {
"@REPEATER_PREFIX@": prefix(repeater_handler),
"@REPEATER_NOISE@": repeater_handler[start:end],
"@ROOM_PREFIX@": prefix(room_handler),
"@ROOM_DISPATCH@": re.search(
r"if \(handleTelemetryHistoryCommand\([\s\S]*?\)\) return;", room_handler).group(),
"@ROOM_GATE@": gate,
"@ROOM_HISTORY@": extract_braced(room, "bool MyMesh::handleTelemetryHistoryCommand("),
}
harness = HARNESS
for marker, value in replacements.items():
harness = harness.replace(marker, value)
flags = [] if os.name == "nt" else ["-fsanitize=address,undefined",
"-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
with tempfile.TemporaryDirectory(prefix="meshcore-noise-cli-") as directory:
directory = Path(directory)
for legacy in (False, True):
with self.subTest(old_prefix_plumbing=legacy):
cpp, binary = directory / "cli.cpp", directory / "cli"
code = harness.replace("prefixed_reply ? 157 : 160, !prefixed_reply",
"prefixed_reply ? 160 : 160, true") if legacy else harness
cpp.write_text(code, encoding="ascii")
built = subprocess.run([os.environ.get("CXX") or shutil.which("g++") or "g++",
"-std=c++17", "-Wall", "-Wextra", "-Werror", *flags,
"-I", str(ROOT / "src"), str(cpp), "-o", str(binary)],
capture_output=True, text=True, timeout=60)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
checked = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
if legacy:
self.assertNotEqual(checked.returncode, 0)
self.assertIn("storage[i]", checked.stderr)
else:
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
self.assertIn("noise CLI prefix, permission and payload checks passed", checked.stdout)
if __name__ == "__main__":
unittest.main()
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Exercise the production five-bit noise history and its CLI/raw encoders."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class NoiseFloorHistoryTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
raise RuntimeError("noise history tests require a host C++ compiler")
cls.work = tempfile.TemporaryDirectory(prefix="meshcore-noise-history-")
cls.binary = Path(cls.work.name) / ("history.exe" if os.name == "nt" else "history")
flags = ["-std=c++11", "-O1", "-g", "-Wall", "-Wextra", "-Werror"]
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
"-fno-omit-frame-pointer", "-fno-pie", "-no-pie"]
result = subprocess.run([
compiler, *flags, "-I" + str(ROOT / "src"),
str(ROOT / "test/fixtures/noise_floor_history/main.cpp"), "-o", str(cls.binary),
], capture_output=True, text=True, timeout=60)
if result.returncode:
cls.work.cleanup()
raise AssertionError(result.stdout + result.stderr)
@classmethod
def tearDownClass(cls):
cls.work.cleanup()
def run_case(self, scenario):
result = subprocess.run([str(self.binary), scenario], capture_output=True,
text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_selection_thresholds_directional_rounding_and_sentinels(self):
self.run_case("selection")
def test_three_fresh_subslots_duplicate_rejection_and_millis_wrap(self):
self.run_case("freshness")
def test_retunes_clear_pending_samples_and_keep_profile_histories_separate(self):
self.run_case("invalidation")
def test_eight_day_packed_ring_rollover_and_oldest_partial_page(self):
self.run_case("rollover")
def test_missing_buckets_and_rtc_corrections_are_bounded(self):
self.run_case("clock")
def test_base64_160_byte_bounds_raw_header_255_samples_and_padding(self):
self.run_case("wire")
if __name__ == "__main__":
unittest.main()
+254
View File
@@ -0,0 +1,254 @@
"""Execute the production freshness API and publication paths with real estimators."""
from pathlib import Path
import os
import subprocess
import sys
import tempfile
import unittest
from test_radio_receive_contract import ROOT, method, transition_harness
FIXTURE = r'''
struct UnsupportedRadio {
@DEFAULT_GETTER@
@DEFAULT_REQUEST@
};
static void fill(NoiseFloorEstimator& estimator, float dbm) {
for (unsigned i = 0; i < NoiseFloorEstimator::SAMPLE_COUNT; ++i) {
now_ms += NoiseFloorEstimator::SAMPLE_INTERVAL_MS;
assert(estimator.add(dbm, now_ms));
}
}
static uint32_t reading(const RadioLibWrapper& w, unsigned profile, float expected) {
float dbm = 999;
uint32_t published = 999;
assert(w.getNoiseFloorReading(profile, dbm, published));
assert(fabsf(dbm - expected) < 0.02f);
return published;
}
static void missing(const RadioLibWrapper& w, unsigned profile) {
float dbm = 999;
uint32_t published = 999;
assert(!w.getNoiseFloorReading(profile, dbm, published));
assert(dbm == 999 && published == 999);
}
static void baseline(RadioLibWrapper& w, float primary = -120, float secondary = -118) {
w._noise_floor_valid = w._noise_floor_secondary_valid = false;
fill(w._floor_estimator, primary);
if (w._profiles.enabled()) fill(w._secondary_floor_estimator, secondary);
w._nf_refresh_requested = true;
w.loop();
}
static void dual(RadioLibWrapper& w) {
mesh::RadioProfileConfig second;
second.params.freq = 911.15f;
second.params.bw = 250;
second.params.sf = 7;
second.params.cr = 5;
second.mode = mesh::RadioProfileMode::RxTx;
w._profiles.setSecondary(second, false);
w._profiles.primary = second.params;
w._profile_rxps_suspended = true;
w._profile_scan_generation[0] = w._profiles.generation[0];
w._profile_scan_generation[1] = w._profiles.generation[1];
}
int main(int argc, char** argv) {
assert(argc == 2);
const char* scenario = argv[1];
if (!strcmp(scenario, "unsupported")) {
UnsupportedRadio radio;
float dbm = 123;
uint32_t published = 456;
for (unsigned profile : {0U, 1U, 2U, 255U}) {
assert(!radio.getNoiseFloorReading(profile, dbm, published));
assert(dbm == 123 && published == 456);
radio.requestNoiseFloorMeasurement();
}
RadioLibWrapper w;
for (unsigned profile : {0U, 1U, 2U, 255U}) missing(w, profile);
} else if (!strcmp(scenario, "single")) {
RadioLibWrapper w;
baseline(w);
const uint32_t first = now_ms;
assert(reading(w, 0, -120) == first);
missing(w, 1); missing(w, 2); missing(w, 255);
w.requestNoiseFloorMeasurement();
assert(reading(w, 0, -120) == first);
fill(w._floor_estimator, -120);
w.loop();
assert(now_ms != first && reading(w, 0, -120) == now_ms);
const uint32_t second = now_ms;
w.requestNoiseFloorMeasurement();
fill(w._floor_estimator, -60);
w.loop();
assert(reading(w, 0, -120) == second); // held rise is not a publication
assert(w._nf_last_calib == now_ms && now_ms != second);
w.requestNoiseFloorMeasurement();
w.busy = true;
w.loop(); // arm a bounded window, then let it expire without idle RSSI
now_ms += NF_CONTINUOUS_TIMEOUT_MS;
w.loop();
assert(!w._nf_refresh_requested);
assert(reading(w, 0, -120) == second);
} else if (!strcmp(scenario, "dual")) {
RadioLibWrapper w;
dual(w); baseline(w);
const uint32_t first = now_ms;
assert(reading(w, 0, -120) == first && reading(w, 1, -118) == first);
w.requestNoiseFloorMeasurement();
fill(w._floor_estimator, -120);
fill(w._secondary_floor_estimator, -60); // one profile may hold while the other publishes
w.loop();
assert(reading(w, 0, -120) == now_ms);
assert(reading(w, 1, -118) == first);
const uint32_t primary = now_ms;
w.requestNoiseFloorMeasurement();
w.busy = true; w.loop();
now_ms += NF_CONTINUOUS_TIMEOUT_MS;
w.loop();
assert(!w._nf_refresh_requested);
assert(reading(w, 0, -120) == primary && reading(w, 1, -118) == first);
w._profiles.secondary.mode = mesh::RadioProfileMode::Off;
missing(w, 1);
} else if (!strcmp(scenario, "invalidate")) {
RadioLibWrapper w;
dual(w); baseline(w);
++w._profiles.generation[1]; // reject the old profile before scanner service
missing(w, 1);
assert(reading(w, 0, -120) == now_ms);
++w._profiles.generation[0]; missing(w, 0);
w.recalibrateNoiseFloor();
missing(w, 0); missing(w, 1);
assert(w._nf_published_valid == 0 && w._nf_refresh_requested);
RadioLibWrapper gain;
baseline(gain);
assert(gain.setRxBoostedGainMode(true));
missing(gain, 0);
RadioLibWrapper reset;
baseline(reset);
reset.resetAGC();
assert(reset._noise_floor_valid); // legacy filter can retain its last value
missing(reset, 0); // telemetry cannot claim that value was measured after reset
} else if (!strcmp(scenario, "rollover")) {
for (bool two : {false, true}) {
RadioLibWrapper w;
if (two) dual(w);
w._noise_floor_valid = w._noise_floor_secondary_valid = false;
now_ms = UINT32_MAX - 10000;
fill(w._floor_estimator, -120);
if (two) fill(w._secondary_floor_estimator, -118);
now_ms = 0;
w.loop();
assert(reading(w, 0, -120) == 0);
if (two) assert(reading(w, 1, -118) == 0);
w.requestNoiseFloorMeasurement();
fill(w._floor_estimator, -120);
if (two) fill(w._secondary_floor_estimator, -118);
w.loop();
assert(reading(w, 0, -120) == now_ms && now_ms != 0);
}
} else if (!strcmp(scenario, "request")) {
for (unsigned owner : {0U, 1U, 2U, 3U, 4U, 5U, 6U}) {
RadioLibWrapper w;
baseline(w);
const uint32_t published = now_ms;
if (owner == 0) w.packet = true;
if (owner == 1) w.state = STATE_TX_WAIT;
if (owner == 2) w._cw_active = true;
if (owner == 3) w._morse_owned = true;
if (owner == 4) w._morse_rx_owned = true;
if (owner == 5) w._beacon_owned = true;
if (owner == 6) w.busy = true;
const unsigned arms = w.arms, stops = w.stops, reads = w.reads;
const unsigned scans = w.radio.scans, resets = w.agc_resets;
w.requestNoiseFloorMeasurement();
assert(reading(w, 0, -120) == published && w._nf_refresh_requested);
assert(w._floor_estimator.add(-120, now_ms));
w.loop();
const auto deadline = w._nf_calib_deadline;
for (unsigned i = 0; i < 4; ++i) {
now_ms += 1;
w.requestNoiseFloorMeasurement();
assert(w._floor_estimator.count() == 1 && w._nf_calib_deadline == deadline);
}
assert(w.arms == arms && w.stops == stops && w.reads == reads);
assert(w.radio.scans == scans && w.agc_resets == resets);
assert(reading(w, 0, -120) == published);
}
} else assert(false);
printf("PASS: %s\n", scenario);
}
'''
class NoiseFloorReadingTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.directory = tempfile.TemporaryDirectory(prefix="meshcore-noise-reading-")
cls.addClassCleanup(cls.directory.cleanup)
work = Path(cls.directory.name)
source = (ROOT / "src/helpers/radiolib/RadioLibWrappers.cpp").read_text()
header = (ROOT / "src/helpers/radiolib/RadioLibWrappers.h").read_text()
dispatcher = (ROOT / "src/Dispatcher.h").read_text()
harness = transition_harness(source).split("struct LegacyRadio {", 1)[0]
api = "\n".join(method(header, signature).replace(" override", "") for signature in (
"bool getNoiseFloorReading(", "void requestNoiseFloorMeasurement("))
harness = harness.replace(" bool tryResetAGC();", api + "\n bool tryResetAGC();")
harness = harness.replace("#include <cassert>", "#include <cassert>\n#include <cstring>")
harness = harness.replace("bool serviceCarrierWave() { return false; }",
"bool _morse_owned = false, _morse_rx_owned = false, _beacon_owned = false;\n"
" bool serviceCarrierWave() { return _cw_active || _morse_owned || _morse_rx_owned; }")
loop = method(source, "void RadioLibWrapper::loop(")
harness = harness.replace(loop,
"#define MESH_ENABLE_TX_BEACONS 1\n#define MESH_ENABLE_CARRIER_TOOLS 1\n"
+ loop + "\n#undef MESH_ENABLE_TX_BEACONS\n#undef MESH_ENABLE_CARRIER_TOOLS\n")
fixture = FIXTURE.replace("@DEFAULT_GETTER@", method(dispatcher,
"virtual bool getNoiseFloorReading(")).replace("@DEFAULT_REQUEST@", method(dispatcher,
"virtual void requestNoiseFloorMeasurement("))
cls.binaries = {}
flags = [] if not sys.platform.startswith("linux") else [
"-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
for family in ("sx1262", "other"):
cpp, binary = work / (family + ".cpp"), work / family
cpp.write_text((harness + fixture).replace("\u2014", "-"), encoding="ascii")
built = subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17", "-O1", "-g",
"-Wall", "-Wextra", "-Werror", *flags,
*(["-DUSE_SX1262=1"] if family == "sx1262" else []),
"-I", str(ROOT / "src"), str(cpp), "-o", str(binary)],
capture_output=True, text=True, timeout=60)
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
cls.binaries[family] = binary
def run_case(self, scenario):
for family, binary in self.binaries.items():
with self.subTest(family=family):
result = subprocess.run([str(binary), scenario], capture_output=True,
text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("PASS: " + scenario, result.stdout)
def test_unsupported_and_unmeasured_profiles_are_missing(self):
self.run_case("unsupported")
def test_single_only_successful_publications_advance_timestamp(self):
self.run_case("single")
def test_dual_publication_timestamps_remain_independent(self):
self.run_case("dual")
def test_profile_gain_and_rf_reset_invalidate_telemetry_readings(self):
self.run_case("invalidate")
def test_millis_zero_and_rollover_are_valid_publication_times(self):
self.run_case("rollover")
def test_requests_join_collection_without_interrupting_radio_owners(self):
self.run_case("request")
if __name__ == "__main__":
unittest.main()
+117
View File
@@ -0,0 +1,117 @@
"""Execute each LR instantaneous-RSSI method against failed hardware reads."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def rssi_method(header):
start = header.index("float getCurrentRSSI() override {")
end = header.index("\n }", start) + len("\n }")
return header[start:end]
class NoiseFloorRssiErrorTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
raise RuntimeError("RSSI error tests require a host C++ compiler")
cls.work = tempfile.TemporaryDirectory(prefix="meshcore-rssi-errors-")
cls.addClassCleanup(cls.work.cleanup)
binary = Path(cls.work.name) / ("rssi.exe" if os.name == "nt" else "rssi")
classes = []
for family in ("LR1110", "LR1121", "LR2021"):
name = "Custom" + family + "Wrapper"
source = (ROOT / ("src/helpers/radiolib/" + name + ".h")).read_text()
classes.append("class " + name + " : public WrapperBase { public: "
+ rssi_method(source) + " };\n")
harness = r'''
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include "helpers/radiolib/NoiseFloorEstimator.h"
constexpr int RADIOLIB_ERR_NONE = 0;
struct FakeRadio {
int status = 0;
float rssi = -119.25f;
bool write_value = true;
int getRssiInst(float* value) {
if (write_value) *value = rssi;
return status;
}
};
using CustomLR1110 = FakeRadio;
using CustomLR1121 = FakeRadio;
using CustomLR2021 = FakeRadio;
struct WrapperBase {
FakeRadio radio;
FakeRadio* _radio = &radio;
virtual ~WrapperBase() = default;
virtual float getCurrentRSSI() = 0;
};
@CLASSES@
template<class Wrapper> void exercise() {
Wrapper wrapper;
assert(wrapper.getCurrentRSSI() == -119.25f);
for (int status : {-1, -2, -16, 1}) {
wrapper.radio.status = status;
for (bool write : {false, true}) {
wrapper.radio.write_value = write;
NoiseFloorEstimator estimator;
for (unsigned sample = 0; sample < NoiseFloorEstimator::SAMPLE_COUNT; ++sample) {
const float rssi = wrapper.getCurrentRSSI();
assert(isnan(rssi));
assert(!estimator.add(rssi, sample * NoiseFloorEstimator::SAMPLE_INTERVAL_MS));
}
assert(estimator.count() == 0 && !estimator.complete());
int32_t floor = -12000;
assert(!estimator.publish(floor, false));
assert(floor == -12000);
}
}
wrapper.radio.status = 0;
wrapper.radio.write_value = false;
assert(isnan(wrapper.getCurrentRSSI()));
wrapper.radio.write_value = true;
assert(wrapper.getCurrentRSSI() == -119.25f);
NoiseFloorEstimator estimator;
for (unsigned sample = 0; sample < NoiseFloorEstimator::SAMPLE_COUNT; ++sample) {
assert(estimator.add(wrapper.getCurrentRSSI(), sample * NoiseFloorEstimator::SAMPLE_INTERVAL_MS));
}
int32_t floor = 0;
assert(estimator.publish(floor, false) && floor == -11925);
}
int main() {
exercise<CustomLR1110Wrapper>();
exercise<CustomLR1121Wrapper>();
exercise<CustomLR2021Wrapper>();
}
'''.replace("@CLASSES@", "\n".join(classes))
harness = harness.replace("#include <stdint.h>", "#include <stdint.h>\n#include <initializer_list>")
source = Path(cls.work.name) / "rssi.cpp"
source.write_text(harness, encoding="ascii")
flags = ["-std=c++11", "-O1", "-g", "-Wall", "-Wextra", "-Werror"]
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
"-fno-pie", "-no-pie"]
built = subprocess.run([compiler, *flags, "-I" + str(ROOT / "src"),
str(source), "-o", str(binary)],
capture_output=True, text=True, timeout=60)
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
cls.binary = binary
def test_failed_reads_cannot_fabricate_noise_floor_samples(self):
result = subprocess.run([str(self.binary)], capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
if __name__ == "__main__":
unittest.main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Exercise the production radio-to-history sampler with controlled publications."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
class NoiseFloorSamplerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
if not compiler:
raise RuntimeError("noise sampler tests require a host C++ compiler")
cls.work = tempfile.TemporaryDirectory(prefix="meshcore-noise-sampler-")
cls.binary = Path(cls.work.name) / ("sampler.exe" if os.name == "nt" else "sampler")
flags = ["-std=c++11", "-O1", "-g", "-Wall", "-Wextra", "-Werror"]
if os.name != "nt":
flags += ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
"-fno-omit-frame-pointer", "-fno-pie", "-no-pie"]
result = subprocess.run([
compiler, *flags, "-I" + str(ROOT / "src"),
str(ROOT / "test/fixtures/noise_floor_sampler/main.cpp"), "-o", str(cls.binary),
], capture_output=True, text=True, timeout=60)
if result.returncode:
cls.work.cleanup()
raise AssertionError(result.stdout + result.stderr)
@classmethod
def tearDownClass(cls):
cls.work.cleanup()
def run_case(self, scenario):
result = subprocess.run([str(self.binary), scenario], capture_output=True,
text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_three_fresh_publications_complete_a_bucket_without_extra_requests(self):
self.run_case("successful")
def test_cached_estimates_do_not_fill_multiple_subslots(self):
self.run_case("cached")
def test_millis_wrap_and_a_zero_publication_timestamp_are_valid(self):
self.run_case("rollover")
def test_retunes_and_validity_changes_discard_only_pending_profile_readings(self):
self.run_case("generations")
def test_radio2_disable_reenable_keeps_history_and_restarts_pending_aggregation(self):
self.run_case("enable_disable")
def test_rtc_jumps_start_new_buckets_and_do_not_loop_unbounded(self):
self.run_case("clock")
def test_unsupported_radios_and_fresh_dual_profiles_need_no_hardware_actions(self):
self.run_case("unsupported_fresh")
def test_invalid_rssi_never_suppresses_measurements_or_survives_as_pending_data(self):
self.run_case("invalid")
if __name__ == "__main__":
unittest.main()
+1
View File
@@ -46,6 +46,7 @@ struct RadioLibWrapper {
bool _profile_standby_held=false, _saved_standby_xosc=false;
bool _nf_calib_active=false, _nf_refresh_requested=false, _noise_floor_valid=true, _noise_floor_secondary_valid=true, _profile_refresh_required=false;
bool _nf_window_armed=false, _nf_lazy_refresh=false, _nf_refresh_attempted=false;
uint8_t _nf_published_valid=0;
unsigned long _nf_last_calib=0, _nf_calib_deadline=0, _nf_sample_from=0;
NoiseFloorEstimator _floor_estimator;
NoiseFloorEstimator _secondary_floor_estimator;
+2
View File
@@ -80,6 +80,8 @@ struct RadioLibWrapper {
bool _nf_calib_active = false, _nf_refresh_requested = true, _noise_floor_valid = true,
_noise_floor_secondary_valid = true;
bool _nf_window_armed = false, _nf_lazy_refresh = false, _nf_refresh_attempted = false;
uint32_t _nf_published_at[2] = {}, _nf_published_generation[2] = {};
uint8_t _nf_published_valid = 0;
bool _cad_enabled = true, packet = false, busy = false, inject_arm_irq = false;
bool _rx_boosted_gain_valid = false, _cur_rx_boosted_gain = false, gain_apply_success = true;
bool _wd_last_busy = false;
+1
View File
@@ -99,6 +99,7 @@ struct Chip : LR2021 {
bool _params_valid=true,_profile_rxps_suspended=true,_profile_saved_rxps=false;
bool _noise_floor_valid=true,_noise_floor_secondary_valid=true,_nf_refresh_requested=false;
bool _nf_window_armed=false,_nf_lazy_refresh=false,_nf_refresh_attempted=false;
uint8_t _nf_published_valid=0;
uint32_t _profile_retry_at=0,_profile_generation=1,_profile_visit_stamp=0,_profile_scan_generation[2]={};
uint8_t _active_profile=0,_cur_sf=7,_cur_cr=5;
uint16_t _physical_preamble=32;
+3 -1
View File
@@ -76,6 +76,7 @@ HISTORY_HARNESS = r'''
#include <helpers/SensorManager.h>
#include <helpers/TelemetryHistory.h>
#include <helpers/ExternalVoltageHistory.h>
#include <helpers/NoiseFloorHistory.h>
#include <helpers/ClientACLResponse.h>
#include <Wire.h>
#define ATOMIC_FILE_WRITER_IMPLEMENTATION
@@ -138,12 +139,13 @@ public:
uint8_t reply_data[184];
mesh::TelemetryHistory telemetry_history;
mesh::ExternalVoltageHistory external_voltage_history;
mesh::NoiseFloorHistory noise_floor_history;
Clock* getRTCClock() {return &clock;}
void configureHistory() {
@HISTORY_INIT@
}
void sampleTelemetryHistory();
bool handleTelemetryHistoryCommand(const char*,char*);
bool handleTelemetryHistoryCommand(const char*,char*,size_t=160,bool=true);
int handleRequest(ClientInfo*,uint32_t,uint8_t*,size_t,size_t);
void handleCommand(uint32_t sender_timestamp,char* command,char* reply,
int gpio_client_index=-1,uint8_t gpio_path_hash_size=1) {
+2 -1
View File
@@ -38,7 +38,7 @@ class TelemetryPersistenceTests(unittest.TestCase):
"bool CommonCLI::handleDataTxCommand(")) + "\n"
generated += '#define TELEMETRY_HISTORY_TX_PREFS_FILE "/telemetry_tx"\n'
for name in ("RETRY_MILLIS", "PACKET_SPACING_MILLIS", "DEFAULT_DAYS", "MAX_DAYS",
"TEMPERATURE", "VOLTAGE", "EXTERNAL_VOLTAGE"):
"TEMPERATURE", "VOLTAGE", "EXTERNAL_VOLTAGE", "NOISE", "NOISE2"):
generated += re.search(r"static const uint(?:8|64)_t TELEMETRY_HISTORY_TX_" +
name + r"[^;]*;", source).group() + "\n"
generated += "\n".join(extract_braced(source, signature) for signature in (
@@ -46,6 +46,7 @@ class TelemetryPersistenceTests(unittest.TestCase):
"static bool recoverTelemetryHistoryTxPrefs(",
"static bool readTelemetryHistoryTxPrefsImage(", "void MyMesh::loadTelemetryHistoryTxPrefs(",
"bool MyMesh::saveTelemetryHistoryTxPrefs(", "bool MyMesh::sendTelemetryHistorySnapshot(",
"bool MyMesh::sendNoiseFloorHistorySnapshot(",
"bool MyMesh::sendExternalVoltageHistorySnapshot(", "void MyMesh::serviceTelemetryHistoryTx(",
"void MyMesh::formatTelemetryHistoryTxStatus(", "static char* trimSpaces(")) + "\n"
generated += ('void MyMesh::handle(char* command, char* reply, ClientInfo* sender) {\n'