diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index f8145ecd..5d48f4c6 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/boards/heltec-rc52.json b/boards/heltec-rc52.json new file mode 100644 index 00000000..404aac19 --- /dev/null +++ b/boards/heltec-rc52.json @@ -0,0 +1,61 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x8071"], + ["0x239A", "0x0071"], + ["0x239A", "0x8072"] + ], + "usb_product": "HT-n5262", + "mcu": "nrf52840", + "variant": "heltec_rc52", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": [ + "bluetooth", + "lora" + ], + "debug": { + "jlink_device": "nRF52840_xxAA", + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52.cfg" + }, + "frameworks": [ + "arduino" + ], + "name": "Heltec RC52", + "upload": { + "maximum_ram_size": 237568, + "maximum_size": 815104, + "speed": 115200, + "protocol": "nrfutil", + "protocols": [ + "jlink", + "nrfjprog", + "nrfutil", + "stlink" + ], + "use_1200bps_touch": true, + "require_upload_port": true, + "wait_for_upload_port": true + }, + "url": "https://heltec.org/", + "vendor": "Heltec" +} diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 1488c646..7bd0e3ac 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -1026,7 +1026,21 @@ region save **Parameters:** - `value`: `0` for continuous tracking, or a period. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default). -**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. +**Note:** A periodic acquisition stops after receiving a valid fix, then resumes after the configured period. Without a fix it stops after 5 minutes (`GPS_PERIODIC_ACQUISITION_TIMEOUT_MS`), or, until the first fix since boot, after the first fix timeout (see `gps firstfix`). + +--- + +#### View or change the first fix timeout +**Usage:** +- `gps firstfix` +- `gps firstfix ` + +**Parameters:** +- `value`: `0` for no limit, or a duration up to `1d`. The value can be postfixed with `s`, `m`, `h` or `d` to specify the unit (seconds by default). + +**Default:** `1h` (`GPS_FIRST_FIX_TIMEOUT_MS`) + +**Note:** In periodic mode, limits an acquisition until the first valid fix since boot. A cold start can take much longer than the usual 5 minutes with a weak sky view; after the limit the GPS sleeps for the period and tries again. Saved with the other GPS settings. --- @@ -1085,7 +1099,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. - `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. @@ -1101,6 +1115,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 +1124,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) @@ -1247,13 +1265,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/companion_cli.md b/docs/companion_cli.md index 87d94b55..212eb905 100644 --- a/docs/companion_cli.md +++ b/docs/companion_cli.md @@ -413,6 +413,18 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`. --- +#### Change BLE name +**Usage:** +- `get ble.name` +- `set ble.name ` + +**Parameters:** +- `name`: New BLE name + +**Note:** By default the BLE name is `Meshcore-` followed by the node name. If `` is empty the BLE name will be reset to the aforementioned default. These commands require a reboot to take effect. + +--- + ### Wifi #### Get status diff --git a/docs/payloads.md b/docs/payloads.md index c60a78d6..493f628c 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 35b37d82..00000000 --- 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/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 1a1bcbe7..cd6966e8 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -2154,6 +2154,30 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char* sprintf(reply, "> pin is now %06d", _prefs.ble_pin); return true; } + if (strcmp(command, "set ble.name") == 0) { + _prefs.ble_name[0] = 0; + savePrefs(); + sprintf(reply, "> BLE name reset to %s%s (reboot to apply)", BLE_NAME_PREFIX, _prefs.node_name); + return true; + } + if (memcmp(command, "set ble.name ", 13) == 0) { + if (AdvertDataParser::isValidName(&command[13])) { + StrHelper::strncpy(_prefs.ble_name, &command[13], sizeof(_prefs.ble_name)); + savePrefs(); + sprintf(reply, "> BLE name is now %s (reboot to apply)", _prefs.ble_name); + } else { + strcpy(reply, "Error, bad chars"); + } + return true; + } + if (strcmp(command, "get ble.name") == 0) { + if (_prefs.ble_name[0]) { + sprintf(reply, "> %s", _prefs.ble_name); + } else { + sprintf(reply, "> %s%s", BLE_NAME_PREFIX, _prefs.node_name); + } + return true; + } #ifdef ENABLE_WIFI_INTERFACE if (memcmp(command, "set wifi.ssid ", 14) == 0) { diff --git a/examples/companion_radio/NodePrefs.h b/examples/companion_radio/NodePrefs.h index c5387976..9150cccc 100644 --- a/examples/companion_radio/NodePrefs.h +++ b/examples/companion_radio/NodePrefs.h @@ -31,6 +31,7 @@ public: float tx_delay_factor = 0; float direct_tx_delay_factor = 0; uint32_t ble_pin = 0; + char ble_name[32] = {0}; uint8_t advert_loc_policy = 0; uint8_t buzzer_quiet = 0; uint8_t vibe_quiet = 0; @@ -38,6 +39,7 @@ public: uint32_t gps_interval = 0; // GPS read interval in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default + int32_t gps_first_fix = -1; // first-fix timeout in seconds, 0 = no limit, -1 = build default uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t autoadd_config = 0; // bitmask for auto-add contacts config uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted) @@ -169,6 +171,7 @@ private: def("int", _parent->gps_interval); // interval in seconds def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); + def("ffix", _parent->gps_first_fix); #ifdef GPS_GUARD def("fence", _parent->gps_fence); def("guard", _parent->gps_guard); @@ -180,6 +183,12 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getFirstFixTimeout(uint32_t& seconds) const override { + if (_parent->gps_first_fix < 0) return false; + seconds = (uint32_t)_parent->gps_first_fix; + return true; + } + void setFirstFixTimeout(uint32_t seconds) override { _parent->gps_first_fix = (int32_t)seconds; markDirty(); } bool getGuardFence(uint32_t& metres) const override { if (_parent->gps_fence < 0) return false; metres = (uint32_t)_parent->gps_fence; @@ -216,6 +225,7 @@ private: def("defs_nm", _parent->default_scope_name, sizeof(_parent->default_scope_name)); def("defs_key", (void *) _parent->default_scope_key, sizeof(_parent->default_scope_key)); def("pin", _parent->ble_pin); + def("ble_name", _parent->ble_name, sizeof(_parent->ble_name)); def("buzz_q", _parent->buzzer_quiet); def("vibe_q", _parent->vibe_quiet); def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config diff --git a/examples/companion_radio/main.cpp b/examples/companion_radio/main.cpp index c534772c..3e7ec6dc 100644 --- a/examples/companion_radio/main.cpp +++ b/examples/companion_radio/main.cpp @@ -215,7 +215,13 @@ void setup() { // add bluetooth interface #if defined(BLE_PIN_CODE) - bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); + char *prefix = BLE_NAME_PREFIX; + char *ble_name = the_mesh.getNodePrefs()->node_name; + if (the_mesh.getNodePrefs()->ble_name[0]) { + prefix = ""; + ble_name = the_mesh.getNodePrefs()->ble_name; + } + bluetooth_interface.begin((const char *) prefix, ble_name, the_mesh.getBLEPin()); interface_manager.addInterface(InterfaceType::Bluetooth, &bluetooth_interface); #endif @@ -276,27 +282,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", (const char*)protocol); MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__); MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__); } diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 99cd35bb..21f833a5 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]; @@ -779,7 +730,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) { @@ -911,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), @@ -932,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; @@ -1348,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 @@ -1427,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 f30eedd0..7e4cfd4f 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_room_server/MyMesh.cpp b/examples/simple_room_server/MyMesh.cpp index b1a88dd8..c1a6b09f 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 bb747f63..4916ddcd 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); @@ -789,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; @@ -1001,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)) { @@ -1033,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 @@ -1075,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 f1431f6f..e6746d47 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 @@ public: 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 @@ private: 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 00000000..f6157f9a --- /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 41bf3189..6efa7834 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 6d455f73..66991daa 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -21,14 +21,13 @@ protected: 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 c33105c9..f66fbf2e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -168,26 +168,15 @@ 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> +<../src/Packet.cpp> +<../src/helpers/ConfigSerializer.cpp> +<../src/helpers/DynamicConfigSerializer.cpp> - +<../src/helpers/TimeSeriesData.cpp> 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/src/Identity.cpp b/src/Identity.cpp index 51a01ae7..045fe097 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -7,6 +7,10 @@ #ifdef USE_CC310_HW_CRYPTO #include #include "nrf_cc310/include/crys_ec_edw_api.h" +#include "nrf_cc310/include/ssi_pal_mutex.h" +extern "C" { + extern SaSi_PalMutex sasiAsymCryptoMutex; +} #endif namespace mesh { @@ -30,6 +34,13 @@ bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) c CRYSError_t rc = CRYS_ECEDW_Verify((uint8_t*)sig, CRYS_ECEDW_SIGNATURE_BYTES, (uint8_t*)pub_key, CRYS_ECEDW_MOD_SIZE_IN_BYTES, (uint8_t*)message, (size_t)msg_len, &cc310_tmp); + + // workaround for CC310 v0.9.13 where mutex can still be locked after a failed verification + if (rc != CRYS_OK && sasiAsymCryptoMutex != 0) { + MESH_DEBUG_PRINTLN("CRYS_ECEDW_Verify mutex still locked after error result, unlocking"); + SaSi_PalMutexUnlock(&sasiAsymCryptoMutex); + } + return rc == CRYS_OK; #elif 0 // NOTE: memory corruption bug was found in this function!! diff --git a/src/helpers/BaseChatMesh.cpp b/src/helpers/BaseChatMesh.cpp index 4368d17f..58c08dea 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; diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 2c79bae1..64fed99b 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 diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index cb85f6f9..24b1fe26 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -64,6 +64,7 @@ public: uint32_t gps_interval = 0; // in seconds uint32_t gps_period = 0; // periodic acquisition interval in seconds int32_t gps_fence = -1; // GPS_GUARD fence in metres, 0 = off, -1 = build default + int32_t gps_first_fix = -1; // first-fix timeout in seconds, 0 = no limit, -1 = build default uint8_t gps_guard = 1; // GPS_GUARD on/off uint8_t advert_loc_policy = 0; uint32_t discovery_mod_timestamp = 0; @@ -164,6 +165,7 @@ private: def("int", _parent->gps_interval); // interval in seconds def("period", _parent->gps_period); // periodic acquisition interval in seconds def("adv_loc", _parent->advert_loc_policy); + def("ffix", _parent->gps_first_fix); #ifdef GPS_GUARD def("fence", _parent->gps_fence); def("guard", _parent->gps_guard); @@ -175,6 +177,12 @@ private: void setGpsEnabled(bool enabled) override { _parent->gps_enabled = enabled; markDirty(); } uint32_t getGpsPeriod() const override { return _parent->gps_period; } void setGpsPeriod(uint32_t seconds) override { _parent->gps_period = seconds; markDirty(); } + bool getFirstFixTimeout(uint32_t& seconds) const override { + if (_parent->gps_first_fix < 0) return false; + seconds = (uint32_t)_parent->gps_first_fix; + return true; + } + void setFirstFixTimeout(uint32_t seconds) override { _parent->gps_first_fix = (int32_t)seconds; markDirty(); } bool getGuardFence(uint32_t& metres) const override { if (_parent->gps_fence < 0) return false; metres = (uint32_t)_parent->gps_fence; diff --git a/src/helpers/CommonGpsPrefs.cpp b/src/helpers/CommonGpsPrefs.cpp index cdc889d0..d9768fe1 100644 --- a/src/helpers/CommonGpsPrefs.cpp +++ b/src/helpers/CommonGpsPrefs.cpp @@ -46,6 +46,8 @@ bool CommonGpsPrefs::apply(SensorManager& sensors) const { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) return false; applyGuardReference(sensors); + uint32_t first_fix; + if (getFirstFixTimeout(first_fix)) location->setFirstFixTimeout(first_fix); location->setGpsPeriod(getGpsPeriod()); location->setGpsOn(isGpsEnabled()); return true; @@ -62,6 +64,20 @@ static void formatDuration(char* buf, size_t size, uint32_t seconds) { } } +// "[s|m|h|d]", seconds by default +static bool parseDuration(const char* text, uint32_t& seconds) { + char* end; + unsigned long value = strtoul(text, &end, 10); + unsigned long mult = 1; + if (*end == 'm') mult = 60; + else if (*end == 'h') mult = 3600; + else if (*end == 'd') mult = 86400; + if (mult > 1 || *end == 's') end++; // skip the suffix char + if (text[0] == '\0' || *end != '\0') return false; + seconds = (uint32_t)(value * mult); + return true; +} + bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) { if (strcmp(command, "gps") == 0) { LocationProvider* location = sensors.getLocationProvider(); @@ -180,17 +196,10 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, return true; } if (memcmp(command, "gps period ", 11) == 0) { - char* end; - unsigned long period = strtoul(command + 11, &end, 10); - unsigned long mult = 1; - if (*end == 'm') mult = 60; - else if (*end == 'h') mult = 3600; - else if (*end == 'd') mult = 86400; - if (mult > 1 || *end == 's') end++; // skip the suffix char - - if (command[11] == '\0' || *end != '\0') { + uint32_t period; + if (!parseDuration(command + 11, period)) { strcpy(reply, "Error, invalid gps period"); - } else if (!setGpsPeriod(sensors, (uint32_t)(period * mult)) || + } else if (!setGpsPeriod(sensors, period) || !setGpsEnabled(sensors, true)) { strcpy(reply, "Error, gps provider not found"); } else { @@ -198,6 +207,31 @@ bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, } return true; } + if (strcmp(command, "gps firstfix") == 0) { + LocationProvider* location = sensors.getLocationProvider(); + if (location == nullptr) { + strcpy(reply, "Error, gps provider not found"); + } else if (location->getFirstFixTimeout() == 0) { + strcpy(reply, "> 0 (no limit)"); + } else { + sprintf(reply, "> %lu", (unsigned long)location->getFirstFixTimeout()); + } + return true; + } + if (memcmp(command, "gps firstfix ", 13) == 0) { + LocationProvider* location = sensors.getLocationProvider(); + uint32_t seconds; + if (location == nullptr) { + strcpy(reply, "Error, gps provider not found"); + } else if (!parseDuration(command + 13, seconds) || seconds > 86400UL) { // at most a day + strcpy(reply, "Error, invalid first fix timeout"); + } else { + location->setFirstFixTimeout(seconds); + setFirstFixTimeout(seconds); // saved by the caller (isDirty) + strcpy(reply, "OK"); + } + return true; + } if (memcmp(command, "gps sync", 8) == 0) { LocationProvider* location = sensors.getLocationProvider(); if (location == nullptr) { diff --git a/src/helpers/CommonGpsPrefs.h b/src/helpers/CommonGpsPrefs.h index c1e30b8e..5502cba8 100644 --- a/src/helpers/CommonGpsPrefs.h +++ b/src/helpers/CommonGpsPrefs.h @@ -18,6 +18,9 @@ public: virtual void setGpsEnabled(bool enabled) = 0; virtual uint32_t getGpsPeriod() const = 0; virtual void setGpsPeriod(uint32_t seconds) = 0; + // Saved first-fix timeout in seconds; false = not set, use the build default. + virtual bool getFirstFixTimeout(uint32_t& seconds) const { return false; } + virtual void setFirstFixTimeout(uint32_t seconds) { } // Reference position for the anti-spoofing guard (GPS_GUARD), e.g. the configured node position. virtual bool getGuardReference(double& lat, double& lon) const { return false; } diff --git a/src/helpers/TimeSeriesData.cpp b/src/helpers/TimeSeriesData.cpp deleted file mode 100644 index 371433c6..00000000 --- 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 3b7cdd47..00000000 --- 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/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index 278677de..d038031b 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; diff --git a/src/helpers/sensors/GpsGuard.h b/src/helpers/sensors/GpsGuard.h index cf713033..46b1936c 100644 --- a/src/helpers/sensors/GpsGuard.h +++ b/src/helpers/sensors/GpsGuard.h @@ -133,7 +133,6 @@ public: 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. @@ -280,16 +279,17 @@ public: 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)); diff --git a/src/helpers/sensors/LocationProvider.h b/src/helpers/sensors/LocationProvider.h index 5b5b69c0..218e9ad6 100644 --- a/src/helpers/sensors/LocationProvider.h +++ b/src/helpers/sensors/LocationProvider.h @@ -18,6 +18,7 @@ public: long satellites = 0; long timestamp = 0; unsigned long acquiredAt = 0; // millis() when the fix was stored + uint8_t fixMode = 0; // from GSA: 2 = 2D, 3 = 3D, 0 = unknown }; struct FixStats { @@ -81,6 +82,9 @@ public: } virtual void setGpsPeriod(uint32_t seconds) { } virtual uint32_t getGpsPeriod() const { return 0; } + // periodic mode: limit of an acquisition before the first fix since boot, 0 = no limit + virtual void setFirstFixTimeout(uint32_t seconds) { } + virtual uint32_t getFirstFixTimeout() const { return 0; } virtual uint32_t getLastFixAge() const { // in seconds, UINT32_MAX if never const LastFix f = getLastFix(); return f.valid ? (uint32_t)(millis() - f.acquiredAt) / 1000UL : UINT32_MAX; diff --git a/src/helpers/sensors/MicroNMEALocationProvider.h b/src/helpers/sensors/MicroNMEALocationProvider.h index bc9f5efa..85262ba4 100644 --- a/src/helpers/sensors/MicroNMEALocationProvider.h +++ b/src/helpers/sensors/MicroNMEALocationProvider.h @@ -12,6 +12,12 @@ #ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS #define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL #endif +// default limit for the periodic window before the first fix since boot (a cold start +// can take up to ~30 min with a weak sky view); 0 = keep searching until a fix. +// Can be changed at runtime with `gps firstfix`. +#ifndef GPS_FIRST_FIX_TIMEOUT_MS + #define GPS_FIRST_FIX_TIMEOUT_MS 3600000UL +#endif // in periodic mode, keep reading after the first valid fix until enough satellites // are used or the settle time has elapsed @@ -22,8 +28,18 @@ #define GPS_FIX_SETTLE_MS 10000UL #endif +// a 2D fix does not replace a 3D fix younger than this (it is less precise) +#ifndef GPS_3D_FIX_PREFERRED_MS + #define GPS_3D_FIX_PREFERRED_MS 300000UL +#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; @@ -31,9 +47,11 @@ class MicroNMEALocationProvider : public LocationProvider { long time_valid = 0; unsigned long _last_time_sync = 0; uint32_t _gpsPeriodSeconds = 0; + uint32_t _firstFixTimeoutSeconds = GPS_FIRST_FIX_TIMEOUT_MS / 1000UL; unsigned long _nextAcquisition = 0; unsigned long _acquisitionStarted = 0; unsigned long _firstFixInWindow = 0; + bool _goodFixInWindow = false; // a fix that lets the GPS sleep (3D, or fix mode unknown) bool _acquiringPeriodically = false; unsigned long _onceDeadline = 0; static const unsigned long TIME_SYNC_INTERVAL = 1800000; @@ -47,6 +65,26 @@ class MicroNMEALocationProvider : public LocationProvider { unsigned long _last_nmea_ms = 0; bool _uart_seen = false; bool _nmea_seen = false; + uint8_t _gsa_fix_mode = 0; // fix mode from the last GSA: 1 = none, 2 = 2D, 3 = 3D + unsigned long _gsa_ms = 0; + + static bool isGsa(const char* id) { // GPGSA, GNGSA, BDGSA, ... + const size_t n = strlen(id); + return n >= 3 && strcmp(id + n - 3, "GSA") == 0; + } + // $--GSA,,,... + void parseGsa(const char* s) { + s = strchr(s, ','); + if (s != NULL) s = strchr(s + 1, ','); + if (s != NULL && s[1] >= '1' && s[1] <= '3') { + _gsa_fix_mode = s[1] - '0'; + _gsa_ms = millis(); + } + } + // 0 (unknown) if the receiver does not send GSA, or sent none recently + uint8_t currentFixMode() const { + return (_gsa_fix_mode != 0 && (uint32_t)(millis() - _gsa_ms) <= 2000) ? _gsa_fix_mode : 0; + } #ifdef GPS_GUARD GpsGuard _guard; #endif @@ -71,6 +109,7 @@ class MicroNMEALocationProvider : public LocationProvider { _acquiringPeriodically = true; _acquisitionStarted = millis(); _firstFixInWindow = 0; + _goodFixInWindow = false; } void finishPeriodicAcquisition() { @@ -84,13 +123,17 @@ class MicroNMEALocationProvider : public LocationProvider { bool saveFix() { // only store a fix when the snapshot is coherent (sats > 0). - // Returns true if the fix was stored. + // Returns true if the fix was accepted (stored, or kept out by a recent 3D fix). if (nmea.getNumSatellites() == 0) return false; #ifdef GPS_GUARD // only plausible, stable fixes become the last fix (position, telemetry, time sync) if (!_guard.acceptFix(nmea.getLatitude(), nmea.getLongitude(), nmea.getNumSatellites(), nmea.getHDOP(), getTimestamp())) return false; #endif + const uint8_t mode = currentFixMode(); + // a 2D fix is valid but less precise: keep a recent 3D fix instead + if (mode == 2 && _lastFix.valid && _lastFix.fixMode == 3 && + (uint32_t)(millis() - _lastFix.acquiredAt) < GPS_3D_FIX_PREFERRED_MS) return true; LastFix fix; fix.latitude = nmea.getLatitude(); @@ -102,6 +145,7 @@ class MicroNMEALocationProvider : public LocationProvider { fix.satellites = nmea.getNumSatellites(); fix.timestamp = getTimestamp(); fix.acquiredAt = millis(); + fix.fixMode = mode; fix.valid = true; _lastFix = fix; return true; @@ -125,6 +169,12 @@ class MicroNMEALocationProvider : public LocationProvider { if (isValid()) time_valid++; } + // the time sync has had its chance: done, not needed, or refused by GPS_GUARD. + // updateTime() tries it on the tick where time_valid goes from 3 to 4. + bool timeSyncSettled() const { + return _clock == nullptr || !_time_sync_needed || time_valid > 3; + } + bool timeSyncAllowed() { #ifdef GPS_GUARD return _guard.acceptTime(getTimestamp(), _clock->getCurrentTime()); @@ -135,7 +185,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++; @@ -145,6 +195,7 @@ public: if (!wasActive) { _acquisitionStarted = millis(); _firstFixInWindow = 0; + _goodFixInWindow = false; } if (_gpsPeriodSeconds > 0 && _driver->isActive()) { nmea.clear(); @@ -152,6 +203,7 @@ public: _acquiringPeriodically = true; _acquisitionStarted = millis(); _firstFixInWindow = 0; + _goodFixInWindow = false; } } @@ -194,6 +246,14 @@ public: return _gpsPeriodSeconds; } + void setFirstFixTimeout(uint32_t seconds) override { + _firstFixTimeoutSeconds = seconds; + } + + uint32_t getFirstFixTimeout() const override { + return _firstFixTimeoutSeconds; + } + uint32_t getAcquisitionAge() const override { return (uint32_t)(millis() - _acquisitionStarted) / 1000UL; } @@ -294,7 +354,7 @@ public: if (_driver->pollGpsSwitch()) _gpsOn = true; if (_onceDeadline != 0) { - if (_firstFixInWindow != 0 && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) { + if (_goodFixInWindow && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) { _onceDeadline = millis() + GPS_FIX_SETTLE_MS; } if ((long)(millis() - _onceDeadline) >= 0) { @@ -330,6 +390,7 @@ public: _nmea_seen = true; const char* messageId = nmea.getMessageID(); + if (isGsa(messageId)) parseGsa(nmea.getSentence()); #ifdef GPS_GUARD if (parsed && !nmea.isValid() && (strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) { @@ -343,11 +404,18 @@ public: _firstFixInWindow = millis(); fixStatsFix((uint32_t)(_firstFixInWindow - _acquisitionStarted)); } - if (_acquiringPeriodically) { - // stay on until a pending time sync is done (or the settle time is over) - const bool synced = _clock == nullptr || !_time_sync_needed; - if ((nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX && synced) || - (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS) { + // after a 2D fix the GPS stays on (up to the acquisition timeout) + // to give the receiver a chance to get a 3D fix + const uint8_t mode = currentFixMode(); + if (mode == 0 || mode == 3) _goodFixInWindow = true; + if (_acquiringPeriodically && _goodFixInWindow) { + // stay on until a pending time sync has been tried, even past the settle + // time: after a hot start the fix can come before the time is steady, and + // the window would close unsynced until the next period. The acquisition + // timeout below still bounds it. + if (timeSyncSettled() && + (nmea.getNumSatellites() >= GPS_MIN_SATS_FOR_FIX || + (uint32_t)(millis() - _firstFixInWindow) >= GPS_FIX_SETTLE_MS)) { finishPeriodicAcquisition(); } } @@ -358,10 +426,13 @@ public: } } - // no timeout until a first fix has been obtained (cold start can be long) - if (_acquiringPeriodically && _lastFix.valid && - (uint32_t)(millis() - _acquisitionStarted) >= GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) { - finishPeriodicAcquisition(); + // a longer limit until a first fix has been obtained (cold start can be long) + if (_acquiringPeriodically) { + const uint32_t limit = _lastFix.valid ? GPS_PERIODIC_ACQUISITION_TIMEOUT_MS + : _firstFixTimeoutSeconds * 1000UL; + if (limit > 0 && (uint32_t)(millis() - _acquisitionStarted) >= limit) { + finishPeriodicAcquisition(); + } } updateTime(); @@ -390,5 +461,8 @@ public: fix_age, (unsigned long)_begin_calls, (unsigned long)_stop_calls); + // fix mode from GSA (1 none, 2 2D, 3 3D, 0 no recent GSA) + const size_t len = strlen(out); + if (len < out_size) snprintf(out + len, out_size - len, " fm:%u", currentFixMode()); } }; diff --git a/src/helpers/sensors/RakI2cGpsDriver.h b/src/helpers/sensors/RakI2cGpsDriver.h index ac76e069..74327c6a 100644 --- a/src/helpers/sensors/RakI2cGpsDriver.h +++ b/src/helpers/sensors/RakI2cGpsDriver.h @@ -41,7 +41,15 @@ class RakI2cGpsDriver : public GpsDriver { } #ifndef RAK_3401 - pinMode(powerPin, INPUT); + if (powerPin == WB_IO2) { + // WB_IO2 switches the 3V3_S slot rail, which also powers a serial GPS and the other + // slot modules. Left as an input, the rail follows whatever the base board pulls it + // to: some keep it on, others switch it off, and the serial GPS loses power (#3830). + // Keep it driven HIGH, as before the probe; a GPS power pin re-claims it later. + digitalWrite(powerPin, HIGH); + } else { + pinMode(powerPin, INPUT); + } #endif return false; } diff --git a/src/helpers/sensors/RakLocationProvider.h b/src/helpers/sensors/RakLocationProvider.h index 2dda12a5..f395530f 100644 --- a/src/helpers/sensors/RakLocationProvider.h +++ b/src/helpers/sensors/RakLocationProvider.h @@ -211,6 +211,20 @@ public: return _gpsPeriodSeconds; } + // the first-fix limit is only implemented on the serial NMEA path + void setFirstFixTimeout(uint32_t seconds) override { + _nmea.setFirstFixTimeout(seconds); + } + + uint32_t getFirstFixTimeout() const override { + return _useI2c ? 0 : _nmea.getFirstFixTimeout(); + } + + void formatDiagnostics(char* out, size_t out_size) override { + if (_useI2c) LocationProvider::formatDiagnostics(out, out_size); + else _nmea.formatDiagnostics(out, out_size); + } + bool isGpsOn() const override { return _useI2c ? _gpsOn : _nmea.isGpsOn(); } diff --git a/src/helpers/ui/NV3001BDisplay.cpp b/src/helpers/ui/NV3001BDisplay.cpp index 3bbecd2e..a98bcab6 100644 --- a/src/helpers/ui/NV3001BDisplay.cpp +++ b/src/helpers/ui/NV3001BDisplay.cpp @@ -448,10 +448,12 @@ bool NV3001BDisplay::begin() { digitalWrite(PIN_TFT_DC, HIGH); delay(20); -#ifdef NRF52_PLATFORM - spi.begin(); // Pins are set by the nRF52 variant. -#else +#if defined(NRF52_PLATFORM) + spi.begin(); +#elif defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) spi.begin(PIN_TFT_SCL, PIN_TFT_MISO, PIN_TFT_SDA, PIN_TFT_CS); +#else + spi.begin(); #endif if (PIN_TFT_RST >= 0) { pinMode(PIN_TFT_RST, OUTPUT); diff --git a/src/helpers/ui/NV3001BDisplay.h b/src/helpers/ui/NV3001BDisplay.h index 5886f102..fcf7b16f 100644 --- a/src/helpers/ui/NV3001BDisplay.h +++ b/src/helpers/ui/NV3001BDisplay.h @@ -20,16 +20,14 @@ #define NV3001B_PANEL_HEIGHT 220 #endif +class NV3001BDisplay : public DisplayDriver { +#if defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) #ifndef NV3001B_SPI_HOST #define NV3001B_SPI_HOST HSPI #endif - -class NV3001BDisplay : public DisplayDriver { -#ifdef NRF52_PLATFORM - SPIClass& spi; -#else - SPIClass spi; + SPIClass owned_spi; #endif + SPIClass& spi; RefCountedDigitalPin* periph_power; bool is_on = false; uint16_t color = 0xffff; @@ -54,12 +52,17 @@ class NV3001BDisplay : public DisplayDriver { void drawChar(int x, int y, char ch); public: -#ifdef NRF52_PLATFORM - explicit NV3001BDisplay(SPIClass& bus) : - DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(bus), periph_power(nullptr) { } -#else +#if defined(ESP_PLATFORM) || defined(ESP32_PLATFORM) NV3001BDisplay(RefCountedDigitalPin* power = nullptr) : - DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(NV3001B_SPI_HOST), periph_power(power) { } + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), + owned_spi(NV3001B_SPI_HOST), spi(owned_spi), periph_power(power) { } + + NV3001BDisplay(SPIClass* displaySpi, RefCountedDigitalPin* power = nullptr) : + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), + owned_spi(NV3001B_SPI_HOST), spi(displaySpi ? *displaySpi : owned_spi), periph_power(power) { } +#else + NV3001BDisplay(SPIClass* displaySpi = &SPI, RefCountedDigitalPin* power = nullptr) : + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(displaySpi ? *displaySpi : SPI), periph_power(power) { } #endif bool begin(); 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 d505af36..00000000 --- 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 c24e6306..00000000 --- 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 96c892ae..00000000 --- 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 0bbf2e5a..00000000 --- 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 cc616612..00000000 --- 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(); -} 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 eeb1aa6e..00000000 --- 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(); -} diff --git a/variants/heltec_rc52/HeltecRC52Board.cpp b/variants/heltec_rc52/HeltecRC52Board.cpp new file mode 100644 index 00000000..c1d4deea --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52Board.cpp @@ -0,0 +1,95 @@ +#include "HeltecRC52Board.h" + +#include +#include + +extern void variant_shutdown(); + +#ifdef NRF52_POWER_MANAGEMENT +const PowerMgtConfig power_config = { + .lpcomp_ain_channel = PWRMGT_LPCOMP_AIN, + .lpcomp_refsel = PWRMGT_LPCOMP_REFSEL, + .voltage_bootlock = PWRMGT_VOLTAGE_BOOTLOCK}; + +void HeltecRC52Board::initiateShutdown(uint8_t reason) +{ + shutdownPeripherals(); + + bool enable_lpcomp = (reason == SHUTDOWN_REASON_LOW_VOLTAGE || + reason == SHUTDOWN_REASON_BOOT_PROTECT); + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, enable_lpcomp ? ADC_CTRL_ENABLED : !ADC_CTRL_ENABLED); + + if (enable_lpcomp) { + configureVoltageWake(power_config.lpcomp_ain_channel, power_config.lpcomp_refsel); + } + + enterSystemOff(reason); +} +#endif + +void HeltecRC52Board::begin() +{ + NRF52BoardDCDC::begin(); + + pinMode(PIN_VBAT_READ, INPUT); + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + +#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL) + Wire.setPins(PIN_BOARD_SDA, PIN_BOARD_SCL); +#endif + Wire.begin(); + + pinMode(SENSOR_RST_PIN, OUTPUT); + digitalWrite(SENSOR_RST_PIN, HIGH); + pinMode(SENSOR_INT, INPUT); + + +#ifdef NRF52_POWER_MANAGEMENT + checkBootVoltage(&power_config); +#endif + pinMode(P_LORA_TX_LED, OUTPUT); + digitalWrite(P_LORA_TX_LED, LOW); // off by default, active high + + periph_power.begin(); + periph_power.claim(); +} + +void HeltecRC52Board::shutdownPeripherals() +{ + NRF52Board::shutdownPeripherals(); + variant_shutdown(); +} + +void HeltecRC52Board::onBeforeTransmit() { + digitalWrite(P_LORA_TX_LED, HIGH); +} + +void HeltecRC52Board::onAfterTransmit() { + digitalWrite(P_LORA_TX_LED, LOW); +} + +uint16_t HeltecRC52Board::getBattMilliVolts() +{ + analogReadResolution(12); + analogReference(AR_INTERNAL_3_0); + pinMode(PIN_VBAT_READ, INPUT); + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, ADC_CTRL_ENABLED); + + delay(10); + uint32_t raw = 0; + for (int i = 0; i < 8; i++) { + raw += analogRead(PIN_VBAT_READ); + } + raw /= 8; + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + + return (uint16_t)((float)raw * MV_LSB * ADC_MULTIPLIER); +} + +const char* HeltecRC52Board::getManufacturerName() const +{ + return "Heltec RC52"; +} diff --git a/variants/heltec_rc52/HeltecRC52Board.h b/variants/heltec_rc52/HeltecRC52Board.h new file mode 100644 index 00000000..548b1049 --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52Board.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include +#include + +class HeltecRC52Board : public NRF52BoardDCDC { +protected: +#ifdef NRF52_POWER_MANAGEMENT + void initiateShutdown(uint8_t reason) override; +#endif + +public: + RefCountedDigitalPin periph_power; + + HeltecRC52Board() : NRF52Board("RC52_OTA"), periph_power(SENSOR_POWER_CTRL_PIN, SENSOR_POWER_ON) {} + + void begin() override; + void onBeforeTransmit() override; + void onAfterTransmit() override; + void shutdownPeripherals() override; + uint16_t getBattMilliVolts() override; + const char* getManufacturerName() const override; +}; diff --git a/variants/heltec_rc52/HeltecRC52RotaryInput.cpp b/variants/heltec_rc52/HeltecRC52RotaryInput.cpp new file mode 100644 index 00000000..8baea9f3 --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52RotaryInput.cpp @@ -0,0 +1,128 @@ +#include "HeltecRC52RotaryInput.h" + +#include +#include + +namespace { +constexpr uint8_t TCA6408_ADDR = 0x20; +constexpr uint8_t TCA6408_INPUT_REG = 0x00; +constexpr uint8_t TCA6408_POLARITY_REG = 0x02; +constexpr uint8_t TCA6408_CONFIG_REG = 0x03; +constexpr uint8_t TCA6408_ROTARY_A_MASK = 0x01; +constexpr uint8_t TCA6408_ROTARY_B_MASK = 0x02; +constexpr uint8_t TCA6408_ROTARY_MASK = TCA6408_ROTARY_A_MASK | TCA6408_ROTARY_B_MASK; +constexpr uint32_t TCA6408_DEBOUNCE_MS = 5; +} + +bool HeltecRC52RotaryInput::begin() +{ + initialized = true; + ready = false; + input_state = TCA6408_ROTARY_MASK; + active_low_phase = false; + + if (periph_power && !power_claimed) { + periph_power->claim(); + power_claimed = true; + delay(12); + } + + if (!writeRegister(TCA6408_POLARITY_REG, 0x00) || !writeRegister(TCA6408_CONFIG_REG, 0xFF)) { + return false; + } + + uint8_t state = 0; + if (!readInput(state)) { + return false; + } + + input_state = state & TCA6408_ROTARY_MASK; + ready = true; + return true; +} + +RotaryInputEvent HeltecRC52RotaryInput::poll() +{ + if (!initialized) { + begin(); + return RotaryInputEvent::None; + } + + if (!ready) { + return RotaryInputEvent::None; + } + + uint8_t new_state = 0; + if (!readInput(new_state)) { + return RotaryInputEvent::None; + } + + new_state &= TCA6408_ROTARY_MASK; + RotaryInputEvent event = handleTransition(new_state); + input_state = new_state; + return event; +} + +bool HeltecRC52RotaryInput::writeRegister(uint8_t reg, uint8_t value) +{ + Wire.beginTransmission(TCA6408_ADDR); + Wire.write(reg); + Wire.write(value); + return Wire.endTransmission() == 0; +} + +bool HeltecRC52RotaryInput::readInput(uint8_t& value) +{ + Wire.beginTransmission(TCA6408_ADDR); + Wire.write(TCA6408_INPUT_REG); + if (Wire.endTransmission(false) != 0) { + return false; + } + if (Wire.requestFrom(TCA6408_ADDR, static_cast(1)) != 1) { + return false; + } + + value = Wire.read(); + return true; +} + +RotaryInputEvent HeltecRC52RotaryInput::handleTransition(uint8_t newState) +{ + uint8_t changed = (input_state ^ newState) & TCA6408_ROTARY_MASK; + RotaryInputEvent event = RotaryInputEvent::None; + bool a_low = (newState & TCA6408_ROTARY_A_MASK) == 0; + bool b_low = (newState & TCA6408_ROTARY_B_MASK) == 0; + + if (!a_low && !b_low) { + active_low_phase = false; + } + + if (!active_low_phase && (changed & TCA6408_ROTARY_A_MASK) && a_low && !b_low) { + event = RotaryInputEvent::Prev; + active_low_phase = true; + } else if (!active_low_phase && (changed & TCA6408_ROTARY_B_MASK) && b_low && !a_low) { + event = RotaryInputEvent::Next; + active_low_phase = true; + } + + if (event == RotaryInputEvent::None && !active_low_phase && (changed & TCA6408_ROTARY_A_MASK)) { + bool a_rising = (newState & TCA6408_ROTARY_A_MASK) != 0; + if (a_rising && b_low) { + event = RotaryInputEvent::Prev; + } + } + + if (event == RotaryInputEvent::None && !active_low_phase && (changed & TCA6408_ROTARY_B_MASK)) { + bool b_rising = (newState & TCA6408_ROTARY_B_MASK) != 0; + if (b_rising && a_low) { + event = RotaryInputEvent::Next; + } + } + + if (event == RotaryInputEvent::None || (millis() - last_event_ms) < TCA6408_DEBOUNCE_MS) { + return RotaryInputEvent::None; + } + + last_event_ms = millis(); + return event; +} diff --git a/variants/heltec_rc52/HeltecRC52RotaryInput.h b/variants/heltec_rc52/HeltecRC52RotaryInput.h new file mode 100644 index 00000000..4aa6f823 --- /dev/null +++ b/variants/heltec_rc52/HeltecRC52RotaryInput.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include + +class HeltecRC52RotaryInput : public RotaryInput { +public: + explicit HeltecRC52RotaryInput(RefCountedDigitalPin* periphPower = nullptr) : periph_power(periphPower) { } + + bool begin() override; + RotaryInputEvent poll() override; + bool isReady() const override { return ready; } + +private: + bool writeRegister(uint8_t reg, uint8_t value); + bool readInput(uint8_t& value); + RotaryInputEvent handleTransition(uint8_t newState); + + uint8_t input_state = 0x03; + uint32_t last_event_ms = 0; + bool ready = false; + bool initialized = false; + bool power_claimed = false; + bool active_low_phase = false; + RefCountedDigitalPin* periph_power = nullptr; +}; diff --git a/variants/heltec_rc52/platformio.ini b/variants/heltec_rc52/platformio.ini new file mode 100644 index 00000000..d6526494 --- /dev/null +++ b/variants/heltec_rc52/platformio.ini @@ -0,0 +1,192 @@ +[heltec_rc52] +extends = nrf52_base +board = heltec-rc52 +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = ${nrf52_base.build_flags} + ${sensor_base.build_flags} + -I lib/nrf52/s140_nrf52_6.1.1_API/include + -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 + -I variants/heltec_rc52 + -I src/helpers/ui + -D HELTEC_RC52 + -D NRF52_POWER_MANAGEMENT + -D USE_SX1262 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D P_LORA_DIO_1=11 + -D P_LORA_NSS=13 + -D P_LORA_RESET=32 + -D P_LORA_BUSY=24 + -D P_LORA_SCLK=25 + -D P_LORA_MISO=14 + -D P_LORA_MOSI=22 + -D P_LORA_TX_LED=15 + -D LORA_TX_POWER=22 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_RX_BOOSTED_GAIN=1 + -D SX126X_DIO2_AS_RF_SWITCH=true + -D SX126X_DIO3_TCXO_VOLTAGE=1.8 +build_src_filter = ${nrf52_base.build_src_filter} + + + + + +<../variants/heltec_rc52> +lib_deps = + ${nrf52_base.lib_deps} + ${sensor_base.lib_deps} +debug_tool = jlink +upload_protocol = nrfutil + +[env:heltec_rc52_without_display_repeater] +extends = heltec_rc52 +build_src_filter = ${heltec_rc52.build_src_filter} + +<../examples/simple_repeater> +build_flags = + ${heltec_rc52.build_flags} + -D ADVERT_NAME='"Heltec RC52 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + +[env:heltec_rc52_without_display_room_server] +extends = heltec_rc52 +build_src_filter = ${heltec_rc52.build_src_filter} + +<../examples/simple_room_server> +build_flags = + ${heltec_rc52.build_flags} + -D ADVERT_NAME='"Heltec RC52 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + +[env:heltec_rc52_without_display_companion_radio_ble] +extends = heltec_rc52 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52.build_flags} + -I examples/companion_radio/ui-new + -D DISPLAY_CLASS=NullDisplayDriver + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${heltec_rc52.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:heltec_rc52_without_display_companion_radio_usb] +extends = heltec_rc52 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52.build_flags} + -I examples/companion_radio/ui-new + -D DISPLAY_CLASS=NullDisplayDriver + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +build_src_filter = ${heltec_rc52.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52.lib_deps} + densaugeo/base64 @ ~1.4.0 + +; +; Heltec RC52 with NV3001B display +; +[heltec_rc52_with_display] +extends = heltec_rc52 +board_build.ldscript = boards/nrf52840_s140_v6.ld +build_flags = + ${heltec_rc52.build_flags} + -D HELTEC_RC52_WITH_DISPLAY + -D DISPLAY_CLASS=NV3001BDisplay +build_src_filter = ${heltec_rc52.build_src_filter} + + + + +lib_deps = + ${heltec_rc52.lib_deps} + +[env:heltec_rc52_repeater] +extends = heltec_rc52_with_display +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + +<../examples/simple_repeater> +build_flags = + ${heltec_rc52_with_display.build_flags} + -D ADVERT_NAME='"Heltec RC52 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 + +[env:heltec_rc52_room_server] +extends = heltec_rc52_with_display +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + +<../examples/simple_room_server> +build_flags = + ${heltec_rc52_with_display.build_flags} + -D ADVERT_NAME='"Heltec RC52 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' + +[env:heltec_rc52_companion_radio_ble] +extends = heltec_rc52_with_display +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52_with_display.build_flags} + -I examples/companion_radio/ui-new + -D PIN_BUZZER=5 + -D UI_HAS_ROTARY_INPUT + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D BLE_PIN_CODE=123456 + -D ENV_INCLUDE_GPS=1 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52_with_display.lib_deps} + densaugeo/base64 @ ~1.4.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:heltec_rc52_companion_radio_usb] +extends = heltec_rc52_with_display +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${heltec_rc52_with_display.build_flags} + -I examples/companion_radio/ui-new + -D PIN_BUZZER=5 + -D UI_HAS_ROTARY_INPUT + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 + -D ENV_INCLUDE_GPS=1 +build_src_filter = ${heltec_rc52_with_display.build_src_filter} + + + + + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${heltec_rc52_with_display.lib_deps} + densaugeo/base64 @ ~1.4.0 + end2endzone/NonBlockingRTTTL@^1.3.0 + +[env:heltec_rc52_kiss_modem] +extends = heltec_rc52 +build_src_filter = ${heltec_rc52.build_src_filter} + +<../examples/kiss_modem/> diff --git a/variants/heltec_rc52/target.cpp b/variants/heltec_rc52/target.cpp new file mode 100644 index 00000000..dc5652d8 --- /dev/null +++ b/variants/heltec_rc52/target.cpp @@ -0,0 +1,54 @@ +#include "target.h" + +#include +#include + +#if defined(UI_HAS_ROTARY_INPUT) +#include "HeltecRC52RotaryInput.h" +#endif + +#ifdef ENV_INCLUDE_GPS +#include +#endif + +HeltecRC52Board board; + +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); +WRAPPER_CLASS radio_driver(radio, board); + +VolatileRTCClock fallback_clock; +AutoDiscoverRTCClock rtc_clock(fallback_clock); + +#if ENV_INCLUDE_GPS +NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, + &board.periph_power); +MicroNMEALocationProvider nmea(gps_driver, &rtc_clock); +EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea); +#else +EnvironmentSensorManager sensors; +#endif + +#ifdef DISPLAY_CLASS +#ifdef HELTEC_RC52_WITH_DISPLAY +DISPLAY_CLASS display(&SPI1); +#else +DISPLAY_CLASS display; +#endif +MomentaryButton user_btn(PIN_USER_BTN, 1000, true); +#if defined(UI_HAS_ROTARY_INPUT) +static HeltecRC52RotaryInput rotaryInputImpl(&board.periph_power); +RotaryInput& rotary_input = rotaryInputImpl; +#endif +#endif + +bool radio_init() +{ + rtc_clock.begin(Wire); + return radio.std_init(&SPI); +} + +mesh::LocalIdentity radio_new_identity() +{ + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); +} diff --git a/variants/heltec_rc52/target.h b/variants/heltec_rc52/target.h new file mode 100644 index 00000000..efb7fdcb --- /dev/null +++ b/variants/heltec_rc52/target.h @@ -0,0 +1,38 @@ +#pragma once + +#define RADIOLIB_STATIC_ONLY 1 +#include +#include +#include +#include +#include +#include +#include + +#ifdef DISPLAY_CLASS +#include +#if defined(UI_HAS_ROTARY_INPUT) +#include +#endif +#ifdef HELTEC_RC52_WITH_DISPLAY +#include +#else +#include +#endif +#endif + +extern HeltecRC52Board board; +extern WRAPPER_CLASS radio_driver; +extern AutoDiscoverRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; + +#ifdef DISPLAY_CLASS +extern DISPLAY_CLASS display; +extern MomentaryButton user_btn; +#if defined(UI_HAS_ROTARY_INPUT) +extern RotaryInput& rotary_input; +#endif +#endif + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/heltec_rc52/variant.cpp b/variants/heltec_rc52/variant.cpp new file mode 100644 index 00000000..a4a090fa --- /dev/null +++ b/variants/heltec_rc52/variant.cpp @@ -0,0 +1,84 @@ +#include "variant.h" +#include "Arduino.h" +#include "nrf.h" +#include +#include "wiring_constants.h" +#include "wiring_digital.h" + +const uint32_t g_ADigitalPinMap[] = { + 0xff, 0xff, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47}; + +void initVariant() +{ + pinMode(PIN_BUTTON1, INPUT_PULLUP); + + pinMode(RADIOCORE_FEM_EN, OUTPUT); + digitalWrite(RADIOCORE_FEM_EN, HIGH); + + pinMode(RADIOCORE_VFEM_CTRL, OUTPUT); + digitalWrite(RADIOCORE_VFEM_CTRL, HIGH); + + pinMode(PIN_ADC_CTRL, OUTPUT); + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + +#ifdef PIN_BUZZER + pinMode(PIN_BUZZER, OUTPUT); + digitalWrite(PIN_BUZZER, LOW); +#endif + + pinMode(PIN_TFT_EN, OUTPUT); + digitalWrite(PIN_TFT_EN, !PIN_TFT_EN_ACTIVE); + pinMode(PIN_TFT_BL, OUTPUT); + digitalWrite(PIN_TFT_BL, !PIN_TFT_BL_ACTIVE); + pinMode(PIN_TFT_CS, OUTPUT); + digitalWrite(PIN_TFT_CS, HIGH); +} + +void variant_shutdown() +{ + Wire.end(); + + digitalWrite(RADIOCORE_FEM_EN, LOW); + digitalWrite(RADIOCORE_VFEM_CTRL, LOW); + digitalWrite(PIN_ADC_CTRL, !ADC_CTRL_ENABLED); + + digitalWrite(PIN_TFT_BL, !PIN_TFT_BL_ACTIVE); + digitalWrite(PIN_TFT_EN, !PIN_TFT_EN_ACTIVE); + + nrf_gpio_cfg_default(PIN_BUTTON1); + nrf_gpio_cfg_default(PIN_ADC_CTRL); +#ifdef PIN_BUZZER + nrf_gpio_cfg_default(PIN_BUZZER); +#endif + + nrf_gpio_cfg_default(PIN_TFT_BL); + nrf_gpio_cfg_default(PIN_TFT_EN); + nrf_gpio_cfg_default(PIN_TFT_CS); + nrf_gpio_cfg_default(PIN_TFT_DC); + nrf_gpio_cfg_default(PIN_TFT_RST); + + nrf_gpio_cfg_default(PIN_SPI_MISO); + nrf_gpio_cfg_default(PIN_SPI_MOSI); + nrf_gpio_cfg_default(PIN_SPI_SCK); + + // SPI1 MISO is not connected; its sentinel is not a physical GPIO. + nrf_gpio_cfg_default(PIN_SPI1_MOSI); + nrf_gpio_cfg_default(PIN_SPI1_SCK); + + nrf_gpio_cfg_default(PIN_GPS_EN); + nrf_gpio_cfg_default(PIN_GPS_RESET); + nrf_gpio_cfg_default(PIN_GPS_PPS); + nrf_gpio_cfg_default(PIN_GPS_RX); + nrf_gpio_cfg_default(PIN_GPS_TX); + + nrf_gpio_cfg_default(SENSOR_POWER_CTRL_PIN); + nrf_gpio_cfg_default(SENSOR_RST_PIN); + nrf_gpio_cfg_default(SENSOR_INT); + nrf_gpio_cfg_default(PIN_BOARD_SDA); + nrf_gpio_cfg_default(PIN_BOARD_SCL); + + nrf_gpio_cfg_default(RADIOCORE_FEM_EN); + nrf_gpio_cfg_default(RADIOCORE_VFEM_CTRL); +} diff --git a/variants/heltec_rc52/variant.h b/variants/heltec_rc52/variant.h new file mode 100644 index 00000000..bd2662fb --- /dev/null +++ b/variants/heltec_rc52/variant.h @@ -0,0 +1,99 @@ +#ifndef _VARIANT_HELTEC_RC52_ +#define _VARIANT_HELTEC_RC52_ + +#define VARIANT_MCK (64000000ul) +#define USE_LFXO + +#include "WVariant.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define HARD_VERSION_ADDR (0xED000 + 7 * 4096 - 16 - 1) +#define HT_LICENSE_ADDR (0xED000 + 7 * 4096 - 16) +#define HT_LICENSE_ADDR_BASE (0xED000 + 6 * 4096) + +#define PINS_COUNT (48) +#define NUM_DIGITAL_PINS (48) +#define NUM_ANALOG_INPUTS (1) +#define NUM_ANALOG_OUTPUTS (0) + +#define PIN_LED1 (-1) +#define PIN_NEOPIXEL (-1) +#define NEOPIXEL_NUM 0 +#define LED_BUILTIN PIN_LED1 +#define LED_BLUE PIN_LED1 +#define LED_STATE_ON 1 + +#define PIN_BUTTON1 (32 + 10) // P1.10, external pull-up, active low +#define PIN_BUTTON_USER PIN_BUTTON1 +#define PIN_USER_BTN PIN_BUTTON1 + +#define ADC_RESOLUTION 14 +#define PIN_VBAT_READ (0 + 31) +#define PIN_ADC_CTRL (0 + 4) +#define ADC_CTRL_ENABLED HIGH +#define ADC_MULTIPLIER 4.9F +#define MV_LSB (3000.0F / 4096.0F) + +#define PWRMGT_VOLTAGE_BOOTLOCK 3300 +#define PWRMGT_LPCOMP_AIN 7 +#define PWRMGT_LPCOMP_REFSEL 1 + +#define WIRE_INTERFACES_COUNT 1 + +#define PIN_BOARD_SDA (32 + 11) // P1.11 +#define PIN_BOARD_SCL (0 + 2) // P0.02 +#define PIN_WIRE_SDA PIN_BOARD_SDA +#define PIN_WIRE_SCL PIN_BOARD_SCL +#define SENSOR_POWER_CTRL_PIN (0 + 12) +#define SENSOR_POWER_ON HIGH +#define SENSOR_INT (0 + 20) +#define SENSOR_RST_PIN (32 + 15) + + +#define PIN_GPS_TX (0 + 8) +#define PIN_GPS_RX (0 + 7) +#define PIN_GPS_EN (32 + 9) +#define PIN_GPS_PPS (32 + 1) +#define PIN_GPS_RESET (32 + 6) +#define PIN_GPS_EN_ACTIVE HIGH +#define PIN_GPS_RESET_ACTIVE LOW +#define GPS_BAUD_RATE 9600 +#define GPS_THREAD_INTERVAL 50 +#define PERIPHERAL_WARMUP_MS 100 + +#define PIN_SERIAL1_RX PIN_GPS_RX +#define PIN_SERIAL1_TX PIN_GPS_TX + +#define PIN_TFT_CS (32 + 4) +#define PIN_TFT_RST (0 + 10) +#define PIN_TFT_DC (0 + 28) +#define PIN_TFT_SCL (0 + 30) +#define PIN_TFT_SDA (32 + 2) +#define PIN_TFT_EN (32 + 13) +#define PIN_TFT_EN_ACTIVE LOW +#define PIN_TFT_BL (0 + 9) +#define PIN_TFT_BL_ACTIVE HIGH +#define SPI_FREQUENCY 8000000 + +#define RADIOCORE_FEM_EN (0 + 26) +#define RADIOCORE_VFEM_CTRL (0 + 16) + +#define SPI_INTERFACES_COUNT 2 +#define SPI_32MHZ_INTERFACE 1 + +#define PIN_SPI_MISO (0 + 14) +#define PIN_SPI_MOSI (0 + 22) +#define PIN_SPI_SCK (0 + 25) + +#define PIN_SPI1_MISO (0) // g_ADigitalPinMap[0] is 0xFF (NRFX_SPIM_PIN_NOT_USED). +#define PIN_SPI1_MOSI PIN_TFT_SDA +#define PIN_SPI1_SCK PIN_TFT_SCL + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/variants/meshpocket_v2/target.cpp b/variants/meshpocket_v2/target.cpp index d22ce41a..714de97b 100644 --- a/variants/meshpocket_v2/target.cpp +++ b/variants/meshpocket_v2/target.cpp @@ -8,7 +8,7 @@ VolatileRTCClock rtc_clock; NmeaGpsDriver gps_driver(Serial1); MicroNMEALocationProvider gps(gps_driver, &rtc_clock); EnvironmentSensorManager sensors(gps); -DISPLAY_CLASS display(SPI1); +DISPLAY_CLASS display(&SPI1); MomentaryButton user_btn(PIN_USER_BTN, 1000, true, true); bool radio_init() { diff --git a/variants/xiao_s3_wio/XiaoS3WIOBoard.h b/variants/xiao_s3_wio/XiaoS3WIOBoard.h index 7ae06a35..4a635334 100644 --- a/variants/xiao_s3_wio/XiaoS3WIOBoard.h +++ b/variants/xiao_s3_wio/XiaoS3WIOBoard.h @@ -7,6 +7,13 @@ class XiaoS3WIOBoard : public ESP32Board { public: XiaoS3WIOBoard() { } + void begin() { + while (!Serial.availableForWrite()) + delay(10); + + ESP32Board::begin(); + } + const char* getManufacturerName() const override { return "Xiao S3 WIO"; }