Merge pull request #19 from meshcore-dev/dev

merge Dev
This commit is contained in:
Quency-D authored and GitHub committed 2026-11-11 10:19:51 +08:00
commit 3633402e59
154 files changed
+4224 -898

No files matched your search

+5
View File
@@ -40,6 +40,11 @@ jobs:
- PicoW_repeater
# STM32
- wio-e5-mini_repeater
- LilyGo_T3_STM32_repeater
- LilyGo_T3_STM32_companion_radio_usb
- LilyGo_T3_STM32_repeater_ina219
- LilyGo_T3_STM32_companion_radio_usb_ina219
- nucleo_wl55jc_repeater
# ESP32-C6
- LilyGo_Tlora_C6_repeater_
# LR1110 (nRF52)
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
uses: ./.github/actions/setup-build-environment
- name: Run Unit Tests
run: pio test -e native -e native_kiss_modem -vv
run: pio test -e native -e native_kiss_modem -e native_rak3401_onboard_radio -vv
- name: Upload Test Results
# Upload test results even if the test step failed.
+1
View File
@@ -38,6 +38,7 @@ For developers:
- Install [PlatformIO](https://docs.platformio.org) in [Visual Studio Code](https://code.visualstudio.com).
- Clone and open the MeshCore repository in Visual Studio Code.
- For the LilyGO T3 STM32, see the [board build and flashing guide](./variants/lilygo_t3_stm32/README.md).
- See the example applications you can modify and run:
- [Companion Radio](./examples/companion_radio) - For use with an external chat app, over BLE, USB or Wi-Fi.
- [KISS Modem](./examples/kiss_modem) - Serial KISS protocol bridge for host applications. ([protocol docs](./docs/kiss_modem_protocol.md))
+39
View File
@@ -0,0 +1,39 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld"
},
"core": "esp32",
"extra_flags": [
"-D ARDUINO_USB_CDC_ON_BOOT=0",
"-D ARDUINO_USB_MSC_ON_BOOT=0",
"-D ARDUINO_USB_DFU_ON_BOOT=0",
"-D ARDUINO_USB_MODE=0",
"-D ARDUINO_RUNNING_CORE=1",
"-D ARDUINO_EVENT_RUNNING_CORE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "esp32s3"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "DFRobot LoRaWAN ESP32-S3 (4 MB Flash, No PSRAM)",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 524288,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 921600
},
"url": "https://www.dfrobot.com",
"vendor": "DFRobot"
}
+32
View File
@@ -0,0 +1,32 @@
{
"build": {
"arduino": {
"variant_h": "variant_generic.h"
},
"core": "stm32",
"cpu": "cortex-m4",
"extra_flags": "-DSTM32WL -DSTM32WLxx -DSTM32WL55xx",
"f_cpu": "48000000L",
"framework_extra_flags": {
"arduino": "-DUSE_CM4_STARTUP_FILE -DARDUINO_GENERIC_WL55CCUX"
},
"mcu": "stm32wl55ccu6",
"product_line": "STM32WL55xx",
"variant": "STM32WLxx/WL54CCU_WL55CCU_WLE4C(8-B-C)U_WLE5C(8-B-C)U"
},
"debug": {
"jlink_device": "STM32WL55CC",
"openocd_target": "stm32wlx",
"svd_path": "STM32WL5x_CM4.svd"
},
"frameworks": ["arduino"],
"name": "LilyGO T3 STM32 V1.0 (STM32WL55CCU6)",
"upload": {
"maximum_ram_size": 65536,
"maximum_size": 262144,
"protocol": "serial",
"protocols": ["serial", "stlink", "jlink"]
},
"url": "https://github.com/Xinyuan-LilyGO/T3-STM32",
"vendor": "LilyGO"
}
+83 -4
View File
@@ -999,9 +999,16 @@ region save
---
### GPS (When GPS support is compiled in)
#### View or change GPS state
#### View GPS state
**Usage:**
- `gps`
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
---
#### Change GPS state
**Usage:**
- `gps <state>`
**Parameters:**
@@ -1009,9 +1016,30 @@ region save
**Default:** `off`
**Note:** Output format:
- `off` when the GPS hardware is disabled
- `on, {active|deactivated}, {fix|no fix}, {sat count} sats` when the GPS hardware is enabled
---
#### View or change the GPS acquisition period
**Usage:**
- `gps period`
- `gps period <value>`
**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.
---
#### View the last GPS fix
**Usage:**
- `gps fix`
**Output:**
- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix.
- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix.
- `> No fix[, acq <time>]`: no valid fix since the node started.
**Note:** Ages and durations are given in `s`, `m` or `h`.
---
@@ -1021,6 +1049,50 @@ region save
---
#### On demand GPS fix
**Usage:**
- `gps once`
- `gps once -s`
**Parameters:**
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
---
#### View GPS time to first fix statistics
**Usage:**
- `gps fix_stats`
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
---
#### View GPS diagnostics
**Usage:**
- `gps diag`
---
#### GPS anti-spoofing guard (When built with `GPS_GUARD`)
With `GPS_GUARD`, a fix becomes the node's last fix (position, telemetry, adverts) only after it passes plausibility checks: at least `GPS_GUARD_MIN_SATS` satellites, HDOP ≤ `GPS_GUARD_MAX_HDOP10`/10, inside the optional build-time region (`GPS_GUARD_LAT_MIN/MAX`, `GPS_GUARD_LON_MIN/MAX`), within the fence around the node's configured `lat`/`lon` (if set), no jump faster than `GPS_GUARD_MAX_SPEED_KMH`, and `GPS_GUARD_STABLE_FIXES` consistent fixes in a row. An unverified position is never reported.
GPS time is written to the clock only while such a fix is current, never earlier than the firmware build date, and, once the clock holds a plausible time (from the build date to 10 years after it), only within `GPS_GUARD_TIME_MAX_STEP` seconds for the first sync and within clock drift (`GPS_GUARD_TIME_DRIFT_BASE` s + `GPS_GUARD_TIME_DRIFT_PPM`) afterwards. Setting the clock manually (`time`, `clock sync`) resets that anchor. A clock outside that window (e.g. a bogus date in 2080) is corrected by the first trusted fix.
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 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 <metres>`: fence radius around the configured `lat`/`lon` (`0` = off). Default `GPS_GUARD_FENCE_M` (1000); a value set here is saved.
- `gps ref`: the reference position; follows `set lat`, `set lon` and `gps setloc`.
---
#### Set this node's location based on the GPS coordinates
**Usage:**
- `gps setloc`
@@ -1175,6 +1247,13 @@ region save
---
### Repeater health history
History is queried over the mesh using the sensor-compatible `0x04` min/max/average
request; there is no history CLI command. Retention and recording interval are controlled
by `REPEATER_HISTORY_SLOTS` and `REPEATER_HISTORY_INTERVAL_SECS` at build time.
See [Repeater health history](repeater_history.md) for the channel mapping and flags.
### Ethernet (when Ethernet support is compiled in)
Ethernet support is available on RAK4631 boards with a RAK13800 (W5100S) Ethernet module. Use the `_ethernet` firmware variants (e.g. `RAK_4631_repeater_ethernet`) to enable this feature.
+107
View File
@@ -7,6 +7,7 @@ Since version 1.18 meshcore companion radio firmware has a CLI interface, which
- [Configuration](#configuration)
- [System](#system)
- [Radio](#radio)
- [GPS](#gps)
- [BLE](#ble)
- [Wifi](#wifi)
- [UI](#ui)
@@ -65,6 +66,20 @@ Since version 1.18 meshcore companion radio firmware has a CLI interface, which
---
#### Fine-tune the battery reading
**Usage:**
- `get adc.multiplier`
- `set adc.multiplier <value>`
**Parameters:**
- `value`: ADC multiplier (0.0-10.0)
**Default:** `0.0` (value defined by board)
**Note:** Returns "Error: unsupported" if the board doesn't support it. Same command as on repeaters, for boards whose battery divider resistors vary (e.g. DIY ProMicro / Faketec).
---
### Radio
Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
@@ -119,6 +134,84 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
---
### GPS
#### View GPS state
**Usage:**
- `gps`
**Note:** Reports the requested state, receiver activity, last-fix status (last fix gives number of sats and how long ago was the fix), and mode. In periodic mode, `waiting` means the receiver is off between acquisitions; the last fix remains available. `off(hw)` means a hardware GPS switch is off.
---
#### Change GPS state
**Usage:**
- `gps <state>`
**Parameters:**
- `state`: `on`|`off`
---
#### View or change the GPS acquisition period
**Usage:**
- `gps period`
- `gps period <value>`
**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.
---
#### View the last GPS fix
**Usage:**
- `gps fix`
**Output:**
- `> Fix (n sat): <lat>, <lon>`: the GPS currently has a fix.
- `> Last fix <age> ago (n sat)[, acq <time>]: <lat>, <lon>`: position of the last valid fix; `acq` is shown only while the receiver is running and shows how for how long the gps has been trying to get a fix.
- `> No fix[, acq <time>]`: no valid fix since the node started.
**Note:** Ages and durations are given in `s`, `m` or `h`.
---
#### Sync this node's clock with GPS time
**Usage:**
- `gps sync`
---
#### On demand GPS fix
**Usage:**
- `gps once`
- `gps once -s`
**Parameters:**
- `-s`: also sync this node's clock with GPS time (as `gps sync`)
**Note:** Starts an acquisition now. If the GPS is off, it is switched and kept on until a valid fix and then turned off.
**Reply:** `OK - turning on and acquiring` (GPS was off), `OK - waking gps` (periodic mode, receiver off between acquisitions) or `OK - gps already on`. `Error, gps hw switch off` if a hardware GPS switch is off, `Error, gps once not supported`.
---
#### View GPS time to first fix statistics
**Usage:**
- `gps fix_stats`
**Output:** `> ttf:<last>/<max> ok:<n> miss:<n>`: last and maximum time between a start of the GPS and its first valid fix, then the last count of consecutive starts with a fix (`ok`) or without one (`miss`).
---
#### View GPS diagnostics
**Usage:**
- `gps diag`
---
#### View or change this node's rx boosted gain mode (SX12xx and LR1110)
**Usage:**
- `get radio.rxgain`
@@ -373,6 +466,20 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
---
#### GPS key action
**Usage:**
- `set ui.gps_action <action>`
- `get ui.gps_action`
**Parameters:**
- `action`: `toggle` (or `0`) to switch the GPS on and off, `once` (or `trigger`, `1`) to acquire a fix on demand, as `gps once`
**Default:** `toggle`, or `once` on boards with a GPS switch
**Note:** Only used by the `ui-new` screens for now.
---
#### Node discovery screen shows nodes names
**Usage:**
- `set ui.nd_name <state>`
+24 -2
View File
@@ -103,7 +103,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v
| `0x01` | get stats | get stats of repeater or room server |
| `0x02` | keepalive | (deprecated) |
| `0x03` | get telemetry | request node telemetry |
| `0x04` | get min/max/avg | get sensor node stats on time series data |
| `0x04` | get min/max/avg | get sensor or repeater time series statistics |
| `0x05` | get acl | node ACL query |
| `0x06` | get neighbors | node neighbors query |
| `0x08` | subscribe | subscribe to telemetry push |
@@ -140,7 +140,7 @@ Gets information about the node, possibly including the following:
| req type | 1 | 0x03 (request sub type) |
| permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) |
#### Get Min/Max/Ave (Sensor nodes)
#### Get Min/Max/Ave (Sensor and repeater nodes)
| Field | Size (bytes) | Description |
|----------------|--------------|------------------------------|
@@ -150,6 +150,28 @@ Gets information about the node, possibly including the following:
| end | 4 | ending time, seconds ago |
| reserved | 2 | should be zeroes |
Requires an authenticated client with the READ_ONLY role or higher. The range includes
samples whose age is `end <= age < start`, in seconds. Request integers are little-endian.
The repeater uses exactly the sensor request and response layout.
The response body (after decryption) is:
| Field | Size (bytes) | Description |
|----------------|--------------|-------------|
| tag | 4 | echoed request timestamp, little-endian |
| current time | 4 | current node RTC Unix time, little-endian |
| series | variable | up to 8 series records, described below |
Each series record contains a channel byte, an LPP type byte, then min, max, and average
in that order. Each value uses the type's Cayenne LPP size, multiplier, sign, and
big-endian encoding. There is no count byte; parse records to the end of the response.
Nonzero reserved bytes return only the tag and current time.
Repeater history is pull-only, uses uptime internally, and omits series with no valid
samples in the requested range. Its returned current time still comes from the RTC;
an unset or corrected RTC does not affect sampling or range selection. See
[Repeater health history](repeater_history.md) for channels, retention, and build flags.
#### Subscribe to Telemetry push - (Sensor nodes)
| Field | Size (bytes) | Description |
+84
View File
@@ -0,0 +1,84 @@
# Repeater health history
The simple repeater keeps health samples in RAM and answers mesh request
`REQ_TYPE_GET_AVG_MIN_MAX` (`0x04`). A logged-in client needs READ_ONLY access or
higher. This is pull-only: recording history sends no packets. Existing GET_STATUS
and telemetry responses are unchanged.
## Series
| Channel | LPP type | Value recorded each interval |
|---------|----------|------------------------------|
| 200 | `LPP_VOLTAGE` (116) | Battery voltage in V, averaged from periodic reads every 15 seconds |
| 201 | `LPP_ANALOG_INPUT` (2, signed) | Radio noise floor in dBm at the end of the interval |
| 202 | `LPP_PERCENTAGE` (120) | TX airtime percentage over the elapsed interval |
| 203 | `LPP_PERCENTAGE` (120) | RX airtime percentage over the elapsed interval |
| 204 | `LPP_TEMPERATURE` (103) | MCU temperature in degrees C, when supported |
These channels are dedicated to history. Existing self telemetry and GPS use channel 1;
`EnvironmentSensorManager` assigns at most 16 active entries to channels 2–17. Channels
200–204 therefore do not collide with current repeater telemetry. Custom sensor managers
should leave this range free. History channels do not change the channels in `0x03`.
Battery averaging reduces the effect of short voltage dips during transmission. Noise
floor and temperature are point samples. Recording advances on fixed interval boundaries
without accumulating loop delays; the airtime denominator uses a separate actual
measurement timestamp. TX/RX values are unsigned counter deltas in
milliseconds divided by the actual elapsed interval, multiplied by 100. Percentages
use the sensor protocol's integer LPP encoding, so fractional percentages are truncated.
NaN temperatures and the radio driver's uncalibrated noise-floor sentinel (0 dBm)
are skipped. At most five series are returned, below the eight-series reply limit.
## Query and retention
Use the [sensor-compatible `0x04` request](payloads.md#get-minmaxave-sensor-and-repeater-nodes):
start and end are seconds ago, followed by two zero reserved bytes. For example,
`start=3600, end=0` selects samples from the last hour, including age zero and excluding
age 3600. The reply echoes the request timestamp, adds the current RTC time, and then
encodes each series as channel, LPP type, min, max, average. There is no series count.
Empty series are omitted; an empty range returns just the eight-byte header.
Sampling and queries use monotonic uptime, accumulated across `millis()` wraps. The
RTC is used only for the response timestamp. Samples occupy a fixed interval grid
anchored at the first valid sample. Missed intervals are empty (NaN) slots; a gap
at least as long as the ring capacity expires the old ring. Late readings are assigned
to their interval boundary, so their reported age can differ by less than one interval.
Only one timestamp is stored per series.
Unsigned second differences handle seconds-counter wrap; retained samples and query
ranges must span less than one full 32-bit seconds cycle (about 136 years).
The first sample is recorded after one interval. Each series retains the configured
number of interval slots, including missing intervals. History is lost on reboot and
is not written to flash.
## Build flags
| Flag | Default | Description |
|------|---------|-------------|
| `REPEATER_HISTORY_INTERVAL_SECS` | `300` | Positive recording interval in seconds |
| `REPEATER_HISTORY_SLOTS` | `288`, or `0` on STM32/RP2040 | Interval slots per series; nominally 24 hours at five-minute intervals when enabled |
Set these using PlatformIO `build_flags`, for example `-D REPEATER_HISTORY_SLOTS=144`
for nominally 12 hours. `-D REPEATER_HISTORY_SLOTS=0` removes history members,
allocations, sampling, and handling of `0x04` entirely. STM32 and RP2040 builds default
to disabled history to conserve RAM; they can explicitly opt in with a smaller slot count.
There are no history CLI settings.
For both nRF52 and ESP32, sample storage is `5 * slots * 4` bytes (one float per
interval), or 5,760 bytes at the defaults. Comparing enabled and disabled builds shows
168 additional bytes in the enclosing mesh object on both platforms (including padding),
for a total of 5,928 bytes plus allocator overhead for five arrays. Unsupported temperature still reserves
its series storage. Query results use temporary stack space, not retained history RAM.
## Custom sensor sketch compatibility
The old `examples/simple_sensor/TimeSeriesData.h` include forwards to the shared helper.
Deprecated `RTCClock*` overloads remain available for existing custom sketches. They
ignore the RTC and use a shared, wrap-safe `millis()` accumulator; callers should migrate
to explicit monotonic seconds. Call the legacy API regularly enough to observe each
`millis()` wrap (less than about 49 days between calls), and use one clock API consistently
for each series. The shared legacy clock is linked only when these overloads are used.
The integer literal `0` is ambiguous between the seconds and pointer overloads. Use a
`uint32_t` variable (or `uint32_t(0)`) for uptime zero, and `nullptr` for a legacy null
clock argument.
+46
View File
@@ -993,6 +993,8 @@ void MyMesh::begin() {
_prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, -9, MAX_LORA_TX_POWER);
_prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 1); // Ensure boolean 0 or 1
_prefs.gps_interval = constrain(_prefs.gps_interval, 0, 86400); // Max 24 hours
_prefs.adc_multiplier = constrain(_prefs.adc_multiplier, 0.0f, 10.0f);
if (!board.setAdcMultiplier(_prefs.adc_multiplier)) _prefs.adc_multiplier = 0.0f;
_active_ble_pin = _prefs.ble_pin;
@@ -2093,6 +2095,11 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
return true;
}
if (_prefs.getGpsPrefs()->handleCommand(command, sensors, reply)) {
if (_prefs.getGpsPrefs()->isDirty()) { savePrefs(); }
return true;
}
// hook for variant-specific CLI processing
if (board.handleCommand(command, sender_timestamp, reply)) {
if (_prefs.isDirty()) { savePrefs(); }
@@ -2210,6 +2217,33 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
return true;
}
if (memcmp(command, "set adc.multiplier ", 19) == 0) { // same as CommonCLI
float mult = atof(&command[19]);
if (mult < 0.0f || mult > 10.0f) {
strcpy(reply, "Error, must be from 0 to 10");
} else if (board.setAdcMultiplier(mult)) {
_prefs.adc_multiplier = mult;
savePrefs();
if (mult == 0.0f) {
strcpy(reply, "OK - using default board multiplier");
} else {
sprintf(reply, "OK - multiplier set to %.3f", mult);
}
} else {
strcpy(reply, "Error: unsupported");
}
return true;
}
if (strcmp(command, "get adc.multiplier") == 0) {
float mult = board.getAdcMultiplier();
if (mult == 0.0f) {
strcpy(reply, "Error: unsupported");
} else {
sprintf(reply, "> %.3f", mult);
}
return true;
}
if (strcmp(command, "get tz.offset") == 0) {
float q = _prefs.tz_offset * 4;
sprintf(reply, (q == (int)q && ((int)q & 1)) ? "> %.2f" : "> %.1f", _prefs.tz_offset);
@@ -2286,6 +2320,18 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
sprintf(reply, "> ui.nd_name is now %d", _prefs.ui_nd_name);
return true;
}
if (memcmp(command, "set ui.gps_action", 17) == 0) {
const char* v = &command[17];
while (*v == ' ') v++;
_prefs.ui_gps_action = (memcmp(v, "once", 4) == 0 || memcmp(v, "trigger", 7) == 0 || *v == '1') ? 1 : 0; // anything else: toggle
savePrefs();
sprintf(reply, "> now %s", _prefs.ui_gps_action ? "once" : "toggle");
return true;
}
if (memcmp(command, "get ui.gps_action", 17) == 0) {
sprintf(reply, "> %s", _prefs.ui_gps_action ? "once" : "toggle");
return true;
}
if (memcmp(command, "get ui.show_clock", 17) == 0) {
sprintf(reply, "> %d", _prefs.ui_show_clock);
return true;
+6 -5
View File
@@ -203,12 +203,13 @@ public:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
sensors.setSettingValue("gps", _prefs.gps_enabled ? "1" : "0");
if (_prefs.gps_interval > 0) {
char interval_str[12]; // Max: 24 hours = 86400 seconds (5 digits + null)
sprintf(interval_str, "%u", _prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval_str);
if (_prefs.gps_interval > 0 &&
sensors.getSettingByKey("gps_interval") != nullptr) {
char interval[11];
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval);
}
_prefs.getGpsPrefs()->apply(sensors);
}
#endif
+36 -3
View File
@@ -2,6 +2,7 @@
#include <cstdint> // For uint8_t, uint32_t
#include <helpers/ConfigSerializer.h>
#include <helpers/CommonRadioPrefs.h>
#include <helpers/CommonGpsPrefs.h>
#include <helpers/DynamicConfigSerializer.h>
#define TELEM_MODE_DENY 0
@@ -35,6 +36,9 @@ public:
uint8_t vibe_quiet = 0;
uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled)
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
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)
uint8_t radio_fem_rxgain = 0; // external LoRa FEM RX gain (LNA)
@@ -48,6 +52,7 @@ public:
char default_scope_name[31];
uint8_t default_scope_key[16];
float tz_offset = 0;
float adc_multiplier = 0; // battery ADC multiplier, 0 = board default
#ifdef ENABLE_WIFI_INTERFACE
#ifndef WIFI_SSID
#define WIFI_SSID ""
@@ -85,6 +90,11 @@ public:
uint8_t ui_auto_off_keep_msgs = 1;
uint8_t ui_max_partial = EINK_MAX_PARTIAL_REFRESH;
uint8_t ui_nd_name = 1;
#ifdef PIN_GPS_SWITCH
uint8_t ui_gps_action = 1;
#else
uint8_t ui_gps_action = 0;
#endif
#endif
private:
@@ -151,16 +161,36 @@ private:
};
RadioPrefs radio;
class GPSPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
class GPSPrefs : public CommonGpsPrefs {
NodePrefs* _parent;
protected:
void structure() override {
def("en", _parent->gps_enabled); // boolean
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);
#ifdef GPS_GUARD
def("fence", _parent->gps_fence);
def("guard", _parent->gps_guard);
#endif
}
public:
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
bool isGpsEnabled() const override { return _parent->gps_enabled; }
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 getGuardFence(uint32_t& metres) const override {
if (_parent->gps_fence < 0) return false;
metres = (uint32_t)_parent->gps_fence;
return true;
}
void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); }
bool getGuardEnabled(bool& enabled) const override {
enabled = _parent->gps_guard != 0;
return true;
}
void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); }
};
GPSPrefs gps;
@@ -194,6 +224,7 @@ private:
def("tel_loc", _parent->telemetry_mode_loc);
def("tel_env", _parent->telemetry_mode_env);
def("tz_offset", _parent->tz_offset);
def("adc_mult", _parent->adc_multiplier);
}
public:
CompanionPrefs(NodePrefs* parent) : _parent(parent) { }
@@ -231,6 +262,7 @@ private:
def("off_blank", _parent->ui_auto_off_blank);
def("off_keep_msgs", _parent->ui_auto_off_keep_msgs);
def("nd_name", _parent->ui_nd_name);
def("gps_act", _parent->ui_gps_action);
}
public:
UI_Prefs(NodePrefs* parent) : _parent(parent) {}
@@ -275,8 +307,9 @@ public:
void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; }
CommonRadioPrefs* getRadioPrefs() { return &radio; }
CommonGpsPrefs* getGpsPrefs() { return &gps; }
KeyValueStore* getCustom() { return &custom; }
bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); }
void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); }
bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); }
void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); }
};
+58 -1
View File
@@ -2,6 +2,11 @@
#include <Mesh.h>
#include "MyMesh.h"
#if defined(ENABLE_WIFI_INTERFACE) && defined(ENABLE_ESP_MDNS)
#define HAS_ESP_MDNS
#include <ESPmDNS.h>
#endif
// Believe it or not, this std C function is busted on some platforms!
static uint32_t _atoi(const char* sp) {
uint32_t n = 0;
@@ -132,6 +137,10 @@ void halt() {
bool wifi_enabled = false; // set at boot from prefs; false also when the effective SSID is blank
#endif
#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP)
static void loopDuringDisplayRefresh();
#endif
void setup() {
Serial.begin(115200);
board.begin();
@@ -266,6 +275,33 @@ void setup() {
interface_manager.addInterface(InterfaceType::Ethernet, &ethernet_interface);
#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 c = nodeName[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_') {
sanitizedNodeName += c;
}
}
String mdnsName = "meshcore_";
mdnsName += sanitizedNodeName;
if (!MDNS.begin(mdnsName.c_str())) {
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", "firmware-version", FIRMWARE_VERSION);
String protocol; protocol+=FIRMWARE_VER_CODE;
MDNS.addServiceTxt("meshcore", "tcp", "protocol-version", protocol.c_str());
MDNS.addServiceTxt("meshcore", "tcp", "build-date", __DATE__);
MDNS.addServiceTxt("meshcore", "tcp", "build-time", __TIME__);
}
#endif
// add hardware serial interface
#if defined(SERIAL_RX)
companion_serial.setPins(SERIAL_RX, SERIAL_TX);
@@ -284,15 +320,36 @@ void setup() {
#ifdef DISPLAY_CLASS
ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved
the_mesh.setListener(&ui_task);
#ifdef EINK_REFRESH_LOOP
if (disp != NULL) disp->setBusyHook(loopDuringDisplayRefresh);
#endif
#endif
board.onBootComplete();
}
void loop() {
// Work that must keep running even while the UI is blocked (e.g. by an e-ink refresh).
// Called from loop() and from the display busy hook, so both always run the same set.
static void loopCore() {
the_mesh.loop();
interface_manager.loop();
sensors.loop();
}
#if defined(DISPLAY_CLASS) && defined(EINK_REFRESH_LOOP)
// Runs from inside the e-ink busy wait, so radio/BLE/sensors keep going during a panel refresh.
// Must not touch the display: UI listener callbacks only update state and schedule the next frame.
static void loopDuringDisplayRefresh() {
static bool active = false;
if (active) return;
active = true;
loopCore();
active = false;
}
#endif
void loop() {
loopCore();
#ifdef DISPLAY_CLASS
ui_task.loop();
#endif
+59 -17
View File
@@ -86,6 +86,30 @@ public:
}
};
#if ENV_INCLUDE_GPS == 1
// exact period with the largest unit that divides it: "30s", "5m", "2h"
static void formatGpsPeriod(char* buf, size_t size, uint32_t seconds) {
if (seconds % 3600 == 0) {
snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600));
} else if (seconds % 60 == 0) {
snprintf(buf, size, "%lum", (unsigned long)(seconds / 60));
} else {
snprintf(buf, size, "%lus", (unsigned long)seconds);
}
}
// age of the last fix, rounded down to a single unit: "45s", "12m", "3h"
static void formatFixAge(char* buf, size_t size, uint32_t seconds) {
if (seconds < 60) {
snprintf(buf, size, "%lus", (unsigned long)seconds);
} else if (seconds < 3600) {
snprintf(buf, size, "%lum", (unsigned long)(seconds / 60));
} else {
snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600));
}
}
#endif
class HomeScreen : public UIScreen {
enum HomePage {
FIRST,
@@ -418,16 +442,28 @@ public:
char buf[50];
int y = 18;
bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH);
if (gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
} else {
strcpy(buf, gps_state ? "gps on" : "gps off");
bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled();
uint32_t period = nmea != NULL ? nmea->getGpsPeriod() : 0;
char fix_buf[12] = "";
if (nmea != NULL) {
uint32_t fix_age = nmea->getLastFixAge();
if (fix_age == UINT32_MAX) {
strcpy(fix_buf, "no fix");
} else {
formatFixAge(fix_buf, sizeof(fix_buf), fix_age);
}
}
if (nmea != NULL && nmea->hasHardwareEnableState() && gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
} else if (!gps_state) {
strcpy(buf, "gps off");
} else if (period == 0) {
strcpy(buf, "gps on");
} else {
char per[12];
formatGpsPeriod(per, sizeof(per), period);
snprintf(buf, sizeof(buf), "%s (%s)", nmea != NULL && nmea->isActive() ? "active" : "sleep", per);
}
#else
strcpy(buf, gps_state ? "gps on" : "gps off");
#endif
display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) {
@@ -436,8 +472,7 @@ public:
display.drawTextLeftAlign(0, y, "Can't access GPS");
} else {
display.setColor(UIColor::primary_txt);
strcpy(buf, nmea->isValid()?"fix":"no fix");
display.drawTextRightAlign(display.width()-1, y, buf);
display.drawTextRightAlign(display.width()-1, y, fix_buf);
y = y + 12;
display.setColor(UIColor::secondary_txt);
display.drawTextLeftAlign(0, y, "sat");
@@ -626,7 +661,7 @@ public:
}
#if ENV_INCLUDE_GPS == 1
if (c == KEY_ENTER && _page == HomePage::GPS) {
_task->toggleGPS();
if (_node_prefs->ui_gps_action == 1) _task->triggerGPS(); else _task->toggleGPS();
return true;
}
#endif
@@ -1245,16 +1280,14 @@ void UITask::toggleGPS() {
for (int i = 0; i < num; i++) {
if (strcmp(_sensors->getSettingName(i), "gps") == 0) {
if (strcmp(_sensors->getSettingValue(i), "1") == 0) {
_sensors->setSettingValue("gps", "0");
_node_prefs->gps_enabled = 0;
_node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false);
notify(UIEventType::ack);
} else {
_sensors->setSettingValue("gps", "1");
_node_prefs->gps_enabled = 1;
_node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true);
notify(UIEventType::ack);
}
the_mesh.savePrefs();
showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800);
showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800);
_next_refresh = 0;
break;
}
@@ -1262,6 +1295,15 @@ void UITask::toggleGPS() {
}
}
void UITask::triggerGPS() {
LocationProvider* location = _sensors != NULL ? _sensors->getLocationProvider() : NULL;
if (location != NULL && !(location->hasHardwareEnableState() && !location->isHardwareEnabled())
&& location->startOnce()) {
notify(UIEventType::ack);
}
_next_refresh = 0;
}
void UITask::toggleBuzzer() {
// Toggle buzzer quiet mode
#ifdef PIN_BUZZER
+1
View File
@@ -119,6 +119,7 @@ public:
void toggleBuzzer();
bool getGPSState();
void toggleGPS();
void triggerGPS();
// MyMesh::Listener
void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override;
+3 -2
View File
@@ -609,14 +609,15 @@ void UITask::handleButtonQuadruplePress() {
for (int i = 0; i < num; i++) {
if (strcmp(_sensors->getSettingName(i), "gps") == 0) {
if (strcmp(_sensors->getSettingValue(i), "1") == 0) {
_sensors->setSettingValue("gps", "0");
_node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false);
notify(UIEventType::ack);
sprintf(_alert, "GPS: Disabled");
} else {
_sensors->setSettingValue("gps", "1");
_node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true);
notify(UIEventType::ack);
sprintf(_alert, "GPS: Enabled");
}
the_mesh.savePrefs();
break;
}
}
+7 -9
View File
@@ -254,16 +254,16 @@ public:
char buf[50];
int y = 8;
bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH);
bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled();
if (nmea != NULL && nmea->hasHardwareEnableState()) {
if (gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
} else {
strcpy(buf, gps_state ? "gps on" : "gps off");
}
#else
} else {
strcpy(buf, gps_state ? "gps on" : "gps off");
#endif
}
display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) {
@@ -833,16 +833,14 @@ void UITask::toggleGPS() {
for (int i = 0; i < num; i++) {
if (strcmp(_sensors->getSettingName(i), "gps") == 0) {
if (strcmp(_sensors->getSettingValue(i), "1") == 0) {
_sensors->setSettingValue("gps", "0");
_node_prefs->gps_enabled = 0;
_node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false);
notify(UIEventType::ack);
} else {
_sensors->setSettingValue("gps", "1");
_node_prefs->gps_enabled = 1;
_node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true);
notify(UIEventType::ack);
}
the_mesh.savePrefs();
showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800);
showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800);
_next_refresh = 0;
break;
}
+103 -5
View File
@@ -1,5 +1,8 @@
#include "MyMesh.h"
#include <algorithm>
#if REPEATER_HISTORY_SLOTS > 0
#include <helpers/sensors/LPPDataHelpers.h>
#endif
/* ------------------------------ Config -------------------------------- */
@@ -46,6 +49,9 @@
#define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
#define REQ_TYPE_KEEP_ALIVE 0x02
#define REQ_TYPE_GET_TELEMETRY_DATA 0x03
#if REPEATER_HISTORY_SLOTS > 0
#define REQ_TYPE_GET_AVG_MIN_MAX 0x04
#endif
#define REQ_TYPE_GET_ACCESS_LIST 0x05
#define REQ_TYPE_GET_NEIGHBOURS 0x06
#define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2
@@ -209,6 +215,7 @@ uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender
}
int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
if (payload_len == 0) return 0;
// uint32_t now = getRTCClock()->getCurrentTimeUnique();
// memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
@@ -259,6 +266,48 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
return 4 + tlen; // reply_len
}
#if REPEATER_HISTORY_SLOTS > 0
if (payload[0] == REQ_TYPE_GET_AVG_MIN_MAX && payload_len >= 11 &&
(sender->permissions & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) {
uint32_t start_secs_ago, end_secs_ago;
memcpy(&start_secs_ago, &payload[1], 4);
memcpy(&end_secs_ago, &payload[5], 4);
MinMaxAvg data[8];
int n = 0;
if (payload[9] == 0 && payload[10] == 0) {
uint32_t now_secs = uptime_millis / 1000;
battery_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_BATTERY,
LPP_VOLTAGE);
noise_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_NOISE,
LPP_ANALOG_INPUT);
tx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_TX,
LPP_PERCENTAGE);
rx_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n++], HISTORY_RX,
LPP_PERCENTAGE);
temperature_history.calcMinMaxAvg(now_secs, start_secs_ago, end_secs_ago, &data[n], HISTORY_TEMPERATURE,
LPP_TEMPERATURE);
// Unsupported temperature sensors and empty ranges have no encodable LPP value.
if (!isnan(data[n]._avg)) n++;
}
uint8_t ofs = 4;
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(&reply_data[ofs], &now, 4);
ofs += 4;
for (int i = 0; i < n; i++) {
auto d = &data[i];
if (isnan(d->_avg)) continue;
reply_data[ofs++] = d->_channel;
reply_data[ofs++] = d->_lpp_type;
uint8_t sz = LPPData::getDataSize(d->_lpp_type);
uint32_t mult = LPPData::getMultiplier(d->_lpp_type);
bool is_signed = LPPData::isSigned(d->_lpp_type);
ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed);
ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed);
ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed);
}
return ofs;
}
#endif
if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
uint8_t res1 = payload[1]; // reserved for future (extra query params)
uint8_t res2 = payload[2];
@@ -862,6 +911,13 @@ void MyMesh::sendNodeDiscoverReq() {
MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
mesh::RTCClock &rtc, mesh::MeshTables &tables)
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
#if REPEATER_HISTORY_SLOTS > 0
battery_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS),
noise_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS),
tx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS),
rx_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS),
temperature_history(REPEATER_HISTORY_SLOTS, REPEATER_HISTORY_INTERVAL_SECS),
#endif
region_map(key_store), temp_map(key_store),
_cli(board, rtc, sensors, region_map, acl, &_prefs, this),
telemetry(MAX_PACKET_PAYLOAD - 4),
@@ -876,6 +932,12 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
{
last_millis = 0;
uptime_millis = 0;
#if REPEATER_HISTORY_SLOTS > 0
history_last_secs = history_battery_secs = history_airtime_secs = 0;
history_tx_millis = history_rx_millis = 0;
history_battery_total = 0;
history_battery_count = 0;
#endif
next_local_advert = next_flood_advert = 0;
dirty_contacts_expiry = 0;
set_radio_at = revert_radio_at = 0;
@@ -1286,7 +1348,48 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
}
}
#if REPEATER_HISTORY_SLOTS > 0
void MyMesh::recordHistory() {
uint32_t now_secs = uptime_millis / 1000;
// Average periodic reads without repeatedly enabling the battery divider.
if (uint32_t(now_secs - history_battery_secs) >= 15) {
history_battery_total += board.getBattMilliVolts();
history_battery_count++;
history_battery_secs = now_secs;
}
uint32_t elapsed_secs = now_secs - history_last_secs;
if (elapsed_secs < REPEATER_HISTORY_INTERVAL_SECS) return;
// Advance the sampling grid without accumulating loop delays or replaying missed slots.
history_last_secs += (elapsed_secs / REPEATER_HISTORY_INTERVAL_SECS) * REPEATER_HISTORY_INTERVAL_SECS;
uint32_t airtime_elapsed_secs = now_secs - history_airtime_secs;
if (history_battery_count > 0) {
battery_history.recordData(history_last_secs, history_battery_total / history_battery_count / 1000.0f);
}
int noise_floor = _radio->getNoiseFloor();
if (noise_floor != 0) noise_history.recordData(history_last_secs, noise_floor); // zero means uncalibrated
uint32_t tx_millis = getTotalAirTime();
uint32_t rx_millis = getReceiveAirTime();
// Counters are milliseconds; unsigned subtraction also handles their wrap.
tx_history.recordData(history_last_secs, uint32_t(tx_millis - history_tx_millis) / (airtime_elapsed_secs * 10.0f));
rx_history.recordData(history_last_secs, uint32_t(rx_millis - history_rx_millis) / (airtime_elapsed_secs * 10.0f));
temperature_history.recordData(history_last_secs, board.getMCUTemperature()); // ignores NaN
history_airtime_secs = now_secs;
history_tx_millis = tx_millis;
history_rx_millis = rx_millis;
history_battery_total = 0;
history_battery_count = 0;
}
#endif
void MyMesh::loop() {
// Update before dispatching requests, including across millis() wrap.
uint32_t now = millis();
uptime_millis += uint32_t(now - last_millis);
last_millis = now;
#if REPEATER_HISTORY_SLOTS > 0
recordHistory();
#endif
#ifdef WITH_BRIDGE
bridge.loop();
#endif
@@ -1324,11 +1427,6 @@ void MyMesh::loop() {
acl.save(_fs);
dirty_contacts_expiry = 0;
}
// update uptime
uint32_t now = millis();
uptime_millis += now - last_millis;
last_millis = now;
}
// To check if there is pending work
+34 -1
View File
@@ -37,6 +37,22 @@
#include <helpers/RoutingPolicy.h>
#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 <helpers/TimeSeriesData.h>
static_assert(REPEATER_HISTORY_INTERVAL_SECS > 0, "History interval must be positive");
#endif
#ifdef WITH_BRIDGE
extern AbstractBridge* bridge;
#endif
@@ -82,6 +98,16 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
FILESYSTEM* _fs;
uint32_t last_millis;
uint64_t uptime_millis;
#if REPEATER_HISTORY_SLOTS > 0
// Dedicated history channels 200..204; environment telemetry occupies 1..17.
enum { HISTORY_BATTERY = 200, HISTORY_NOISE, HISTORY_TX, HISTORY_RX, HISTORY_TEMPERATURE };
TimeSeriesData battery_history, noise_history, tx_history, rx_history, temperature_history;
uint32_t history_last_secs, history_battery_secs, history_airtime_secs;
uint32_t history_tx_millis, history_rx_millis;
float history_battery_total;
uint32_t history_battery_count;
void recordHistory();
#endif
unsigned long next_local_advert, next_flood_advert;
bool _logging;
NodePrefs _prefs;
@@ -159,7 +185,14 @@ protected:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
if (sensors.getSettingByKey("gps_interval") != nullptr) {
// gps_interval was introduced only for EnvironmentSensorManager
// and has little interest ... kept only as a legacy
char interval[11];
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval);
}
_prefs.getGpsPrefs()->apply(sensors);
}
#endif
+2 -2
View File
@@ -140,7 +140,7 @@ mesh::Packet *MyMesh::createSelfAdvert() {
}
File MyMesh::openAppend(const char *fname) {
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
return _fs->open(fname, FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
return _fs->open(fname, "a");
@@ -782,7 +782,7 @@ void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr,
}
bool MyMesh::formatFileSystem() {
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
return InternalFS.format();
#elif defined(RP2040_PLATFORM)
return LittleFS.format();
+9 -2
View File
@@ -3,7 +3,7 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include <InternalFileSystem.h>
#elif defined(RP2040_PLATFORM)
#include <LittleFS.h>
@@ -168,7 +168,14 @@ protected:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
if (sensors.getSettingByKey("gps_interval") != nullptr) {
// gps_interval was introduced only for EnvironmentSensorManager
// and has little interest ... kept only as a legacy
char interval[11];
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval);
}
_prefs.getGpsPrefs()->apply(sensors);
}
#endif
+1 -1
View File
@@ -50,7 +50,7 @@ void setup() {
fast_rng.begin(radio_driver.getRngSeed());
FILESYSTEM* fs;
#if defined(NRF52_PLATFORM)
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
InternalFS.begin();
fs = &InternalFS;
IdentityStore store(InternalFS, "");
+9 -3
View File
@@ -789,7 +789,9 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise
{
next_local_advert = next_flood_advert = 0;
dirty_contacts_expiry = 0;
last_read_time = 0;
last_read_time = uint32_t(0) - SENSOR_READ_INTERVAL_SECS; // read immediately on the first loop
last_millis = 0;
uptime_millis = 0;
num_alert_tasks = 0;
set_radio_at = revert_radio_at = 0;
recv_pkt_region = NULL;
@@ -999,6 +1001,9 @@ bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) {
}
void SensorMesh::loop() {
uint32_t now = millis();
uptime_millis += uint32_t(now - last_millis);
last_millis = now;
mesh::Mesh::loop();
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
@@ -1028,7 +1033,8 @@ void SensorMesh::loop() {
}
uint32_t curr = getRTCClock()->getCurrentTime();
if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) {
uint32_t uptime_secs = getUptimeSeconds();
if (uint32_t(uptime_secs - last_read_time) >= SENSOR_READ_INTERVAL_SECS) {
telemetry.reset();
telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
// query other sensors -- target specific
@@ -1069,7 +1075,7 @@ void SensorMesh::loop() {
onSensorDataRead();
last_read_time = curr;
last_read_time = uptime_secs;
}
// check the alert send queue
+10 -2
View File
@@ -3,7 +3,7 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include "TimeSeriesData.h"
#include <helpers/TimeSeriesData.h>
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include <InternalFileSystem.h>
@@ -88,6 +88,7 @@ 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); }
@@ -154,6 +155,8 @@ 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];
@@ -173,7 +176,12 @@ private:
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0");
if (sensors.getSettingByKey("gps_interval") != nullptr) {
char interval[11];
snprintf(interval, sizeof(interval), "%lu", (unsigned long)_prefs.gps_interval);
sensors.setSettingValue("gps_interval", interval);
}
_prefs.getGpsPrefs()->apply(sensors);
}
#endif
};
-45
View File
@@ -1,45 +0,0 @@
#include "TimeSeriesData.h"
void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) {
uint32_t now = clock->getCurrentTime();
if (now >= last_timestamp + interval_secs) {
last_timestamp = now;
data[next] = value; // append to cycle table
next = (next + 1) % num_slots;
}
}
void TimeSeriesData::calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const {
int i = next, n = num_slots;
uint32_t ago = clock->getCurrentTime() - last_timestamp;
int num_values = 0;
float total = 0.0f;
dest->_channel = channel;
dest->_lpp_type = lpp_type;
// start at most recet recording, back-track through to oldest
while (n > 0) {
n--;
i = (i + num_slots - 1) % num_slots; // go back by one
if (ago >= end_secs_ago && ago < start_secs_ago) { // filter by the desired time range
float v = data[i];
num_values++;
total += v;
if (num_values == 1) {
dest->_max = dest->_min = v;
} else {
if (v < dest->_min) dest->_min = v;
if (v > dest->_max) dest->_max = v;
}
}
ago += interval_secs;
}
// calc average
if (num_values > 0) {
dest->_avg = total / num_values;
} else {
dest->_max = dest->_min = dest->_avg = NAN;
}
}
+2 -27
View File
@@ -1,29 +1,4 @@
#pragma once
#include <Arduino.h>
#include <Mesh.h>
struct MinMaxAvg {
float _min, _max, _avg;
uint8_t _lpp_type, _channel;
};
class TimeSeriesData {
float* data;
int num_slots, next;
uint32_t last_timestamp;
uint32_t interval_secs;
public:
TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) {
memset(data, 0, sizeof(float)*num);
}
TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) {
data = new float[num];
memset(data, 0, sizeof(float)*num);
}
void recordData(mesh::RTCClock* clock, float value);
void calcMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const;
};
// Compatibility include for custom sensor sketches; implementation lives in src/helpers.
#include <helpers/TimeSeriesData.h>
+3 -2
View File
@@ -21,13 +21,14 @@ protected:
void onSensorDataRead() override {
float batt_voltage = getVoltage(TELEM_CHANNEL_SELF);
battery_data.recordData(getRTCClock(), batt_voltage); // record battery
battery_data.recordData(getUptimeSeconds(), batt_voltage); // record battery
alertIf(batt_voltage < 3.4f, critical_batt, HIGH_PRI_ALERT, "Battery is critical!");
alertIf(batt_voltage < 3.6f, low_batt, LOW_PRI_ALERT, "Battery is low");
}
int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override {
battery_data.calcMinMaxAvg(getRTCClock(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE);
battery_data.calcMinMaxAvg(getUptimeSeconds(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF,
LPP_VOLTAGE);
return 1;
}
+11
View File
@@ -168,15 +168,26 @@ 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
+13 -62
View File
@@ -211,6 +211,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (sender_timestamp > curr) {
getRTCClock()->setCurrentTime(sender_timestamp + 1);
CommonGpsPrefs::onClockSetManually(*_sensors);
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
@@ -230,6 +231,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
uint32_t curr = getRTCClock()->getCurrentTime();
if (secs > curr) {
getRTCClock()->setCurrentTime(secs);
CommonGpsPrefs::onClockSetManually(*_sensors);
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(reply, "OK - clock set: %02d:%02d - %d/%d/%d UTC", dt.hour(), dt.minute(), dt.day(), dt.month(), dt.year());
@@ -349,52 +351,17 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
*(dp-1) = 0; // remove last CR
}
}
} else if (_prefs->getGpsPrefs()->handleCommand(command, *_sensors, reply)) {
if (_prefs->getGpsPrefs()->isDirty()) savePrefs();
} else if (memcmp(command, "region", 6) == 0) {
handleRegionCmd(command, reply);
#if ENV_INCLUDE_GPS == 1
} else if (memcmp(command, "gps on", 6) == 0) {
if (_sensors->setSettingValue("gps", "1")) {
_prefs->gps_enabled = 1;
savePrefs();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps toggle not found");
}
} else if (memcmp(command, "gps off", 7) == 0) {
if (_sensors->setSettingValue("gps", "0")) {
_prefs->gps_enabled = 0;
savePrefs();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps toggle not found");
}
} else if (memcmp(command, "gps sync", 8) == 0) {
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
l->syncTime();
strcpy(reply, "ok");
} else {
strcpy(reply, "gps provider not found");
}
} else if (strcmp(command, "gps diag") == 0) {
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
const char* setting = _sensors->getSettingByKey("gps");
bool requested = setting != NULL && strcmp(setting, "1") == 0;
int prefix_len = snprintf(reply, 160, "req:%u ", requested ? 1U : 0U);
if (prefix_len < 0 || prefix_len >= 160) {
reply[159] = 0;
} else {
l->formatDiagnostics(reply + prefix_len, 160 - prefix_len);
}
} else {
strcpy(reply, "gps provider not found");
}
} else if (memcmp(command, "gps setloc", 10) == 0) {
_prefs->node_lat = _sensors->node_lat;
_prefs->node_lon = _sensors->node_lon;
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else if (memcmp(command, "gps advert", 10) == 0) {
if (strlen(command) == 10) {
switch (_prefs->advert_loc_policy) {
@@ -408,40 +375,22 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
strcpy(reply, "> share");
break;
default:
strcpy(reply, "error");
strcpy(reply, "Error, invalid policy");
}
} else if (memcmp(command+11, "none", 4) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_NONE;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else if (memcmp(command+11, "share", 5) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_SHARE;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else if (memcmp(command+11, "prefs", 5) == 0) {
_prefs->advert_loc_policy = ADVERT_LOC_PREFS;
savePrefs();
strcpy(reply, "ok");
strcpy(reply, "OK");
} else {
strcpy(reply, "error");
}
} else if (memcmp(command, "gps", 3) == 0) {
LocationProvider * l = _sensors->getLocationProvider();
if (l != NULL) {
bool enabled = l->isEnabled(); // is EN pin on ?
bool fix = l->isValid(); // has fix ?
int sats = l->satellitesCount();
bool active = !strcmp(_sensors->getSettingByKey("gps"), "1");
if (enabled) {
sprintf(reply, "on, %s, %s, %d sats",
active?"active":"deactivated",
fix?"fix":"no fix",
sats);
} else {
strcpy(reply, "off");
}
} else {
strcpy(reply, "Can't find GPS");
strcpy(reply, "Error, invalid policy");
}
#endif
} else if (memcmp(command, "powersaving on", 14) == 0) {
@@ -549,10 +498,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, _prefs->disable_fwd ? "OK - repeat is now OFF" : "OK - repeat is now ON");
} else if (memcmp(config, "lat ", 4) == 0) {
_prefs->node_lat = atof(&config[4]);
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config, "lon ", 4) == 0) {
_prefs->node_lon = atof(&config[4]);
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config, "flood.max.unscoped ", 19) == 0) {
+33 -3
View File
@@ -7,6 +7,7 @@
#include <helpers/RegionMap.h>
#include <helpers/ConfigSerializer.h>
#include <helpers/CommonRadioPrefs.h>
#include <helpers/CommonGpsPrefs.h>
#include <helpers/DynamicConfigSerializer.h>
#if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE)
@@ -61,6 +62,9 @@ public:
// Gps settings
uint8_t gps_enabled = 0;
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
uint8_t gps_guard = 1; // GPS_GUARD on/off
uint8_t advert_loc_policy = 0;
uint32_t discovery_mod_timestamp = 0;
float adc_multiplier = 0;
@@ -152,16 +156,41 @@ private:
};
BridgePrefs bridge;
class GPSPrefs : public ConfigSerializer {
class GPSPrefs : public CommonGpsPrefs {
NodePrefs* _parent;
protected:
void structure() override {
def("en", _parent->gps_enabled); // boolean
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);
#ifdef GPS_GUARD
def("fence", _parent->gps_fence);
def("guard", _parent->gps_guard);
#endif
}
public:
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
bool isGpsEnabled() const override { return _parent->gps_enabled; }
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 getGuardFence(uint32_t& metres) const override {
if (_parent->gps_fence < 0) return false;
metres = (uint32_t)_parent->gps_fence;
return true;
}
void setGuardFence(uint32_t metres) override { _parent->gps_fence = (int32_t)metres; markDirty(); }
bool getGuardEnabled(bool& enabled) const override {
enabled = _parent->gps_guard != 0;
return true;
}
void setGuardEnabled(bool enabled) override { _parent->gps_guard = enabled ? 1 : 0; markDirty(); }
bool getGuardReference(double& lat, double& lon) const override {
lat = _parent->node_lat;
lon = _parent->node_lon;
return true;
}
};
GPSPrefs gps;
@@ -234,10 +263,11 @@ public:
}
CommonRadioPrefs* getRadioPrefs() { return &radio; }
CommonGpsPrefs* getGpsPrefs() { return &gps; }
KeyValueStore* getCustom() { return &custom; }
bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || custom.isDirty(); }
void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); custom.clearDirty(); }
bool isDirty() const override { return ConfigSerializer::isDirty() || radio.isDirty() || gps.isDirty() || custom.isDirty(); }
void clearDirty() override { ConfigSerializer::clearDirty(); radio.clearDirty(); gps.clearDirty(); custom.clearDirty(); }
};
class CommonCLICallbacks {
+285
View File
@@ -0,0 +1,285 @@
#include "CommonGpsPrefs.h"
#include <helpers/sensors/LocationProvider.h>
#ifdef GPS_GUARD
#include <helpers/sensors/GpsGuard.h>
#endif
bool CommonGpsPrefs::setGpsEnabled(SensorManager& sensors, bool enabled) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) return false;
location->setGpsOn(enabled);
setGpsEnabled(enabled);
return true;
}
bool CommonGpsPrefs::setGpsPeriod(SensorManager& sensors, uint32_t seconds) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) return false;
location->setGpsPeriod(seconds);
setGpsPeriod(seconds);
return true;
}
void CommonGpsPrefs::applyGuardReference(SensorManager& sensors) const {
#ifdef GPS_GUARD
LocationProvider* location = sensors.getLocationProvider();
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
double lat, lon;
if (guard != nullptr && getGuardReference(lat, lon)) guard->setReference(lat, lon);
uint32_t fence;
if (guard != nullptr && getGuardFence(fence)) guard->setFence(fence);
bool enabled;
if (guard != nullptr && getGuardEnabled(enabled)) guard->setEnabled(enabled);
#endif
}
// The clock was set by hand: the guard drops its GPS time anchor and any alert.
void CommonGpsPrefs::onClockSetManually(SensorManager& sensors) {
#ifdef GPS_GUARD
LocationProvider* location = sensors.getLocationProvider();
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
if (guard != nullptr) guard->clockSetManually();
#endif
}
bool CommonGpsPrefs::apply(SensorManager& sensors) const {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) return false;
applyGuardReference(sensors);
location->setGpsPeriod(getGpsPeriod());
location->setGpsOn(isGpsEnabled());
return true;
}
// single unit, rounded down: "45s", "12m", "3h"
static void formatDuration(char* buf, size_t size, uint32_t seconds) {
if (seconds < 60) {
snprintf(buf, size, "%lus", (unsigned long)seconds);
} else if (seconds < 3600) {
snprintf(buf, size, "%lum", (unsigned long)(seconds / 60));
} else {
snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600));
}
}
bool CommonGpsPrefs::handleCommand(const char* command, SensorManager& sensors, char* reply) {
if (strcmp(command, "gps") == 0) {
LocationProvider* location = sensors.getLocationProvider();
char mode[32];
if (getGpsPeriod() == 0) {
strcpy(mode, "continuous");
} else {
snprintf(mode, sizeof(mode), "periodic (%lus)",
(unsigned long)getGpsPeriod());
}
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
} else if (location->isGpsOn()) {
const char* activity = "active";
if (!location->isActive()) {
if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) {
activity = "off(hw)";
} else if (getGpsPeriod() > 0) {
activity = "waiting";
} else {
activity = "inactive";
}
}
char fix[32];
if (location->hasValidFix()) {
char age[12];
formatDuration(age, sizeof(age), location->getLastFixAge());
snprintf(fix, sizeof(fix), "%ld sats %s ago", location->satellitesCount(), age);
} else {
strcpy(fix, "no fix");
}
snprintf(reply, 160, "> on, %s, %s, %s", activity, fix, mode);
} else {
snprintf(reply, 160, "> off, %s", mode);
}
return true;
}
if (strcmp(command, "gps fix") == 0) {
LocationProvider* location = sensors.getLocationProvider();
char acq[16] = "";
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
return true;
}
if (location->isActive()) {
char t[12];
formatDuration(t, sizeof(t), location->getAcquisitionAge());
snprintf(acq, sizeof(acq), "acq %s", t);
}
if (!location->hasValidFix()) {
snprintf(reply, 160, "> No fix%s%s", acq[0] ? ", " : "", acq);
} else {
const long latitude = location->getLatitude();
const long longitude = location->getLongitude();
char pos[40];
snprintf(pos, sizeof(pos), "%.6f, %.6f", latitude / 1e6, longitude / 1e6);
if (location->isValid()) {
snprintf(reply, 160, "> Fix (%d sat): %s", location->satellitesCount(), pos);
} else {
char age[12];
formatDuration(age, sizeof(age), location->getLastFixAge());
snprintf(reply, 160, "> Fix %s ago (%d sat)%s%s: %s", age, location->satellitesCount(),acq[0] ? ", " : "", acq, pos);
}
}
return true;
}
if (memcmp(command, "gps once", 8) == 0) { // before "gps on"
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
return true;
}
if (location->hasHardwareEnableState() && !location->isHardwareEnabled()) {
strcpy(reply, "Error, gps hw switch off");
return true;
}
if (strstr(command, " -s") != nullptr) location->syncTime();
const char* state = !location->isGpsOn() ? "turning on and acquiring"
: (location->getGpsPeriod() > 0 && !location->isActive()) ? "waking gps"
: "gps already on";
if (location->startOnce()) {
snprintf(reply, 160, "OK - %s", state);
} else {
strcpy(reply, "Error, gps once not supported");
}
return true;
}
if (memcmp(command, "gps on", 6) == 0) {
if (!setGpsEnabled(sensors, true)) {
strcpy(reply, "Error, gps toggle not found");
} else {
strcpy(reply, "OK");
}
return true;
}
if (memcmp(command, "gps off", 7) == 0) {
if (!setGpsEnabled(sensors, false)) {
strcpy(reply, "Error, gps toggle not found");
} else {
strcpy(reply, "OK");
}
return true;
}
if (strcmp(command, "gps period") == 0) {
if (getGpsPeriod() == 0) {
strcpy(reply, "> 0 (continuous)");
} else {
sprintf(reply, "> %lu", (unsigned long)getGpsPeriod());
}
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') {
strcpy(reply, "Error, invalid gps period");
} else if (!setGpsPeriod(sensors, (uint32_t)(period * mult)) ||
!setGpsEnabled(sensors, true)) {
strcpy(reply, "Error, gps provider not found");
} else {
strcpy(reply, "OK");
}
return true;
}
if (memcmp(command, "gps sync", 8) == 0) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
} else {
location->syncTime();
strcpy(reply, "OK");
}
return true;
}
if (strcmp(command, "gps fix_stats") == 0) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
} else {
const LocationProvider::FixStats s = location->getFixStats();
char last[12] = "-", max[12] = "-";
if (s.maxTtffMs > 0) {
formatDuration(last, sizeof(last), (s.lastTtffMs + 500) / 1000);
formatDuration(max, sizeof(max), (s.maxTtffMs + 500) / 1000);
}
snprintf(reply, 160, "> ttf:%s/%s ok:%lu miss:%lu", last, max,
(unsigned long)s.consecutiveFixes, (unsigned long)s.consecutiveMisses);
}
return true;
}
#ifdef GPS_GUARD
if (memcmp(command, "gps guard", 9) == 0 || memcmp(command, "gps fence", 9) == 0 ||
strcmp(command, "gps ref") == 0) {
LocationProvider* location = sensors.getLocationProvider();
GpsGuard* guard = location != nullptr ? location->getGuard() : nullptr;
if (guard == nullptr) {
strcpy(reply, "Error, gps guard not supported");
} else if (strcmp(command, "gps guard") == 0) {
reply[0] = '>'; reply[1] = ' ';
guard->formatStatus(reply + 2, 158);
} else if (strcmp(command, "gps guard on") == 0 || strcmp(command, "gps guard off") == 0) {
const bool enabled = command[11] == 'n';
guard->setEnabled(enabled);
setGuardEnabled(enabled); // saved by the caller (isDirty)
strcpy(reply, "OK");
} else if (strcmp(command, "gps guard accept") == 0) {
// operator confirms that the alerted GPS time is right: apply it to the clock
long offset;
if (!guard->isTimeAlert()) {
strcpy(reply, "Error, no time alert");
} else if (!location->getClockOffset(offset) ||
!guard->acceptAlertedTime(offset, (uint32_t)location->getTimestamp()) ||
!location->applyTimeNow()) {
strcpy(reply, "Error, no current trusted fix with the alerted time");
} else {
strcpy(reply, "OK - clock set from GPS");
}
} else if (strcmp(command, "gps fence") == 0) {
sprintf(reply, "> %lu", (unsigned long)guard->getFence());
} else if (memcmp(command, "gps fence ", 10) == 0) {
char* end;
unsigned long metres = strtoul(command + 10, &end, 10);
if (command[10] == '\0' || *end != '\0' || metres > 20000000UL) { // at most half the Earth
strcpy(reply, "Error, invalid fence");
} else {
guard->setFence((uint32_t)metres);
setGuardFence((uint32_t)metres); // saved by the caller (isDirty)
strcpy(reply, "OK");
}
} else if (strcmp(command, "gps ref") == 0) {
snprintf(reply, 160, "> %.6f, %.6f", guard->getRefLat(), guard->getRefLon());
} else {
return false;
}
return true;
}
#endif
if (strcmp(command, "gps diag") == 0) {
LocationProvider* location = sensors.getLocationProvider();
if (location == nullptr) {
strcpy(reply, "Error, gps provider not found");
} else {
int prefix = snprintf(reply, 160, "> req:%u ", isGpsEnabled() ? 1U : 0U);
if (prefix >= 0 && prefix < 160) location->formatDiagnostics(reply + prefix, 160 - prefix);
}
return true;
}
return false;
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "ConfigSerializer.h"
#include "SensorManager.h"
class CommonGpsPrefs : public ConfigSerializer {
bool _is_dirty = false;
protected:
CommonGpsPrefs() = default;
public:
void markDirty() { _is_dirty = true; }
void clearDirty() { _is_dirty = false; }
bool isDirty() const { return _is_dirty; }
virtual bool isGpsEnabled() const = 0;
virtual void setGpsEnabled(bool enabled) = 0;
virtual uint32_t getGpsPeriod() const = 0;
virtual void setGpsPeriod(uint32_t seconds) = 0;
// 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; }
// Saved fence radius for the guard; false = not set, use the build default.
virtual bool getGuardFence(uint32_t& metres) const { return false; }
virtual void setGuardFence(uint32_t metres) { }
// Saved on/off state of the guard; false = not set, guard on.
virtual bool getGuardEnabled(bool& enabled) const { return false; }
virtual void setGuardEnabled(bool enabled) { }
bool setGpsEnabled(SensorManager& sensors, bool enabled);
void applyGuardReference(SensorManager& sensors) const;
static void onClockSetManually(SensorManager& sensors);
bool setGpsPeriod(SensorManager& sensors, uint32_t seconds);
bool apply(SensorManager& sensors) const;
bool handleCommand(const char* command, SensorManager& sensors, char* reply);
};
+2
View File
@@ -63,11 +63,13 @@ void ESP32Board::enterDeepSleep(uint32_t secs) {
radio_driver.powerOff();
// Keep LoRa inactive during deepsleep
#ifdef P_LORA_NSS
digitalWrite(P_LORA_NSS, HIGH);
#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6)
gpio_hold_en((gpio_num_t)P_LORA_NSS);
#else
rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS);
#endif
#endif
// Power off GPS if any
+6
View File
@@ -69,9 +69,11 @@ public:
virtual void powerOff() override;
void enterDeepSleep(uint32_t secs);
#ifdef P_LORA_DIO_1
uint32_t getIRQGpio() override {
return P_LORA_DIO_1; // default for SX1262
}
#endif
void sleep(uint32_t secs) override {
// Skip if not allow to sleep
@@ -82,6 +84,10 @@ public:
// Set GPIO wakeup
gpio_num_t wakeupPin = (gpio_num_t)getIRQGpio();
if (wakeupPin == GPIO_NUM_NC) { // no radio IRQ pin to wake on
delay(1);
return;
}
// Configure timer wakeup
if (secs > 0) {
+4
View File
@@ -14,10 +14,13 @@ public:
digitalWrite(_pin, !_active); // initial state
}
// Both set the level, then make the pin an output again, since other code may have left it
// an input. On a RAK19007 with a RAK12501, WB_IO2 left as an input keeps 3V3_S in its last state.
void claim() {
_claims++;
if (_claims > 0) {
digitalWrite(_pin, _active);
pinMode(_pin, OUTPUT);
}
}
@@ -27,6 +30,7 @@ public:
_claims--;
if (_claims == 0) {
digitalWrite(_pin, !_active);
pinMode(_pin, OUTPUT);
}
}
};
+91
View File
@@ -0,0 +1,91 @@
#include "TimeSeriesData.h"
#include <Arduino.h>
#include <math.h>
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);
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <stdint.h>
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;
};
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include "NmeaGpsDriver.h"
class AirohaGpsDriver : public NmeaGpsDriver {
bool waitFor(const char* prefix, uint32_t timeout_ms) { // TODO: Refactor so it doesn't block the loop !
char sentence[100];
size_t length = 0;
const size_t prefixLength = strlen(prefix);
const uint32_t deadline = millis() + timeout_ms;
while ((int32_t)(millis() - deadline) < 0) {
if (available() <= 0) {
yield();
continue;
}
const char c = (char)read();
#ifdef GPS_NMEA_DEBUG
Serial.print(c);
#endif
if (c == '$') length = 0;
if (length < sizeof(sentence) - 1) {
sentence[length++] = c;
sentence[length] = '\0';
if (length >= prefixLength && strncmp(sentence, prefix, prefixLength) == 0) {
return true;
}
}
}
return false;
}
void enterBackupSleep() {
for (uint8_t attempt = 0; attempt < 3; attempt++) {
drain();
sendNmeaSentence("$PAIR650,0");
if (waitFor("$PAIR001,650,0", 50)) {
#ifdef GPS_NMEA_DEBUG
Serial.printf("Airoha RTC backup sleep accepted after %u attempts\r\n", attempt + 1);
#endif
waitFor("$PAIR650,0", 50);
return;
}
}
}
public:
AirohaGpsDriver(UART_TYPE& serial)
: NmeaGpsDriver(serial, -1, -1, -1, -1, nullptr, HIGH, LOW, GPS_BAUD_RATE) {}
void initialize() {
NmeaGpsDriver::begin();
reset();
}
void begin() override {
NmeaGpsDriver::begin();
digitalWrite(GPS_EN, HIGH);
delay(10);
digitalWrite(GPS_RTC_INT, HIGH);
delay(5);
digitalWrite(GPS_RTC_INT, LOW);
}
void reset() override {
digitalWrite(GPS_RESET, HIGH);
delay(10);
digitalWrite(GPS_RESET, LOW);
}
void stop() override {
digitalWrite(GPS_VRTC_EN, HIGH);
digitalWrite(GPS_RTC_INT, LOW);
enterBackupSleep();
digitalWrite(GPS_EN, LOW);
NmeaGpsDriver::stop();
}
bool isActive() const override {
return digitalRead(GPS_EN) == HIGH;
}
};
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include <helpers/sensors/LocationProvider.h>
// Board must keep the GPS RTC backup pin powered and can cut GPS power once we return.
// Returns true if the command was acked within 3 attempts, otherwise returns false.
static inline bool airohaEnterSleep(LocationProvider* nmea) {
for (uint8_t attempt = 0; attempt < 3; attempt++) {
nmea->drain();
nmea->sendSentence("$PAIR650,0");
if (nmea->waitFor("$PAIR001,650,0", 50)) { // wait for the command received signal
#ifdef GPS_NMEA_DEBUG
Serial.printf("Airoha RTC Backup sleep command accepted by GPS after %u attempts\r\n", attempt + 1);
#endif
nmea->waitFor("$PAIR650,0", 50); // give the GPS 50ms grace to signal it is ready for sleep
return true;
}
}
return false;
}
+35 -235
View File
@@ -1,6 +1,9 @@
#include "EnvironmentSensorManager.h"
#include <Wire.h>
#if ENV_INCLUDE_GPS && defined(GPS_GUARD)
#include <helpers/sensors/GpsGuard.h>
#endif
#if ENV_PIN_SDA && ENV_PIN_SCL
#define TELEM_WIRE &Wire1 // Use Wire1 as the I2C bus for Environment Sensors
@@ -160,56 +163,6 @@ static Adafruit_VL53L0X VL53L0X;
static RAK12035_SoilMoisture RAK12035;
#endif
#if ENV_INCLUDE_GPS && defined(RAK_BOARD) && !defined(RAK_WISMESH_TAG)
#define RAK_WISBLOCK_GPS
#endif
#ifdef RAK_WISBLOCK_GPS
static uint32_t gpsResetPin = 0;
static bool i2cGPSFlag = false;
static bool serialGPSFlag = false;
#ifndef TELEM_RAK12500_ADDRESS
#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c
#endif
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
static SFE_UBLOX_GNSS ublox_GNSS;
class RAK12500LocationProvider : public LocationProvider {
long _lat = 0;
long _lng = 0;
long _alt = 0;
int _sats = 0;
long _epoch = 0;
bool _fix = false;
public:
long getLatitude() override { return _lat; }
long getLongitude() override { return _lng; }
long getAltitude() override { return _alt; }
long satellitesCount() override { return _sats; }
bool isValid() override { return _fix; }
long getTimestamp() override { return _epoch; }
void sendSentence(const char * sentence) override { }
void reset() override { }
void begin() override { }
void stop() override { }
void loop() override {
if (ublox_GNSS.getGnssFixOk(8)) {
_fix = true;
_lat = ublox_GNSS.getLatitude(2) / 10;
_lng = ublox_GNSS.getLongitude(2) / 10;
_alt = ublox_GNSS.getAltitude(2);
_sats = ublox_GNSS.getSIV(2);
} else {
_fix = false;
}
_epoch = ublox_GNSS.getUnixEpoch(2);
}
bool isEnabled() override { return true; }
};
static RAK12500LocationProvider RAK12500_provider;
#endif
// ============================================================
// I2C bus scanner
// Probes every valid address and records which ones ACK.
@@ -375,14 +328,17 @@ static void query_ina3221(uint8_t ch, uint8_t sub_ch, CayenneLPP& lpp) {
#endif
#if ENV_INCLUDE_INA219
static uint8_t init_ina219(TwoWire* wire, uint8_t) {
// INA219 static instance was constructed with the address; begin() uses it.
return INA219.begin(wire) ? 1 : 0;
static Adafruit_INA219 INA219_ALT((TELEM_INA219_ADDRESS == 0x40) ? 0x41 : 0x40);
static Adafruit_INA219* active_ina219 = &INA219;
static uint8_t init_ina219(TwoWire* wire, uint8_t addr) {
active_ina219 = (addr == TELEM_INA219_ADDRESS) ? &INA219 : &INA219_ALT;
return active_ina219->begin(wire) ? 1 : 0;
}
static void query_ina219(uint8_t ch, uint8_t, CayenneLPP& lpp) {
lpp.addVoltage(ch, INA219.getBusVoltage_V());
lpp.addCurrent(ch, INA219.getCurrent_mA() / 1000.0f);
lpp.addPower(ch, INA219.getPower_mW() / 1000.0f);
lpp.addVoltage(ch, active_ina219->getBusVoltage_V());
lpp.addCurrent(ch, active_ina219->getCurrent_mA() / 1000.0f);
lpp.addPower(ch, active_ina219->getPower_mW() / 1000.0f);
}
#endif
@@ -554,6 +510,7 @@ struct SensorDef {
};
#define TELEM_BOSCH_ALT_ADDR(addr) ((uint8_t)((addr) == 0x76 ? 0x77 : 0x76))
#define TELEM_INA219_ALT_ADDR(addr) ((uint8_t)((addr) == 0x40 ? 0x41 : 0x40))
static const SensorDef SENSOR_TABLE[] = {
#if ENV_INCLUDE_AHTX0
@@ -589,6 +546,7 @@ static const SensorDef SENSOR_TABLE[] = {
#endif
#if ENV_INCLUDE_INA219
{ TELEM_INA219_ADDRESS, "INA219", init_ina219, query_ina219 },
{ TELEM_INA219_ALT_ADDR(TELEM_INA219_ADDRESS), "INA219", init_ina219, query_ina219 },
#endif
#if ENV_INCLUDE_INA260
{ TELEM_INA260_ADDRESS, "INA260", init_ina260, query_ina260 },
@@ -612,6 +570,7 @@ static const SensorDef SENSOR_TABLE[] = {
};
#undef TELEM_BOSCH_ALT_ADDR
#undef TELEM_INA219_ALT_ADDR
static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TABLE[0])) - 1;
@@ -624,12 +583,8 @@ static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TA
bool EnvironmentSensorManager::begin() {
#if ENV_INCLUDE_GPS
#ifdef RAK_WISBLOCK_GPS
rakGPSInit();
#else
initBasicGPS();
#endif
#endif
#if ENV_PIN_SDA && ENV_PIN_SCL
#ifdef NRF52_PLATFORM
@@ -684,15 +639,24 @@ bool EnvironmentSensorManager::begin() {
bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) {
next_available_channel = TELEM_CHANNEL_SELF + 1;
if (requester_permissions & TELEM_PERM_LOCATION && gps_active) {
#if ENV_INCLUDE_GPS
if (requester_permissions & TELEM_PERM_LOCATION && _location->isGpsOn()) {
telemetry.addGPS(TELEM_CHANNEL_SELF, node_lat, node_lon, node_altitude);
}
#endif
if (requester_permissions & TELEM_PERM_ENVIRONMENT) {
for (int i = 0; i < _active_sensor_count; i++) {
_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;
@@ -702,7 +666,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen
int EnvironmentSensorManager::getNumSettings() const {
int settings = 0;
#if ENV_INCLUDE_GPS
if (gps_detected) settings++; // only show GPS setting if GPS is detected
if (gps_detected) settings += 1; // GPS enablement
#endif
return settings;
}
@@ -721,7 +685,7 @@ const char* EnvironmentSensorManager::getSettingValue(int i) const {
int settings = 0;
#if ENV_INCLUDE_GPS
if (gps_detected && i == settings++) {
return gps_active ? "1" : "0";
return _location->isGpsOn() ? "1" : "0";
}
#endif
return NULL;
@@ -748,157 +712,16 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val
#if ENV_INCLUDE_GPS
void EnvironmentSensorManager::initBasicGPS() {
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
Serial1.begin(GPS_BAUD_RATE);
#else
Serial1.begin(9600);
#endif
// Try to detect if GPS is physically connected to determine if we should expose the setting
_location->begin();
_location->reset();
#ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("No GPS wake/reset pin found for this board. Continuing on...");
#endif
// Give the GPS time to power up and emit its first NMEA sentence. Cold-start
// modules can take several seconds, so poll for up to ~5s instead of checking
// once after a fixed 1s delay -- returning as soon as any data appears, so
// fast modules add no boot delay (issue #2258).
#ifdef ENV_SKIP_GPS_DETECT
gps_detected = true;
#else
gps_detected = false;
for (int i = 0; i < 20 && !gps_detected; i++) {
delay(250);
gps_detected = (Serial1.available() > 0);
}
#endif
if (gps_detected) {
MESH_DEBUG_PRINTLN("GPS detected");
#ifdef PERSISTANT_GPS
gps_active = true;
return;
#endif
} else {
MESH_DEBUG_PRINTLN("No GPS detected");
}
_location->stop();
gps_active = false; //Set GPS visibility off until setting is changed
gps_detected = _location->autoDetect();
MESH_DEBUG_PRINTLN("%s", gps_detected ? "GPS detected" : "No GPS detected");
}
// gps code for rak might be moved to MicroNMEALoactionProvider
// or make a new location provider ...
#ifdef RAK_WISBLOCK_GPS
void EnvironmentSensorManager::rakGPSInit(){
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
Serial1.begin(GPS_BAUD_RATE);
#else
Serial1.begin(9600);
#endif
//search for the correct IO standby pin depending on socket used
if(gpsIsAwake(WB_IO2)){
}
else if(gpsIsAwake(WB_IO4)){
}
else if(gpsIsAwake(WB_IO5)){
}
else{
MESH_DEBUG_PRINTLN("No GPS found");
gps_active = false;
gps_detected = false;
Serial1.end();
return;
}
#ifndef FORCE_GPS_ALIVE // for use with repeaters, until GPS toggle is implimented
//Now that GPS is found and set up, set to sleep for initial state
stop_gps();
#endif
}
bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin){
#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD)
if (ioPin == WB_IO2) {
// WB_IO2 powers the Ethernet module on RAK baseboards.
return false;
}
#endif
#ifndef RAK_3401
//set initial waking state
pinMode(ioPin,OUTPUT);
digitalWrite(ioPin,LOW);
delay(500);
digitalWrite(ioPin,HIGH);
#endif
// give gps time to power up
delay(500);
//Try to init RAK12500 on I2C
if (ublox_GNSS.begin(Wire) == true){
MESH_DEBUG_PRINTLN("RAK12500 GPS init correctly with pin %i",ioPin);
ublox_GNSS.setI2COutput(COM_TYPE_UBX);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS);
ublox_GNSS.setMeasurementRate(1000);
ublox_GNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT);
gpsResetPin = ioPin;
i2cGPSFlag = true;
gps_active = true;
gps_detected = true;
_location = &RAK12500_provider;
return true;
} else if (Serial1.available()) {
MESH_DEBUG_PRINTLN("Serial GPS init correctly and is turned on");
#ifdef PIN_GPS_EN
if(PIN_GPS_EN){
gpsResetPin = PIN_GPS_EN;
}
#endif
serialGPSFlag = true;
gps_active = true;
gps_detected = true;
return true;
}
#ifndef RAK_3401
pinMode(ioPin, INPUT);
#endif
MESH_DEBUG_PRINTLN("GPS did not init with this IO pin... try the next");
return false;
}
#endif
void EnvironmentSensorManager::start_gps() {
gps_active = true;
#ifdef RAK_WISBLOCK_GPS
#ifndef RAK_3401
pinMode(gpsResetPin, OUTPUT);
digitalWrite(gpsResetPin, HIGH);
#endif
return;
#endif
_location->begin();
_location->reset();
_location->setGpsOn(true);
#ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("Start GPS is N/A on this board. Actual GPS state unchanged");
@@ -906,20 +729,11 @@ void EnvironmentSensorManager::start_gps() {
}
void EnvironmentSensorManager::stop_gps() {
gps_active = false;
#ifdef RAK_WISBLOCK_GPS
#ifndef RAK_3401 // rak3401 shouldn't turn off WB_IO2 as it powers the PA
pinMode(gpsResetPin, OUTPUT);
digitalWrite(gpsResetPin, LOW);
#endif
return;
#endif
_location->setGpsOn(false);
_location->stop();
#ifndef PIN_GPS_EN
#ifndef PIN_GPS_EN
MESH_DEBUG_PRINTLN("Stop GPS is N/A on this board. Actual GPS state unchanged");
#endif
#endif
}
#endif // ENV_INCLUDE_GPS
@@ -928,30 +742,16 @@ void EnvironmentSensorManager::loop() {
#if ENV_INCLUDE_GPS
static unsigned long next_gps_update = 0;
if (gps_active) {
_location->loop();
}
_location->loop();
if ((long)(millis() - next_gps_update) > 0) {
if(gps_active){
#ifdef RAK_WISBLOCK_GPS
if ((i2cGPSFlag || serialGPSFlag) && _location->isValid()) {
if (_location->isGpsOn() && _location->hasValidFix()) {
node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.;
MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon);
node_altitude = ((double)_location->getAltitude()) / 1000.0;
MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude);
}
#else
if (_location->isValid()) {
node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.;
MESH_DEBUG_PRINTLN("lat %f lon %f", node_lat, node_lon);
node_altitude = ((double)_location->getAltitude()) / 1000.0;
MESH_DEBUG_PRINTLN("lat %f lon %f alt %f", node_lat, node_lon, node_altitude);
}
#endif
}
next_gps_update = millis() + (gps_update_interval_sec * 1000);
}
#endif
@@ -20,7 +20,6 @@ protected:
uint8_t next_available_channel = TELEM_CHANNEL_SELF + 1;
bool gps_detected = false;
bool gps_active = false;
uint32_t gps_update_interval_sec = 1;
#if ENV_INCLUDE_GPS
@@ -28,10 +27,6 @@ protected:
void start_gps();
void stop_gps();
void initBasicGPS();
#ifdef RAK_BOARD
void rakGPSInit();
bool gpsIsAwake(uint8_t ioPin);
#endif
#endif
public:
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <stdint.h>
class GpsDriver {
public:
virtual ~GpsDriver() = default;
virtual void begin() = 0;
virtual void reset() = 0;
virtual void stop() = 0;
virtual bool isActive() const = 0;
virtual bool hasHardwareEnableState() const { return false; }
virtual bool isHardwareEnabled() const { return true; }
// Returns true when the switch explicitly enables GPS in software.
virtual bool pollGpsSwitch() { return false; }
virtual bool detect(uint32_t timeout_ms) = 0;
};
+300
View File
@@ -0,0 +1,300 @@
#pragma once
// GPS anti-spoofing guard (opt-in with GPS_GUARD).
//
// A location provider asks the guard before it stores a fix as its last fix and before it
// writes GPS time to the clock:
// - acceptFix(): plausibility checks (satellites, HDOP, optional build-time region, distance
// from a reference position, jump speed) and N consecutive consistent fixes;
// - acceptTime(): GPS time only while a trusted fix is current, not before this firmware
// was built, and once the clock is valid only small corrections (clock drift after the
// first accepted sync), so a spoofer cannot walk the clock away.
// A trusted fix that keeps disagreeing with the clock by the same offset raises an alert;
// the operator can then accept that GPS time (acceptAlertedTime()).
#include <Arduino.h>
#include <MeshCore.h>
#include <RTClib.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef GPS_GUARD_MIN_SATS
#define GPS_GUARD_MIN_SATS 4
#endif
#ifndef GPS_GUARD_MAX_HDOP10
#define GPS_GUARD_MAX_HDOP10 40 // HDOP 4.0
#endif
#ifndef GPS_GUARD_FENCE_M
#define GPS_GUARD_FENCE_M 1000 // max distance from the reference position (0 = off)
#endif
#ifndef GPS_GUARD_STABLE_FIXES
#define GPS_GUARD_STABLE_FIXES 5 // consecutive consistent fixes (one per GPS second)
#endif
#ifndef GPS_GUARD_STABLE_M
#define GPS_GUARD_STABLE_M 100
#endif
#ifndef GPS_GUARD_MAX_SPEED_KMH
#define GPS_GUARD_MAX_SPEED_KMH 250 // jump limit relative to the last trusted fix
#endif
#ifndef GPS_GUARD_TIME_MAX_STEP
#define GPS_GUARD_TIME_MAX_STEP 600 // max GPS-vs-clock correction (s) once the clock is valid
#endif
#ifndef GPS_GUARD_TIME_DRIFT_BASE
#define GPS_GUARD_TIME_DRIFT_BASE 5 // after the first sync: fixed allowance (s) ...
#endif
#ifndef GPS_GUARD_TIME_DRIFT_PPM
#define GPS_GUARD_TIME_DRIFT_PPM 100 // ... plus clock drift since that sync (~8.6 s/day)
#endif
#ifndef GPS_GUARD_ALERT_MIN
#define GPS_GUARD_ALERT_MIN 60 // alert after GPS disagrees with the clock this long ...
#endif
#ifndef GPS_GUARD_ALERT_TOLERANCE
#define GPS_GUARD_ALERT_TOLERANCE 60 // ... by an offset that stays within this many seconds
#endif
#ifndef GPS_GUARD_TRUSTED_MS
#define GPS_GUARD_TRUSTED_MS 5000 // a trusted fix is "current" for this long
#endif
class GpsGuard {
bool _enabled = true; // off: every fix and GPS time passes, as without GPS_GUARD
double _ref_lat = 0, _ref_lon = 0; // 0,0 = no reference position
uint32_t _fence_m = GPS_GUARD_FENCE_M;
bool _have_trusted = false;
unsigned long _last_trusted_ms = 0;
double _last_trusted_lat = 0, _last_trusted_lon = 0;
double _cand_lat = 0, _cand_lon = 0;
uint32_t _cand_time = 0; // GPS second of the last counted candidate
uint32_t _rej_log_time = 0; // GPS second of the last logged rejection
uint8_t _stable_count = 0;
char _fix_status[24] = "no fix";
char _time_status[24] = "-";
bool _time_accepted = false; // a GPS time sync was accepted (drift budget anchor)
unsigned long _last_time_accept_ms = 0;
bool _time_disagree = false;
long _time_disagree_offset = 0; // GPS minus clock, seconds
unsigned long _time_disagree_since_ms = 0;
bool _time_alert = false;
static double distanceM(double lat1, double lon1, double lat2, double lon2) {
const double R = 6371000.0, D2R = 0.017453292519943295;
double dlat = (lat2 - lat1) * D2R, dlon = (lon2 - lon1) * D2R;
double a = sin(dlat / 2) * sin(dlat / 2) +
cos(lat1 * D2R) * cos(lat2 * D2R) * sin(dlon / 2) * sin(dlon / 2);
return 2 * R * atan2(sqrt(a), sqrt(1 - a));
}
bool trustedFixIsCurrent() const {
return _have_trusted && (uint32_t)(millis() - _last_trusted_ms) <= GPS_GUARD_TRUSTED_MS;
}
void trackTimeDisagreement(long offset) {
const unsigned long now = millis();
if (!_time_disagree || labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) {
_time_disagree = true;
_time_disagree_offset = offset;
_time_disagree_since_ms = now;
_time_alert = false;
return;
}
if (!_time_alert && (uint32_t)(now - _time_disagree_since_ms) >= GPS_GUARD_ALERT_MIN * 60000UL) {
_time_alert = true;
MESH_DEBUG_PRINTLN("GPS TIME ALERT: GPS differs from clock by %lds for %u min", offset, GPS_GUARD_ALERT_MIN);
}
}
public:
// Plausible GPS time window: not before this firmware was built, at most 10 years after.
static uint32_t minEpoch() {
static const uint32_t min_epoch = DateTime(__DATE__, __TIME__).unixtime() - 86400;
return min_epoch;
}
static uint32_t maxEpoch() { return minEpoch() + 10UL * 365 * 86400; }
void setReference(double lat, double lon) { _ref_lat = lat; _ref_lon = lon; }
double getRefLat() const { return _ref_lat; }
double getRefLon() const { return _ref_lon; }
void setFence(uint32_t metres) { _fence_m = metres; }
uint32_t getFence() const { return _fence_m; }
bool hasTrustedFix() const { return _have_trusted; }
bool isEnabled() const { return _enabled; }
void setEnabled(bool enabled) {
if (enabled == _enabled) return;
_enabled = enabled;
// start over: a re-enabled guard needs fresh stable fixes, and no alert survives
_have_trusted = false;
_stable_count = 0;
_time_accepted = false;
_time_disagree = false;
_time_alert = false;
strcpy(_fix_status, "no fix");
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.
bool acceptFix(long lat_e6, long lon_e6, long sats, uint8_t hdop10, uint32_t gps_time) {
const double lat = lat_e6 / 1000000.0;
const double lon = lon_e6 / 1000000.0;
const unsigned long now = millis();
if (!_enabled) return true;
const char* why = NULL;
double dist = 0;
if (sats < GPS_GUARD_MIN_SATS) {
why = "sats";
} else if (hdop10 == 255 || hdop10 > GPS_GUARD_MAX_HDOP10) {
why = "hdop";
}
#if defined(GPS_GUARD_LAT_MIN) && defined(GPS_GUARD_LAT_MAX) && defined(GPS_GUARD_LON_MIN) && defined(GPS_GUARD_LON_MAX)
else if (lat < GPS_GUARD_LAT_MIN || lat > GPS_GUARD_LAT_MAX || lon < GPS_GUARD_LON_MIN || lon > GPS_GUARD_LON_MAX) {
why = "region";
}
#endif
else if (_fence_m > 0 && (_ref_lat != 0 || _ref_lon != 0) &&
(dist = distanceM(_ref_lat, _ref_lon, lat, lon)) > _fence_m) {
why = "fence";
} else if (_have_trusted) {
dist = distanceM(_last_trusted_lat, _last_trusted_lon, lat, lon);
double secs = (uint32_t)(now - _last_trusted_ms) / 1000.0;
if (secs < 1) secs = 1;
if (dist / secs > GPS_GUARD_MAX_SPEED_KMH / 3.6) why = "jump";
}
if (why) {
_stable_count = 0;
if (dist > 0) {
snprintf(_fix_status, sizeof(_fix_status), "rej %s %.1fkm", why, dist / 1000.0);
} else {
snprintf(_fix_status, sizeof(_fix_status), "rej %s", why);
}
if (gps_time == 0 || gps_time != _rej_log_time) { // GGA and RMC report the same second: log it once
_rej_log_time = gps_time;
MESH_DEBUG_PRINTLN("GPS fix rejected (%s): %f,%f sats=%ld hdop=%u", why, lat, lon, sats, hdop10);
}
return false;
}
if (!_have_trusted || _stable_count < GPS_GUARD_STABLE_FIXES) {
// Require several consecutive, mutually consistent fixes. GGA and RMC report the
// same GPS second: count each second once.
if (_stable_count > 0 && distanceM(_cand_lat, _cand_lon, lat, lon) > GPS_GUARD_STABLE_M) {
_stable_count = 0;
}
if (_stable_count == 0 || gps_time != _cand_time) {
if (_stable_count < 255) _stable_count++;
}
_cand_lat = lat;
_cand_lon = lon;
_cand_time = gps_time;
if (_stable_count < GPS_GUARD_STABLE_FIXES) {
snprintf(_fix_status, sizeof(_fix_status), "settle %u/%u", _stable_count, GPS_GUARD_STABLE_FIXES);
return false;
}
}
if (!_have_trusted) {
MESH_DEBUG_PRINTLN("GPS fix trusted: %f,%f sats=%ld hdop=%u", lat, lon, sats, hdop10);
}
_have_trusted = true;
_last_trusted_ms = now;
_last_trusted_lat = lat;
_last_trusted_lon = lon;
snprintf(_fix_status, sizeof(_fix_status), "ok %ldsat", sats);
return true;
}
// No usable fix right now (e.g. receiver lost the fix): restart the consistency count.
void noFix(long sats) {
_stable_count = 0;
snprintf(_fix_status, sizeof(_fix_status), "no fix %ldsat", sats);
}
// GPS time is only written to the clock while a trusted fix is current, it is not
// older than this firmware, and (once the clock is plausible) it only nudges the clock.
bool acceptTime(uint32_t gps_time, uint32_t clock_time) {
if (!_enabled) return true;
const char* why = NULL;
long step = 0;
if (!trustedFixIsCurrent()) {
why = "nofix";
} else if (gps_time < minEpoch() || gps_time > maxEpoch()) {
why = "range";
} else if (clock_time >= minEpoch() && clock_time <= maxEpoch()) {
// The clock already holds a plausible time. A clock outside that window (e.g. a
// bogus 2080 date at boot) is treated like an unset one, so GPS can correct it.
step = (long)gps_time - (long)clock_time;
long limit = GPS_GUARD_TIME_MAX_STEP;
if (_time_accepted) {
// After the first accepted sync only allow corrections the size of real clock
// drift, so a spoofer cannot walk the clock away in many small steps.
uint32_t elapsed_s = (uint32_t)(millis() - _last_time_accept_ms) / 1000;
limit = GPS_GUARD_TIME_DRIFT_BASE + (long)((uint64_t)elapsed_s * GPS_GUARD_TIME_DRIFT_PPM / 1000000UL);
if (limit > GPS_GUARD_TIME_MAX_STEP) limit = GPS_GUARD_TIME_MAX_STEP;
}
if (labs(step) > limit) why = "step";
}
if (why) {
if (step != 0) {
snprintf(_time_status, sizeof(_time_status), "rej %s %lds", why, step);
trackTimeDisagreement(step);
} else {
snprintf(_time_status, sizeof(_time_status), "rej %s", why);
}
return false;
}
snprintf(_time_status, sizeof(_time_status), "ok %+lds", (long)gps_time - (long)clock_time);
// Every accepted sync anchors the drift budget (fail closed: no walking the clock in
// repeated MAX_STEP jumps). A wrongly anchored time is recovered with a manual clock
// set, which resets the anchor (clockSetManually()).
_time_disagree = false;
_time_alert = false;
_time_accepted = true;
_last_time_accept_ms = millis();
return true;
}
// The clock was set by hand: drop the drift anchor and any alert.
void clockSetManually() {
_time_accepted = false;
_time_disagree = false;
_time_alert = false;
}
// Operator confirms that the alerted GPS time is right. offset = current GPS minus clock.
// Returns true if the caller may write the GPS time to the clock now.
bool acceptAlertedTime(long offset, uint32_t gps_time) {
if (!_time_alert || !trustedFixIsCurrent()) return false;
if (labs(offset - _time_disagree_offset) > GPS_GUARD_ALERT_TOLERANCE) return false; // not the alerted offset
if (gps_time < minEpoch() || gps_time > maxEpoch()) return false;
_time_accepted = true;
_last_time_accept_ms = millis();
_time_disagree = false;
_time_alert = false;
snprintf(_time_status, sizeof(_time_status), "ok manual");
return true;
}
// e.g. "ok 7sat time ok +1s", "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;
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));
} else {
snprintf(out, out_size, "%s time %s", _fix_status, time_status);
}
}
};
+86 -3
View File
@@ -5,34 +5,117 @@
#include <stdio.h>
class GpsGuard;
class LocationProvider {
public:
// Last valid fix, always filled in one go so readers get a consistent snapshot.
struct LastFix {
bool valid = false;
long latitude = 0;
long longitude = 0;
long altitude = 0;
long satellites = 0;
long timestamp = 0;
unsigned long acquiredAt = 0; // millis() when the fix was stored
};
struct FixStats {
uint32_t lastTtffMs = 0; //time to first fix in ms
uint32_t maxTtffMs = 0;
uint32_t consecutiveFixes = 0;
uint32_t consecutiveMisses = 0;
};
protected:
bool _time_sync_needed = true;
bool _gpsOn = false;
LastFix _lastFix;
FixStats _fixStats;
void fixStatsFix(uint32_t ttffMs) {
_fixStats.lastTtffMs = ttffMs;
if (ttffMs > _fixStats.maxTtffMs) _fixStats.maxTtffMs = ttffMs;
_fixStats.consecutiveFixes++;
_fixStats.consecutiveMisses = 0;
}
void fixStatsMiss() {
_fixStats.consecutiveMisses++;
_fixStats.consecutiveFixes = 0;
}
public:
virtual ~LocationProvider() = default;
virtual void syncTime() { _time_sync_needed = true; }
virtual bool waitingTimeSync() { return _time_sync_needed; }
virtual long getLatitude() = 0;
virtual long getLongitude() = 0;
virtual long getAltitude() = 0;
virtual long satellitesCount() = 0;
virtual bool isValid() = 0;
virtual bool isValid() = 0; // current fix is valid
virtual bool hasValidFix() { return getLastFix().valid || isValid(); } // a valid fix was obtained at some point
virtual LastFix getLastFix() const { return _lastFix; } // snapshot of the last valid fix
virtual FixStats getFixStats() const { return _fixStats; }
virtual long getTimestamp() = 0;
virtual void sendSentence(const char * sentence);
virtual bool waitFor(const char* prefix, uint32_t timeout_ms) { return false; }
virtual void drain() { }
virtual bool detect(uint32_t timeout_ms) { return false; }
virtual bool keepEnabledAfterDetection() const { return false; }
// Power on, detect, then leave the GPS on or off as the board wants.
// Returns true if a GPS is present.
virtual bool autoDetect() {
setGpsOn(true);
#ifdef ENV_SKIP_GPS_DETECT
bool found = true;
#else
bool found = detect(5000);
#endif
#ifdef PERSISTANT_GPS
if (found) return true;
#endif
if (found && keepEnabledAfterDetection()) return true;
setGpsOn(false);
return found;
}
virtual void setGpsPeriod(uint32_t seconds) { }
virtual uint32_t getGpsPeriod() 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;
}
virtual bool hasHardwareEnableState() const { return false; }
virtual bool isHardwareEnabled() const { return true; }
virtual bool isGpsOn() const { return _gpsOn; }
virtual uint32_t getAcquisitionAge() const { return 0; }
virtual bool startOnce() { return false; }
virtual void setGpsOn(bool on) {
_gpsOn = on;
if (on) {
begin();
reset();
} else {
stop();
}
}
virtual void reset() = 0;
virtual void begin() = 0;
virtual void stop() = 0;
virtual void loop() = 0;
virtual bool isEnabled() = 0;
virtual bool isActive() = 0;
// Format compact diagnostics in the caller-provided buffer. Providers that
// have more information (for example UART counters) can override this.
// Anti-spoofing guard (GPS_GUARD), nullptr if this provider has none
virtual GpsGuard* getGuard() { return nullptr; }
virtual bool getClockOffset(long& offset) { return false; } // GPS time minus clock time
virtual bool applyTimeNow() { return false; } // write GPS time to the clock now
virtual void formatDiagnostics(char* out, size_t out_size) {
if (out_size == 0) return;
snprintf(out, out_size, "en:%u sat:%ld fix:%u",
isEnabled() ? 1U : 0U,
isActive() ? 1U : 0U,
satellitesCount(),
isValid() ? 1U : 0U);
}
+269 -159
View File
@@ -1,69 +1,43 @@
#pragma once
#include "NmeaGpsDriver.h"
#include "LocationProvider.h"
#include <MicroNMEA.h>
#include <RTClib.h>
#include <helpers/RefCountedDigitalPin.h>
#include <string.h>
#ifndef GPS_EN
#ifdef PIN_GPS_EN
#define GPS_EN PIN_GPS_EN
#else
#define GPS_EN (-1)
#endif
#ifdef GPS_GUARD
#include "GpsGuard.h"
#endif
#ifndef GPS_EN_ACTIVE
#ifdef PIN_GPS_EN_ACTIVE
#define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE
#else
#define GPS_EN_ACTIVE HIGH
#endif
#ifndef GPS_PERIODIC_ACQUISITION_TIMEOUT_MS
#define GPS_PERIODIC_ACQUISITION_TIMEOUT_MS 300000UL
#endif
#ifndef GPS_RESET
#ifdef PIN_GPS_RESET
#define GPS_RESET PIN_GPS_RESET
#else
#define GPS_RESET (-1)
#endif
// in periodic mode, keep reading after the first valid fix until enough satellites
// are used or the settle time has elapsed
#ifndef GPS_MIN_SATS_FOR_FIX
#define GPS_MIN_SATS_FOR_FIX 5
#endif
#ifndef GPS_RESET_ACTIVE
#ifdef PIN_GPS_RESET_ACTIVE
#define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE
#else
#define GPS_RESET_ACTIVE LOW
#endif
#ifndef GPS_FIX_SETTLE_MS
#define GPS_FIX_SETTLE_MS 10000UL
#endif
class MicroNMEALocationProvider : public LocationProvider {
char _nmeaBuffer[100];
MicroNMEA nmea;
mesh::RTCClock* _clock;
Stream* _gps_serial;
RefCountedDigitalPin* _peripher_power;
int8_t _claims = 0;
int _pin_reset;
int _pin_en;
NmeaGpsDriver* _driver;
unsigned long next_check = 0;
long time_valid = 0;
unsigned long _last_time_sync = 0;
static const unsigned long TIME_SYNC_INTERVAL = 1800000; // Re-sync every 30 minutes
uint32_t _gpsPeriodSeconds = 0;
unsigned long _nextAcquisition = 0;
unsigned long _acquisitionStarted = 0;
unsigned long _firstFixInWindow = 0;
bool _acquiringPeriodically = false;
unsigned long _onceDeadline = 0;
static const unsigned long TIME_SYNC_INTERVAL = 1800000;
#ifdef GPS_L76K
void configureL76K() {
// Reapply the constellation mode at each provider start instead of
// assuming it survives a receiver power cycle.
// Mode 7 enables GPS + BeiDou + GLONASS.
delay(250);
MicroNMEA::sendSentence(*_gps_serial, "$PCAS04,7");
delay(250);
}
#endif
// Observation-only diagnostics. These fields do not change GPS power,
// timing, reset behaviour, or parser input.
uint32_t _uart_bytes = 0;
uint32_t _nmea_checksum_ok = 0;
uint32_t _nmea_checksum_bad = 0;
@@ -71,10 +45,11 @@ class MicroNMEALocationProvider : public LocationProvider {
uint32_t _stop_calls = 0;
unsigned long _last_uart_ms = 0;
unsigned long _last_nmea_ms = 0;
unsigned long _last_fix_ms = 0;
bool _uart_seen = false;
bool _nmea_seen = false;
bool _fix_seen = false;
#ifdef GPS_GUARD
GpsGuard _guard;
#endif
static uint32_t ageMs(unsigned long timestamp) {
return (uint32_t)(millis() - timestamp);
@@ -88,109 +63,226 @@ class MicroNMEALocationProvider : public LocationProvider {
}
}
public :
MicroNMEALocationProvider(Stream& ser, mesh::RTCClock* clock = NULL, int pin_reset = GPS_RESET, int pin_en = GPS_EN,RefCountedDigitalPin* peripher_power=NULL) :
nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _gps_serial(&ser), _peripher_power(peripher_power), _pin_reset(pin_reset), _pin_en(pin_en) {
if (_pin_reset != -1) {
pinMode(_pin_reset, OUTPUT);
digitalWrite(_pin_reset, GPS_RESET_ACTIVE);
}
if (_pin_en != -1) {
pinMode(_pin_en, OUTPUT);
digitalWrite(_pin_en, !GPS_EN_ACTIVE);
}
void startPeriodicAcquisition() {
nmea.clear();
time_valid = 0;
_driver->begin();
_driver->reset();
_acquiringPeriodically = true;
_acquisitionStarted = millis();
_firstFixInWindow = 0;
}
void claim() {
_claims++;
if (_peripher_power) _peripher_power->claim();
void finishPeriodicAcquisition() {
if (_firstFixInWindow == 0) fixStatsMiss();
_driver->stop();
nmea.clear(); // the parser keeps the last time as valid otherwise
time_valid = 0;
_acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
}
void release() {
if (_claims == 0) return; // avoid negative _claims
_claims--;
if (_peripher_power) _peripher_power->release();
bool saveFix() {
// only store a fix when the snapshot is coherent (sats > 0).
// Returns true if the fix was stored.
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
LastFix fix;
fix.latitude = nmea.getLatitude();
fix.longitude = nmea.getLongitude();
// altitude comes from GGA only: keep the previous one if not available
if (!nmea.getAltitude(fix.altitude)) {
fix.altitude = _lastFix.valid ? _lastFix.altitude : 0;
}
fix.satellites = nmea.getNumSatellites();
fix.timestamp = getTimestamp();
fix.acquiredAt = millis();
fix.valid = true;
_lastFix = fix;
return true;
}
void updateTime() {
if (!isValid() || (millis() - _last_nmea_ms) > 2000) time_valid = 0; // no stale time
if ((long)(millis() - next_check) <= 0) return;
next_check = millis() + 1000;
if (!_time_sync_needed && _clock != nullptr &&
(millis() - _last_time_sync) > TIME_SYNC_INTERVAL) {
_time_sync_needed = true;
}
if (_time_sync_needed && time_valid > 2 && _clock != nullptr && timeSyncAllowed()) {
_clock->setCurrentTime(getTimestamp());
_time_sync_needed = false;
_last_time_sync = millis();
}
if (isValid()) time_valid++;
}
bool timeSyncAllowed() {
#ifdef GPS_GUARD
return _guard.acceptTime(getTimestamp(), _clock->getCurrentTime());
#else
return true;
#endif
}
public:
MicroNMEALocationProvider(NmeaGpsDriver& driver, mesh::RTCClock* clock = nullptr)
: nmea(_nmeaBuffer, sizeof(_nmeaBuffer)), _clock(clock), _driver(&driver) {}
void begin() override {
_begin_calls++;
claim();
if (_pin_en != -1) {
digitalWrite(_pin_en, GPS_EN_ACTIVE);
_onceDeadline = 0;
const bool wasActive = _driver->isActive();
_driver->begin();
if (!wasActive) {
_acquisitionStarted = millis();
_firstFixInWindow = 0;
}
if (_pin_reset != -1) {
digitalWrite(_pin_reset, !GPS_RESET_ACTIVE);
if (_gpsPeriodSeconds > 0 && _driver->isActive()) {
nmea.clear();
time_valid = 0;
_acquiringPeriodically = true;
_acquisitionStarted = millis();
_firstFixInWindow = 0;
}
}
void reset() override {
if (_pin_reset != -1) {
digitalWrite(_pin_reset, GPS_RESET_ACTIVE);
delay(10);
digitalWrite(_pin_reset, !GPS_RESET_ACTIVE);
}
#ifdef GPS_L76K
// EnvironmentSensorManager calls reset() immediately after begin().
// Configure only after that reset so the setting is not discarded.
configureL76K();
#endif
_driver->reset();
}
void stop() override {
_stop_calls++;
if (_pin_en != -1) {
digitalWrite(_pin_en, !GPS_EN_ACTIVE);
}
if (_pin_reset != -1) {
digitalWrite(_pin_reset, GPS_RESET_ACTIVE);
}
release();
_onceDeadline = 0;
_acquiringPeriodically = false;
_driver->stop();
nmea.clear();
time_valid = 0;
}
bool isEnabled() override {
// directly read the enable pin if present as gps can be
// activated/deactivated outside of here ...
if (_pin_en != -1) {
return digitalRead(_pin_en) == GPS_EN_ACTIVE;
} else {
return true; // no enable so must be active
}
bool isActive() override {
return _driver->isActive();
}
void syncTime() override { nmea.clear(); LocationProvider::syncTime(); }
long getLatitude() override { return nmea.getLatitude(); }
long getLongitude() override { return nmea.getLongitude(); }
long getAltitude() override {
bool hasHardwareEnableState() const override {
return _driver->hasHardwareEnableState();
}
bool isHardwareEnabled() const override {
return _driver->isHardwareEnabled();
}
bool detect(uint32_t timeout_ms) override {
return _driver->detect(timeout_ms);
}
void setGpsPeriod(uint32_t seconds) override {
_gpsPeriodSeconds = seconds;
_nextAcquisition = millis();
_acquiringPeriodically = false;
}
uint32_t getGpsPeriod() const override {
return _gpsPeriodSeconds;
}
uint32_t getAcquisitionAge() const override {
return (uint32_t)(millis() - _acquisitionStarted) / 1000UL;
}
bool startOnce() override {
if (_gpsOn) { // already on, acquire now
_nextAcquisition = millis();
return true;
}
setGpsOn(true);
_onceDeadline = millis() + GPS_PERIODIC_ACQUISITION_TIMEOUT_MS;
return true;
}
void syncTime() override {
nmea.clear();
LocationProvider::syncTime();
}
// Position, altitude and satellite count describe the last saved fix
// Before the first saved fix, fall back to the live parser state
// (not with GPS_GUARD: an unverified position is never reported).
#ifdef GPS_GUARD
GpsGuard* getGuard() override { return &_guard; }
bool hasValidFix() override { return _lastFix.valid; }
long getLatitude() override { return _lastFix.latitude; }
long getLongitude() override { return _lastFix.longitude; }
long getAltitude() override { return _lastFix.altitude; }
#else
long getLatitude() override {
return _lastFix.valid ? _lastFix.latitude : nmea.getLatitude();
}
long getLongitude() override {
return _lastFix.valid ? _lastFix.longitude : nmea.getLongitude();
}
long getAltitude() override {
if (_lastFix.valid) return _lastFix.altitude;
long alt = 0;
nmea.getAltitude(alt);
return alt;
}
long satellitesCount() override { return nmea.getNumSatellites(); }
bool isValid() override { return nmea.isValid(); }
#endif
long getTimestamp() override {
DateTime dt(nmea.getYear(), nmea.getMonth(),nmea.getDay(),nmea.getHour(),nmea.getMinute(),nmea.getSecond());
return dt.unixtime();
}
void drain() { while (_gps_serial->available()) _gps_serial->read(); }
const char* getSentence() const { return nmea.getSentence(); }
void sendSentence(const char *sentence) override {
nmea.sendSentence(*_gps_serial, sentence);
// GPS time minus clock time, from a current fix with a settled time
bool getClockOffset(long& offset) override {
if (_clock == nullptr || !isValid() || time_valid < 3) return false;
offset = (long)getTimestamp() - (long)_clock->getCurrentTime();
return true;
}
bool waitFor(const char* prefix, uint32_t timeout_ms) {
size_t plen = strlen(prefix);
uint32_t timeout = millis() + timeout_ms;
while ((int32_t)(millis() - timeout) < 0) {
if (_gps_serial->available()) {
char c = _gps_serial->read();
#ifdef GPS_NMEA_DEBUG
// write the current GPS time to the clock now (caller has done its own checks)
bool applyTimeNow() override {
if (_clock == nullptr || !isValid() || time_valid < 3) return false;
_clock->setCurrentTime(getTimestamp());
_time_sync_needed = false;
_last_time_sync = millis();
return true;
}
long satellitesCount() override {
return _lastFix.valid ? _lastFix.satellites : nmea.getNumSatellites();
}
bool isValid() override { return nmea.isValid(); }
long getTimestamp() override {
if (!nmea.isValid()) return _lastFix.timestamp;
DateTime dt(nmea.getYear(), nmea.getMonth(), nmea.getDay(),
nmea.getHour(), nmea.getMinute(), nmea.getSecond());
return dt.unixtime();
}
void drain() override { _driver->drain(); }
const char* getSentence() const { return nmea.getSentence(); }
void sendSentence(const char* sentence) override {
_driver->sendNmeaSentence(sentence);
}
bool waitFor(const char* prefix, uint32_t timeout_ms) override {
const size_t prefixLength = strlen(prefix);
const uint32_t deadline = millis() + timeout_ms;
while ((int32_t)(millis() - deadline) < 0) {
if (_driver->available() > 0) {
const char c = (char)_driver->read();
#ifdef GPS_NMEA_DEBUG
Serial.print(c);
#endif
if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, plen) == 0) return true;
#endif
if (nmea.process(c) && strncmp(nmea.getSentence(), prefix, prefixLength) == 0) {
return true;
}
} else {
yield();
}
@@ -199,34 +291,66 @@ public :
}
void loop() override {
if (_driver->pollGpsSwitch()) _gpsOn = true;
while (_gps_serial->available()) {
char c = _gps_serial->read();
if (_onceDeadline != 0) {
if (_firstFixInWindow != 0 && (long)(_onceDeadline - (millis() + GPS_FIX_SETTLE_MS)) > 0) {
_onceDeadline = millis() + GPS_FIX_SETTLE_MS;
}
if ((long)(millis() - _onceDeadline) >= 0) {
if (_driver->isActive()) {
setGpsOn(false);
} else { // do not stop twice
_gpsOn = false;
_onceDeadline = 0;
_acquiringPeriodically = false;
}
}
}
if (_gpsOn && _gpsPeriodSeconds > 0 && !_acquiringPeriodically &&
(long)(millis() - _nextAcquisition) >= 0) {
startPeriodicAcquisition();
}
while (_driver->available() > 0) {
const char c = (char)_driver->read();
_uart_bytes++;
_last_uart_ms = millis();
_uart_seen = true;
#ifdef GPS_NMEA_DEBUG
#ifdef GPS_NMEA_DEBUG
Serial.print(c);
#endif
bool parsed = nmea.process(c);
#endif
const bool parsed = nmea.process(c);
// MicroNMEA leaves the completed sentence in its buffer after the
// first line terminator. CRLF therefore counts once: CR observes the
// sentence, then LF clears the now-empty buffer.
if ((c == '\0' || c == '\r' || c == '\n') && nmea.getSentence()[0] != '\0') {
if (MicroNMEA::testChecksum(nmea.getSentence())) {
_nmea_checksum_ok++;
_last_nmea_ms = millis();
_nmea_seen = true;
// Refresh fix age only when a newly parsed GGA/RMC sentence
// carries a valid fix. Other valid NMEA sentences must not
// make an old position look fresh.
const char* message_id = nmea.getMessageID();
if (parsed && isValid() &&
(strcmp(message_id, "GGA") == 0 || strcmp(message_id, "RMC") == 0)) {
_last_fix_ms = millis();
_fix_seen = true;
const char* messageId = nmea.getMessageID();
#ifdef GPS_GUARD
if (parsed && !nmea.isValid() &&
(strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) {
_guard.noFix(nmea.getNumSatellites());
}
#endif
if (parsed && nmea.isValid() &&
(strcmp(messageId, "GGA") == 0 || strcmp(messageId, "RMC") == 0)) {
if (!saveFix()) continue; // incoherent snapshot
if (_firstFixInWindow == 0) {
_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) {
finishPeriodicAcquisition();
}
}
}
} else {
_nmea_checksum_bad++;
@@ -234,25 +358,13 @@ public :
}
}
if (!isValid()) time_valid = 0;
if ((long)(millis() - next_check) > 0) {
next_check = millis() + 1000;
// Re-enable time sync periodically when GPS has valid fix
if (!_time_sync_needed && _clock != NULL && (millis() - _last_time_sync) > TIME_SYNC_INTERVAL) {
_time_sync_needed = true;
}
if (_time_sync_needed && time_valid > 2) {
if (_clock != NULL) {
_clock->setCurrentTime(getTimestamp());
_time_sync_needed = false;
_last_time_sync = millis();
}
}
if (isValid()) {
time_valid ++;
}
// 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();
}
updateTime();
}
void formatDiagnostics(char* out, size_t out_size) override {
@@ -263,13 +375,11 @@ public :
char fix_age[11];
formatAge(uart_age, sizeof(uart_age), _uart_seen, _last_uart_ms);
formatAge(nmea_age, sizeof(nmea_age), _nmea_seen, _last_nmea_ms);
formatAge(fix_age, sizeof(fix_age), _fix_seen, _last_fix_ms);
formatAge(fix_age, sizeof(fix_age), _lastFix.valid, _lastFix.acquiredAt);
// Compact enough for CommonCLI's 160-byte reply buffer, including the
// "req:" prefix added by CommonCLI.
snprintf(out, out_size,
"en:%u ub:%lu ua:%s ok:%lu bad:%lu na:%s sat:%ld fix:%u fa:%s bc:%lu sc:%lu",
isEnabled() ? 1U : 0U,
isActive() ? 1U : 0U,
(unsigned long)_uart_bytes,
uart_age,
(unsigned long)_nmea_checksum_ok,
+350
View File
@@ -0,0 +1,350 @@
#pragma once
#include "GpsDriver.h"
#include <Arduino.h>
#include <helpers/RefCountedDigitalPin.h>
#include <MeshCore.h>
#include <stdlib.h>
#include <string.h>
#ifndef UART_TYPE
#ifdef NRF52_PLATFORM
#define UART_TYPE Uart
#else
#define UART_TYPE HardwareSerial
#endif
#endif
#ifndef PIN_GPS_TX
#define PIN_GPS_TX (-1)
#endif
#ifndef PIN_GPS_RX
#define PIN_GPS_RX (-1)
#endif
#ifndef GPS_EN
#ifdef PIN_GPS_EN
#define GPS_EN PIN_GPS_EN
#else
#define GPS_EN (-1)
#endif
#endif
#ifndef GPS_EN_ACTIVE
#ifdef PIN_GPS_EN_ACTIVE
#define GPS_EN_ACTIVE PIN_GPS_EN_ACTIVE
#else
#define GPS_EN_ACTIVE HIGH
#endif
#endif
#ifndef GPS_RESET
#ifdef PIN_GPS_RESET
#define GPS_RESET PIN_GPS_RESET
#else
#define GPS_RESET (-1)
#endif
#endif
#ifndef GPS_RESET_ACTIVE
#ifdef PIN_GPS_RESET_ACTIVE
#define GPS_RESET_ACTIVE PIN_GPS_RESET_ACTIVE
#else
#define GPS_RESET_ACTIVE LOW
#endif
#endif
#ifndef GPS_BAUD_RATE
#ifdef GPS_BAUDRATE
#define GPS_BAUD_RATE GPS_BAUDRATE
#else
#define GPS_BAUD_RATE 9600
#endif
#endif
// Optional rates detect() tries after GPS_BAUD_RATE, for GPS modules whose baud rate is
// not known in advance (e.g. -D GPS_BAUD_PROBE_LIST=9600,115200,38400). Used by every
// NmeaGpsDriver that does not pass its own list.
#ifdef GPS_BAUD_PROBE_LIST
static const uint32_t NMEA_GPS_PROBE_BAUDS[] = { GPS_BAUD_PROBE_LIST };
#define GPS_PROBE_BAUDS NMEA_GPS_PROBE_BAUDS
#define GPS_PROBE_COUNT ((uint8_t)(sizeof(NMEA_GPS_PROBE_BAUDS) / sizeof(NMEA_GPS_PROBE_BAUDS[0])))
#else
#define GPS_PROBE_BAUDS nullptr
#define GPS_PROBE_COUNT 0
#endif
#ifndef PIN_GPS_SWITCH
#define PIN_GPS_SWITCH (-1)
#endif
#ifndef GPS_SWITCH_ACTIVE
#define GPS_SWITCH_ACTIVE HIGH
#endif
#ifndef GPS_SWITCH_IS_HARDWARE
#define GPS_SWITCH_IS_HARDWARE 1
#endif
#ifndef GPS_SWITCH_TURNS_GPS_ON
#define GPS_SWITCH_TURNS_GPS_ON 0
#endif
class NmeaGpsDriver : public GpsDriver {
UART_TYPE* _hardwareSerial = nullptr;
RefCountedDigitalPin* _peripheralPower = nullptr;
int _txPin = -1;
int _rxPin = -1;
int _resetPin = -1;
int _enablePin = -1;
int _enableActive = HIGH;
int _resetActive = LOW;
uint32_t _baudRate = 9600;
const uint32_t* _probeBauds = nullptr; // optional rates to try in detect(), set by the board
uint8_t _probeCount = 0;
int _hardwareEnablePin = -1;
int _hardwareEnableActive = HIGH;
bool _started = false;
#if !GPS_SWITCH_IS_HARDWARE
bool _requestedOn = false;
bool _switchStateKnown = false;
bool _lastSwitchEnabled = false;
unsigned long _nextSwitchPoll = 0;
#endif
void startHardware() {
if (_hardwareSerial == nullptr || _started) return;
if (_hardwareSerial != nullptr) {
if (_txPin != -1 && _rxPin != -1) {
_hardwareSerial->setPins(_txPin, _rxPin);
}
_hardwareSerial->begin(_baudRate);
}
if (_peripheralPower != nullptr) _peripheralPower->claim();
if (_enablePin != -1) digitalWrite(_enablePin, _enableActive);
if (_resetPin != -1) digitalWrite(_resetPin, !_resetActive);
_started = true;
}
void reopenSerial(uint32_t baud) {
_hardwareSerial->end();
if (_txPin != -1 && _rxPin != -1) {
_hardwareSerial->setPins(_txPin, _rxPin);
}
_hardwareSerial->begin(baud);
drain();
}
// True if a complete NMEA sentence with a valid checksum arrives within timeout_ms.
bool seesValidNmea(uint32_t timeout_ms) {
char line[100];
int len = -1; // -1 = waiting for '$'
const uint32_t start = millis();
while ((uint32_t)(millis() - start) < timeout_ms) {
if (available() <= 0) { delay(2); continue; }
const char c = (char)read();
if (c == '$') { len = 0; continue; }
if (len < 0) continue;
if (c == '\r' || c == '\n') {
line[len] = '\0';
const char* star = strchr(line, '*');
if (star != nullptr && strlen(star) >= 3) {
uint8_t sum = 0;
for (const char* p = line; p < star; p++) sum ^= (uint8_t)*p;
if (sum == (uint8_t)strtoul(star + 1, nullptr, 16)) return true;
}
len = -1;
} else if (len < (int)sizeof(line) - 1) {
line[len++] = c;
} else {
len = -1; // longer than any NMEA sentence: wrong baud rate
}
}
return false;
}
// Bytes arriving does not mean the baud rate is right: at the wrong rate the
// parser only sees garbage and never gets a fix. Try the configured rate, then the
// board's list, and keep the first that yields valid NMEA. The rate is kept in
// _baudRate, so later power cycles reopen the UART with it.
bool tryBaudRate(uint32_t baud) {
reopenSerial(baud);
if (!seesValidNmea(2000)) return false;
_baudRate = baud;
MESH_DEBUG_PRINTLN("GPS baud rate: %lu", (unsigned long)_baudRate);
return true;
}
void detectBaudRate() {
const uint32_t configured = _baudRate;
if (tryBaudRate(configured)) return;
for (uint8_t i = 0; i < _probeCount; i++) {
if (_probeBauds[i] != configured && tryBaudRate(_probeBauds[i])) return;
}
reopenSerial(configured);
MESH_DEBUG_PRINTLN("GPS baud rate not detected, using %lu", (unsigned long)configured);
}
void stopHardware() {
if (!_started) return;
if (_enablePin != -1) digitalWrite(_enablePin, !_enableActive);
if (_resetPin != -1) digitalWrite(_resetPin, _resetActive);
if (_peripheralPower != nullptr) _peripheralPower->release();
_started = false;
}
public:
NmeaGpsDriver() = default;
NmeaGpsDriver(UART_TYPE& serial, int txPin = PIN_GPS_TX, int rxPin = PIN_GPS_RX,
int resetPin = GPS_RESET, int enablePin = GPS_EN,
RefCountedDigitalPin* peripheralPower = nullptr,
int enableActive = GPS_EN_ACTIVE, int resetActive = GPS_RESET_ACTIVE,
uint32_t baudRate = GPS_BAUD_RATE,
int hardwareEnablePin = PIN_GPS_SWITCH,
int hardwareEnableActive = GPS_SWITCH_ACTIVE,
const uint32_t* probeBauds = GPS_PROBE_BAUDS, uint8_t probeCount = GPS_PROBE_COUNT)
: _hardwareSerial(&serial), _peripheralPower(peripheralPower), _txPin(txPin), _rxPin(rxPin),
_resetPin(resetPin), _enablePin(enablePin), _enableActive(enableActive),
_resetActive(resetActive), _baudRate(baudRate),
_probeBauds(probeBauds), _probeCount(probeBauds != nullptr ? probeCount : 0),
_hardwareEnablePin(hardwareEnablePin), _hardwareEnableActive(hardwareEnableActive) {
if (_resetPin != -1) {
pinMode(_resetPin, OUTPUT);
digitalWrite(_resetPin, _resetActive);
}
if (_enablePin != -1) {
pinMode(_enablePin, OUTPUT);
digitalWrite(_enablePin, !_enableActive);
}
if (_hardwareEnablePin != -1) {
pinMode(_hardwareEnablePin, INPUT);
}
}
// Board with a GPS whose baud rate is not known in advance: detect() also tries the
// rates in probeBauds (after the configured one). The array must stay valid (static).
NmeaGpsDriver(UART_TYPE& serial, const uint32_t* probeBauds, uint8_t probeCount)
: NmeaGpsDriver(serial, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, nullptr,
GPS_EN_ACTIVE, GPS_RESET_ACTIVE, GPS_BAUD_RATE, PIN_GPS_SWITCH,
GPS_SWITCH_ACTIVE, probeBauds, probeCount) {}
void begin() override {
#if !GPS_SWITCH_IS_HARDWARE
_requestedOn = true;
if (!isHardwareEnabled()) return;
#endif
startHardware();
}
void reset() override {
if (!_started) return;
if (_resetPin != -1) {
digitalWrite(_resetPin, _resetActive);
delay(10);
digitalWrite(_resetPin, !_resetActive);
}
#ifdef GPS_L76K
delay(250);
sendNmeaSentence("$PCAS04,7");
delay(250);
#endif
}
void stop() override {
#if !GPS_SWITCH_IS_HARDWARE
_requestedOn = false;
#endif
stopHardware();
}
bool isActive() const override {
return _started && isHardwareEnabled();
}
bool hasHardwareEnableState() const override {
return _hardwareEnablePin != -1;
}
bool isHardwareEnabled() const override {
return _hardwareEnablePin == -1 ||
digitalRead(_hardwareEnablePin) == _hardwareEnableActive;
}
bool pollGpsSwitch() override {
#if !GPS_SWITCH_IS_HARDWARE
if (_hardwareEnablePin == -1 ||
(long)(millis() - _nextSwitchPoll) < 0) return false;
_nextSwitchPoll = millis() + 1000;
const bool switchEnabled = isHardwareEnabled();
const bool enablesGps = GPS_SWITCH_TURNS_GPS_ON && _switchStateKnown &&
!_lastSwitchEnabled && switchEnabled;
_switchStateKnown = true;
_lastSwitchEnabled = switchEnabled;
if (enablesGps) _requestedOn = true;
if (_requestedOn && switchEnabled) {
startHardware();
} else {
stopHardware();
}
return enablesGps;
#else
return false;
#endif
}
bool detect(uint32_t timeout_ms) override {
bool found = available() > 0;
const uint32_t deadline = millis() + timeout_ms;
while (!found && (int32_t)(millis() - deadline) < 0) {
found = available() > 0;
if (!found) delay(10);
}
// only on a real detection (timeout > 0), not on the quick "still active?" polls
if (found && timeout_ms > 0 && _probeCount > 0 && _started && _hardwareSerial != nullptr) {
detectBaudRate();
}
return found;
}
int available() {
return _hardwareSerial == nullptr ? 0 : _hardwareSerial->available();
}
int read() {
return _hardwareSerial == nullptr ? -1 : _hardwareSerial->read();
}
void drain() {
while (available() > 0) read();
}
void sendNmeaSentence(const char* sentence) {
if (_hardwareSerial == nullptr || sentence == nullptr || sentence[0] != '$') return;
uint8_t checksum = 0;
const char* p = sentence + 1;
while (*p != '\0' && *p != '*') checksum ^= (uint8_t)*p++;
_hardwareSerial->print(sentence);
if (*p == '\0') {
char checksumSuffix[6];
snprintf(checksumSuffix, sizeof(checksumSuffix), "*%02X\r\n", checksum);
_hardwareSerial->print(checksumSuffix);
} else {
_hardwareSerial->print("\r\n");
}
}
};
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include "GpsDriver.h"
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
// Driver for the RAK12500 (u-blox, I2C). Serial NMEA modules are handled by NmeaGpsDriver.
class RakI2cGpsDriver : public GpsDriver {
TwoWire& _wire;
SFE_UBLOX_GNSS _gnss;
uint8_t _powerPin = 0;
bool _detected = false;
bool _started = false;
bool probeRak12500(uint8_t powerPin) {
#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD)
if (powerPin == WB_IO2) return false;
#endif
#ifndef RAK_3401
pinMode(powerPin, OUTPUT);
digitalWrite(powerPin, LOW);
delay(500);
digitalWrite(powerPin, HIGH);
#endif
delay(500);
if (_gnss.begin(_wire)) {
_gnss.setI2COutput(COM_TYPE_UBX);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GALILEO);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_GLONASS);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_SBAS);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_BEIDOU);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_IMES);
_gnss.enableGNSS(true, SFE_UBLOX_GNSS_ID_QZSS);
_gnss.setMeasurementRate(1000);
_gnss.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT);
_powerPin = powerPin;
return true;
}
#ifndef RAK_3401
pinMode(powerPin, INPUT);
#endif
return false;
}
public:
RakI2cGpsDriver(TwoWire& wire = Wire) : _wire(wire) {}
void begin() override {
if (!_detected) return;
#ifndef RAK_3401
pinMode(_powerPin, OUTPUT);
digitalWrite(_powerPin, HIGH);
#endif
_started = true;
}
void reset() override {}
void stop() override {
if (_detected) {
#ifndef RAK_3401
pinMode(_powerPin, OUTPUT);
digitalWrite(_powerPin, LOW);
#endif
}
_started = false;
}
bool isActive() const override {
return _started;
}
// Probes the I2C module on the possible power pins; the module is left powered.
bool detect(uint32_t) override {
if (_detected) return true;
if (probeRak12500(WB_IO2) || probeRak12500(WB_IO4) || probeRak12500(WB_IO5)) {
_detected = true;
_started = true;
}
return _detected;
}
bool isDetected() const { return _detected; }
bool hasFix() { return _started && _gnss.getGnssFixOk(8); }
long getLatitude() { return _gnss.getLatitude(2) / 10; }
long getLongitude() { return _gnss.getLongitude(2) / 10; }
long getAltitude() { return _gnss.getAltitude(2); }
long getSatellites() { return _gnss.getSIV(2); }
long getTimestamp() { return _gnss.getUnixEpoch(2); }
};
+230
View File
@@ -0,0 +1,230 @@
#pragma once
#include "MicroNMEALocationProvider.h"
#include "NmeaGpsDriver.h"
#include "RakI2cGpsDriver.h"
class RakLocationProvider : public LocationProvider {
RakI2cGpsDriver& _driver; // RAK12500 (I2C)
NmeaGpsDriver _nmeaDriver; // serial NMEA module
MicroNMEALocationProvider _nmea;
bool _detected = false;
bool _useI2c = false;
uint32_t _gpsPeriodSeconds = 0;
unsigned long _nextAcquisition = 0;
unsigned long _acquisitionStarted = 0;
bool _acquiringPeriodically = false;
void saveRak12500Fix() {
LastFix fix;
fix.latitude = _driver.getLatitude();
fix.longitude = _driver.getLongitude();
fix.altitude = _driver.getAltitude();
fix.satellites = _driver.getSatellites();
fix.timestamp = _driver.getTimestamp();
fix.acquiredAt = millis();
fix.valid = true;
_lastFix = fix;
}
public:
// serialPower, if given, switches the serial module's supply (WB_IO2 on WisBlock bases).
RakLocationProvider(RakI2cGpsDriver& driver, mesh::RTCClock* clock = nullptr,
UART_TYPE& serial = Serial1, RefCountedDigitalPin* serialPower = nullptr)
: _driver(driver), _nmeaDriver(serial, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN, serialPower),
_nmea(_nmeaDriver, clock) {}
void syncTime() override {
LocationProvider::syncTime();
if (!_useI2c) _nmea.syncTime();
}
long getLatitude() override {
return _useI2c ? _lastFix.latitude : _nmea.getLatitude();
}
long getLongitude() override {
return _useI2c ? _lastFix.longitude : _nmea.getLongitude();
}
long getAltitude() override {
return _useI2c ? _lastFix.altitude : _nmea.getAltitude();
}
long satellitesCount() override {
return _useI2c ? _lastFix.satellites : _nmea.satellitesCount();
}
bool isValid() override {
return _useI2c ? _driver.hasFix() : _nmea.isValid();
}
FixStats getFixStats() const override {
return _useI2c ? _fixStats : _nmea.getFixStats();
}
LastFix getLastFix() const override {
return _useI2c ? _lastFix : _nmea.getLastFix();
}
long getTimestamp() override {
return _useI2c ? _lastFix.timestamp : _nmea.getTimestamp();
}
// the anti-spoofing guard (GPS_GUARD) only covers the serial NMEA path
GpsGuard* getGuard() override {
return _useI2c ? nullptr : _nmea.getGuard();
}
bool hasValidFix() override {
return _useI2c ? LocationProvider::hasValidFix() : _nmea.hasValidFix();
}
bool getClockOffset(long& offset) override {
return _useI2c ? false : _nmea.getClockOffset(offset);
}
bool applyTimeNow() override {
return _useI2c ? false : _nmea.applyTimeNow();
}
void sendSentence(const char* sentence) override {
if (!_useI2c) _nmea.sendSentence(sentence);
}
bool waitFor(const char* prefix, uint32_t timeout_ms) override {
return _useI2c ? false : _nmea.waitFor(prefix, timeout_ms);
}
void drain() override {
if (!_useI2c) _nmea.drain();
}
void reset() override {
if (!_useI2c) _nmea.reset();
}
void begin() override {
if (_detected && _useI2c) {
_driver.begin();
_acquiringPeriodically = _gpsPeriodSeconds > 0;
_acquisitionStarted = millis();
} else if (_detected) {
_nmea.begin();
} else {
_nmeaDriver.begin();
}
}
void stop() override {
_acquiringPeriodically = false;
if (_useI2c) {
_driver.stop();
} else {
_nmea.stop();
}
}
bool detect(uint32_t timeout_ms) override {
if (_detected) return true;
// the serial module is started first, then the I2C module is probed
_nmeaDriver.begin();
if (_driver.detect(timeout_ms)) {
// The serial driver keeps its claim on serialPower, so the rail stays as it is without one.
// The RAK12500 driver switches its own power pin, and serialPower is only used on the serial path.
_useI2c = true;
} else if (!_nmeaDriver.detect(0)) {
_nmeaDriver.stop();
return false;
}
_detected = true;
if (_useI2c) {
_acquiringPeriodically = _gpsPeriodSeconds > 0;
_acquisitionStarted = millis();
} else {
_nmea.setGpsPeriod(_gpsPeriodSeconds);
_nmea.begin();
}
return true;
}
bool keepEnabledAfterDetection() const override {
#ifdef FORCE_GPS_ALIVE
return true;
#else
return false;
#endif
}
void loop() override {
if (_useI2c) {
if (_gpsOn) {
if (_gpsPeriodSeconds > 0) {
if (!_acquiringPeriodically &&
(long)(millis() - _nextAcquisition) >= 0) {
_driver.begin();
_acquiringPeriodically = true;
_acquisitionStarted = millis();
}
}
const bool hasCurrentFix = _driver.hasFix();
if (hasCurrentFix) {
// first fix since the start
if (!_lastFix.valid || (long)(_lastFix.acquiredAt - _acquisitionStarted) < 0) {
fixStatsFix((uint32_t)(millis() - _acquisitionStarted));
}
saveRak12500Fix();
}
if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && hasCurrentFix) {
_driver.stop();
_acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
} else if (_gpsPeriodSeconds > 0 && _acquiringPeriodically && _lastFix.valid &&
(uint32_t)(millis() - _acquisitionStarted) >=
GPS_PERIODIC_ACQUISITION_TIMEOUT_MS) {
fixStatsMiss();
_driver.stop();
_acquiringPeriodically = false;
_nextAcquisition = millis() + _gpsPeriodSeconds * 1000UL;
}
}
} else {
_nmea.loop();
}
}
bool isActive() override {
return _useI2c ? _driver.isActive() : _nmea.isActive();
}
void setGpsPeriod(uint32_t seconds) override {
_gpsPeriodSeconds = seconds;
_nextAcquisition = millis();
if (!_useI2c) _nmea.setGpsPeriod(seconds);
}
uint32_t getGpsPeriod() const override {
return _gpsPeriodSeconds;
}
bool isGpsOn() const override {
return _useI2c ? _gpsOn : _nmea.isGpsOn();
}
uint32_t getAcquisitionAge() const override {
return _useI2c ? (uint32_t)(millis() - _acquisitionStarted) / 1000UL : _nmea.getAcquisitionAge();
}
bool startOnce() override {
return _useI2c ? false : _nmea.startOnce(); // not supported on the RAK12500
}
void setGpsOn(bool on) override {
if (_useI2c) LocationProvider::setGpsOn(on);
else { _gpsOn = on; _nmea.setGpsOn(on); }
}
};
+1
View File
@@ -28,6 +28,7 @@ public:
virtual bool isOn() = 0;
virtual bool isEink() { return false; } // default to non-eink, override in eink drivers
virtual void forceFullRefresh() {} // next refresh will be full for eink
virtual void setBusyHook(void (*hook)()) {} // eink: hook is called repeatedly while waiting for panel refresh
virtual void turnOn() = 0;
virtual void turnOn(int max_partial) { turnOn(); }
virtual void turnOff() = 0;
+10 -2
View File
@@ -88,7 +88,9 @@ void GxEPDDisplay::drawSleepIcon() {
display.fillRect((x - 5) * scale_x - 1, y * scale_y, (W+5) * scale_x + 2, (H-2) * scale_y + 1, GxEPD_WHITE);
_curr_color = GxEPD_BLACK;
drawXbm(x, y, sleep_icon_24x24, W, H);
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.display(true);
display.epd2.setBusyCallback(NULL);
}
void GxEPDDisplay::turnOff(bool blank) {
@@ -99,17 +101,18 @@ void GxEPDDisplay::turnOff(bool blank) {
}
_isOn = false;
last_display_crc_value=0;
display.hibernate();
}
void GxEPDDisplay::blankScreen() {
// do full refresh before powering off to clear screen
// no full refresh needed at wakeup
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.clearScreen(0xFF); // Clears microcontroller side RAM
display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers
display.epd2.setBusyCallback(NULL);
_partial_refresh_count = 0;
last_display_crc_value = 0;
// we can hibernate as screen has been cleaned
display.hibernate();
}
void GxEPDDisplay::clear() {
@@ -126,8 +129,10 @@ void GxEPDDisplay::startFrame(ColorVal bkg) {
|| (_max_partial_refresh > 0
&& _partial_refresh_count >= _max_partial_refresh)) {
// forces a full wipe of the screen ...
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.clearScreen(0xFF); // Clears microcontroller side RAM
display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers
display.epd2.setBusyCallback(NULL);
// we'll need a partial refresh after that (whatever crc value is)
last_display_crc_value = 0;
_partial_refresh_count = 0;
@@ -239,7 +244,10 @@ void GxEPDDisplay::endFrame() {
if (_isOn == false) return;
uint32_t crc = display_crc.finalize();
if (crc != last_display_crc_value) {
// keep the rest of the firmware running while the panel refreshes (~0.5s partial)
if (_busy_hook) display.epd2.setBusyCallback(busyCallback, this);
display.display(true);
display.epd2.setBusyCallback(NULL);
_partial_refresh_count++;
}
last_display_crc_value = crc;
+7
View File
@@ -39,6 +39,12 @@ class GxEPDDisplay : public DisplayDriver {
bool _force_full_refresh = false;
int _partial_refresh_count = 0;
int _max_partial_refresh = 0;
void (*_busy_hook)() = NULL;
static void busyCallback(const void* self) {
((const GxEPDDisplay*)self)->_busy_hook();
delay(1); // same as GxEPD2 does without a callback
}
public:
#if defined(EINK_DISPLAY_MODEL)
@@ -53,6 +59,7 @@ public:
bool isEink() override { return true; }
void forceFullRefresh() override { _force_full_refresh = true; }
void turnOn(int max_partial) override;
void setBusyHook(void (*hook)()) override { _busy_hook = hook; }
void turnOn() override;
void turnOff(bool blank) override;
void turnOff() override { turnOff(false); }
+6 -1
View File
@@ -25,7 +25,12 @@ bool SSD1306Display::begin() {
#ifdef DISPLAY_ROTATION
display.setRotation(DISPLAY_ROTATION);
#endif
return display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS, true, false) && i2c_probe(Wire, DISPLAY_ADDRESS);
bool success = display.begin(SSD1306_SWITCHCAPVCC, DISPLAY_ADDRESS, true, false);
#if defined(PIN_OLED_CS) && defined(PIN_OLED_DC)
return success;
#else
return success && i2c_probe(Wire, DISPLAY_ADDRESS);
#endif
}
void SSD1306Display::turnOn() {
+8
View File
@@ -15,6 +15,10 @@
#define DISPLAY_ADDRESS 0x3C
#endif
#if defined(PIN_OLED_CS) != defined(PIN_OLED_DC)
#error "SPI OLED requires both PIN_OLED_CS and PIN_OLED_DC"
#endif
class SSD1306Display : public DisplayDriver {
Adafruit_SSD1306 display;
bool _isOn;
@@ -24,7 +28,11 @@ class SSD1306Display : public DisplayDriver {
bool i2c_probe(TwoWire& wire, uint8_t addr);
public:
SSD1306Display(RefCountedDigitalPin* peripher_power=NULL) : DisplayDriver(128, 64),
#if defined(PIN_OLED_CS) && defined(PIN_OLED_DC)
display(128, 64, &SPI, PIN_OLED_DC, PIN_OLED_RESET, PIN_OLED_CS),
#else
display(128, 64, &Wire, PIN_OLED_RESET),
#endif
_peripher_power(peripher_power)
{
_isOn = false;
+3 -2
View File
@@ -102,7 +102,8 @@
static TFT_eSPI lcd = TFT_eSPI(160, 80);
static uint32_t curr_color;
#if defined(HELTEC_LORA_V3) || defined(HELTEC_TRACKER_V2)
#if defined(HELTEC_LORA_V3) || defined(HELTEC_TRACKER_V2) || defined(DFROBOT_LORAWAN_ESP32S3)
// ESP32-S3: HSPI is SPI3. The SX1262 uses FSPI (SPI2) so the two buses do not share a controller.
static SPIClass tft_spi(HSPI);
#define _spi (&tft_spi)
#else
@@ -490,7 +491,7 @@ void ST7735Display::_resetAndInit() {
// run init commands
displayInit(Rcmd1);
#if defined(HELTEC_TRACKER_V2) || defined(HELTEC_T096)
#if defined(HELTEC_TRACKER_V2) || defined(HELTEC_T096) || defined(DFROBOT_LORAWAN_ESP32S3)
displayInit(Rcmd2green160x80);
//uint8_t madctl = ST77XX_MADCTL_MY | ST77XX_MADCTL_MV |ST7735_MADCTL_BGR;//Adjust color to BGR
//display.sendCommand(ST77XX_MADCTL, &madctl, 1);
@@ -0,0 +1,18 @@
#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);
@@ -0,0 +1,6 @@
#pragma once
struct StartupWire {
void begin() {}
};
inline StartupWire Wire;
@@ -0,0 +1,44 @@
#pragma once
#include <Arduino.h>
#include <string>
#include <vector>
#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<std::string> 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() {}
};
@@ -0,0 +1,70 @@
#include <gtest/gtest.h>
#include <array>
// Exercise the real startup code with a power-management stub that stops at SYSTEMOFF.
#include "../../variants/rak3401/RAK3401Board.cpp"
namespace startup_test {
std::vector<std::string> events;
bool permitBoot;
std::array<uint32_t, 48> 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<std::string>{"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<std::string>{"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<std::string>{"onboard", "voltage", "off"}));
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,66 @@
#include <gtest/gtest.h>
#include <array>
#include <string>
#include "../../variants/rak3401/OnboardRadioSleep.h"
namespace {
struct FakeRadioIO {
std::string version = "SX1261";
std::array<bool, 3> 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();
}
+138
View File
@@ -0,0 +1,138 @@
#include <Arduino.h>
#include <MeshCore.h>
#include <cmath>
#include <gtest/gtest.h>
#include <helpers/TimeSeriesData.h>
#include <utility>
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<uint32_t, uint32_t>(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();
}
@@ -0,0 +1,20 @@
#include "DFRobotLoRaBoard.h"
void DFRobotLoRaBoard::begin() {
// SX1262 module power. Held high for the whole boot; Companion does not
// drop into deep sleep, so the pin does not need an RTC hold.
pinMode(LORA_POWER_EN, OUTPUT);
digitalWrite(LORA_POWER_EN, HIGH);
delay(10);
periph_power.begin();
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, HIGH);
ESP32Board::begin();
}
const char* DFRobotLoRaBoard::getManufacturerName() const {
return "DFRobot LoRaWAN ESP32-S3";
}
@@ -0,0 +1,15 @@
#pragma once
#include <Arduino.h>
#include <helpers/RefCountedDigitalPin.h>
#include <helpers/ESP32Board.h>
class DFRobotLoRaBoard : public ESP32Board {
public:
RefCountedDigitalPin periph_power;
DFRobotLoRaBoard() : periph_power(PIN_VEXT_EN, PIN_VEXT_EN_ACTIVE) { }
void begin();
const char* getManufacturerName() const override;
};
@@ -0,0 +1,73 @@
; DFRobot LoRaWAN ESP32-S3 (DFR1195)
; ESP32-S3-WROOM-1-N4 (4 MB flash, no PSRAM), SX1262, SPI ST7735S 80x160.
; Pin map follows variants/esp32s3/DFRobot_LoRaWAN_ESP32-S3 in the Meshtastic tree.
; LoRa is on FSPI. The display is on HSPI (SPI3), matching ST7735_SPI_HOST.
[DFRobot_LoRaWAN_ESP32S3]
extends = esp32_base
board = dfrobot_lorawan_esp32s3
; 4 MB module: app slots are 1.9 MB. The default 4 MB table only leaves 1.25 MB.
board_build.partitions = min_spiffs.csv
build_flags =
${esp32_base.build_flags}
-I variants/dfrobot_lorawan_esp32s3
-D DFROBOT_LORAWAN_ESP32S3
-D ESP32_CPU_FREQ=80
-D RADIO_CLASS=CustomSX1262
-D WRAPPER_CLASS=CustomSX1262Wrapper
-D LORA_TX_POWER=22
-D P_LORA_NSS=10
-D P_LORA_DIO_1=4
-D P_LORA_RESET=41
-D P_LORA_BUSY=40
-D P_LORA_SCLK=7
-D P_LORA_MISO=5
-D P_LORA_MOSI=6
-D LORA_POWER_EN=42
-D SX126X_DIO2_AS_RF_SWITCH=true
-D SX126X_DIO3_TCXO_VOLTAGE=3.3
-D SX126X_CURRENT_LIMIT=140
-D SX126X_RX_BOOSTED_GAIN=1
-D PIN_USER_BTN=18
-D PIN_LED=21
-D PIN_VEXT_EN=48
-D PIN_VEXT_EN_ACTIVE=LOW
-D PIN_BOARD_SDA=8
-D PIN_BOARD_SCL=9
-D PIN_TFT_CS=17
-D PIN_TFT_DC=14
-D PIN_TFT_RST=15
-D PIN_TFT_SDA=11
-D PIN_TFT_SCL=12
-D PIN_TFT_LEDA_CTL=16
-D PIN_TFT_LEDA_CTL_ACTIVE=HIGH
build_src_filter = ${esp32_base.build_src_filter}
+<../variants/dfrobot_lorawan_esp32s3>
lib_deps =
${esp32_base.lib_deps}
bodmer/TFT_eSPI @ ^2.4.31
; Landscape UI on the 80x160 panel. Use 3 if the picture is upside down.
[env:DFRobot_LoRaWAN_ESP32S3_companion_radio_ble]
extends = DFRobot_LoRaWAN_ESP32S3
build_flags =
${DFRobot_LoRaWAN_ESP32S3.build_flags}
-I src/helpers/ui
-I examples/companion_radio/ui-new
-D DISPLAY_ROTATION=3
-D DISPLAY_CLASS=ST7735Display
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D BLE_PIN_CODE=123456
-D OFFLINE_QUEUE_SIZE=256
; -D BLE_DEBUG_LOGGING=1
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
build_src_filter = ${DFRobot_LoRaWAN_ESP32S3.build_src_filter}
+<helpers/esp32/SerialBLEInterface.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<helpers/ui/ST7735Display.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
lib_deps =
${DFRobot_LoRaWAN_ESP32S3.lib_deps}
densaugeo/base64 @ ~1.4.0
@@ -0,0 +1,34 @@
#include <Arduino.h>
#include <SPI.h>
#include "target.h"
DFRobotLoRaBoard board;
// FSPI is SPI2. The ST7735 driver takes HSPI (SPI3); the default SPIClass
// constructor on ESP32-S3 is HSPI and would collide with the display.
static SPIClass spi(FSPI);
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);
ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
SensorManager sensors;
#ifdef DISPLAY_CLASS
DISPLAY_CLASS display(&board.periph_power);
// Active-low button, internal pull-up.
MomentaryButton user_btn(PIN_USER_BTN, 1000, true, true);
#endif
bool radio_init() {
fallback_clock.begin();
rtc_clock.begin(Wire);
return radio.std_init(&spi);
}
mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/radiolib/RadioLibWrappers.h>
#include <DFRobotLoRaBoard.h>
#include <helpers/radiolib/CustomSX1262Wrapper.h>
#include <helpers/AutoDiscoverRTCClock.h>
#include <helpers/SensorManager.h>
#ifdef DISPLAY_CLASS
#include <helpers/ui/ST7735Display.h>
#include <helpers/ui/MomentaryButton.h>
#endif
extern DFRobotLoRaBoard board;
extern WRAPPER_CLASS radio_driver;
extern AutoDiscoverRTCClock rtc_clock;
extern SensorManager sensors;
#ifdef DISPLAY_CLASS
extern DISPLAY_CLASS display;
extern MomentaryButton user_btn;
#endif
bool radio_init();
mesh::LocalIdentity radio_new_identity();
+4 -3
View File
@@ -26,9 +26,10 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#include <helpers/sensors/RakLocationProvider.h>
RakI2cGpsDriver gps_driver;
RakLocationProvider location(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(location);
#else
EnvironmentSensorManager sensors;
#endif
+2 -1
View File
@@ -26,7 +26,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+2 -1
View File
@@ -27,7 +27,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+6 -11
View File
@@ -11,7 +11,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
SolarSensorManager sensors = SolarSensorManager(nmea);
SolarExternalWatchdog external_watchdog;
@@ -30,17 +31,11 @@ mesh::LocalIdentity radio_new_identity() {
}
void SolarSensorManager::start_gps() {
if (!gps_active) {
gps_active = true;
_location->begin();
}
_location->setGpsOn(true);
}
void SolarSensorManager::stop_gps() {
if (gps_active) {
gps_active = false;
_location->stop();
}
_location->setGpsOn(false);
}
bool SolarSensorManager::begin() {
@@ -71,7 +66,7 @@ void SolarSensorManager::loop() {
_location->loop();
if (millis() > next_gps_update) {
if (_location->isValid()) {
if (_location->isGpsOn() && _location->hasValidFix()) {
node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.;
node_altitude = ((double)_location->getAltitude()) / 1000.0;
@@ -91,7 +86,7 @@ const char* SolarSensorManager::getSettingName(int i) const {
const char* SolarSensorManager::getSettingValue(int i) const {
if (gps_detected && i == 0) {
return gps_active ? "1" : "0";
return _location->isGpsOn() ? "1" : "0";
}
return NULL;
}
-1
View File
@@ -14,7 +14,6 @@
#endif
class SolarSensorManager : public SensorManager {
bool gps_active = false;
bool gps_detected = false;
LocationProvider* _location;
+3 -1
View File
@@ -20,7 +20,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, PIN_GPS_RESET, PIN_GPS_EN);
NmeaGpsDriver gps_driver(Serial1, PIN_GPS_TX, PIN_GPS_RX, PIN_GPS_RESET,
PIN_GPS_EN);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+3 -1
View File
@@ -22,7 +22,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
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;
+3 -1
View File
@@ -21,7 +21,9 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
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;
+2 -1
View File
@@ -22,7 +22,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
+2 -1
View File
@@ -12,7 +12,8 @@ WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
TowerV2ExternalWatchdog external_watchdog;
+2 -2
View File
@@ -31,8 +31,8 @@ build_flags =
-D USE_PIN_TFT=1
-D PIN_VEXT_EN=3 ; Vext is connected to VDD which is also connected to OLED & GPS
-D PIN_TFT_LEDA_CTL=21 ; LEDK (switches on/off via mosfet to create the ground)
-D PIN_GPS_RX=33
-D PIN_GPS_TX=34
-D PIN_GPS_TX=33 ; GPS module TX -> MCU RX (GPIO33)
-D PIN_GPS_RX=34 ; GPS module RX <- MCU TX (GPIO34)
-D PIN_GPS_EN=35 ; N-ch MOSFET Q2 drives P-ch high-side switch → active HIGH (default)
-D PIN_GPS_RESET=36
-D PIN_GPS_RESET_ACTIVE=LOW
+24 -14
View File
@@ -17,7 +17,25 @@ WRAPPER_CLASS radio_driver(radio, board);
ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
// GPS_EN (GPIO35) drives N-ch MOSFET → P-ch high-side switch; GPS_RESET (GPIO36) active LOW
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
class HeltecTrackerGpsDriver : public NmeaGpsDriver {
public:
HeltecTrackerGpsDriver()
: NmeaGpsDriver(Serial1, PIN_GPS_TX, PIN_GPS_RX, GPS_RESET, GPS_EN,
&board.periph_power) {}
void reset() override {
NmeaGpsDriver::reset();
// Send configuration after reset
if (isActive()) {
delay(250);
sendNmeaSentence("$CFGSYS,h35155*68");
// TODO: remove active wait (250ms is a lot)
}
}
};
HeltecTrackerGpsDriver gps_driver;
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
HWTSensorManager sensors = HWTSensorManager(nmea);
#ifdef DISPLAY_CLASS
@@ -43,23 +61,15 @@ mesh::LocalIdentity radio_new_identity() {
}
void HWTSensorManager::start_gps() {
if (!gps_active) {
_location->begin(); // Claims periph_power via RefCountedDigitalPin
gps_active = true;
Serial1.println("$CFGSYS,h35155*68"); // Configure GPS for all constellations
}
_location->setGpsOn(true);
}
void HWTSensorManager::stop_gps() {
if (gps_active) {
gps_active = false;
_location->stop(); // Releases periph_power via RefCountedDigitalPin
}
_location->setGpsOn(false);
}
bool HWTSensorManager::begin() {
// init GPS port
Serial1.begin(115200, SERIAL_8N1, PIN_GPS_RX, PIN_GPS_TX);
// the GPS UART (pins, baud rate) is now configured by gps_driver when the GPS is started
return true;
}
@@ -76,7 +86,7 @@ void HWTSensorManager::loop() {
_location->loop();
if (millis() > next_gps_update) {
if (gps_active && _location->isValid()) {
if (_location->isGpsOn() && _location->hasValidFix()) {
node_lat = ((double)_location->getLatitude())/1000000.;
node_lon = ((double)_location->getLongitude())/1000000.;
node_altitude = ((double)_location->getAltitude()) / 1000.0;
@@ -93,7 +103,7 @@ const char* HWTSensorManager::getSettingName(int i) const {
}
const char* HWTSensorManager::getSettingValue(int i) const {
if (i == 0) {
return gps_active ? "1" : "0";
return _location->isGpsOn() ? "1" : "0";
}
return NULL;
}
-1
View File
@@ -14,7 +14,6 @@
#endif
class HWTSensorManager : public SensorManager {
bool gps_active = false;
LocationProvider * _location;
void start_gps();
+3 -2
View File
@@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
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;
@@ -43,4 +45,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2
View File
@@ -212,6 +212,7 @@ build_flags =
-D BLE_DEBUG_LOGGING=1
-D OFFLINE_QUEUE_SIZE=256
-D ENABLE_WIFI_INTERFACE
-D ENABLE_ESP_MDNS
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
build_src_filter = ${heltec_v4_oled.build_src_filter}
@@ -231,6 +232,7 @@ build_flags =
${heltec_v4_oled.build_flags}
-I examples/companion_radio/ui-new
-D ENABLE_WIFI_INTERFACE
-D ENABLE_ESP_MDNS
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D OFFLINE_QUEUE_SIZE=256
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -43,4 +44,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+3 -1
View File
@@ -17,7 +17,9 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock, GPS_RESET, GPS_EN, &board.periph_power);
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;
+2 -2
View File
@@ -12,7 +12,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() {
return mesh::LocalIdentity(&rng); // create new random identity
}
+101
View File
@@ -0,0 +1,101 @@
# LilyGO T3 STM32 V1.0
MVP support for the STM32WL55CCU6 board with its integrated Sub-GHz radio and
128×64 SSD1315 SPI OLED. Supports a USB companion and a repeater, with a default
transmit power of **20 dBm**. The companion uses USB serial; the board has no BLE.
## Build
```sh
pio run -e LilyGo_T3_STM32_companion_radio_usb
pio run -e LilyGo_T3_STM32_repeater
```
The companion supports 100 contacts and eight channels. Radio settings inherit
the repository defaults; select settings appropriate to the board's RF band.
Existing saved preferences override build defaults.
## Optional INA219 telemetry
The INA219 builds use MeshCore's existing environment sensor driver to report
voltage, current, and power. Build either role with:
```sh
pio run -e LilyGo_T3_STM32_repeater_ina219
pio run -e LilyGo_T3_STM32_companion_radio_usb_ina219
```
Connect the sensor's logic supply to **3.3 V** and use a common ground:
| INA219 connection | T3 STM32 connection |
| --- | --- |
| VCC / logic supply | 3.3 V |
| GND | GND |
| SDA | PB7 (JP2 pin 9) |
| SCL | PB8 (JP2 pin 10) |
PB7/PB8 are the alternate I2C1 pins exposed on the board headers. The default
STM32 I2C pins, PA9/PA10, are reserved for USB serial. The OLED uses SPI.
The sensor is detected at startup at address **0x40**; to use another address,
override `TELEM_INA219_ADDRESS` in the build flags. An absent sensor produces no
additional telemetry. The base builds do not initialize I2C or include the driver.
The measurement terminals (VIN+ and VIN-) go in series with the positive supply
of the circuit being measured; these are separate from the sensor's logic supply.
See the [INA219 wiring guide](https://learn.adafruit.com/adafruit-ina219-current-sensor-breakout/wiring).
USB power can bypass a sensor placed only in the battery lead.
Readings use environment telemetry permissions. Existing telemetry encodes current
in 1 mA steps and power in whole watts; it does not provide accumulated mAh or
battery percentage. INA219 telemetry has been confirmed on hardware with the
repeater build; the USB companion sensor build has been compile-tested only.
## Flash and connect
Connect the USB serial port. Hold BOOT, press and release RST, then release BOOT:
```sh
pio run -e LilyGo_T3_STM32_companion_radio_usb -t upload --upload-port /dev/ttyACM0
```
Choose your actual serial port, then press RST after programming. The repeater
CLI and USB companion protocol both use USART1 at **115200 baud**.
The bundled `stm32flash` 0.7 may reject device ID `0x497` due to an
[upstream packaging issue](https://github.com/platformio/platform-ststm32/issues/899).
Use an updated [stm32flash](https://sourceforge.net/p/stm32flash/code/ci/master/tree/)
with STM32WL support, or STM32CubeProgrammer in UART mode. For CubeProgrammer,
use `.pio/build/<environment>/firmware.hex`, or `firmware.bin` at `0x08000000`.
ST-Link and J-Link uploads are also available through the board's SWD connector.
Application flash is limited to **224 KiB**. InternalFS occupies the final
32 KiB at `0x08038000`–`0x0803FFFF`; preserve it when updating to retain the
identity and settings.
## Hardware mapping
| Function | Pins / setting |
| --- | --- |
| USART1 | TX PA9, RX PA10 |
| Radio RF switch | PB2/PB6: idle 0/0, RX 1/0, HP TX 0/1 |
| Radio oscillator | 32 MHz crystal; TCXO mode disabled |
| SPI1 | SCK PA5, MISO PA6, MOSI PA7 |
| OLED | CS PB12, DC PA8, no software reset pin |
| SD card | CS PA4, held high |
| User button | PH3/BOOT, active high |
| LEDs | PA0/PA1, left off |
Initialization follows the manufacturer's
[hardware files](https://github.com/Xinyuan-LilyGO/T3-STM32/tree/master/hardware)
and [reference firmware](https://github.com/Xinyuan-LilyGO/T3-STM32/tree/master/examples/6_SubGHz_TXRX).
## MVP validation and limitations
Hardware checks covered OLED startup, USB companion communication, advertisement
reception, Public message transmission, and matching repeater trace replies at
20 dBm. Public packets were captured and decrypted independently. Some repeater
pings timed out; long-term reliability has not been established. Higher transmit
powers are outside the validated MVP setting.
The repeater builds successfully; forwarding has not been hardware-tested.
Built-in battery telemetry, SD storage, and low-power optimization are not implemented.
@@ -0,0 +1,11 @@
#pragma once
#ifdef __cplusplus
// Include the device headers first so subsequent Arduino includes cannot
// reintroduce the peripheral macro. It conflicts with both mesh::RNG and
// Crypto's global RNG object. Leave C HAL sources' register macros intact.
#include <Arduino.h>
#ifdef RNG
#undef RNG
#endif
#endif
+81
View File
@@ -0,0 +1,81 @@
[lilygo_t3_stm32]
extends = stm32_base
board = lilygo_t3_stm32
board_upload.maximum_size = 229376 ; final 32 KiB reserved for InternalFS
build_flags = ${stm32_base.build_flags}
-include variants/lilygo_t3_stm32/STM32ArduinoCompat.h
-I variants/lilygo_t3_stm32
-D RADIO_CLASS=CustomSTM32WLx
-D WRAPPER_CLASS=CustomSTM32WLxWrapper
-D LORA_TX_POWER=20
-D SX126X_CURRENT_LIMIT=140
-D RX_BOOSTED_GAIN=true
-D STM32WL_TCXO_VOLTAGE=0 ; crystal oscillator; manufacturer sets IS_TCXO_SUPPORTED=0
-D PIN_SERIAL_TX=PA9
-D PIN_SERIAL_RX=PA10
-D SERIAL_UART_INSTANCE=1
-D PIN_SPI_SCK=PA5
-D PIN_SPI_MISO=PA6
-D PIN_SPI_MOSI=PA7
-D PIN_OLED_CS=PB12
-D PIN_OLED_DC=PA8
-D PIN_OLED_RESET=-1
-D PIN_USER_BTN=PH3
-D USER_BTN_PRESSED=HIGH
-D DISPLAY_CLASS=SSD1306Display
build_src_filter = ${stm32_base.build_src_filter}
+<../variants/lilygo_t3_stm32>
+<helpers/ui/SSD1306Display.cpp>
lib_deps = ${stm32_base.lib_deps}
adafruit/Adafruit SSD1306 @ ^2.5.13
[env:LilyGo_T3_STM32_repeater]
extends = lilygo_t3_stm32
build_flags = ${lilygo_t3_stm32.build_flags}
-D ADVERT_NAME='"T3 STM32 Repeater"'
-D ADMIN_PASSWORD='"password"'
-D MAX_NEIGHBOURS=50
build_src_filter = ${lilygo_t3_stm32.build_src_filter}
+<../examples/simple_repeater/*.cpp>
[env:LilyGo_T3_STM32_companion_radio_usb]
extends = lilygo_t3_stm32
build_flags = ${lilygo_t3_stm32.build_flags}
-I examples/companion_radio/ui-orig
-D MAX_CONTACTS=100
-D MAX_GROUP_CHANNELS=8
-D ENABLE_USB_INTERFACE
build_src_filter = ${lilygo_t3_stm32.build_src_filter}
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-orig/*.cpp>
lib_deps = ${lilygo_t3_stm32.lib_deps}
densaugeo/base64 @ ~1.4.0
; Optional INA219 telemetry on I2C1. Keep the base builds sensor-free.
[lilygo_t3_stm32_ina219]
build_flags =
-D ENV_INCLUDE_INA219=1
-D PIN_WIRE_SDA=PB7
-D PIN_WIRE_SCL=PB8
build_src_filter =
+<helpers/sensors/EnvironmentSensorManager.cpp>
lib_deps =
adafruit/Adafruit INA219 @ ^1.2.3
[env:LilyGo_T3_STM32_repeater_ina219]
extends = env:LilyGo_T3_STM32_repeater
build_flags = ${env:LilyGo_T3_STM32_repeater.build_flags}
${lilygo_t3_stm32_ina219.build_flags}
build_src_filter = ${env:LilyGo_T3_STM32_repeater.build_src_filter}
${lilygo_t3_stm32_ina219.build_src_filter}
lib_deps = ${lilygo_t3_stm32.lib_deps}
${lilygo_t3_stm32_ina219.lib_deps}
[env:LilyGo_T3_STM32_companion_radio_usb_ina219]
extends = env:LilyGo_T3_STM32_companion_radio_usb
build_flags = ${env:LilyGo_T3_STM32_companion_radio_usb.build_flags}
${lilygo_t3_stm32_ina219.build_flags}
build_src_filter = ${env:LilyGo_T3_STM32_companion_radio_usb.build_src_filter}
${lilygo_t3_stm32_ina219.build_src_filter}
lib_deps = ${env:LilyGo_T3_STM32_companion_radio_usb.lib_deps}
${lilygo_t3_stm32_ina219.lib_deps}
+94
View File
@@ -0,0 +1,94 @@
#include <Arduino.h>
#include <SPI.h>
#if ENV_INCLUDE_INA219
#include <Wire.h>
#endif
#include "target.h"
LilyGoT3STM32Board board;
RADIO_CLASS radio = new STM32WLx_Module();
WRAPPER_CLASS radio_driver(radio, board);
VolatileRTCClock rtc_clock;
#if ENV_INCLUDE_INA219
EnvironmentSensorManager sensors;
#else
SensorManager sensors;
#endif
DISPLAY_CLASS display;
// PH3 is also BOOT0: the board's button is active high with an external pull-down.
MomentaryButton user_btn(PIN_USER_BTN, 1000, false);
static const uint32_t rfswitch_pins[] = {
PB2, PB6, RADIOLIB_NC, RADIOLIB_NC, RADIOLIB_NC
};
static const Module::RfSwitchMode_t rfswitch_table[] = {
{STM32WLx::MODE_IDLE, {LOW, LOW}},
{STM32WLx::MODE_RX, {HIGH, LOW}},
{STM32WLx::MODE_TX_HP, {LOW, HIGH}},
END_OF_MODE_TABLE,
};
void LilyGoT3STM32Board::begin() {
STM32Board::begin();
#if ENV_INCLUDE_INA219
// These builds remap Wire to PB7/PB8; PA9/PA10 are used by USART1.
Wire.begin();
#endif
// The SD card shares SPI1 with the OLED; keep it deselected.
digitalWrite(PA4, HIGH);
pinMode(PA4, OUTPUT);
digitalWrite(PIN_OLED_CS, HIGH);
pinMode(PIN_OLED_CS, OUTPUT);
pinMode(PIN_USER_BTN, INPUT);
// Both onboard LEDs are active high. Leave them off until explicitly needed.
digitalWrite(PA0, LOW);
pinMode(PA0, OUTPUT);
digitalWrite(PA1, LOW);
pinMode(PA1, OUTPUT);
SPI.setSCLK(PIN_SPI_SCK);
SPI.setMISO(PIN_SPI_MISO);
SPI.setMOSI(PIN_SPI_MOSI);
SPI.begin();
delay(200); // OLED power-on settling time used by the manufacturer's example.
}
#ifndef LORA_CR
#define LORA_CR 5
#endif
static bool check_radio_status(int status, const char* stage) {
if (status == RADIOLIB_ERR_NONE) return true;
Serial.print("ERROR: ");
Serial.print(stage);
Serial.print(": ");
Serial.println(status);
return false;
}
bool radio_init() {
radio.setRfSwitchTable(rfswitch_pins, rfswitch_table);
int status = radio.begin(LORA_FREQ, LORA_BW, LORA_SF, LORA_CR,
RADIOLIB_SX126X_SYNC_WORD_PRIVATE, LORA_TX_POWER,
16, STM32WL_TCXO_VOLTAGE, 0);
if (!check_radio_status(status, "radio.begin")) return false;
// Match the manufacturer's 3.3 V power-LDO trim (REG_DRV_CTRL).
const uint8_t power_ldo_3v3 = 0x0E;
status = radio.writeRegister(0x091F, &power_ldo_3v3, 1);
if (!check_radio_status(status, "power LDO trim")) return false;
status = radio.setCurrentLimit(SX126X_CURRENT_LIMIT);
if (!check_radio_status(status, "current limit")) return false;
status = radio.setRxBoostedGainMode(RX_BOOSTED_GAIN);
if (!check_radio_status(status, "RX gain")) return false;
return check_radio_status(radio.setCRC(1), "CRC");
}
mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng);
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <RadioLib.h>
#include <helpers/stm32/STM32Board.h>
#include <helpers/radiolib/CustomSTM32WLxWrapper.h>
#include <helpers/ArduinoHelpers.h>
#if ENV_INCLUDE_INA219
#include <helpers/sensors/EnvironmentSensorManager.h>
#else
#include <helpers/SensorManager.h>
#endif
#include <helpers/ui/SSD1306Display.h>
#include <helpers/ui/MomentaryButton.h>
class LilyGoT3STM32Board : public STM32Board {
public:
void begin() override;
const char* getManufacturerName() const override {
return "LilyGO T3 STM32";
}
};
extern LilyGoT3STM32Board board;
extern WRAPPER_CLASS radio_driver;
extern VolatileRTCClock rtc_clock;
#if ENV_INCLUDE_INA219
extern EnvironmentSensorManager sensors;
#else
extern SensorManager sensors;
#endif
extern DISPLAY_CLASS display;
extern MomentaryButton user_btn;
bool radio_init();
mesh::LocalIdentity radio_new_identity();
+2 -2
View File
@@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -34,4 +35,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -2
View File
@@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -47,4 +48,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng);
}
+2 -2
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -38,4 +39,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -17,7 +17,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -19,7 +19,8 @@ AutoDiscoverRTCClock rtc_clock(fallback_clock);
#if ENV_INCLUDE_GPS
#include <helpers/sensors/MicroNMEALocationProvider.h>
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors;
@@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -14,7 +14,8 @@ WRAPPER_CLASS radio_driver(radio, board);
ESP32RTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
MicroNMEALocationProvider gps(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider gps(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors(gps);
#ifdef DISPLAY_CLASS
+2
View File
@@ -93,6 +93,7 @@ build_flags =
${LilyGo_T-Echo.build_flags}
-I src/helpers/ui
-I examples/companion_radio/ui-new
-D EINK_REFRESH_LOOP
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D QSPIFLASH=1
@@ -120,6 +121,7 @@ build_flags =
${LilyGo_T-Echo.build_flags}
-I src/helpers/ui
-I examples/companion_radio/ui-new
-D EINK_REFRESH_LOOP
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D OFFLINE_QUEUE_SIZE=256
+2 -3
View File
@@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -36,5 +37,3 @@ mesh::LocalIdentity radio_new_identity() {
RadioNoiseListener rng(radio);
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -1
View File
@@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
+2 -2
View File
@@ -13,7 +13,8 @@ VolatileRTCClock fallback_clock;
AutoDiscoverRTCClock rtc_clock(fallback_clock);
#ifdef ENV_INCLUDE_GPS
MicroNMEALocationProvider nmea = MicroNMEALocationProvider(Serial1, &rtc_clock);
NmeaGpsDriver gps_driver(Serial1);
MicroNMEALocationProvider nmea(gps_driver, &rtc_clock);
EnvironmentSensorManager sensors = EnvironmentSensorManager(nmea);
#else
EnvironmentSensorManager sensors = EnvironmentSensorManager();
@@ -35,4 +36,3 @@ mesh::LocalIdentity radio_new_identity() {
return mesh::LocalIdentity(&rng); // create new random identity
}
+2 -2
View File
@@ -23,8 +23,8 @@ build_flags =
-D SX126X_DIO2_AS_RF_SWITCH=false
-D SX126X_DIO3_TCXO_VOLTAGE=1.8
-D SX126X_RX_BOOSTED_GAIN=1
-D PIN_GPS_RX=12
-D PIN_GPS_TX=15
-D PIN_GPS_TX=12 ; GPS module TX -> MCU RX (GPIO12)
-D PIN_GPS_RX=15 ; GPS module RX <- MCU TX (GPIO15)
-D DISPLAY_CLASS=SSD1306Display
build_src_filter = ${esp32_base.build_src_filter}
+<../variants/meshadventurer>
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff. Show more