From 25c1867bbd910099f2b6777c48c489789b8930df Mon Sep 17 00:00:00 2001 From: Maxwell Date: Sun, 8 Nov 2026 16:34:54 +0200 Subject: [PATCH 01/14] Add min/max/avg history queries to repeaters Move TimeSeriesData from simple_sensor into src/helpers and drive it with monotonic uptime, so RTC changes cannot stall recording or break queries. Keep the old RTCClock* overloads as deprecated for custom sensor sketches. Record 24h of battery, noise floor, TX/RX airtime % and MCU temperature on repeaters and answer the existing 0x04 min/max/avg request using the same format as sensor nodes. No packets are sent by this feature. REPEATER_HISTORY_SLOTS=0 removes it; default off on STM32/RP2040. Add native tests for TimeSeriesData and document the request and channels. --- docs/cli_commands.md | 7 ++ docs/payloads.md | 26 +++- docs/repeater_history.md | 84 +++++++++++++ examples/simple_repeater/MyMesh.cpp | 108 +++++++++++++++- examples/simple_repeater/MyMesh.h | 26 ++++ examples/simple_sensor/SensorMesh.cpp | 12 +- examples/simple_sensor/SensorMesh.h | 5 +- examples/simple_sensor/TimeSeriesData.cpp | 45 ------- examples/simple_sensor/TimeSeriesData.h | 29 +---- examples/simple_sensor/main.cpp | 5 +- platformio.ini | 1 + src/helpers/TimeSeriesData.cpp | 91 ++++++++++++++ src/helpers/TimeSeriesData.h | 38 ++++++ test/test_time_series/test_time_series.cpp | 138 +++++++++++++++++++++ 14 files changed, 530 insertions(+), 85 deletions(-) create mode 100644 docs/repeater_history.md delete mode 100644 examples/simple_sensor/TimeSeriesData.cpp create mode 100644 src/helpers/TimeSeriesData.cpp create mode 100644 src/helpers/TimeSeriesData.h create mode 100644 test/test_time_series/test_time_series.cpp diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 9fde4d436e5..c19473fe8c2 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1175,6 +1175,13 @@ region save --- +### Repeater health history + +History is queried over the mesh using the sensor-compatible `0x04` min/max/average +request; there is no history CLI command. Retention and recording interval are controlled +by `REPEATER_HISTORY_SLOTS` and `REPEATER_HISTORY_INTERVAL_SECS` at build time. +See [Repeater health history](repeater_history.md) for the channel mapping and flags. + ### Ethernet (when Ethernet support is compiled in) Ethernet support is available on RAK4631 boards with a RAK13800 (W5100S) Ethernet module. Use the `_ethernet` firmware variants (e.g. `RAK_4631_repeater_ethernet`) to enable this feature. diff --git a/docs/payloads.md b/docs/payloads.md index 493f628ce6e..c60a78d6cf1 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -103,7 +103,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | `0x01` | get stats | get stats of repeater or room server | | `0x02` | keepalive | (deprecated) | | `0x03` | get telemetry | request node telemetry | -| `0x04` | get min/max/avg | get sensor node stats on time series data | +| `0x04` | get min/max/avg | get sensor or repeater time series statistics | | `0x05` | get acl | node ACL query | | `0x06` | get neighbors | node neighbors query | | `0x08` | subscribe | subscribe to telemetry push | @@ -140,7 +140,7 @@ Gets information about the node, possibly including the following: | req type | 1 | 0x03 (request sub type) | | permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) | -#### Get Min/Max/Ave (Sensor nodes) +#### Get Min/Max/Ave (Sensor and repeater nodes) | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -150,6 +150,28 @@ Gets information about the node, possibly including the following: | end | 4 | ending time, seconds ago | | reserved | 2 | should be zeroes | +Requires an authenticated client with the READ_ONLY role or higher. The range includes +samples whose age is `end <= age < start`, in seconds. Request integers are little-endian. +The repeater uses exactly the sensor request and response layout. + +The response body (after decryption) is: + +| Field | Size (bytes) | Description | +|----------------|--------------|-------------| +| tag | 4 | echoed request timestamp, little-endian | +| current time | 4 | current node RTC Unix time, little-endian | +| series | variable | up to 8 series records, described below | + +Each series record contains a channel byte, an LPP type byte, then min, max, and average +in that order. Each value uses the type's Cayenne LPP size, multiplier, sign, and +big-endian encoding. There is no count byte; parse records to the end of the response. +Nonzero reserved bytes return only the tag and current time. + +Repeater history is pull-only, uses uptime internally, and omits series with no valid +samples in the requested range. Its returned current time still comes from the RTC; +an unset or corrected RTC does not affect sampling or range selection. See +[Repeater health history](repeater_history.md) for channels, retention, and build flags. + #### Subscribe to Telemetry push - (Sensor nodes) | Field | Size (bytes) | Description | diff --git a/docs/repeater_history.md b/docs/repeater_history.md new file mode 100644 index 00000000000..35b37d8200f --- /dev/null +++ b/docs/repeater_history.md @@ -0,0 +1,84 @@ +# Repeater health history + +The simple repeater keeps health samples in RAM and answers mesh request +`REQ_TYPE_GET_AVG_MIN_MAX` (`0x04`). A logged-in client needs READ_ONLY access or +higher. This is pull-only: recording history sends no packets. Existing GET_STATUS +and telemetry responses are unchanged. + +## Series + +| Channel | LPP type | Value recorded each interval | +|---------|----------|------------------------------| +| 200 | `LPP_VOLTAGE` (116) | Battery voltage in V, averaged from periodic reads every 15 seconds | +| 201 | `LPP_ANALOG_INPUT` (2, signed) | Radio noise floor in dBm at the end of the interval | +| 202 | `LPP_PERCENTAGE` (120) | TX airtime percentage over the elapsed interval | +| 203 | `LPP_PERCENTAGE` (120) | RX airtime percentage over the elapsed interval | +| 204 | `LPP_TEMPERATURE` (103) | MCU temperature in degrees C, when supported | + +These channels are dedicated to history. Existing self telemetry and GPS use channel 1; +`EnvironmentSensorManager` assigns at most 16 active entries to channels 2–17. Channels +200–204 therefore do not collide with current repeater telemetry. Custom sensor managers +should leave this range free. History channels do not change the channels in `0x03`. + +Battery averaging reduces the effect of short voltage dips during transmission. Noise +floor and temperature are point samples. Recording advances on fixed interval boundaries +without accumulating loop delays; the airtime denominator uses a separate actual +measurement timestamp. TX/RX values are unsigned counter deltas in +milliseconds divided by the actual elapsed interval, multiplied by 100. Percentages +use the sensor protocol's integer LPP encoding, so fractional percentages are truncated. +NaN temperatures and the radio driver's uncalibrated noise-floor sentinel (0 dBm) +are skipped. At most five series are returned, below the eight-series reply limit. + +## Query and retention + +Use the [sensor-compatible `0x04` request](payloads.md#get-minmaxave-sensor-and-repeater-nodes): +start and end are seconds ago, followed by two zero reserved bytes. For example, +`start=3600, end=0` selects samples from the last hour, including age zero and excluding +age 3600. The reply echoes the request timestamp, adds the current RTC time, and then +encodes each series as channel, LPP type, min, max, average. There is no series count. +Empty series are omitted; an empty range returns just the eight-byte header. + +Sampling and queries use monotonic uptime, accumulated across `millis()` wraps. The +RTC is used only for the response timestamp. Samples occupy a fixed interval grid +anchored at the first valid sample. Missed intervals are empty (NaN) slots; a gap +at least as long as the ring capacity expires the old ring. Late readings are assigned +to their interval boundary, so their reported age can differ by less than one interval. +Only one timestamp is stored per series. +Unsigned second differences handle seconds-counter wrap; retained samples and query +ranges must span less than one full 32-bit seconds cycle (about 136 years). + +The first sample is recorded after one interval. Each series retains the configured +number of interval slots, including missing intervals. History is lost on reboot and +is not written to flash. + +## Build flags + +| Flag | Default | Description | +|------|---------|-------------| +| `REPEATER_HISTORY_INTERVAL_SECS` | `300` | Positive recording interval in seconds | +| `REPEATER_HISTORY_SLOTS` | `288`, or `0` on STM32/RP2040 | Interval slots per series; nominally 24 hours at five-minute intervals when enabled | + +Set these using PlatformIO `build_flags`, for example `-D REPEATER_HISTORY_SLOTS=144` +for nominally 12 hours. `-D REPEATER_HISTORY_SLOTS=0` removes history members, +allocations, sampling, and handling of `0x04` entirely. STM32 and RP2040 builds default +to disabled history to conserve RAM; they can explicitly opt in with a smaller slot count. +There are no history CLI settings. + +For both nRF52 and ESP32, sample storage is `5 * slots * 4` bytes (one float per +interval), or 5,760 bytes at the defaults. Comparing enabled and disabled builds shows +168 additional bytes in the enclosing mesh object on both platforms (including padding), +for a total of 5,928 bytes plus allocator overhead for five arrays. Unsupported temperature still reserves +its series storage. Query results use temporary stack space, not retained history RAM. + +## Custom sensor sketch compatibility + +The old `examples/simple_sensor/TimeSeriesData.h` include forwards to the shared helper. +Deprecated `RTCClock*` overloads remain available for existing custom sketches. They +ignore the RTC and use a shared, wrap-safe `millis()` accumulator; callers should migrate +to explicit monotonic seconds. Call the legacy API regularly enough to observe each +`millis()` wrap (less than about 49 days between calls), and use one clock API consistently +for each series. The shared legacy clock is linked only when these overloads are used. + +The integer literal `0` is ambiguous between the seconds and pointer overloads. Use a +`uint32_t` variable (or `uint32_t(0)`) for uptime zero, and `nullptr` for a legacy null +clock argument. diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index b50d19d013d..99cd35bbaf5 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1,5 +1,8 @@ #include "MyMesh.h" #include +#if REPEATER_HISTORY_SLOTS > 0 +#include +#endif /* ------------------------------ Config -------------------------------- */ @@ -46,6 +49,9 @@ #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 +#if REPEATER_HISTORY_SLOTS > 0 +#define REQ_TYPE_GET_AVG_MIN_MAX 0x04 +#endif #define REQ_TYPE_GET_ACCESS_LIST 0x05 #define REQ_TYPE_GET_NEIGHBOURS 0x06 #define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2 @@ -209,6 +215,7 @@ uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender } int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) { + if (payload_len == 0) return 0; // uint32_t now = getRTCClock()->getCurrentTimeUnique(); // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') @@ -259,6 +266,48 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t memcpy(&reply_data[4], telemetry.getBuffer(), tlen); return 4 + tlen; // reply_len } +#if REPEATER_HISTORY_SLOTS > 0 + if (payload[0] == REQ_TYPE_GET_AVG_MIN_MAX && payload_len >= 11 && + (sender->permissions & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + uint32_t start_secs_ago, end_secs_ago; + memcpy(&start_secs_ago, &payload[1], 4); + memcpy(&end_secs_ago, &payload[5], 4); + MinMaxAvg data[8]; + int n = 0; + if (payload[9] == 0 && payload[10] == 0) { + uint32_t now_secs = uptime_millis / 1000; + battery_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_BATTERY, + LPP_VOLTAGE); + noise_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_NOISE, + LPP_ANALOG_INPUT); + tx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_TX, + LPP_PERCENTAGE); + rx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_RX, + LPP_PERCENTAGE); + temperature_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n], HISTORY_TEMPERATURE, + LPP_TEMPERATURE); + // Unsupported temperature sensors and empty ranges have no encodable LPP value. + if (!isnan(data[n]._avg)) n++; + } + uint8_t ofs = 4; + uint32_t now = getRTCClock()->getCurrentTime(); + memcpy(&reply_data[ofs], &now, 4); + ofs += 4; + for (int i = 0; i < n; i++) { + auto d = &data[i]; + if (isnan(d->_avg)) continue; + reply_data[ofs++] = d->_channel; + reply_data[ofs++] = d->_lpp_type; + uint8_t sz = LPPData::getDataSize(d->_lpp_type); + uint32_t mult = LPPData::getMultiplier(d->_lpp_type); + bool is_signed = LPPData::isSigned(d->_lpp_type); + ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); + } + return ofs; + } +#endif if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) { uint8_t res1 = payload[1]; // reserved for future (extra query params) uint8_t res2 = payload[2]; @@ -862,6 +911,13 @@ void MyMesh::sendNodeDiscoverReq() { MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng, mesh::RTCClock &rtc, mesh::MeshTables &tables) : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), +#if REPEATER_HISTORY_SLOTS > 0 + battery_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + noise_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + tx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + rx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), + temperature_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), +#endif region_map(key_store), temp_map(key_store), _cli(board, rtc, sensors, region_map, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), @@ -876,6 +932,12 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc { last_millis = 0; uptime_millis = 0; +#if REPEATER_HISTORY_SLOTS > 0 + history_last_secs = history_battery_secs = history_airtime_secs = 0; + history_tx_millis = history_rx_millis = 0; + history_battery_total = 0; + history_battery_count = 0; +#endif next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; set_radio_at = revert_radio_at = 0; @@ -1286,7 +1348,48 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply } } +#if REPEATER_HISTORY_SLOTS > 0 +void MyMesh::recordHistory() { + uint32_t now_secs = uptime_millis / 1000; + // Average periodic reads without repeatedly enabling the battery divider. + if (uint32_t(now_secs - history_battery_secs) >= 15) { + history_battery_total += board.getBattMilliVolts(); + history_battery_count++; + history_battery_secs = now_secs; + } + uint32_t elapsed_secs = now_secs - history_last_secs; + if (elapsed_secs < REPEATER_HISTORY_INTERVAL_SECS) return; + // Advance the sampling grid without accumulating loop delays or replaying missed slots. + history_last_secs += (elapsed_secs / REPEATER_HISTORY_INTERVAL_SECS) * REPEATER_HISTORY_INTERVAL_SECS; + uint32_t airtime_elapsed_secs = now_secs - history_airtime_secs; + + if (history_battery_count > 0) { + battery_history.recordData(history_last_secs, history_battery_total / history_battery_count / 1000.0f); + } + int noise_floor = _radio->getNoiseFloor(); + if (noise_floor != 0) noise_history.recordData(history_last_secs, noise_floor); // zero means uncalibrated + uint32_t tx_millis = getTotalAirTime(); + uint32_t rx_millis = getReceiveAirTime(); + // Counters are milliseconds; unsigned subtraction also handles their wrap. + tx_history.recordData(history_last_secs, uint32_t(tx_millis - history_tx_millis) / (airtime_elapsed_secs * 10.0f)); + rx_history.recordData(history_last_secs, uint32_t(rx_millis - history_rx_millis) / (airtime_elapsed_secs * 10.0f)); + temperature_history.recordData(history_last_secs, board.getMCUTemperature()); // ignores NaN + history_airtime_secs = now_secs; + history_tx_millis = tx_millis; + history_rx_millis = rx_millis; + history_battery_total = 0; + history_battery_count = 0; +} +#endif + void MyMesh::loop() { + // Update before dispatching requests, including across millis() wrap. + uint32_t now = millis(); + uptime_millis += uint32_t(now - last_millis); + last_millis = now; +#if REPEATER_HISTORY_SLOTS > 0 + recordHistory(); +#endif #ifdef WITH_BRIDGE bridge.loop(); #endif @@ -1324,11 +1427,6 @@ void MyMesh::loop() { acl.save(_fs); dirty_contacts_expiry = 0; } - - // update uptime - uint32_t now = millis(); - uptime_millis += now - last_millis; - last_millis = now; } // To check if there is pending work diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index dc89325861c..2fbdd872697 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -37,6 +37,22 @@ #include #include "RateLimiter.h" +#ifndef REPEATER_HISTORY_SLOTS +#if defined(STM32_PLATFORM) || defined(RP2040_PLATFORM) +#define REPEATER_HISTORY_SLOTS 0 +#else +#define REPEATER_HISTORY_SLOTS 288 +#endif +#endif +#ifndef REPEATER_HISTORY_INTERVAL_SECS +#define REPEATER_HISTORY_INTERVAL_SECS 300 +#endif + +#if REPEATER_HISTORY_SLOTS > 0 +#include +static_assert(REPEATER_HISTORY_INTERVAL_SECS > 0, "History interval must be positive"); +#endif + #ifdef WITH_BRIDGE extern AbstractBridge* bridge; #endif @@ -82,6 +98,16 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { FILESYSTEM* _fs; uint32_t last_millis; uint64_t uptime_millis; +#if REPEATER_HISTORY_SLOTS > 0 + // Dedicated history channels 200..204; environment telemetry occupies 1..17. + enum { HISTORY_BATTERY = 200, HISTORY_NOISE, HISTORY_TX, HISTORY_RX, HISTORY_TEMPERATURE }; + TimeSeriesData battery_history, noise_history, tx_history, rx_history, temperature_history; + uint32_t history_last_secs, history_battery_secs, history_airtime_secs; + uint32_t history_tx_millis, history_rx_millis; + float history_battery_total; + uint32_t history_battery_count; + void recordHistory(); +#endif unsigned long next_local_advert, next_flood_advert; bool _logging; NodePrefs _prefs; diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index b186066810d..bb747f63caa 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -789,7 +789,9 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise { next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; - last_read_time = 0; + last_read_time = uint32_t(0) - SENSOR_READ_INTERVAL_SECS; // read immediately on the first loop + last_millis = 0; + uptime_millis = 0; num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; @@ -999,6 +1001,9 @@ bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { } void SensorMesh::loop() { + uint32_t now = millis(); + uptime_millis += uint32_t(now - last_millis); + last_millis = now; mesh::Mesh::loop(); if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { @@ -1028,7 +1033,8 @@ void SensorMesh::loop() { } uint32_t curr = getRTCClock()->getCurrentTime(); - if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) { + uint32_t uptime_secs = getUptimeSeconds(); + if (uint32_t(uptime_secs - last_read_time) >= SENSOR_READ_INTERVAL_SECS) { telemetry.reset(); telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); // query other sensors -- target specific @@ -1069,7 +1075,7 @@ void SensorMesh::loop() { onSensorDataRead(); - last_read_time = curr; + last_read_time = uptime_secs; } // check the alert send queue diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 590ca0c7657..e98fa571030 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -3,7 +3,7 @@ #include // needed for PlatformIO #include -#include "TimeSeriesData.h" +#include #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include @@ -88,6 +88,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); protected: + uint32_t getUptimeSeconds() const { return uptime_millis / 1000; } // current telemetry data queries float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } float getCurrent(uint8_t channel) { return getTelemValue(channel, LPP_CURRENT); } @@ -154,6 +155,8 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { RegionEntry* load_stack[8]; TransportKey default_scope; uint32_t last_read_time; + uint32_t last_millis; + uint64_t uptime_millis; int matching_peer_indexes[MAX_SEARCH_RESULTS]; int num_alert_tasks; Trigger* alert_tasks[MAX_CONCURRENT_ALERTS]; diff --git a/examples/simple_sensor/TimeSeriesData.cpp b/examples/simple_sensor/TimeSeriesData.cpp deleted file mode 100644 index f6157f9afc7..00000000000 --- a/examples/simple_sensor/TimeSeriesData.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "TimeSeriesData.h" - -void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) { - uint32_t now = clock->getCurrentTime(); - if (now >= last_timestamp + interval_secs) { - last_timestamp = now; - - data[next] = value; // append to cycle table - next = (next + 1) % num_slots; - } -} - -void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const { - int i = next, n = num_slots; - uint32_t ago = clock->getCurrentTime() - last_timestamp; - int num_values = 0; - float total = 0.0f; - - dest->_channel = channel; - dest->_lpp_type = lpp_type; - - // start at most recet recording, back-track through to oldest - while (n > 0) { - n--; - i = (i + num_slots - 1) % num_slots; // go back by one - if (ago >= end_secs_ago && ago < start_secs_ago) { // filter by the desired time range - float v = data[i]; - num_values++; - total += v; - if (num_values == 1) { - dest->_max = dest->_min = v; - } else { - if (v < dest->_min) dest->_min = v; - if (v > dest->_max) dest->_max = v; - } - } - ago += interval_secs; - } - // calc average - if (num_values > 0) { - dest->_avg = total / num_values; - } else { - dest->_max = dest->_min = dest->_avg = NAN; - } -} diff --git a/examples/simple_sensor/TimeSeriesData.h b/examples/simple_sensor/TimeSeriesData.h index 6efa7834ad0..41bf318932b 100644 --- a/examples/simple_sensor/TimeSeriesData.h +++ b/examples/simple_sensor/TimeSeriesData.h @@ -1,29 +1,4 @@ #pragma once -#include -#include - -struct MinMaxAvg { - float _min, _max, _avg; - uint8_t _lpp_type, _channel; -}; - -class TimeSeriesData { - float* data; - int num_slots, next; - uint32_t last_timestamp; - uint32_t interval_secs; - -public: - TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { - memset(data, 0, sizeof(float)*num); - } - TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { - data = new float[num]; - memset(data, 0, sizeof(float)*num); - } - - void recordData(mesh::RTCClock* clock, float value); - void calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const; -}; - +// Compatibility include for custom sensor sketches; implementation lives in src/helpers. +#include diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 66991daada5..6d455f73be6 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -21,13 +21,14 @@ class MyMesh : public SensorMesh { void onSensorDataRead() override { float batt_voltage = getVoltage(TELEM_CHANNEL_SELF); - battery_data.recordData(getRTCClock(), batt_voltage); // record battery + battery_data.recordData(getUptimeSeconds(), batt_voltage); // record battery alertIf(batt_voltage < 3.4f, critical_batt, HIGH_PRI_ALERT, "Battery is critical!"); alertIf(batt_voltage < 3.6f, low_batt, LOW_PRI_ALERT, "Battery is low"); } int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override { - battery_data.calcMinMaxAvg(getRTCClock(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); + battery_data.calcMinMaxAvg(getUptimeSeconds(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, + LPP_VOLTAGE); return 1; } diff --git a/platformio.ini b/platformio.ini index f66fbf2e5cf..7fdc8b64d22 100644 --- a/platformio.ini +++ b/platformio.ini @@ -174,6 +174,7 @@ build_src_filter = +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> + +<../src/helpers/TimeSeriesData.cpp> lib_deps = google/googletest @ 1.17.0 diff --git a/src/helpers/TimeSeriesData.cpp b/src/helpers/TimeSeriesData.cpp new file mode 100644 index 00000000000..371433c615c --- /dev/null +++ b/src/helpers/TimeSeriesData.cpp @@ -0,0 +1,91 @@ +#include "TimeSeriesData.h" + +#include +#include + +TimeSeriesData::TimeSeriesData(float *array, int num, uint32_t secs) + : data(array), num_slots(num > 0 ? num : 0), next(0), count(0), last_timestamp(0), interval_secs(secs), + owns_data(array == nullptr) { + if (num_slots > 0) { + if (owns_data) data = new float[num_slots]; + } +} + +TimeSeriesData::~TimeSeriesData() { + if (owns_data) delete[] data; +} + +void TimeSeriesData::recordData(uint32_t now_secs, float value) { + if (num_slots == 0 || isnan(value)) return; + uint32_t steps = 1; + if (count > 0 && interval_secs > 0) { + uint32_t elapsed = now_secs - last_timestamp; + if (elapsed < interval_secs) return; + steps = elapsed / interval_secs; + last_timestamp += steps * interval_secs; // keep a fixed sampling grid + } else { + last_timestamp = now_secs; + } + + // A long pause expires the whole ring in O(capacity), never O(elapsed time). + if (steps >= uint32_t(num_slots)) { + next = count = 0; + } else { + for (uint32_t i = 1; i < steps; i++) { + data[next] = NAN; + next = (next + 1) % num_slots; + if (count < num_slots) count++; + } + } + + data[next] = value; + next = (next + 1) % num_slots; + if (count < num_slots) count++; +} + +void TimeSeriesData::calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, + MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { + dest->_channel = channel; + dest->_lpp_type = lpp_type; + dest->_min = dest->_max = dest->_avg = NAN; + int num_values = 0; + float total = 0.0f; + int i = next; + uint64_t ago = uint32_t(now_secs - last_timestamp); + for (int n = 0; n < count; n++) { + i = (i + num_slots - 1) % num_slots; + if (ago >= end_secs_ago && ago < start_secs_ago && !isnan(data[i])) { + float v = data[i]; + if (num_values == 0) { + dest->_min = dest->_max = v; + } else { + if (v < dest->_min) dest->_min = v; + if (v > dest->_max) dest->_max = v; + } + total += v; + num_values++; + } + ago += interval_secs; + } + if (num_values > 0) dest->_avg = total / num_values; +} + +// Shared only by legacy callers; never consult the RTC, even after a time sync. +// At least one legacy call is required per millis() wrap (about 49 days). +static uint32_t legacyMonotonicSeconds() { + static uint32_t last_millis = 0; + static uint64_t uptime_millis = 0; + uint32_t now = millis(); + uptime_millis += uint32_t(now - last_millis); + last_millis = now; + return uptime_millis / 1000; +} + +void TimeSeriesData::recordData(mesh::RTCClock *, float value) { + recordData(legacyMonotonicSeconds(), value); +} + +void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock *, uint32_t start_secs_ago, uint32_t end_secs_ago, + MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { + calcMinMaxAvg(legacyMonotonicSeconds(), start_secs_ago, end_secs_ago, dest, channel, lpp_type); +} diff --git a/src/helpers/TimeSeriesData.h b/src/helpers/TimeSeriesData.h new file mode 100644 index 00000000000..3b7cdd47ced --- /dev/null +++ b/src/helpers/TimeSeriesData.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace mesh { +class RTCClock; +} + +struct MinMaxAvg { + float _min, _max, _avg; + uint8_t _lpp_type, _channel; +}; + +class TimeSeriesData { + float *data; + int num_slots, next, count; + uint32_t last_timestamp, interval_secs; + bool owns_data; + +public: + TimeSeriesData(float *array, int num, uint32_t secs); + TimeSeriesData(int num, uint32_t secs) : TimeSeriesData(nullptr, num, secs) {} + ~TimeSeriesData(); + TimeSeriesData(const TimeSeriesData &) = delete; + TimeSeriesData &operator=(const TimeSeriesData &) = delete; + + // Caller supplies monotonic seconds, accumulated across millisecond clock wraps. + void recordData(uint32_t now_secs, float value); + void calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, + uint8_t channel, uint8_t lpp_type) const; + + // Compatibility for custom sensor sketches. The RTC argument is ignored. + [[deprecated("Pass monotonic seconds instead of RTCClock*")]] + void recordData(mesh::RTCClock *clock, float value); + [[deprecated("Pass monotonic seconds instead of RTCClock*")]] + void calcMinMaxAvg(mesh::RTCClock *clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, + uint8_t channel, uint8_t lpp_type) const; +}; diff --git a/test/test_time_series/test_time_series.cpp b/test/test_time_series/test_time_series.cpp new file mode 100644 index 00000000000..eeb1aa6ebeb --- /dev/null +++ b/test/test_time_series/test_time_series.cpp @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +#include + +static MinMaxAvg query(const TimeSeriesData &series, uint32_t now, uint32_t start, uint32_t end) { + MinMaxAvg result; + series.calcMinMaxAvg(now, start, end, &result, 200, 116); + return result; +} + +TEST(TimeSeriesData, RingWrapKeepsNewestSamples) { + TimeSeriesData series(3, 10); + for (uint32_t i = 1; i <= 5; i++) + series.recordData(i * 10, float(i)); + auto result = query(series, 50, 100, 0); + EXPECT_FLOAT_EQ(result._min, 3); + EXPECT_FLOAT_EQ(result._max, 5); + EXPECT_FLOAT_EQ(result._avg, 4); + EXPECT_EQ(result._channel, 200); + EXPECT_EQ(result._lpp_type, 116); +} + +TEST(TimeSeriesData, RangeIncludesEndAndExcludesStart) { + TimeSeriesData series(4, 10); + series.recordData(10, -5); + series.recordData(20, -3); + series.recordData(30, -1); + series.recordData(40, 7); + auto result = query(series, 40, 30, 10); + EXPECT_FLOAT_EQ(result._min, -3); + EXPECT_FLOAT_EQ(result._max, -1); + EXPECT_FLOAT_EQ(result._avg, -2); +} + +TEST(TimeSeriesData, EmptyAndUnwrittenRangesReturnNaN) { + TimeSeriesData series(4, 10); + EXPECT_TRUE(std::isnan(query(series, 0, 100, 0)._avg)); + series.recordData(10, 4); + for (auto range : { std::pair(100, 1), { 0, 0 }, { 1, 10 } }) { + auto result = query(series, 10, range.first, range.second); + EXPECT_TRUE(std::isnan(result._min)); + EXPECT_TRUE(std::isnan(result._max)); + EXPECT_TRUE(std::isnan(result._avg)); + } +} + +TEST(TimeSeriesData, CadenceAndNaNSamples) { + float storage[3]; + TimeSeriesData series(storage, 3, 10); + series.recordData(uint32_t(0), 2); // uptime zero is a valid first sample + series.recordData(9, 100); + EXPECT_FLOAT_EQ(query(series, 9, 100, 0)._avg, 2); + series.recordData(10, 4); + series.recordData(19, 100); + series.recordData(20, NAN); + series.recordData(20, 6); + EXPECT_FLOAT_EQ(query(series, 20, 100, 0)._avg, 4); +} + +TEST(TimeSeriesData, LargeGapsExpireOldSamplesAndDoNotStall) { + TimeSeriesData series(4, 300); + series.recordData(300, 1); + const uint32_t later = UINT32_MAX / 300 * 300; + series.recordData(later, 3); + EXPECT_FLOAT_EQ(query(series, later, 301, 0)._avg, 3); + EXPECT_FLOAT_EQ(query(series, later, UINT32_MAX, 0)._avg, 3); + series.recordData(later + uint32_t(300), 5); // seconds counter wrap + auto result = query(series, later + uint32_t(300), 301, 0); + EXPECT_FLOAT_EQ(result._min, 3); + EXPECT_FLOAT_EQ(result._max, 5); + EXPECT_FLOAT_EQ(result._avg, 4); +} + +TEST(TimeSeriesData, MissingIntervalsAreEmptyInsteadOfMovingOldSamplesForward) { + TimeSeriesData series(5, 10); + series.recordData(10, 2); + series.recordData(40, 8); + EXPECT_TRUE(std::isnan(query(series, 40, 30, 1)._avg)); + EXPECT_FLOAT_EQ(query(series, 40, 31, 0)._avg, 5); + series.recordData(52, 10); // late read belongs to the fixed slot at 50 + EXPECT_FLOAT_EQ(query(series, 52, 3, 0)._avg, 10); + EXPECT_TRUE(std::isnan(query(series, 52, 2, 0)._avg)); +} + +TEST(TimeSeriesData, QueryAgeDoesNotOverflowWhileWalkingTheRing) { + TimeSeriesData series(3, 10); + series.recordData(10, 1); + series.recordData(20, 2); + EXPECT_TRUE(std::isnan(query(series, uint32_t(20 + (UINT32_MAX - 5)), 100, 0)._avg)); +} + +TEST(TimeSeriesData, LegacyClockAPIUsesMonotonicTimeAcrossRTCAndMillisWrap) { + class Clock : public mesh::RTCClock { + public: + uint32_t time = 100000; + int reads = 0; + uint32_t getCurrentTime() override { + reads++; + return time; + } + void setCurrentTime(uint32_t value) override { time = value; } + } clock; + TimeSeriesData series(3, 1); + g_mock_millis = UINT32_MAX - 499; + series.recordData(&clock, 2); + clock.setCurrentTime(0); + g_mock_millis = 500; + series.recordData(&clock, 4); + MinMaxAvg result; + series.calcMinMaxAvg(&clock, 2, 0, &result, 1, 116); + EXPECT_FLOAT_EQ(result._avg, 3); + EXPECT_EQ(clock.reads, 0); +} + +TEST(TimeSeriesData, MillisecondCounterWrapDoesNotResetSeconds) { + TimeSeriesData series(3, 1); + uint32_t last_millis = UINT32_MAX - 499; + uint64_t uptime_millis = last_millis; + series.recordData(uint32_t(uptime_millis / 1000), 1); + uint32_t now = 500; + uptime_millis += uint32_t(now - last_millis); + series.recordData(uint32_t(uptime_millis / 1000), 3); + EXPECT_FLOAT_EQ(query(series, uint32_t(uptime_millis / 1000), 2, 0)._avg, 2); +} + +TEST(TimeSeriesData, ZeroCapacityIsEmpty) { + TimeSeriesData series(0, 10); + series.recordData(100, 1); + EXPECT_TRUE(std::isnan(query(series, 100, 1000, 0)._avg)); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} From ef6ef2e9d2bb9e3dd9d9d79ba3f8bd0cf210fe3c Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Tue, 10 Nov 2026 19:33:38 +0200 Subject: [PATCH 02/14] GPS: GPS_BAUD_PROBE_LIST as a build flag for any NmeaGpsDriver; enable on Station G2/G3 The probe list was wired only in variants/promicro/target.cpp. It is now the default list of NmeaGpsDriver when GPS_BAUD_PROBE_LIST is set, so a variant enables baud autodetection with a build flag alone. Station G2 and G3 enable it: their Grove UART connector is used with M5Stack Unit GPS modules, which default to 115200. --- src/helpers/sensors/NmeaGpsDriver.h | 14 +++++++++++++- variants/promicro/target.cpp | 7 +------ variants/station_g2/platformio.ini | 1 + variants/station_g3_esp32/platformio.ini | 1 + 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/helpers/sensors/NmeaGpsDriver.h b/src/helpers/sensors/NmeaGpsDriver.h index dfe75a4f8f4..9beacdc2fde 100644 --- a/src/helpers/sensors/NmeaGpsDriver.h +++ b/src/helpers/sensors/NmeaGpsDriver.h @@ -64,6 +64,18 @@ #endif #endif +// Optional rates detect() tries after GPS_BAUD_RATE, for GPS modules whose baud rate is +// not known in advance (e.g. -D GPS_BAUD_PROBE_LIST=9600,115200,38400). Used by every +// NmeaGpsDriver that does not pass its own list. +#ifdef GPS_BAUD_PROBE_LIST + static const uint32_t NMEA_GPS_PROBE_BAUDS[] = { GPS_BAUD_PROBE_LIST }; + #define GPS_PROBE_BAUDS NMEA_GPS_PROBE_BAUDS + #define GPS_PROBE_COUNT ((uint8_t)(sizeof(NMEA_GPS_PROBE_BAUDS) / sizeof(NMEA_GPS_PROBE_BAUDS[0]))) +#else + #define GPS_PROBE_BAUDS nullptr + #define GPS_PROBE_COUNT 0 +#endif + #ifndef PIN_GPS_SWITCH #define PIN_GPS_SWITCH (-1) #endif @@ -199,7 +211,7 @@ class NmeaGpsDriver : public GpsDriver { uint32_t baudRate = GPS_BAUD_RATE, int hardwareEnablePin = PIN_GPS_SWITCH, int hardwareEnableActive = GPS_SWITCH_ACTIVE, - const uint32_t* probeBauds = nullptr, uint8_t probeCount = 0) + const uint32_t* probeBauds = GPS_PROBE_BAUDS, uint8_t probeCount = GPS_PROBE_COUNT) : _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin), _resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive), _resetActive(resetActive), _baudRate(baudRate), diff --git a/variants/promicro/target.cpp b/variants/promicro/target.cpp index 4cdeb6e0826..5758d9cda7e 100644 --- a/variants/promicro/target.cpp +++ b/variants/promicro/target.cpp @@ -12,12 +12,7 @@ VolatileRTCClock fallback_clock; AutoDiscoverRTCClock rtc_clock(fallback_clock); #if ENV_INCLUDE_GPS #include - #ifdef GPS_BAUD_PROBE_LIST // e.g. -D GPS_BAUD_PROBE_LIST=9600,38400,115200 - static const uint32_t gps_probe_bauds[] = { GPS_BAUD_PROBE_LIST }; - NmeaGpsDriver gps_driver(Serial1, gps_probe_bauds, sizeof(gps_probe_bauds) / sizeof(gps_probe_bauds[0])); - #else - NmeaGpsDriver gps_driver(Serial1); - #endif + NmeaGpsDriver gps_driver(Serial1); MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); #else diff --git a/variants/station_g2/platformio.ini b/variants/station_g2/platformio.ini index c1ae765fede..c4fd344ddea 100644 --- a/variants/station_g2/platformio.ini +++ b/variants/station_g2/platformio.ini @@ -25,6 +25,7 @@ build_flags = -D PIN_USER_BTN=38 -D PIN_GPS_RX=15 -D PIN_GPS_TX=7 + -D GPS_BAUD_PROBE_LIST=9600,115200,38400 ; Grove UART GPS units (e.g. M5Stack Unit GPS v1.1) default to 115200 -D SX126X_DIO2_AS_RF_SWITCH=true -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 diff --git a/variants/station_g3_esp32/platformio.ini b/variants/station_g3_esp32/platformio.ini index 7006d939ee5..2ce8bb39244 100644 --- a/variants/station_g3_esp32/platformio.ini +++ b/variants/station_g3_esp32/platformio.ini @@ -29,6 +29,7 @@ build_flags = -D PIN_USER_BTN=38 -D PIN_GPS_RX=15 -D PIN_GPS_TX=7 + -D GPS_BAUD_PROBE_LIST=9600,115200,38400 ; Grove UART GPS units (e.g. M5Stack Unit GPS v1.1) default to 115200 -D SX126X_DIO2_AS_RF_SWITCH=true -D SX126X_DIO3_TCXO_VOLTAGE=1.8 -D SX126X_CURRENT_LIMIT=140 From 196ca97751316daacea21093e3258503d70ec547 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Wed, 11 Nov 2026 01:48:12 +0200 Subject: [PATCH 03/14] GPS guard: show "time wait" instead of "rej nofix" between fixes When the last GPS time check passed but there is no current trusted fix (e.g. the GPS is asleep between periodic fixes), gps guard showed "time rej nofix", which reads like a rejection although the clock is fine. Show "time wait" instead. A real rejection without a trusted fix (GPS time arriving while fixes are rejected) still shows "rej nofix". --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 1488c646e6f..5d2ac70e446 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1085,7 +1085,7 @@ GPS time is written to the clock only while such a fix is current, never earlier Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** -- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. - `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. - `gps fence`, `gps fence `: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index cf7130333aa..66f4b92ff6a 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -280,16 +280,17 @@ class GpsGuard { return true; } - // e.g. "ok 7sat time ok +1s", "rej region time rej nofix", + // e.g. "ok 7sat time ok +1s", "ok 7sat time wait", "rej region time rej nofix", // "ok 9sat time rej step 3600s ALERT gps-clk +3600s 75m" void formatStatus(char* out, size_t out_size) const { if (!_enabled) { snprintf(out, out_size, "off"); return; } - // The time status is only refreshed when a sync is due: without a current trusted fix, - // do not keep showing an old "ok" as if GPS time were usable now. - const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "rej nofix" : _time_status; + // The time status is only refreshed when a sync is due. Without a current trusted fix + // (e.g. GPS asleep between periodic fixes) an old "ok" is not shown as current: the last + // check passed and the next one waits for a trusted fix. + const char* time_status = (_time_status[0] == 'o' && !trustedFixIsCurrent()) ? "wait" : _time_status; if (_time_alert) { snprintf(out, out_size, "%s time %s ALERT gps-clk %+lds %lum", _fix_status, time_status, _time_disagree_offset, (unsigned long)((uint32_t)(millis() - _time_disagree_since_ms) / 60000)); From 224658694ff722e4b1be17db1b1db1a72f855779 Mon Sep 17 00:00:00 2001 From: Valentin Metz Date: Wed, 11 Nov 2026 05:23:22 +0100 Subject: [PATCH 04/14] Fix stack-buffer overflow in CLI reply buffers The remote-CLI reply buffers in onPeerDataRecv() (repeater, room server, sensor) and BaseChatMesh were sized temp[166] for a 5-byte datagram header plus 161 bytes of reply. But MyMesh::handleCommand() first reflects a 3-byte correlation prefix (e.g. 'aa|') into the reply, after which CommonCLI commands may write up to 160 chars + NUL into the remaining 158 bytes -- overflowing the buffer by 2 bytes (e.g. a full 'regions' listing via exportTo(reply, 160)). Triggering this remotely crashes the node (observed as an unresponsive repeater after a prefixed 'regions' query); the 2 out-of-bounds bytes are a printable region-name character and a NUL. Size the buffers for the full worst case instead: 5 header + 3 prefix + 160 reply + 1 NUL = 169. Verified with a host ASan harness reproducing the exact layout: prefixed 'regions' with a 25-region listing overflowed temp[166] (BufStream::write, RegionMap.cpp) and now passes clean with temp[169]; unprefixed (serial) path unaffected. --- examples/simple_repeater/MyMesh.cpp | 3 ++- examples/simple_room_server/MyMesh.cpp | 3 ++- examples/simple_sensor/SensorMesh.cpp | 3 ++- src/helpers/BaseChatMesh.cpp | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 99cd35bbaf5..7d06811f4d4 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -779,7 +779,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, } } - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; char *command = (char *)&data[5]; char *reply = (char *)&temp[5]; if (is_retry) { diff --git a/examples/simple_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index b1a88dd8765..c1a6b09ff07 100644 --- a/examples/simple_room_server/MyMesh.cpp +++ b/examples/simple_room_server/MyMesh.cpp @@ -462,7 +462,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key, PUB_KEY_SIZE); - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; bool send_ack; if (flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND) { if (client->isAdmin()) { diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index bb747f63caa..2798c690117 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -667,7 +667,8 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i // len can be > original length, but 'text' will be padded with zeroes data[len] = 0; // need to make a C string again, with null terminator - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; char *command = (char *) &data[5]; char *reply = (char *) &temp[5]; handleCommand(from, sender_timestamp, command, reply); diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 4368d17f1c2..58c08deaa3f 100644 --- a/src/helpers/BaseChatMesh.cpp +++ b/src/helpers/BaseChatMesh.cpp @@ -266,7 +266,8 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender onCommandDataRecv(from, packet, sender_timestamp, text); // let UI know // NOTE: no ack expected for CLI_DATA replies } else if (flags == TXT_TYPE_CLI_COMMAND) { - uint8_t temp[166]; + // 5-byte datagram header + 3-byte reflected CLI prefix + 160-byte reply text + NUL + uint8_t temp[169]; char *command = (char *)&data[5]; char *reply = (char *)&temp[5]; *reply = 0; From 0147165b1467bf8e2a0f4a714cb026a9f791f57d Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 11 Nov 2026 07:26:01 -0400 Subject: [PATCH 05/14] tests: revert rak13302 tests --- .github/workflows/run-unit-tests.yml | 2 +- platformio.ini | 10 --- .../mocks/Arduino.h | 18 ----- test/test_rak3401_board_startup/mocks/Wire.h | 6 -- .../mocks/helpers/NRF52Board.h | 44 ------------ .../test_board_startup.cpp | 70 ------------------- .../test_onboard_radio.cpp | 66 ----------------- 7 files changed, 1 insertion(+), 215 deletions(-) delete mode 100644 test/test_rak3401_board_startup/mocks/Arduino.h delete mode 100644 test/test_rak3401_board_startup/mocks/Wire.h delete mode 100644 test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h delete mode 100644 test/test_rak3401_board_startup/test_board_startup.cpp delete mode 100644 test/test_rak3401_onboard_radio/test_onboard_radio.cpp diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index f8145ecd261..5d48f4c67be 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -20,7 +20,7 @@ jobs: uses: ./.github/actions/setup-build-environment - name: Run Unit Tests - run: pio test -e native -e native_kiss_modem -e native_rak3401_onboard_radio -vv + run: pio test -e native -e native_kiss_modem -vv - name: Upload Test Results # Upload test results even if the test step failed. diff --git a/platformio.ini b/platformio.ini index c33105c9849..7fdc8b64d22 100644 --- a/platformio.ini +++ b/platformio.ini @@ -168,7 +168,6 @@ build_flags = -std=c++17 -I test/mocks test_build_src = yes test_ignore = test_kiss_modem - test_rak3401_board_startup build_src_filter = -<*> +<../src/Utils.cpp> @@ -179,15 +178,6 @@ build_src_filter = lib_deps = google/googletest @ 1.17.0 -[env:native_rak3401_onboard_radio] -; Board startup needs isolated GPIO and power-management mocks. -extends = env:native -test_build_src = no -test_filter = test_rak3401_* -test_ignore = -build_flags = -I test/test_rak3401_board_startup/mocks - ${env:native.build_flags} - [env:native_kiss_modem] platform = native test_framework = googletest diff --git a/test/test_rak3401_board_startup/mocks/Arduino.h b/test/test_rak3401_board_startup/mocks/Arduino.h deleted file mode 100644 index d505af36a2f..00000000000 --- a/test/test_rak3401_board_startup/mocks/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "../../mocks/Arduino.h" - -#define NRF52_POWER_MANAGEMENT 1 -#define PWRMGT_LPCOMP_AIN 3 -#define PWRMGT_LPCOMP_REFSEL 4 -#define PWRMGT_VOLTAGE_BOOTLOCK 3300 -#define SX126X_POWER_EN 21 -#define INPUT 0 -#define OUTPUT 1 -#define LOW 0 -#define HIGH 1 - -void pinMode(uint32_t pin, uint32_t mode); -void digitalWrite(uint32_t pin, uint32_t value); -void analogReadResolution(uint32_t bits); -uint32_t analogRead(uint32_t pin); diff --git a/test/test_rak3401_board_startup/mocks/Wire.h b/test/test_rak3401_board_startup/mocks/Wire.h deleted file mode 100644 index c24e6306529..00000000000 --- a/test/test_rak3401_board_startup/mocks/Wire.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -struct StartupWire { - void begin() {} -}; -inline StartupWire Wire; diff --git a/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h b/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h deleted file mode 100644 index 96c892ae2a6..00000000000 --- a/test/test_rak3401_board_startup/mocks/helpers/NRF52Board.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include -#include - -#define SHUTDOWN_REASON_LOW_VOLTAGE 0x4C -#define SHUTDOWN_REASON_BOOT_PROTECT 0x42 - -struct PowerMgtConfig { - uint8_t lpcomp_ain_channel; - uint8_t lpcomp_refsel; - uint16_t voltage_bootlock; -}; - -namespace startup_test { -extern std::vector events; -extern bool permitBoot; -struct SystemOff { uint8_t reason; }; -} - -class NRF52Board { -protected: - bool checkBootVoltage(const PowerMgtConfig*) { - startup_test::events.push_back("voltage"); - if (!startup_test::permitBoot) initiateShutdown(SHUTDOWN_REASON_BOOT_PROTECT); - return true; - } - virtual void initiateShutdown(uint8_t reason) { enterSystemOff(reason); } - void configureVoltageWake(uint8_t, uint8_t) {} - void enterSystemOff(uint8_t reason) { - startup_test::events.push_back("off"); - throw startup_test::SystemOff{reason}; - } -public: - explicit NRF52Board(const char* = nullptr) {} - virtual uint16_t getBattMilliVolts() = 0; - virtual const char* getManufacturerName() const = 0; -}; - -class NRF52BoardDCDC : virtual public NRF52Board { -public: - void begin() {} -}; diff --git a/test/test_rak3401_board_startup/test_board_startup.cpp b/test/test_rak3401_board_startup/test_board_startup.cpp deleted file mode 100644 index 0bbf2e5aa08..00000000000 --- a/test/test_rak3401_board_startup/test_board_startup.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include -#include -// Exercise the real startup code with a power-management stub that stops at SYSTEMOFF. -#include "../../variants/rak3401/RAK3401Board.cpp" - -namespace startup_test { -std::vector events; -bool permitBoot; -std::array outputs; -rak3401::OnboardRadioState radioState; -} - -void pinMode(uint32_t, uint32_t) {} -void digitalWrite(uint32_t pin, uint32_t value) { startup_test::outputs.at(pin) = value; } -void analogReadResolution(uint32_t) {} -uint32_t analogRead(uint32_t) { return 2500; } - -rak3401::OnboardRadioState rak3401::sleepOnboardRadio() { - startup_test::events.push_back("onboard"); - return startup_test::radioState; -} - -class RakBoardStartup : public testing::Test { -protected: - void SetUp() override { - startup_test::events.clear(); - startup_test::outputs.fill(HIGH); - startup_test::permitBoot = true; - startup_test::radioState = rak3401::OnboardRadioState::Asleep; - } -}; - -TEST_F(RakBoardStartup, OnboardRadioHandledBeforeVoltageCheck) { - RAK3401Board board; - board.begin(); - EXPECT_EQ(startup_test::events, (std::vector{"onboard", "voltage"})); - EXPECT_EQ(startup_test::outputs.at(SX126X_POWER_EN), HIGH); - EXPECT_EQ(startup_test::outputs.at(PIN_3V3_EN), HIGH); -} - -TEST_F(RakBoardStartup, LowVoltageExitStillHandlesOnboardRadio) { - startup_test::permitBoot = false; - RAK3401Board board; - try { - board.begin(); - FAIL() << "Expected protective shutdown"; - } catch (const startup_test::SystemOff& off) { - EXPECT_EQ(off.reason, SHUTDOWN_REASON_BOOT_PROTECT); - } - EXPECT_EQ(startup_test::events, (std::vector{"onboard", "voltage", "off"})); - EXPECT_EQ(startup_test::outputs.at(SX126X_POWER_EN), LOW); - EXPECT_EQ(startup_test::outputs.at(PIN_3V3_EN), LOW); -} - -TEST_F(RakBoardStartup, OptionalRadioFailuresDoNotBypassBootProtection) { - for (auto state : {rak3401::OnboardRadioState::Absent, rak3401::OnboardRadioState::BusyTimeout, - rak3401::OnboardRadioState::SleepFailed}) { - startup_test::events.clear(); - startup_test::permitBoot = false; - startup_test::radioState = state; - RAK3401Board board; - EXPECT_THROW(board.begin(), startup_test::SystemOff); - EXPECT_EQ(startup_test::events, (std::vector{"onboard", "voltage", "off"})); - } -} - -int main(int argc, char** argv) { - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/test/test_rak3401_onboard_radio/test_onboard_radio.cpp b/test/test_rak3401_onboard_radio/test_onboard_radio.cpp deleted file mode 100644 index cc616612940..00000000000 --- a/test/test_rak3401_onboard_radio/test_onboard_radio.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include -#include -#include -#include "../../variants/rak3401/OnboardRadioSleep.h" - -namespace { -struct FakeRadioIO { - std::string version = "SX1261"; - std::array ready = {true, true, true}; - std::string calls; - unsigned waits = 0; - bool probePulls = true; - - void begin() { calls += "begin "; } - void reset() { calls += "reset "; } - bool waitBusy(bool high, unsigned timeout) { - calls += high ? "busy-high " : "busy-low "; - EXPECT_EQ(timeout, 20u); - if (high) EXPECT_FALSE(probePulls); - const bool result = ready.at(waits++); - return result; - } - void readVersion(char* out) { calls += "version "; memcpy(out, version.data(), 6); } - void releaseProbePulls() { calls += "release-pulls "; probePulls = false; } - void sleep() { EXPECT_FALSE(probePulls); calls += "sleep "; } - void end() { calls += "end "; } -}; -} - -TEST(RakOnboardRadio, PresentRadioSleepsBeforeBusRelease) { - FakeRadioIO io; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::Asleep); - EXPECT_EQ(io.calls, "begin reset busy-low version release-pulls busy-low sleep busy-high end "); -} - -TEST(RakOnboardRadio, AbsentAndFloatingResponsesNeverReceiveSleep) { - for (const std::string version : {std::string(6, '\0'), std::string(6, '\xff'), std::string("SX126X")}) { - FakeRadioIO io; - io.version = version; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::Absent); - EXPECT_EQ(io.calls, "begin reset busy-low version end "); - } -} - -TEST(RakOnboardRadio, BusyTimeoutsReleaseBusWithoutSleep) { - for (unsigned failure = 0; failure < 2; failure++) { - FakeRadioIO io; - io.ready[failure] = false; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::BusyTimeout); - EXPECT_EQ(io.calls.find("sleep "), std::string::npos); - EXPECT_EQ(io.calls, failure == 0 ? "begin reset busy-low end " : - "begin reset busy-low version release-pulls busy-low end "); - } -} - -TEST(RakOnboardRadio, MissingSleepReadbackIsReportedAndBusReleased) { - FakeRadioIO io; - io.ready[2] = false; - EXPECT_EQ(rak3401::sleepOnboardRadio(io, "SX1261"), rak3401::OnboardRadioState::SleepFailed); - EXPECT_EQ(io.calls.substr(io.calls.size() - 4), "end "); -} - -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 85bba10742b004629659358cb47d71357ae93fc0 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 11 Nov 2026 07:37:24 -0400 Subject: [PATCH 06/14] companion_radio: rewrite mdns part removing String class --- examples/companion_radio/main.cpp | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index c534772cd26..367d7bfa73e 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -276,27 +276,30 @@ void setup() { #endif #ifdef HAS_ESP_MDNS - String nodeName = the_mesh.getNodeName(); - String sanitizedNodeName; - sanitizedNodeName.reserve(nodeName.length()); - for (size_t i = 0; i < nodeName.length(); ++i) { + const char* nodeName = the_mesh.getNodeName(); + + // "meshcore_" prefix + sanitized node name, capped at 63 chars (max DNS label length) + char mdnsName[64]; + const size_t prefixLen = snprintf(mdnsName, sizeof(mdnsName), "meshcore_"); + size_t pos = prefixLen; + for (size_t i = 0; nodeName[i] != '\0' && pos < sizeof(mdnsName) - 1; ++i) { const char c = nodeName[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') { - sanitizedNodeName += c; + mdnsName[pos++] = c; } } + mdnsName[pos] = '\0'; - String mdnsName = "meshcore_"; - mdnsName += sanitizedNodeName; - if (!MDNS.begin(mdnsName.c_str())) { + if (!MDNS.begin(mdnsName)) { WIFI_DEBUG_PRINTLN("mDNS failed to start!"); } else { MDNS.addService("meshcore", "tcp", TCP_PORT); - MDNS.addServiceTxt("meshcore", "tcp", "node-name", the_mesh.getNodeName()); + MDNS.addServiceTxt("meshcore", "tcp", "node-name", nodeName); MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION); - String protocol; protocol+=FIRMWARE_VER_CODE; - MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol.c_str()); + char protocol[12]; + snprintf(protocol, sizeof(protocol), "%d", (int)FIRMWARE_VER_CODE); + MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol); MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__); MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__); } From 74f1f5a156739558c6dc08e26ad4e63535c0a7c5 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 11 Nov 2026 07:49:41 -0400 Subject: [PATCH 07/14] Revert "Merge pull request #3784 from Maxwell456/feature/repeater-history" This reverts commit f678f6ac151c795bd3fb6d519b401acbadd92d17, reversing changes made to b8ae75d258efa3a00f8679e0ec1516c014bf9dee. --- docs/cli_commands.md | 7 -- docs/payloads.md | 26 +--- docs/repeater_history.md | 84 ------------- examples/simple_repeater/MyMesh.cpp | 108 +--------------- examples/simple_repeater/MyMesh.h | 26 ---- examples/simple_sensor/SensorMesh.cpp | 12 +- examples/simple_sensor/SensorMesh.h | 5 +- examples/simple_sensor/TimeSeriesData.cpp | 45 +++++++ examples/simple_sensor/TimeSeriesData.h | 29 ++++- examples/simple_sensor/main.cpp | 5 +- platformio.ini | 1 - src/helpers/TimeSeriesData.cpp | 91 -------------- src/helpers/TimeSeriesData.h | 38 ------ test/test_time_series/test_time_series.cpp | 138 --------------------- 14 files changed, 85 insertions(+), 530 deletions(-) delete mode 100644 docs/repeater_history.md create mode 100644 examples/simple_sensor/TimeSeriesData.cpp delete mode 100644 src/helpers/TimeSeriesData.cpp delete mode 100644 src/helpers/TimeSeriesData.h delete mode 100644 test/test_time_series/test_time_series.cpp diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 1488c646e6f..754f5120131 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1247,13 +1247,6 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). --- -### Repeater health history - -History is queried over the mesh using the sensor-compatible `0x04` min/max/average -request; there is no history CLI command. Retention and recording interval are controlled -by `REPEATER_HISTORY_SLOTS` and `REPEATER_HISTORY_INTERVAL_SECS` at build time. -See [Repeater health history](repeater_history.md) for the channel mapping and flags. - ### Ethernet (when Ethernet support is compiled in) Ethernet support is available on RAK4631 boards with a RAK13800 (W5100S) Ethernet module. Use the `_ethernet` firmware variants (e.g. `RAK_4631_repeater_ethernet`) to enable this feature. diff --git a/docs/payloads.md b/docs/payloads.md index c60a78d6cf1..493f628ce6e 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -103,7 +103,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | `0x01` | get stats | get stats of repeater or room server | | `0x02` | keepalive | (deprecated) | | `0x03` | get telemetry | request node telemetry | -| `0x04` | get min/max/avg | get sensor or repeater time series statistics | +| `0x04` | get min/max/avg | get sensor node stats on time series data | | `0x05` | get acl | node ACL query | | `0x06` | get neighbors | node neighbors query | | `0x08` | subscribe | subscribe to telemetry push | @@ -140,7 +140,7 @@ Gets information about the node, possibly including the following: | req type | 1 | 0x03 (request sub type) | | permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) | -#### Get Min/Max/Ave (Sensor and repeater nodes) +#### Get Min/Max/Ave (Sensor nodes) | Field | Size (bytes) | Description | |----------------|--------------|------------------------------| @@ -150,28 +150,6 @@ Gets information about the node, possibly including the following: | end | 4 | ending time, seconds ago | | reserved | 2 | should be zeroes | -Requires an authenticated client with the READ_ONLY role or higher. The range includes -samples whose age is `end <= age < start`, in seconds. Request integers are little-endian. -The repeater uses exactly the sensor request and response layout. - -The response body (after decryption) is: - -| Field | Size (bytes) | Description | -|----------------|--------------|-------------| -| tag | 4 | echoed request timestamp, little-endian | -| current time | 4 | current node RTC Unix time, little-endian | -| series | variable | up to 8 series records, described below | - -Each series record contains a channel byte, an LPP type byte, then min, max, and average -in that order. Each value uses the type's Cayenne LPP size, multiplier, sign, and -big-endian encoding. There is no count byte; parse records to the end of the response. -Nonzero reserved bytes return only the tag and current time. - -Repeater history is pull-only, uses uptime internally, and omits series with no valid -samples in the requested range. Its returned current time still comes from the RTC; -an unset or corrected RTC does not affect sampling or range selection. See -[Repeater health history](repeater_history.md) for channels, retention, and build flags. - #### Subscribe to Telemetry push - (Sensor nodes) | Field | Size (bytes) | Description | diff --git a/docs/repeater_history.md b/docs/repeater_history.md deleted file mode 100644 index 35b37d8200f..00000000000 --- a/docs/repeater_history.md +++ /dev/null @@ -1,84 +0,0 @@ -# Repeater health history - -The simple repeater keeps health samples in RAM and answers mesh request -`REQ_TYPE_GET_AVG_MIN_MAX` (`0x04`). A logged-in client needs READ_ONLY access or -higher. This is pull-only: recording history sends no packets. Existing GET_STATUS -and telemetry responses are unchanged. - -## Series - -| Channel | LPP type | Value recorded each interval | -|---------|----------|------------------------------| -| 200 | `LPP_VOLTAGE` (116) | Battery voltage in V, averaged from periodic reads every 15 seconds | -| 201 | `LPP_ANALOG_INPUT` (2, signed) | Radio noise floor in dBm at the end of the interval | -| 202 | `LPP_PERCENTAGE` (120) | TX airtime percentage over the elapsed interval | -| 203 | `LPP_PERCENTAGE` (120) | RX airtime percentage over the elapsed interval | -| 204 | `LPP_TEMPERATURE` (103) | MCU temperature in degrees C, when supported | - -These channels are dedicated to history. Existing self telemetry and GPS use channel 1; -`EnvironmentSensorManager` assigns at most 16 active entries to channels 2–17. Channels -200–204 therefore do not collide with current repeater telemetry. Custom sensor managers -should leave this range free. History channels do not change the channels in `0x03`. - -Battery averaging reduces the effect of short voltage dips during transmission. Noise -floor and temperature are point samples. Recording advances on fixed interval boundaries -without accumulating loop delays; the airtime denominator uses a separate actual -measurement timestamp. TX/RX values are unsigned counter deltas in -milliseconds divided by the actual elapsed interval, multiplied by 100. Percentages -use the sensor protocol's integer LPP encoding, so fractional percentages are truncated. -NaN temperatures and the radio driver's uncalibrated noise-floor sentinel (0 dBm) -are skipped. At most five series are returned, below the eight-series reply limit. - -## Query and retention - -Use the [sensor-compatible `0x04` request](payloads.md#get-minmaxave-sensor-and-repeater-nodes): -start and end are seconds ago, followed by two zero reserved bytes. For example, -`start=3600, end=0` selects samples from the last hour, including age zero and excluding -age 3600. The reply echoes the request timestamp, adds the current RTC time, and then -encodes each series as channel, LPP type, min, max, average. There is no series count. -Empty series are omitted; an empty range returns just the eight-byte header. - -Sampling and queries use monotonic uptime, accumulated across `millis()` wraps. The -RTC is used only for the response timestamp. Samples occupy a fixed interval grid -anchored at the first valid sample. Missed intervals are empty (NaN) slots; a gap -at least as long as the ring capacity expires the old ring. Late readings are assigned -to their interval boundary, so their reported age can differ by less than one interval. -Only one timestamp is stored per series. -Unsigned second differences handle seconds-counter wrap; retained samples and query -ranges must span less than one full 32-bit seconds cycle (about 136 years). - -The first sample is recorded after one interval. Each series retains the configured -number of interval slots, including missing intervals. History is lost on reboot and -is not written to flash. - -## Build flags - -| Flag | Default | Description | -|------|---------|-------------| -| `REPEATER_HISTORY_INTERVAL_SECS` | `300` | Positive recording interval in seconds | -| `REPEATER_HISTORY_SLOTS` | `288`, or `0` on STM32/RP2040 | Interval slots per series; nominally 24 hours at five-minute intervals when enabled | - -Set these using PlatformIO `build_flags`, for example `-D REPEATER_HISTORY_SLOTS=144` -for nominally 12 hours. `-D REPEATER_HISTORY_SLOTS=0` removes history members, -allocations, sampling, and handling of `0x04` entirely. STM32 and RP2040 builds default -to disabled history to conserve RAM; they can explicitly opt in with a smaller slot count. -There are no history CLI settings. - -For both nRF52 and ESP32, sample storage is `5 * slots * 4` bytes (one float per -interval), or 5,760 bytes at the defaults. Comparing enabled and disabled builds shows -168 additional bytes in the enclosing mesh object on both platforms (including padding), -for a total of 5,928 bytes plus allocator overhead for five arrays. Unsupported temperature still reserves -its series storage. Query results use temporary stack space, not retained history RAM. - -## Custom sensor sketch compatibility - -The old `examples/simple_sensor/TimeSeriesData.h` include forwards to the shared helper. -Deprecated `RTCClock*` overloads remain available for existing custom sketches. They -ignore the RTC and use a shared, wrap-safe `millis()` accumulator; callers should migrate -to explicit monotonic seconds. Call the legacy API regularly enough to observe each -`millis()` wrap (less than about 49 days between calls), and use one clock API consistently -for each series. The shared legacy clock is linked only when these overloads are used. - -The integer literal `0` is ambiguous between the seconds and pointer overloads. Use a -`uint32_t` variable (or `uint32_t(0)`) for uptime zero, and `nullptr` for a legacy null -clock argument. diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 7d06811f4d4..21f833a588d 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1,8 +1,5 @@ #include "MyMesh.h" #include -#if REPEATER_HISTORY_SLOTS > 0 -#include -#endif /* ------------------------------ Config -------------------------------- */ @@ -49,9 +46,6 @@ #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 -#if REPEATER_HISTORY_SLOTS > 0 -#define REQ_TYPE_GET_AVG_MIN_MAX 0x04 -#endif #define REQ_TYPE_GET_ACCESS_LIST 0x05 #define REQ_TYPE_GET_NEIGHBOURS 0x06 #define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2 @@ -215,7 +209,6 @@ uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender } int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) { - if (payload_len == 0) return 0; // uint32_t now = getRTCClock()->getCurrentTimeUnique(); // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') @@ -266,48 +259,6 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t memcpy(&reply_data[4], telemetry.getBuffer(), tlen); return 4 + tlen; // reply_len } -#if REPEATER_HISTORY_SLOTS > 0 - if (payload[0] == REQ_TYPE_GET_AVG_MIN_MAX && payload_len >= 11 && - (sender->permissions & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { - uint32_t start_secs_ago, end_secs_ago; - memcpy(&start_secs_ago, &payload[1], 4); - memcpy(&end_secs_ago, &payload[5], 4); - MinMaxAvg data[8]; - int n = 0; - if (payload[9] == 0 && payload[10] == 0) { - uint32_t now_secs = uptime_millis / 1000; - battery_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_BATTERY, - LPP_VOLTAGE); - noise_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_NOISE, - LPP_ANALOG_INPUT); - tx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_TX, - LPP_PERCENTAGE); - rx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_RX, - LPP_PERCENTAGE); - temperature_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n], HISTORY_TEMPERATURE, - LPP_TEMPERATURE); - // Unsupported temperature sensors and empty ranges have no encodable LPP value. - if (!isnan(data[n]._avg)) n++; - } - uint8_t ofs = 4; - uint32_t now = getRTCClock()->getCurrentTime(); - memcpy(&reply_data[ofs], &now, 4); - ofs += 4; - for (int i = 0; i < n; i++) { - auto d = &data[i]; - if (isnan(d->_avg)) continue; - reply_data[ofs++] = d->_channel; - reply_data[ofs++] = d->_lpp_type; - uint8_t sz = LPPData::getDataSize(d->_lpp_type); - uint32_t mult = LPPData::getMultiplier(d->_lpp_type); - bool is_signed = LPPData::isSigned(d->_lpp_type); - ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); - ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); - ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); - } - return ofs; - } -#endif if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) { uint8_t res1 = payload[1]; // reserved for future (extra query params) uint8_t res2 = payload[2]; @@ -912,13 +863,6 @@ void MyMesh::sendNodeDiscoverReq() { MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng, mesh::RTCClock &rtc, mesh::MeshTables &tables) : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), -#if REPEATER_HISTORY_SLOTS > 0 - battery_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - noise_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - tx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - rx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), - temperature_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS), -#endif region_map(key_store), temp_map(key_store), _cli(board, rtc, sensors, region_map, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4), @@ -933,12 +877,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc { last_millis = 0; uptime_millis = 0; -#if REPEATER_HISTORY_SLOTS > 0 - history_last_secs = history_battery_secs = history_airtime_secs = 0; - history_tx_millis = history_rx_millis = 0; - history_battery_total = 0; - history_battery_count = 0; -#endif next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; set_radio_at = revert_radio_at = 0; @@ -1349,48 +1287,7 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply } } -#if REPEATER_HISTORY_SLOTS > 0 -void MyMesh::recordHistory() { - uint32_t now_secs = uptime_millis / 1000; - // Average periodic reads without repeatedly enabling the battery divider. - if (uint32_t(now_secs - history_battery_secs) >= 15) { - history_battery_total += board.getBattMilliVolts(); - history_battery_count++; - history_battery_secs = now_secs; - } - uint32_t elapsed_secs = now_secs - history_last_secs; - if (elapsed_secs < REPEATER_HISTORY_INTERVAL_SECS) return; - // Advance the sampling grid without accumulating loop delays or replaying missed slots. - history_last_secs += (elapsed_secs / REPEATER_HISTORY_INTERVAL_SECS) * REPEATER_HISTORY_INTERVAL_SECS; - uint32_t airtime_elapsed_secs = now_secs - history_airtime_secs; - - if (history_battery_count > 0) { - battery_history.recordData(history_last_secs, history_battery_total / history_battery_count / 1000.0f); - } - int noise_floor = _radio->getNoiseFloor(); - if (noise_floor != 0) noise_history.recordData(history_last_secs, noise_floor); // zero means uncalibrated - uint32_t tx_millis = getTotalAirTime(); - uint32_t rx_millis = getReceiveAirTime(); - // Counters are milliseconds; unsigned subtraction also handles their wrap. - tx_history.recordData(history_last_secs, uint32_t(tx_millis - history_tx_millis) / (airtime_elapsed_secs * 10.0f)); - rx_history.recordData(history_last_secs, uint32_t(rx_millis - history_rx_millis) / (airtime_elapsed_secs * 10.0f)); - temperature_history.recordData(history_last_secs, board.getMCUTemperature()); // ignores NaN - history_airtime_secs = now_secs; - history_tx_millis = tx_millis; - history_rx_millis = rx_millis; - history_battery_total = 0; - history_battery_count = 0; -} -#endif - void MyMesh::loop() { - // Update before dispatching requests, including across millis() wrap. - uint32_t now = millis(); - uptime_millis += uint32_t(now - last_millis); - last_millis = now; -#if REPEATER_HISTORY_SLOTS > 0 - recordHistory(); -#endif #ifdef WITH_BRIDGE bridge.loop(); #endif @@ -1428,6 +1325,11 @@ void MyMesh::loop() { acl.save(_fs); dirty_contacts_expiry = 0; } + + // update uptime + uint32_t now = millis(); + uptime_millis += now - last_millis; + last_millis = now; } // To check if there is pending work diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index f30eedd00b8..7e4cfd4f22e 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -37,22 +37,6 @@ #include #include "RateLimiter.h" -#ifndef REPEATER_HISTORY_SLOTS -#if defined(STM32_PLATFORM) || defined(RP2040_PLATFORM) -#define REPEATER_HISTORY_SLOTS 0 -#else -#define REPEATER_HISTORY_SLOTS 288 -#endif -#endif -#ifndef REPEATER_HISTORY_INTERVAL_SECS -#define REPEATER_HISTORY_INTERVAL_SECS 300 -#endif - -#if REPEATER_HISTORY_SLOTS > 0 -#include -static_assert(REPEATER_HISTORY_INTERVAL_SECS > 0, "History interval must be positive"); -#endif - #ifdef WITH_BRIDGE extern AbstractBridge* bridge; #endif @@ -98,16 +82,6 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { FILESYSTEM* _fs; uint32_t last_millis; uint64_t uptime_millis; -#if REPEATER_HISTORY_SLOTS > 0 - // Dedicated history channels 200..204; environment telemetry occupies 1..17. - enum { HISTORY_BATTERY = 200, HISTORY_NOISE, HISTORY_TX, HISTORY_RX, HISTORY_TEMPERATURE }; - TimeSeriesData battery_history, noise_history, tx_history, rx_history, temperature_history; - uint32_t history_last_secs, history_battery_secs, history_airtime_secs; - uint32_t history_tx_millis, history_rx_millis; - float history_battery_total; - uint32_t history_battery_count; - void recordHistory(); -#endif unsigned long next_local_advert, next_flood_advert; bool _logging; NodePrefs _prefs; diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 2798c690117..4916ddcdf0d 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -790,9 +790,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise { next_local_advert = next_flood_advert = 0; dirty_contacts_expiry = 0; - last_read_time = uint32_t(0) - SENSOR_READ_INTERVAL_SECS; // read immediately on the first loop - last_millis = 0; - uptime_millis = 0; + last_read_time = 0; num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; @@ -1002,9 +1000,6 @@ bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { } void SensorMesh::loop() { - uint32_t now = millis(); - uptime_millis += uint32_t(now - last_millis); - last_millis = now; mesh::Mesh::loop(); if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { @@ -1034,8 +1029,7 @@ void SensorMesh::loop() { } uint32_t curr = getRTCClock()->getCurrentTime(); - uint32_t uptime_secs = getUptimeSeconds(); - if (uint32_t(uptime_secs - last_read_time) >= SENSOR_READ_INTERVAL_SECS) { + if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) { telemetry.reset(); telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); // query other sensors -- target specific @@ -1076,7 +1070,7 @@ void SensorMesh::loop() { onSensorDataRead(); - last_read_time = uptime_secs; + last_read_time = curr; } // check the alert send queue diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index f1431f6f3ce..e6746d470c7 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -3,7 +3,7 @@ #include // needed for PlatformIO #include -#include +#include "TimeSeriesData.h" #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include @@ -88,7 +88,6 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); protected: - uint32_t getUptimeSeconds() const { return uptime_millis / 1000; } // current telemetry data queries float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } float getCurrent(uint8_t channel) { return getTelemValue(channel, LPP_CURRENT); } @@ -155,8 +154,6 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { RegionEntry* load_stack[8]; TransportKey default_scope; uint32_t last_read_time; - uint32_t last_millis; - uint64_t uptime_millis; int matching_peer_indexes[MAX_SEARCH_RESULTS]; int num_alert_tasks; Trigger* alert_tasks[MAX_CONCURRENT_ALERTS]; diff --git a/examples/simple_sensor/TimeSeriesData.cpp b/examples/simple_sensor/TimeSeriesData.cpp new file mode 100644 index 00000000000..f6157f9afc7 --- /dev/null +++ b/examples/simple_sensor/TimeSeriesData.cpp @@ -0,0 +1,45 @@ +#include "TimeSeriesData.h" + +void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) { + uint32_t now = clock->getCurrentTime(); + if (now >= last_timestamp + interval_secs) { + last_timestamp = now; + + data[next] = value; // append to cycle table + next = (next + 1) % num_slots; + } +} + +void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const { + int i = next, n = num_slots; + uint32_t ago = clock->getCurrentTime() - last_timestamp; + int num_values = 0; + float total = 0.0f; + + dest->_channel = channel; + dest->_lpp_type = lpp_type; + + // start at most recet recording, back-track through to oldest + while (n > 0) { + n--; + i = (i + num_slots - 1) % num_slots; // go back by one + if (ago >= end_secs_ago && ago < start_secs_ago) { // filter by the desired time range + float v = data[i]; + num_values++; + total += v; + if (num_values == 1) { + dest->_max = dest->_min = v; + } else { + if (v < dest->_min) dest->_min = v; + if (v > dest->_max) dest->_max = v; + } + } + ago += interval_secs; + } + // calc average + if (num_values > 0) { + dest->_avg = total / num_values; + } else { + dest->_max = dest->_min = dest->_avg = NAN; + } +} diff --git a/examples/simple_sensor/TimeSeriesData.h b/examples/simple_sensor/TimeSeriesData.h index 41bf318932b..6efa7834ad0 100644 --- a/examples/simple_sensor/TimeSeriesData.h +++ b/examples/simple_sensor/TimeSeriesData.h @@ -1,4 +1,29 @@ #pragma once -// Compatibility include for custom sensor sketches; implementation lives in src/helpers. -#include +#include +#include + +struct MinMaxAvg { + float _min, _max, _avg; + uint8_t _lpp_type, _channel; +}; + +class TimeSeriesData { + float* data; + int num_slots, next; + uint32_t last_timestamp; + uint32_t interval_secs; + +public: + TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { + memset(data, 0, sizeof(float)*num); + } + TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { + data = new float[num]; + memset(data, 0, sizeof(float)*num); + } + + void recordData(mesh::RTCClock* clock, float value); + void calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const; +}; + diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 6d455f73be6..66991daada5 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -21,14 +21,13 @@ class MyMesh : public SensorMesh { void onSensorDataRead() override { float batt_voltage = getVoltage(TELEM_CHANNEL_SELF); - battery_data.recordData(getUptimeSeconds(), batt_voltage); // record battery + battery_data.recordData(getRTCClock(), batt_voltage); // record battery alertIf(batt_voltage < 3.4f, critical_batt, HIGH_PRI_ALERT, "Battery is critical!"); alertIf(batt_voltage < 3.6f, low_batt, LOW_PRI_ALERT, "Battery is low"); } int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override { - battery_data.calcMinMaxAvg(getUptimeSeconds(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, - LPP_VOLTAGE); + battery_data.calcMinMaxAvg(getRTCClock(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); return 1; } diff --git a/platformio.ini b/platformio.ini index 7fdc8b64d22..f66fbf2e5cf 100644 --- a/platformio.ini +++ b/platformio.ini @@ -174,7 +174,6 @@ build_src_filter = +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> - +<../src/helpers/TimeSeriesData.cpp> lib_deps = google/googletest @ 1.17.0 diff --git a/src/helpers/TimeSeriesData.cpp b/src/helpers/TimeSeriesData.cpp deleted file mode 100644 index 371433c615c..00000000000 --- a/src/helpers/TimeSeriesData.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "TimeSeriesData.h" - -#include -#include - -TimeSeriesData::TimeSeriesData(float *array, int num, uint32_t secs) - : data(array), num_slots(num > 0 ? num : 0), next(0), count(0), last_timestamp(0), interval_secs(secs), - owns_data(array == nullptr) { - if (num_slots > 0) { - if (owns_data) data = new float[num_slots]; - } -} - -TimeSeriesData::~TimeSeriesData() { - if (owns_data) delete[] data; -} - -void TimeSeriesData::recordData(uint32_t now_secs, float value) { - if (num_slots == 0 || isnan(value)) return; - uint32_t steps = 1; - if (count > 0 && interval_secs > 0) { - uint32_t elapsed = now_secs - last_timestamp; - if (elapsed < interval_secs) return; - steps = elapsed / interval_secs; - last_timestamp += steps * interval_secs; // keep a fixed sampling grid - } else { - last_timestamp = now_secs; - } - - // A long pause expires the whole ring in O(capacity), never O(elapsed time). - if (steps >= uint32_t(num_slots)) { - next = count = 0; - } else { - for (uint32_t i = 1; i < steps; i++) { - data[next] = NAN; - next = (next + 1) % num_slots; - if (count < num_slots) count++; - } - } - - data[next] = value; - next = (next + 1) % num_slots; - if (count < num_slots) count++; -} - -void TimeSeriesData::calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, - MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { - dest->_channel = channel; - dest->_lpp_type = lpp_type; - dest->_min = dest->_max = dest->_avg = NAN; - int num_values = 0; - float total = 0.0f; - int i = next; - uint64_t ago = uint32_t(now_secs - last_timestamp); - for (int n = 0; n < count; n++) { - i = (i + num_slots - 1) % num_slots; - if (ago >= end_secs_ago && ago < start_secs_ago && !isnan(data[i])) { - float v = data[i]; - if (num_values == 0) { - dest->_min = dest->_max = v; - } else { - if (v < dest->_min) dest->_min = v; - if (v > dest->_max) dest->_max = v; - } - total += v; - num_values++; - } - ago += interval_secs; - } - if (num_values > 0) dest->_avg = total / num_values; -} - -// Shared only by legacy callers; never consult the RTC, even after a time sync. -// At least one legacy call is required per millis() wrap (about 49 days). -static uint32_t legacyMonotonicSeconds() { - static uint32_t last_millis = 0; - static uint64_t uptime_millis = 0; - uint32_t now = millis(); - uptime_millis += uint32_t(now - last_millis); - last_millis = now; - return uptime_millis / 1000; -} - -void TimeSeriesData::recordData(mesh::RTCClock *, float value) { - recordData(legacyMonotonicSeconds(), value); -} - -void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock *, uint32_t start_secs_ago, uint32_t end_secs_ago, - MinMaxAvg *dest, uint8_t channel, uint8_t lpp_type) const { - calcMinMaxAvg(legacyMonotonicSeconds(), start_secs_ago, end_secs_ago, dest, channel, lpp_type); -} diff --git a/src/helpers/TimeSeriesData.h b/src/helpers/TimeSeriesData.h deleted file mode 100644 index 3b7cdd47ced..00000000000 --- a/src/helpers/TimeSeriesData.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include - -namespace mesh { -class RTCClock; -} - -struct MinMaxAvg { - float _min, _max, _avg; - uint8_t _lpp_type, _channel; -}; - -class TimeSeriesData { - float *data; - int num_slots, next, count; - uint32_t last_timestamp, interval_secs; - bool owns_data; - -public: - TimeSeriesData(float *array, int num, uint32_t secs); - TimeSeriesData(int num, uint32_t secs) : TimeSeriesData(nullptr, num, secs) {} - ~TimeSeriesData(); - TimeSeriesData(const TimeSeriesData &) = delete; - TimeSeriesData &operator=(const TimeSeriesData &) = delete; - - // Caller supplies monotonic seconds, accumulated across millisecond clock wraps. - void recordData(uint32_t now_secs, float value); - void calcMinMaxAvg(uint32_t now_secs, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, - uint8_t channel, uint8_t lpp_type) const; - - // Compatibility for custom sensor sketches. The RTC argument is ignored. - [[deprecated("Pass monotonic seconds instead of RTCClock*")]] - void recordData(mesh::RTCClock *clock, float value); - [[deprecated("Pass monotonic seconds instead of RTCClock*")]] - void calcMinMaxAvg(mesh::RTCClock *clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg *dest, - uint8_t channel, uint8_t lpp_type) const; -}; diff --git a/test/test_time_series/test_time_series.cpp b/test/test_time_series/test_time_series.cpp deleted file mode 100644 index eeb1aa6ebeb..00000000000 --- a/test/test_time_series/test_time_series.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include -#include -#include -#include -#include -#include - -static MinMaxAvg query(const TimeSeriesData &series, uint32_t now, uint32_t start, uint32_t end) { - MinMaxAvg result; - series.calcMinMaxAvg(now, start, end, &result, 200, 116); - return result; -} - -TEST(TimeSeriesData, RingWrapKeepsNewestSamples) { - TimeSeriesData series(3, 10); - for (uint32_t i = 1; i <= 5; i++) - series.recordData(i * 10, float(i)); - auto result = query(series, 50, 100, 0); - EXPECT_FLOAT_EQ(result._min, 3); - EXPECT_FLOAT_EQ(result._max, 5); - EXPECT_FLOAT_EQ(result._avg, 4); - EXPECT_EQ(result._channel, 200); - EXPECT_EQ(result._lpp_type, 116); -} - -TEST(TimeSeriesData, RangeIncludesEndAndExcludesStart) { - TimeSeriesData series(4, 10); - series.recordData(10, -5); - series.recordData(20, -3); - series.recordData(30, -1); - series.recordData(40, 7); - auto result = query(series, 40, 30, 10); - EXPECT_FLOAT_EQ(result._min, -3); - EXPECT_FLOAT_EQ(result._max, -1); - EXPECT_FLOAT_EQ(result._avg, -2); -} - -TEST(TimeSeriesData, EmptyAndUnwrittenRangesReturnNaN) { - TimeSeriesData series(4, 10); - EXPECT_TRUE(std::isnan(query(series, 0, 100, 0)._avg)); - series.recordData(10, 4); - for (auto range : { std::pair(100, 1), { 0, 0 }, { 1, 10 } }) { - auto result = query(series, 10, range.first, range.second); - EXPECT_TRUE(std::isnan(result._min)); - EXPECT_TRUE(std::isnan(result._max)); - EXPECT_TRUE(std::isnan(result._avg)); - } -} - -TEST(TimeSeriesData, CadenceAndNaNSamples) { - float storage[3]; - TimeSeriesData series(storage, 3, 10); - series.recordData(uint32_t(0), 2); // uptime zero is a valid first sample - series.recordData(9, 100); - EXPECT_FLOAT_EQ(query(series, 9, 100, 0)._avg, 2); - series.recordData(10, 4); - series.recordData(19, 100); - series.recordData(20, NAN); - series.recordData(20, 6); - EXPECT_FLOAT_EQ(query(series, 20, 100, 0)._avg, 4); -} - -TEST(TimeSeriesData, LargeGapsExpireOldSamplesAndDoNotStall) { - TimeSeriesData series(4, 300); - series.recordData(300, 1); - const uint32_t later = UINT32_MAX / 300 * 300; - series.recordData(later, 3); - EXPECT_FLOAT_EQ(query(series, later, 301, 0)._avg, 3); - EXPECT_FLOAT_EQ(query(series, later, UINT32_MAX, 0)._avg, 3); - series.recordData(later + uint32_t(300), 5); // seconds counter wrap - auto result = query(series, later + uint32_t(300), 301, 0); - EXPECT_FLOAT_EQ(result._min, 3); - EXPECT_FLOAT_EQ(result._max, 5); - EXPECT_FLOAT_EQ(result._avg, 4); -} - -TEST(TimeSeriesData, MissingIntervalsAreEmptyInsteadOfMovingOldSamplesForward) { - TimeSeriesData series(5, 10); - series.recordData(10, 2); - series.recordData(40, 8); - EXPECT_TRUE(std::isnan(query(series, 40, 30, 1)._avg)); - EXPECT_FLOAT_EQ(query(series, 40, 31, 0)._avg, 5); - series.recordData(52, 10); // late read belongs to the fixed slot at 50 - EXPECT_FLOAT_EQ(query(series, 52, 3, 0)._avg, 10); - EXPECT_TRUE(std::isnan(query(series, 52, 2, 0)._avg)); -} - -TEST(TimeSeriesData, QueryAgeDoesNotOverflowWhileWalkingTheRing) { - TimeSeriesData series(3, 10); - series.recordData(10, 1); - series.recordData(20, 2); - EXPECT_TRUE(std::isnan(query(series, uint32_t(20 + (UINT32_MAX - 5)), 100, 0)._avg)); -} - -TEST(TimeSeriesData, LegacyClockAPIUsesMonotonicTimeAcrossRTCAndMillisWrap) { - class Clock : public mesh::RTCClock { - public: - uint32_t time = 100000; - int reads = 0; - uint32_t getCurrentTime() override { - reads++; - return time; - } - void setCurrentTime(uint32_t value) override { time = value; } - } clock; - TimeSeriesData series(3, 1); - g_mock_millis = UINT32_MAX - 499; - series.recordData(&clock, 2); - clock.setCurrentTime(0); - g_mock_millis = 500; - series.recordData(&clock, 4); - MinMaxAvg result; - series.calcMinMaxAvg(&clock, 2, 0, &result, 1, 116); - EXPECT_FLOAT_EQ(result._avg, 3); - EXPECT_EQ(clock.reads, 0); -} - -TEST(TimeSeriesData, MillisecondCounterWrapDoesNotResetSeconds) { - TimeSeriesData series(3, 1); - uint32_t last_millis = UINT32_MAX - 499; - uint64_t uptime_millis = last_millis; - series.recordData(uint32_t(uptime_millis / 1000), 1); - uint32_t now = 500; - uptime_millis += uint32_t(now - last_millis); - series.recordData(uint32_t(uptime_millis / 1000), 3); - EXPECT_FLOAT_EQ(query(series, uint32_t(uptime_millis / 1000), 2, 0)._avg, 2); -} - -TEST(TimeSeriesData, ZeroCapacityIsEmpty) { - TimeSeriesData series(0, 10); - series.recordData(100, 1); - EXPECT_TRUE(std::isnan(query(series, 100, 1000, 0)._avg)); -} - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} From 79e0f4eafe1c172bf6d6c11a22b8e760d93e8bdd Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 11 Nov 2026 07:58:39 -0400 Subject: [PATCH 08/14] gps_guard: remove time alert telemetry --- src/helpers/sensors/EnvironmentSensorManager.cpp | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 278677ded34..d038031b91f 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -1,9 +1,6 @@ #include "EnvironmentSensorManager.h" #include -#if ENV_INCLUDE_GPS && defined(GPS_GUARD) -#include -#endif #if ENV_PIN_SDA && ENV_PIN_SCL #define TELEM_WIRE &Wire1 // Use Wire1 as the I2C bus for Environment Sensors @@ -650,13 +647,6 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen _active_sensors[i].query(next_available_channel, _active_sensors[i].sub_channel, telemetry); next_available_channel++; } - #if ENV_INCLUDE_GPS && defined(GPS_GUARD) - // GPS-vs-clock offset in hours on its own channel while the guard's time alert is active - GpsGuard* guard = _location->getGuard(); - if (guard != nullptr && guard->isTimeAlert()) { - telemetry.addAnalogInput(next_available_channel++, guard->getAlertOffset() / 3600.0f); - } - #endif } return true; From bed72861924235a77fd71b6db0cc2e4902c112e4 Mon Sep 17 00:00:00 2001 From: Florent Date: Wed, 11 Nov 2026 09:52:03 -0400 Subject: [PATCH 09/14] CommonCLI: get/set loc to replace gps advert command --- docs/cli_commands.md | 6 +++++- src/helpers/CommonCLI.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 754f5120131..0a446e9cb97 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1101,6 +1101,8 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). #### View or change the GPS advert policy **Usage:** +- `get advert.loc` +- `set advert.loc ` - `gps advert` - `gps advert ` @@ -1108,10 +1110,12 @@ Covers serial NMEA receivers (`MicroNMEALocationProvider`). - `policy`: `none`|`share`|`prefs` - `none`: don't include location in adverts - `share`: share gps location (from SensorManager) - - `prefs`: location stored in node's lat and lon settings + - `prefs`: location stored in node's lat and lon settings (can be different from gps value) **Default:** `prefs` +**Note:** `gps advert` command is the old format but is only accessible when a gps is attached to the unit. It has been kept for compatibility but one should prefer using `get/set` commands instead. + --- ### Sensors (When sensor support is compiled in) diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 2c79bae16af..64fed99b34d 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -467,6 +467,22 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep savePrefs(); strcpy(reply, "OK"); } + } else if (memcmp(config, "advert.loc ", 11) == 0) { + if (memcmp(config+11, "none", 4) == 0) { + _prefs->advert_loc_policy = ADVERT_LOC_NONE; + savePrefs(); + strcpy(reply, "OK"); + } else if (memcmp(config+11, "share", 5) == 0) { + _prefs->advert_loc_policy = ADVERT_LOC_SHARE; + savePrefs(); + strcpy(reply, "OK"); + } else if (memcmp(config+11, "prefs", 5) == 0) { + _prefs->advert_loc_policy = ADVERT_LOC_PREFS; + savePrefs(); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Error, invalid policy"); + } } else if (memcmp(config, "guest.password ", 15) == 0) { StrHelper::strncpy(_prefs->guest_password, &config[15], sizeof(_prefs->guest_password)); savePrefs(); @@ -665,6 +681,20 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep sprintf(reply, "> %d", ((uint32_t) _prefs->flood_advert_interval)); } else if (memcmp(config, "advert.interval", 15) == 0) { sprintf(reply, "> %d", ((uint32_t) _prefs->advert_interval) * 2); + } else if (memcmp(config, "advert.loc", 10) == 0) { + switch (_prefs->advert_loc_policy) { + case ADVERT_LOC_NONE: + strcpy(reply, "> none"); + break; + case ADVERT_LOC_PREFS: + strcpy(reply, "> prefs"); + break; + case ADVERT_LOC_SHARE: + strcpy(reply, "> share"); + break; + default: + strcpy(reply, "Error, invalid policy"); + } } else if (memcmp(config, "guest.password", 14) == 0) { sprintf(reply, "> %s", _prefs->guest_password); } else if (sender_timestamp == 0 && memcmp(config, "prv.key", 7) == 0) { // from serial command line only From b920e7d249f945eaf351a619b7c4e97349aef265 Mon Sep 17 00:00:00 2001 From: Olexandr Tyshchenko Date: Wed, 11 Nov 2026 16:18:58 +0200 Subject: [PATCH 10/14] GPS guard: drop leftovers of the alert telemetry channel #3813 removed the telemetry channel for the GPS time alert. Remove the docs sentence that still described it and the now unused GpsGuard::getAlertOffset(). --- docs/cli_commands.md | 2 +- src/helpers/sensors/GpsGuard.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 469de260d1d..bc30adbd48c 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1085,7 +1085,7 @@ GPS time is written to the clock only while such a fix is current, never earlier Covers serial NMEA receivers (`MicroNMEALocationProvider`). **Usage:** -- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. While the alert is active, the offset in hours is also reported in telemetry on the next free channel. +- `gps guard`: status, e.g. `> ok 7sat time ok +1s`, `> rej region time rej nofix`, `> ok 7sat time wait` (last check passed, no current trusted fix to check again, e.g. GPS asleep between periodic fixes), or `... ALERT gps-clk +3600s 75m` when a trusted fix has disagreed with the clock by the same offset for `GPS_GUARD_ALERT_MIN` minutes. - `gps guard on`, `gps guard off`: turn the guard on or off (saved, default on). While off, every fix and GPS time is accepted and `gps guard` shows `off`. - `gps guard accept`: while an alert is active, confirm that the GPS time is right and apply it to the clock. - `gps fence`, `gps fence `: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved. diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index 66f4b92ff6a..46b1936caae 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -133,7 +133,6 @@ class GpsGuard { strcpy(_time_status, "-"); } bool isTimeAlert() const { return _time_alert; } - long getAlertOffset() const { return _time_disagree_offset; } // Fix as reported by the receiver: lat/lon in micro-degrees, HDOP in tenths (255 = unknown), // gps_time = UTC epoch of the fix. Returns true if the fix can be stored as trusted. From e1c1d76c5fd6943b26e65dc91545752480630bac Mon Sep 17 00:00:00 2001 From: nullrouten0 <201262769+nullrouten0@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:58:36 +0000 Subject: [PATCH 11/14] GPS: stop MicroNMEA reading past the NMEA buffer Add a 16-byte zeroed tail behind the 100-byte NMEA buffer. MicroNMEA's fixed-width field skips can read a few bytes past the end of a malformed sentence; with the tail those reads land on NUL bytes. Co-Authored-By: Claude Sonnet 5.5 --- src/helpers/sensors/MicroNMEALocationProvider.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index bc9f5efa764..09b4d955461 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -23,7 +23,12 @@ #endif class MicroNMEALocationProvider : public LocationProvider { - char _nmeaBuffer[100]; + // MicroNMEA never writes past the length it is given, but its fixed-width field + // skips can read a few bytes past the end of a malformed sentence. The zeroed tail + // lets those reads stop on NUL bytes instead of reading the members that follow. + static constexpr size_t NMEA_BUFFER_LEN = 100; + static constexpr size_t NMEA_BUFFER_TAIL = 16; + char _nmeaBuffer[NMEA_BUFFER_LEN + NMEA_BUFFER_TAIL] = {}; MicroNMEA nmea; mesh::RTCClock* _clock; NmeaGpsDriver* _driver; @@ -135,7 +140,7 @@ class MicroNMEALocationProvider : public LocationProvider { public: MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr) - : nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {} + : nmea(_nmeaBuffer, NMEA_BUFFER_LEN), _clock(clock), _driver(&driver) {} void begin() override { _begin_calls++; From e3c1c34828d38ab878546b95ab24fcce81cc6516 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Thu, 12 Nov 2026 16:08:30 +1300 Subject: [PATCH 12/14] fix for mdns string not compiling due to ambiguous overload --- examples/companion_radio/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index 367d7bfa73e..b6d6643d73a 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -299,7 +299,7 @@ void setup() { MDNS.addServiceTxt("meshcore", "tcp", "firmware-version", FIRMWARE_VERSION); char protocol[12]; snprintf(protocol, sizeof(protocol), "%d", (int)FIRMWARE_VER_CODE); - MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol); + MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", (const char*)protocol); MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__); MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__); } From 275c56e9e26a6f481bdc9f382f81736aeef3c49b Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Thu, 12 Nov 2026 19:25:53 +0100 Subject: [PATCH 13/14] docs: advert.loc in the CLI table doc, GPS_BAUD_PROBE_LIST default in the E2a doc --- docs/refactoring/0011-variant-target.md | 3 +++ docs/refactoring/0013-cli-command-table.md | 8 +++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/refactoring/0011-variant-target.md b/docs/refactoring/0011-variant-target.md index d6892c62713..53a8e22efa7 100644 --- a/docs/refactoring/0011-variant-target.md +++ b/docs/refactoring/0011-variant-target.md @@ -2146,6 +2146,9 @@ New macros in `target.h`, inside nothing (the GPS lines are not under `DISPLAY_C `&board.periph_power`. - `GPS_BAUD_PROBE_LIST` (promicro, B): already a macro in the ini; the shared file reads it as `target.cpp` does today. + Since upstream #3798 (sync of 12.11.) `NmeaGpsDriver` reads the macro itself as the default + of its constructor, so `promicro` no longer needs the special case and the shared file + needs none either. - The type of `sensors` is not a new field: `target.h` already says `extern EnvironmentSensorManager sensors;`, and `decltype(sensors) sensors(nmea);` defines exactly that type. Checked to compile with `g++ -std=gnu++11 -c` on a stand-in (a diff --git a/docs/refactoring/0013-cli-command-table.md b/docs/refactoring/0013-cli-command-table.md index 44dd9f0707d..c0f71000ee1 100644 --- a/docs/refactoring/0013-cli-command-table.md +++ b/docs/refactoring/0013-cli-command-table.md @@ -125,6 +125,7 @@ falls through to the next branch and, in the end, to "Unknown command". | `allow.read.only` | `OK` | on if the value starts with `on`, save | | | `flood.advert.interval` | `OK` or `Error: interval range is 3-168 hours` | hours, `updateFloodAdvertTimer`, save | 0 allowed (off); 1 and 2 are errors | | `advert.interval` | `OK` or `Error: interval range is 60-240 minutes` | stored as minutes / 2, `updateAdvertTimer`, save | 0 allowed; see quirk on zeroing | +| `advert.loc` | `OK` or `Error, invalid policy` | `none`, `share` or `prefs` (prefix match) to `advert_loc_policy`, save | upstream #3815; all builds, unlike `gps advert` | | `guest.password` | `OK` | 15 characters, save | no echo | | `prv.key` | `OK, reboot to apply! New pubkey: ` or `Error, bad key` | `saveIdentity(new id)` | accepted over the air; valid keys only | | `name` | `OK` or `Error, bad chars` | 31 characters, save | longer names are cut without an error | @@ -148,7 +149,8 @@ falls through to the next branch and, in the end, to "Unknown command". ### `get ` All replies start with `> `. Keys: `allow.read.only` (on or off), -`flood.advert.interval`, `advert.interval` (minutes), `guest.password`, `prv.key` +`flood.advert.interval`, `advert.interval` (minutes), `advert.loc` (`> none|prefs|share` +or `Error, invalid policy`), `guest.password`, `prv.key` (ts 0, uppercase hex), `name`, `repeat`, `lat`, `lon`, `flood.max.type` (`> grpdata:4 trace:3`, `> none` when empty, unnamed types as numbers), `flood.max.advert`, `flood.max.unscoped`, `flood.max`, `owner.info` (newline shown as `|`, cut at 159 @@ -184,8 +186,8 @@ single precision noise (`869.6179809` for 869.618). | File | Tests | Covers | |---|---|---| | `test_cli_commands.cpp` | 47 | dispatch order, board hook, prefix quirks, power, clock, advert, neighbors, tempradio, password, erase, ver, board, powersaving, log, stats, routing | -| `test_cli_set.cpp` | 49 | every `set` key, ranges, truncation, the zeroing in `savePrefs`, radio precedence, bridge and `extra.sf` variants | -| `test_cli_get.cpp` | 24 | every `get` key, prefix order, hex output, variants, fallback | +| `test_cli_set.cpp` | 52 | every `set` key, ranges, truncation, the zeroing in `savePrefs`, radio precedence, bridge and `extra.sf` variants | +| `test_cli_get.cpp` | 25 | every `get` key, prefix order, hex output, variants, fallback | | `test_cli_region.cpp` | 34 | every `region` sub command, limits, errors, callbacks | | `test_cli_sensor.cpp` | 39 | `sensor get\|set\|list` with paging, `gps ...` (GPS build) or "Unknown command" (others) | | `test_cli_flood_type.cpp` | 19 | `set` and `get flood.max.type`: names and numbers, sorted list, `off`, range and type errors, damaged stored list, full list | From 6f781cc4f0a6b3c80d09908e0aace89c4c16ce87 Mon Sep 17 00:00:00 2001 From: Marcel Verdult Date: Thu, 12 Nov 2026 19:25:53 +0100 Subject: [PATCH 14/14] docs: note for the upstream/dev sync of 12.11.2026 --- .../refactoring/sync-upstream-dev-20261112.md | 128 ++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 docs/refactoring/sync-upstream-dev-20261112.md diff --git a/docs/refactoring/sync-upstream-dev-20261112.md b/docs/refactoring/sync-upstream-dev-20261112.md new file mode 100644 index 00000000000..f7054a8d67e --- /dev/null +++ b/docs/refactoring/sync-upstream-dev-20261112.md @@ -0,0 +1,128 @@ +# Sync upstream/dev into integration (12.11.2026) + +Merge of `upstream/dev` bb870313 (24 commits since the last sync base b8ae75d2) into +`integration` 5e32b39d, branch `claude/sync-upstream-dev-20261112-cdc32f`. The merge is a +signed merge commit (no rebase, no squash). Nothing is pushed and nothing is merged into +`integration`. + +## What upstream brought + +- GPS: #3798 `GPS_BAUD_PROBE_LIST` as a build flag for any `NmeaGpsDriver` (the constructor + default now reads it; enabled on Station G2 and G3), #3801 GPS guard shows `time wait` + instead of `rej nofix` between fixes, #3813 and #3817 drop the guard's alert telemetry + channel (`getAlertOffset()` and the `querySensors` code are gone), #3819 MicroNMEA no + longer reads past its buffer (16 zeroed tail bytes). +- #3815 CLI `get advert.loc` and `set advert.loc `, usable without a GPS; + `gps advert` stays for GPS builds. +- #3807 stack-buffer overflow fix in CLI reply buffers (touches the three `MyMesh.cpp`). +- #3811 and #3822 mDNS name built without `String` (`examples/companion_radio/main.cpp`). +- #3784 repeater history queries and its revert #3812 (net effect in this range: none). +- 0147165b reverts the rak13302 tests: `test/test_rak3401_board_startup/`, + `test/test_rak3401_onboard_radio/` and `[env:native_rak3401_onboard_radio]` are gone. + +## Probe and merge + +`git merge-tree --write-tree --name-only HEAD upstream/dev` listed 3 conflict files. The +merge commit is 66ab992a (signed, `gpgsig` present in the commit object). + +## Conflicts and how they were solved + +- `src/helpers/CommonCLI.cpp`: upstream put `advert.loc` into the old `else if` chains of + `handleSetCmd` and `handleGetCmd`, which the fork replaced with the tables of step 13. + The fork side stays. `advert.loc` is now `CommonCLIImpl::setAdvertLoc` / `getAdvertLoc` + and one row in `kSetCmds` (`"advert.loc "`) and one in `kGetCmds` (`"advert.loc"`), placed + before `guest.password`. Not gated by `ENV_INCLUDE_GPS`, as upstream. Replies are + upstream's (`OK`, `Error, invalid policy`, `> none|prefs|share`). Neither name is a prefix + of another row, so the order does not matter. Tests in the harness of 13a (`CliTest`): + `SetAdvertLocTakesEachPolicyAndSaves`, `SetAdvertLocWithAnUnknownPolicyAnswersErrorAndChangesNothing`, + `SetAdvertLocNeedsItsTrailingSpaceAndKeepsAdvertIntervalApart` in `test_cli_set.cpp`, + `GetAdvertLocShowsThePolicy` in `test_cli_get.cpp`. They run in the five `native_common_cli*` + environments (+4 cases each). +- `platformio.ini`: upstream shortened `test_ignore` to `test_kiss_modem`; the fork keeps its + long list and drops only `test_rak3401_board_startup`. The merge removed + `[env:native_rak3401_onboard_radio]`. +- `.github/workflows/run-unit-tests.yml`: the fork's `pio test` line without + `-e native_rak3401_onboard_radio` (27 environments). + +Silent collisions, checked and fine: + +- E2a (`VariantTarget.cpp`, `SENSORS_TARGET_GLOBALS`): the shared `NmeaGpsDriver gps_driver(Serial1);` + now picks up `GPS_BAUD_PROBE_LIST` through the constructor default of #3798. Station G2 and + G3 use the shared block and define the flag, so they get the probe list without a line of + their own. Measured on the built images: `NMEA_GPS_PROBE_BAUDS` is a symbol in + `Station_G2_repeater`, and the byte triple 9600, 115200, 38400 is in the firmware of + `Station_G2_repeater` and `Station_G3_ESP32_repeater`, not in `Heltec_v3_repeater`. +- `variants/promicro/target.cpp` (group B, own `target.cpp`): auto-merged to the plain + `NmeaGpsDriver gps_driver(Serial1);`; upstream dropped the local probe-list branch because + the driver reads the flag itself. `docs/refactoring/0011-variant-target.md` says so now. +- `EnvironmentSensorManager.cpp`: upstream removed the guard alert telemetry; the fork's + `GpsGuard`/GPS code from the 10.11. sync is not touched. `getAlertOffset`, `rej nofix` + appear nowhere else in the tree (grep over `*.cpp`, `*.h`, `*.ini`; `docs/cli_commands.md` + mentions both and was updated by upstream). + +## Docs + +`0013-cli-command-table.md`: `advert.loc` row in the set table, `advert.loc` in the key list of +the get section, test counts for `test_cli_set.cpp` (52) and `test_cli_get.cpp` (25). + +## Checks + +Native, the environments of `run-unit-tests.yml`, one by one with `pio test -e `, exit +code 0 each. + +| | Environments | Cases | Succeeded | Skipped | Failed | +|---|---|---|---|---|---| +| before the merge (5e32b39d) | 28 | 2447 | 2446 | 1 (`native_radio_chips`) | 0 | +| after the merge | 27 | 2456 | 2455 | 1 (`native_radio_chips`) | 0 | + +Difference: the reverted rak13302 tests (4 cases in `native`, 7 in the removed environment) +and the 20 new `advert.loc` cases (4 in each of the five `native_common_cli*`). +`native` 143 to 139, `native_common_cli` 185 to 189, `_esp32` 185 to 189, `_espnow` 193 to +197, `_nrf52` 198 to 202, `_rs232` 192 to 196; all other environments unchanged. + +Firmware: 19 environments, `SOURCE_DATE_EPOCH=1760000000`, merged tree. Not the 211 of +`sync-build-envs.txt` (see open points). Chosen for what the merge touches: E2a variants with +and without the probe list (Station G2 and G3, Heltec V3, V4, V4 R8, tracker V2, T096, +ProMicro), all three mDNS code paths (WiFi companions), CommonCLI on every platform (nRF52, +ESP32, RP2040). + +| Env | RAM | Flash | Result | +|---|---|---|---| +| Station_G2_repeater | 74968 | 1218873 | builds | +| Station_G2_companion_radio_wifi | 184800 | 1153665 | builds | +| Station_G2_companion_radio_ble | 184420 | 1333341 | link error, flash too big (max 1310720) | +| Station_G3_ESP32_repeater | 74976 | 1220477 | builds | +| Station_G3_ESP32_companion_radio_ble | 184428 | 1335009 | link error, flash too big | +| Heltec_v3_repeater | 62768 | 1186005 | builds | +| heltec_v4_repeater | 62740 | 1184149 | builds | +| heltec_v4_companion_radio_wifi | 174492 | 1145681 | builds | +| heltec_v4_r8_repeater | 62656 | 1187681 | builds | +| heltec_tracker_v2_repeater | 74608 | 1237145 | builds | +| Heltec_t096_repeater | 35828 | 432632 | builds | +| RAK_4631_repeater | 37664 | 468524 | builds | +| RAK_4631_companion_radio_ble | 150160 | 492368 | builds | +| ProMicro_repeater | 34156 | 364304 | builds | +| ThinkNode_M1_companion_radio_ble | 151680 | 384564 | builds | +| t1000e_repeater | 33116 | 311128 | builds | +| t1000e_companion_radio_usb | 141396 | 321076 | builds | +| MeshTracker_X1_repeater | 33196 | 318608 | builds | +| PicoW_repeater | 85484 | 532216 | builds | + +The two BLE companions that fail are not caused by this merge. The same two environments +built the same way overflow on `integration` 5e32b39d (`Station_G3_ESP32_companion_radio_ble` +1334945, `Station_G2_companion_radio_ble` 1333265) and `Station_G3_ESP32_companion_radio_ble` +on `upstream/dev` bb870313 (1327237) as well. The merge adds 64 bytes (G3) and 76 bytes (G2) +over `integration`. Caveat: the libdeps of these builds were seeded from existing +`.pio/libdeps` directories to stay under the PlatformIO registry limit (no integrity file), +so absolute sizes may differ from a fresh CI build. Whether the images overflow with freshly +resolved libraries is NOT VERIFIED. The fork premium over `upstream/dev` for +`Station_G3_ESP32_companion_radio_ble` is +7772 bytes, in the range of the 10.11. sync. + +## Open points, NOT VERIFIED + +- Not built: 192 of the 211 environments of `sync-build-envs.txt`, no size comparison against + `upstream/dev` except the one environment above. +- No board run, no image flashed: probe-list baud detection on Station G2/G3 with a Grove + GPS at 115200, the `time wait` guard status, the mDNS name on a device. +- No host test for `get/set advert.loc` outside the CLI harness, none for the GPS guard, + `NmeaGpsDriver` probe list or the MicroNMEA buffer tail (#3819).