Compare commits

..
Author SHA1 Message Date
tthandClaude Opus 5.5 0cc30308e9 Repo: ignore raw bench logs and the enclosure's STL/3MF exports
pub-release / release (push) Successful in 40m10s
Changelog: -
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:44:01 +01:00
tthandClaude Opus 5.5 7a7c894e2d Bench: opt-in nRF52 instrument for MCU awake time and CPU time per received packet
Changelog: -
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:30:27 +01:00
tthandClaude Opus 5.5 22700192bd Merge upstream/dev (1 commit: sec patch) [upstream-sync]
Changelog: Repeater, room server, sensor: an admin's CLI reply captured over the air can no longer be sent back to the node as a command (upstream security fix)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:53:23 +01:00
Liam Cottle eb8fdb5e06 Merge pull request #3914 from razzeee/feature/m1-empty-lists
Show when the companion has no adverts or sensor readings
2026-11-30 14:07:51 +13:00
Liam Cottle f88242f2a6 Merge pull request #3987 from jadonfloyd/wio-l1-overridable-joystick-pins
Make Wio Tracker L1 joystick pins overridable
2026-11-30 12:02:25 +13:00
Scott Powell c2036b9502 * sec patch 2026-11-29 16:06:00 +11:00
upstream-sync-bot fbbf4a8170 Merge upstream/dev (2 commits) [upstream-sync]
pub-release / release (push) Successful in 36m52s
2026-11-29 05:05:08 +00:00
ripplebiz 8603065de7 Merge pull request #3936 from meshcore-dev/sensor-gps-movement
Sensor GPS telemetry push
2026-11-29 10:51:44 +11:00
Jadon FloydandClaude Opus 5.5 716e76c731 Make Wio Tracker L1 joystick pins overridable
Wrap the JOYSTICK_* pin defines in variants/wio-tracker-l1/variant.h
in #ifndef guards so builds can remap them with -D flags, e.g. for
enclosures that mount the display rotated 90 degrees relative to the
joystick. No change to default behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XZSU585Bf7KxVsYxYZyfun
2026-11-27 22:50:37 -07:00
upstream-sync-bot 5a44b5ff52 Merge upstream/dev (3 commits) [upstream-sync]
pub-release / release (push) Successful in 41m13s
2026-11-28 05:05:09 +00:00
tthandClaude Opus 5.5 44f7566337 Docs: nRF52 sleep fixes re-measured at 3.3 V — CC310 insomnia +3.3 mA, DC/DC worth 0.6 mA
Changelog: -
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 02:42:26 +01:00
Liam Cottle bda1c586f1 Merge pull request #3945 from MarkRose/fix/contact-name-nul
Terminate contact names received from the companion app 🤖🤖
2026-11-28 10:29:02 +13:00
tthandClaude Opus 5.5 736691cbd2 CI: pub-release finds the previous release by its tag, not the stored target commit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:21:33 +01:00
tthandClaude Opus 5.5 540f87ca77 Repeater, room server, companion: SenseCAP Solar reads its battery voltage correctly again
pub-release / release (push) Successful in 41m4s
Changelog: SenseCAP Solar (repeater, room server, companion): the battery voltage reads correctly again; since the previous release it read 0.1-0.15 V high, so the low-voltage cutoff would have let the cell run lower.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:32:40 +01:00
upstream-sync-bot ba6f6cd073 Merge upstream/dev (2 commits) [upstream-sync]
pub-release / release (push) Canceled after 21m30s
2026-11-27 17:05:12 +00:00
tthandClaude Opus 5.5 14f5892033 Repeater, room server, sensor, companion: set commands refuse out-of-range or non-numeric values instead of saving them
Changelog: Repeater, room server, sensor, companion: `set tx`, `set radio`, `set freq` and other number settings now refuse a value that is out of range or not a number, instead of saving it and answering OK.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:33:42 +01:00
ripplebiz e730d2ecb2 Merge pull request #3950 from praguevara/fix-acl-admin-overwrite
Fix admin being overwritten when the client ACL is full of admins
2026-11-27 22:18:14 +11:00
Mark RoseandClaude Opus 5.5 3accaf358d Bound the contact name copy into the UI recent list
addToRecents() in the new and tiny companion UIs strcpy()s the contact
name into a 32-byte field. Names are terminated on receipt now, but use
a bounded copy here as well, like the other name copies in the UIs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:23:50 -06:00
Pablo Ramón Guevara 6ae61bbb40 fix bug where a login from a new identity silently removes an admin 2026-11-26 18:33:12 +01:00
Mark RoseandClaude Opus 5.5 e86ed1373b Terminate contact names received from the app
updateContactFromFrame() copies 32 name bytes from the companion frame
without terminating them, so an app (or a corrupt frame) can store a name
with no NUL. The UI then passes it to sprintf() into fixed-size origin
buffers. Terminate the name on receipt and use snprintf() in both UIs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:02:20 -06:00
Scott Powell b0fd8e6801 * special case when min_deltas has LPP_GPS value 2026-11-25 12:10:35 +11:00
razze 82bf0782f6 Show when the companion has no adverts or sensor readings
Skip empty slots when drawing recent adverts so the list starts at the top.
2026-11-23 03:35:31 +01:00
35 changed files with 664 additions and 99 deletions

No files matched your search

+5
View File
@@ -322,6 +322,11 @@ jobs:
# changelog against the newest older release that HEAD descends from
prev="" base=""
while read -r t c; do
# the tag, not the release's target_commitish: Gitea keeps the
# commitish from creation, and after a rewrite of the public
# history (26. 11. 2026) it named commits no longer in it -- no
# base was found and the notes listed the last 20 commits
c=$(git rev-parse -q --verify "refs/tags/$t^{commit}" 2>/dev/null || echo "$c")
if [ "$c" != "$SHA" ] && git merge-base --is-ancestor "$c" "$SHA" 2>/dev/null; then
prev=$t base=$c
break
+3
View File
@@ -31,3 +31,6 @@ ether.pid
# data z pochůzkových testů (.tth/tools/walk.sh fetch) — polohy, necommitovat
walk-data/
# raw bench data (measurement nights, watch logs): local only, results go to docs/
/logs/
+1 -1
View File
@@ -274,7 +274,7 @@ Refer to the node's manual for the correct settings to use.
- `set tx <dbm>`
**Parameters:**
- `dbm`: Power level in dBm (1-22)
- `dbm`: Power level in dBm (-9 to 22 on SX126x; meshcore-tth refuses values out of range or not taken by the radio)
**Set by build flag:** `LORA_TX_POWER`
+1 -1
View File
@@ -123,7 +123,7 @@ Radio parameters are common to all roles and handled by `CommonRadioPrefs`.
- `set tx <dbm>`
**Parameters:**
- `dbm`: Power level in dBm (1-22)
- `dbm`: Power level in dBm (-9 to 22 on SX126x; meshcore-tth refuses values out of range or not taken by the radio)
**Set by build flag:** `LORA_TX_POWER`
+82 -7
View File
@@ -171,6 +171,34 @@ a half-drained `rxlog`/`pktlog` page would otherwise wait for the next
connection event — the bridge drains those on a 2-minute duty cycle, so a slower
drain directly costs collected frames.
### CPU time per received packet (`PWR_DUTY_INSTRUMENT`)
A bench build with `-D PWR_DUTY_INSTRUMENT` (nRF52 only, nothing changes
without the flag) prints one line to the USB console every ~10 s:
```
PWRDUTY awake_ms=… asleep_ms=… wakes=… duty_permille=… pkt_us=… pkt_n=…
```
- `awake_ms`, `asleep_ms` and `duty_permille` are the time between a return
from `NRF52Board::sleep()` and the next entry into it, against the WFE span
inside it. This needs `powersaving on`: without it `sleep()` is never called.
- `wakes` counts the passes through `sleep()`. BLE and USB events wake the
core too, so the duty is not packet cost alone.
- `pkt_us` and `pkt_n` are the CPU time spent in
`Dispatcher::processRecvPacket()` (dedup, crypto, routing) and the number of
packets. They do not depend on background wakes. This is the work a filter
on the radio side could skip for a packet that is dropped anyway.
All counters are cumulative since boot, so take the difference between two
lines.
Measured on the XIAO x4, 24. 11. 2026, live mesh, about 440 packets/h (all
flood adverts): about **6.8 ms CPU per received packet**, mostly the Ed25519
check of the advert signature. The duty went from 0.05 % at rest to 0.13 %.
The awake time is a small part of a node's current; the radio's RX and the
SoftDevice dominate.
## A mast that runs flat: bootlock and cutoff
A panel that gets no direct sun in winter (remote-mast faces east, 11/2026:
@@ -254,14 +282,57 @@ connects to over BLE stays in it. Toggling the clear at runtime
on an already clean node changes nothing (+0.01 / +0.02 mA), because the state
is decided at boot.
**The same run again at 3.3 V without VBUS (27. 11. 2026).** Here x4 is fed on
its 3V3 pin at 3.25 V, so `bench duty` reads `vbus 0 usbd 0` and HFXO is
off. This is the closer match to a node on a cell. The setup was the same:
38 cells, two rounds, all of them valid. Baseline repeatability (detrended SD of
the base cells) was **0.009 / 0.015 mA**, so the threshold here is 0.03 mA.
The baseline is **6.90 mA** (22 mW, against 57 mW on the 5 V pin).
| boot with | before first BLE connection | after it |
|---|---|---|
| both fixes | 6.91 / 6.92 mA | 6.89 / 6.88 mA |
| no CC clear | **10.16 / 10.16 mA** | 6.91 / 6.89 mA |
| no CC clear, no late DC/DC (= old main) | **10.18 / 10.18 mA** | 6.89 / 6.94 mA |
| no late DC/DC | 6.90 / 6.91 mA | 6.93 / 6.92 mA |
The CC310 insomnia costs **+3.3 mA, almost half of the whole node**. Every
sample of those windows sits above 8.5 mA. The core wakes 14 900 times a
second, against 986, it is awake 79 % of the time, and `cc_pend` reads 1.
At this voltage **DC/DC is worth 0.6 mA**. `bench dcdc off` at runtime gives
+0.63 / +0.60 mA, and `A_like` (DC/DC off, CC clear off, nfcal 2 s) gives
+0.59 / +0.61 mA, the same thing. On the 5 V pin the same switch was below
resolution. The late re-enable still changes nothing, because `DCDCEN` reads 1
after every boot with or without it. So the regulator mode matters, and
SoftDevice simply does not turn it off.
| knob (3.3 V) | round 1 | round 2 |
|---|---|---|
| `bench dcdc off` | +0.63 mA | +0.60 mA |
| `bench cc off` (runtime) | +0.00 mA | −0.01 mA |
| `bench nfcal 2000` | −0.04 mA (one pair) | |
| `set radio.rxps max` | −2.30 mA | −2.30 mA |
| `set radio.rxps balanced` | −1.98 mA | −1.82 mA |
| `set radio.rxgain off` | −0.45 mA | −0.51 mA |
| `powersaving off` | +2.37 mA (one pair) | |
The rxps, rxgain and powersaving deltas match the 5 V run to within 0.3 mA.
In relative terms, rxps max now takes a third off the node. Reception from the
x1 witness matched what it sent in every cell (base 82 received for 72 sent;
x4 also hears other bench traffic). The witness again only detects a gross
loss, not a sensitivity loss.
**Measured to make no difference, kept anyway** (each below 0.1 mA):
- **DC/DC re-enabled after SoftDevice start** (`onBootComplete()`):
+0.02 / −0.10 mA at runtime, and no difference as a boot flag. The premise
that S140 puts `NRF_POWER` back to LDO did not hold on this board.
`DCDCEN` read 1 after every boot, with or without the late enable. The
late enable is kept as a harmless safeguard.
+0.02 / −0.10 mA at runtime on the 5 V pin, and no difference as a boot flag
at either voltage. The premise that S140 puts `NRF_POWER` back to LDO did not
hold on this board. `DCDCEN` read 1 after every boot, with or without the
late enable. The late enable is kept as a harmless safeguard. DC/DC itself
does matter at 3.3 V (see above).
- **Noise-floor calibration every 10 s instead of 2 s**
(`NOISE_FLOOR_CALIB_INTERVAL`): +0.08 mA, one pair.
(`NOISE_FLOOR_CALIB_INTERVAL`): +0.08 mA at 5 V and −0.04 mA at 3.3 V, one
pair each. That is at the edge of resolution and of no practical weight.
**Not measured** (compile-time or other hardware):
- **Avoid `NRF_SPIM3` (Nordic Errata 195)**: `[nrf52_base]` sets
@@ -278,8 +349,12 @@ is decided at boot.
- **SenseCAP Solar battery divider (`VBAT_ENABLE`)**: held `HIGH` (off) at boot
and set back to `HIGH` right after `getBattMilliVolts()`, instead of staying
`LOW`. `initiateShutdown()` still drives it `LOW` when it arms the LPCOMP
wake. Open question: with the divider off, the ADC pin may sit near VDD +
0.3 V on a full cell. This is yet to be checked with a meter on the board.
wake. It saves ~2.8 µA (4.2 V over 1.5 MOhm). With the old 10 ms settle the
reading came out 110-150 mV high (mast-three and second-mast after the OTA of
26.-27. 11. 2026, both at night, remote-mast without the change flat): the ADC
node starts high with the divider off. The settle is 100 ms now; still to be
checked against a meter, and whether the ADC pin sits near VDD + 0.3 V on a
full cell.
**Runtime knobs from the same night**, for comparison (paired deltas):
+17 -1
View File
@@ -106,12 +106,27 @@ stall watchdog", "Reboot into the bootloader" and "Why the board last reset".
| `dfu [uf2\|serial\|ota]` | *local only*: reboot into the bootloader -- UF2 drive (default), CDC port for `adafruit-nrfutil`, or BLE DFU |
| `fw ...` | `-ota` images only: admin-pushed firmware update, see [ota.md](ota.md) |
## Number arguments of `set` (all, and the companion's serial CLI)
Upstream parses the value of a `set` with `atoi()`/`atof()`: text became 0,
`300` became 44 in a one-byte setting, and the result was saved with `OK`. This
fork refuses a value that is not a number or lies outside the range and keeps
the old one (`Error, must be ...`). It applies to `set tx` (-9 up to the
board's `MAX_LORA_TX_POWER`, else 30, and saved only if the radio takes it:
SX1262 -9..22), `set radio` and `tempradio` (each field; the timeout 1-10080
min), `set freq`, `set lat`/`set lon`, `set flood.max`, `set
flood.max.unscoped`, `set flood.max.advert` (0-64), `set int.thresh` (0-255),
`set multi.acks` (0-1), `set path.hash.mode` (0-2), `set agc.reset.interval`
(0-1020), `set rxdelay`, `set txdelay`, `set direct.txdelay`, `set
adc.multiplier`, and on the companion `set pin`, `set adc.multiplier`, `set
tz.offset`. No exponent (`1e3`), no `nan`/`inf`.
## Diagnostics
| command | where | |
|---|---|---|
| `blink [n]` / `blink on\|off` | repeater | flash a spare LED (not the BLE or TX one) `n` times (default 6, max 999), or until `blink off` (gives up after 10 min); finds a board on a bench or a node on a mast |
| `txpwr [dBm]` | repeater | LoRa output power until reboot, with RadioLib's status (`set tx` saves and says OK even when the radio refused) |
| `txpwr [dBm]` | repeater | LoRa output power until reboot, with RadioLib's status; takes -9..30 |
| `i2c` | all | scan the I2C bus |
| `get chip` | nRF52 (repeater, room server, sensor) | the silicon (`nRF52840 AAD0`; variant `xxF0` and later = rev3) and `UICR.APPROTECT`: `open` means SWD can read the whole flash, keys included ([locked-bootloader.md](locked-bootloader.md)) |
| `dio1` | own build: `PIN_DIAG` | has the SX1262 raise TX_DONE and compares its IRQ register with the level on the DIO1 pin -- which end of a dead IRQ line is broken |
@@ -195,6 +210,7 @@ The ones that change what a node does; set in `platformio.ini` /
| `LOGIN_FAIL_MAX`, `LOGIN_FAIL_SECS` | `4`, `180` (s) | after that many wrong passwords in the window no password is checked until it ends (an admin already in the ACL always gets in) |
| `NRF52_POWER_MANAGEMENT`, `PWRMGT_RUNTIME` | upstream: off; on in `SenseCap_Solar_repeater` (the masts) | boot protection, and with `PWRMGT_RUNTIME` the runtime `pwr.bootlock` / `pwr.cutoff` above |
| `PWRMGT_BOOTLOCK_DEFAULT`, `PWRMGT_CUTOFF_DEFAULT` | `PWRMGT_VOLTAGE_BOOTLOCK` (SenseCAP 3300), `0` (mV) | thresholds for a node without `/pwr_guard` |
| `PWR_DUTY_INSTRUMENT` | unset | bench only, nRF52: every ~10 s a `PWRDUTY` line on the USB console with the time the MCU was awake and asleep, its wakes, and the CPU time spent on received packets. See [power.md](power.md#cpu-time-per-received-packet-pwr_duty_instrument) |
Prefs saved on the node override the build defaults: a reflash keeps what a
node already has; only a new node or one after `erase` takes them.
+12 -5
View File
@@ -5,6 +5,7 @@
#include <WiFi.h>
#endif
#include <Mesh.h>
#include <helpers/CliArgs.h>
#define CMD_APP_START 1
#define CMD_SEND_TXT_MSG 2
@@ -202,6 +203,7 @@ void MyMesh::updateContactFromFrame(ContactInfo &contact, uint32_t& last_mod, co
memcpy(contact.out_path, &frame[i], MAX_PATH_SIZE);
i += MAX_PATH_SIZE;
memcpy(contact.name, &frame[i], 32);
contact.name[sizeof(contact.name) - 1] = 0; // the app is not trusted to NUL-terminate
i += 32;
memcpy(&contact.last_advert_timestamp, &frame[i], 4);
i += 4;
@@ -2209,7 +2211,12 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
#endif
if (memcmp(command, "set pin ", 8) == 0) {
_prefs.ble_pin = atoi(&command[8]);
long pin; // atoi(): "abc" was PIN 0, i.e. a random one
if (!cli_args::parseInt(&command[8], 0, 999999, &pin)) {
strcpy(reply, "Error, PIN must be 0-999999");
return true;
}
_prefs.ble_pin = pin;
savePrefs();
sprintf(reply, "> pin is now %06d", _prefs.ble_pin);
return true;
@@ -2302,8 +2309,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
}
if (memcmp(command, "set adc.multiplier ", 19) == 0) { // same as CommonCLI
float mult = atof(&command[19]);
if (mult < 0.0f || mult > 10.0f) {
float mult = 0;
if (!cli_args::parseFloat(&command[19], 0.0f, 10.0f, &mult)) {
strcpy(reply, "Error, must be from 0 to 10");
} else if (board.setAdcMultiplier(mult)) {
_prefs.adc_multiplier = mult;
@@ -2334,8 +2341,8 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp, char*
return true;
}
if (memcmp(command, "set tz.offset ", 14) == 0) {
float tz = atof(&command[14]);
if (tz < -12 || tz > 14) {
float tz = 0;
if (!cli_args::parseFloat(&command[14], -12.0f, 14.0f, &tz)) {
strcpy(reply, "Error, must be from -12 to +14");
} else {
_prefs.tz_offset = tz;
+11 -3
View File
@@ -1,6 +1,7 @@
#include "MyMesh.h"
#include <algorithm>
#include <helpers/sensors/LPPDataHelpers.h>
#include <helpers/UTF8Helpers.h>
/* ------------------------------ Config -------------------------------- */
@@ -397,13 +398,13 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
}
client = acl.putClient(sender, 0); // add to contacts (if not already known)
if (client == NULL) return 0;
if (sender_timestamp <= client->last_timestamp) {
MESH_DEBUG_PRINTLN("Possible login replay attack!");
return 0; // FATAL: client table is full -OR- replay attack
}
MESH_DEBUG_PRINTLN("Login success!");
client->last_timestamp = sender_timestamp;
client->last_activity = getRTCClock()->getCurrentTime();
client->permissions &= ~0x03;
client->permissions |= perms;
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
@@ -413,6 +414,7 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
}
}
client->last_activity = getRTCClock()->getCurrentTime();
if (is_flood) {
client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
@@ -1251,12 +1253,12 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
uint32_t timestamp;
memcpy(&timestamp, data, 4);
if (timestamp > client->last_timestamp) { // prevent replay attacks
if (timestamp > client->last_req_timestamp) { // prevent replay attacks
acl.persistTimestamp(client, timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
if (reply_len == 0) return; // invalid command
client->last_timestamp = timestamp;
client->last_req_timestamp = timestamp;
client->last_activity = getRTCClock()->getCurrentTime();
if (packet->isRouteFlood()) {
@@ -1285,6 +1287,11 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
} else if (!mesh::isValidUtf8TextAndPadding(&data[5], len - 5)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid text payload! (id prefix: %02X:%02X)", client->id.pub_key[0], client->id.pub_key[1]);
_err_flags |= ERR_EVENT_DIAG1; // report in next Get Stats
} else if (_reply_echo.matches(data, 5 + strnlen((const char *)&data[5], len - 5))) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: text is our own CLI reply");
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
bool is_retry = (sender_timestamp == client->last_timestamp);
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
@@ -1328,6 +1335,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
}
memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
_reply_echo.note(temp, 5 + text_len);
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
if (reply) {
+2
View File
@@ -28,6 +28,7 @@
#include <helpers/ArduinoHelpers.h>
#include <helpers/ClientACL.h>
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
#include <helpers/ReplyEchoGuard.h>
#include <helpers/CommonCLI.h>
#include <helpers/IdentityStore.h>
#include <helpers/SimpleMeshTables.h>
@@ -197,6 +198,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
NodePrefs _prefs;
ClientACL acl;
LoginGuard login_guard; // CUSTOM (TeTeHacko)
ReplyEchoGuard _reply_echo;
CommonCLI _cli;
uint8_t reply_data[MAX_PACKET_PAYLOAD];
uint8_t reply_path[MAX_PATH_SIZE];
+7 -1
View File
@@ -3,6 +3,7 @@
#include "MyMesh.h"
#include <helpers/NodeMaintenance.h>
#include <helpers/CliArgs.h>
// ===========================================================================
// CUSTOM (TeTeHacko): `blink [n]` -- make THIS board flash its LED on demand,
@@ -625,7 +626,12 @@ MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock,
bool txPwrHandleCommand(const char* command, char* reply) {
if (memcmp(command, "txpwr", 5) != 0 || (command[5] != 0 && command[5] != ' ')) return false;
if (command[5] == ' ') {
int dbm = atoi(&command[6]);
long dbm_l; // atoi() into int8_t: "250" went out as -6 dBm, "abc" as 0
if (!cli_args::parseInt(&command[6], -9, 30, &dbm_l)) {
strcpy(reply, "ERR - txpwr <-9..30 dBm>");
return true;
}
int dbm = dbm_l;
radio_driver.setTxPower((int8_t) dbm);
int16_t st = radio_driver.getLastTxPowerStatus();
sprintf(reply, "%s - txpwr %d dBm, RadioLib status %d%s", st == RADIOLIB_ERR_NONE ? "OK" : "ERR",
+12 -3
View File
@@ -1,4 +1,5 @@
#include "MyMesh.h"
#include <helpers/UTF8Helpers.h>
#include <algorithm>
#define REPLY_DELAY_MILLIS 1500
@@ -378,6 +379,8 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
}
client = acl.putClient(sender, 0); // add to known clients (if not already known)
if (client == NULL) return;
if (sender_timestamp <= client->last_timestamp) {
MESH_DEBUG_PRINTLN("possible replay attack!");
return;
@@ -388,7 +391,6 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
client->extra.room.pending_ack = 0;
client->extra.room.push_failures = 0;
client->last_activity = getRTCClock()->getCurrentTime();
client->permissions &= ~0x03;
client->permissions |= perm;
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
@@ -396,6 +398,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
}
client->last_activity = getRTCClock()->getCurrentTime();
if (packet->isRouteFlood()) {
client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
@@ -467,6 +470,11 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
} else if (!mesh::isValidUtf8TextAndPadding(&data[5], len - 5)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid text payload! (id prefix: %02X:%02X)", client->id.pub_key[0], client->id.pub_key[1]);
_err_flags |= ERR_EVENT_DIAG1; // report in next Get Stats
} else if (_reply_echo.matches(data, 5 + strnlen((const char *)&data[5], len - 5))) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: text is our own CLI reply");
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
bool is_retry = (sender_timestamp == client->last_timestamp);
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
@@ -542,6 +550,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
now++;
}
memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
_reply_echo.note(temp, 5 + text_len);
// calc expected ACK reply
// mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key,
@@ -562,11 +571,11 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
} else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
uint32_t sender_timestamp;
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
if (sender_timestamp < client->last_timestamp) { // prevent replay attacks
if (sender_timestamp < client->last_req_timestamp) { // prevent replay attacks
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
} else {
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
client->last_timestamp = sender_timestamp;
client->last_req_timestamp = sender_timestamp;
uint32_t now = getRTCClock()->getCurrentTime();
client->last_activity = now; // <-- THIS will keep client connection alive
+2
View File
@@ -21,6 +21,7 @@
#include <helpers/StatsFormatHelper.h>
#include <helpers/ClientACL.h>
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
#include <helpers/ReplyEchoGuard.h>
#include <helpers/RegionMap.h>
#include <helpers/RoutingPolicy.h>
#include <RTClib.h>
@@ -100,6 +101,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
RegionMap region_map, temp_map;
ClientACL acl;
LoginGuard login_guard; // CUSTOM (TeTeHacko)
ReplyEchoGuard _reply_echo;
CommonCLI _cli;
unsigned long dirty_contacts_expiry;
uint8_t reply_data[MAX_PACKET_PAYLOAD];
+61 -14
View File
@@ -1,6 +1,7 @@
#include "SensorMesh.h"
#include <helpers/RoutingPolicy.h>
#include <helpers/sensors/LPPDataHelpers.h>
#include <helpers/UTF8Helpers.h>
/* ------------------------------ Config -------------------------------- */
@@ -81,14 +82,26 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) {
/* --------------------- Cayenne LPP helpers ----------------------------*/
static const uint8_t* findTelemValueRaw(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) {
uint8_t i = 0;
while (i + 2 < size) {
uint8_t ch = buf[i++]; // Get channel #
uint8_t t = buf[i++]; // Get data type
uint8_t sz = LPPData::getDataSize(t);
if (ch == channel && t == type) return &buf[i];
i += sz; // skip
}
return NULL; // not found
}
static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type, float def_value) {
uint8_t i = 0;
while (i + 2 < size) {
// Get channel #
uint8_t ch = buf[i++];
// Get data type
uint8_t t = buf[i++];
uint8_t ch = buf[i++]; // Get channel #
uint8_t t = buf[i++]; // Get data type
uint8_t sz = LPPData::getDataSize(t);
if (ch == channel && t == type) {
@@ -101,6 +114,8 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u
/* ------------------ end Cayenne LPP helpers ----------------------*/
#include <helpers/GPSLocHelper.h>
bool SensorMesh::telemHasChanged(ClientInfo* c) {
auto buf = telemetry.getBuffer();
uint8_t size = telemetry.getSize();
@@ -112,11 +127,29 @@ bool SensorMesh::telemHasChanged(ClientInfo* c) {
uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type
uint8_t sz = LPPData::getDataSize(t);
float min_delta = LPPData::getFloat(&c->extra.sensor.min_deltas[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
float pv = LPPData::getFloat(&c->extra.sensor.prev_telem[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
if (t == LPP_GPS) { // special case for movement detection
// NOTE: actual min_delta is NOT LPP_GPS but should be a LPP_DISTANCE value (4 byte, unsigned)
float min_distance = LPPData::getFloat(&c->extra.sensor.min_deltas[i + 2], LPPData::getDataSize(LPP_DISTANCE), LPPData::getMultiplier(LPP_DISTANCE), false);
float prev_lat, prev_lon, _alt;
LPPData::readGPS(&c->extra.sensor.prev_telem[i + 2], prev_lat, prev_lon, _alt);
float curr_lat, curr_lon;
{
const uint8_t* curr = findTelemValueRaw(buf, size, ch, t);
if (curr) {
LPPData::readGPS(curr, curr_lat, curr_lon, _alt);
} else {
curr_lat = curr_lon = 0.0f;
}
}
float dist = GPSLocHelper::calcGreatArcMeters(prev_lat, prev_lon, curr_lat, curr_lon);
if (dist > min_distance) changed = true; // Yes, has Moved!
} else {
float min_delta = LPPData::getFloat(&c->extra.sensor.min_deltas[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
float pv = LPPData::getFloat(&c->extra.sensor.prev_telem[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
float v = findTelemValue(buf, size, ch, t, 0.0f);
if (abs(v - pv) > min_delta) changed = true; // Yes, has changed
float v = findTelemValue(buf, size, ch, t, 0.0f);
if (abs(v - pv) > min_delta) changed = true; // Yes, has changed
}
i += 2 + sz; // skip
}
@@ -130,10 +163,17 @@ bool SensorMesh::telemHasChanged(ClientInfo* c) {
c->extra.sensor.prev_telem[i] = ch;
c->extra.sensor.prev_telem[i + 1] = t;
float v = findTelemValue(buf, size, ch, t, 0.0f);
LPPData::putFloat(&c->extra.sensor.prev_telem[i + 2], v, sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
if (t == LPP_GPS) { // special case for GPS data
const uint8_t* v_ptr = findTelemValueRaw(buf, size, ch, t);
if (v_ptr) {
memcpy(&c->extra.sensor.prev_telem[i + 2], v_ptr, 9); // LPP_GPS format: 3 x 3 byte values
} else {
memset(&c->extra.sensor.prev_telem[i + 2], 0, 9);
}
} else {
float v = findTelemValue(buf, size, ch, t, 0.0f);
LPPData::putFloat(&c->extra.sensor.prev_telem[i + 2], v, sz, LPPData::getMultiplier(t), LPPData::isSigned(t));
}
i += 2 + sz; // skip
}
}
@@ -392,19 +432,20 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t*
}
client = acl.putClient(sender, PERM_RECV_ALERTS_HI | PERM_RECV_ALERTS_LO); // add to contacts (if not already known)
if (client == NULL) return 0;
if (sender_timestamp <= client->last_timestamp) {
MESH_DEBUG_PRINTLN("Possible login replay attack!");
return 0; // FATAL: client table is full -OR- replay attack
}
MESH_DEBUG_PRINTLN("Login success!");
client->last_timestamp = sender_timestamp;
client->last_activity = getRTCClock()->getCurrentTime();
client->permissions |= PERM_ACL_ADMIN;
acl.persistTimestamp(client, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): admin only, so after the role
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
}
client->last_activity = getRTCClock()->getCurrentTime();
if (is_flood) {
client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
@@ -658,7 +699,12 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
if (sender_timestamp > from->last_timestamp) { // prevent replay attacks
if (!mesh::isValidUtf8TextAndPadding(&data[5], len - 5)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid text payload! (id prefix: %02X:%02X)", from->id.pub_key[0], from->id.pub_key[1]);
_err_flags |= ERR_EVENT_DIAG1; // report in next Get Stats
} else if (_reply_echo.matches(data, 5 + strnlen((const char *)&data[5], len - 5))) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: text is our own CLI reply");
} else if (sender_timestamp > from->last_timestamp) { // prevent replay attacks
acl.persistTimestamp(from, sender_timestamp, getRTCClock()->getCurrentTime()); // CUSTOM (TeTeHacko): before acting
if (flags == TXT_TYPE_PLAIN) {
bool handled = handleIncomingMsg(*from, sender_timestamp, &data[5], flags, len - 5);
@@ -697,6 +743,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
}
memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
temp[4] = (TXT_TYPE_CLI_DATA << 2);
_reply_echo.note(temp, 5 + text_len);
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from->id, secret, temp, 5 + text_len);
if (reply) {
+2
View File
@@ -23,6 +23,7 @@
#include <helpers/StatsFormatHelper.h>
#include <helpers/ClientACL.h>
#include <helpers/LoginGuard.h> // CUSTOM (TeTeHacko)
#include <helpers/ReplyEchoGuard.h>
#include <helpers/RegionMap.h>
#include <RTClib.h>
#include <target.h>
@@ -149,6 +150,7 @@ private:
NodePrefs _prefs;
ClientACL acl;
LoginGuard login_guard; // CUSTOM (TeTeHacko)
ReplyEchoGuard _reply_echo;
CommonCLI _cli;
uint8_t reply_data[MAX_PACKET_PAYLOAD];
unsigned long dirty_contacts_expiry;
+2
View File
@@ -1 +1,3 @@
stl/
*.stl
*.3mf
+17
View File
@@ -6,6 +6,16 @@
#include <math.h>
#ifdef PWR_DUTY_INSTRUMENT
// CUSTOM (TeTeHacko): bench instrument. Pure CPU time spent processing a received
// packet (dedup + crypto + routing), independent of BLE/USB background wakes --
// unlike the sleep-duty measure. This is the work a radio-side filter could skip
// for a dropped packet. Printed by NRF52Board::sleep() (extern below).
#include <Arduino.h>
uint64_t g_pkt_proc_us = 0;
uint32_t g_pkt_proc_count = 0;
#endif
namespace mesh {
#define MAX_RX_DELAY_MILLIS 32000 // 32 seconds
@@ -273,6 +283,9 @@ void Dispatcher::checkRecv() {
}
void Dispatcher::processRecvPacket(Packet* pkt) {
#ifdef PWR_DUTY_INSTRUMENT
uint32_t _pwr_t0 = micros();
#endif
DispatcherAction action = onRecvPacket(pkt);
if (action == ACTION_RELEASE) {
_mgr->free(pkt);
@@ -284,6 +297,10 @@ void Dispatcher::processRecvPacket(Packet* pkt) {
_mgr->queueOutbound(pkt, priority, futureMillis(_delay));
}
#ifdef PWR_DUTY_INSTRUMENT
g_pkt_proc_us += (uint32_t)(micros() - _pwr_t0);
g_pkt_proc_count++;
#endif
}
void Dispatcher::checkSend() {
+1
View File
@@ -121,6 +121,7 @@ typedef uint32_t DispatcherAction;
#ifndef MESH_TX_RETRIES
#define MESH_TX_RETRIES 3
#endif
#define ERR_EVENT_DIAG1 (1 << 8) // role-specific error flag
/**
* \brief The low-level task that manages detecting incoming Packets, and the queueing
+5 -1
View File
@@ -1,5 +1,6 @@
#include <helpers/BaseChatMesh.h>
#include <Utils.h>
#include <helpers/UTF8Helpers.h>
#ifndef SERVER_RESPONSE_DELAY
#define SERVER_RESPONSE_DELAY 300
@@ -247,7 +248,10 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
// len can be > original length, but 'text' will be padded with zeroes
data[len] = 0; // need to make a C string again, with null terminator
if (flags == TXT_TYPE_PLAIN) {
size_t text_ofs = (flags == TXT_TYPE_SIGNED_PLAIN) ? 9 : 5; // signed text starts after 4-byte sender prefix
if (len < text_ofs || !mesh::isValidUtf8TextAndPadding(&data[text_ofs], len - text_ofs)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid text payload!");
} else if (flags == TXT_TYPE_PLAIN) {
from.lastmod = getRTCClock()->getCurrentTime(); // update last heard time
onMessageRecv(from, packet, sender_timestamp, (const char *) &data[5]); // let UI know
+56
View File
@@ -0,0 +1,56 @@
#pragma once
// CUSTOM (TeTeHacko): strict number arguments for CLI `set` commands.
//
// atoi()/atof() take any text: "abc" is 0, "300" goes into a uint8_t as 44,
// and "nan" is a float that no range check refuses (under -ffast-math, which
// the nRF52 builds use, the compiler may even fold that check away). The set
// commands then saved the result and answered "OK" -- `set tx 30` on an
// SX1262, `set freq abc` (150 MHz after the next boot's clamp), `set flood.max
// 300` (44). These helpers accept a whole number (or decimal) in a range and
// nothing else: optional surrounding white space and sign, digits, and for the
// float a '.' and fraction. No exponent, no hex, no trailing text.
#include <ctype.h>
#include <stdlib.h>
namespace cli_args {
// Returns true and sets *out when `s` is an integer in [lo, hi].
inline bool parseInt(const char* s, long lo, long hi, long* out) {
if (!s) return false;
while (isspace((unsigned char)*s)) s++;
const char* p = s;
if (*p == '+' || *p == '-') p++;
if (!isdigit((unsigned char)*p)) return false;
char* end;
long v = strtol(s, &end, 10);
while (isspace((unsigned char)*end)) end++;
if (*end != 0) return false;
if (v < lo || v > hi) return false;
*out = v;
return true;
}
// Returns true and sets *out when `s` is a decimal number in [lo, hi].
inline bool parseFloat(const char* s, float lo, float hi, float* out) {
if (!s) return false;
while (isspace((unsigned char)*s)) s++;
const char* p = s;
if (*p == '+' || *p == '-') p++;
bool digits = false;
while (isdigit((unsigned char)*p)) { p++; digits = true; }
if (*p == '.') {
p++;
while (isdigit((unsigned char)*p)) { p++; digits = true; }
}
if (!digits) return false;
const char* rest = p;
while (isspace((unsigned char)*rest)) rest++;
if (*rest != 0) return false; // exponent, "nan", "inf" or trailing text
float v = strtof(s, nullptr);
if (!(v >= lo && v <= hi)) return false;
*out = v;
return true;
}
} // namespace cli_args
+5 -3
View File
@@ -115,7 +115,7 @@ void ClientACL::loadTimestamps() {
}
}
for (int i = 0; i < num_clients; i++) {
clients[i].last_timestamp = clients[i].saved_timestamp;
clients[i].last_timestamp = clients[i].last_req_timestamp = clients[i].saved_timestamp;
}
}
@@ -219,7 +219,7 @@ ClientInfo* ClientACL::getClient(const uint8_t* pubkey, int key_len) {
ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
uint32_t min_time = 0xFFFFFFFF;
ClientInfo* oldest = &clients[MAX_CLIENTS - 1];
ClientInfo* oldest = NULL;
for (int i = 0; i < num_clients; i++) {
if (id.matches(clients[i].id)) return &clients[i]; // already known
if (!clients[i].isAdmin() && clients[i].last_activity < min_time) {
@@ -232,6 +232,7 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
if (num_clients < MAX_CLIENTS) {
c = &clients[num_clients++];
} else {
if (oldest == NULL) return NULL; // every entry is an admin, so don't evict
c = oldest; // evict least active contact
orphanTimestamp(c);
}
@@ -241,7 +242,7 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
c->out_path_len = OUT_PATH_UNKNOWN;
for (int i = 0; i < _num_ts_orphans; i++) { // known before: its replay floor comes back
if (memcmp(_ts_orphans[i].prefix, id.pub_key, ACL_TS_PREFIX) == 0) {
c->saved_timestamp = c->last_timestamp = _ts_orphans[i].ts;
c->saved_timestamp = c->last_timestamp = c->last_req_timestamp = _ts_orphans[i].ts;
_num_ts_orphans--;
memmove(&_ts_orphans[i], &_ts_orphans[i + 1], (_num_ts_orphans - i) * sizeof(TsOrphan));
break;
@@ -268,6 +269,7 @@ bool ClientACL::applyPermissions(const mesh::LocalIdentity& self_id, const uint8
mesh::Identity id(pubkey);
c = putClient(id, 0);
if (c == NULL) return false; // couldn't put client
c->permissions = perms; // update their permissions
self_id.calcSharedSecret(c->shared_secret, pubkey);
+2 -1
View File
@@ -20,6 +20,7 @@ struct ClientInfo {
uint8_t shared_secret[PUB_KEY_SIZE];
uint32_t last_timestamp; // by THEIR clock (restored from /s_acl_ts* on boot)
uint32_t saved_timestamp; // last_timestamp as last written to /s_acl_ts*
uint32_t last_req_timestamp; // REQ only (upstream split); restored from saved_timestamp too
uint32_t last_activity; // by OUR clock (transient)
union {
struct {
@@ -86,7 +87,7 @@ public:
void persistTimestamp(ClientInfo* c, uint32_t sender_timestamp, uint32_t now);
ClientInfo* getClient(const uint8_t* pubkey, int key_len);
ClientInfo* putClient(const mesh::Identity& id, uint8_t init_perms);
ClientInfo* putClient(const mesh::Identity& id, uint8_t init_perms); // returns NULL if table is full and all entries are admins
bool applyPermissions(const mesh::LocalIdentity& self_id, const uint8_t* pubkey, int key_len, uint8_t perms);
int getNumClients() const { return num_clients; }
+47 -24
View File
@@ -1,4 +1,5 @@
#include <Arduino.h>
#include "CliArgs.h"
#include "CommonCLI.h"
#include "TxtDataHelpers.h"
#include "AdvertDataHelpers.h"
@@ -354,12 +355,14 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
StrHelper::strncpy(tmp, &command[10], sizeof(tmp));
const char *parts[5];
int num = mesh::Utils::parseTextParts(tmp, parts, 5);
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f;
uint8_t sf = num > 2 ? atoi(parts[2]) : 0;
uint8_t cr = num > 3 ? atoi(parts[3]) : 0;
int temp_timeout_mins = num > 4 ? atoi(parts[4]) : 0;
if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f && temp_timeout_mins > 0) {
float freq = 0, bw = 0;
long sf_l = 0, cr_l = 0, mins_l = 0;
if (num == 5 && cli_args::parseFloat(parts[0], 150.0f, 2500.0f, &freq) &&
cli_args::parseFloat(parts[1], 7.0f, 500.0f, &bw) &&
cli_args::parseInt(parts[2], 5, 12, &sf_l) && cli_args::parseInt(parts[3], 5, 8, &cr_l) &&
cli_args::parseInt(parts[4], 1, 10080, &mins_l)) {
uint8_t sf = sf_l, cr = cr_l;
int temp_timeout_mins = mins_l;
_callbacks->applyTempRadioParams(freq, bw, sf, cr, temp_timeout_mins);
sprintf(reply, "OK - temp params for %d mins", temp_timeout_mins);
} else {
@@ -733,18 +736,28 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
savePrefs();
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");
float v;
if (cli_args::parseFloat(&config[4], -90.0f, 90.0f, &v)) {
_prefs->node_lat = v;
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Error, must be -90..90");
}
} else if (memcmp(config, "lon ", 4) == 0) {
_prefs->node_lon = atof(&config[4]);
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
float v;
if (cli_args::parseFloat(&config[4], -180.0f, 180.0f, &v)) {
_prefs->node_lon = v;
_prefs->getGpsPrefs()->applyGuardReference(*_sensors);
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Error, must be -180..180");
}
} else if (memcmp(config, "flood.max.unscoped ", 19) == 0) {
uint8_t m = atoi(&config[19]);
if (m <= 64) {
long m; // was uint8_t = atoi(): "300" became 44 and passed
if (cli_args::parseInt(&config[19], 0, 64, &m)) {
_prefs->flood_max_unscoped = m;
savePrefs();
strcpy(reply, "OK");
@@ -752,8 +765,8 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, "Error, max 64");
}
} else if (memcmp(config, "flood.max.advert ", 17) == 0) {
uint8_t m = atoi(&config[17]);
if (m <= 64) {
long m; // was uint8_t = atoi(): "300" became 44 and passed
if (cli_args::parseInt(&config[17], 0, 64, &m)) {
_prefs->flood_max_advert = m;
savePrefs();
strcpy(reply, "OK");
@@ -761,8 +774,8 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, "Error, max 64");
}
} else if (memcmp(config, "flood.max ", 10) == 0) {
uint8_t m = atoi(&config[10]);
if (m <= 64) {
long m; // was uint8_t = atoi(): "300" became 44 and passed
if (cli_args::parseInt(&config[10], 0, 64, &m)) {
_prefs->flood_max = m;
savePrefs();
strcpy(reply, "OK");
@@ -800,9 +813,14 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, "OK");
}
} else if (sender_timestamp == 0 && memcmp(config, "freq ", 5) == 0) {
_prefs->freq = atof(&config[5]);
savePrefs();
strcpy(reply, "OK - reboot to apply");
float f; // was atof(): "abc" saved 0, i.e. 150 MHz after the next boot's clamp
if (cli_args::parseFloat(&config[5], 150.0f, 2500.0f, &f)) {
_prefs->freq = f;
savePrefs();
strcpy(reply, "OK - reboot to apply");
} else {
strcpy(reply, "Error, must be 150-2500 MHz");
}
#ifdef WITH_BRIDGE
} else if (memcmp(config, "bridge.enabled ", 15) == 0) {
_prefs->bridge_enabled = memcmp(&config[15], "on", 2) == 0;
@@ -885,7 +903,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
strcpy(reply, "on - shows on next advert");
}
} else if (memcmp(config, "adc.multiplier ", 15) == 0) {
_prefs->adc_multiplier = atof(&config[15]);
float m;
if (!cli_args::parseFloat(&config[15], 0.0f, 10.0f, &m)) {
strcpy(reply, "Error, must be 0-10 (0 = board default)");
return;
}
_prefs->adc_multiplier = m;
if (_board->setAdcMultiplier(_prefs->adc_multiplier)) {
savePrefs();
if (_prefs->adc_multiplier == 0.0f) {
+66 -23
View File
@@ -1,4 +1,5 @@
#include "CommonRadioPrefs.h"
#include "CliArgs.h"
#include "TxtDataHelpers.h"
#include "Utils.h"
#include "target.h"
@@ -30,6 +31,19 @@ RxPowerSavingControl* rxpsControl() {
}
#endif
// CUSTOM (TeTeHacko): the radio's verdict on the last setTxPower(), where the
// driver keeps one (RadioLibWrapper); other drivers (ESP-NOW) count as accepted.
template <class R>
auto lastTxPowerStatus(R& r, int) -> decltype(r.getLastTxPowerStatus()) { return r.getLastTxPowerStatus(); }
template <class R>
int16_t lastTxPowerStatus(R&, long) { return 0; }
#ifdef MAX_LORA_TX_POWER
constexpr long TX_POWER_MAX = MAX_LORA_TX_POWER;
#else
constexpr long TX_POWER_MAX = 30; // the same ceiling as the prefs load clamp
#endif
} // namespace
#ifdef WITH_RX_POWERSAVING
@@ -62,12 +76,12 @@ bool CommonRadioPrefs::getByKey(const char* key, char* value, size_t max_len) {
}
bool CommonRadioPrefs::setByKey(const char* key, const char* value) {
if (strcmp(key, "fem_rxgain") == 0) {
setFEMRxGain(atoi(value));
setFEMRxGain(atoi(value) ? 1 : 0); // boolean, as the prefs load clamps it
markDirty();
return true;
}
if (strcmp(key, "fem_txgain") == 0) {
setFEMTxGain(atoi(value));
setFEMTxGain(atoi(value) ? 1 : 0); // boolean, as the prefs load clamps it
markDirty();
return true;
}
@@ -111,11 +125,12 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
strcpy(tmp, &command[10]);
const char *parts[4];
int num = mesh::Utils::parseTextParts(tmp, parts, 4);
float freq = num > 0 ? strtof(parts[0], nullptr) : 0.0f;
float bw = num > 1 ? strtof(parts[1], nullptr) : 0.0f;
uint8_t sf = num > 2 ? atoi(parts[2]) : 0;
uint8_t cr = num > 3 ? atoi(parts[3]) : 0;
if (freq >= 150.0f && freq <= 2500.0f && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7.0f && bw <= 500.0f) {
float freq = 0, bw = 0;
long sf_l = 0, cr_l = 0;
if (num == 4 && cli_args::parseFloat(parts[0], 150.0f, 2500.0f, &freq) &&
cli_args::parseFloat(parts[1], 7.0f, 500.0f, &bw) &&
cli_args::parseInt(parts[2], 5, 12, &sf_l) && cli_args::parseInt(parts[3], 5, 8, &cr_l)) {
uint8_t sf = sf_l, cr = cr_l;
setSpreadFactor(sf);
setCodingRate(cr);
setFreq(freq);
@@ -186,8 +201,13 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set int.thresh ", 15) == 0) {
setIntThresh(atoi(&command[15]));
strcpy(reply, "OK");
long t;
if (cli_args::parseInt(&command[15], 0, 255, &t)) {
setIntThresh(t);
strcpy(reply, "OK");
} else {
strcpy(reply, "Error, must be 0-255");
}
return true;
}
@@ -221,8 +241,23 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set tx ", 7) == 0) {
setTxPower(atoi(&command[7]));
radio_driver.setTxPower(getTxPower());
// CUSTOM (TeTeHacko): was atoi() straight into the prefs and "OK" -- out of
// range or not a number got saved, and the radio could refuse it silently
// (SX1262 takes -9..22 and keeps its old power). Only a power the radio
// took is saved now.
long dbm;
if (!cli_args::parseInt(&command[7], -9, TX_POWER_MAX, &dbm)) {
sprintf(reply, "Error, must be -9..%d", (int)TX_POWER_MAX);
return true;
}
int8_t old_dbm = getTxPower();
radio_driver.setTxPower((int8_t)dbm);
if (lastTxPowerStatus(radio_driver, 0) != 0) {
radio_driver.setTxPower(old_dbm);
sprintf(reply, "Error, radio refuses %d dBm (kept %d)", (int)dbm, (int)old_dbm);
return true;
}
setTxPower((int8_t)dbm);
strcpy(reply, "OK");
return true;
}
@@ -232,8 +267,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set rxdelay ", 12) == 0) {
float db = atof(&command[12]);
if (db >= 0 && db <= 20.0f) {
float db;
if (cli_args::parseFloat(&command[12], 0, 20.0f, &db)) {
setRxDelay(db);
strcpy(reply, "OK");
} else {
@@ -247,8 +282,11 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set agc.reset.interval ", 23) == 0) {
int secs = atoi(&command[23]);
secs = constrain(secs, 0, 255 * 4);
long secs;
if (!cli_args::parseInt(&command[23], 0, 255 * 4, &secs)) {
strcpy(reply, "Error, must be 0-1020");
return true;
}
setAgcResetInt((uint16_t) secs);
sprintf(reply, "OK - interval rounded to %d", (uint32_t) getAgcResetInt());
return true;
@@ -260,8 +298,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
}
if (memcmp(command, "set path.hash.mode ", 19) == 0) {
const char* config = command + 19;
uint8_t mode = atoi(config);
if (mode < 3) {
long mode;
if (cli_args::parseInt(config, 0, 2, &mode)) {
setHashMode(mode);
strcpy(reply, "OK");
} else {
@@ -275,8 +313,13 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set multi.acks ", 15) == 0) {
setMultiAcks(atoi(&command[15]));
strcpy(reply, "OK");
long n;
if (cli_args::parseInt(&command[15], 0, 1, &n)) {
setMultiAcks(n);
strcpy(reply, "OK");
} else {
strcpy(reply, "Error, must be 0 or 1");
}
return true;
}
@@ -285,8 +328,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set txdelay ", 12) == 0) {
float f = atof(&command[12]);
if (f >= 0 && f <= 2.0f) {
float f;
if (cli_args::parseFloat(&command[12], 0, 2.0f, &f)) {
setFloodTxDelay(f);
strcpy(reply, "OK");
} else {
@@ -300,8 +343,8 @@ bool CommonRadioPrefs::handleCommand(const char* command, uint32_t sender_timest
return true;
}
if (memcmp(command, "set direct.txdelay ", 19) == 0) {
float f = atof(&command[19]);
if (f >= 0 && f <= 2.0f) {
float f;
if (cli_args::parseFloat(&command[19], 0, 2.0f, &f)) {
setDirectTxDelay(f);
strcpy(reply, "OK");
} else {
+26
View File
@@ -0,0 +1,26 @@
#pragma once
class GPSLocHelper {
static constexpr double APPROX_RADIUS = 6371e3; // 6,371 km
static double toRadians(float degrees) {
return degrees * PI / 180;
}
public:
static float calcGreatArcMeters(float lat1, float lon1, float lat2, float lon2) {
double diffLati = toRadians(lat1 - lat2);
double diffLong = toRadians(lon1 - lon2);
double radiusStartLati = toRadians(lat2);
double radiusEndLati = toRadians(lat1);
// A and C are the 'sides' from the spherical triangle.
double sinLati = sin(diffLati / 2);
double sinLong = sin(diffLong / 2);
double a = sinLati*sinLati + sinLong*sinLong * cos(radiusStartLati) * cos(radiusEndLati);
double c = 2 * asin(sqrt(a));
return APPROX_RADIUS * c;
}
};
+39 -1
View File
@@ -328,11 +328,27 @@ bool NRF52Board::isExternalPowered() {
}
}
#ifdef PWR_DUTY_INSTRUMENT
// CUSTOM (TeTeHacko): bench instrument (opt-in, -D PWR_DUTY_INSTRUMENT). Measures
// what share of wall time the MCU is awake: the loop calls sleep() every pass, so
// the gap between a sleep() return and the next sleep() entry is CPU-awake time,
// and the WFE span inside is asleep. Combined with `recv` from stats-packets it
// gives the CPU cost per received packet (the part a radio-side filter could cut).
// Prints one line to Serial every ~10 s. No effect unless the flag is set.
static uint64_t s_awake_us = 0, s_asleep_us = 0;
static uint32_t s_last_exit_us = 0, s_wakes = 0, s_report_us = 0;
static bool s_have_exit = false;
// Pure per-packet CPU time, measured in Dispatcher::processRecvPacket (immune to
// BLE/USB background wakes, unlike the awake/asleep duty above).
extern uint64_t g_pkt_proc_us;
extern uint32_t g_pkt_proc_count;
#endif
void NRF52Board::sleep(uint32_t secs) {
// Clear FPU interrupt flags to avoid insomnia
// see errata 87 for details https://docs.nordicsemi.com/bundle/errata_nRF52840_Rev3/page/ERR/nRF52840/Rev3/latest/anomaly_840_87.html
#if (__FPU_USED == 1)
__set_FPSCR(__get_FPSCR() & ~(0x0000009F));
__set_FPSCR(__get_FPSCR() & ~(0x0000009F));
(void) __get_FPSCR();
NVIC_ClearPendingIRQ(FPU_IRQn);
#endif
@@ -350,6 +366,11 @@ void NRF52Board::sleep(uint32_t secs) {
uint8_t sd_enabled = 0;
sd_softdevice_is_enabled(&sd_enabled);
#ifdef PWR_DUTY_INSTRUMENT
uint32_t t_enter = micros();
if (s_have_exit) s_awake_us += (uint32_t)(t_enter - s_last_exit_us);
#endif
if (sd_enabled) {
// first call processes pending softdevice events, second call sleeps.
sd_app_evt_wait();
@@ -360,6 +381,23 @@ void NRF52Board::sleep(uint32_t secs) {
__WFE();
__WFE();
}
#ifdef PWR_DUTY_INSTRUMENT
uint32_t t_exit = micros();
s_asleep_us += (uint32_t)(t_exit - t_enter);
s_last_exit_us = t_exit;
s_have_exit = true;
s_wakes++;
if ((uint32_t)(t_exit - s_report_us) >= 10000000UL) {
s_report_us = t_exit;
uint64_t tot = s_awake_us + s_asleep_us;
uint32_t permille = tot ? (uint32_t)((s_awake_us * 1000) / tot) : 0;
Serial.printf("PWRDUTY awake_ms=%lu asleep_ms=%lu wakes=%lu duty_permille=%lu pkt_us=%lu pkt_n=%lu\r\n",
(unsigned long)(s_awake_us / 1000), (unsigned long)(s_asleep_us / 1000),
(unsigned long)s_wakes, (unsigned long)permille,
(unsigned long)(g_pkt_proc_us), (unsigned long)g_pkt_proc_count);
}
#endif
}
// Temperature from NRF52 MCU
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
/**
* \brief Remembers the last CLI replies sent, as a hash of each reply's plaintext (timestamp, flags, text),
* so the same bytes coming back as a command (hash bytes swapped, same shared secret) are refused.
*/
class ReplyEchoGuard {
static const int SLOTS = 16;
uint32_t _hash[SLOTS] = {};
int _next = 0;
static uint32_t hash(const uint8_t* p, size_t len) { // FNV-1a, never zero (zero marks an empty slot)
uint32_t h = 2166136261u;
for (size_t i = 0; i < len; i++) {
h = (h ^ p[i]) * 16777619u;
}
return h ? h : 1;
}
public:
void note(const uint8_t* plain, size_t len) {
_hash[_next] = hash(plain, len);
_next = (_next + 1) % SLOTS;
}
bool matches(const uint8_t* plain, size_t len) const {
uint32_t h = hash(plain, len);
for (int i = 0; i < SLOTS; i++) {
if (_hash[i] == h) return true;
}
return false;
}
};
+46
View File
@@ -53,4 +53,50 @@ inline size_t validUtf8PrefixLength(const char* text, size_t max_bytes) {
return offset;
}
inline bool isValidUtf8TextAndPadding(const uint8_t* data, size_t len) {
size_t offset = 0;
bool seen_null = false;
size_t null_pos = 0;
while (offset < len) {
const uint8_t first = static_cast<uint8_t>(data[offset]);
if (seen_null) {
if (first == 0) { // OK, is zero padding
offset++;
} else if (offset == null_pos + 1 && first >= 4 && first != 0xFF) { // OK, extended attempt byte (see composeMsgPacket)
offset++;
} else {
return false; // Error, non-zero padding encountered
}
} else {
if (first == 0) {
seen_null = true;
null_pos = offset;
offset++;
} else {
size_t sequence_length = 0;
if (first < 0x20 && first != '\t' && first != '\n' && first != '\r') {
return false; // control character
} else if (first <= 0x7F) {
sequence_length = 1;
} else if (first >= 0xC2 && first <= 0xDF) {
sequence_length = 2;
} else if (first >= 0xE0 && first <= 0xEF) {
sequence_length = 3;
} else if (first >= 0xF0 && first <= 0xF4) {
sequence_length = 4;
} else {
return false; // unsupported UTF-8 encoding
}
if (offset + sequence_length > len) return false; // invalid UTF-8 encoding
for (size_t i = 1; i < sequence_length; i++) {
if (!isUtf8Continuation(data[offset + i])) return false; // invalid UTF-8 encoding
}
offset += sequence_length;
}
}
}
return true; // is OK
}
} // namespace mesh
+6
View File
@@ -162,6 +162,12 @@ public:
return size;
}
static uint8_t readGPS(const uint8_t* _buf, float& lat, float& lon, float& alt) {
lat = getFloat(&_buf[0], 3, 10000, true);
lon = getFloat(&_buf[3], 3, 10000, true);
alt = getFloat(&_buf[6], 3, 100, true);
return 9;
}
};
class LPPReader {
+13 -4
View File
@@ -264,7 +264,7 @@ public:
auto p = &recent[recent_next_idx];
recent_next_idx = (recent_next_idx + 1) % UI_RECENT_LIST_SIZE;
strcpy(p->name, contact.name);
StrHelper::strncpy(p->name, contact.name, sizeof(p->name));
p->recv_timestamp = _rtc->getCurrentTime();
}
@@ -392,7 +392,7 @@ public:
} else if (_page == HomePage::RECENT) {
display.setColor(UIColor::primary_txt);
int y = 20;
for (int i = 0, k = recent_next_idx; i < UI_RECENT_LIST_SIZE; i++, y += 11, k = (k + 1) % UI_RECENT_LIST_SIZE) {
for (int i = 0, k = recent_next_idx; i < UI_RECENT_LIST_SIZE; i++, k = (k + 1) % UI_RECENT_LIST_SIZE) {
auto a = &recent[k];
if (a->name[0] == 0) continue; // empty slot
int secs = _rtc->getCurrentTime() - a->recv_timestamp;
@@ -412,6 +412,10 @@ public:
display.drawTextEllipsized(0, y, max_name_width, filtered_recent_name);
display.setCursor(display.width() - timestamp_width - 1, y);
display.print(tmp);
y += 11;
}
if (y == 20) {
display.drawTextCentered(display.width() / 2, 32, "No recent adverts");
}
} else if (_page == HomePage::RADIO) {
display.setColor(UIColor::primary_txt);
@@ -513,6 +517,11 @@ public:
} else if (_page == HomePage::SENSORS) {
int y = 18;
refresh_sensors();
if (sensors_nb == 0) {
display.setColor(UIColor::primary_txt);
display.drawTextCentered(display.width() / 2, 32, "No sensor readings");
return 5000;
}
char buf[30];
char name[30];
LPPReader r(sensors_lpp.getBuffer(), sensors_lpp.getSize());
@@ -741,9 +750,9 @@ public:
auto p = &unread[head];
p->timestamp = _rtc->getCurrentTime();
if (path_count == 0xFF) {
sprintf(p->origin, "(D) %s:", from_name);
snprintf(p->origin, sizeof(p->origin), "(D) %s:", from_name);
} else {
sprintf(p->origin, "(%d) %s:", (uint32_t) path_count, from_name);
snprintf(p->origin, sizeof(p->origin), "(%d) %s:", (uint32_t) path_count, from_name);
}
StrHelper::strncpy(p->msg, msg, sizeof(p->msg));
}
+4 -4
View File
@@ -155,9 +155,9 @@ void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t t
uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF;
if (path_len == 0xFF) {
sprintf(_origin, "(F) %s", from.name);
snprintf(_origin, sizeof(_origin), "(F) %s", from.name);
} else {
sprintf(_origin, "(%d) %s", (uint32_t) path_len, from.name);
snprintf(_origin, sizeof(_origin), "(%d) %s", (uint32_t) path_len, from.name);
}
StrHelper::strncpy(_msg, text, sizeof(_msg));
@@ -182,9 +182,9 @@ void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_det
uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF;
if (path_len == 0xFF) {
sprintf(_origin, "(F) %s", channel_details.name);
snprintf(_origin, sizeof(_origin), "(F) %s", channel_details.name);
} else {
sprintf(_origin, "(%d) %s", (uint32_t) path_len, channel_details.name);
snprintf(_origin, sizeof(_origin), "(%d) %s", (uint32_t) path_len, channel_details.name);
}
StrHelper::strncpy(_msg, text, sizeof(_msg));
+1 -1
View File
@@ -159,7 +159,7 @@ public:
auto p = &recent[recent_next_idx];
recent_next_idx = (recent_next_idx + 1) % UI_RECENT_LIST_SIZE;
strcpy(p->name, contact.name);
StrHelper::strncpy(p->name, contact.name, sizeof(p->name));
p->recv_timestamp = _rtc->getCurrentTime();
}
@@ -183,6 +183,7 @@ TEST(AclReplayFloor, AlternatesSlotsAcrossReboots) {
n.boot();
c = n.acl->getClient(idFor(1).pub_key, PUB_KEY_SIZE);
ASSERT_EQ(c->last_timestamp, ts) << "boot " << boot;
ASSERT_EQ(c->last_req_timestamp, ts) << "boot " << boot; // REQ floor (upstream split) comes back too
}
}
+55
View File
@@ -0,0 +1,55 @@
#include <gtest/gtest.h>
#include "helpers/CliArgs.h"
using cli_args::parseFloat;
using cli_args::parseInt;
TEST(CliArgsInt, AcceptsWholeNumbersInRange) {
long v = 0;
EXPECT_TRUE(parseInt("22", -9, 22, &v)); EXPECT_EQ(v, 22);
EXPECT_TRUE(parseInt("-9", -9, 22, &v)); EXPECT_EQ(v, -9);
EXPECT_TRUE(parseInt(" +5 ", -9, 22, &v)); EXPECT_EQ(v, 5);
EXPECT_TRUE(parseInt("0", 0, 64, &v)); EXPECT_EQ(v, 0);
}
TEST(CliArgsInt, RefusesOutOfRangeAndGarbage) {
long v = 7;
EXPECT_FALSE(parseInt("23", -9, 22, &v));
EXPECT_FALSE(parseInt("-10", -9, 22, &v));
EXPECT_FALSE(parseInt("300", 0, 64, &v)); // would be 44 in a uint8_t
EXPECT_FALSE(parseInt("abc", 0, 64, &v)); // atoi() says 0
EXPECT_FALSE(parseInt("", 0, 64, &v));
EXPECT_FALSE(parseInt("12abc", 0, 64, &v));
EXPECT_FALSE(parseInt("1.5", 0, 64, &v));
EXPECT_FALSE(parseInt("-", 0, 64, &v));
EXPECT_FALSE(parseInt(nullptr, 0, 64, &v));
EXPECT_EQ(v, 7); // untouched on failure
}
TEST(CliArgsFloat, AcceptsDecimalsInRange) {
float f = 0;
EXPECT_TRUE(parseFloat("869.432", 150, 2500, &f)); EXPECT_FLOAT_EQ(f, 869.432f);
EXPECT_TRUE(parseFloat("-12.5", -90, 90, &f)); EXPECT_FLOAT_EQ(f, -12.5f);
EXPECT_TRUE(parseFloat(".5", 0, 2, &f)); EXPECT_FLOAT_EQ(f, 0.5f);
EXPECT_TRUE(parseFloat("2", 0, 2, &f)); EXPECT_FLOAT_EQ(f, 2.0f);
EXPECT_TRUE(parseFloat("3. ", 0, 9, &f)); EXPECT_FLOAT_EQ(f, 3.0f);
}
TEST(CliArgsFloat, RefusesNanInfExponentAndGarbage) {
float f = 1;
EXPECT_FALSE(parseFloat("nan", -1e9f, 1e9f, &f));
EXPECT_FALSE(parseFloat("inf", -1e9f, 1e9f, &f));
EXPECT_FALSE(parseFloat("1e3", 0, 1e9f, &f));
EXPECT_FALSE(parseFloat("abc", 0, 2500, &f));
EXPECT_FALSE(parseFloat("", 0, 2500, &f));
EXPECT_FALSE(parseFloat(".", 0, 2500, &f));
EXPECT_FALSE(parseFloat("869,4", 150, 2500, &f));
EXPECT_FALSE(parseFloat("100", 150, 2500, &f));
EXPECT_FALSE(parseFloat("91", -90, 90, &f));
EXPECT_EQ(f, 1);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+4 -1
View File
@@ -57,7 +57,10 @@ public:
int adcvalue = 0;
analogReadResolution(12);
analogReference(AR_INTERNAL_3_0);
delay(10);
// CUSTOM (TeTeHacko): the divider is off (VBAT_ENABLE HIGH) between reads
// since #27, so the ADC node starts high. 10 ms left ~+110..150 mV on the
// reading (mast-three and second-mast, 26.-27. 11. 2026); 100 ms settles it.
delay(100);
adcvalue = analogRead(BATTERY_PIN);
digitalWrite(VBAT_ENABLE, HIGH);
return (adcvalue * ADC_MULTIPLIER * AREF_VOLTAGE) / 4.096;
+14
View File
@@ -32,11 +32,25 @@
#define PIN_BUTTON5 (28) // Joystick Right
#define PIN_BUTTON6 (29) // Joystick Press
#define PIN_BACK_BTN PIN_BUTTON1
// Joystick pins can be overridden from build_flags, e.g. for an enclosure
// that mounts the display rotated 90 degrees relative to the joystick:
// -D JOYSTICK_UP=PIN_BUTTON4 -D JOYSTICK_DOWN=PIN_BUTTON5
// -D JOYSTICK_LEFT=PIN_BUTTON3 -D JOYSTICK_RIGHT=PIN_BUTTON2
#ifndef JOYSTICK_UP
#define JOYSTICK_UP PIN_BUTTON2
#endif
#ifndef JOYSTICK_DOWN
#define JOYSTICK_DOWN PIN_BUTTON3
#endif
#ifndef JOYSTICK_LEFT
#define JOYSTICK_LEFT PIN_BUTTON4
#endif
#ifndef JOYSTICK_RIGHT
#define JOYSTICK_RIGHT PIN_BUTTON5
#endif
#ifndef JOYSTICK_PRESS
#define JOYSTICK_PRESS PIN_BUTTON6
#endif
#define PIN_USER_BTN PIN_BUTTON6
// Buzzer