Merge branch 'dev' into feature/lilygo-t3-stm32

This commit is contained in:
fdlamotte authored and GitHub committed 2026-11-10 08:22:52 -04:00
commit f40e13a425
178 files changed
+5207 -1141

No files matched your search

+1
View File
@@ -44,6 +44,7 @@ jobs:
- 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)
+18
View File
@@ -18,6 +18,15 @@ Thanks for considering contributing to this project!
### 3. Submitting Code Changes (Pull Requests)
The project receives far more code than it is able to process.
To increase the likelihood of your PR being accepted, please consider
the following:
- **Keep it small.** Changes of about 10 lines or fewer were merged 64% of the time; changes over 1000 lines, 10%.
- **Keep the description short.** A few sentences on what changed and why is enough. Longer descriptions were merged less often.
- **Build a track record with small fixes first.** First-time contributors were merged 31% of the time, rising to 74% after 10 merged PRs.
- **Open the PR when it is ready for review, not as a draft.**
#### Small fixes (typos, comments, examples, small bug fixes)
→ Just open a pull request — no prior issue needed
@@ -52,6 +61,15 @@ Please follow the existing C++ style (per the .clang-format)
(But consistency with existing code is more important than strict rules)
## LLM Agent Specific Advice
- **Have a human read and understand every line before opening the PR.** Check every claim in the description against the code.
- **Search open PRs first** so you don't duplicate one that's already waiting.
- **Pick a subsystem maintainers are actively merging in.** If several PRs for the same board or feature have sat for weeks with no response, a new one will likely sit too.
- **Prefer low-risk changes.** Build fixes and documentation fixes merge most often (about 61% and 64%). Changes to protocol or behavior, and crash or overflow fixes, get much more scrutiny.
- **Make a minimal diff in the existing style.** Don't reformat, rename, or "tidy" code next to your change.
- **Don't use a templated description.** Lots of headings and boilerplate on a small change reads as generated. Just say what changed, why, and what hardware you tested on.
## Thank You!
> [!NOTE]
+76 -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`
+579
View File
@@ -0,0 +1,579 @@
# Companion CLI
Since version 1.18 meshcore companion radio firmware has a CLI interface, which can be accessed locally (through companion radio protocol) or remotely via the network.
## Navigation
- [Operational](#operational)
- [Configuration](#configuration)
- [System](#system)
- [Radio](#radio)
- [GPS](#gps)
- [BLE](#ble)
- [Wifi](#wifi)
- [UI](#ui)
## Operational
### Reboot the node
**Usage:**
- `reboot`
**Note:** No reply is sent.
---
### Power-off the node
**Usage:**
- `poweroff`, or
- `shutdown`
**Note:** No reply is sent.
---
## Configuration
### System
#### View or change this node's name
**Usage:**
- `get name`
- `set name <name>`
**Parameters:**
- `name`: Node name
**Set by build flag:** `ADVERT_NAME`
**Default:** Varies by board
**Note:** Advertised names can use up to 23 bytes when location is included and 31 bytes otherwise. Emoji and Unicode characters may take more than one byte. Names that exceed the available advert space are truncated at a valid UTF-8 code point boundary.
---
#### View this node's firmware version
**Usage:** `ver`
---
#### Configure this node's timezone
**Usage:**
- `set tz.offset <offset>`
- `get tz.offset`
**Parameters:**
- `offset`: float value of the offset in hours
---
#### 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`.
#### View or change this node's radio parameters
**Usage:**
- `get radio`
- `set radio <freq>,<bw>,<sf>,<cr>`
**Parameters:**
- `freq`: Frequency in MHz
- `bw`: Bandwidth in kHz
- `sf`: Spreading factor (5-12)
- `cr`: Coding rate (5-8)
**Set by build flag:** `LORA_FREQ`, `LORA_BW`, `LORA_SF`, `LORA_CR`
**Default:** `869.618,62.5,8,5`
**Note:** Requires reboot to apply
---
#### View or change this node's transmit power
**Usage:**
- `get tx`
- `set tx <dbm>`
**Parameters:**
- `dbm`: Power level in dBm (1-22)
**Set by build flag:** `LORA_TX_POWER`
**Default:** Varies by board
**Notes:** This setting only controls the power level of the LoRa chip. Some nodes have an additional power amplifier stage which increases the total output. Refer to the node's manual for the correct setting to use. **Setting a value too high may violate the laws in your country.**
---
#### View or change this node's frequency
**Usage:**
- `get freq`
- `set freq <frequency>`
**Parameters:**
- `frequency`: Frequency in MHz
**Default:** `869.618`
**Note:** Requires reboot to apply
**Serial Only:** `set freq <frequency>`
---
### 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`
- `set radio.rxgain <state>`
**Parameters:**
- `state`: `on`|`off`
**Default:** `on`
---
#### View or change the LoRa FEM receive-path gain state on supported boards
**Usage:**
- `get radio.fem.rxgain`
- `set radio.fem.rxgain <state>`
**Parameters:**
- `state`: `on`|`off`
**Notes:**
- This controls the external LoRa FEM receive-path LNA where the board supports it.
- This is separate from `radio.rxgain`, which controls the radio chip receive gain mode.
---
#### View or change the LoRa FEM transmit-path gain state on supported boards
**Usage:**
- `get radio.fem.txgain`
- `set radio.fem.txgain <state>`
**Parameters:**
- `state`: `on`|`off`
**Notes:**
- This controls a software-selectable external LoRa FEM transmit gain where the board supports it.
- On Station G3, remove the PA PL1 jumper to allow software control. `on` selects PA PL1 high/short and `off` selects PA PL1 low/open. The PA PL2 hardware jumper determines whether this switches between power levels 1/3 or 2/4.
- Select an operating level and SX1262 transmit power that comply with local RF limits and the Station G3 power-supply requirements.
- The setting is saved immediately, but on Station G3 the level is applied to the hardware at the start of the next transmit, so that the PA supply rail is never re-targeted while the PA is being driven. `get` reports the configured state, which may lead the hardware until the node next transmits.
---
#### View or change the duty cycle limit
**Usage:**
- `get dutycycle`
- `set dutycycle <value>`
**Parameters:**
- `value`: Duty cycle percentage (1-100)
**Default:** `50%` (equivalent to airtime factor 1.0)
**Examples:**
- `set dutycycle 100` — no duty cycle limit
- `set dutycycle 50` — 50% duty cycle (default)
- `set dutycycle 10` — 10% duty cycle
- `set dutycycle 1` — 1% duty cycle (strictest EU requirement)
> **Note:** Added in firmware v1.15.0
---
#### View or change the airtime factor (duty cycle limit)
> **Deprecated** as of firmware v1.15.0. Use [`get/set dutycycle`](#view-or-change-the-duty-cycle-limit) instead.
**Usage:**
- `get af`
- `set af <value>`
**Parameters:**
- `value`: Airtime factor (0-9). After each transmission, the repeater enforces a silent period of approximately the on-air transmission time multiplied by the value. This results in a long-term duty cycle of roughly 1 divided by (1 plus the value). For example:
- `af = 1` → ~50% duty
- `af = 2` → ~33% duty
- `af = 3` → ~25% duty
- `af = 9` → ~10% duty
You are responsible for choosing a value that is appropriate for your jurisdiction and channel plan (for example EU 868 Mhz 10% duty cycle regulation).
**Default:** `1.0`
---
#### View or change the local interference threshold
**Usage:**
- `get int.thresh`
- `set int.thresh <value>`
**Parameters:**
- `value`: Interference threshold value
**Default:** `0.0`
---
#### Enable or disable hardware Channel Activity Detection (CAD)
**Usage:**
- `get cad`
- `set cad <on|off>`
**Description:** When enabled, the radio performs a hardware Channel Activity Detection scan before transmitting and defers if the channel is busy. Runs independently of `int.thresh` — either, both, or none may be active.
**Parameters:**
- `on|off`: Enable or disable hardware CAD
**Default:** `off`
---
#### View or change the AGC Reset Interval
**Usage:**
- `get agc.reset.interval`
- `set agc.reset.interval <value>`
**Parameters:**
- `value`: Interval in seconds, 0-1020, rounded down to a multiple of 4 (17 becomes 16). 0 to disable.
**Default:** `0.0`
---
#### Enable or disable Multi-Acks support
**Usage:**
- `get multi.acks`
- `set multi.acks <state>`
**Parameters:**
- `state`: `0` (disable) or `1` (enable)
**Default:** `0`
---
#### View or change this node's advert path hash size
**Usage:**
- `get path.hash.mode`
- `set path.hash.mode <value>`
**Parameters:**
- `value`: Path hash size (0-2)
- `0`: 1 Byte hash size (256 unique ids)[64 max flood]
- `1`: 2 Byte hash size (65,536 unique ids)[32 max flood]
- `2`: 3 Byte hash size (16,777,216 unique ids)[21 max flood]
- `3`: DO NOT USE (Reserved)
**Default:** `0`
**Note:** the 'path.hash.mode' sets the low-level ID/hash encoding size used when the repeater adverts. This setting has no impact on what packet ID/hash size this repeater forwards, all sizes should be forwarded on firmware >= 1.14. This feature was added in firmware 1.14
#### View or change the retransmit delay factor for flood traffic
**Usage:**
- `get txdelay`
- `set txdelay <value>`
**Parameters:**
- `value`: Transmit delay factor (0-2)
**Default:** `0.5`
**Note:** When multiple nearby repeaters all hear the same flood packet, each waits a random amount of time before retransmitting to avoid simultaneous collisions. This factor scales the size of that random window. Higher values reduce collision risk at the cost of added latency. `0` disables the window entirely.
---
#### View or change the retransmit delay factor for direct traffic
**Usage:**
- `get direct.txdelay`
- `set direct.txdelay <value>`
**Parameters:**
- `value`: Direct transmit delay factor (0-2)
**Default:** `0.3` (Repeater) - `0.2` (Room Server, Sensor)
**Note:** Same collision-avoidance random window as `txdelay`, but applied to direct (non-flood, routed) traffic. The default is lower because direct packets are addressed to a specific next hop, so far fewer nodes compete to retransmit them.
---
#### [Experimental] View or change the processing delay for received traffic
**Usage:**
- `get rxdelay`
- `set rxdelay <value>`
**Parameters:**
- `value`: Receive delay base (0-20)
**Default:** `0.0`
**Note:** When enabled, repeaters that received a flood packet with a weak signal are held in a delay queue before processing, while those that received it with a strong signal process it immediately. This gives strong-signal paths forwarding priority. By the time weak-signal nodes process their copy, the packet may have already propagated and will be suppressed as a duplicate, reducing redundant retransmissions.
---
### BLE
#### Change BLE PIN
**Usage:**
- `set pin <pin>`
**Parameters:**
- `pin`: New BLE PIN
**Set by build flag:** `BLE_PIN_CODE`
---
### Wifi
#### Get status
**Usage:**
- `get wifi.status`
- `get wifi.ip`
---
#### Toggle
**Usage:**
- `set wifi.enabled <value>`
- `get wifi.enabled`
**Parameters:**
- `value`: `0` (disable) or `1` (enable)
---
#### Set SSID
**Usage:**
- `set wifi.ssid <value>`
- `get wifi.ssid`
**Parameters:**
- `value`: ssid as a string
---
#### Set password
**Usage:**
- `set wifi.pwd <value>`
- `get wifi.pwd`
**Parameters:**
- `value`: password string
---
### UI
#### Show clock
**Usage:**
- `set ui.show_clock <state>`
- `get ui.show_clock`
**Parameters:**
- `state`: `0` (disable) or `1` (enable)
**Default:** `0` (or `UI_SHOW_CLOCK` build flag)
---
#### 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>`
- `get ui.nd_name`
**Parameters:**
- `state`: `1` (show name) or `0` (show pubkey_prefix)
**Default:** `1`
**Note:** When showing name, there is not always enough space to draw both incoming and outgoing snr values.
---
#### Auto-off screen
**Usage:**
- `set ui.auto_off_delay <delay>`
- `get ui.auto_off_delay`
**Parameters:**
- `delay`: in seconds (`0` means always on)
**Default:** `15` (or set by `AUTO_OFF_MILLIS` build flag (in ms))
**Note:**
On e-ink displays, when turned off, the screen is not necessarily blanked, see `ui.auto_off_blank` and `ui.backlight_delay`.
When screen is not blanked, it is not refreshed any more. To let the user aware of that, a sleep icon is shown.
---
#### Display backlight timeout
**Usage:**
- `set ui.backlight_delay <delay>`
- `get ui.backlight_delay`
**Parameters:**
- `delay`: in seconds
- `0` means no timeout
- `-2` means always off
- `-1` means always on
**Note:**
When set to `0`, backlight can only be triggered using backlight btn.
---
#### When to turn backlight on
**Usage:**
- `set ui.backlight_on_keys <state>`
- `get ui.backlight_on_keys`
- `set ui.backlight_on_msgs <state>`
- `get ui.backlight_on_msgs`
**Parameters:**
- `state`: `0` (disable) or `1` (enable)
**Default:**
- `ui.backlight_on_msgs = 0`
- `ui.backlight_on_keys = 0` if there is a backlight button on the board, else `1`
**Note:**
By default backlight is triggered by backlight button if present (as long as the button is pressed backlight is on, and is turned off after a delay).
These toggles permits to toggle backlight when keys are pressed or when a message arrives (it acts as a notification signal).
If `backlight_delay` is set to `0` then this setting has no effect, backlight won't be turned on.
---
#### Control if eink screen should be blanked
**Usage:**
- `set ui.auto_off_blank <state>`
- `get ui.auto_off_blank`
**Parameters:**
- `state`: `0` (disable) or `1` (enable)
**Default:** `0` (or set by `UI_SCREENOFF_BLANK` build flag)
**Note:**
If disabled, when screen is shut the displays stays on screen and is not updated (an sleep icons covers battery to show the screen is sleeping).
When screen is blanked, the controller is also put into hibernation, which should preserve the screen a little and some battery ...
---
#### Maximum number of partial refreshes
**Usage:**
- `set ui.max_partial <value>`
- `get ui.max_partial`
**Parmeters:**
- `value`: max partial refreshes before doing a full refresh
**Default:** 0 (no partial refresh or set by `EINK_MAX_PARTIAL_REFRESH` build flag)
**Note:**
Forcing full refresh helps revives the screen when some tearing appears (under certain environmental conditions). If you see some tearing appearing, you can force full refresh on your screen manually by double clicking the backlight button. If tearing reappears often, use this setting to force full refresh every `value` partial refreshes.
+82 -2
View File
@@ -118,10 +118,17 @@ MeshCore-specific functionality uses the standard KISS SetHardware command. The
| Reboot | `0x18` | - |
| SetSignalReport | `0x19` | Enable (1): 0x00=disable, nonzero=enable |
| GetSignalReport | `0x1A` | - |
| GetCapabilities | `0x1B` | - |
| SetAgcResetInterval | `0x1C` | Seconds (2): 0=disable, 0-1020 |
| GetAgcResetInterval | `0x1D` | - |
| SetFemState | `0x1E` | Apply mask (1) + Value mask (1) |
| GetFemState | `0x1F` | - |
| SetRxBoostedGain | `0x20` | Enable (1): 0x00=disable, nonzero=enable |
| GetRxBoostedGain | `0x21` | - |
### Response Sub-commands (TNC to Host)
Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range.
Response codes use the high-bit convention: `response = command | 0x80`. Generic and unsolicited responses use the `0xF0`+ range. Set commands that report state (SetSignalReport, SetAgcResetInterval, SetFemState, SetRxBoostedGain) reply with the matching Get response, so `0x9C`, `0x9E` and `0xA0` are never sent.
| Sub-command | Value | Data |
|--------------|--------|-----------------------------------------|
@@ -147,6 +154,10 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic
| DeviceName | `0x96` | Name (variable, UTF-8) |
| Pong | `0x97` | - |
| SignalReport | `0x9A` | Status (1): 0x00=disabled, 0x01=enabled |
| Capabilities | `0x9B` | Feature bits (4) |
| AgcResetInterval | `0x9D` | Effective seconds (2) |
| FemState | `0x9F` | Capability mask (1) + Value mask (1) |
| RxBoostedGain | `0xA1` | Status (1): 0x00=disabled, 0x01=enabled |
| OK | `0xF0` | - |
| Error | `0xF1` | Error code (1) |
| TxDone | `0xF8` | Result (1): 0x00=failed, 0x01=success |
@@ -163,6 +174,7 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic
| UnknownCmd | `0x05` | Unknown sub-command |
| EncryptFailed | `0x06` | Encryption failed |
| TxBusy | `0x07` | Radio TX busy, or host output queue full |
| Unsupported | `0x08` | Command known, but not supported by this board |
### Unsolicited Events
@@ -215,7 +227,75 @@ All values little-endian.
|-------------|---------|-----------------------|
| Noise floor | 2 bytes | int16_t, dBm (signed) |
The modem recalibrates the noise floor every 2 seconds with an AGC reset every 30 seconds.
The modem recalibrates the noise floor every 2 seconds. AGC resets follow the configured AGC reset interval (default 32 seconds).
### Capabilities (Capabilities response)
All values little-endian. Hosts should probe capabilities rather than infer them from the firmware version: boards running the same version expose different hardware controls. Firmware older than version 2 answers GetCapabilities with `UnknownCmd`; treat that as no capabilities.
| Field | Size | Description |
|--------------|---------|--------------------|
| Feature bits | 4 bytes | uint32_t, see below |
| Bit | Value | Description |
|-----|--------|-------------------------------------------|
| 0 | `0x01` | AGC reset interval control (always set) |
| 1 | `0x02` | External FEM RX (LNA) gain control |
| 2 | `0x04` | External FEM TX (PA) gain control |
| 3 | `0x08` | Radio chip boosted RX gain control |
Remaining bits are reserved and sent as 0.
### AGC Reset Interval (SetAgcResetInterval / AgcResetInterval response)
All values little-endian.
| Field | Size | Description |
|---------|---------|-------------------------------------------|
| Seconds | 2 bytes | uint16_t, 0 = disabled, maximum 1020 |
The modem periodically resets the radio's AGC while idle (no transmission in progress and host output not backed up). The interval has 4-second resolution, matching the MeshCore `agc.reset.interval` setting: requested values are rounded down to a multiple of 4, so 1-3 disable the reset. Values above 1020 return `InvalidParam`. SetAgcResetInterval replies with the AgcResetInterval response carrying the effective value, and restarts the countdown from the time of the request.
The default is 32 seconds (previously a fixed 30; changed so the default is a settable 4-second multiple). The setting is not persisted; hosts should re-send it after reconnecting or rebooting the modem.
### FEM State (SetFemState / FemState response)
Controls the board's external LoRa front-end module gain. This is separate from the radio chip's own RX boosted gain. TX/RX switching of the FEM is handled by the board and is not affected by these settings.
| Bit | Value | Description |
|-----|--------|---------------------------------|
| 0 | `0x01` | RX gain (LNA enabled) |
| 1 | `0x02` | TX gain (PA high gain enabled) |
SetFemState data:
| Field | Size | Description |
|------------|--------|------------------------------------------------|
| Apply mask | 1 byte | Bits to change; bits not set are left as-is |
| Value mask | 1 byte | New value for each bit in the apply mask |
FemState response data:
| Field | Size | Description |
|-----------------|--------|---------------------------------------------------|
| Capability mask | 1 byte | Bits this board can control |
| Value mask | 1 byte | Current state; always 0 for uncontrollable bits |
Example: enable RX gain without changing TX gain: apply `0x01`, value `0x01`.
If any bit in the apply mask is not in the board's capability mask (including reserved bits), the modem replies `Unsupported` and changes nothing. Otherwise SetFemState replies with the FemState response carrying the state read back from the board; if a bit differs from the request, that change did not take effect. SetFemState and GetFemState requests, including their error replies, are answered strictly in the order received. A SetFemState received while a packet is on air (before its TxDone is queued) is held and applied after TxDone, so its reply follows TxDone, and FEM requests that arrive after it wait behind it. Up to 4 FEM requests can wait; beyond that the modem replies `TxBusy` immediately. Capabilities come from the board's own `get/set radio.fem.rxgain` and `radio.fem.txgain` CLI commands (see [cli_commands.md](./cli_commands.md)): a gain is controllable when the board answers `get` with `> on` or `> off`. Any board that implements those commands is supported without KISS changes, and a board with a fixed, board-managed FEM (for example RAK3401) reports none. Changes made over KISS are not saved to the board's preferences.
The setting is not persisted; the board's power-on default applies after reboot.
### RX Boosted Gain (SetRxBoostedGain / RxBoostedGain response)
Controls the radio chip's own boosted RX gain mode (SX1262, SX1268, LLCC68, LR11x0, LR2021), the equivalent of the MeshCore `radio.rxgain` setting. This is independent of the external FEM RX gain controlled by SetFemState; a board can support either, both or neither.
| Field | Size | Description |
|--------|--------|------------------------------------|
| Status | 1 byte | 0x00 = power-saving, 0x01 = boosted |
SetRxBoostedGain always replies with the RxBoostedGain response carrying the effective state read back from the radio; if it differs from the requested value, the change did not take effect. Some radios must drop to standby to apply it, so the modem replies `TxBusy` and changes nothing while a packet is on air or host output is backed up; retry later. Before applying, any completed received packet is delivered to the host first. A packet still being received at that moment can be lost. Radios whose driver has no boosted RX gain control (for example SX127x and STM32WLx) do not set capability bit 3 and reply `Unsupported` to both commands. The power-on default is the build's `SX126X_RX_BOOSTED_GAIN` setting; the value is not persisted, and periodic AGC resets preserve it.
### Stats (Stats response)
+1
View File
@@ -20,6 +20,7 @@ Once you have a working app/project, you need to be able to demonstrate it exist
| 0120 | MCO Advanced | most.original.address@gmail.com — https://hdden.ru/MCOa/ |
| 0130 - 013F | StreamSensor | william@housedillon.com - https://housedillon.com/blog/lora-e5-with-seeed-fusion |
| 0140 | Nelos | support@nelos.app — https://nelos.app |
| 0150 | Road Events | juraj@bednar.io — https://github.com/jooray/roadbeacon/blob/main/nips/road-events.md |
| FF00 - FFFF | -reserved for testing/dev- | |
(add rows, inside the range 0100 - FEFF for custom apps)
+172 -4
View File
@@ -341,7 +341,7 @@ uint8_t MyMesh::getAutoAddMaxHops() const {
void MyMesh::onContactOverwrite(const uint8_t* pub_key) {
_store->deleteBlobByKey(pub_key, PUB_KEY_SIZE); // delete from storage
if (_serial->isConnected()) {
if (_serial && _serial->isConnected()) {
out_frame[0] = PUSH_CODE_CONTACT_DELETED;
memcpy(&out_frame[1], pub_key, PUB_KEY_SIZE);
_serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE);
@@ -349,7 +349,7 @@ void MyMesh::onContactOverwrite(const uint8_t* pub_key) {
}
void MyMesh::onContactsFull() {
if (_serial->isConnected()) {
if (_serial && _serial->isConnected()) {
out_frame[0] = PUSH_CODE_CONTACTS_FULL;
_serial->writeFrame(out_frame, 1);
}
@@ -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;
@@ -1175,7 +1177,9 @@ void MyMesh::handleCmdFrame(size_t len) {
? ERR_CODE_NOT_FOUND
: ERR_CODE_UNSUPPORTED_CMD); // unknown recipient, or unsupported TXT_TYPE_*
}
} else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel text msg
} else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG && len >= 7) { // send GroupChannel text msg
// 7 = code, txt_type, channel_idx and the 4 byte timestamp; the text may be empty.
// Without this the text length below is computed as len - 7 and turns negative.
int i = 1;
uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN
uint8_t channel_idx = cmd_frame[i++];
@@ -2091,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(); }
@@ -2122,6 +2131,23 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
return true;
}
#ifdef PIN_BUZZER
if (strcmp(command, "get buzzer") == 0) {
sprintf(reply, "> %s", _prefs.buzzer_quiet ? "off" : "on");
return true;
}
if (memcmp(command, "set buzzer ", 11) == 0) {
if (strcmp(&command[11], "on") == 0 || strcmp(&command[11], "off") == 0) {
_prefs.buzzer_quiet = strcmp(&command[11], "off") == 0;
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Error: state must be on or off");
}
return true;
}
#endif
if (memcmp(command, "set pin ", 8) == 0) {
_prefs.ble_pin = atoi(&command[8]);
savePrefs();
@@ -2191,8 +2217,36 @@ 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) {
sprintf(reply, "> %.1f", _prefs.tz_offset);
float q = _prefs.tz_offset * 4;
sprintf(reply, (q == (int)q && ((int)q & 1)) ? "> %.2f" : "> %.1f", _prefs.tz_offset);
return true;
}
if (memcmp(command, "set tz.offset ", 14) == 0) {
@@ -2206,6 +2260,120 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
}
return true;
}
#ifdef DISPLAY_CLASS
if (memcmp(command, "set ui.show_clock", 17) == 0) {
_prefs.ui_show_clock = atoi(&command[17]) ? 1 : 0;
savePrefs();
sprintf(reply, "> now %d", _prefs.ui_show_clock);
return true;
}
if (memcmp(command, "set ui.auto_off_delay", 21) == 0) {
_prefs.ui_auto_off_delay = atoi(&command[21]);
savePrefs();
sprintf(reply, "> now %d seconds", _prefs.ui_auto_off_delay);
return true;
}
if (memcmp(command, "set ui.backlight_delay", 22) == 0) {
_prefs.ui_backlight_delay = atoi(&command[22]);
savePrefs();
if (_prefs.ui_backlight_delay >= 0)
sprintf(reply, "> now %d seconds", _prefs.ui_backlight_delay);
else if (_prefs.ui_backlight_delay == -1)
sprintf(reply, "> now always on (-1)");
else
sprintf(reply, "> now disabled (<-1)");
return true;
}
if (memcmp(command, "set ui.backlight_on_keys", 24) == 0) {
_prefs.ui_backlight_on_keys = atoi(&command[24]);
savePrefs();
sprintf(reply, "> now %d", _prefs.ui_backlight_on_keys);
return true;
}
if (memcmp(command, "set ui.backlight_on_msgs", 24) == 0) {
_prefs.ui_backlight_on_msgs = atoi(&command[24]);
savePrefs();
sprintf(reply, "> now %d", _prefs.ui_backlight_on_msgs);
return true;
}
if (memcmp(command, "set ui.auto_off_blank", 21) == 0) {
_prefs.ui_auto_off_blank = atoi(&command[21]);
savePrefs();
sprintf(reply, "> now %d", _prefs.ui_auto_off_blank);
return true;
}
if (memcmp(command, "set ui.auto_off_keep_msgs", 25) == 0) {
_prefs.ui_auto_off_keep_msgs = atoi(&command[25]);
savePrefs();
sprintf(reply, "> now %d", _prefs.ui_auto_off_keep_msgs);
return true;
}
if (memcmp(command, "set ui.max_partial", 18) == 0) {
_prefs.ui_max_partial = atoi(&command[18]);
savePrefs();
sprintf(reply, "> now %d (applied at next screen wakeup)", _prefs.ui_max_partial);
return true;
}
if (memcmp(command, "set ui.nd_name", 14) == 0) {
_prefs.ui_nd_name = atoi(&command[14]);
savePrefs();
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;
}
if (memcmp(command, "get ui.auto_off_delay", 21) == 0) {
sprintf(reply, "> %d seconds", _prefs.ui_auto_off_delay);
return true;
}
if (memcmp(command, "get ui.backlight_delay", 22) == 0) {
if (_prefs.ui_backlight_delay >= 0)
sprintf(reply, "> %d seconds", _prefs.ui_backlight_delay);
else if (_prefs.ui_backlight_delay == -1)
sprintf(reply, "> always on (-1)");
else
sprintf(reply, "> disabled (<-1)");
return true;
}
if (memcmp(command, "get ui.backlight_on_keys", 24) == 0) {
sprintf(reply, "> %d", _prefs.ui_backlight_on_keys);
return true;
}
if (memcmp(command, "get ui.backlight_on_msgs", 24) == 0) {
sprintf(reply, "> %d", _prefs.ui_backlight_on_msgs);
return true;
}
if (memcmp(command, "get ui.auto_off_blank", 21) == 0) {
sprintf(reply, "> %d", _prefs.ui_auto_off_blank);
return true;
}
if (memcmp(command, "get ui.auto_off_keep_msgs", 25) == 0) {
sprintf(reply, "> %d", _prefs.ui_auto_off_keep_msgs);
return true;
}
if (memcmp(command, "get ui.max_partial", 18) == 0) {
sprintf(reply, "> %d", _prefs.ui_max_partial);
return true;
}
if (memcmp(command, "get ui.nd_name", 14) == 0) {
sprintf(reply, "> %d", _prefs.ui_nd_name);
return true;
}
#endif
return false; // not handled
}
+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
+93 -5
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 ""
@@ -58,6 +63,39 @@ public:
// use ssid from prefs, or fallback to ssid from build flags
const char* getWifiSSID() const { return wifi_ssid[0] ? wifi_ssid : WIFI_SSID; }
#endif
#ifdef DISPLAY_CLASS
#ifndef UI_SHOW_CLOCK
#define UI_SHOW_CLOCK 0
#endif
#ifndef AUTO_OFF_MILLIS
#define AUTO_OFF_MILLIS 15000
#endif
#ifndef EINK_MAX_PARTIAL_REFRESH
#define EINK_MAX_PARTIAL_REFRESH 0
#endif
uint8_t ui_show_clock = UI_SHOW_CLOCK;
uint32_t ui_auto_off_delay = AUTO_OFF_MILLIS / 1000;
int32_t ui_backlight_delay = 5;
#if defined(BACKLIGHT_BTN)
uint8_t ui_backlight_on_keys = 0;
#else
uint8_t ui_backlight_on_keys = 1;
#endif
uint8_t ui_backlight_on_msgs = 0;
#ifdef UI_SCREENOFF_BLANK
uint8_t ui_auto_off_blank = 1;
#else
uint8_t ui_auto_off_blank = 0;
#endif
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:
class RadioPrefs : public CommonRadioPrefs {
@@ -102,8 +140,8 @@ private:
void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); }
uint8_t getRxGain() const override { return _parent->rx_boosted_gain; }
void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); }
uint8_t getTxPower() const override { return _parent->tx_power_dbm; }
void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); }
int8_t getTxPower() const override { return _parent->tx_power_dbm; }
void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); }
float getRxDelay() const override { return _parent->rx_delay_base; }
void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); }
uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; }
@@ -123,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;
@@ -166,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) { }
@@ -189,6 +248,28 @@ private:
WiFiPrefs wifi;
#endif
#ifdef DISPLAY_CLASS
class UI_Prefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("show_clock", _parent->ui_show_clock);
def("auto_off", _parent->ui_auto_off_delay);
def("bl_dly", _parent->ui_backlight_delay);
def("bl_keys", _parent->ui_backlight_on_keys);
def("bl_msgs", _parent->ui_backlight_on_msgs);
def("max_partial", _parent->ui_max_partial);
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) {}
};
UI_Prefs ui;
#endif
protected:
void structure() override {
def("name", node_name, sizeof(node_name));
@@ -203,12 +284,18 @@ protected:
def("custom", custom);
#ifdef ENABLE_WIFI_INTERFACE
def("wifi", wifi);
#endif
#ifdef DISPLAY_CLASS
def("ui", ui);
#endif
}
public:
NodePrefs() : radio(this), gps(this), companion(this), custom(&radio)
#ifdef ENABLE_WIFI_INTERFACE
, wifi(this)
#endif
#ifdef DISPLAY_CLASS
, ui(this)
#endif
{
node_name[0] = 0;
@@ -220,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(); }
};
+172 -88
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,
@@ -122,7 +146,6 @@ class HomeScreen : public UIScreen {
uint32_t disc_node_req_tag = 0;
uint32_t disc_nodes_count = 0;
uint32_t discovery_req_time = 0;
bool discovery_disp_names = true; // by default desplay names if available (removes SNR_O)
#endif
void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) {
@@ -197,11 +220,10 @@ class HomeScreen : public UIScreen {
sensors_nb ++;
}
sensors_scroll = sensors_nb > UI_RECENT_LIST_SIZE;
#if AUTO_OFF_MILLIS > 0
next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec
#else
next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min
#endif
if (display.isEink()) // preserve eink displays
next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min
else
next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec
}
}
@@ -294,17 +316,17 @@ public:
sprintf(tmp, "MSG: %d", _task->getMsgCount());
display.drawTextCentered(display.width() / 2, 22, tmp);
#endif
#ifdef UI_SHOW_CLOCK
display.setTextSize(3);
uint32_t now = _rtc->getCurrentTime();
now += (int32_t)(_node_prefs->tz_offset * 3600);
DateTime dt (now);
sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute());
display.drawTextCentered(display.width() / 2, 60, tmp);
display.setTextSize(1);
sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year());
display.drawTextCentered(display.width() / 2, 80, tmp);
#endif
if (_node_prefs->ui_show_clock) {
display.setTextSize(3);
uint32_t now = _rtc->getCurrentTime();
now += (int32_t)(_node_prefs->tz_offset * 3600);
DateTime dt (now);
sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute());
display.drawTextCentered(display.width() / 2, 60, tmp);
display.setTextSize(1);
sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year());
display.drawTextCentered(display.width() / 2, 80, tmp);
}
#ifdef ENABLE_WIFI_INTERFACE
IPAddress ip = WiFi.localIP();
snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
@@ -314,21 +336,20 @@ public:
if (_task->hasConnection()) {
display.setColor(UIColor::warning_txt);
display.setTextSize(1);
#ifdef UI_SHOW_CLOCK
display.drawTextCentered(display.width() / 2, 110, "< Connected >");
#else
display.drawTextCentered(display.width() / 2, 43, "< Connected >");
#endif
if (_node_prefs->ui_show_clock)
display.drawTextCentered(display.width() / 2, 110, "< Connected >");
else
display.drawTextCentered(display.width() / 2, 43, "< Connected >");
} else if (the_mesh.getBLEPin() != 0) { // BT pin
display.setColor(UIColor::warning_txt);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
#ifdef UI_SHOW_CLOCK
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 110, tmp);
#else
display.setTextSize(2);
display.drawTextCentered(display.width() / 2, 43, tmp);
#endif
if (_node_prefs->ui_show_clock) {
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 110, tmp);
} else {
display.setTextSize(2);
display.drawTextCentered(display.width() / 2, 43, tmp);
}
}
} else if (_page == HomePage::RECENT) {
the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE);
@@ -395,16 +416,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) {
@@ -413,8 +446,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");
@@ -519,7 +551,7 @@ public:
for (int i = 0; i < count; i++, y += 11) {
char name[32];
auto a = &discovered[i];
if ((a->name[0] == 0) || !discovery_disp_names) {
if ((a->name[0] == 0) || !_node_prefs->ui_nd_name) {
mesh::Utils::toHex(name, a->pubkey_prefix, 4);
} else {
strncpy(name, a->name, 32);
@@ -600,7 +632,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
@@ -619,7 +651,7 @@ public:
return true;
}
if (c == KEY_SELECT && _page == HomePage::DISCOVERY) {
discovery_disp_names = !discovery_disp_names;
_node_prefs->ui_nd_name = !_node_prefs->ui_nd_name;
return true;
}
#endif
@@ -703,11 +735,7 @@ public:
display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg));
display.printWordWrap(filtered_msg, display.width());
#if AUTO_OFF_MILLIS==0 // probably e-ink
return 10000; // 10 s
#else
return 1000; // next render after 1000 ms
#endif
return display.isEink() ? 10000 : 1000; // 10 s for eink
}
bool handleInput(char c) override {
@@ -731,7 +759,6 @@ public:
void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs) {
_display = display;
_sensors = sensors;
_auto_off = millis() + AUTO_OFF_MILLIS;
#if defined(PIN_USER_BTN)
user_btn.begin();
@@ -739,11 +766,16 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no
#if defined(PIN_USER_BTN_ANA)
analog_btn.begin();
#endif
#if defined(BACKLIGHT_BTN)
backlight_btn.begin();
#endif
_node_prefs = node_prefs;
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000;
_backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000;
if (_display != NULL) {
_display->turnOn();
_display->turnOn(_node_prefs->ui_max_partial);
}
#ifdef PIN_BUZZER
@@ -809,11 +841,14 @@ void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t t
if (_display != NULL) {
if (!_display->isOn() && !hasConnection()) {
_display->turnOn();
_display->turnOn(_node_prefs->ui_max_partial);
}
if (_display->isOn()) {
_auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer
_next_refresh = 100; // trigger refresh
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer
_next_refresh = 100; // trigger refresh
if (_node_prefs->ui_backlight_on_msgs) {
_backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000;
}
}
}
@@ -829,10 +864,10 @@ void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_det
if (_display != NULL) {
if (!_display->isOn() && !hasConnection()) {
_display->turnOn();
_display->turnOn(_node_prefs->ui_max_partial);
}
if (_display->isOn()) {
_auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer
_next_refresh = 100; // trigger refresh
}
}
@@ -910,9 +945,9 @@ void UITask::shutdown(bool restart){
if (restart) {
_board->reboot();
} else {
display.forceFullRefresh();
display.clear();
display.endFrame();
if (_display->isEink()) {
_display->turnOff(true);
}
// Power off board including radio, display, GPS and components
_board->powerOff();
}
@@ -957,7 +992,7 @@ void UITask::loop() {
if (ev == BUTTON_EVENT_CLICK) {
c = checkDisplayOn(KEY_ENTER);
} else if (ev == BUTTON_EVENT_LONG_PRESS) {
display.turnOff();
display.turnOff(true);
} else if (ev == BUTTON_EVENT_DOUBLE_CLICK) {
c = handleDoubleClick(KEY_SELECT);
} else if (ev == BUTTON_EVENT_TRIPLE_CLICK) {
@@ -977,11 +1012,11 @@ void UITask::loop() {
#endif
#if defined(UI_HAS_ROTARY_INPUT)
RotaryInputEvent rotaryEv = rotary_input.poll();
if (c == 0 && _display != NULL && _display->isOn()) {
if (c == 0 && _display != NULL) {
if (rotaryEv == RotaryInputEvent::Next) {
c = KEY_NEXT;
c = checkDisplayOn(KEY_NEXT);
} else if (rotaryEv == RotaryInputEvent::Prev) {
c = KEY_PREV;
c = checkDisplayOn(KEY_PREV);
}
}
#endif
@@ -1000,27 +1035,59 @@ void UITask::loop() {
_analogue_pin_read_millis = millis();
}
#endif
#if defined(DISP_BACKLIGHT) || defined(EXP_PIN_BACKLIGHT)
#if defined(BACKLIGHT_BTN)
if (millis() > next_backlight_btn_check) {
bool touch_state = digitalRead(PIN_BUTTON2);
#if defined(DISP_BACKLIGHT)
digitalWrite(DISP_BACKLIGHT, !touch_state);
#elif defined(EXP_PIN_BACKLIGHT)
expander.digitalWrite(EXP_PIN_BACKLIGHT, !touch_state);
#endif
next_backlight_btn_check = millis() + 300;
if (backlight_btn.isPressed()) {
if (!_display->isOn()) {
_display->turnOn(_node_prefs->ui_max_partial);
_next_refresh = 0;
}
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer
_backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; // extend auto_off for backlight
}
next_backlight_btn_check = millis() + 100;
}
int bev = backlight_btn.check();
if (bev == BUTTON_EVENT_DOUBLE_CLICK) {
_display->forceFullRefresh();
} else if (bev == BUTTON_EVENT_TRIPLE_CLICK) {
_display->turnOff(true);
_backlight_off = 0;
}
#endif
bool backlight_state;
if (_node_prefs->ui_backlight_delay == -1) {
backlight_state = true;
} else if (_node_prefs->ui_backlight_delay < -1) {
backlight_state = false;
} else if (_node_prefs->ui_backlight_delay == 0) {
backlight_state = false;
#ifdef BACKLIGHT_BTN
backlight_state = backlight_btn.isPressed();
#endif
} else {
backlight_state = (millis() < _backlight_off);
}
#if defined(DISP_BACKLIGHT)
digitalWrite(DISP_BACKLIGHT, backlight_state);
#elif defined(EXP_PIN_BACKLIGHT)
expander.digitalWrite(EXP_PIN_BACKLIGHT, backlight_state);
#endif
#endif
if (c != 0 && curr) {
curr->handleInput(c);
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer
_next_refresh = 100; // trigger refresh
}
userLedHandler();
#ifdef PIN_BUZZER
if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet);
if (buzzer.isPlaying()) buzzer.loop();
#endif
@@ -1045,20 +1112,27 @@ void UITask::loop() {
}
_display->endFrame();
}
#if AUTO_OFF_MILLIS > 0
if (_node_prefs->ui_auto_off_delay > 0) {
#ifdef KEEP_DISPLAY_ON_USB
// Opt-in: refresh the auto-off deadline while externally powered, so the
// timer counts from the moment external power is removed. Off by default
// because OLED panels burn in quickly; only enable for LCD targets or
// where the display is replaceable.
if (board.isExternalPowered()) {
_auto_off = millis() + AUTO_OFF_MILLIS;
}
// Opt-in: refresh the auto-off deadline while externally powered, so the
// timer counts from the moment external power is removed. Off by default
// because OLED panels burn in quickly; only enable for LCD targets or
// where the display is replaceable.
if (board.isExternalPowered()) {
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000;
}
#endif
if (millis() > _auto_off) {
_display->turnOff();
if (millis() > _auto_off) {
if (_node_prefs->ui_auto_off_blank &&
!(_node_prefs->ui_auto_off_keep_msgs
&& curr == msg_preview)) {
// don't blank if messages are waiting
_display->turnOff(true);
} else {
_display->turnOff();
}
}
}
#endif
}
#ifdef PIN_VIBRATION
@@ -1090,10 +1164,13 @@ void UITask::loop() {
char UITask::checkDisplayOn(char c) {
if (_display != NULL) {
if (!_display->isOn()) {
_display->turnOn(); // turn display on and consume event
_display->turnOn(_node_prefs->ui_max_partial); // turn display on and consume event
c = 0;
}
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
_auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer
if (_node_prefs->ui_backlight_on_keys) {
_backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000;
}
_next_refresh = 0; // trigger refresh
}
return c;
@@ -1140,16 +1217,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;
}
@@ -1157,6 +1232,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
+3 -1
View File
@@ -61,7 +61,8 @@ class UITask : public AbstractUITask {
unsigned long _alert_expiry;
int _msgcount;
unsigned long ui_started_at, next_batt_chck;
int next_backlight_btn_check = 0;
unsigned long next_backlight_btn_check = 0;
unsigned long _backlight_off = 0;
#ifdef PIN_STATUS_LED
int led_state = 0;
int next_led_change = 0;
@@ -113,6 +114,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;
+4 -2
View File
@@ -485,6 +485,7 @@ void UITask::loop() {
userLedHandler();
#ifdef PIN_BUZZER
if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet);
if (buzzer.isPlaying()) buzzer.loop();
#endif
@@ -608,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;
}
}
+8 -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) {
@@ -691,6 +691,7 @@ void UITask::loop() {
userLedHandler();
#ifdef PIN_BUZZER
if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet);
if (buzzer.isPlaying()) buzzer.loop();
#endif
@@ -832,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;
}
+226
View File
@@ -1,5 +1,6 @@
#include "KissModem.h"
#include <CayenneLPP.h>
#include <stdio.h>
KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng,
mesh::Radio& radio, mesh::MainBoard& board, SensorManager& sensors)
@@ -20,8 +21,15 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r
_setTxPowerCallback = nullptr;
_getCurrentRssiCallback = nullptr;
_getStatsCallback = nullptr;
_setRxBoostedGainCallback = nullptr;
_getRxBoostedGainCallback = nullptr;
_pollRxCallback = nullptr;
_config = {0, 0, 0, 0, 0};
_signal_report_enabled = true;
_agc_reset_interval_sec = KISS_AGC_RESET_DEFAULT_SEC;
_next_agc_reset_ms = 0;
_fem_op_head = 0;
_fem_op_count = 0;
resetOutputQueue();
}
@@ -31,6 +39,9 @@ void KissModem::begin() {
_rx_active = false;
_has_pending_tx = false;
_tx_state = TX_IDLE;
_fem_op_head = 0;
_fem_op_count = 0;
_next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000;
resetOutputQueue();
}
@@ -240,10 +251,24 @@ void KissModem::loop() {
}
processTx();
processFemOps();
maybeResetAgc();
tryFlushFrames();
queuePendingBusyError();
}
void KissModem::maybeResetAgc() {
if (_agc_reset_interval_sec == 0) return;
// same guard as the RX path in main.cpp, so receive is restarted right after the reset
if (_tx_state != TX_IDLE || isHostOutputBackedUp()) return;
uint32_t now = millis();
if ((int32_t)(now - _next_agc_reset_ms) >= 0) {
_radio.resetAGC();
_next_agc_reset_ms = now + (uint32_t)_agc_reset_interval_sec * 1000;
}
}
void KissModem::processFrame() {
if (_rx_len < 1) return;
@@ -381,6 +406,27 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint
case HW_CMD_GET_SIGNAL_REPORT:
handleGetSignalReport();
break;
case HW_CMD_GET_CAPABILITIES:
handleGetCapabilities();
break;
case HW_CMD_SET_AGC_RESET_INTERVAL:
handleSetAgcResetInterval(data, len);
break;
case HW_CMD_GET_AGC_RESET_INTERVAL:
handleGetAgcResetInterval();
break;
case HW_CMD_SET_FEM_STATE:
handleSetFemState(data, len);
break;
case HW_CMD_GET_FEM_STATE:
handleGetFemState();
break;
case HW_CMD_SET_RX_BOOSTED_GAIN:
handleSetRxBoostedGain(data, len);
break;
case HW_CMD_GET_RX_BOOSTED_GAIN:
handleGetRxBoostedGain();
break;
default:
writeHardwareError(HW_ERR_UNKNOWN_CMD);
break;
@@ -732,3 +778,183 @@ void KissModem::handleGetSignalReport() {
uint8_t val = _signal_report_enabled ? 0x01 : 0x00;
writeHardwareFrame(HW_RESP(HW_CMD_GET_SIGNAL_REPORT), &val, 1);
}
void KissModem::handleGetCapabilities() {
uint32_t caps = HW_CAP_AGC_RESET;
uint8_t fem_caps, fem_values;
readFemState(&fem_caps, &fem_values);
if (fem_caps & HW_FEM_RX_GAIN) caps |= HW_CAP_FEM_RX_GAIN;
if (fem_caps & HW_FEM_TX_GAIN) caps |= HW_CAP_FEM_TX_GAIN;
if (_setRxBoostedGainCallback && _getRxBoostedGainCallback) caps |= HW_CAP_RX_BOOSTED_GAIN;
uint8_t buf[4] = { (uint8_t)caps, (uint8_t)(caps >> 8), (uint8_t)(caps >> 16), (uint8_t)(caps >> 24) };
writeHardwareFrame(HW_RESP(HW_CMD_GET_CAPABILITIES), buf, 4);
}
void KissModem::handleSetAgcResetInterval(const uint8_t* data, uint16_t len) {
if (len < 2) {
writeHardwareError(HW_ERR_INVALID_LENGTH);
return;
}
uint16_t secs = (uint16_t)(data[0] | (data[1] << 8));
if (secs > KISS_AGC_RESET_MAX_SEC) {
writeHardwareError(HW_ERR_INVALID_PARAM);
return;
}
_agc_reset_interval_sec = secs - (secs % KISS_AGC_RESET_STEP_SEC);
_next_agc_reset_ms = millis() + (uint32_t)_agc_reset_interval_sec * 1000;
handleGetAgcResetInterval();
}
void KissModem::handleGetAgcResetInterval() {
uint8_t buf[2] = { (uint8_t)_agc_reset_interval_sec, (uint8_t)(_agc_reset_interval_sec >> 8) };
writeHardwareFrame(HW_RESP(HW_CMD_GET_AGC_RESET_INTERVAL), buf, 2);
}
// FEM gain is reached through the board's own "radio.fem.*" CLI commands, the same ones users run.
static const char* femGainName(uint8_t bit) {
return bit == HW_FEM_RX_GAIN ? "rxgain" : "txgain";
}
// Anything but an exact "> on" / "> off" (not handled, "Error: ...", unexpected text) means unsupported.
bool KissModem::queryFemGain(uint8_t bit, bool* enabled) {
char cmd[32];
char reply[KISS_BOARD_REPLY_SIZE] = { 0 };
snprintf(cmd, sizeof(cmd), "get radio.fem.%s", femGainName(bit));
if (!_board.handleCommand(cmd, 0, reply)) return false;
if (strcmp(reply, "> on") == 0) {
*enabled = true;
} else if (strcmp(reply, "> off") == 0) {
*enabled = false;
} else {
return false;
}
return true;
}
// Success is judged by reading the state back, not by the wording of the set reply.
bool KissModem::setFemGain(uint8_t bit, bool enable) {
char cmd[32];
char reply[KISS_BOARD_REPLY_SIZE] = { 0 };
snprintf(cmd, sizeof(cmd), "set radio.fem.%s %s", femGainName(bit), enable ? "on" : "off");
_board.handleCommand(cmd, 0, reply);
bool now;
return queryFemGain(bit, &now) && now == enable;
}
void KissModem::readFemState(uint8_t* caps, uint8_t* values) {
*caps = 0;
*values = 0;
const uint8_t bits[] = { HW_FEM_RX_GAIN, HW_FEM_TX_GAIN };
for (uint8_t bit : bits) {
bool enabled;
if (queryFemGain(bit, &enabled)) {
*caps |= bit;
if (enabled) *values |= bit;
}
}
}
bool KissModem::queueFemReply() {
uint8_t buf[2];
readFemState(&buf[0], &buf[1]);
return queueHardwareFrame(HW_RESP(HW_CMD_GET_FEM_STATE), buf, 2, false);
}
// The reply always carries the read-back state, so a bit that failed to apply shows its real value.
void KissModem::applyFemState(uint8_t apply_mask, uint8_t value_mask) {
if (apply_mask & HW_FEM_RX_GAIN) {
setFemGain(HW_FEM_RX_GAIN, (value_mask & HW_FEM_RX_GAIN) != 0);
}
if (apply_mask & HW_FEM_TX_GAIN) {
setFemGain(HW_FEM_TX_GAIN, (value_mask & HW_FEM_TX_GAIN) != 0);
}
}
void KissModem::enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask) {
if (_fem_op_count >= KISS_FEM_OP_QUEUE_DEPTH) {
writeHardwareError(HW_ERR_TX_BUSY); // too many FEM requests waiting
return;
}
FemOp& op = _fem_ops[(_fem_op_head + _fem_op_count) % KISS_FEM_OP_QUEUE_DEPTH];
op.kind = kind;
op.apply_mask = apply_mask;
op.value_mask = value_mask;
op.applied = false;
_fem_op_count++;
processFemOps();
}
// Every FEM reply goes out in request order. A Set waits until TxDone is queued, since board
// setters drive FEM pins directly; each reply is retained until there is room to queue it.
void KissModem::processFemOps() {
while (_fem_op_count > 0) {
FemOp& op = _fem_ops[_fem_op_head];
if (op.kind == FEM_OP_ERROR) {
if (!queueHardwareFrame(HW_RESP_ERROR, &op.value_mask, 1, false)) return;
} else {
if (op.kind == FEM_OP_SET && !op.applied) {
if (_tx_state == TX_SENDING || _tx_state == TX_DONE_PENDING) return;
uint8_t caps, values;
readFemState(&caps, &values);
if (op.apply_mask & ~caps) {
// all-or-nothing: any bit the board cannot control rejects the whole request
op.kind = FEM_OP_ERROR;
op.value_mask = HW_ERR_UNSUPPORTED;
continue;
}
applyFemState(op.apply_mask, op.value_mask);
op.applied = true;
}
if (!queueFemReply()) return;
}
_fem_op_head = (uint8_t)((_fem_op_head + 1) % KISS_FEM_OP_QUEUE_DEPTH);
_fem_op_count--;
}
}
void KissModem::handleSetFemState(const uint8_t* data, uint16_t len) {
if (len < 2) {
enqueueFemOp(FEM_OP_ERROR, 0, HW_ERR_INVALID_LENGTH);
return;
}
enqueueFemOp(FEM_OP_SET, data[0], data[1]);
}
void KissModem::handleGetFemState() {
enqueueFemOp(FEM_OP_GET, 0, 0);
}
void KissModem::handleSetRxBoostedGain(const uint8_t* data, uint16_t len) {
if (len < 1) {
writeHardwareError(HW_ERR_INVALID_LENGTH);
return;
}
if (!_setRxBoostedGainCallback || !_getRxBoostedGainCallback) {
writeHardwareError(HW_ERR_UNSUPPORTED);
return;
}
// some drivers (LR2021) drop to standby to apply the gain, which would abort a TX and
// discard a completed RX packet; so never during TX, and only after draining RX
if (_tx_state == TX_SENDING || isHostOutputBackedUp()) {
writeHardwareError(HW_ERR_TX_BUSY);
return;
}
if (_pollRxCallback) _pollRxCallback();
tryFlushFrames();
if (_tx_frame_count >= KISS_TX_FRAME_QUEUE_DEPTH) {
writeHardwareError(HW_ERR_TX_BUSY); // no room left for the reply; change nothing
return;
}
// always reply with the state read back, so a failed or partial write is never misreported
_setRxBoostedGainCallback(data[0] != 0x00);
handleGetRxBoostedGain();
}
void KissModem::handleGetRxBoostedGain() {
if (!_getRxBoostedGainCallback) {
writeHardwareError(HW_ERR_UNSUPPORTED);
return;
}
uint8_t val = _getRxBoostedGainCallback() ? 0x01 : 0x00;
writeHardwareFrame(HW_RESP(HW_CMD_GET_RX_BOOSTED_GAIN), &val, 1);
}
+75 -1
View File
@@ -62,6 +62,13 @@
#define HW_CMD_REBOOT 0x18
#define HW_CMD_SET_SIGNAL_REPORT 0x19
#define HW_CMD_GET_SIGNAL_REPORT 0x1A
#define HW_CMD_GET_CAPABILITIES 0x1B
#define HW_CMD_SET_AGC_RESET_INTERVAL 0x1C
#define HW_CMD_GET_AGC_RESET_INTERVAL 0x1D
#define HW_CMD_SET_FEM_STATE 0x1E
#define HW_CMD_GET_FEM_STATE 0x1F
#define HW_CMD_SET_RX_BOOSTED_GAIN 0x20
#define HW_CMD_GET_RX_BOOSTED_GAIN 0x21
/* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */
#define HW_RESP(cmd) ((cmd) | 0x80)
@@ -81,13 +88,37 @@
#define HW_ERR_UNKNOWN_CMD 0x05
#define HW_ERR_ENCRYPT_FAILED 0x06
#define HW_ERR_TX_BUSY 0x07
#define HW_ERR_UNSUPPORTED 0x08
#define KISS_FIRMWARE_VERSION 1
/* GetCapabilities feature bits */
#define HW_CAP_AGC_RESET (1UL << 0)
#define HW_CAP_FEM_RX_GAIN (1UL << 1)
#define HW_CAP_FEM_TX_GAIN (1UL << 2)
#define HW_CAP_RX_BOOSTED_GAIN (1UL << 3)
/* SetFemState / GetFemState mask bits */
#define HW_FEM_RX_GAIN (1 << 0)
#define HW_FEM_TX_GAIN (1 << 1)
/* Matches the CLI reply buffer boards write into from handleCommand() */
#define KISS_BOARD_REPLY_SIZE 160
/* FEM requests are answered strictly in arrival order; this many may wait (e.g. during a TX) */
#define KISS_FEM_OP_QUEUE_DEPTH 4
#define KISS_AGC_RESET_DEFAULT_SEC 32 // a multiple of the 4 s step, so hosts can set it back
#define KISS_AGC_RESET_MAX_SEC 1020
#define KISS_AGC_RESET_STEP_SEC 4
#define KISS_FIRMWARE_VERSION 2
typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr);
typedef void (*SetTxPowerCallback)(uint8_t power);
typedef float (*GetCurrentRssiCallback)();
typedef void (*GetStatsCallback)(uint32_t* rx, uint32_t* tx, uint32_t* errors);
typedef bool (*SetRxBoostedGainCallback)(bool enable);
typedef bool (*GetRxBoostedGainCallback)();
typedef void (*PollRxCallback)();
struct RadioConfig {
uint32_t freq_hz;
@@ -97,6 +128,19 @@ struct RadioConfig {
uint8_t tx_power;
};
enum FemOpKind : uint8_t {
FEM_OP_SET,
FEM_OP_GET,
FEM_OP_ERROR
};
struct FemOp {
FemOpKind kind;
uint8_t apply_mask; // FEM_OP_SET
uint8_t value_mask; // FEM_OP_SET; error code for FEM_OP_ERROR
bool applied; // FEM_OP_SET: hardware changed, reply still to be queued
};
enum TxState {
TX_IDLE,
TX_WAIT_CLEAR,
@@ -136,9 +180,17 @@ class KissModem {
SetTxPowerCallback _setTxPowerCallback;
GetCurrentRssiCallback _getCurrentRssiCallback;
GetStatsCallback _getStatsCallback;
SetRxBoostedGainCallback _setRxBoostedGainCallback;
GetRxBoostedGainCallback _getRxBoostedGainCallback;
PollRxCallback _pollRxCallback;
RadioConfig _config;
bool _signal_report_enabled;
uint16_t _agc_reset_interval_sec;
uint32_t _next_agc_reset_ms;
FemOp _fem_ops[KISS_FEM_OP_QUEUE_DEPTH];
uint8_t _fem_op_head;
uint8_t _fem_op_count;
uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE];
uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH];
uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH];
@@ -165,6 +217,14 @@ class KissModem {
void processFrame();
void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len);
void processTx();
void maybeResetAgc();
bool queryFemGain(uint8_t bit, bool* enabled);
bool setFemGain(uint8_t bit, bool enable);
void readFemState(uint8_t* caps, uint8_t* values);
bool queueFemReply();
void applyFemState(uint8_t apply_mask, uint8_t value_mask);
void enqueueFemOp(FemOpKind kind, uint8_t apply_mask, uint8_t value_mask);
void processFemOps();
void handleGetIdentity();
void handleGetRandom(const uint8_t* data, uint16_t len);
@@ -192,6 +252,13 @@ class KissModem {
void handleGetDeviceName();
void handleSetSignalReport(const uint8_t* data, uint16_t len);
void handleGetSignalReport();
void handleGetCapabilities();
void handleSetAgcResetInterval(const uint8_t* data, uint16_t len);
void handleGetAgcResetInterval();
void handleSetFemState(const uint8_t* data, uint16_t len);
void handleGetFemState();
void handleSetRxBoostedGain(const uint8_t* data, uint16_t len);
void handleGetRxBoostedGain();
public:
KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& rng,
@@ -204,6 +271,13 @@ public:
void setTxPowerCallback(SetTxPowerCallback cb) { _setTxPowerCallback = cb; }
void setGetCurrentRssiCallback(GetCurrentRssiCallback cb) { _getCurrentRssiCallback = cb; }
void setGetStatsCallback(GetStatsCallback cb) { _getStatsCallback = cb; }
// Only register these when the radio supports boosted RX gain; they define the capability.
// Delivers any completed RX packet to the host; called before settings that restart the receiver.
void setPollRxCallback(PollRxCallback cb) { _pollRxCallback = cb; }
void setRxBoostedGainCallbacks(SetRxBoostedGainCallback set_cb, GetRxBoostedGainCallback get_cb) {
_setRxBoostedGainCallback = set_cb;
_getRxBoostedGainCallback = get_cb;
}
void onPacketReceived(int8_t snr, int8_t rssi, const uint8_t* packet, uint16_t len);
bool isTxBusy() const { return _tx_state != TX_IDLE; }
+26 -16
View File
@@ -19,7 +19,6 @@
#endif
#define NOISE_FLOOR_CALIB_INTERVAL_MS 2000
#define AGC_RESET_INTERVAL_MS 30000
#define USB_TX_TIMEOUT_MS 50
#define USB_TX_BUFFER_SIZE 1024
@@ -27,7 +26,6 @@ StdRNG rng;
mesh::LocalIdentity identity;
KissModem* modem;
static uint32_t next_noise_floor_calib_ms = 0;
static uint32_t next_agc_reset_ms = 0;
void halt() {
while (1) ;
@@ -75,6 +73,24 @@ void onGetStats(uint32_t* rx, uint32_t* tx, uint32_t* errors) {
*errors = radio_driver.getPacketsRecvErrors();
}
void pollRadioRx() {
uint8_t rx_buf[256];
int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf));
if (rx_len > 0) {
int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4);
int8_t rssi = (int8_t)radio_driver.getLastRSSI();
modem->onPacketReceived(snr, rssi, rx_buf, rx_len);
}
}
bool onSetRxBoostedGain(bool enable) {
return radio_driver.setRxBoostedGainMode(enable);
}
bool onGetRxBoostedGain() {
return radio_driver.getRxBoostedGainMode();
}
void setup() {
board.begin();
@@ -115,7 +131,10 @@ void setup() {
delay(100);
#if defined(ESP32) && defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS);
#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE
// HWCDC only; TinyUSB's USBCDC TX buffer is fixed at build time
Serial.setTxBufferSize(USB_TX_BUFFER_SIZE);
#endif
#endif
modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors);
#endif
@@ -124,6 +143,10 @@ void setup() {
modem->setTxPowerCallback(onSetTxPower);
modem->setGetCurrentRssiCallback(onGetCurrentRssi);
modem->setGetStatsCallback(onGetStats);
modem->setPollRxCallback(pollRadioRx);
if (radio_driver.supportsRxBoostedGain()) {
modem->setRxBoostedGainCallbacks(onSetRxBoostedGain, onGetRxBoostedGain);
}
modem->begin();
board.onBootComplete();
@@ -133,20 +156,7 @@ void loop() {
modem->loop();
if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) {
if (!modem->isTxBusy()) {
if ((uint32_t)(millis() - next_agc_reset_ms) >= AGC_RESET_INTERVAL_MS) {
radio_driver.resetAGC();
next_agc_reset_ms = millis();
}
}
uint8_t rx_buf[256];
int rx_len = radio_driver.recvRaw(rx_buf, sizeof(rx_buf));
if (rx_len > 0) {
int8_t snr = (int8_t)(radio_driver.getLastSNR() * 4);
int8_t rssi = (int8_t)radio_driver.getLastRSSI();
modem->onPacketReceived(snr, rssi, rx_buf, rx_len);
}
pollRadioRx();
}
board.loop();
+2 -2
View File
@@ -229,8 +229,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
stats.n_recv_direct = getNumRecvDirect();
stats.err_events = _err_flags;
stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
stats.n_direct_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF);
stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF);
stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
stats.n_recv_errors = radio_driver.getPacketsRecvErrors();
memcpy(&reply_data[4], &stats, sizeof(stats));
+8 -1
View File
@@ -159,7 +159,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
+5 -4
View File
@@ -1,4 +1,5 @@
#include "MyMesh.h"
#include <algorithm>
#define REPLY_DELAY_MILLIS 1500
#define PUSH_NOTIFY_DELAY_MILLIS 2000
@@ -139,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");
@@ -170,8 +171,8 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
stats.n_recv_direct = getNumRecvDirect();
stats.err_events = _err_flags;
stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
stats.n_direct_dups = ((SimpleMeshTables *)getTables())->getNumDirectDups();
stats.n_flood_dups = ((SimpleMeshTables *)getTables())->getNumFloodDups();
stats.n_direct_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF);
stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF);
stats.n_posted = _num_posted;
stats.n_post_push = _num_post_pushes;
@@ -781,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, "");
+6 -1
View File
@@ -173,7 +173,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
};
+3 -3
View File
@@ -19,8 +19,7 @@ monitor_speed = 115200
lib_deps =
SPI
Wire
;jgromes/RadioLib @ ^7.7.1
https://github.com/jgromes/RadioLib.git#6d8934836678d8894e3d556550475b37dce3e2b6
jgromes/RadioLib @ 7.8.1
rweather/Crypto @ ^0.4.0
adafruit/RTClib @ ^2.1.3
melopero/Melopero RV3028 @ ^1.1.0
@@ -102,7 +101,8 @@ lib_deps =
extends = arduino_base
upload_protocol = picotool
board_build.core = earlephilhower
platform = https://github.com/maxgerhardt/platform-raspberrypi.git ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9
; commit points to framework-arduinopico 5.6.0
platform = https://github.com/maxgerhardt/platform-raspberrypi.git#4e22a0dcdd94eead72fdf56ea59a3d7c8aa2f379
build_flags = ${arduino_base.build_flags}
-D RP2040_PLATFORM
+14 -1
View File
@@ -128,6 +128,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
ContactInfo* from = NULL;
for (int i = 0; i < num_contacts; i++) {
if (contacts[i].isEmptySlot()) continue;
if (id.matches(contacts[i].id)) { // is from one of our contacts
from = &contacts[i];
if (timestamp <= from->last_advert_timestamp) { // check for replay attacks!!
@@ -203,6 +204,11 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
int BaseChatMesh::searchPeersByHash(const uint8_t* hash) {
int n = 0;
for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) {
// Skip empty/unconfigured anon slots. An empty slot has an all-zero pub_key
// (an order-4 Edwards25519 point whose clamped X25519 key exchange yields an
// all-zero shared secret for any private key) and would otherwise match
// src_hash == 0x00 as a null-key peer sink while consuming search slots.
if (contacts[i].isEmptySlot()) continue;
if (contacts[i].id.isHashMatch(hash)) {
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
}
@@ -516,6 +522,11 @@ int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timest
}
bool BaseChatMesh::sendGroupMessage(uint32_t timestamp, mesh::GroupChannel& channel, const char* sender_name, const char* text, int text_len) {
if (text_len < 0) { // memcpy() below would read this as a size_t, so clamping cannot catch it
MESH_DEBUG_PRINTLN("sendGroupMessage: invalid negative text_len=%d", text_len);
return false;
}
uint8_t temp[5+MAX_TEXT_LEN+32];
memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
temp[4] = 0; // TXT_TYPE_PLAIN
@@ -866,6 +877,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) {
int len = strlen(name_prefix);
for (int i = 0; i < num_contacts; i++) {
auto c = &contacts[i];
if (c->isEmptySlot() || c->name[0] == 0) continue;
if (memcmp(c->name, name_prefix, len) == 0) return c;
}
return NULL; // not found
@@ -874,6 +886,7 @@ ContactInfo* BaseChatMesh::searchContactsByPrefix(const char* name_prefix) {
ContactInfo* BaseChatMesh::lookupContactByPubKey(const uint8_t* pub_key, int prefix_len) {
for (int i = 0; i < num_contacts; i++) {
auto c = &contacts[i];
if (c->isEmptySlot()) continue;
if (memcmp(c->id.pub_key, pub_key, prefix_len) == 0) return c;
}
return NULL; // not found
@@ -891,7 +904,7 @@ bool BaseChatMesh::addContact(const ContactInfo& contact) {
bool BaseChatMesh::removeContact(ContactInfo& contact) {
int idx = 0;
while (idx < num_contacts && !contacts[idx].id.matches(contact.id)) {
while (idx < num_contacts && (contacts[idx].isEmptySlot() || !contacts[idx].id.matches(contact.id))) {
idx++;
}
if (idx >= num_contacts) return false; // not found
+27 -68
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());
@@ -326,67 +328,40 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
if (start >= end) {
strcpy(reply, "no custom var");
} else {
const int reply_max = 160; // callers pass a 160-byte reply buffer
const int next_reserve = 16; // room for "... next:NNN"
sprintf(dp, "%d vars\n", end);
dp = strchr(dp, 0);
int i;
for (i = start; i < end && (dp-reply < 134); i++) {
sprintf(dp, "%s=%s\n",
_sensors->getSettingName(i),
_sensors->getSettingValue(i));
for (i = start; i < end; i++) {
const char* name = _sensors->getSettingName(i);
const char* value = _sensors->getSettingValue(i);
if (name == NULL) name = "?";
if (value == NULL) value = "";
int room = reply_max - next_reserve - (int)(dp - reply);
int need = snprintf(NULL, 0, "%s=%s\n", name, value);
if (need >= room && i > start) break; // continue on the next page
snprintf(dp, room, "%s=%s\n", name, value); // a single oversized entry is truncated
dp = strchr(dp, 0);
if (need >= room) { i++; break; }
}
if (i < end) {
sprintf(dp, "... next:%d", i);
} else {
snprintf(dp, reply_max - (int)(dp - reply), "... next:%d", i);
} else if (dp > reply && *(dp-1) == '\n') {
*(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) {
@@ -400,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) {
@@ -541,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) {
+35 -5
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;
@@ -115,8 +119,8 @@ private:
void setIntThresh(uint8_t t) override { _parent->interference_threshold = t; markDirty(); }
uint8_t getRxGain() const override { return _parent->rx_boosted_gain; }
void setRxGain(uint8_t g) override { _parent->rx_boosted_gain = g; markDirty(); }
uint8_t getTxPower() const override { return _parent->tx_power_dbm; }
void setTxPower(uint8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); }
int8_t getTxPower() const override { return _parent->tx_power_dbm; }
void setTxPower(int8_t dbm) override { _parent->tx_power_dbm = dbm; markDirty(); }
float getRxDelay() const override { return _parent->rx_delay_base; }
void setRxDelay(float d) override { _parent->rx_delay_base = d; markDirty(); }
uint16_t getAgcResetInt() const override { return _parent->agc_reset_interval * 4; }
@@ -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);
};
+18 -2
View File
@@ -2,6 +2,22 @@
#include "TxtDataHelpers.h"
#include "Utils.h"
#include "target.h"
#include <ctype.h>
namespace {
// strtof() and atof() also read "nan" and "inf". A NaN cannot be refused by a
// range check: no ordered comparison is true for it, and under -ffast-math,
// which nRF52 builds use, the compiler may assume it never occurs and fold any
// test on the parsed value away. So the text is checked before it is parsed:
// after optional white space and sign, a number starts with a digit or a '.'.
bool looksLikeANumber(const char* s) {
while (isspace((unsigned char)*s)) s++;
if (*s == '+' || *s == '-') s++;
return isdigit((unsigned char)*s) || *s == '.';
}
} // namespace
bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) {
if (strcmp(key, "fem_rxgain") == 0) {
@@ -69,7 +85,7 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
if (memcmp(command, "set af ", 7) == 0) {
char* end;
float af = strtof(&command[7], &end);
if (end == &command[7] || af < 0 || af > 9) {
if (end == &command[7] || !looksLikeANumber(&command[7]) || af < 0 || af > 9) {
strcpy(reply, "ERROR: af must be 0-9");
} else {
setAirtimeFactor(af);
@@ -87,7 +103,7 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
}
if (memcmp(command, "set dutycycle ", 14) == 0) {
float dc = atof(&command[14]);
if (dc < 1 || dc > 100) {
if (!looksLikeANumber(&command[14]) || dc < 1 || dc > 100) {
strcpy(reply, "ERROR: dutycycle must be 1-100");
} else {
setAirtimeFactor((100.0f / dc) - 1.0f);
+2 -2
View File
@@ -35,8 +35,8 @@ public:
virtual uint8_t getRxGain() const = 0;
virtual void setRxGain(uint8_t g) = 0;
virtual uint8_t getTxPower() const = 0;
virtual void setTxPower(uint8_t dbm) = 0;
virtual int8_t getTxPower() const = 0;
virtual void setTxPower(int8_t dbm) = 0;
virtual float getRxDelay() const = 0;
virtual void setRxDelay(float d) = 0;
+6
View File
@@ -31,6 +31,12 @@ struct ContactInfo {
bool isTelemLocAllowed() const { return flags & 0x04; }
bool isTelemEnvAllowed() const { return flags & 0x08; }
bool isRemoteCLIAllowed() const { return flags & 0x10; }
bool isEmptySlot() const {
for (int i = 0; i < PUB_KEY_SIZE; i++) {
if (id.pub_key[i] != 0) return false;
}
return true;
}
private:
mutable uint8_t shared_secret[PUB_KEY_SIZE];
+4
View File
@@ -3,6 +3,10 @@
#include "ESP32Board.h"
#include <target.h>
// The RTC backup of ESP32RTCClock, declared in ESP32Board.h.
RTC_NOINIT_ATTR uint32_t _rtc_backup_time;
RTC_NOINIT_ATTR uint32_t _rtc_backup_magic;
#if defined(ADMIN_PASSWORD) && !defined(DISABLE_WIFI_OTA) // Repeater or Room Server only
#include <WiFi.h>
#include <AsyncTCP.h>
+5 -2
View File
@@ -200,8 +200,11 @@ public:
}
};
static RTC_NOINIT_ATTR uint32_t _rtc_backup_time;
static RTC_NOINIT_ATTR uint32_t _rtc_backup_magic;
// The time ESP32RTCClock restores after a reset, in RTC memory that a reset does
// not clear. Defined once, in ESP32Board.cpp: the inline members below run in
// every translation unit that uses them and must all see the same backup.
extern uint32_t _rtc_backup_time;
extern uint32_t _rtc_backup_magic;
#define RTC_BACKUP_MAGIC 0xAA55CC33
#define RTC_TIME_MIN 1772323200 // 1 Mar 2026
+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);
}
}
};
+1 -1
View File
@@ -188,7 +188,7 @@ int RegionMap::getTransportKeysFor(const RegionEntry& src, TransportKey dest[],
}
RegionEntry* RegionMap::findMatch(mesh::Packet* packet, uint8_t mask) {
if (packet->transport_codes[0] == 0) return &wildcard;
if (packet->transport_codes[0] == 0) return (wildcard.flags & mask) == 0 ? &wildcard : NULL;
for (int i = 0; i < num_regions; i++) {
auto region = &regions[i];
if ((region->flags & mask) == 0) { // does region allow this? (per 'mask' param)
+1
View File
@@ -17,6 +17,7 @@ inline bool isFloodHopLimitExceeded(const Packet* packet, uint8_t flood_max,
uint8_t hops = packet->getPathHashCount();
if (hops >= flood_max) return true;
if (packet->getRouteType() == ROUTE_TYPE_FLOOD && hops >= flood_max_unscoped) return true;
if (packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD && packet->transport_codes[0] == 0 && hops >= flood_max_unscoped) return true; // scope 0, treat as unscoped
if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && hops >= flood_max_advert) return true;
return false;
}
+7 -1
View File
@@ -20,6 +20,11 @@ public:
}
bool lastRxHadCRC() override {
bool crc = true;
((CustomLLCC68 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomLLCC68 *)_radio)->isReceiving();
}
@@ -35,8 +40,9 @@ public:
}
uint8_t getSpreadingFactor() const override { return ((CustomLLCC68 *)_radio)->spreadingFactor; }
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); }
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
return ((CustomLLCC68 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
+3 -2
View File
@@ -39,8 +39,9 @@ class CustomLR1110 : public LR1110 {
float getFreqMHz() const { return freqMHz; }
int16_t setRxBoostedGainMode(bool en) {
_rx_boosted = en;
return LR1110::setRxBoostedGainMode(en);
int16_t status = LR1110::setRxBoostedGainMode(en);
if (status == RADIOLIB_ERR_NONE) _rx_boosted = en;
return status;
}
bool getRxBoostedGainMode() const { return _rx_boosted; }
@@ -19,6 +19,11 @@ public:
((CustomLR1110 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool lastRxHadCRC() override {
bool crc = true;
((CustomLR1110 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomLR1110 *)_radio)->isReceiving();
}
@@ -43,6 +48,7 @@ public:
uint8_t getSpreadingFactor() const override { return ((CustomLR1110 *)_radio)->getSpreadingFactor(); }
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
return ((CustomLR1110 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
+3 -2
View File
@@ -68,8 +68,9 @@ class CustomLR1121 : public LR1121 {
float getFreqMHz() const { return freqMHz; }
int16_t setRxBoostedGainMode(bool en) {
_rx_boosted = en;
return LR1121::setRxBoostedGainMode(en);
int16_t status = LR1121::setRxBoostedGainMode(en);
if (status == RADIOLIB_ERR_NONE) _rx_boosted = en;
return status;
}
bool getRxBoostedGainMode() const { return _rx_boosted; }
@@ -20,6 +20,11 @@ public:
}
void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1121 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); }
bool lastRxHadCRC() override {
bool crc = true;
((CustomLR1121 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomLR1121 *)_radio)->isReceiving();
}
@@ -44,6 +49,7 @@ public:
uint8_t getSpreadingFactor() const override { return ((CustomLR1121 *)_radio)->getSpreadingFactor(); }
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
return ((CustomLR1121 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
+18 -2
View File
@@ -8,7 +8,9 @@ class CustomLR2021 : public LR2021 {
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
bool _rx_boosted = false;
// last applied gain level per RX path, mirroring RadioLib's gainModeLf/gainModeHf defaults
uint8_t _rx_gain_lf = RADIOLIB_LR2021_RX_BOOST_LF;
uint8_t _rx_gain_hf = RADIOLIB_LR2021_RX_BOOST_HF;
public:
CustomLR2021(Module *mod) : LR2021(mod) { irqDioNum = LR2021_IRQ_DIO; }
@@ -68,7 +70,21 @@ class CustomLR2021 : public LR2021 {
float getFreqMHz() const { return freqMHz; }
bool getRxBoostedGainMode() const { return _rx_boosted; }
bool isHighFreqPath() const { return freqMHz > RADIOLIB_LR2021_LF_CUTOFF_FREQ; }
int16_t setRxBoostedGainMode(uint8_t level) {
uint8_t& applied = isHighFreqPath() ? _rx_gain_hf : _rx_gain_lf;
int16_t status = LR2021::setRxBoostedGainMode(level);
if (status == RADIOLIB_ERR_NONE) {
applied = level;
} else {
// RadioLib caches the level before sending it; restore it so the next startReceive keeps the old gain
LR2021::setRxBoostedGainMode(applied);
}
return status;
}
bool getRxBoostedGainMode() const { return (isHighFreqPath() ? _rx_gain_hf : _rx_gain_lf) != 0; }
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags
+21 -7
View File
@@ -16,15 +16,23 @@ public:
CustomLR2021Wrapper(CustomLR2021& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
((CustomLR2021 *)_radio)->setFrequency(freq);
((CustomLR2021 *)_radio)->setSpreadingFactor(sf);
((CustomLR2021 *)_radio)->setBandwidth(bw);
((CustomLR2021 *)_radio)->setCodingRate(cr);
auto r = (CustomLR2021 *)_radio;
// LR2021 only accepts RF/modulation config commands while in STANDBY mode.
// Re-configuring while in continuous RX gets silently rejected (-706),
// which broke hot frequency changes over BLE.
int16_t status = r->standby();
if (status != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: standby() -> %d", status); }
if ((status = r->setFrequency(freq)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setFrequency() -> %d", status); }
if ((status = r->setSpreadingFactor(sf)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setSpreadingFactor() -> %d", status); }
if ((status = r->setBandwidth(bw)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setBandwidth() -> %d", status); }
if ((status = r->setCodingRate(cr)) != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: setCodingRate() -> %d", status); }
updatePreamble(sf);
applySideDetectorConfig();
// internal idle() sets STATE_IDLE, which triggers a startReceive() on the next loop
status = applySideDetectorConfig();
if (status != RADIOLIB_ERR_NONE) { MESH_DEBUG_PRINTLN("CustomLR2021Wrapper: applySideDetectorConfig() -> %d", status); }
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomLR2021 *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomLR2021 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
r->setPreambleMillis(pm.preambleMillis); // pure in-memory setters, no standby needed
r->setMaxPayloadMillis(pm.payloadMillis);
}
@@ -73,6 +81,11 @@ public:
return tSym;
}
bool lastRxHadCRC() override {
bool crc = true;
((CustomLR2021 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomLR2021 *)_radio)->isReceiving();
}
@@ -93,6 +106,7 @@ public:
uint8_t getSpreadingFactor() const override { return ((CustomLR2021 *)_radio)->getSpreadingFactor(); }
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
((CustomLR2021 *)_radio)->standby(); // LR2021 must be in standby to accept setRxBoostedGainMode
int16_t status = ((CustomLR2021 *)_radio)->setRxBoostedGainMode(en ? LR2021_RX_BOOST_LEVEL: 0);
@@ -20,6 +20,11 @@ public:
((CustomSTM32WLx *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool lastRxHadCRC() override {
bool crc = true;
((CustomSTM32WLx *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomSTM32WLx *)_radio)->isReceiving();
}
@@ -23,6 +23,11 @@ public:
((CustomSX1262 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool lastRxHadCRC() override {
bool crc = true;
((CustomSX1262 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomSX1262 *)_radio)->isReceiving();
}
@@ -41,6 +46,7 @@ public:
((CustomSX1262 *)_radio)->sleep(false);
}
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
@@ -23,6 +23,11 @@ public:
((CustomSX1268 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool lastRxHadCRC() override {
bool crc = true;
((CustomSX1268 *)_radio)->getLoRaRxHeaderInfo(NULL, &crc);
return crc;
}
bool isReceivingPacket() override {
return ((CustomSX1268 *)_radio)->isReceiving();
}
@@ -38,6 +43,7 @@ public:
}
uint8_t getSpreadingFactor() const override { return ((CustomSX1268 *)_radio)->spreadingFactor; }
bool supportsRxBoostedGain() const override { return true; }
bool setRxBoostedGainMode(bool en) override {
return ((CustomSX1268 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
+1 -2
View File
@@ -15,7 +15,6 @@ inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz, bool rx_boost_gain) {
// Re-calibrate for the actual operating frequency (band=4MHz matches RadioLib default).
radio->calibrateImageRejection(freqMHz - 4.0f, freqMHz + 4.0f);
#ifdef RX_BOOSTED_GAIN
// always reapply: the gain may have been changed at runtime even when no build default is set
radio->setRxBoostedGainMode(rx_boost_gain);
#endif
}
@@ -132,6 +132,9 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) {
if (len > 0) {
if (len > sz) { len = sz; }
int err = _radio->readData(bytes, len);
if (err == RADIOLIB_ERR_NONE && !lastRxHadCRC()) {
err = RADIOLIB_ERR_LORA_HEADER_DAMAGED; // header says no CRC, so the payload was never checked
}
if (err != RADIOLIB_ERR_NONE) {
MESH_DEBUG_PRINTLN("RadioLibWrapper: error: readData(%d)", err);
len = 0;
+6 -1
View File
@@ -26,10 +26,14 @@ protected:
void startRecv();
float packetScoreInt(float snr, int sf, int packet_len);
virtual bool isReceivingPacket() =0;
virtual bool lastRxHadCRC() { return true; }
virtual void doResetAGC();
public:
RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board) : _radio(&radio), _board(&board), _preamble_sf(0) { n_recv = n_sent = 0; }
RadioLibWrapper(PhysicalLayer& radio, mesh::MainBoard& board)
: _radio(&radio), _board(&board), _preamble_sf(0) {
n_recv = n_sent = n_recv_errors = 0;
}
void begin() override;
virtual void powerOff() { _radio->sleep(); }
@@ -75,6 +79,7 @@ public:
float packetScore(float snr, int packet_len) override { return packetScoreInt(snr, 10, packet_len); } // assume sf=10
virtual bool supportsRxBoostedGain() const { return false; }
virtual bool setRxBoostedGainMode(bool) { return false; }
virtual bool getRxBoostedGainMode() const { return false; }
+1 -2
View File
@@ -25,9 +25,8 @@ inline void sx126xResetAGC(SX126x* radio, bool rx_boost_gain) {
#ifdef SX126X_DIO2_AS_RF_SWITCH
radio->setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
#endif
#ifdef SX126X_RX_BOOSTED_GAIN
// always reapply: the gain may have been changed at runtime even when no build default is set
radio->setRxBoostedGainMode(rx_boost_gain);
#endif
#ifdef SX126X_REGISTER_PATCH
uint8_t r_data = 0;
radio->readRegister(0x8B5, &r_data, 1);
+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;
}
+23 -229
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.
@@ -624,12 +577,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 +633,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 +660,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 +679,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 +706,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 +723,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 +736,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,
+338
View File
@@ -0,0 +1,338 @@
#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
#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 = nullptr, uint8_t probeCount = 0)
: _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); }
}
};
+45
View File
@@ -0,0 +1,45 @@
#include "AutoDetectDisplay.h"
#include <MeshCore.h>
int AutoDetectDisplay::getDisplayStatus(TwoWire& wire, uint8_t addr) {
int status = -1;
for(int i = 0; i < 4; i++){
// request display status
wire.beginTransmission(addr);
wire.write((uint8_t)0x00);
// ensure response received
if (wire.endTransmission() != 0) return -1; // expect success
if (wire.requestFrom((int)addr, 1) == 0) return -1; // expect at least 1 byte
// ensure two consecutive reads are the same
int previous = status;
status = wire.read() & 0x0F;
if(status == previous){
break;
}
}
return status;
}
bool AutoDetectDisplay::begin() {
// request status from display address
int status = getDisplayStatus(Wire, DISPLAY_ADDRESS);
MESH_DEBUG_PRINTLN("AutoDetectDisplay: status=0x%02X", status);
// detect SH1106
if(status == 0x00 || status == 0x08){
MESH_DEBUG_PRINTLN("AutoDetectDisplay: SH1106 detected");
_impl = &_sh1106;
return _sh1106.begin();
}
// fallback to SSD1306
MESH_DEBUG_PRINTLN("AutoDetectDisplay: falling back to SSD1306");
_impl = &_ssd1306;
return _ssd1306.begin();
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "DisplayDriver.h"
#include "SSD1306Display.h"
#include "SH1106Display.h"
// Auto detects SH1106 display at runtime, otherwise falls back to using SSD1306
class AutoDetectDisplay : public DisplayDriver {
DisplayDriver* _impl;
SSD1306Display _ssd1306;
SH1106Display _sh1106;
int getDisplayStatus(TwoWire& wire, uint8_t addr);
public:
AutoDetectDisplay() : DisplayDriver(128, 64), _impl(&_ssd1306) { }
bool begin();
bool isOn() override { return _impl->isOn(); }
void turnOn() override { _impl->turnOn(); }
void turnOff() override { _impl->turnOff(); }
void clear() override { _impl->clear(); }
void startFrame(ColorVal bkg = UIColor::window_bkg) override { _impl->startFrame(bkg); }
void setTextSize(int sz) override { _impl->setTextSize(sz); }
void setColor(ColorVal c) override { _impl->setColor(c); }
void setCursor(int x, int y) override { _impl->setCursor(x, y); }
void print(const char* str) override { _impl->print(str); }
void fillRect(int x, int y, int w, int h) override { _impl->fillRect(x, y, w, h); }
void drawRect(int x, int y, int w, int h) override { _impl->drawRect(x, y, w, h); }
void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override { _impl->drawXbm(x, y, bits, w, h); }
uint16_t getTextWidth(const char* str) override { return _impl->getTextWidth(str); }
void endFrame() override { _impl->endFrame(); }
};
+2
View File
@@ -25,7 +25,9 @@ public:
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 turnOn() = 0;
virtual void turnOn(int max_partial) { turnOn(); }
virtual void turnOff() = 0;
virtual void turnOff(bool blank) { turnOff(); }
virtual void clear() = 0;
virtual void startFrame(ColorVal bkg = UIColor::window_bkg) = 0;
virtual void setTextSize(int sz) = 0;
+48 -26
View File
@@ -1,11 +1,6 @@
#include "GxEPDDisplay.h"
#ifdef EXP_PIN_BACKLIGHT
#include <PCA9557.h>
extern PCA9557 expander;
#endif
#ifndef DISPLAY_ROTATION
#define DISPLAY_ROTATION 3
#endif
@@ -52,7 +47,7 @@ bool GxEPDDisplay::begin() {
}
display.setPartialWindow(0, 0, display.width(), display.height());
resetPartialRefreshCounter();
_partial_refresh_count = 0;
#if DISP_BACKLIGHT
digitalWrite(DISP_BACKLIGHT, LOW);
@@ -65,29 +60,55 @@ bool GxEPDDisplay::begin() {
void GxEPDDisplay::turnOn() {
if (!_init) begin();
#if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN)
digitalWrite(DISP_BACKLIGHT, HIGH);
#elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN)
expander.digitalWrite(EXP_PIN_BACKLIGHT, HIGH);
#endif
if (!_isOn) {
_isOn = true;
}
}
void GxEPDDisplay::turnOff() {
#if defined(DISP_BACKLIGHT) && !defined(BACKLIGHT_BTN)
digitalWrite(DISP_BACKLIGHT, LOW);
#elif defined(EXP_PIN_BACKLIGHT) && !defined(BACKLIGHT_BTN)
expander.digitalWrite(EXP_PIN_BACKLIGHT, LOW);
#endif
void GxEPDDisplay::turnOn(int max_partial) {
setMaxPartialRefresh(max_partial);
turnOn();
}
// 24x24 sleep icon, MSB-first (matches GxEPDDisplay::drawXbm)
static const uint8_t sleep_icon_24x24[] = {
0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0xe0, 0x0e, 0x03, 0xc0, 0x18,
0x0f, 0x80, 0x70, 0x1f, 0x80, 0xff, 0x3f, 0x80, 0xff, 0x3f, 0x00, 0x00,
0x7f, 0x3f, 0x00, 0x7f, 0x3f, 0x00, 0xff, 0x0e, 0x00, 0xff, 0x1c, 0x7c,
0xff, 0xbf, 0x7c, 0xff, 0xbf, 0x38, 0xff, 0xc0, 0x7c, 0xff, 0xe0, 0x7c,
0xff, 0xf0, 0x00, 0x7f, 0xfc, 0x00, 0x7f, 0xff, 0xf8, 0x3f, 0xff, 0xf0,
0x1f, 0xff, 0xf0, 0x0f, 0xff, 0xe0, 0x07, 0xff, 0x80, 0x01, 0xff, 0x00
};
void GxEPDDisplay::drawSleepIcon() {
const int W = 24, H = 24;
int x = (int)(display.width() / scale_x) - W; // top-right, logical coordinates
int y = 0;
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);
display.display(true);
}
void GxEPDDisplay::turnOff(bool blank) {
if (blank) {
blankScreen();
} else {
drawSleepIcon();
}
_isOn = false;
last_display_crc_value=0;
}
void GxEPDDisplay::blankScreen() {
// do full refresh before powering off to clear screen
// no full refresh needed at wakeup
display.clearScreen(0xFF); // Clears microcontroller side RAM
display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers
resetPartialRefreshCounter();
last_display_crc_value=0;
_partial_refresh_count = 0;
last_display_crc_value = 0;
// we can hibernate as screen has been cleaned
display.hibernate();
}
@@ -101,15 +122,18 @@ void GxEPDDisplay::startFrame(ColorVal bkg) {
display.fillScreen(bkg);
display.setTextColor(_curr_color = UIColor::primary_txt);
display_crc.reset();
if (_cycles_before_full_refresh != 0) {
display.setPartialWindow(0, 0, display.width(), display.height());
} else {
if (_force_full_refresh
|| (_max_partial_refresh > 0
&& _partial_refresh_count >= _max_partial_refresh)) {
// forces a full wipe of the screen ...
display.clearScreen(0xFF); // Clears microcontroller side RAM
display.writeScreenBuffer(0xFF); // Forces 0xFF (White) into the display controller's history registers
// we'll need a partial refresh after that (whatever crc value is)
last_display_crc_value = 0;
resetPartialRefreshCounter();
_partial_refresh_count = 0;
_force_full_refresh = false;
} else {
display.setPartialWindow(0, 0, display.width(), display.height());
}
}
@@ -216,9 +240,7 @@ void GxEPDDisplay::endFrame() {
uint32_t crc = display_crc.finalize();
if (crc != last_display_crc_value) {
display.display(true);
if (_cycles_before_full_refresh > 0) {
_cycles_before_full_refresh--;
}
_partial_refresh_count++;
}
last_display_crc_value = crc;
}
+10 -11
View File
@@ -16,12 +16,6 @@
#include "DisplayDriver.h"
#ifndef EINK_MAX_PARTIAL_REFRESH
// 60 to prevent ghosting when refreshing every minute ...
// set to -1 to disable the counter
#define EINK_MAX_PARTIAL_REFRESH -1
#endif
class GxEPDDisplay : public DisplayDriver {
#if defined(EINK_DISPLAY_MODEL)
@@ -42,8 +36,9 @@ class GxEPDDisplay : public DisplayDriver {
uint16_t _curr_color;
CRC32 display_crc;
int last_display_crc_value = 0;
int _cycles_before_full_refresh;
int max_partial_refresh = EINK_MAX_PARTIAL_REFRESH; // so this can be changed by an option after
bool _force_full_refresh = false;
int _partial_refresh_count = 0;
int _max_partial_refresh = 0;
public:
#if defined(EINK_DISPLAY_MODEL)
@@ -56,10 +51,13 @@ public:
bool isOn() override { return _isOn; }
bool isEink() override { return true; }
void forceFullRefresh() override { _cycles_before_full_refresh = 0; };
void resetPartialRefreshCounter() { _cycles_before_full_refresh = max_partial_refresh; };
void forceFullRefresh() override { _force_full_refresh = true; }
void turnOn(int max_partial) override;
void turnOn() override;
void turnOff() override;
void turnOff(bool blank) override;
void turnOff() override { turnOff(false); }
virtual void blankScreen();
virtual void setMaxPartialRefresh(int count) {_max_partial_refresh = count; }
void clear() override;
void startFrame(ColorVal bkg = UIColor::window_bkg) override;
void setTextSize(int sz) override;
@@ -69,6 +67,7 @@ public:
void fillRect(int x, int y, int w, int h) override;
void drawRect(int x, int y, int w, int h) override;
void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override;
void drawSleepIcon();
uint16_t getTextWidth(const char* str) override;
void endFrame() override;
};
+9 -9
View File
@@ -10,15 +10,15 @@ bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr)
}
// Color scheme
ColorVal UIColor::window_bkg = SH110X_BLACK;
ColorVal UIColor::title_bkg = SH110X_BLACK;
ColorVal UIColor::title_txt = SH110X_WHITE;
ColorVal UIColor::primary_txt = SH110X_WHITE;
ColorVal UIColor::secondary_txt = SH110X_WHITE;
ColorVal UIColor::warning_txt = SH110X_WHITE;
ColorVal UIColor::popup_bkg = SH110X_BLACK;
ColorVal UIColor::popup_txt = SH110X_WHITE;
ColorVal UIColor::corp_blue = SH110X_WHITE;
__attribute__((weak)) ColorVal UIColor::window_bkg = SH110X_BLACK;
__attribute__((weak)) ColorVal UIColor::title_bkg = SH110X_BLACK;
__attribute__((weak)) ColorVal UIColor::title_txt = SH110X_WHITE;
__attribute__((weak)) ColorVal UIColor::primary_txt = SH110X_WHITE;
__attribute__((weak)) ColorVal UIColor::secondary_txt = SH110X_WHITE;
__attribute__((weak)) ColorVal UIColor::warning_txt = SH110X_WHITE;
__attribute__((weak)) ColorVal UIColor::popup_bkg = SH110X_BLACK;
__attribute__((weak)) ColorVal UIColor::popup_txt = SH110X_WHITE;
__attribute__((weak)) ColorVal UIColor::corp_blue = SH110X_WHITE;
bool SH1106Display::begin()
{
+2
View File
@@ -13,6 +13,7 @@ public:
virtual bool isSendComplete() { return true; }
virtual void onSendFinished() {}
virtual int16_t getNoiseFloor() { return -120; }
virtual void resetAGC() {}
};
class MainBoard {
@@ -22,6 +23,7 @@ public:
virtual float getMCUTemperature() { return 25.0f; }
virtual const char* getManufacturerName() { return "mock-board"; }
virtual void reboot() {}
virtual bool handleCommand(const char*, uint32_t, char*) { return false; }
};
}
@@ -0,0 +1,230 @@
#include <gtest/gtest.h>
#include <cstring>
#include <ed_25519.h>
#include "Dispatcher.cpp"
#include "Mesh.cpp"
#include "helpers/AdvertDataHelpers.cpp"
#include "helpers/BaseChatMesh.cpp"
void StrHelper::strncpy(char* dest, const char* src, size_t buf_sz) {
if (buf_sz == 0) return;
std::strncpy(dest, src, buf_sz - 1);
dest[buf_sz - 1] = 0;
}
namespace mesh {
Identity::Identity() {
memset(pub_key, 0, sizeof(pub_key));
}
bool Identity::verify(const uint8_t*, const uint8_t*, int) const {
return true;
}
LocalIdentity::LocalIdentity() : Identity() {
memset(prv_key, 0, sizeof(prv_key));
}
void LocalIdentity::sign(uint8_t* sig, const uint8_t*, int) const {
memset(sig, 0, SIGNATURE_SIZE);
}
void LocalIdentity::calcSharedSecret(uint8_t* secret, const uint8_t* other_pub_key) const {
ed25519_key_exchange(secret, other_pub_key, prv_key);
}
} // namespace mesh
namespace {
class DummyRadio : public mesh::Radio {
public:
int recvRaw(uint8_t*, int) override { return 0; }
uint32_t getEstAirtimeFor(int) override { return 10; }
float packetScore(float, int) override { return 1.0f; }
bool startSendRaw(const uint8_t*, int) override { return true; }
bool isSendComplete() override { return true; }
void onSendFinished() override {}
bool isInRecvMode() const override { return true; }
};
class DummyMillisecondClock : public mesh::MillisecondClock {
public:
unsigned long getMillis() override { return 1000; }
};
class DummyRNG : public mesh::RNG {
public:
void random(uint8_t* dest, size_t len) override { memset(dest, 0x42, len); }
};
class DummyRTCClock : public mesh::RTCClock {
uint32_t _now = 1700000000;
public:
uint32_t getCurrentTime() override { return _now; }
void setCurrentTime(uint32_t time) override { _now = time; }
};
class DummyPacketManager : public mesh::PacketManager {
public:
mesh::Packet* allocNew() override { return nullptr; }
void free(mesh::Packet*) override {}
void queueOutbound(mesh::Packet*, uint8_t, uint32_t) override {}
mesh::Packet* getNextOutbound(uint32_t) override { return nullptr; }
int getOutboundCount(uint32_t) const override { return 0; }
int getOutboundTotal() const override { return 0; }
int getFreeCount() const override { return 16; }
mesh::Packet* getOutboundByIdx(int) override { return nullptr; }
mesh::Packet* removeOutboundByIdx(int) override { return nullptr; }
void queueInbound(mesh::Packet*, uint32_t) override {}
mesh::Packet* getNextInbound(uint32_t) override { return nullptr; }
};
class DummyMeshTables : public mesh::MeshTables {
public:
bool wasSeen(const mesh::Packet*) override { return false; }
void markSeen(const mesh::Packet*) override {}
void clear(const mesh::Packet*) override {}
};
class TestChatMesh : public BaseChatMesh {
public:
int messages_received = 0;
TestChatMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng,
mesh::RTCClock& rtc, mesh::PacketManager& mgr, mesh::MeshTables& tables)
: BaseChatMesh(radio, ms, rng, rtc, mgr, tables) {}
void onDiscoveredContact(ContactInfo&, bool, uint8_t, const uint8_t*) override {}
ContactInfo* processAck(const uint8_t*) override { return nullptr; }
void onContactPathUpdated(const ContactInfo&) override {}
void onMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override {
messages_received++;
}
void onCommandDataRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override {}
void onCLICommandRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*, char*) override {}
void onSignedMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const uint8_t*, const char*) override {}
void onChannelMessageRecv(const mesh::GroupChannel&, mesh::Packet*, uint32_t, const char*) override {}
uint8_t onContactRequest(const ContactInfo&, uint32_t, const uint8_t*, uint8_t, uint8_t*) override { return 0; }
void onContactResponse(const ContactInfo&, const uint8_t*, uint8_t) override {}
uint32_t calcFloodTimeoutMillisFor(uint32_t) const override { return 1000; }
uint32_t calcDirectTimeoutMillisFor(uint32_t, uint8_t) const override { return 1000; }
void onSendTimeout() override {}
using BaseChatMesh::resetContacts;
using BaseChatMesh::searchPeersByHash;
using BaseChatMesh::getPeerSharedSecret;
using mesh::Mesh::onRecvPacket;
};
struct MeshFixture {
DummyRadio radio;
DummyMillisecondClock ms;
DummyRNG rng;
DummyRTCClock rtc;
DummyPacketManager mgr;
DummyMeshTables tables;
TestChatMesh chat{radio, ms, rng, rtc, mgr, tables};
};
} // namespace
TEST(EmptyContactSlots, ZeroPubKeyProducesAllZeroSharedSecretForAnyPrivateKey) {
ContactInfo empty_slot;
memset(&empty_slot, 0, sizeof(empty_slot));
EXPECT_TRUE(empty_slot.isEmptySlot());
uint8_t raw_prv[PRV_KEY_SIZE];
for (int i = 0; i < PRV_KEY_SIZE; i++) {
raw_prv[i] = static_cast<uint8_t>(0xA5 ^ (i * 13 + 7));
}
uint8_t secret[PUB_KEY_SIZE];
ed25519_key_exchange(secret, empty_slot.id.pub_key, raw_prv);
uint8_t expected_zeroes[PUB_KEY_SIZE] = { 0 };
EXPECT_EQ(0, memcmp(secret, expected_zeroes, PUB_KEY_SIZE));
}
TEST(EmptyContactSlots, NullKeyPeerPacketIsRejectedWhenAnonSlotsAreEmpty) {
MeshFixture fx;
fx.chat.self_id.pub_key[0] = 0x42;
// Craft a PAYLOAD_TYPE_TXT_MSG addressed to self_id (dest_hash=0x42) with src_hash=0x00,
// encrypted and MAC'd under the all-zero 32-byte key that an empty ContactInfo slot derives.
uint8_t zero_secret[PUB_KEY_SIZE] = { 0 };
uint8_t plaintext[16] = { 0 };
uint32_t ts = 1700000001;
memcpy(plaintext, &ts, 4);
plaintext[4] = (TXT_TYPE_PLAIN << 2);
strcpy(reinterpret_cast<char*>(&plaintext[5]), "forged");
mesh::Packet pkt;
pkt.header = ROUTE_TYPE_FLOOD | (PAYLOAD_TYPE_TXT_MSG << PH_TYPE_SHIFT);
pkt.path_len = 0;
pkt.payload[0] = 0x42; // dest_hash (matches fx.chat.self_id)
pkt.payload[1] = 0x00; // src_hash (matches all-zero pub_key if empty slots are not skipped)
int enc_len = mesh::Utils::encryptThenMAC(zero_secret, &pkt.payload[2], plaintext, 12);
pkt.payload_len = static_cast<uint8_t>(2 + enc_len);
fx.chat.onRecvPacket(&pkt);
EXPECT_EQ(0, fx.chat.messages_received);
}
TEST(EmptyContactSlots, SearchPeersByHashSkipsEmptyAnonSlotsAndFindsRealZeroPrefixPeer) {
MeshFixture fx;
const uint8_t zero_hash = 0x00;
// Freshly reset contacts has MAX_ANON_CONTACTS (8) zeroed transient slots.
EXPECT_EQ(0, fx.chat.searchPeersByHash(&zero_hash));
// Add a legitimate permanent contact whose public key starts with 0x00.
ContactInfo peer;
memset(&peer, 0, sizeof(peer));
peer.type = ADV_TYPE_CHAT;
peer.lastmod = 1700000100;
strcpy(peer.name, "Alice");
peer.id.pub_key[0] = 0x00;
for (int i = 1; i < PUB_KEY_SIZE; i++) {
peer.id.pub_key[i] = static_cast<uint8_t>(i);
}
ASSERT_TRUE(fx.chat.addContact(peer));
// Only the populated contact at index MAX_ANON_CONTACTS should match.
EXPECT_EQ(1, fx.chat.searchPeersByHash(&zero_hash));
// Lookup by pubkey and name prefix must also skip the empty transient slots.
uint8_t zero_prefix[6] = { 0 };
EXPECT_EQ(nullptr, fx.chat.lookupContactByPubKey(zero_prefix, sizeof(zero_prefix)));
ContactInfo* found = fx.chat.lookupContactByPubKey(peer.id.pub_key, 6);
ASSERT_NE(nullptr, found);
EXPECT_STREQ("Alice", found->name);
ContactInfo* by_name = fx.chat.searchContactsByPrefix("");
ASSERT_NE(nullptr, by_name);
EXPECT_STREQ("Alice", by_name->name);
}
TEST(EmptyContactSlots, PopulatedTransientAnonSlotStillMatchesEvenWhenLastmodIsZero) {
MeshFixture fx;
const uint8_t zero_hash = 0x00;
ContactInfo anon;
memset(&anon, 0, sizeof(anon));
anon.type = ADV_TYPE_NONE;
anon.lastmod = 0; // e.g. RTC not yet initialised on nRF52
anon.id.pub_key[0] = 0x00;
anon.id.pub_key[1] = 0x7F;
ASSERT_TRUE(fx.chat.addContact(anon));
EXPECT_FALSE(anon.isEmptySlot());
EXPECT_EQ(1, fx.chat.searchPeersByHash(&zero_hash));
EXPECT_NE(nullptr, fx.chat.lookupContactByPubKey(anon.id.pub_key, PUB_KEY_SIZE));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+546
View File
@@ -0,0 +1,546 @@
#include <gtest/gtest.h>
#include <queue>
#include <vector>
#include "KissModem.h"
namespace {
class RecordingStream : public Stream {
public:
void pushRx(const std::vector<uint8_t>& bytes) {
for (uint8_t b : bytes) _rx.push(b);
}
int availableForWrite() override { return blocked ? 0 : 4096; }
size_t write(const uint8_t* buffer, size_t size) override {
if (blocked) return 0;
_writes.insert(_writes.end(), buffer, buffer + size);
return size;
}
size_t write(uint8_t b) override { return write(&b, 1); }
int available() override { return (int)_rx.size(); }
int read() override {
if (_rx.empty()) return -1;
int b = _rx.front();
_rx.pop();
return b;
}
// Decoded SetHardware payloads (sub-command + data), consumed on read.
std::vector<std::vector<uint8_t>> takeHardwareFrames() {
std::vector<std::vector<uint8_t>> frames;
std::vector<uint8_t> cur;
bool in_frame = false, esc = false;
for (uint8_t b : _writes) {
if (b == KISS_FEND) {
if (in_frame && cur.size() > 1 && cur[0] == KISS_CMD_SETHARDWARE) {
frames.emplace_back(cur.begin() + 1, cur.end());
}
cur.clear();
in_frame = true;
continue;
}
if (b == KISS_FESC) { esc = true; continue; }
if (esc) { b = (b == KISS_TFEND) ? KISS_FEND : KISS_FESC; esc = false; }
cur.push_back(b);
}
_writes.clear();
return frames;
}
bool blocked = false;
private:
std::queue<uint8_t> _rx;
std::vector<uint8_t> _writes;
};
class ZeroRNG : public mesh::RNG {
public:
void random(uint8_t* dest, size_t sz) override { memset(dest, 0, sz); }
};
class AgcRadio : public mesh::Radio {
public:
bool startSendRaw(const uint8_t*, uint16_t) override { return true; }
bool isSendComplete() override { return send_complete; }
void resetAGC() override { agc_resets++; }
bool send_complete = true;
int agc_resets = 0;
};
// Implements FEM through the "radio.fem.*" CLI text, worded like the Heltec / Station G3 boards.
class FemBoard : public mesh::MainBoard {
public:
const char* getManufacturerName() override { return "fem-board"; }
bool handleCommand(const char* command, uint32_t, char* reply) override {
commands++;
if (handleGain(command, reply, "rxgain", has_lna, lna, lna_sets, lna_sticks)) return true;
if (handleGain(command, reply, "txgain", has_pa, pa, pa_sets, pa_sticks)) return true;
return false;
}
bool has_lna = false, has_pa = false;
bool lna = false, pa = false;
int lna_sets = 0, pa_sets = 0;
bool lna_sticks = false, pa_sticks = false; // set reports OK but the state does not change
bool unhandled = false; // board does not implement radio.fem.* at all
const char* odd_get_reply = nullptr; // unexpected get wording
int commands = 0;
private:
bool handleGain(const char* command, char* reply, const char* name, bool has, bool& state, int& sets, bool sticks) {
if (unhandled) return false;
char get_cmd[32], set_cmd[32];
snprintf(get_cmd, sizeof(get_cmd), "get radio.fem.%s", name);
snprintf(set_cmd, sizeof(set_cmd), "set radio.fem.%s ", name);
if (strcmp(command, get_cmd) == 0) {
if (!has) strcpy(reply, "Error: unsupported");
else if (odd_get_reply) strcpy(reply, odd_get_reply);
else sprintf(reply, "> %s", state ? "on" : "off");
return true;
}
if (strncmp(command, set_cmd, strlen(set_cmd)) == 0) {
if (!has) {
strcpy(reply, "Error: unsupported");
} else {
sets++;
if (!sticks) state = strcmp(command + strlen(set_cmd), "on") == 0;
strcpy(reply, "OK - LoRa FEM gain changed");
}
return true;
}
return false;
}
};
class NoSensors : public SensorManager {
public:
bool querySensors(uint8_t, CayenneLPP&) override { return false; }
};
class KissHwControlTest : public ::testing::Test {
protected:
RecordingStream serial;
mesh::LocalIdentity identity;
ZeroRNG rng;
AgcRadio radio;
FemBoard board;
NoSensors sensors;
KissModem modem;
KissHwControlTest() : modem(serial, identity, rng, radio, board, sensors) {
g_mock_millis = 1000;
modem.begin();
}
std::vector<std::vector<uint8_t>> hw(const std::vector<uint8_t>& payload) {
std::vector<uint8_t> frame = {KISS_FEND, KISS_CMD_SETHARDWARE};
frame.insert(frame.end(), payload.begin(), payload.end());
frame.push_back(KISS_FEND);
serial.pushRx(frame);
modem.loop();
return serial.takeHardwareFrames();
}
std::vector<uint8_t> hw1(const std::vector<uint8_t>& payload) {
auto frames = hw(payload);
EXPECT_EQ(frames.size(), 1U);
return frames.empty() ? std::vector<uint8_t>{} : frames[0];
}
void advance(uint32_t ms) {
g_mock_millis += ms;
modem.loop();
}
void startTxAndHold() {
radio.send_complete = false;
serial.pushRx({KISS_FEND, KISS_CMD_DATA, 0x42, KISS_FEND});
modem.loop();
modem.loop();
advance((uint32_t)KISS_DEFAULT_TXDELAY * 10);
ASSERT_TRUE(modem.isActuallyTransmitting());
}
};
bool g_rx_boost = false;
bool g_rx_boost_set_ok = true;
int g_rx_boost_sets = 0;
bool fakeSetRxBoost(bool en) {
g_rx_boost_sets++;
if (!g_rx_boost_set_ok) return false;
g_rx_boost = en;
return true;
}
bool fakeGetRxBoost() { return g_rx_boost; }
KissModem* g_poll_modem = nullptr;
bool g_poll_has_packet = false;
int g_polls = 0;
void fakePollRx() {
g_polls++;
if (g_poll_has_packet && g_poll_modem) {
static constexpr uint8_t PKT[] = {0x55};
g_poll_has_packet = false;
g_poll_modem->onPacketReceived(4, -80, PKT, sizeof(PKT));
}
}
const std::vector<uint8_t> ERR_UNSUPPORTED = {HW_RESP_ERROR, HW_ERR_UNSUPPORTED};
TEST_F(KissHwControlTest, VersionIsTwo) {
EXPECT_EQ(hw1({HW_CMD_GET_VERSION}), (std::vector<uint8_t>{HW_RESP(HW_CMD_GET_VERSION), 2, 0}));
}
TEST_F(KissHwControlTest, CapabilitiesOnBareBoardAreAgcOnly) {
EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x01, 0x00, 0x00, 0x00}));
}
TEST_F(KissHwControlTest, CapabilitiesReflectBoardFem) {
board.has_lna = true;
EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x03, 0x00, 0x00, 0x00}));
board.has_pa = true;
EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x07, 0x00, 0x00, 0x00}));
}
TEST_F(KissHwControlTest, AgcIntervalDefaultsToThirtyTwoSeconds) {
EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 32, 0}));
// the default must be restorable, i.e. a multiple of the 4 s step
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}), (std::vector<uint8_t>{0x9D, 4, 0}));
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, KISS_AGC_RESET_DEFAULT_SEC, 0}), (std::vector<uint8_t>{0x9D, KISS_AGC_RESET_DEFAULT_SEC, 0}));
}
TEST_F(KissHwControlTest, AgcIntervalSetReturnsEffectiveRoundedValue) {
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 10, 0}), (std::vector<uint8_t>{0x9D, 8, 0}));
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0}), (std::vector<uint8_t>{0x9D, 4, 0}));
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFC, 0x03}), (std::vector<uint8_t>{0x9D, 0xFC, 0x03}));
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0, 0}), (std::vector<uint8_t>{0x9D, 0, 0}));
EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 0, 0}));
}
TEST_F(KissHwControlTest, AgcIntervalRejectsOutOfRangeAndShortPayload) {
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 0xFD, 0x03}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_PARAM}));
EXPECT_EQ(hw1({HW_CMD_SET_AGC_RESET_INTERVAL, 4}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH}));
EXPECT_EQ(hw1({HW_CMD_GET_AGC_RESET_INTERVAL}), (std::vector<uint8_t>{0x9D, 32, 0}));
}
TEST_F(KissHwControlTest, AgcResetsOnDefaultSchedule) {
advance(31999);
EXPECT_EQ(radio.agc_resets, 0);
advance(1);
EXPECT_EQ(radio.agc_resets, 1);
advance(31999);
EXPECT_EQ(radio.agc_resets, 1);
advance(1);
EXPECT_EQ(radio.agc_resets, 2);
}
TEST_F(KissHwControlTest, AgcZeroDisablesResets) {
hw({HW_CMD_SET_AGC_RESET_INTERVAL, 0, 0});
for (int i = 0; i < 10; i++) advance(60000);
EXPECT_EQ(radio.agc_resets, 0);
}
TEST_F(KissHwControlTest, AgcIntervalChangeRestartsDeadline) {
hw({HW_CMD_SET_AGC_RESET_INTERVAL, 0x2C, 0x01}); // 300 s
advance(100000);
hw({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0});
EXPECT_EQ(radio.agc_resets, 0);
advance(3999);
EXPECT_EQ(radio.agc_resets, 0);
advance(1);
EXPECT_EQ(radio.agc_resets, 1);
}
TEST_F(KissHwControlTest, AgcResetWaitsForTxToFinish) {
hw({HW_CMD_SET_AGC_RESET_INTERVAL, 4, 0});
startTxAndHold();
advance(10000);
EXPECT_EQ(radio.agc_resets, 0);
radio.send_complete = true;
modem.loop(); // TX done -> TX_DONE_PENDING
modem.loop(); // TxDone flushed -> idle, overdue reset runs
EXPECT_EQ(radio.agc_resets, 1);
}
TEST_F(KissHwControlTest, FemUnsupportedOnBareBoard) {
EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x00, 0x00}));
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED);
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, 0}), ERR_UNSUPPORTED);
}
TEST_F(KissHwControlTest, FemSetRxLeavesTxUntouched) {
board.has_lna = board.has_pa = true;
board.pa = true;
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), (std::vector<uint8_t>{0x9F, 0x03, 0x03}));
EXPECT_TRUE(board.lna);
EXPECT_EQ(board.pa_sets, 0);
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, 0}), (std::vector<uint8_t>{0x9F, 0x03, 0x01}));
EXPECT_FALSE(board.pa);
EXPECT_EQ(board.lna_sets, 1);
}
TEST_F(KissHwControlTest, FemPartialCapabilityRejectsWholeRequest) {
board.has_lna = true;
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN}), ERR_UNSUPPORTED);
EXPECT_EQ(board.lna_sets, 0);
EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x01, 0x00}));
}
TEST_F(KissHwControlTest, FemUnknownBitsAreUnsupported) {
board.has_lna = board.has_pa = true;
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, 0x04, 0x04}), ERR_UNSUPPORTED);
}
TEST_F(KissHwControlTest, FemUnhandledCommandsMeanUnsupported) {
board.has_lna = board.has_pa = true;
board.unhandled = true;
EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x00, 0x00}));
EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x01, 0x00, 0x00, 0x00}));
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED);
}
TEST_F(KissHwControlTest, FemUnexpectedGetWordingMeansUnsupported) {
board.has_lna = true;
board.odd_get_reply = "> enabled";
EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x00, 0x00}));
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}), ERR_UNSUPPORTED);
EXPECT_EQ(board.lna_sets, 0);
}
TEST_F(KissHwControlTest, FemSetThatDoesNotTakeRepliesWithReadBackState) {
board.has_lna = board.has_pa = true;
board.lna_sticks = true; // board says OK but LNA stays off
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN, HW_FEM_RX_GAIN | HW_FEM_TX_GAIN}),
(std::vector<uint8_t>{0x9F, 0x03, 0x02}));
EXPECT_FALSE(board.lna);
EXPECT_TRUE(board.pa);
}
TEST_F(KissHwControlTest, FemShortPayloadIsInvalidLength) {
EXPECT_EQ(hw1({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH}));
}
TEST_F(KissHwControlTest, FemSetDuringTxIsDeferredUntilAfterTxDone) {
board.has_lna = true;
startTxAndHold();
serial.takeHardwareFrames();
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty());
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, 0}).empty()); // queued behind the first
EXPECT_EQ(board.lna_sets, 0);
radio.send_complete = true;
modem.loop(); // TX done -> TX_DONE_PENDING; FEM still held
modem.loop(); // TxDone queued -> idle; FEM applied in order
for (int i = 0; i < 3; i++) modem.loop();
auto frames = serial.takeHardwareFrames();
ASSERT_EQ(frames.size(), 3U);
EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01}));
EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x00}));
EXPECT_FALSE(board.lna);
EXPECT_EQ(board.lna_sets, 2);
}
TEST_F(KissHwControlTest, PipelinedFemRequestsAreAnsweredInArrivalOrder) {
board.has_lna = true;
startTxAndHold();
serial.takeHardwareFrames();
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty());
EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty());
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_TX_GAIN, HW_FEM_TX_GAIN}).empty()); // unsupported bit
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN}).empty()); // short payload
radio.send_complete = true;
for (int i = 0; i < 6; i++) modem.loop();
auto frames = serial.takeHardwareFrames();
ASSERT_EQ(frames.size(), 5U);
EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01}));
EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
EXPECT_EQ(frames[3], ERR_UNSUPPORTED);
EXPECT_EQ(frames[4], (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH}));
EXPECT_EQ(board.lna_sets, 1);
}
TEST_F(KissHwControlTest, FemQueueOverflowRepliesTxBusyImmediately) {
board.has_lna = true;
startTxAndHold();
serial.takeHardwareFrames();
for (int i = 0; i < KISS_FEM_OP_QUEUE_DEPTH; i++) {
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty());
}
EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY}));
EXPECT_EQ(board.lna_sets, 0);
}
TEST_F(KissHwControlTest, FemGetWithNothingQueuedIsAnsweredDuringTx) {
board.has_lna = true;
startTxAndHold();
serial.takeHardwareFrames();
EXPECT_EQ(hw1({HW_CMD_GET_FEM_STATE}), (std::vector<uint8_t>{0x9F, 0x01, 0x00}));
}
TEST_F(KissHwControlTest, FemGetDuringDeferredSetIsAnsweredAfterSet) {
board.has_lna = true;
startTxAndHold();
serial.takeHardwareFrames();
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty());
EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty());
radio.send_complete = true;
modem.loop();
modem.loop();
auto frames = serial.takeHardwareFrames();
ASSERT_EQ(frames.size(), 3U);
EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01}));
EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
}
TEST_F(KissHwControlTest, DeferredFemRepliesSurviveHostBackpressure) {
board.has_lna = true;
hw({HW_CMD_SET_SIGNAL_REPORT, 0}); // one output frame per RX packet
startTxAndHold();
serial.takeHardwareFrames();
EXPECT_TRUE(hw({HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN}).empty());
EXPECT_TRUE(hw({HW_CMD_GET_FEM_STATE}).empty());
// with writes blocked: RX packet takes slot 1, TxDone slot 2, so the Set reply cannot be queued
serial.blocked = true;
static constexpr uint8_t PKT[] = {0x01};
modem.onPacketReceived(0, 0, PKT, sizeof(PKT));
radio.send_complete = true;
for (int i = 0; i < 5; i++) modem.loop();
EXPECT_TRUE(board.lna); // applied once TxDone was queued, reply still held
serial.blocked = false;
for (int i = 0; i < 5; i++) modem.loop();
EXPECT_EQ(board.lna_sets, 1);
auto frames = serial.takeHardwareFrames();
ASSERT_EQ(frames.size(), 3U);
EXPECT_EQ(frames[0], (std::vector<uint8_t>{HW_RESP_TX_DONE, 0x01}));
EXPECT_EQ(frames[1], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
EXPECT_EQ(frames[2], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
}
TEST_F(KissHwControlTest, ImmediateFemReplySurvivesHostBackpressure) {
board.has_lna = true;
hw({HW_CMD_SET_SIGNAL_REPORT, 0});
serial.blocked = true;
static constexpr uint8_t PKT[] = {0x01};
modem.onPacketReceived(0, 0, PKT, sizeof(PKT));
modem.onPacketReceived(0, 0, PKT, sizeof(PKT)); // output queue now full
serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_FEM_STATE, HW_FEM_RX_GAIN, HW_FEM_RX_GAIN, KISS_FEND});
modem.loop();
EXPECT_TRUE(board.lna);
serial.blocked = false;
for (int i = 0; i < 5; i++) modem.loop();
auto frames = serial.takeHardwareFrames();
ASSERT_EQ(frames.size(), 1U); // FemState, not TxBusy
EXPECT_EQ(frames[0], (std::vector<uint8_t>{0x9F, 0x01, 0x01}));
EXPECT_EQ(board.lna_sets, 1);
}
class KissRxBoostTest : public KissHwControlTest {
protected:
KissRxBoostTest() {
g_rx_boost = true;
g_rx_boost_set_ok = true;
g_rx_boost_sets = 0;
modem.setRxBoostedGainCallbacks(fakeSetRxBoost, fakeGetRxBoost);
g_poll_modem = &modem;
g_poll_has_packet = false;
g_polls = 0;
modem.setPollRxCallback(fakePollRx);
}
};
TEST_F(KissHwControlTest, RxBoostedGainUnsupportedWithoutCallbacks) {
EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), ERR_UNSUPPORTED);
EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 1}), ERR_UNSUPPORTED);
}
TEST_F(KissRxBoostTest, CapabilityAdvertised) {
EXPECT_EQ(hw1({HW_CMD_GET_CAPABILITIES}), (std::vector<uint8_t>{0x9B, 0x09, 0x00, 0x00, 0x00}));
}
TEST_F(KissRxBoostTest, GetReportsCurrentState) {
EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), (std::vector<uint8_t>{0xA1, 0x01}));
}
TEST_F(KissRxBoostTest, SetRepliesWithEffectiveState) {
EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector<uint8_t>{0xA1, 0x00}));
EXPECT_FALSE(g_rx_boost);
EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0x7F}), (std::vector<uint8_t>{0xA1, 0x01}));
EXPECT_TRUE(g_rx_boost);
}
TEST_F(KissRxBoostTest, SetFailureRepliesWithUnchangedState) {
g_rx_boost_set_ok = false;
EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector<uint8_t>{0xA1, 0x01}));
EXPECT_TRUE(g_rx_boost);
}
TEST_F(KissRxBoostTest, SetDuringTxIsRejectedWithoutTouchingRadio) {
startTxAndHold();
serial.takeHardwareFrames();
EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN, 0}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY}));
EXPECT_EQ(g_rx_boost_sets, 0);
EXPECT_EQ(hw1({HW_CMD_GET_RX_BOOSTED_GAIN}), (std::vector<uint8_t>{0xA1, 0x01}));
}
TEST_F(KissRxBoostTest, SetShortPayloadIsInvalidLength) {
EXPECT_EQ(hw1({HW_CMD_SET_RX_BOOSTED_GAIN}), (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_INVALID_LENGTH}));
EXPECT_EQ(g_rx_boost_sets, 0);
}
TEST_F(KissRxBoostTest, CompletedRxPacketIsDeliveredBeforeGainChange) {
g_poll_has_packet = true;
auto frames = hw({HW_CMD_SET_RX_BOOSTED_GAIN, 0});
EXPECT_EQ(g_polls, 1);
EXPECT_FALSE(g_rx_boost);
ASSERT_EQ(frames.size(), 2U); // RxMeta for the drained packet, then the gain reply
EXPECT_EQ(frames[0][0], HW_RESP_RX_META);
EXPECT_EQ(frames[1], (std::vector<uint8_t>{0xA1, 0x00}));
}
TEST_F(KissRxBoostTest, NoRoomForReplyAfterDrainChangesNothing) {
serial.blocked = true;
g_poll_has_packet = true; // data + meta fill both output slots
serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_RX_BOOSTED_GAIN, 0, KISS_FEND});
modem.loop();
EXPECT_EQ(g_rx_boost_sets, 0);
EXPECT_TRUE(g_rx_boost);
serial.blocked = false;
for (int i = 0; i < 5; i++) modem.loop();
auto frames = serial.takeHardwareFrames();
ASSERT_EQ(frames.size(), 2U);
EXPECT_EQ(frames[0][0], HW_RESP_RX_META);
EXPECT_EQ(frames[1], (std::vector<uint8_t>{HW_RESP_ERROR, HW_ERR_TX_BUSY}));
}
TEST_F(KissRxBoostTest, SetWhileHostOutputBackedUpIsRejected) {
serial.blocked = true;
static constexpr uint8_t PKT[] = {0x01};
modem.onPacketReceived(0, 0, PKT, sizeof(PKT));
serial.pushRx({KISS_FEND, KISS_CMD_SETHARDWARE, HW_CMD_SET_RX_BOOSTED_GAIN, 0, KISS_FEND});
modem.loop();
EXPECT_EQ(g_polls, 0);
EXPECT_EQ(g_rx_boost_sets, 0);
}
} // namespace
@@ -8,6 +8,9 @@ static Packet makeFlood(uint8_t route_type, uint8_t payload_type, uint8_t hops)
p.header = route_type | (payload_type << PH_TYPE_SHIFT);
p.setPathHashSizeAndCount(1, hops);
p.payload_len = 1;
if (route_type == ROUTE_TYPE_TRANSPORT_FLOOD) {
p.transport_codes[0] = 1; // has to be non-zero
}
return p;
}
+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;
+2 -2
View File
@@ -158,14 +158,14 @@ bool T096Board::handleCommand(const char* command, uint32_t sender_timestamp, ch
strcpy(reply, "Error: unsupported");
} else if (memcmp(&command[21], "on", 2) == 0) {
if (setLoRaFemLnaEnabled(true)) {
_prefs->setByKey("fem_rxgain", "1");
if (_prefs) _prefs->setByKey("fem_rxgain", "1");
strcpy(reply, "OK - LoRa FEM RX gain on");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
}
} else if (memcmp(&command[21], "off", 3) == 0) {
if (setLoRaFemLnaEnabled(false)) {
_prefs->setByKey("fem_rxgain", "0");
if (_prefs) _prefs->setByKey("fem_rxgain", "0");
strcpy(reply, "OK - LoRa FEM RX gain off");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
+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();
@@ -99,14 +99,14 @@ bool HeltecTrackerV2Board::handleCommand(const char* command, uint32_t sender_ti
strcpy(reply, "Error: unsupported");
} else if (memcmp(&command[21], "on", 2) == 0) {
if (setLoRaFemLnaEnabled(true)) {
_prefs->setByKey("fem_rxgain", "1");
if (_prefs) _prefs->setByKey("fem_rxgain", "1");
strcpy(reply, "OK - LoRa FEM RX gain on");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
}
} else if (memcmp(&command[21], "off", 3) == 0) {
if (setLoRaFemLnaEnabled(false)) {
_prefs->setByKey("fem_rxgain", "0");
if (_prefs) _prefs->setByKey("fem_rxgain", "0");
strcpy(reply, "OK - LoRa FEM RX gain off");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
+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 -2
View File
@@ -100,14 +100,14 @@ bool HeltecV4Board::handleCommand(const char* command, uint32_t sender_timestamp
strcpy(reply, "Error: unsupported");
} else if (memcmp(&command[21], "on", 2) == 0) {
if (setLoRaFemLnaEnabled(true)) {
_prefs->setByKey("fem_rxgain", "1");
if (_prefs) _prefs->setByKey("fem_rxgain", "1");
strcpy(reply, "OK - LoRa FEM RX gain on");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
}
} else if (memcmp(&command[21], "off", 3) == 0) {
if (setLoRaFemLnaEnabled(false)) {
_prefs->setByKey("fem_rxgain", "0");
if (_prefs) _prefs->setByKey("fem_rxgain", "0");
strcpy(reply, "OK - LoRa FEM RX gain off");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
+2
View File
@@ -380,12 +380,14 @@ build_flags =
-D AUTO_SHUTDOWN_MILLIVOLTS=3400
-D BLE_DEBUG_LOGGING=1
-D OFFLINE_QUEUE_SIZE=256
-D ENABLE_WIFI_INTERFACE
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
build_src_filter = ${heltec_v4_tft.build_src_filter}
+<helpers/ui/ST7789LCDDisplay.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<helpers/esp32/*.cpp>
+<helpers/wifi/*.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
lib_deps =
+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 -2
View File
@@ -122,14 +122,14 @@ bool HeltecV4R8Board::handleCommand(const char* command, uint32_t sender_timesta
strcpy(reply, "Error: unsupported");
} else if (memcmp(&command[21], "on", 2) == 0) {
if (setLoRaFemLnaEnabled(true)) {
_prefs->setByKey("fem_rxgain", "1");
if (_prefs) _prefs->setByKey("fem_rxgain", "1");
strcpy(reply, "OK - LoRa FEM RX gain on");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
}
} else if (memcmp(&command[21], "off", 3) == 0) {
if (setLoRaFemLnaEnabled(false)) {
_prefs->setByKey("fem_rxgain", "0");
if (_prefs) _prefs->setByKey("fem_rxgain", "0");
strcpy(reply, "OK - LoRa FEM RX gain off");
} else {
strcpy(reply, "Error: failed to apply LoRa FEM RX gain");
+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
}
+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;
@@ -131,11 +131,13 @@ build_flags =
-D MAX_GROUP_CHANNELS=40
-D BLE_PIN_CODE=123456
-D OFFLINE_QUEUE_SIZE=256
-D ENABLE_WIFI_INTERFACE
; -D BLE_DEBUG_LOGGING=1
; -D MESH_PACKET_LOGGING=8
; -D MESH_DEBUG=1
build_src_filter = ${T_Beam_S3_Supreme_SX1262.build_src_filter}
+<helpers/esp32/*.cpp>
+<helpers/wifi/*.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
@@ -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
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more