Compare commits

..
Author SHA1 Message Date
Ben Meadors 38c4001f52 Merge branch 'develop' into feature/rak4631-lockdown 2026-03-02 06:40:58 -06:00
m1nlandBen Meadors 80af726877 avoid memory leak when possibly malformed packet received (#9781)
getByIndex allocates memory and returns dummy channel whenever
chIndex validation fails. Comment implies this may happen
when malformed packet is received. The fix changes implementation
so static dummyChannel is returned in such case.

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2026-02-28 18:37:41 -06:00
m1nlandBen Meadors 563adc6aaa enhancement(mesh): remove late packets from tx queue when full (#9779)
* enhance tx queue priority management

In busy environments, especially for ROUTER_LATE role, tx queue
fills very quickly. Delayed packets became late but new packets
to be retransmitted won't be put into the tx queue as old ones
stay there for a very long time (even a minute or more). This change
makes meshtastic prioritize new packets over late packets from tx queue
and allows to remove late packet from back of tx queue when there
is no space for a new one.

* apply copilot recommendation for cast

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2026-02-28 17:17:29 -06:00
Ben Meadors 67f806b0a5 Merge remote-tracking branch 'origin/master' into develop 2026-02-28 11:08:15 -06:00
niccellular 067d6834c7 fix audit findings from Opus 4.6 specifically looking for race conditions and logic bugs
Three-agent security audit of the LOCKDOWN build identified race conditions,
  incomplete key zeroing, and missing memory hygiene. All findings except HIGH-1
  are addressed here. HIGH-1 (revokeAllAuth not resetting per-instance
  isAdminAuthorized) was reviewed and closed as wontfix: PKC admin key holders
  have persistent access regardless, so the 7-second pre-reboot window changes
  nothing about the threat model.

  HIGH-2: lockNow() previously only zeroed dek[]. Now also zeroes kek[],
  ephemeralKek[], and their derived flags so no key material survives a lock
  event in a RAM dump.

  HIGH-3: isAdminAuthorized (per-instance) and s_localAdminAuthorized (static)
  changed from plain bool to std::atomic<bool>. Both flags are written from the
  NimBLE FreeRTOS task and read from the main loop — non-atomic reads were a
  data race.

  MED-1: readAndDecrypt() and encryptAndWrite() now snapshot dek[] into a stack-
  local dekSnapshot[] on entry before acquiring any lock. A concurrent lockNow()
  that zeros dek[] mid-operation either zeroes the snapshot (HMAC fails securely)
  or has no effect on an already-captured copy. dekSnapshot is zeroed on all exit
  paths.

  MED-2: close() and handleStartConfig() no longer clear s_localAdminAuthorized.
  Resetting it on every disconnect was an auth DoS — any new client connection
  would silently revoke the passphrase-authenticated state, forcing the operator
  to re-enter the passphrase on every reconnect. Device-level auth now persists
  until explicit Lock Now (revokeAllAuth()).

  MED-3: readAndDecrypt() scoped the spiLock LockGuard to a nested block
  covering only the FSCom.open/read/close sequence. The lock is released before
  any HMAC or AES-CTR work. spiLock is a non-recursive binary semaphore;
  holding it across CC310 calls created a re-entry deadlock risk.

  MED-4: AdminModule zeros the passphrase bytes in toRadioScratch via a volatile
  pointer cast before returning from both the Lock Now and provision/unlock
  paths. Prevents the passphrase lingering in the scratch buffer until the next
  ToRadio message overwrites it.

  MED-5: readAndDecrypt() was missing memset(fileBuf) on the hmacData OOM early-
  exit path, leaving ciphertext in the heap until the allocator reuses it.

  MED-6: readAndDecrypt() now sets outLen=0 on entry so callers never observe a
  stale length value on any early failure return.

  MED-7: readAndDecrypt() calls memset(outBuf, 0, ciphertextLen) on AES-CTR
  failure to clear partial plaintext that may have been written to the caller's
  buffer before the error was detected.

  MED-8: Passphrase length limit corrected from 64 to 32 bytes throughout
  (EncryptedStorage.cpp provisionPassphrase/unlockWithPassphrase, AdminModule.cpp
  ppLen range check, EncryptedStorage.h doc comments). The proto private_key field
  is 32 bytes; accepting 33-64 silently failed inside EncryptedStorage while
  appearing to succeed at the AdminModule gate.

  L-1: readAndDecrypt() now rejects files larger than 65536+54 bytes before
  allocating the heap buffer, preventing OOM or integer overflow on corrupt or
  attacker-supplied oversized files.

  L-2: migrateFile() has a precondition comment that spiLock must not be held
  by the caller; both isEncrypted() and encryptAndWrite() acquire it internally.
2026-02-28 11:57:47 -05:00
Ben Meadors c7dc536640 Merge remote-tracking branch 'origin/develop' 2026-02-28 09:39:25 -06:00
Ben Meadors 6920a5f8b1 Increase PSRAM malloc threshold from 256 bytes to 2048 bytes (#9758) 2026-02-28 09:34:26 -06:00
github-actions[bot]andvidplace7 2b7a230977 Upgrade trunk (#9752)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-28 08:41:34 -06:00
renovate[bot] 1e16185fdd chore(deps): update platformio/ststm32 to v19.5.0 (#9764)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-28 08:41:21 -06:00
renovate[bot] 60c2592694 chore(deps): update adafruit dps310 to v1.1.6 (#9763)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-28 08:41:01 -06:00
renovate[bot] fc0ad4956e chore(deps): update adafruit ahtx0 to v2.0.6 (#9766)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-28 08:40:15 -06:00
Ben Meadors 43aa90fc3f Unlock 0x8B5 register macro guard for SX162 (#9777) 2026-02-28 08:38:08 -06:00
Ben Meadors c28bdbd7e6 Fix mqtt test 2026-02-28 08:32:05 -06:00
Jonathan BennettandBen Meadors 857c7b3a3a Don't launch canned message when waking screen or silencing notification (#9762)
* Don't launch canned message when waking screen or silencing notification

* Add screen ifdefs

* Get the #if right

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2026-02-27 17:07:03 -06:00
niccellularandClaude Sonnet 4.6 3f9d76f054 addressing copilot comments
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-27 16:35:18 -05:00
niccellular 545ae99ff8 Merge branch 'develop' of https://github.com/meshtastic/firmware into develop 2026-02-27 08:00:19 -05:00
Andrew Yong 83cac93ca8 fix(MQTT): Send first MapReport as soon as possible (#8872)
* fix(MQTT): First MapReport does not get sent

Throttle::isWithinTimespanMs(last_report_to_map, map_publish_interval_msecs) is
used to maintain the map reporting interval, but because last_report_to_map has
an initial value of 0, the map report routine does not start until the system
millis() time has passed map_publish_interval_msecs.

Fix this by adding a check that last_report_to_map is not 0.

Signed-off-by: Andrew Yong <me@ndoo.sg>

* feat(MQTT): Send MapReporting immediately upon location fix

Do not update last_report_to_map when Map Report is attempted without a valid
location, as this results in waiting up to an hour (or configured Map Report
interval).

That usually happens because most nodes do not keep GPS warm, so GPS usually
locks after the first attempt at Map Report.

This change also results in the log WARNing message getting spammed until a
location is obtained, so remove the message for now.

Signed-off-by: Andrew Yong <me@ndoo.sg>

* feat(MQTT): Throttled warning when position is not available for MapReport

Signed-off-by: Andrew Yong <me@ndoo.sg>

---------

Signed-off-by: Andrew Yong <me@ndoo.sg>
2026-02-27 05:16:55 -06:00
niccellular fd7fc40255 Add rak4631_lockdown hardened build variant
Introduces a new RAK4631 build variant (-DMESHTASTIC_LOCKDOWN=1) with
encrypted flash storage, BLE/USB config access control, and hardened
defaults.

New files:
- variants/nrf52840/rak4631_lockdown/ — PlatformIO env, variant header
- src/security/EncryptedStorage.h/.cpp — AES-128-CTR + HMAC-SHA256
  encrypted proto storage using CC310 hardware, passphrase-gated DEK,
  TTL/boot-count unlock token, backoff on failed attempts
- src/security/APProtect.h/.cpp — UICR APPROTECT (SWD lockout)

Modified files:
- configuration.h — MESHTASTIC_LOCKDOWN flag derives
  PHONEAPI_ACCESS_CONTROL, ENCRYPTED_STORAGE, ENABLE_APPROTECT,
  HARDENED_DEFAULTS (nRF52 only)
- NodeDB.cpp/.h — encrypted loadProto/saveProto, locked-boot early
  return, migration of plaintext files to MENC, hardened defaults,
  saveToDiskNoRetry guard prevents FSCom.format() when storage locked
- PhoneAPI.cpp/.h — per-connection auth reset, redacts channel PSKs
  and security keys for unauthorized clients, revokeAllAuth() for
  Lock Now, post-config TAK_LOCKED/TAK_NEEDS_PROVISION notification
- AdminModule.cpp — passphrase delivery via set_config(security),
  provision/unlock/re-verify flow, Lock Now sentinel (0xFF),
  PKC admin auth callback to PhoneAPI
- PowerFSM.cpp — guard serialEnter() BLE disable on nRF52
2026-02-26 22:15:40 -05:00
renovate[bot] d34fa3e7df chore(deps): update platformio/nordicnrf52 to v10.11.0 (#9760)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-26 08:11:00 -06:00
renovate[bot] 75cb8bb5ea chore(deps): update platformio/espressif32 to v6.13.0 (#9759)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-26 08:09:44 -06:00
renovate[bot] 2a99cc6a25 chore(deps): update adafruit mlx90614 to v2.1.6 (#9756)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-26 08:01:28 -06:00
renovate[bot] b5f98d1270 chore(deps): update adafruit_tsl2561 to v1.1.3 (#9757)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-26 08:01:03 -06:00
Ben Meadors ef697319da Merge remote-tracking branch 'origin/develop' 2026-02-26 07:53:34 -06:00
Ben Meadors efd68f9fad Fix Bluetooth on RAK Ethernet Gateway by removing MESHTASTIC_EXCLUDE_POWER_FSM from build_flags (#9755) 2026-02-26 07:38:13 -06:00
Ben MeadorsandCopilot 3a74e049ab Add Transmit history persistence for respecting traffic intervals between reboots (#9748)
* Add transmit history for throttling that persists between reboots

* Fix RAK long press detection to prevent phantom shutdowns from floating pins

* Update test/test_transmit_history/test_main.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Test fixes and placeholder for content handler tests

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-25 20:41:07 -06:00
KokoandBen Meadors 3b1b308357 platform: nrf52: Fix typo in BLEDfuSecure filename (#9709)
Change file name from BLEDfuScure.cpp to BLEDfuSecure.cpp. Fix filenames
in documentation.

Signed-off-by: Koko <github@kokosoftware.pl>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2026-02-25 18:00:02 -06:00
Jonathan BennettandBen Meadors 5a068431ed Add GPIO_DETECT_PA portduino config, and support 13302 detection with it (#9741)
* Add GPIO_DETECT_PA portduino config, and support 13302 detection with it.

* Tweak PA detect gpio to use pinMapping

* minor yaml output fixes

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2026-02-25 14:18:07 -06:00
github-actions[bot]andvidplace7 25f086a64f Upgrade trunk (#9744)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-25 08:30:32 -06:00
Ben Meadors a93d4d7e9d Revert "Fix/rak3401 button (#9668)" (#9747)
This reverts commit a5523b04ef.
2026-02-25 08:26:49 -06:00
Thomas Göttgens 54781cf51a hopefully fix remaining cppcheck issues (#9745) 2026-02-25 10:27:21 +01:00
Wessel ad7d19c317 Remove unused global rIf that shadows locals and fails cppcheck (#9743)
I noticed because my PR failed
2026-02-24 20:57:58 -06:00
Thomas Göttgens 58496e56d2 fail cppcheck on low already. Code quality for the win. 2026-02-24 22:45:38 +01:00
Ben Meadors 2c18a41613 Merge remote-tracking branch 'origin/master' into develop 2026-02-24 14:28:15 -06:00
github-actions[bot]andthebentern c65eecc295 Update protobufs (#9739)
Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com>
2026-02-24 14:27:23 -06:00
Ben Meadors cac45d9ced Align telemetry broadcast want_response behavior with traceroute (#9717)
* Align telemetry broadcast want_response behavior with traceroute

* Fixes

* Reduce side-effects by making the telemetry modules handle the ignorerequest

* Remove unnecessary ignoreRequest flag

* Try inheriting from MeshModule

* Add exclusion for sensor/router roles and add base telem module
2026-02-24 13:26:47 -06:00
Wessel 02d42f87d3 Implement 'agc' reset for SX126x & LR11x0 chip families (#9705)
* Implement 'agc' reset for SX126x chip family

There's no actual agc on SX126x chips but you can reset the analog
registers by doing a warm sleep & running calibration.

* Address PR comments & implement for LR11x0 too

* calibrate for configured frequency band

* Gate LR11X0_AGC_RESET
2026-02-24 08:03:25 -06:00
Ben Meadors 9c439f8d0a FIx loophole with telemetry coercion 2026-02-24 06:01:52 -06:00
github-actions[bot]andvidplace7 cf998f03b6 Upgrade trunk (#9731)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-24 05:47:18 -06:00
renovate[bot] f9d1f2414a chore(deps): update sensorlib to v0.3.4 (#9727)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-24 05:46:27 -06:00
renovate[bot] 13b25c0614 chore(deps): update meshtastic-st7789 digest to 9ee76d6 (#9729)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-23 20:42:52 -06:00
Austin 607b631114 meshtasticd: Add Luckfox Lyra Hat pinmaps (#9730)
Luckfox Lyra Plus + Waveshare Pi Pico Hat
Luckfox Lyra Ultra + wehooper4's "Luckfox Ultra" hat.
2026-02-23 20:42:41 -06:00
ManuelandCopilot 99e88bb499 Support mini ePaper S3 Kit (#9335)
* initial draft

* update DC pin

* add ADC channel

* fix e-ink display

* update GxEPD2 reference

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Apply suggestion from @Copilot

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-23 12:08:24 -06:00
github-actions[bot]andvidplace7 4f84cf011d Upgrade trunk (#9724)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-23 05:38:33 -06:00
renovate[bot] 0726a9f774 chore(deps): update radiolib to v7.6.0 (#9695)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-22 18:46:39 +01:00
Ben Meadors f8cc1d6046 Merge remote-tracking branch 'origin/develop' 2026-02-22 06:10:05 -06:00
Ben MeadorsandCopilot f615990c00 Limit http connections and add free heap check before allocating for SSL (#9693)
* Reduce maximum concurrent HTTPS connections to save memory

* Add heap check and limit connections to prevent HTTPS connection related crashes

* Use Throttle::isWithinTimespanMs for overflow-safe heap warning throttle

* Update src/mesh/http/WebServer.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Fix double-free heap corruption and parser leak in web server handlers

- Remove double-free in handleFsBrowseStatic, handleNodes, handleScanNetworks:
  JSONValue(const JSONArray&) shallow-copies pointers, so delete value already
  recursively frees all elements. The explicit cleanup loops were deleting the
  same pointers a second time, corrupting the ESP32 heap allocator metadata.
  This is the likely root cause of #8827 (SSL setup failures after uptime).
- Fix memory leak in handleFormUpload: two early-return paths were missing
  delete parser.
- Remove unused global HTTPClient httpClient and its includes.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-21 09:06:17 -06:00
HarukiToredaandBen Meadors 8f81b194d3 BLE Pairing fix (#9701)
* BLE Pairing fix

* gating for consistency

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2026-02-20 10:38:07 -06:00
github-actions[bot]andvidplace7 6bc3e31537 Upgrade trunk (#9696)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-20 06:45:46 -06:00
renovate[bot] 15460c8f97 Update meshtastic-GxEPD2 digest to c7eb4c3 (#9694)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-19 17:11:04 -06:00
Ben Meadors a77ac21e0d Trunk 2026-02-19 07:17:50 -06:00
Ben Meadors 2b6d8f6824 Merge branch 'develop' 2026-02-19 07:17:20 -06:00
+19 4c91beeda9 Develop to master (#9618)
* Don't ever define PIN_LED or BLE_LED_INVERTED (#9494)

* Don't ever define PIN_LED

* Deprecate BLE_LED_INVERTED

* Add StatusMessage module and config overrides (#9351)

* Add StatusMessage module and config overrides

* Trunk

* Don't reboot node simply for a StatusMessage config update

* Missed in reviews - fixing send bubble (#9505)

* Prefer EXT_PWR_DETECT pin over chargingVolt to detect power unplugged (#9511)

* Make sure we always return a value in NodeDB::restorePreferences() (#9516)

In case FScom is not defined there is no return statement. This
moves the return outside of the ifdef to make sure a defined
value is returned.

* Inkhud battery icon improvements. (#9513)

* Inkhud battery icon improvements.
Fixes the battery icon draining from the flat side towards the bump, which is backwards from general design language seen on most devices
By request of kr0n05_ on discord, adds the ability to mirror the battery icon which fixes that issue in another way, and is also a common design seen on other devices.

* Remove option for icon mirroring

* Add border + dither to battery to prevent font overlap

* Fix trunk format

* Code cleanup, courtesy of Xaositek.

* Add reply bot module with DM-only responses and rate limiting (#9456)

* Implement Meshtastic reply bot module with ping and status features

Adds a reply bot module that listens for /ping, /hello, and /test commands received via direct messages or broadcasts on the primary channel. The module always replies via direct message to the sender only, reporting hop count, RSSI, and SNR. Per-sender cooldowns are enforced to reduce network spam, and the module can be excluded at build time via a compile flag. Updates include the new module source files and required build configuration changes.

* Update ReplyBotModule.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/modules/ReplyBotModule.h

Match the existing MESHTASTIC_EXCLUDE_* guard pattern so the module is excluded by default.

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/modules/ReplyBotModule.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Tidying up

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* HotFix for ReplyBot - Modules.cpp included and moved configuration.h (#9532)

* Undefine LED_BUILTIN (#9531)

Keep variant in sync with
https://github.com/meshtastic/firmware/commit/df40085

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* Add agc reset attempt (#8163)

* Add agc reset attempt

* Add radioLibInterface include

* Trunk

* AGC reset don't crash, don't naively call

* Update src/main.cpp

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Use Throttle function

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Remove unused hmx variable (#9529)

The variable is not used at all in the function, remove it to
silence the compiler warning.

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* Rename LED_PIN to LED_POWER, move handling out of main to dedicated module (#9512)

* Rename LED_PIN to LED_POWER, move handling out of main to dedicated module

* Misc

* Remove errant endif

* Fix hop_limit upgrade detection (#9550)

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* meshtasticd: Fix install on Fedora 43 (#9556)

* RPM: Include meshtasticd-start.sh (#9561)

* Add Slash Key to VirtualKeyboard (#9563)

Addition of ? and / to the virtual Keyboard via short and long press

* Add support for CW2015 LiPo battery fuel gauge (#9564)

* Add support for CW2015 LiPo battery fuel gauge

* Address Copilot's concerns, minor fixups

* Make LED_POWER blip even in critical battery (#9545)

* Enable FORTIFY and SP for native builds (#9537)

* Enable FORITFY and NX for native builds

meshtasticd does have an executable stack and is not built with fortify, which makes exploitation of memory corruption bugs easier than it has to be. This enables fortify and a non-executable stack.

This gives the following improvements on Debian Trixie:

$ checksec --file=./.pio/build/native/meshtasticd
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH	Symbols		FORTIFY	Fortified	Fortifiable	FILE
Partial RELRO   No canary found   NX enabled    PIE enabled     No RPATH   No RUNPATH   13516 Symbols	  No	0		17		./.pio/build/native/meshtasticd

$ checksec --file=./.pio/build/native/meshtasticd
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH	Symbols		FORTIFY	Fortified	Fortifiable	FILE
Partial RELRO   Canary found      NX enabled    PIE enabled     No RPATH   No RUNPATH   13519 Symbols	  Yes	12		20		./.pio/build/native/meshtasticd

Tested with --sim mode I do not get any crashes or similar.

* Enable FORTIFY and NX for native builds

meshtasticd does have an executable stack and is not built with fortify, which makes exploitation of memory corruption bugs easier than it has to be. This enables fortify and a non-executable stack.

This gives the following improvements on Debian Trixie:

$ checksec --file=./.pio/build/native/meshtasticd
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH	Symbols		FORTIFY	Fortified	Fortifiable	FILE
Partial RELRO   No canary found   NX enabled    PIE enabled     No RPATH   No RUNPATH   13516 Symbols	  No	0		17		./.pio/build/native/meshtasticd

$ checksec --file=./.pio/build/native/meshtasticd
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH	Symbols		FORTIFY	Fortified	Fortifiable	FILE
Partial RELRO   Canary found      NX enabled    PIE enabled     No RPATH   No RUNPATH   13519 Symbols	  Yes	12		20		./.pio/build/native/meshtasticd

Tested with --sim mode I do not get any crashes or similar.

* Enable FORTIFY and SP for native builds

meshtasticd does have a stack canaries and is not built with fortify, which makes exploitation of memory corruption bugs easier than it has to be. This enables fortify and stack canaries.

This gives the following improvements on Debian Trixie:

$ checksec --file=./.pio/build/native/meshtasticd
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH	Symbols		FORTIFY	Fortified	Fortifiable	FILE
Partial RELRO   No canary found   NX enabled    PIE enabled     No RPATH   No RUNPATH   13516 Symbols	  No	0		17		./.pio/build/native/meshtasticd

$ checksec --file=./.pio/build/native/meshtasticd
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH	Symbols		FORTIFY	Fortified	Fortifiable	FILE
Partial RELRO   Canary found      NX enabled    PIE enabled     No RPATH   No RUNPATH   13519 Symbols	  Yes	12		20		./.pio/build/native/meshtasticd

Tested with --sim mode I do not get any crashes or similar.

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* Update built-in documentation for current method of implementation (#9592)

* Refactor logging in ProtobufModule to ensure message details are logged after successful decoding (#9536)

* Automated version bumps (#9604)

Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com>

* Add missing openocd_target to custom nrf52 boards (#9603)

This stops platformio complaining about `Missing target configuration for me25ls01-4y10td` etc when trying to flash with nrfutil.

* Add sdl libs for native builds (#9595)

* Add sdl libs for native builds

* Alpine try again

* fix some random compiler warnings (#9596)

* Modify the dependency library of v4-tft (#9507)

* BaseUI: Favorite Screen Signal Quality improvement (#9566)

* Favorite Signal Quality improvement

* Show Voltage if node shares it.

* Trunk Fix

* Change Favorite tittle to encase name with Asterisks

* Add Pluggin In condition for Battery Line

* Adjust getUptimeStr Prefixes

* Create isAPIConnected for SharedCommon usage

* Correct leftSideSpacing to account for isAPIConnected

---------

Co-authored-by: Jason P <applewiz@mac.com>

* ExternalNotification and StatusLED now call AmbientLighting to update… (#9554)

* ExternalNotification and StatusLED now call AmbientLighting to update RGB LEDs. Add optional heartbeat

* Don't overwrite RGB state if heartbeat is disabled.

* Use the right define

* Remove another .h and make rgb static

* move rgb objects into AmbientLighting class

* Straighten out AmbientLighting Thread object

* Use %f for floats

* Fixes on SCD4X admin comands (#9607)

* Fixes on SCD4X admin comands

* Minor fix in logs for SEN5X

---------

Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* feat/add sfa30 (#9372)

* Move PMSA003I to separate class and update AQ telemetry

* AirQualityTelemetry module not depend on PM sensor presence

* Remove commented line

* Fixes on PMS class

* Add missing warmup period to wakeUp function

* Fixes on compilation for different variants

* Add functions to check for I2C bus speed and set it

* Initial implementation for SFA30Sensor

* Move PMSA003I to separate class and update AQ telemetry

* AirQualityTelemetry module not depend on PM sensor presence

* Remove commented line

* Fixes on PMS class

* Add missing warmup period to wakeUp function

* Fixes on compilation for different variants

* Add functions to check for I2C bus speed and set it

* Add ScreenFonts.h

Co-authored-by: Hannes Fuchs <hannes.fuchs+git@0xef.de>

* PMSA003I 1st round test

* Fix I2C scan speed

* Fix minor issues and bring back I2C SPEED def

* Remove PMSA003I library as its no longer needed

* Add functional SCD4X

* Fix screen frame for CO2

* Add admin commands to SCD4X class

* Add further admin commands and fixes.

* Remove unused I2C speed functions and cleanup

* Cleanup of SEN5X specific code added from switching branches
* Remove SCAN_I2C_CLOCK_SPEED block as its not needed
* Remove associated functions for setting I2C speed

* Unify build epoch to add flag in platformio-custom.py (#7917)

* Unify build_epoch replacement logic in platformio-custom

* Missed one

* Fix build error in rak_wismesh_tap_v2 (#7905)

In the logs was:
"No screen resolution defined in build_flags. Please define DISPLAY_SIZE."

set according to similar devices.

* Put guards in place around debug heap operations (#7955)

* Put guards in place around debug heap operations

* Add macros to clean up code

* Add pointer as well

* Cleanup

* Fix memory leak in NextHopRouter: always free packet copy when removing from pending

* Formatting

* Only queue 2 client notification

* Merge pull request #7965 from compumike/compumike/fix-nrf52-bluetooth-memory-leak

Fix memory leak in `NRF52Bluetooth`: allocate `BluetoothStatus` on stack, not heap

* Merge pull request #7964 from compumike/compumike/fix-nimble-bluetooth-memory-leak

Fix memory leak in `NimbleBluetooth`: allocate `BluetoothStatus` on stack, not heap

* Update protobufs (#7973)

Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com>

* T-Lora Pager: Support LR1121 and SX1280 models (#7956)

* T-Lora Pager: Support LR1121 and SX1280 models

* Remove ifdefs

* Trunk

* Trunk

* Static memory pool allocation (#7966)

* Static memory pool

* Initializer

* T-Lora Pager: Support LR1121 and SX1280 models (#7956)

* T-Lora Pager: Support LR1121 and SX1280 models

* Remove ifdefs

---------

Co-authored-by: WillyJL <me@willyjl.dev>

* Portduino dynamic alloc

* Missed

* Drop the limit

* Update meshtastic-esp8266-oled-ssd1306 digest to 0cbc26b (#7977)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>

* Fix json report crashes on esp32 (#7978)

* Tweak maximums

* Fix DRAM overflow on old esp32 targets

* Guard bad time warning logs using GPS_DEBUG (#7897)

In 2.7.7 / 2.7.8 we introduced some new checks for time accuracy.

In combination, these result in a spamming of the logs when a bad time is found

When the GPS is active, we're calling the GPS thread every 0.2secs.

So this log could be printed 4,500 times in a no-lock scenario :)

Reserve this experience for developers using GPS_DEBUG.

Fixes https://github.com/meshtastic/firmware/issues/7896

* Scale probe buffer size based on current baud rate (#7975)

* Scale probe buffer size based on current baud rate

* Throttle bad time validation logging and fix time comparison logic

* Remove comment

* Missed the other instances

* Copy pasta

* Fix GPS gm_mktime memory leak (#7981)

* Fix overflow of time value (#7984)

* Fix overflow of time value

* Revert "Fix overflow of time value"

This reverts commit 084796920179e80a7500d36c25fd4d82b3ef4214.

* That got boogered up

* Remove PMSA003 include from modules

* Add flag to exclude air quality module

* Rework PMSA003I to align with new I2C scanner

* Reworks AQ telemetry to match new dynamic allocation method
* Adds VBLE_I2C_CLOCK_SPEED build flag for sensors with different I2C speed requirements
* Reworks PMSA003I

* Move add sensor template to separate file

* Split telemetry on screen options

* Add variable I2C clock compile flag

* Added to Seeed Xiao S3 as demo

* Fix drawFrame in AQ module

* Module settings override to i2cScan module function

* Move to CAN_RECLOCK_I2C per architecture

* Add reclock function in TelemetrySensor.cpp
* Add flag in ESP32 common

* Minor fix

* Move I2C reclock function to src/detect

* Fix uninitMemberVar errors and compile issue

* Make sleep, wakeUp functions generic

* Fix STM32 builds

* Add exclude AQ sensor to builds that have environmental sensor excludes
* Add includes to AddI2CSensorTemplate.h

* SEN5X first pass

* WIP Sen5X functions

* Further (non-working) progress in SEN5X

* WIP Sen5X functions

* Changes on SEN5X library - removing pm_env as well

* Small cleanup of SEN5X sensors

* Minor change for SEN5X detection

* Remove dup code

* Enable PM sensor before sending telemetry.

This enables the PM sensor for a predefined period to allow for warmup.

Once telemetry is sent, the sensor shuts down again.

* Small cleanups in SEN5X sensor

* Add dynamic measurement interval for SEN5X

* Only disable SEN5X if enough time after reading.

* Idle for SEN5X on communication error

* Cleanup of logs and remove unnecessary delays

* Small TODO

* Settle on uint16_t for SEN5X PM data

* Make AQTelemetry sensors non-exclusive

* Implementation of cleaning in FS prefs and cleanup

* Remove unnecessary LOGS
* Add cleaning date storage in FS
* Report non-cumulative PN

* Bring back detection code for SEN5X after branch rebase

* Add placeholder for admin message

* Add VOC measurements and persistence (WIP)

* Adds VOC measurements and state
* Still not working on VOC Index persistence
* Should it stay in continuous mode?

* Add one-shot mode config flag to SEN5X

* Add nan checks on sensor data from SEN5X

* Working implementation on VOCState

* Adds initial timer for SEN55 to not sleep if VOCstate is not stable (1h)
* Adds conditions for stability and sensor state

* Fixes on VOC state and mode swtiching

* Adds a new RHT/Gas only mode, with 3600s stabilization time
* Fixes the VOCState buffer mismatch
* Fixes SEN50/54/55 model mistake

* Adapt SEN5X to new sensor list structure. Improve reclock.

* Improve reClockI2C conditions for different variants
* Add sleep, wakeUp, pendingForReady, hasSleep functions to PM sensors to save battery
* Add SEN5X

* Fix merge errors

* Small reordering in PMS class for consistency

* If one sensor fails, AQ telemetry still reports data

* Small formatting fix

* Add SEN5X to AQI in ScanI2C

* SCD4X now part of AQ module with template list

* Fixes difference between idle and sleep
* In LowPower, sleep is disabled
* Requires testing for I2C clock comms for commands

* Remove unnecessary import

* Add co2 to serialized AQ metrics

* Add SFA30 with new sensor template in AQ module

* Update library dependencies in platformio.ini

* Fix unitialized variables in SEN5X constructor

* Fix missing import

* Fix uninitMemberVars

* Fix import error for SCD4X

* Fix I2CClock logic

* Fix not reclocking back to 700000Hz

* Fix multiple sensors being read simultaneously

*  The logic in AQ module is different to the one in EnvironmentTelemetryModule.  In Env module, if any sensor fails to getMetrics, no valid flag for the module. This prevents other sensors to report data.

* Fix pending clock change in PMSA003

* Cleanup of SEN5X class

* Exclude AQ sensor from wio-e5 due to flash limitations

* Fix I2C clock change logic

* Make sure clock is always set to needed value

* Fix returns

* Fix trunk

* Fix on condition in reclock

* Fix trunk

* Final SFA30 class implementation

* Add HCHO to screen and improve logs

* Add metrics to mesh packet serializer

* Minor fixes in logs

* OCD tidy up of logs

* Fix sleep function

* Remove old I2C_CLOCK_SPEED code

---------

Co-authored-by: nikl <nikl174@mailbox.org>
Co-authored-by: Hannes Fuchs <hannes.fuchs+git@0xef.de>
Co-authored-by: Nashui-Yan <yannashui10@gmail.com>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
Co-authored-by: Tom Fifield <tom@tomfifield.net>
Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com>
Co-authored-by: WillyJL <me@willyjl.dev>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>

* Log rxBad PacketHeaders with more info (id, relay_node) like printPacket, so we can try to match RX errors to other packets in the logs. (#9614)

* Exclude status message module

* fix: zero entire public key array instead of only first byte (#9619)

* Update protobufs (#9621)

* Xiao NRF - define suitable i2c pins for the sub-variants (#8866)

Co-authored-by: Christian Walther <cwalther@gmx.ch>

* Update src/detect/ScanI2C.cpp

Co-authored-by: Wessel <wessel@weebl.me>

* Update src/modules/Telemetry/Sensor/SFA30Sensor.cpp

Co-authored-by: Wessel <wessel@weebl.me>

* Update src/modules/Telemetry/Sensor/SFA30Sensor.cpp

Co-authored-by: Wessel <wessel@weebl.me>

* Update src/modules/Telemetry/Sensor/SFA30Sensor.cpp

Co-authored-by: Wessel <wessel@weebl.me>

* Update src/mesh/NodeDB.cpp

Co-authored-by: Wessel <wessel@weebl.me>

* convert GPS global and some new in gps.cpp to unique_ptr (#9628)

Trying this to see if anything bad happen if I were to replace most raw pointers with unique_ptr.

I didn't used std::make_unique since it is only supported in C++14 and onwards but until we update esp32 to arduino 3.x the ESP32 xtensa chips use a C++11 std.

* replace delete in RedirectablePrint.cpp with std::unique_ptr (#9642)

Is part of the unique_ptr modernization effort.

* replace delete in EInkDynamicDisplay.{cpp,h} with std::unique_ptr (#9643)

Is part of the unique_ptr modernization effort.

* Undefine LED_BUILTIN for Heltec v2 variant (#9647)

* Undefine LED_BUILTIN for Heltec v2 variant

* Undefine LED_BUILTIN for Heltec v2.1 variant

---------

Co-authored-by: Jorropo <jorropo.pgm@gmail.com>

* replace delete in RadioInterface.cpp with std::unique_ptr (#9645)

Is part of the unique_ptr modernization effort.

* fix typo in PIN_GPS_SWITCH (#9648)

Wasn't caught by CI.

* replace delete in CryptoEngine.{cpp,h} with std::unique_ptr (#9649)

Is part of the unique_ptr modernization effort.

* workaround NCP5623 and LP5562 I2C builds (#9652)

Theses two appear to be buggy on r1-neo and nomadstar meteor pro, they rely on Wire.h being included previously to their import.

Idk why other platforms using the same smart LEDs are working while theses ones don't.

This should make CI green on the dev branch.

* replace delete in AudioThread.h with std::unique_ptr (#9651)

Is part of the unique_ptr modernization effort.

* Add USB_MODE=1 for Station G2 (#9660)

* InkHUD: Favorite Map Applet (#9654)

* fix a lot of low level cppcheck warnings (#9623)

* simplify the observer pattern, since all the called functions are const getters.
* use arduino macro over std: for numerical values and refactor local variables in drawScrollbar()
* oh, so Cppcheck actually complained about const pointers not being const.
* slowly getting out of ifdef hell
* fix inkHUD warnings as well
* last 2 check warnings
* git checks should fail on low defects from now on

* Feat/add scd30 (#9609)

* Merge develop into SCD30

* Add SCD30 class

* Fix logging and admin commands

* Minor cleanup and logging improvements

* Minor formatting issue

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Improvements on setTemperature

* Fix casting float-uint16_t
* Pass 100 for resetting temperature offset

* Fix issues pointed out by copilot

* Add quick reboot to set interval quicker on scd30

* Change saveState to only happen after boot and minor log changes

* Fix missing semicolon in one shot mode log

---------

Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* fix: respect DontMqttMeBro flag regardless of channel PSK (#9626)

The previous PSK check was broken from its introduction in #4643 —
memcmp was used in boolean context without comparing to 0, inverting
the condition. Since no one noticed for over a year, the PSK-based
filtering provided no practical value. Simplifying to always respect
the sender's preference is both more correct and easier to reason about.

* our firmware action is too clever

Update pio_target and add pio_opts for checks.

* fix detection of SCD30 by checking if the size of the return from a 2 byte register read is correct (#9664)

* fix detection of SCD30 by checking if thee size of the return from a 2 byte register read is correct
fix signedness warning in PMSA003 sensor code.

* Add alternate path for LPS22HB

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* check EndTransmission for errors and compare returned length to expected value

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* #9623 resolved a local shadow of next_key by converting it to int. (#9665)

* zip a few gitrefs down (#9672)

* InkHUD: Allow non-system applets to subscribe to input events (#9514)

* Allow inkhud user applets to consume inputs with opt-in system
Adds a way for applets to subscribe to input events while keeping it off
by default to preserve compatibility and expected behaviours. Adds
example for use as well.
* Add check for nullptr on getActiveApplet uses
* Remove redundant includes
* Move subscribedInputs to protected
* More consistent naming scheme

* Fake IAQ values on Non-BSEC2 platforms like Platformio and the original ESP32 (#9663)

* BSEC2 Replacement
- add approximation for IAQ to non-BSEC2 platforms.
- Re-add this sensor to ESP32 targets, and refactor env_extra includes.
- Fix C++ 11 compatibility
* Check for gas resistance 0

* ULED_BUILTIN for 9m2ibr_aprs_lora_tracker (#9685)

---------

Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Jason P <applewiz@mac.com>
Co-authored-by: Eric Sesterhenn <eric.sesterhenn@x41-dsec.de>
Co-authored-by: Vortetty <33466216+Vortetty@users.noreply.github.com>
Co-authored-by: Mattatat25 <108779801+mattatat25@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Max <rekin.m@gmail.com>
Co-authored-by: Colby Dillion <colby.dillion@pacshealth.com>
Co-authored-by: Austin <vidplace7@gmail.com>
Co-authored-by: Tom <116762865+NomDeTom@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Chloe Bethel <chloe@9net.org>
Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com>
Co-authored-by: Quency-D <55523105+Quency-D@users.noreply.github.com>
Co-authored-by: HarukiToreda <116696711+HarukiToreda@users.noreply.github.com>
Co-authored-by: oscgonfer <oscgonfer@users.noreply.github.com>
Co-authored-by: nikl <nikl174@mailbox.org>
Co-authored-by: Hannes Fuchs <hannes.fuchs+git@0xef.de>
Co-authored-by: Nashui-Yan <yannashui10@gmail.com>
Co-authored-by: Tom Fifield <tom@tomfifield.net>
Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu>
Co-authored-by: WillyJL <me@willyjl.dev>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Wessel <wessel@weebl.me>
Co-authored-by: Christian Walther <cwalther@gmx.ch>
Co-authored-by: Jorropo <jorropo.pgm@gmail.com>
Co-authored-by: Eric Barch <ericb@ericbarch.com>
Co-authored-by: Clive Blackledge <clive@ansible.org>
2026-02-19 07:16:33 -06:00
github-actions[bot]andvidplace7 d0cf79a991 Upgrade trunk (#9692)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-19 06:03:53 -06:00
github-actions[bot]andvidplace7 5408e81de7 Upgrade trunk (#9683)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-18 06:44:55 -06:00
renovate[bot] 357a33f454 chore(deps): update actions/stale action to v10.2.0 (#9669)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-17 05:45:54 -06:00
harry-iii-lord 4fccda26c6 Concurrency: Modern Periodic wrapper class. (#9501) 2026-02-17 05:44:26 -06:00
github-actions[bot]andvidplace7 f94c01b452 Upgrade trunk (#9671)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-17 05:38:13 -06:00
github-actions[bot]andvidplace7 321ccbf5e2 Upgrade trunk (#9661)
Co-authored-by: vidplace7 <1779290+vidplace7@users.noreply.github.com>
2026-02-16 05:52:46 -06:00
116 changed files with 5563 additions and 2852 deletions
-1
View File
@@ -96,7 +96,6 @@ jobs:
pio_platform: ${{ matrix.check.platform }}
pio_env: ${{ matrix.check.board }}
pio_target: check
pio_opts: --fail-on-defect=low
build:
needs: [setup, version]
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
steps:
- name: Stale PR+Issues
uses: actions/stale@v10.1.1
uses: actions/stale@v10.2.0
with:
days-before-stale: 45
stale-issue-message: This issue has not had any comment or update in the last month. If it is still relevant, please post update comments. If no comments are made, this issue will be closed automagically in 7 days.
+7 -7
View File
@@ -8,20 +8,20 @@ plugins:
uri: https://github.com/trunk-io/plugins
lint:
enabled:
- checkov@3.2.501
- renovate@43.10.3
- checkov@3.2.506
- renovate@43.43.2
- prettier@3.8.1
- trufflehog@3.93.3
- trufflehog@3.93.5
- yamllint@1.38.0
- bandit@1.9.3
- bandit@1.9.4
- trivy@0.69.1
- taplo@0.10.0
- ruff@0.15.1
- isort@7.0.0
- ruff@0.15.4
- isort@8.0.0
- markdownlint@0.47.0
- oxipng@10.1.0
- svgo@4.0.0
- actionlint@1.7.10
- actionlint@1.7.11
- flake8@7.3.0
- hadolint@2.14.0
- shfmt@3.6.0
+26
View File
@@ -0,0 +1,26 @@
# Lightweight container for running native PlatformIO tests on non-Linux hosts
FROM python:3.14-slim-trixie
ENV DEBIAN_FRONTEND=noninteractive
ENV PIP_ROOT_USER_ACTION=ignore
# hadolint ignore=DL3008
RUN apt-get update && apt-get install --no-install-recommends -y \
g++ git ca-certificates pkg-config \
libgpiod-dev libyaml-cpp-dev libbluetooth-dev libi2c-dev libuv1-dev \
libusb-1.0-0-dev libulfius-dev liborcania-dev libssl-dev \
libx11-dev libinput-dev libxkbcommon-x11-dev libsqlite3-dev libsdl2-dev \
&& apt-get clean && rm -rf /var/lib/apt/lists/* \
&& pip install --no-cache-dir platformio==6.1.19 \
&& useradd --create-home --shell /usr/sbin/nologin meshtastic
WORKDIR /firmware
RUN chown -R meshtastic:meshtastic /firmware
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD platformio --version || exit 1
USER meshtastic
# Run tests by default; override with docker run args for specific filters
CMD ["platformio", "test", "-e", "coverage", "-v"]
+1 -1
View File
@@ -23,4 +23,4 @@ for BOARD in $BOARDS; do
CHECK="${CHECK} -e ${BOARD}"
done
pio check --flags "-DAPP_VERSION=${APP_VERSION} --suppressions-list=suppressions.txt --inline-suppr" $CHECK --skip-packages --pattern="src/" --fail-on-defect=medium --fail-on-defect=high
pio check --flags "-DAPP_VERSION=${APP_VERSION} --suppressions-list=suppressions.txt --inline-suppr" $CHECK --skip-packages --pattern="src/" --fail-on-defect=low --fail-on-defect=medium --fail-on-defect=high
@@ -9,3 +9,5 @@ Lora:
DIO3_TCXO_VOLTAGE: true
DIO2_AS_RF_SWITCH: true
spidev: spidev0.0
GPIO_DETECT_PA: 13
TX_GAIN_LORA: [8, 8, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 9, 8, 8, 7]
+16
View File
@@ -0,0 +1,16 @@
# For use with Armbian luckfox-lyra-ultra-w
# Enable overlay 'luckfox-lyra-ultra-w-spi0-cs0-spidev' with armbian-config
# https://github.com/wehooper4/Meshtastic-Hardware/tree/main/Luckfox%20Ultra%20Hat
# 1 Watt Lyra Ultra hat
Lora:
Module: sx1262
DIO2_AS_RF_SWITCH: true
DIO3_TCXO_VOLTAGE: true
CS: 10
IRQ: 5
Busy: 11
Reset: 9
RXen: 14
spidev: spidev0.0 #pins are (CS=10, CLK=8, MOSI=6, MISO=7)
spiSpeed: 2000000
+17
View File
@@ -0,0 +1,17 @@
# For use with Armbian luckfox-lyra-ultra-w
# Enable overlay 'luckfox-lyra-ultra-w-spi0-cs0-spidev' with armbian-config
# https://github.com/wehooper4/Meshtastic-Hardware/tree/main/Luckfox%20Ultra%20Hat
# 2 Watt Lyra Ultra hat
Lora:
Module: sx1262
DIO2_AS_RF_SWITCH: true
DIO3_TCXO_VOLTAGE: true
SX126X_MAX_POWER: 8
CS: 10
IRQ: 5
Busy: 11
Reset: 9
RXen: 14
spidev: spidev0.0 #pins are (CS=10, CLK=8, MOSI=6, MISO=7)
spiSpeed: 2000000
@@ -0,0 +1,25 @@
# For use with Armbian luckfox-lyra // luckfox-lyra-plus
# Enable overlay 'luckfox-lyra-plus-spi0-cs0_rmio13-spidev' with armbian-config
# Waveshare LoRa HAT for Raspberry Pi Pico
# https://www.waveshare.com/wiki/Pico-LoRa-SX1262
Lora:
Module: sx1262
DIO2_AS_RF_SWITCH: true
DIO3_TCXO_VOLTAGE: true
spidev: spidev0.0
CS: # GPIO0_B5
pin: 13
gpiochip: 0
line: 13
IRQ: # GPIO1_C2
pin: 50
gpiochip: 1
line: 18
Busy: # GPIO0_B4
pin: 12
gpiochip: 0
line: 12
Reset: # GPIO0_A2
pin: 2
gpiochip: 0
line: 2
+1 -2
View File
@@ -13,8 +13,7 @@ Lora:
# USB_Serialnum: 12345678
SX126X_MAX_POWER: 22
# Reduce output power to improve EMI
NUM_PA_POINTS: 22
TX_GAIN_LORA: 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 9, 8, 8, 7
TX_GAIN_LORA: [12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 9, 8, 8, 7]
# Note: This module integrates an additional PA to achieve higher output power.
# The 'power' parameter here does not represent the actual RF output.
# TX_GAIN_LORA defines the gain offset applied at each SX1262 input power step (1–22 dBm).
+1 -2
View File
@@ -13,8 +13,7 @@ Lora:
# USB_Serialnum: 12345678
SX126X_MAX_POWER: 22
# Reduce output power to improve EMI
NUM_PA_POINTS: 22
TX_GAIN_LORA: 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 9, 8, 8, 7
TX_GAIN_LORA: [12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 9, 8, 8, 7]
# Note: This module integrates an additional PA to achieve higher output power.
# The 'power' parameter here does not represent the actual RF output.
# TX_GAIN_LORA defines the gain offset applied at each SX1262 input power step (1–22 dBm).
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Run native PlatformIO tests inside Docker (for macOS / non-Linux hosts).
#
# Usage:
# ./bin/test-native-docker.sh # run all native tests
# ./bin/test-native-docker.sh -f test_transmit_history # run specific test filter
# ./bin/test-native-docker.sh --rebuild # force rebuild the image
#
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
IMAGE_NAME="meshtastic-native-test"
REBUILD=false
EXTRA_ARGS=()
for arg in "$@"; do
if [[ "$arg" == "--rebuild" ]]; then
REBUILD=true
else
EXTRA_ARGS+=("$arg")
fi
done
if $REBUILD || ! docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then
echo "Building test image (first run may take a few minutes)..."
docker build -t "$IMAGE_NAME" -f "$ROOT_DIR/Dockerfile.test" "$ROOT_DIR"
fi
# Disable BUILD_EPOCH to avoid full rebuilds between test runs (matches CI)
sed_cmd='s/-DBUILD_EPOCH=$UNIX_TIME/#-DBUILD_EPOCH=$UNIX_TIME/'
# Default: run all tests. Pass extra args (e.g. -f test_transmit_history) through.
if [[ ${#EXTRA_ARGS[@]} -eq 0 ]]; then
CMD=("platformio" "test" "-e" "coverage" "-v")
else
CMD=("platformio" "test" "-e" "coverage" "-v" "${EXTRA_ARGS[@]}")
fi
exec docker run --rm \
-v "$ROOT_DIR:/src:ro" \
"$IMAGE_NAME" \
bash -c "rm -rf /tmp/fw-test && cp -a /src /tmp/fw-test && cd /tmp/fw-test && sed -i '${sed_cmd}' platformio.ini && ${CMD[*]}"
+40
View File
@@ -0,0 +1,40 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"partitions": "default.csv"
},
"core": "esp32",
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_ESP32S3_DEV",
"-DARDUINO_USB_MODE=1",
"-DARDUINO_USB_CDC_ON_BOOT=1",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "esp32s3"
},
"connectivity": ["wifi"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "LilyGo Mini-Epaper-S3 (4 MB Flash, 2MB PSRAM)",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 327680,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 460800
},
"url": "https://www.lilygo.cc",
"vendor": "LilyGo"
}
+4 -4
View File
@@ -138,7 +138,7 @@ lib_deps =
# renovate: datasource=custom.pio depName=Adafruit BME280 packageName=adafruit/library/Adafruit BME280 Library
adafruit/Adafruit BME280 Library@2.3.0
# renovate: datasource=custom.pio depName=Adafruit DPS310 packageName=adafruit/library/Adafruit DPS310
adafruit/Adafruit DPS310@1.1.5
adafruit/Adafruit DPS310@1.1.6
# renovate: datasource=custom.pio depName=Adafruit MCP9808 packageName=adafruit/library/Adafruit MCP9808 Library
adafruit/Adafruit MCP9808 Library@2.0.2
# renovate: datasource=custom.pio depName=Adafruit INA260 packageName=adafruit/library/Adafruit INA260 Library
@@ -150,7 +150,7 @@ lib_deps =
# renovate: datasource=custom.pio depName=Adafruit LIS3DH packageName=adafruit/library/Adafruit LIS3DH
adafruit/Adafruit LIS3DH@1.3.0
# renovate: datasource=custom.pio depName=Adafruit AHTX0 packageName=adafruit/library/Adafruit AHTX0
adafruit/Adafruit AHTX0@2.0.5
adafruit/Adafruit AHTX0@2.0.6
# renovate: datasource=custom.pio depName=Adafruit LSM6DS packageName=adafruit/library/Adafruit LSM6DS
adafruit/Adafruit LSM6DS@4.7.4
# renovate: datasource=custom.pio depName=Adafruit TSL2591 packageName=adafruit/library/Adafruit TSL2591 Library
@@ -158,7 +158,7 @@ lib_deps =
# renovate: datasource=custom.pio depName=EmotiBit MLX90632 packageName=emotibit/library/EmotiBit MLX90632
emotibit/EmotiBit MLX90632@1.0.8
# renovate: datasource=custom.pio depName=Adafruit MLX90614 packageName=adafruit/library/Adafruit MLX90614 Library
adafruit/Adafruit MLX90614 Library@2.1.5
adafruit/Adafruit MLX90614 Library@2.1.6
# renovate: datasource=git-refs depName=INA3221 packageName=https://github.com/sgtwilko/INA3221 gitBranch=FixOverflow
https://github.com/sgtwilko/INA3221/archive/bb03d7e9bfcc74fc798838a54f4f99738f29fc6a.zip
# renovate: datasource=custom.pio depName=QMC5883L Compass packageName=mprograms/library/QMC5883LCompass
@@ -180,7 +180,7 @@ lib_deps =
# renovate: datasource=custom.pio depName=DFRobot_BMM150 packageName=dfrobot/library/DFRobot_BMM150
dfrobot/DFRobot_BMM150@1.0.0
# renovate: datasource=custom.pio depName=Adafruit_TSL2561 packageName=adafruit/library/Adafruit TSL2561
adafruit/Adafruit TSL2561@1.1.2
adafruit/Adafruit TSL2561@1.1.3
# renovate: datasource=custom.pio depName=BH1750_WE packageName=wollewald/library/BH1750_WE
wollewald/BH1750_WE@1.1.10
+1 -3
View File
@@ -51,9 +51,7 @@ class AudioThread : public concurrency::OSThread
i2sRtttl = nullptr;
}
if (rtttlFile != nullptr) {
rtttlFile = nullptr;
}
rtttlFile = nullptr;
setCPUFast(false);
#ifdef T_LORA_PAGER
+4
View File
@@ -182,7 +182,11 @@ static void darkEnter()
static void serialEnter()
{
LOG_POWERFSM("State: serialEnter");
#ifndef ARCH_NRF52
// nRF52 runs BLE on SoftDevice independently of USB serial — no need to disable it.
// (Same rationale as nbEnter() which already guards this with #ifdef ARCH_ESP32)
setBluetoothEnable(false);
#endif
if (screen) {
screen->setOn(true);
}
+2
View File
@@ -35,6 +35,8 @@ void consoleInit()
#if defined(SERIAL_HAS_ON_RECEIVE)
// onReceive does only exist for HardwareSerial not for USB CDC serial
Port.onReceive([sc]() { sc->rxInt(); });
#else
(void)sc;
#endif
DEBUG_PORT.rpInit(); // Simply sets up semaphore
}
+11 -6
View File
@@ -1,24 +1,29 @@
#pragma once
#include <functional>
#include <utility>
#include "concurrency/OSThread.h"
namespace concurrency
{
/**
* @brief Periodically invoke a callback. This just provides C-style callback conventions
* rather than a virtual function - FIXME, remove?
* @brief Periodically invoke a callback.
* Supports both legacy function pointers and modern callables.
*/
class Periodic : public OSThread
{
int32_t (*callback)();
public:
// callback returns the period for the next callback invocation (or 0 if we should no longer be called)
Periodic(const char *name, int32_t (*_callback)()) : OSThread(name), callback(_callback) {}
Periodic(const char *name, int32_t (*cb)()) : OSThread(name), callback(cb) {}
Periodic(const char *name, std::function<int32_t()> cb) : OSThread(name), callback(std::move(cb)) {}
protected:
int32_t runOnce() override { return callback(); }
int32_t runOnce() override { return callback ? callback() : 0; }
private:
std::function<int32_t()> callback;
};
} // namespace concurrency
+64
View File
@@ -528,5 +528,69 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
#define HAS_SCREEN 0
#endif
// -----------------------------------------------------------------------------
// MESHTASTIC_LOCKDOWN — combined hardened build flag
//
// All targets:
// DEBUG_MUTE — suppress serial/USB log output
// MESHTASTIC_EXCLUDE_* — strip non-essential modules
// MESHTASTIC_PHONEAPI_ACCESS_CONTROL — redact keys from unauthenticated BLE/USB/TCP clients
// HARDENED_DEFAULTS — set is_managed, RANDOM_PIN, TAK role at first boot
//
// nRF52 (CC310 hardware crypto):
// MESHTASTIC_ENCRYPTED_STORAGE — AES-128-CTR + HMAC-SHA256 at-rest encryption
// MESHTASTIC_ENABLE_APPROTECT — write UICR APPROTECT to block debug probe
//
// ESP32 (stub — mbedTLS crypto TODO):
// MESHTASTIC_ENCRYPTED_STORAGE — same API, plaintext pass-through until ported
// APPROTECT equivalent — burn JTAG_DISABLE + flash encryption via espsecure.py
// -----------------------------------------------------------------------------
#ifdef MESHTASTIC_LOCKDOWN
// Suppress all serial/USB-CDC log output — prevents info leakage via physical access
#define DEBUG_MUTE
// Strip non-essential modules to reduce attack surface
#define MESHTASTIC_EXCLUDE_DETECTIONSENSOR 1
#define MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR 1
#define MESHTASTIC_EXCLUDE_AIR_QUALITY 1
#define MESHTASTIC_EXCLUDE_HEALTH_TELEMETRY 1
#define MESHTASTIC_EXCLUDE_POWER_TELEMETRY 1
#define MESHTASTIC_EXCLUDE_RANGETEST 1
#define MESHTASTIC_EXCLUDE_REMOTEHARDWARE 1
#define MESHTASTIC_EXCLUDE_STOREFORWARD 1
#define MESHTASTIC_EXCLUDE_CANNEDMESSAGES 1
#define MESHTASTIC_EXCLUDE_SERIAL 1
#define MESHTASTIC_EXCLUDE_POWERSTRESS 1
#define MESHTASTIC_EXCLUDE_DROPZONE 1
#define MESHTASTIC_EXCLUDE_REPLYBOT 1
#define MESHTASTIC_EXCLUDE_PAXCOUNTER 1
#define MESHTASTIC_EXCLUDE_AUDIO 1
#define MESHTASTIC_EXCLUDE_STATUS 1
#define MESHTASTIC_EXCLUDE_GENERIC_THREAD_MODULE 1
#define MESHTASTIC_EXCLUDE_POWERMON 1
#define MESHTASTIC_EXCLUDE_EXTERNALNOTIFICATION 1
// Access control and hardened defaults are pure C++ — no platform-specific deps.
#define MESHTASTIC_PHONEAPI_ACCESS_CONTROL 1
#define HARDENED_DEFAULTS 1
// Platform-specific security features:
#if defined(ARCH_NRF52)
// Full encrypted storage via CC310 hardware AES-128-CTR + HMAC-SHA256.
#define MESHTASTIC_ENCRYPTED_STORAGE 1
// Hardware JTAG/SWD lockout: firmware writes NRF_UICR->APPROTECT = 0x00 once.
#define MESHTASTIC_ENABLE_APPROTECT 1
#elif defined(ARCH_ESP32)
// Encrypted storage stub: plaintext pass-through, same API, crypto TODO (mbedTLS).
// APPROTECT equivalent: burn JTAG_DISABLE eFuse and enable flash encryption
// via espsecure.py at provisioning time — not firmware-controlled.
#define MESHTASTIC_ENCRYPTED_STORAGE 1
#else
#warning "MESHTASTIC_LOCKDOWN: encrypted storage not available on this platform; access control and hardened defaults still active"
#endif
#endif // MESHTASTIC_LOCKDOWN
#include "DebugConfiguration.h"
#include "RF95Configuration.h"
+11
View File
@@ -259,6 +259,17 @@ bool EInkDisplay::connect()
adafruitDisplay->setRotation(3);
adafruitDisplay->setPartialWindow(0, 0, EINK_WIDTH, EINK_HEIGHT);
}
#elif defined(MINI_EPAPER_S3)
spi1 = new SPIClass(HSPI);
spi1->begin(PIN_SPI1_SCK, PIN_SPI1_MISO, PIN_SPI1_MOSI, PIN_EINK_CS);
// Create GxEPD2 objects
auto lowLevel = new EINK_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY, *spi1);
adafruitDisplay = new GxEPD2_BW<EINK_DISPLAY_MODEL, EINK_DISPLAY_MODEL::HEIGHT>(*lowLevel);
// Init GxEPD2
adafruitDisplay->init();
adafruitDisplay->setRotation(1);
#elif defined(HELTEC_WIRELESS_PAPER) || defined(HELTEC_VISION_MASTER_E213)
// Detect display model, before starting SPI
+2 -1
View File
@@ -93,7 +93,8 @@ class EInkDisplay : public OLEDDisplay
SPIClass *hspi = NULL;
#endif
#if defined(HELTEC_MESH_POCKET) || defined(SEEED_WIO_TRACKER_L1_EINK) || defined(HELTEC_MESH_SOLAR_EINK)
#if defined(HELTEC_MESH_POCKET) || defined(SEEED_WIO_TRACKER_L1_EINK) || defined(HELTEC_MESH_SOLAR_EINK) || \
defined(MINI_EPAPER_S3)
SPIClass *spi1 = NULL;
#endif
+4
View File
@@ -875,6 +875,10 @@ int32_t Screen::runOnce()
break;
case Cmd::STOP_ALERT_FRAME:
NotificationRenderer::pauseBanner = false;
// Return from one-off alert mode back to regular frames.
if (!showingNormalScreen && NotificationRenderer::current_notification_type != notificationTypeEnum::text_input) {
setFrames();
}
break;
case Cmd::STOP_BOOT_SCREEN:
EINK_ADD_FRAMEFLAG(dispdev, COSMETIC); // E-Ink: Explicitly use full-refresh for next frame
+2 -2
View File
@@ -1209,8 +1209,8 @@ void TFTDisplay::display(bool fromBlank)
bool somethingChanged = false;
// Store colors byte-reversed so that TFT_eSPI doesn't have to swap bytes in a separate step
colorTftMesh = (TFT_MESH >> 8) | ((TFT_MESH & 0xFF) << 8);
colorTftBlack = (TFT_BLACK >> 8) | ((TFT_BLACK & 0xFF) << 8);
colorTftMesh = __builtin_bswap16(TFT_MESH);
colorTftBlack = __builtin_bswap16(TFT_BLACK);
y = 0;
while (y < displayHeight) {
-6
View File
@@ -12,7 +12,6 @@
#include "graphics/TimeFormatters.h"
#include "graphics/images.h"
#include "main.h"
#include "modules/CannedMessageModule.h"
#include "target_specific.h"
#include <OLEDDisplay.h>
#include <RTC.h>
@@ -1423,11 +1422,6 @@ void UIRenderer::drawNavigationBar(OLEDDisplay *display, OLEDDisplayUiState *sta
const int totalWidth = (pageEnd - pageStart) * iconSize + (pageEnd - pageStart - 1) * spacing;
const int xStart = (SCREEN_WIDTH - totalWidth) / 2;
// Suppress nav overlay entirely
if (cannedMessageModule && cannedMessageModule->isFreeTextUIActive()) {
return;
}
bool navBarVisible = millis() - lastFrameChangeTime <= ICON_DISPLAY_DURATION_MS;
int y = navBarVisible ? (SCREEN_HEIGHT - iconSize - 1) : SCREEN_HEIGHT;
@@ -73,7 +73,7 @@ ProcessMessage InkHUD::FavoritesMapApplet::handleReceived(const meshtastic_MeshP
}
} else {
// For non-local packets, this applet only reacts to favorited nodes.
meshtastic_NodeInfoLite *sender = nodeDB->getMeshNode(mp.from);
const meshtastic_NodeInfoLite *sender = nodeDB->getMeshNode(mp.from);
if (!sender || !sender->is_favorite)
return ProcessMessage::CONTINUE;
+2 -1
View File
@@ -276,7 +276,8 @@ int32_t ButtonThread::runOnce()
case BUTTON_EVENT_LONG_RELEASED: {
LOG_INFO("LONG PRESS RELEASE AFTER %u MILLIS", millis() - buttonPressStartTime);
if (millis() > 30000 && _longLongPress != INPUT_BROKER_NONE &&
// Require press started after boot holdoff to avoid phantom shutdown from floating pins
if (millis() > 30000 && buttonPressStartTime > 30000 && _longLongPress != INPUT_BROKER_NONE &&
(millis() - buttonPressStartTime) >= _longLongPressTime && leadUpPlayed) {
evt.inputEvent = _longLongPress;
this->notifyObservers(&evt);
+16 -1
View File
@@ -100,13 +100,28 @@ void InputBroker::processInputEventQueue()
int InputBroker::handleInputEvent(const InputEvent *event)
{
powerFSM.trigger(EVENT_INPUT); // todo: not every input should wake, like long hold release
#if HAS_SCREEN
bool screenWasOff = false;
if (screen) {
screenWasOff = !screen->isScreenOn();
}
#endif
powerFSM.trigger(EVENT_INPUT);
if (event && event->inputEvent != INPUT_BROKER_NONE && externalNotificationModule &&
moduleConfig.external_notification.enabled && externalNotificationModule->nagging()) {
externalNotificationModule->stopNow();
// If this turns off a notification, don't further process the event
return 0;
}
#if HAS_SCREEN
if (screen && screenWasOff) {
// If the screen was off, it is in the process of turning on, and we just drop the event
return 0;
}
#endif
this->notifyObservers(event);
return 0;
}
+35 -3
View File
@@ -9,6 +9,7 @@
#include "PowerMon.h"
#include "RadioLibInterface.h"
#include "ReliableRouter.h"
#include "TransmitHistory.h"
#include "airtime.h"
#include "buzz.h"
#include "power/PowerHAL.h"
@@ -58,6 +59,13 @@ NimbleBluetooth *nimbleBluetooth = nullptr;
NRF52Bluetooth *nrf52Bluetooth = nullptr;
#endif
#ifdef MESHTASTIC_ENABLE_APPROTECT
#include "security/APProtect.h"
#endif
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
#include "security/EncryptedStorage.h"
#endif
#if HAS_WIFI || defined(USE_WS5500)
#include "mesh/api/WiFiServerAPI.h"
#include "mesh/wifi/WiFiAPClient.h"
@@ -246,7 +254,6 @@ uint32_t timeLastPowered = 0;
static OSThread *powerFSMthread;
OSThread *ambientLightingThread;
RadioInterface *rIf = NULL;
RadioLibHal *RadioLibHAL = NULL;
/**
@@ -364,6 +371,10 @@ void setup()
consoleInit(); // Set serial baud rate and init our mesh console
#endif
#ifdef MESHTASTIC_ENABLE_APPROTECT
enableAPProtect();
#endif
#ifdef UNPHONE
unphone.printStore();
#endif
@@ -389,8 +400,8 @@ void setup()
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
#ifndef SENSECAP_INDICATOR
// use PSRAM for malloc calls > 256 bytes
heap_caps_malloc_extmem_enable(256);
// use PSRAM for malloc calls > 2048 bytes
heap_caps_malloc_extmem_enable(2048);
#endif
#endif
@@ -461,6 +472,17 @@ void setup()
fsInit();
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
EncryptedStorage::initLocked();
if (!EncryptedStorage::isUnlocked()) {
if (!EncryptedStorage::isProvisioned()) {
LOG_WARN("TAK: Device not provisioned — connect and set a passphrase to unlock storage");
} else {
LOG_WARN("TAK: Device locked — connect and provide passphrase to unlock storage");
}
}
#endif
#if !MESHTASTIC_EXCLUDE_I2C
#if defined(I2C_SDA1) && defined(ARCH_RP2040)
Wire1.setSDA(I2C_SDA1);
@@ -704,6 +726,9 @@ void setup()
// We do this as early as possible because this loads preferences from flash
// but we need to do this after main cpu init (esp32setup), because we need the random seed set
nodeDB = new NodeDB;
// Initialize transmit history to persist broadcast throttle timers across reboots
TransmitHistory::getInstance()->loadFromDisk();
#if HAS_TFT
if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_COLOR) {
tftSetup();
@@ -1125,6 +1150,13 @@ void loop()
lastRadioMissedIrqPoll = millis();
RadioLibInterface::instance->pollMissedIrqs();
}
// Periodic AGC reset — warm sleep + recalibrate to prevent stuck AGC gain
static uint32_t lastAgcReset;
if (!Throttle::isWithinTimespanMs(lastAgcReset, AGC_RESET_INTERVAL_MS)) {
lastAgcReset = millis();
RadioLibInterface::instance->resetAGC();
}
}
#ifdef DEBUG_STACK
+3 -7
View File
@@ -22,6 +22,8 @@ const char *Channels::serialChannel = "serial";
const char *Channels::mqttChannel = "mqtt";
#endif
meshtastic_Channel dummyChannel = {.index = -1};
uint8_t xorHash(const uint8_t *p, size_t len)
{
uint8_t code = 0;
@@ -309,13 +311,7 @@ meshtastic_Channel &Channels::getByIndex(ChannelIndex chIndex)
return *ch;
} else {
LOG_ERROR("Invalid channel index %d > %d, malformed packet received?", chIndex, channelFile.channels_count);
static meshtastic_Channel *ch = (meshtastic_Channel *)malloc(sizeof(meshtastic_Channel));
memset(ch, 0, sizeof(meshtastic_Channel));
// ch.index -1 means we don't know the channel locally and need to look it up by settings.name
// not sure this is handled right everywhere
ch->index = -1;
return *ch;
return dummyChannel;
}
}
+32
View File
@@ -299,6 +299,38 @@ template <typename T> bool LR11x0Interface<T>::isActivelyReceiving()
RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED);
}
#ifdef LR11X0_AGC_RESET
template <typename T> void LR11x0Interface<T>::resetAGC()
{
// Safety: don't reset mid-packet
if (sendingPacket != NULL || (isReceiving && isActivelyReceiving()))
return;
LOG_DEBUG("LR11x0 AGC reset: warm sleep + Calibrate(0x3F)");
// 1. Warm sleep — powers down the analog frontend, resetting AGC state
lora.sleep(true, 0);
// 2. Wake to RC standby for stable calibration
lora.standby(RADIOLIB_LR11X0_STANDBY_RC, true);
// 3. Calibrate all blocks (PLL, ADC, image, RC oscillators)
// calibrate() is protected on LR11x0, so use raw SPI (same as internal implementation)
uint8_t calData = RADIOLIB_LR11X0_CALIBRATE_ALL;
module.SPIwriteStream(RADIOLIB_LR11X0_CMD_CALIBRATE, &calData, 1, true, true);
// 4. Re-calibrate image rejection for actual operating frequency
// Calibrate(0x3F) defaults to 902-928 MHz which is wrong for other regions.
lora.calibrateImageRejection(getFreq() - 4.0f, getFreq() + 4.0f);
// 5. Re-apply RX boosted gain mode
lora.setRxBoostedGainMode(config.lora.sx126x_rx_boosted_gain);
// 6. Resume receiving
startReceive();
}
#endif
template <typename T> bool LR11x0Interface<T>::sleep()
{
// \todo Display actual typename of the adapter, not just `LR11x0`
+4
View File
@@ -27,6 +27,10 @@ template <class T> class LR11x0Interface : public RadioLibInterface
bool isIRQPending() override { return lora.getIrqFlags() != 0; }
#ifdef LR11X0_AGC_RESET
void resetAGC() override;
#endif
protected:
/**
* Specific module instance
+12
View File
@@ -106,6 +106,18 @@ class MeshModule
/* We allow modules to ignore a request without sending an error if they have a specific reason for it. */
bool ignoreRequest = false;
/**
* Check if the current request is a multi-hop broadcast. Modules should call this in allocReply()
* and return NULL to prevent reply storms from broadcast requests that have already been relayed.
*/
bool isMultiHopBroadcastRequest()
{
if (currentRequest && isBroadcast(currentRequest->to) && currentRequest->hop_limit < currentRequest->hop_start) {
return true;
}
return false;
}
/** If a bound channel name is set, we will only accept received packets that come in on that channel.
* A special exception (FIXME, not sure if this is a good idea) - packets that arrive on the local interface
* are allowed on any channel (this lets the local user do anything).
+23
View File
@@ -184,6 +184,29 @@ bool MeshPacketQueue::replaceLowerPriorityPacket(meshtastic_MeshPacket *p)
}
}
if (backPacket->tx_after) {
// Check if there's a late packet at the queue end
auto now = millis();
if (backPacket->tx_after < now && (!p->tx_after || backPacket->tx_after > p->tx_after)) {
int32_t dt = (int32_t)(backPacket->tx_after - now);
if (p->tx_after) {
LOG_WARN("Dropping late packet 0x%08x with TX delay %dms to make room in the TX queue for packet 0x%08x with "
"TX delay %ums",
backPacket->id, dt, p->id, p->tx_after - now);
} else {
LOG_WARN("Dropping late packet 0x%08x with TX delay %dms to make room in the TX queue for packet 0x%08x "
"with no TX delay",
backPacket->id, dt, p->id);
}
queue.pop_back();
packetPool.release(backPacket);
// Insert the new packet in the correct order
enqueue(p);
return true;
}
}
// If the back packet's priority is not lower, no replacement occurs
return false;
}
+152 -7
View File
@@ -30,6 +30,10 @@
#include <power/PowerHAL.h>
#include <vector>
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
#include "security/EncryptedStorage.h"
#endif
#ifdef ARCH_ESP32
#if HAS_WIFI
#include "mesh/wifi/WiFiAPClient.h"
@@ -143,9 +147,8 @@ uint32_t get_st7789_id(uint8_t cs, uint8_t sck, uint8_t mosi, uint8_t dc, uint8_
digitalWrite(rst, HIGH);
delay(10);
uint32_t ID = 0;
ID = readwrite8(0x04, 24, 1, cs, sck, mosi, dc, rst);
ID = readwrite8(0x04, 24, 1, cs, sck, mosi, dc, rst); // ST7789 needs twice
readwrite8(0x04, 24, 1, cs, sck, mosi, dc, rst);
uint32_t ID = readwrite8(0x04, 24, 1, cs, sck, mosi, dc, rst); // ST7789 needs twice
return ID;
}
@@ -322,9 +325,9 @@ NodeDB::NodeDB()
// Uncomment below to always enable UDP broadcasts
// config.network.enabled_protocols = meshtastic_Config_NetworkConfig_ProtocolFlags_UDP_BROADCAST;
// If we are setup to broadcast on the default channel, ensure that the telemetry intervals are coerced to the minimum value
// of 30 minutes or more
if (channels.isDefaultChannel(channels.getPrimaryIndex())) {
// If we are setup to broadcast on any default channel slot (with default frequency slot semantics),
// ensure that the telemetry intervals are coerced to the minimum value of 30 minutes or more.
if (channels.hasDefaultChannel()) {
LOG_DEBUG("Coerce telemetry to min of 30 minutes on defaults");
moduleConfig.telemetry.device_update_interval = Default::getConfiguredOrMinimumValue(
moduleConfig.telemetry.device_update_interval, min_default_telemetry_interval_secs);
@@ -646,6 +649,20 @@ void NodeDB::installDefaultConfig(bool preserveKey = false)
config.security.private_key.size = 0;
}
config.security.public_key.size = 0;
#ifdef HARDENED_DEFAULTS
config.security.serial_enabled = false; // Disable USB serial PhoneAPI — no auth, physical access only
config.security.debug_log_api_enabled = false; // No debug log leaks
config.security.admin_channel_enabled = false; // No legacy admin channel
config.security.is_managed = true; // Block all from=0 admin when unlocked;
// operator must use PKC admin key to configure.
// Passphrase delivery still works when locked
// (AdminModule special-cases !isUnlocked()).
config.device.rebroadcast_mode = meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY;
// FIXED_PIN allows the operator to connect via BLE and provision the passphrase.
config.bluetooth.mode = meshtastic_Config_BluetoothConfig_PairingMode_FIXED_PIN;
#endif
#ifdef PIN_GPS_EN
config.position.gps_en_gpio = PIN_GPS_EN;
#endif
@@ -711,7 +728,9 @@ void NodeDB::installDefaultConfig(bool preserveKey = false)
#ifdef USERPREFS_FIXED_BLUETOOTH
config.bluetooth.fixed_pin = USERPREFS_FIXED_BLUETOOTH;
config.bluetooth.mode = meshtastic_Config_BluetoothConfig_PairingMode_FIXED_PIN;
#else
#elif !defined(HARDENED_DEFAULTS)
// Default: use RANDOM_PIN only if device has a screen (to display the PIN).
// set FIXED_PIN in the HARDENED_DEFAULTS block above.
config.bluetooth.mode = hasScreen ? meshtastic_Config_BluetoothConfig_PairingMode_RANDOM_PIN
: meshtastic_Config_BluetoothConfig_PairingMode_FIXED_PIN;
#endif
@@ -1149,6 +1168,37 @@ LoadFileResult NodeDB::loadProto(const char *filename, size_t protoSize, size_t
void *dest_struct)
{
LoadFileResult state = LoadFileResult::OTHER_FAILURE;
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// check if the file is encrypted and decrypt before protobuf decode
if (EncryptedStorage::isEncrypted(filename)) {
uint8_t *decBuf = new uint8_t[protoSize];
if (!decBuf) {
LOG_ERROR("OOM decrypting %s", filename);
return LoadFileResult::OTHER_FAILURE;
}
size_t decLen = 0;
if (EncryptedStorage::readAndDecrypt(filename, decBuf, protoSize, decLen)) {
LOG_INFO("Load encrypted %s", filename);
pb_istream_t stream = pb_istream_from_buffer(decBuf, decLen);
if (fields != &meshtastic_NodeDatabase_msg)
memset(dest_struct, 0, objSize);
if (!pb_decode(&stream, fields, dest_struct)) {
LOG_ERROR("Error: can't decode protobuf %s", PB_GET_ERROR(&stream));
state = LoadFileResult::DECODE_FAILED;
} else {
LOG_INFO("Loaded encrypted %s successfully", filename);
state = LoadFileResult::LOAD_SUCCESS;
}
} else {
LOG_ERROR("Decrypt failed for %s, treating as corrupt", filename);
state = LoadFileResult::DECODE_FAILED;
}
delete[] decBuf;
return state;
}
#endif
#ifdef FSCom
concurrency::LockGuard g(spiLock);
@@ -1225,6 +1275,21 @@ void NodeDB::loadFromDisk()
}
#endif
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
if (!EncryptedStorage::isUnlocked()) {
// Encrypted storage is locked — install defaults and wait for passphrase via BLE/serial.
// reloadFromDisk() will be called by AdminModule once the device is unlocked.
LOG_WARN("NodeDB: Encrypted storage locked, using default config until unlocked");
installDefaultNodeDatabase();
installDefaultDeviceState();
installDefaultConfig();
installDefaultModuleConfig();
installDefaultChannels();
return;
}
#endif
auto state = loadProto(nodeDatabaseFileName, getMaxNodesAllocatedSize(), sizeof(meshtastic_NodeDatabase),
&meshtastic_NodeDatabase_msg, &nodeDatabase);
if (nodeDatabase.version < DEVICESTATE_MIN_VER) {
@@ -1386,6 +1451,35 @@ void NodeDB::loadFromDisk()
LOG_INFO("Loaded UIConfig");
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// Ensure all config segments are persisted to encrypted storage.
// installDefaultConfig/installDefaultModuleConfig only set in-memory structs
// without saving to disk, so we force a save here to ensure encrypted files exist.
{
const char *filesToCheck[] = {configFileName, moduleConfigFileName, channelFileName, deviceStateFileName,
nodeDatabaseFileName};
int segments[] = {SEGMENT_CONFIG, SEGMENT_MODULECONFIG, SEGMENT_CHANNELS, SEGMENT_DEVICESTATE, SEGMENT_NODEDATABASE};
int toSave = 0;
for (int i = 0; i < 5; i++) {
if (!EncryptedStorage::isEncrypted(filesToCheck[i])) {
toSave |= segments[i];
}
}
if (toSave) {
LOG_INFO("TAK: Saving unencrypted segments to encrypted storage (mask=0x%x)", toSave);
saveToDisk(toSave);
}
// Migrate any remaining plaintext proto files (from standard firmware upgrade)
for (const char *fn : filesToCheck) {
if (!EncryptedStorage::isEncrypted(fn)) {
LOG_INFO("Migrating %s to encrypted storage", fn);
EncryptedStorage::migrateFile(fn);
}
}
}
#endif
// 2.4.X - configuration migration to update new default intervals
if (moduleConfig.version < 23) {
LOG_DEBUG("ModuleConfig version %d is stale, upgrading to new default intervals", moduleConfig.version);
@@ -1421,8 +1515,21 @@ void NodeDB::loadFromDisk()
}
#endif
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
/**
* Re-run loadFromDisk() after encrypted storage is unlocked at runtime.
* Called by AdminModule after a successful provisionPassphrase / unlockWithPassphrase.
*/
void NodeDB::reloadFromDisk()
{
LOG_INFO("NodeDB: Reloading config from encrypted storage after unlock");
loadFromDisk();
}
#endif
/** Save a protobuf from a file, return true for success */
bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct,
bool fullAtomic)
@@ -1435,6 +1542,34 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_
return false;
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// Encrypt all files except uiconfig (no secrets) and the DEK file (self-encrypted)
if (strcmp(filename, uiconfigFileName) != 0) {
// First encode protobuf to a temporary buffer
uint8_t *pbBuf = new uint8_t[protoSize];
if (!pbBuf) {
LOG_ERROR("OOM encoding %s for encryption", filename);
return false;
}
pb_ostream_t stream = pb_ostream_from_buffer(pbBuf, protoSize);
if (!pb_encode(&stream, fields, dest_struct)) {
LOG_ERROR("Error: can't encode protobuf %s", PB_GET_ERROR(&stream));
delete[] pbBuf;
return false;
}
size_t encodedSize = stream.bytes_written;
bool ok = EncryptedStorage::encryptAndWrite(filename, pbBuf, encodedSize, fullAtomic);
delete[] pbBuf;
if (!ok) {
LOG_ERROR("EncryptedStorage: Failed to encrypt and write %s", filename);
}
return ok;
}
#endif
bool okay = false;
#ifdef FSCom
auto f = SafeFile(filename, fullAtomic);
@@ -1527,6 +1662,16 @@ bool NodeDB::saveToDiskNoRetry(int saveWhat)
return false;
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// When encrypted storage is locked, encryptAndWrite() returns false for every file.
// That would cause saveToDisk()'s nRF52 retry path to call FSCom.format(), wiping all
// encrypted proto files from flash. Return true here — "nothing to save, not an error."
if (!EncryptedStorage::isUnlocked()) {
LOG_WARN("NodeDB: saveToDisk skipped — encrypted storage locked");
return true;
}
#endif
bool success = true;
#ifdef FSCom
spiLock->lock();
+6
View File
@@ -307,6 +307,12 @@ class NodeDB
newStatus.notifyObservers(&status);
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
/// Re-run loadFromDisk() after the encrypted storage is unlocked at runtime.
/// Called by AdminModule after a successful provisionPassphrase / unlockWithPassphrase.
void reloadFromDisk();
#endif
private:
bool duplicateWarned = false;
bool localPositionUpdatedSinceBoot = false;
+175 -14
View File
@@ -3,6 +3,9 @@
#include "GPS.h"
#endif
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
#include "security/EncryptedStorage.h"
#endif
#include "Channels.h"
#include "Default.h"
#include "FSCommon.h"
@@ -54,6 +57,16 @@ void PhoneAPI::handleStartConfig()
observe(&service->fromNumChanged);
#ifdef FSCom
observe(&xModem.packetReady);
#endif
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
// New physical connection: reset per-connection PKC auth.
// Do NOT reset here on re-requests (want_config_id sent again within the same
// connection after auth) — that would strip auth from a client who just unlocked
// and is re-fetching the full unredacted config.
isAdminAuthorized = false;
// MED-2: s_localAdminAuthorized (device-level passphrase auth) is intentionally
// NOT reset here. It persists until an explicit Lock Now (revokeAllAuth()).
// Resetting it on every new connection would cause an auth DoS.
#endif
}
@@ -127,6 +140,13 @@ void PhoneAPI::close()
config_state = 0;
pauseBluetoothLogging = false;
heartbeatReceived = false;
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
isAdminAuthorized = false;
// MED-2: do NOT reset s_localAdminAuthorized on disconnect.
// It represents device-level passphrase auth and must persist across connections
// until an explicit Lock Now (revokeAllAuth()). Resetting it here would revoke
// any passphrase-authenticated session the moment a second client connects.
#endif
}
}
@@ -155,6 +175,21 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength)
if (pb_decode_from_bytes(buf, bufLength, &meshtastic_ToRadio_msg, &toRadioScratch)) {
switch (toRadioScratch.which_payload_variant) {
case meshtastic_ToRadio_packet_tag:
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
// Allow admin messages addressed to this device — passphrase delivery must get through.
// AdminModule handles its own is_managed gate for those.
// Block everything else — unauthorized clients cannot inject mesh traffic.
// Require the packet to carry a decoded (not encrypted) payload so portnum is valid.
bool isLocalAdmin = toRadioScratch.packet.which_payload_variant == meshtastic_MeshPacket_decoded_tag &&
toRadioScratch.packet.decoded.portnum == meshtastic_PortNum_ADMIN_APP &&
toRadioScratch.packet.to == nodeDB->getNodeNum();
if (!isLocalAdmin) {
LOG_INFO("TAK: Dropping non-admin ToRadio packet from unauthorized client");
return false;
}
}
#endif
return handleToRadioPacket(toRadioScratch.packet);
case meshtastic_ToRadio_want_config_id_tag:
config_nonce = toRadioScratch.want_config_id;
@@ -166,6 +201,12 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength)
close();
break;
case meshtastic_ToRadio_xmodemPacket_tag:
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
LOG_INFO("TAK: Dropping xmodem packet from unauthorized client");
break;
}
#endif
LOG_INFO("Got xmodem packet");
#ifdef FSCom
xModem.handlePacket(toRadioScratch.xmodemPacket);
@@ -286,8 +327,15 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
}
if (config_nonce == SPECIAL_NONCE_ONLY_NODES) {
// If client only wants node info, jump directly to sending nodes
state = STATE_SEND_OTHER_NODEINFOS;
onNowHasData(0);
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
state = STATE_SEND_COMPLETE_ID; // Unauthorized: skip node DB
} else
#endif
{
state = STATE_SEND_OTHER_NODEINFOS;
onNowHasData(0);
}
} else {
state = STATE_SEND_METADATA;
}
@@ -303,7 +351,17 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
case STATE_SEND_CHANNELS:
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_channel_tag;
fromRadioScratch.channel = channels.getByIndex(config_state);
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
// Send channel structure but zero out PSK to prevent key extraction
fromRadioScratch.channel = channels.getByIndex(config_state);
memset(fromRadioScratch.channel.settings.psk.bytes, 0, sizeof(fromRadioScratch.channel.settings.psk.bytes));
fromRadioScratch.channel.settings.psk.size = 0;
} else
#endif
{
fromRadioScratch.channel = channels.getByIndex(config_state);
}
config_state++;
// Advance when we have sent all of our Channels
if (config_state >= MAX_NUM_CHANNELS) {
@@ -336,6 +394,13 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
LOG_DEBUG("Send config: network");
fromRadioScratch.config.which_payload_variant = meshtastic_Config_network_tag;
fromRadioScratch.config.payload_variant.network = config.network;
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
// Redact wifi PSK
memset(fromRadioScratch.config.payload_variant.network.wifi_psk, 0,
sizeof(fromRadioScratch.config.payload_variant.network.wifi_psk));
}
#endif
break;
case meshtastic_Config_display_tag:
LOG_DEBUG("Send config: display");
@@ -356,6 +421,30 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
LOG_DEBUG("Send config: security");
fromRadioScratch.config.which_payload_variant = meshtastic_Config_security_tag;
fromRadioScratch.config.payload_variant.security = config.security;
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
// Redact private key
memset(fromRadioScratch.config.payload_variant.security.private_key.bytes, 0,
sizeof(fromRadioScratch.config.payload_variant.security.private_key.bytes));
fromRadioScratch.config.payload_variant.security.private_key.size = 0;
// Redact admin keys
for (int i = 0; i < 3; i++) {
memset(fromRadioScratch.config.payload_variant.security.admin_key[i].bytes, 0,
sizeof(fromRadioScratch.config.payload_variant.security.admin_key[i].bytes));
fromRadioScratch.config.payload_variant.security.admin_key[i].size = 0;
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// Signal provisioning state via admin_key[0] so the client knows
// whether to show "Set passphrase" vs "Enter passphrase":
// admin_key[0].size == 0 → not provisioned (first time setup)
// admin_key[0].size == 1, bytes[0] == 0x01 → provisioned, locked
if (EncryptedStorage::isProvisioned()) {
fromRadioScratch.config.payload_variant.security.admin_key[0].bytes[0] = 0x01;
fromRadioScratch.config.payload_variant.security.admin_key[0].size = 1;
}
#endif
}
#endif
break;
case meshtastic_Config_sessionkey_tag:
LOG_DEBUG("Send config: sessionkey");
@@ -454,6 +543,12 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
config_state++;
// Advance when we have sent all of our ModuleConfig objects
if (config_state > (_meshtastic_AdminMessage_ModuleConfigType_MAX + 1)) {
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
// Unauthorized client: skip node DB and file manifest — only send config complete
state = STATE_SEND_COMPLETE_ID;
} else
#endif
// Handle special nonce behaviors:
// - SPECIAL_NONCE_ONLY_CONFIG: Skip node info, go directly to file manifest
// - SPECIAL_NONCE_ONLY_NODES: After sending nodes, skip to complete
@@ -544,24 +639,46 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf)
fromRadioScratch.queueStatus = *queueStatusPacketForPhone;
releaseQueueStatusPhonePacket();
} else if (mqttClientProxyMessageForPhone) {
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_mqttClientProxyMessage_tag;
fromRadioScratch.mqttClientProxyMessage = *mqttClientProxyMessageForPhone;
releaseMqttClientProxyPhonePacket();
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
releaseMqttClientProxyPhonePacket(); // Discard — unauthorized client
} else
#endif
{
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_mqttClientProxyMessage_tag;
fromRadioScratch.mqttClientProxyMessage = *mqttClientProxyMessageForPhone;
releaseMqttClientProxyPhonePacket();
}
} else if (xmodemPacketForPhone.control != meshtastic_XModem_Control_NUL) {
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_xmodemPacket_tag;
fromRadioScratch.xmodemPacket = xmodemPacketForPhone;
xmodemPacketForPhone = meshtastic_XModem_init_zero;
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
xmodemPacketForPhone = meshtastic_XModem_init_zero; // Discard — unauthorized client
} else
#endif
{
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_xmodemPacket_tag;
fromRadioScratch.xmodemPacket = xmodemPacketForPhone;
xmodemPacketForPhone = meshtastic_XModem_init_zero;
}
} else if (clientNotification) {
// Always deliver clientNotification — required for TAK_UNLOCKED/TAK_LOCKED to reach client
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_clientNotification_tag;
fromRadioScratch.clientNotification = *clientNotification;
releaseClientNotification();
} else if (packetForPhone) {
printPacket("phone downloaded packet", packetForPhone);
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isAdminAuthorized && !s_localAdminAuthorized) {
releasePhonePacket(); // Discard mesh traffic — unauthorized client
} else
#endif
{
printPacket("phone downloaded packet", packetForPhone);
// Encapsulate as a FromRadio packet
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_packet_tag;
fromRadioScratch.packet = *packetForPhone;
releasePhonePacket();
// Encapsulate as a FromRadio packet
fromRadioScratch.which_payload_variant = meshtastic_FromRadio_packet_tag;
fromRadioScratch.packet = *packetForPhone;
releasePhonePacket();
}
}
break;
@@ -604,6 +721,28 @@ void PhoneAPI::sendConfigComplete()
service->api_state = service->STATE_ETH;
}
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// Immediately after config_complete_id, notify the client if it hasn't authenticated.
// Gate on client auth state (not storage lock state) — storage may be auto-unlocked via
// boot token, but each new BLE/USB connection must still present the passphrase.
if (!isAdminAuthorized && !s_localAdminAuthorized) {
char msg[48];
if (!EncryptedStorage::isProvisioned()) {
strncpy(msg, "TAK_NEEDS_PROVISION", sizeof(msg));
} else {
// Provisioned: client must authenticate. Use lock reason if storage is hard-locked,
// otherwise signal that passphrase auth is required for this connection.
if (!EncryptedStorage::isUnlocked()) {
snprintf(msg, sizeof(msg), "TAK_LOCKED:%s", EncryptedStorage::getLockReason());
} else {
strncpy(msg, "TAK_LOCKED:needs_auth", sizeof(msg));
}
}
sendNotification(meshtastic_LogRecord_Level_WARNING, 0, msg);
LOG_INFO("PhoneAPI: sent %s to client", msg);
}
#endif
// Allow subclasses to know we've entered steady-state so they can lower power consumption
onConfigComplete();
@@ -842,3 +981,25 @@ int PhoneAPI::onNotify(uint32_t newValue)
return timeout ? -1 : 0; // If we timed out, MeshService should stop iterating through observers as we just removed one
}
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
// HIGH-3: static atomic so BLE-task writes and main-loop reads are race-free.
std::atomic<bool> PhoneAPI::s_localAdminAuthorized{false};
void PhoneAPI::authorizeLocalAdmin()
{
s_localAdminAuthorized.store(true);
LOG_INFO("TAK: Local admin authorized via PKC");
}
bool PhoneAPI::isLocalAdminAuthorized()
{
return s_localAdminAuthorized.load();
}
void PhoneAPI::revokeAllAuth()
{
s_localAdminAuthorized.store(false);
LOG_INFO("TAK: All connection auth revoked (Lock Now)");
}
#endif
+21
View File
@@ -4,6 +4,7 @@
#include "concurrency/Lock.h"
#include "mesh-pb-constants.h"
#include "meshtastic/portnums.pb.h"
#include <atomic>
#include <deque>
#include <iterator>
#include <string>
@@ -138,6 +139,19 @@ class PhoneAPI
bool isConnected() { return state != STATE_SEND_NOTHING; }
bool isSendingPackets() { return state == STATE_SEND_PACKETS; }
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
/// Set by AdminModule after successful PKC admin key validation.
/// When true, config dumps include full unredacted secrets.
void setAdminAuthorized(bool authorized) { isAdminAuthorized = authorized; }
bool getAdminAuthorized() const { return isAdminAuthorized; }
/// Static: authorize all local PhoneAPI instances (called by AdminModule)
static void authorizeLocalAdmin();
static bool isLocalAdminAuthorized();
/// Static: immediately revoke all connection-level auth (called on Lock Now)
static void revokeAllAuth();
#endif
protected:
/// Our fromradio packet while it is being assembled
meshtastic_FromRadio fromRadioScratch = {};
@@ -179,6 +193,13 @@ class PhoneAPI
APIType api_type = TYPE_NONE;
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
// HIGH-3: both flags are accessed from multiple tasks (main loop + NimBLE BLE callback
// task), so they must be atomic to prevent data races on read-modify-write sequences.
std::atomic<bool> isAdminAuthorized{false};
static std::atomic<bool> s_localAdminAuthorized;
#endif
private:
void releasePhonePacket();
+5
View File
@@ -529,6 +529,11 @@ void RadioLibInterface::pollMissedIrqs()
}
}
void RadioLibInterface::resetAGC()
{
// Base implementation: no-op. Override in chip-specific subclasses.
}
void RadioLibInterface::checkRxDoneIrqFlag()
{
if (iface->checkIrq(RADIOLIB_IRQ_RX_DONE)) {
+9
View File
@@ -19,6 +19,8 @@
// In addition to the default Rx flags, we need the PREAMBLE_DETECTED flag to detect whether we are actively receiving
#define MESHTASTIC_RADIOLIB_IRQ_RX_FLAGS (RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1 << RADIOLIB_IRQ_PREAMBLE_DETECTED))
#define AGC_RESET_INTERVAL_MS (60 * 1000) // 60 seconds
/**
* We need to override the RadioLib ArduinoHal class to add mutex protection for SPI bus access
*/
@@ -117,6 +119,13 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified
*/
void pollMissedIrqs();
/**
* Reset AGC by power-cycling the analog frontend.
* Subclasses override with chip-specific calibration sequences.
* Safe to call periodically — skips if currently sending or receiving.
*/
virtual void resetAGC();
/**
* Debugging counts
*/
+57 -5
View File
@@ -194,16 +194,13 @@ template <typename T> bool SX126xInterface<T>::init()
LOG_INFO("Set RX gain to power saving mode (boosted mode off); result: %d", result);
}
#ifdef USE_GC1109_PA
// Undocumented SX1262 register patch recommended by Heltec/Semtech for improved RX sensitivity
// on boards with the GC1109 FEM. Sets bit 0 of register 0x8B5.
// Reference: https://github.com/meshcore-dev/MeshCore/pull/1398
// Undocumented SX1262 register patch recommended by Heltec/Semtech for improved RX sensitivity.
// Sets bit 0 of register 0x8B5.
if (module.SPIsetRegValue(0x8B5, 0x01, 0, 0) == RADIOLIB_ERR_NONE) {
LOG_INFO("Applied SX1262 register 0x8B5 patch for GC1109 RX improvement");
} else {
LOG_WARN("Failed to apply SX1262 register 0x8B5 patch for GC1109");
}
#endif
#if 0
// Read/write a register we are not using (only used for FSK mode) to test SPI comms
@@ -434,6 +431,61 @@ template <typename T> bool SX126xInterface<T>::sleep()
return true;
}
template <typename T> void SX126xInterface<T>::resetAGC()
{
// Safety: don't reset mid-packet
if (sendingPacket != NULL || (isReceiving && isActivelyReceiving()))
return;
LOG_DEBUG("SX126x AGC reset: warm sleep + Calibrate(0x7F)");
// 1. Warm sleep — powers down the entire analog frontend, resetting AGC state.
// A plain standby→startReceive cycle does NOT reset the AGC.
lora.sleep(true);
// 2. Wake to RC standby for stable calibration
lora.standby(RADIOLIB_SX126X_STANDBY_RC, true);
// 3. Calibrate all blocks (ADC, PLL, image, RC oscillators)
uint8_t calData = RADIOLIB_SX126X_CALIBRATE_ALL;
module.SPIwriteStream(RADIOLIB_SX126X_CMD_CALIBRATE, &calData, 1, true, false);
// 4. Wait for calibration to complete (BUSY pin goes low)
module.hal->delay(5);
uint32_t start = millis();
while (module.hal->digitalRead(module.getGpio())) {
if (millis() - start > 50)
break;
module.hal->yield();
}
if (module.hal->digitalRead(module.getGpio())) {
LOG_WARN("SX126x AGC reset: calibration did not complete within 50ms");
startReceive();
return;
}
// 5. Re-calibrate image rejection for actual operating frequency
// Calibrate(0x7F) defaults to 902-928 MHz which is wrong for other regions.
lora.calibrateImage(getFreq());
// Re-apply settings that calibration may have reset
// DIO2 as RF switch
#ifdef SX126X_DIO2_AS_RF_SWITCH
lora.setDio2AsRfSwitch(true);
#elif defined(ARCH_PORTDUINO)
if (portduino_config.dio2_as_rf_switch)
lora.setDio2AsRfSwitch(true);
#endif
// RX boosted gain mode
lora.setRxBoostedGainMode(config.lora.sx126x_rx_boosted_gain);
// 6. Resume receiving
startReceive();
}
/** Control PA mode for GC1109 FEM - CPS pin selects full PA (txon=true) or bypass mode (txon=false) */
template <typename T> void SX126xInterface<T>::setTransmitEnable(bool txon)
{
+2
View File
@@ -28,6 +28,8 @@ template <class T> class SX126xInterface : public RadioLibInterface
bool isIRQPending() override { return lora.getIrqFlags() != 0; }
void resetAGC() override;
void setTCXOVoltage(float voltage) { tcxoVoltage = voltage; }
protected:
+202
View File
@@ -0,0 +1,202 @@
#include "TransmitHistory.h"
#include "FSCommon.h"
#include "RTC.h"
#include "SPILock.h"
#include <Throttle.h>
#ifdef FSCom
TransmitHistory *transmitHistory = nullptr;
TransmitHistory *TransmitHistory::getInstance()
{
if (!transmitHistory) {
transmitHistory = new TransmitHistory();
}
return transmitHistory;
}
void TransmitHistory::loadFromDisk()
{
spiLock->lock();
auto file = FSCom.open(FILENAME, FILE_O_READ);
if (file) {
FileHeader header{};
if (file.read((uint8_t *)&header, sizeof(header)) == sizeof(header) && header.magic == MAGIC &&
header.version == VERSION && header.count <= MAX_ENTRIES) {
for (uint8_t i = 0; i < header.count; i++) {
Entry entry{};
if (file.read((uint8_t *)&entry, sizeof(entry)) == sizeof(entry)) {
if (entry.epochSeconds > 0) {
history[entry.key] = entry.epochSeconds;
// Seed in-memory millis so throttle works even without RTC/GPS.
// Treating stored entries as "just sent" is safe — worst case the
// node waits one full interval before its first broadcast.
lastMillis[entry.key] = millis();
}
}
}
LOG_INFO("TransmitHistory: loaded %u entries from disk", header.count);
} else {
LOG_WARN("TransmitHistory: invalid file header, starting fresh");
}
file.close();
} else {
LOG_INFO("TransmitHistory: no history file found, starting fresh");
}
spiLock->unlock();
dirty = false;
}
void TransmitHistory::setLastSentToMesh(uint16_t key)
{
lastMillis[key] = millis();
uint32_t now = getTime();
if (now >= 2) {
history[key] = now;
dirty = true;
// Don't flush to disk on every transmit — flash has limited write endurance.
// The in-memory lastMillis map handles throttle during normal operation.
// Disk is flushed: before deep sleep (sleep.cpp) and periodically here,
// throttled to at most once per 5 minutes. Always save the first time
// after boot so a crash-reboot loop can't avoid persisting.
if (lastDiskSave == 0 || !Throttle::isWithinTimespanMs(lastDiskSave, SAVE_INTERVAL_MS)) {
if (saveToDisk()) {
lastDiskSave = millis();
}
}
}
}
uint32_t TransmitHistory::getLastSentToMeshEpoch(uint16_t key) const
{
auto it = history.find(key);
if (it != history.end()) {
return it->second;
}
return 0;
}
uint32_t TransmitHistory::getLastSentToMeshMillis(uint16_t key) const
{
// Prefer runtime millis value (accurate within this boot)
auto mit = lastMillis.find(key);
if (mit != lastMillis.end()) {
return mit->second;
}
// Fall back to epoch conversion (loaded from disk after reboot)
uint32_t storedEpoch = getLastSentToMeshEpoch(key);
if (storedEpoch == 0) {
return 0; // No stored time — module has never sent
}
uint32_t now = getTime();
if (now < 2) {
// No valid RTC time yet — can't convert to millis. Return 0 so throttle doesn't block.
return 0;
}
if (storedEpoch > now) {
// Stored time is in the future (clock went backwards?) — treat as stale
return 0;
}
uint32_t secondsAgo = now - storedEpoch;
uint32_t msAgo = secondsAgo * 1000;
// Guard against overflow: if the transmit was very long ago, just return 0 (won't throttle)
if (secondsAgo > 86400 || msAgo / 1000 != secondsAgo) {
return 0;
}
// Convert to a millis()-relative timestamp: millis() - msAgo
// This gives a value that, when passed to Throttle::isWithinTimespanMs(value, interval),
// correctly reports whether the transmit was within interval ms.
return millis() - msAgo;
}
bool TransmitHistory::saveToDisk()
{
if (!dirty) {
return true;
}
spiLock->lock();
FSCom.mkdir("/prefs");
// Remove old file first
if (FSCom.exists(FILENAME)) {
FSCom.remove(FILENAME);
}
auto file = FSCom.open(FILENAME, FILE_O_WRITE);
if (file) {
FileHeader header{};
header.magic = MAGIC;
header.version = VERSION;
header.count = (uint8_t)min((size_t)MAX_ENTRIES, history.size());
file.write((uint8_t *)&header, sizeof(header));
uint8_t written = 0;
for (auto &pair : history) {
if (written >= MAX_ENTRIES)
break;
Entry entry{};
entry.key = pair.first;
entry.epochSeconds = pair.second;
file.write((uint8_t *)&entry, sizeof(entry));
written++;
}
file.flush();
file.close();
LOG_DEBUG("TransmitHistory: saved %u entries to disk", written);
dirty = false;
spiLock->unlock();
return true;
} else {
LOG_WARN("TransmitHistory: failed to open file for writing");
}
spiLock->unlock();
return false;
}
#else
// No filesystem available — provide stub with in-memory tracking
TransmitHistory *transmitHistory = nullptr;
TransmitHistory *TransmitHistory::getInstance()
{
if (!transmitHistory) {
transmitHistory = new TransmitHistory();
}
return transmitHistory;
}
void TransmitHistory::loadFromDisk() {}
void TransmitHistory::setLastSentToMesh(uint16_t key)
{
lastMillis[key] = millis();
}
uint32_t TransmitHistory::getLastSentToMeshEpoch(uint16_t key) const
{
return 0;
}
uint32_t TransmitHistory::getLastSentToMeshMillis(uint16_t key) const
{
auto mit = lastMillis.find(key);
return (mit != lastMillis.end()) ? mit->second : 0;
}
bool TransmitHistory::saveToDisk()
{
return true;
}
#endif
+88
View File
@@ -0,0 +1,88 @@
#pragma once
#include "configuration.h"
#include <Arduino.h>
#include <map>
/**
* TransmitHistory persists the last broadcast transmit time (epoch seconds) per portnum
* to the filesystem so that throttle checks survive reboots/crashes.
*
* On boot, modules call getLastSentToMeshMillis() to recover a millis()-relative timestamp
* from the stored epoch time, which plugs directly into existing throttle logic.
*
* On every broadcast transmit, modules call setLastSentToMesh() which updates the
* in-memory cache and flushes to disk.
*
* Keys are meshtastic_PortNum values (one entry per portnum).
*/
#include "mesh/generated/meshtastic/portnums.pb.h"
class TransmitHistory
{
public:
static TransmitHistory *getInstance();
/**
* Load persisted transmit times from disk. Call once during init after filesystem is ready.
*/
void loadFromDisk();
/**
* Record that a broadcast was sent for the given key right now.
* Stores epoch seconds and flushes to disk.
*/
void setLastSentToMesh(uint16_t key);
/**
* Get the last transmit epoch seconds for a given key, or 0 if unknown.
*/
uint32_t getLastSentToMeshEpoch(uint16_t key) const;
/**
* Convert a stored epoch timestamp into a millis()-relative timestamp suitable
* for use with Throttle::isWithinTimespanMs().
*
* Returns 0 if no valid time is stored or if the stored time is in the future
* (which shouldn't happen but guards against clock weirdness).
*
* Example: if the stored epoch is 300 seconds ago, and millis() is currently 10000,
* this returns 10000 - 300000 (wrapped appropriately for uint32_t arithmetic).
*/
uint32_t getLastSentToMeshMillis(uint16_t key) const;
/**
* Flush dirty entries to disk. Called periodically or on demand.
*
* @return true if the data is persisted (or there was nothing to write), false on write/open failure.
*/
bool saveToDisk();
private:
TransmitHistory() = default;
static constexpr const char *FILENAME = "/prefs/transmit_history.dat";
static constexpr uint32_t MAGIC = 0x54485354; // "THST"
static constexpr uint8_t VERSION = 1;
static constexpr uint8_t MAX_ENTRIES = 16;
static constexpr uint32_t SAVE_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
struct __attribute__((packed)) Entry {
uint16_t key;
uint32_t epochSeconds;
};
struct __attribute__((packed)) FileHeader {
uint32_t magic;
uint8_t version;
uint8_t count;
};
std::map<uint16_t, uint32_t> history; // key -> epoch seconds (for disk persistence)
std::map<uint16_t, uint32_t> lastMillis; // key -> millis() value (for runtime throttle)
bool dirty = false;
uint32_t lastDiskSave = 0; // millis() of last disk flush
};
extern TransmitHistory *transmitHistory;
+5 -3
View File
@@ -81,7 +81,9 @@ typedef enum _meshtastic_AdminMessage_ModuleConfigType {
/* TODO: REPLACE */
meshtastic_AdminMessage_ModuleConfigType_STATUSMESSAGE_CONFIG = 13,
/* Traffic management module config */
meshtastic_AdminMessage_ModuleConfigType_TRAFFICMANAGEMENT_CONFIG = 14
meshtastic_AdminMessage_ModuleConfigType_TRAFFICMANAGEMENT_CONFIG = 14,
/* TAK module config */
meshtastic_AdminMessage_ModuleConfigType_TAK_CONFIG = 15
} meshtastic_AdminMessage_ModuleConfigType;
typedef enum _meshtastic_AdminMessage_BackupLocation {
@@ -395,8 +397,8 @@ extern "C" {
#define _meshtastic_AdminMessage_ConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ConfigType)(meshtastic_AdminMessage_ConfigType_DEVICEUI_CONFIG+1))
#define _meshtastic_AdminMessage_ModuleConfigType_MIN meshtastic_AdminMessage_ModuleConfigType_MQTT_CONFIG
#define _meshtastic_AdminMessage_ModuleConfigType_MAX meshtastic_AdminMessage_ModuleConfigType_TRAFFICMANAGEMENT_CONFIG
#define _meshtastic_AdminMessage_ModuleConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ModuleConfigType)(meshtastic_AdminMessage_ModuleConfigType_TRAFFICMANAGEMENT_CONFIG+1))
#define _meshtastic_AdminMessage_ModuleConfigType_MAX meshtastic_AdminMessage_ModuleConfigType_TAK_CONFIG
#define _meshtastic_AdminMessage_ModuleConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ModuleConfigType)(meshtastic_AdminMessage_ModuleConfigType_TAK_CONFIG+1))
#define _meshtastic_AdminMessage_BackupLocation_MIN meshtastic_AdminMessage_BackupLocation_FLASH
#define _meshtastic_AdminMessage_BackupLocation_MAX meshtastic_AdminMessage_BackupLocation_SD
@@ -361,7 +361,7 @@ extern const pb_msgdesc_t meshtastic_BackupPreferences_msg;
/* Maximum encoded size of messages (where known) */
/* meshtastic_NodeDatabase_size depends on runtime parameters */
#define MESHTASTIC_MESHTASTIC_DEVICEONLY_PB_H_MAX_SIZE meshtastic_BackupPreferences_size
#define meshtastic_BackupPreferences_size 2419
#define meshtastic_BackupPreferences_size 2426
#define meshtastic_ChannelFile_size 718
#define meshtastic_DeviceState_size 1737
#define meshtastic_NodeInfoLite_size 196
+10 -4
View File
@@ -93,6 +93,9 @@ typedef struct _meshtastic_LocalModuleConfig {
/* The part of the config that is specific to the Traffic Management module */
bool has_traffic_management;
meshtastic_ModuleConfig_TrafficManagementConfig traffic_management;
/* TAK Config */
bool has_tak;
meshtastic_ModuleConfig_TAKConfig tak;
} meshtastic_LocalModuleConfig;
@@ -102,9 +105,9 @@ extern "C" {
/* Initializer values for message structs */
#define meshtastic_LocalConfig_init_default {false, meshtastic_Config_DeviceConfig_init_default, false, meshtastic_Config_PositionConfig_init_default, false, meshtastic_Config_PowerConfig_init_default, false, meshtastic_Config_NetworkConfig_init_default, false, meshtastic_Config_DisplayConfig_init_default, false, meshtastic_Config_LoRaConfig_init_default, false, meshtastic_Config_BluetoothConfig_init_default, 0, false, meshtastic_Config_SecurityConfig_init_default}
#define meshtastic_LocalModuleConfig_init_default {false, meshtastic_ModuleConfig_MQTTConfig_init_default, false, meshtastic_ModuleConfig_SerialConfig_init_default, false, meshtastic_ModuleConfig_ExternalNotificationConfig_init_default, false, meshtastic_ModuleConfig_StoreForwardConfig_init_default, false, meshtastic_ModuleConfig_RangeTestConfig_init_default, false, meshtastic_ModuleConfig_TelemetryConfig_init_default, false, meshtastic_ModuleConfig_CannedMessageConfig_init_default, 0, false, meshtastic_ModuleConfig_AudioConfig_init_default, false, meshtastic_ModuleConfig_RemoteHardwareConfig_init_default, false, meshtastic_ModuleConfig_NeighborInfoConfig_init_default, false, meshtastic_ModuleConfig_AmbientLightingConfig_init_default, false, meshtastic_ModuleConfig_DetectionSensorConfig_init_default, false, meshtastic_ModuleConfig_PaxcounterConfig_init_default, false, meshtastic_ModuleConfig_StatusMessageConfig_init_default, false, meshtastic_ModuleConfig_TrafficManagementConfig_init_default}
#define meshtastic_LocalModuleConfig_init_default {false, meshtastic_ModuleConfig_MQTTConfig_init_default, false, meshtastic_ModuleConfig_SerialConfig_init_default, false, meshtastic_ModuleConfig_ExternalNotificationConfig_init_default, false, meshtastic_ModuleConfig_StoreForwardConfig_init_default, false, meshtastic_ModuleConfig_RangeTestConfig_init_default, false, meshtastic_ModuleConfig_TelemetryConfig_init_default, false, meshtastic_ModuleConfig_CannedMessageConfig_init_default, 0, false, meshtastic_ModuleConfig_AudioConfig_init_default, false, meshtastic_ModuleConfig_RemoteHardwareConfig_init_default, false, meshtastic_ModuleConfig_NeighborInfoConfig_init_default, false, meshtastic_ModuleConfig_AmbientLightingConfig_init_default, false, meshtastic_ModuleConfig_DetectionSensorConfig_init_default, false, meshtastic_ModuleConfig_PaxcounterConfig_init_default, false, meshtastic_ModuleConfig_StatusMessageConfig_init_default, false, meshtastic_ModuleConfig_TrafficManagementConfig_init_default, false, meshtastic_ModuleConfig_TAKConfig_init_default}
#define meshtastic_LocalConfig_init_zero {false, meshtastic_Config_DeviceConfig_init_zero, false, meshtastic_Config_PositionConfig_init_zero, false, meshtastic_Config_PowerConfig_init_zero, false, meshtastic_Config_NetworkConfig_init_zero, false, meshtastic_Config_DisplayConfig_init_zero, false, meshtastic_Config_LoRaConfig_init_zero, false, meshtastic_Config_BluetoothConfig_init_zero, 0, false, meshtastic_Config_SecurityConfig_init_zero}
#define meshtastic_LocalModuleConfig_init_zero {false, meshtastic_ModuleConfig_MQTTConfig_init_zero, false, meshtastic_ModuleConfig_SerialConfig_init_zero, false, meshtastic_ModuleConfig_ExternalNotificationConfig_init_zero, false, meshtastic_ModuleConfig_StoreForwardConfig_init_zero, false, meshtastic_ModuleConfig_RangeTestConfig_init_zero, false, meshtastic_ModuleConfig_TelemetryConfig_init_zero, false, meshtastic_ModuleConfig_CannedMessageConfig_init_zero, 0, false, meshtastic_ModuleConfig_AudioConfig_init_zero, false, meshtastic_ModuleConfig_RemoteHardwareConfig_init_zero, false, meshtastic_ModuleConfig_NeighborInfoConfig_init_zero, false, meshtastic_ModuleConfig_AmbientLightingConfig_init_zero, false, meshtastic_ModuleConfig_DetectionSensorConfig_init_zero, false, meshtastic_ModuleConfig_PaxcounterConfig_init_zero, false, meshtastic_ModuleConfig_StatusMessageConfig_init_zero, false, meshtastic_ModuleConfig_TrafficManagementConfig_init_zero}
#define meshtastic_LocalModuleConfig_init_zero {false, meshtastic_ModuleConfig_MQTTConfig_init_zero, false, meshtastic_ModuleConfig_SerialConfig_init_zero, false, meshtastic_ModuleConfig_ExternalNotificationConfig_init_zero, false, meshtastic_ModuleConfig_StoreForwardConfig_init_zero, false, meshtastic_ModuleConfig_RangeTestConfig_init_zero, false, meshtastic_ModuleConfig_TelemetryConfig_init_zero, false, meshtastic_ModuleConfig_CannedMessageConfig_init_zero, 0, false, meshtastic_ModuleConfig_AudioConfig_init_zero, false, meshtastic_ModuleConfig_RemoteHardwareConfig_init_zero, false, meshtastic_ModuleConfig_NeighborInfoConfig_init_zero, false, meshtastic_ModuleConfig_AmbientLightingConfig_init_zero, false, meshtastic_ModuleConfig_DetectionSensorConfig_init_zero, false, meshtastic_ModuleConfig_PaxcounterConfig_init_zero, false, meshtastic_ModuleConfig_StatusMessageConfig_init_zero, false, meshtastic_ModuleConfig_TrafficManagementConfig_init_zero, false, meshtastic_ModuleConfig_TAKConfig_init_zero}
/* Field tags (for use in manual encoding/decoding) */
#define meshtastic_LocalConfig_device_tag 1
@@ -132,6 +135,7 @@ extern "C" {
#define meshtastic_LocalModuleConfig_paxcounter_tag 14
#define meshtastic_LocalModuleConfig_statusmessage_tag 15
#define meshtastic_LocalModuleConfig_traffic_management_tag 16
#define meshtastic_LocalModuleConfig_tak_tag 17
/* Struct field encoding specification for nanopb */
#define meshtastic_LocalConfig_FIELDLIST(X, a) \
@@ -171,7 +175,8 @@ X(a, STATIC, OPTIONAL, MESSAGE, ambient_lighting, 12) \
X(a, STATIC, OPTIONAL, MESSAGE, detection_sensor, 13) \
X(a, STATIC, OPTIONAL, MESSAGE, paxcounter, 14) \
X(a, STATIC, OPTIONAL, MESSAGE, statusmessage, 15) \
X(a, STATIC, OPTIONAL, MESSAGE, traffic_management, 16)
X(a, STATIC, OPTIONAL, MESSAGE, traffic_management, 16) \
X(a, STATIC, OPTIONAL, MESSAGE, tak, 17)
#define meshtastic_LocalModuleConfig_CALLBACK NULL
#define meshtastic_LocalModuleConfig_DEFAULT NULL
#define meshtastic_LocalModuleConfig_mqtt_MSGTYPE meshtastic_ModuleConfig_MQTTConfig
@@ -189,6 +194,7 @@ X(a, STATIC, OPTIONAL, MESSAGE, traffic_management, 16)
#define meshtastic_LocalModuleConfig_paxcounter_MSGTYPE meshtastic_ModuleConfig_PaxcounterConfig
#define meshtastic_LocalModuleConfig_statusmessage_MSGTYPE meshtastic_ModuleConfig_StatusMessageConfig
#define meshtastic_LocalModuleConfig_traffic_management_MSGTYPE meshtastic_ModuleConfig_TrafficManagementConfig
#define meshtastic_LocalModuleConfig_tak_MSGTYPE meshtastic_ModuleConfig_TAKConfig
extern const pb_msgdesc_t meshtastic_LocalConfig_msg;
extern const pb_msgdesc_t meshtastic_LocalModuleConfig_msg;
@@ -200,7 +206,7 @@ extern const pb_msgdesc_t meshtastic_LocalModuleConfig_msg;
/* Maximum encoded size of messages (where known) */
#define MESHTASTIC_MESHTASTIC_LOCALONLY_PB_H_MAX_SIZE meshtastic_LocalModuleConfig_size
#define meshtastic_LocalConfig_size 751
#define meshtastic_LocalModuleConfig_size 813
#define meshtastic_LocalModuleConfig_size 820
#ifdef __cplusplus
} /* extern "C" */
+4
View File
@@ -300,6 +300,10 @@ typedef enum _meshtastic_HardwareModel {
meshtastic_HardwareModel_TBEAM_1_WATT = 122,
/* LilyGo T5 S3 ePaper Pro (V1 and V2) */
meshtastic_HardwareModel_T5_S3_EPAPER_PRO = 123,
/* LilyGo T-Beam BPF (144-148Mhz) */
meshtastic_HardwareModel_TBEAM_BPF = 124,
/* LilyGo T-Mini E-paper S3 Kit */
meshtastic_HardwareModel_MINI_EPAPER_S3 = 125,
/* ------------------------------------------------------------------------------------------------------------------------------------------
Reserved ID For developing private Ports. These will show up in live traffic sparsely, so we can use a high number. Keep it within 8 bits.
------------------------------------------------------------------------------------------------------------------------------------------ */
@@ -57,6 +57,9 @@ PB_BIND(meshtastic_ModuleConfig_AmbientLightingConfig, meshtastic_ModuleConfig_A
PB_BIND(meshtastic_ModuleConfig_StatusMessageConfig, meshtastic_ModuleConfig_StatusMessageConfig, AUTO)
PB_BIND(meshtastic_ModuleConfig_TAKConfig, meshtastic_ModuleConfig_TAKConfig, AUTO)
PB_BIND(meshtastic_RemoteHardwarePin, meshtastic_RemoteHardwarePin, AUTO)
@@ -4,6 +4,7 @@
#ifndef PB_MESHTASTIC_MESHTASTIC_MODULE_CONFIG_PB_H_INCLUDED
#define PB_MESHTASTIC_MESHTASTIC_MODULE_CONFIG_PB_H_INCLUDED
#include <pb.h>
#include "meshtastic/atak.pb.h"
#if PB_PROTO_HEADER_VERSION != 40
#error Regenerate this file with the current version of nanopb generator.
@@ -448,6 +449,16 @@ typedef struct _meshtastic_ModuleConfig_StatusMessageConfig {
char node_status[80];
} meshtastic_ModuleConfig_StatusMessageConfig;
/* TAK team/role configuration */
typedef struct _meshtastic_ModuleConfig_TAKConfig {
/* Team color.
Default Unspecifed_Color -> firmware uses Cyan */
meshtastic_Team team;
/* Member role.
Default Unspecifed -> firmware uses TeamMember */
meshtastic_MemberRole role;
} meshtastic_ModuleConfig_TAKConfig;
/* A GPIO pin definition for remote hardware module */
typedef struct _meshtastic_RemoteHardwarePin {
/* GPIO Pin number (must match Arduino) */
@@ -503,6 +514,8 @@ typedef struct _meshtastic_ModuleConfig {
meshtastic_ModuleConfig_StatusMessageConfig statusmessage;
/* Traffic management module config for mesh network optimization */
meshtastic_ModuleConfig_TrafficManagementConfig traffic_management;
/* TAK team/role configuration for TAK_TRACKER */
meshtastic_ModuleConfig_TAKConfig tak;
} payload_variant;
} meshtastic_ModuleConfig;
@@ -560,6 +573,9 @@ extern "C" {
#define meshtastic_ModuleConfig_TAKConfig_team_ENUMTYPE meshtastic_Team
#define meshtastic_ModuleConfig_TAKConfig_role_ENUMTYPE meshtastic_MemberRole
#define meshtastic_RemoteHardwarePin_type_ENUMTYPE meshtastic_RemoteHardwarePinType
@@ -581,6 +597,7 @@ extern "C" {
#define meshtastic_ModuleConfig_CannedMessageConfig_init_default {0, 0, 0, 0, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0}
#define meshtastic_ModuleConfig_AmbientLightingConfig_init_default {0, 0, 0, 0, 0}
#define meshtastic_ModuleConfig_StatusMessageConfig_init_default {""}
#define meshtastic_ModuleConfig_TAKConfig_init_default {_meshtastic_Team_MIN, _meshtastic_MemberRole_MIN}
#define meshtastic_RemoteHardwarePin_init_default {0, "", _meshtastic_RemoteHardwarePinType_MIN}
#define meshtastic_ModuleConfig_init_zero {0, {meshtastic_ModuleConfig_MQTTConfig_init_zero}}
#define meshtastic_ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0, 0, "", 0, 0, false, meshtastic_ModuleConfig_MapReportSettings_init_zero}
@@ -599,6 +616,7 @@ extern "C" {
#define meshtastic_ModuleConfig_CannedMessageConfig_init_zero {0, 0, 0, 0, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0}
#define meshtastic_ModuleConfig_AmbientLightingConfig_init_zero {0, 0, 0, 0, 0}
#define meshtastic_ModuleConfig_StatusMessageConfig_init_zero {""}
#define meshtastic_ModuleConfig_TAKConfig_init_zero {_meshtastic_Team_MIN, _meshtastic_MemberRole_MIN}
#define meshtastic_RemoteHardwarePin_init_zero {0, "", _meshtastic_RemoteHardwarePinType_MIN}
/* Field tags (for use in manual encoding/decoding) */
@@ -717,6 +735,8 @@ extern "C" {
#define meshtastic_ModuleConfig_AmbientLightingConfig_green_tag 4
#define meshtastic_ModuleConfig_AmbientLightingConfig_blue_tag 5
#define meshtastic_ModuleConfig_StatusMessageConfig_node_status_tag 1
#define meshtastic_ModuleConfig_TAKConfig_team_tag 1
#define meshtastic_ModuleConfig_TAKConfig_role_tag 2
#define meshtastic_RemoteHardwarePin_gpio_pin_tag 1
#define meshtastic_RemoteHardwarePin_name_tag 2
#define meshtastic_RemoteHardwarePin_type_tag 3
@@ -738,6 +758,7 @@ extern "C" {
#define meshtastic_ModuleConfig_paxcounter_tag 13
#define meshtastic_ModuleConfig_statusmessage_tag 14
#define meshtastic_ModuleConfig_traffic_management_tag 15
#define meshtastic_ModuleConfig_tak_tag 16
/* Struct field encoding specification for nanopb */
#define meshtastic_ModuleConfig_FIELDLIST(X, a) \
@@ -755,7 +776,8 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,ambient_lighting,payload_var
X(a, STATIC, ONEOF, MESSAGE, (payload_variant,detection_sensor,payload_variant.detection_sensor), 12) \
X(a, STATIC, ONEOF, MESSAGE, (payload_variant,paxcounter,payload_variant.paxcounter), 13) \
X(a, STATIC, ONEOF, MESSAGE, (payload_variant,statusmessage,payload_variant.statusmessage), 14) \
X(a, STATIC, ONEOF, MESSAGE, (payload_variant,traffic_management,payload_variant.traffic_management), 15)
X(a, STATIC, ONEOF, MESSAGE, (payload_variant,traffic_management,payload_variant.traffic_management), 15) \
X(a, STATIC, ONEOF, MESSAGE, (payload_variant,tak,payload_variant.tak), 16)
#define meshtastic_ModuleConfig_CALLBACK NULL
#define meshtastic_ModuleConfig_DEFAULT NULL
#define meshtastic_ModuleConfig_payload_variant_mqtt_MSGTYPE meshtastic_ModuleConfig_MQTTConfig
@@ -773,6 +795,7 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,traffic_management,payload_v
#define meshtastic_ModuleConfig_payload_variant_paxcounter_MSGTYPE meshtastic_ModuleConfig_PaxcounterConfig
#define meshtastic_ModuleConfig_payload_variant_statusmessage_MSGTYPE meshtastic_ModuleConfig_StatusMessageConfig
#define meshtastic_ModuleConfig_payload_variant_traffic_management_MSGTYPE meshtastic_ModuleConfig_TrafficManagementConfig
#define meshtastic_ModuleConfig_payload_variant_tak_MSGTYPE meshtastic_ModuleConfig_TAKConfig
#define meshtastic_ModuleConfig_MQTTConfig_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, BOOL, enabled, 1) \
@@ -958,6 +981,12 @@ X(a, STATIC, SINGULAR, STRING, node_status, 1)
#define meshtastic_ModuleConfig_StatusMessageConfig_CALLBACK NULL
#define meshtastic_ModuleConfig_StatusMessageConfig_DEFAULT NULL
#define meshtastic_ModuleConfig_TAKConfig_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, UENUM, team, 1) \
X(a, STATIC, SINGULAR, UENUM, role, 2)
#define meshtastic_ModuleConfig_TAKConfig_CALLBACK NULL
#define meshtastic_ModuleConfig_TAKConfig_DEFAULT NULL
#define meshtastic_RemoteHardwarePin_FIELDLIST(X, a) \
X(a, STATIC, SINGULAR, UINT32, gpio_pin, 1) \
X(a, STATIC, SINGULAR, STRING, name, 2) \
@@ -982,6 +1011,7 @@ extern const pb_msgdesc_t meshtastic_ModuleConfig_TelemetryConfig_msg;
extern const pb_msgdesc_t meshtastic_ModuleConfig_CannedMessageConfig_msg;
extern const pb_msgdesc_t meshtastic_ModuleConfig_AmbientLightingConfig_msg;
extern const pb_msgdesc_t meshtastic_ModuleConfig_StatusMessageConfig_msg;
extern const pb_msgdesc_t meshtastic_ModuleConfig_TAKConfig_msg;
extern const pb_msgdesc_t meshtastic_RemoteHardwarePin_msg;
/* Defines for backwards compatibility with code written before nanopb-0.4.0 */
@@ -1002,6 +1032,7 @@ extern const pb_msgdesc_t meshtastic_RemoteHardwarePin_msg;
#define meshtastic_ModuleConfig_CannedMessageConfig_fields &meshtastic_ModuleConfig_CannedMessageConfig_msg
#define meshtastic_ModuleConfig_AmbientLightingConfig_fields &meshtastic_ModuleConfig_AmbientLightingConfig_msg
#define meshtastic_ModuleConfig_StatusMessageConfig_fields &meshtastic_ModuleConfig_StatusMessageConfig_msg
#define meshtastic_ModuleConfig_TAKConfig_fields &meshtastic_ModuleConfig_TAKConfig_msg
#define meshtastic_RemoteHardwarePin_fields &meshtastic_RemoteHardwarePin_msg
/* Maximum encoded size of messages (where known) */
@@ -1020,6 +1051,7 @@ extern const pb_msgdesc_t meshtastic_RemoteHardwarePin_msg;
#define meshtastic_ModuleConfig_SerialConfig_size 28
#define meshtastic_ModuleConfig_StatusMessageConfig_size 81
#define meshtastic_ModuleConfig_StoreForwardConfig_size 24
#define meshtastic_ModuleConfig_TAKConfig_size 4
#define meshtastic_ModuleConfig_TelemetryConfig_size 50
#define meshtastic_ModuleConfig_TrafficManagementConfig_size 52
#define meshtastic_ModuleConfig_size 227
+2 -19
View File
@@ -46,10 +46,6 @@ using namespace httpsserver;
#include "mesh/http/ContentHandler.h"
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
HTTPClient httpClient;
#define DEST_FS_USES_LITTLEFS
// We need to specify some content-type mapping, so the resources get delivered with the
@@ -344,11 +340,6 @@ void handleFsBrowseStatic(HTTPRequest *req, HTTPResponse *res)
res->print(jsonString.c_str());
delete value;
// Clean up the fileList to prevent memory leak
for (auto *val : fileList) {
delete val;
}
}
void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res)
@@ -543,6 +534,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res)
if (name != "file") {
LOG_DEBUG("Skip unexpected field");
res->println("<p>No file found.</p>");
delete parser;
return;
}
@@ -550,6 +542,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res)
if (filename == "") {
LOG_DEBUG("Skip unexpected field");
res->println("<p>No file found.</p>");
delete parser;
return;
}
@@ -783,11 +776,6 @@ void handleNodes(HTTPRequest *req, HTTPResponse *res)
std::string jsonString = value->Stringify();
res->print(jsonString.c_str());
delete value;
// Clean up the nodesArray to prevent memory leak
for (auto *val : nodesArray) {
delete val;
}
}
/*
@@ -941,10 +929,5 @@ void handleScanNetworks(HTTPRequest *req, HTTPResponse *res)
std::string jsonString = value->Stringify();
res->print(jsonString.c_str());
delete value;
// Clean up the networkObjs to prevent memory leak
for (auto *val : networkObjs) {
delete val;
}
}
#endif
+22 -3
View File
@@ -9,6 +9,7 @@
#include <HTTPBodyParser.hpp>
#include <HTTPMultipartBodyParser.hpp>
#include <HTTPURLEncodedBodyParser.hpp>
#include <Throttle.h>
#include <WebServer.h>
#include <WiFi.h>
@@ -55,6 +56,12 @@ static const int32_t ACTIVE_INTERVAL_MS = 50;
static const int32_t MEDIUM_INTERVAL_MS = 200;
static const int32_t IDLE_INTERVAL_MS = 1000;
// Maximum concurrent HTTPS connections (reduced from default 4 to save memory)
static const uint8_t MAX_HTTPS_CONNECTIONS = 2;
// Minimum free heap required for SSL handshake (~40KB for mbedTLS contexts)
static const uint32_t MIN_HEAP_FOR_SSL = 40000;
static SSLCert *cert;
static HTTPSServer *secureServer;
static HTTPServer *insecureServer;
@@ -67,8 +74,20 @@ static void handleWebResponse()
if (isWifiAvailable()) {
if (isWebServerReady) {
if (secureServer)
secureServer->loop();
// Check heap before HTTPS processing - SSL requires significant memory
if (secureServer) {
uint32_t freeHeap = ESP.getFreeHeap();
if (freeHeap >= MIN_HEAP_FOR_SSL) {
secureServer->loop();
} else {
// Skip HTTPS when memory is low to prevent SSL setup failures
static uint32_t lastHeapWarning = 0;
if (lastHeapWarning == 0 || !Throttle::isWithinTimespanMs(lastHeapWarning, 30000)) {
LOG_WARN("Low heap (%u bytes), skipping HTTPS processing", freeHeap);
lastHeapWarning = millis();
}
}
}
insecureServer->loop();
}
}
@@ -229,7 +248,7 @@ void initWebServer()
LOG_DEBUG("Init Web Server");
// We can now use the new certificate to setup our server as usual.
secureServer = new HTTPSServer(cert);
secureServer = new HTTPSServer(cert, 443, MAX_HTTPS_CONNECTIONS);
insecureServer = new HTTPServer();
registerHandlers(insecureServer, secureServer);
+1 -1
View File
@@ -56,7 +56,7 @@ class UdpMulticastHandler final
isRunning = false;
}
void onReceive(AsyncUDPPacket packet)
void onReceive(AsyncUDPPacket &packet)
{
if (!isRunning) {
return;
+151 -1
View File
@@ -24,6 +24,12 @@
#include "Default.h"
#include "TypeConversions.h"
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
#include "mesh/PhoneAPI.h"
#endif
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
#include "security/EncryptedStorage.h"
#endif
#if !MESHTASTIC_EXCLUDE_MQTT
#include "mqtt/MQTT.h"
@@ -82,11 +88,39 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
// and only allowing responses from that remote.
if (messageIsResponse(r)) {
LOG_DEBUG("Allow admin response message");
} else if (mp.from == 0) {
} else if (mp.from == 0 && !mp.pki_encrypted) {
// Plain (non-PKC) local admin from BLE/USB client.
// When locked: always allow through — passphrase delivery and LOCK NOW must work.
// When unlocked and is_managed: block unless this is a TAK security command
// (passphrase re-verify / LOCK NOW) or the connection is already passphrase-authorized.
// from=0 + pki_encrypted is NOT matched here and falls through to the PKC check below.
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
if (config.security.is_managed && EncryptedStorage::isUnlocked()) {
// TAK security commands carry a non-empty private_key — always let them through.
// The passphrase HMAC in EncryptedStorage is the security gate for those packets.
// Only the passphrase delivery command itself is whitelisted — it is its own auth gate.
// Destructive commands (factory reset, nodedb reset) require an already-authorized
// connection (passphrase verified or PKC admin key).
bool isTakSecurityCmd =
(r->which_payload_variant == meshtastic_AdminMessage_set_config_tag &&
r->set_config.which_payload_variant == meshtastic_Config_security_tag &&
r->set_config.payload_variant.security.private_key.size >= 1);
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
if (!isTakSecurityCmd && !PhoneAPI::isLocalAdminAuthorized()) {
#else
if (!isTakSecurityCmd) {
#endif
LOG_INFO("Ignore local admin payload because is_managed");
myReply = allocErrorResponse(meshtastic_Routing_Error_NOT_AUTHORIZED, &mp);
return handled;
}
}
#else
if (config.security.is_managed) {
LOG_INFO("Ignore local admin payload because is_managed");
return handled;
}
#endif
} else if (strcasecmp(ch->settings.name, Channels::adminChannel) == 0) {
if (!config.security.admin_channel_enabled) {
LOG_INFO("Ignore admin channel, legacy admin is disabled");
@@ -102,6 +136,15 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
memcmp(mp.public_key.bytes, config.security.admin_key[2].bytes, 32) == 0)) {
LOG_INFO("PKC admin payload with authorized sender key");
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
// Only authorize local PhoneAPI connections when the PKC admin message
// came from a local client (from=0). A remote PKC admin (from!=0) has no
// business unlocking local BLE/USB config dumps.
if (mp.from == 0) {
PhoneAPI::authorizeLocalAdmin();
}
#endif
// Automatically favorite the node that is using the admin key
auto remoteNode = nodeDB->getMeshNode(mp.from);
if (remoteNode && !remoteNode->is_favorite) {
@@ -853,6 +896,113 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c)
config.bluetooth = c.payload_variant.bluetooth;
break;
case meshtastic_Config_security_tag:
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
// set_config(security) doubles as the TAK passphrase transport (no schema changes).
// private_key field encodes the command:
// private_key.bytes/size — raw passphrase (1–64 bytes)
// size==1, bytes[0]==0xFF — LOCK NOW sentinel
// admin_key[1].bytes[0] — boots_remaining for new token (0 → default)
// admin_key[2].bytes[0..3] LE u32 — valid_until_epoch (absolute Unix timestamp; 0 → no time limit)
{
const auto &sec = c.payload_variant.security;
const uint8_t *pp = sec.private_key.bytes;
size_t ppLen = sec.private_key.size;
// MED-4: helper to zero the passphrase bytes in the decoded proto scratch buffer
// before returning. Uses volatile to prevent the compiler from eliding the wipe.
// const_cast is safe here: the underlying buffer is the mutable toRadioScratch member.
auto zeroPassphrase = [&]() {
volatile uint8_t *ppVol = const_cast<volatile uint8_t *>(pp);
for (size_t zi = 0; zi < ppLen; zi++)
ppVol[zi] = 0;
};
// LOCK NOW sentinel — always honoured regardless of lock state
if (ppLen == 1 && pp[0] == 0xFF) {
LOG_INFO("AdminModule: TAK LOCK NOW command received");
EncryptedStorage::lockNow();
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
// Immediately revoke all connection-level auth so that any config
// re-request in the window before reboot gets redacted data.
PhoneAPI::revokeAllAuth();
#endif
sendWarning("TAK_LOCKED");
zeroPassphrase(); // MED-4
reboot(DEFAULT_REBOOT_SECONDS);
return; // No config changed; skip saveChanges entirely
}
// MED-8: cap to 32 bytes to match the proto private_key field size
if (ppLen >= 1 && ppLen <= 32) {
uint8_t boots = EncryptedStorage::TOKEN_DEFAULT_BOOTS;
if (sec.admin_key[1].size >= 1 && sec.admin_key[1].bytes[0] != 0)
boots = sec.admin_key[1].bytes[0];
uint32_t validUntilEpoch = 0;
if (sec.admin_key[2].size >= 4)
memcpy(&validUntilEpoch, sec.admin_key[2].bytes, 4);
bool ok = false;
if (!EncryptedStorage::isUnlocked()) {
// Locked: provision on first boot, otherwise unlock
if (!EncryptedStorage::isProvisioned()) {
LOG_INFO("AdminModule: TAK first-time provisioning with passphrase");
ok = EncryptedStorage::provisionPassphrase(pp, ppLen, boots, validUntilEpoch);
} else {
LOG_INFO("AdminModule: TAK unlock with passphrase");
ok = EncryptedStorage::unlockWithPassphrase(pp, ppLen, boots, validUntilEpoch);
}
if (ok) {
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
PhoneAPI::authorizeLocalAdmin();
#endif
nodeDB->reloadFromDisk();
{
char unlockedMsg[64];
snprintf(unlockedMsg, sizeof(unlockedMsg), "TAK_UNLOCKED:boots=%d:until=%u",
(int)EncryptedStorage::getBootsRemaining(),
(unsigned)EncryptedStorage::getValidUntilEpoch());
sendWarning(unlockedMsg);
}
LOG_INFO("AdminModule: TAK storage unlocked, config reloaded");
}
} else {
// Already unlocked: verify passphrase to authorize this connection for admin.
// unlockWithPassphrase() re-derives KEK, unwraps DEK, refreshes the token.
LOG_INFO("AdminModule: TAK passphrase re-verify for admin authorization");
ok = EncryptedStorage::unlockWithPassphrase(pp, ppLen, boots, validUntilEpoch);
if (ok) {
#ifdef MESHTASTIC_PHONEAPI_ACCESS_CONTROL
PhoneAPI::authorizeLocalAdmin();
#endif
{
char unlockedMsg[64];
snprintf(unlockedMsg, sizeof(unlockedMsg), "TAK_UNLOCKED:boots=%d:until=%u",
(int)EncryptedStorage::getBootsRemaining(),
(unsigned)EncryptedStorage::getValidUntilEpoch());
sendWarning(unlockedMsg);
}
LOG_INFO("AdminModule: TAK passphrase verified, local admin authorized");
}
}
if (!ok) {
uint32_t backoff = EncryptedStorage::getBackoffSecondsRemaining();
char failMsg[64];
if (backoff > 0)
snprintf(failMsg, sizeof(failMsg), "TAK_UNLOCK_FAILED:backoff=%u", backoff);
else
snprintf(failMsg, sizeof(failMsg), "TAK_UNLOCK_FAILED:wrong_passphrase");
sendWarning(failMsg);
LOG_WARN("AdminModule: TAK passphrase verification failed");
}
zeroPassphrase(); // MED-4: wipe passphrase from scratch buffer before returning
return; // Passphrase handled; no config changed, skip saveChanges
}
}
// No passphrase (private_key absent or empty): fall through to normal security config.
// Reachable only when is_managed=false or device is locked (gate allows it in those states).
#endif
LOG_INFO("Set config: Security");
config.security = c.payload_variant.security;
#if !(MESHTASTIC_EXCLUDE_PKI_KEYGEN) && !(MESHTASTIC_EXCLUDE_PKI)
File diff suppressed because it is too large Load Diff
-31
View File
@@ -2,8 +2,6 @@
#if HAS_SCREEN
#include "ProtobufModule.h"
#include "input/InputBroker.h"
#include <utility>
#include <vector>
// ============================
// Enums & Defines
@@ -74,11 +72,6 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
bool shouldDraw();
bool hasMessages();
void resetSearch();
// Treat both freetext compose and emote picker as "text compose UI" for global overlays.
bool isFreeTextUIActive() const
{
return runState == CANNED_MESSAGE_RUN_STATE_FREETEXT || runState == CANNED_MESSAGE_RUN_STATE_EMOTE_PICKER;
}
void updateDestinationSelectionList();
void drawDestinationSelectionScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y);
bool isCharInputAllowed() const;
@@ -155,20 +148,6 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
unsigned long lastUpdateMillis = 0;
String searchQuery;
String freetext;
static constexpr uint8_t maxFreeTextCompletions = 4;
String freeTextCompletion;
String freeTextCompletions[maxFreeTextCompletions];
uint8_t freeTextCompletionCount = 0;
uint8_t freeTextCompletionIndex = 0;
bool freeTextCompletionSuppressed = false;
// Cached wrapped token lines for freetext rendering (rebuilt only when content/width changes).
String freeTextLayoutCacheText;
int freeTextLayoutCacheWidth = -1;
std::vector<std::vector<std::pair<bool, String>>> freeTextLayoutCacheLines;
// When true, the next emote picker selection replaces this typed prefix span.
bool freeTextEmoteReplacePending = false;
unsigned int freeTextEmoteReplaceStart = 0;
unsigned int freeTextEmoteReplaceLength = 0;
// === Message Storage ===
char messageBuffer[CANNED_MESSAGE_MODULE_MESSAGES_SIZE + 1];
@@ -211,16 +190,6 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
int handleDestinationSelectionInput(const InputEvent *event, bool isUp, bool isDown, bool isSelect);
bool handleMessageSelectorInput(const InputEvent *event, bool isUp, bool isDown, bool isSelect);
bool handleFreeTextInput(const InputEvent *event);
bool tryStartFreeTextFromInactive(const InputEvent *event);
void clearComposeState();
int32_t runFreeTextState(UIFrameEvent &e);
String getFreeTextPrefix() const;
void updateFreeTextCompletion();
bool cycleFreeTextCompletion(int8_t step);
bool acceptFreeTextCompletion(bool appendSpace);
void drawFreeTextCompletionRow(OLEDDisplay *display, int16_t x, int16_t rowY, const String &completionPrefix);
void drawFreeTextScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y, char *buffer);
void drawCannedMessageListScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y, char *buffer);
#if defined(USE_VIRTUAL_KEYBOARD)
Letter keyboard[2][4][10] = {{{{"Q", 20, 0, 0, 0, 0},
-999
View File
@@ -1,999 +0,0 @@
#include "configuration.h"
#if HAS_SCREEN
#include "CannedMessageModule.h"
#include "Channels.h"
#include "MeshService.h"
#include "MessageStore.h"
#include "NodeDB.h"
#include "buzz.h"
#include "gps/RTC.h"
#include "graphics/Screen.h"
#include "graphics/SharedUIDisplay.h"
#include "graphics/draw/MessageRenderer.h"
#include "graphics/draw/NotificationRenderer.h"
#include "graphics/emotes.h"
#include "modules/FreeTextModule.h"
#include <algorithm>
#include <cstring>
extern MessageStore messageStore;
extern bool osk_found;
extern NodeNum lastDest;
extern uint8_t lastChannel;
extern bool lastDestSet;
namespace graphics
{
extern int bannerSignalBars;
}
// Tracks whether destination-picker cancel/select should return to canned list vs freetext.
static bool returnToCannedList = false;
namespace
{
// ASCII lowercase helper keeps filtering deterministic and avoids locale overhead.
char toLowerAscii(char c)
{
if (c >= 'A' && c <= 'Z') {
return static_cast<char>(c + ('a' - 'A'));
}
return c;
}
// Case-insensitive substring search without temporary String allocations.
bool containsCaseInsensitiveAscii(const char *text, const char *needle)
{
if (!text || !needle || !needle[0]) {
return true;
}
const size_t textLen = strlen(text);
const size_t needleLen = strlen(needle);
if (needleLen > textLen) {
return false;
}
for (size_t i = 0; i + needleLen <= textLen; ++i) {
bool matched = true;
for (size_t j = 0; j < needleLen; ++j) {
if (toLowerAscii(text[i + j]) != toLowerAscii(needle[j])) {
matched = false;
break;
}
}
if (matched) {
return true;
}
}
return false;
}
// Truncate text to fit width and append ellipsis when clipping is required.
void truncateWithEllipsisToWidth(OLEDDisplay *display, char *text, size_t textSize, int maxWidth)
{
if (!display || !text || textSize == 0) {
return;
}
if (maxWidth <= 0) {
text[0] = '\0';
return;
}
if (display->getStringWidth(text) <= maxWidth) {
return;
}
if (textSize < 4) {
text[0] = '\0';
return;
}
const size_t originalLen = strlen(text);
size_t low = 0;
size_t high = std::min(originalLen, textSize - 4);
char candidate[64];
candidate[0] = '\0';
// Binary search shortest-fitting clipped token with ellipsis.
while (low <= high) {
const size_t mid = low + ((high - low) / 2);
if (mid >= sizeof(candidate)) {
break;
}
memcpy(candidate, text, mid);
candidate[mid] = '\0';
strcat(candidate, "...");
if (display->getStringWidth(candidate) <= maxWidth) {
low = mid + 1;
} else {
if (mid == 0) {
break;
}
high = mid - 1;
}
}
const size_t keep = (low == 0) ? 0 : (low - 1);
const size_t clipped = std::min(keep, textSize - 4);
text[clipped] = '\0';
strcat(text, "...");
}
// Find the emote descriptor for a token label.
const graphics::Emote *findEmoteByLabel(const String &label)
{
for (int i = 0; i < graphics::numEmotes; ++i) {
if (label == graphics::emotes[i].label) {
return &graphics::emotes[i];
}
}
return nullptr;
}
} // namespace
// Reset destination search state and keep the previous selection roughly centered.
void CannedMessageModule::resetSearch()
{
int previousDestIndex = destIndex;
searchQuery = "";
updateDestinationSelectionList();
// Adjust scrollIndex so previousDestIndex is still visible
int totalEntries = activeChannelIndices.size() + filteredNodes.size();
this->visibleRows = (displayHeight - FONT_HEIGHT_SMALL * 2) / FONT_HEIGHT_SMALL;
if (this->visibleRows < 1)
this->visibleRows = 1;
int maxScrollIndex = std::max(0, totalEntries - visibleRows);
scrollIndex = std::min(std::max(previousDestIndex - (visibleRows / 2), 0), maxScrollIndex);
lastUpdateMillis = millis();
requestFocus();
}
// Rebuild searchable destination entries (channels + eligible nodes).
void CannedMessageModule::updateDestinationSelectionList()
{
static size_t lastNumMeshNodes = 0;
static String lastSearchQuery = "";
size_t numMeshNodes = nodeDB->getNumMeshNodes();
bool nodesChanged = (numMeshNodes != lastNumMeshNodes);
lastNumMeshNodes = numMeshNodes;
// Early exit if nothing changed
if (searchQuery == lastSearchQuery && !nodesChanged)
return;
lastSearchQuery = searchQuery;
needsUpdate = false;
this->filteredNodes.clear();
this->activeChannelIndices.clear();
NodeNum myNodeNum = nodeDB->getNodeNum();
const bool hasSearchFilter = searchQuery.length() > 0;
const char *searchText = searchQuery.c_str();
// Preallocate space to reduce reallocation
this->filteredNodes.reserve(numMeshNodes);
for (size_t i = 0; i < numMeshNodes; ++i) {
meshtastic_NodeInfoLite *node = nodeDB->getMeshNodeByIndex(i);
if (!node || node->num == myNodeNum || !node->has_user || node->user.public_key.size != 32)
continue;
const char *nodeName = node->user.long_name;
if (!hasSearchFilter) {
this->filteredNodes.push_back({node, sinceLastSeen(node)});
} else {
// Compare in place to avoid building lower-cased temporary Strings per node.
if (containsCaseInsensitiveAscii(nodeName, searchText)) {
this->filteredNodes.push_back({node, sinceLastSeen(node)});
}
}
}
// Populate unique active channels without temporary String lists.
for (uint8_t i = 0; i < channels.getNumChannels(); ++i) {
const char *name = channels.getName(i);
if (!name || !name[0]) {
continue;
}
bool alreadyIncluded = false;
for (uint8_t existingIndex : this->activeChannelIndices) {
const char *existingName = channels.getName(existingIndex);
if (existingName && strcmp(existingName, name) == 0) {
alreadyIncluded = true;
break;
}
}
if (!alreadyIncluded) {
this->activeChannelIndices.push_back(i);
}
}
scrollIndex = 0; // Show first result at the top
destIndex = 0; // Highlight the first entry
if (nodesChanged && runState == CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION) {
LOG_INFO("Nodes changed, forcing UI refresh.");
screen->forceDisplay();
}
}
// Handle destination picker input: type-to-filter, navigation, select, and cancel.
int CannedMessageModule::handleDestinationSelectionInput(const InputEvent *event, bool isUp, bool isDown, bool isSelect)
{
// Override isDown and isSelect ONLY for destination selector behavior
if (runState == CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION) {
if (event->inputEvent == INPUT_BROKER_USER_PRESS) {
isDown = true;
} else if (event->inputEvent == INPUT_BROKER_SELECT) {
isSelect = true;
}
}
if (event->kbchar >= 32 && event->kbchar <= 126 && !isUp && !isDown && event->inputEvent != INPUT_BROKER_LEFT &&
event->inputEvent != INPUT_BROKER_RIGHT && event->inputEvent != INPUT_BROKER_SELECT) {
this->searchQuery += (char)event->kbchar;
needsUpdate = true;
if ((millis() - lastFilterUpdate) > filterDebounceMs) {
runOnce(); // update filter immediately
lastFilterUpdate = millis();
}
return 1;
}
size_t numMeshNodes = filteredNodes.size();
int totalEntries = numMeshNodes + activeChannelIndices.size();
int columns = 1;
int totalRows = totalEntries;
int maxScrollIndex = std::max(0, totalRows - visibleRows);
scrollIndex = clamp(scrollIndex, 0, maxScrollIndex);
// Handle backspace
if (event->inputEvent == INPUT_BROKER_BACK) {
if (searchQuery.length() > 0) {
searchQuery.remove(searchQuery.length() - 1);
needsUpdate = true;
runOnce();
}
if (searchQuery.length() == 0) {
resetSearch();
needsUpdate = false;
}
return 1;
}
if (isUp) {
if (destIndex > 0) {
destIndex--;
} else if (totalEntries > 0) {
destIndex = totalEntries - 1;
}
if ((destIndex / columns) < scrollIndex)
scrollIndex = destIndex / columns;
else if ((destIndex / columns) >= (scrollIndex + visibleRows))
scrollIndex = (destIndex / columns) - visibleRows + 1;
screen->forceDisplay(true);
return 1;
}
if (isDown) {
if (destIndex + 1 < totalEntries) {
destIndex++;
} else if (totalEntries > 0) {
destIndex = 0;
scrollIndex = 0;
}
if ((destIndex / columns) >= (scrollIndex + visibleRows))
scrollIndex = (destIndex / columns) - visibleRows + 1;
screen->forceDisplay(true);
return 1;
}
// SELECT
if (isSelect) {
if (destIndex < static_cast<int>(activeChannelIndices.size())) {
dest = NODENUM_BROADCAST;
channel = activeChannelIndices[destIndex];
lastDest = dest;
lastChannel = channel;
lastDestSet = true;
} else {
int nodeIndex = destIndex - static_cast<int>(activeChannelIndices.size());
if (nodeIndex >= 0 && nodeIndex < static_cast<int>(filteredNodes.size())) {
const meshtastic_NodeInfoLite *selectedNode = filteredNodes[nodeIndex].node;
if (selectedNode) {
dest = selectedNode->num;
channel = selectedNode->channel;
// Already saves here, but for clarity, also:
lastDest = dest;
lastChannel = channel;
lastDestSet = true;
}
}
}
runState = returnToCannedList ? CANNED_MESSAGE_RUN_STATE_ACTIVE : CANNED_MESSAGE_RUN_STATE_FREETEXT;
returnToCannedList = false;
screen->forceDisplay(true);
return 1;
}
// CANCEL
if (event->inputEvent == INPUT_BROKER_CANCEL || event->inputEvent == INPUT_BROKER_ALT_LONG) {
runState = returnToCannedList ? CANNED_MESSAGE_RUN_STATE_ACTIVE : CANNED_MESSAGE_RUN_STATE_FREETEXT;
returnToCannedList = false;
searchQuery = "";
// UIFrameEvent e;
// e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
// notifyObservers(&e);
screen->forceDisplay(true);
return 1;
}
return 0;
}
// Handle canned-message list input including destination/freetext/exit actions.
bool CannedMessageModule::handleMessageSelectorInput(const InputEvent *event, bool isUp, bool isDown, bool isSelect)
{
// Override isDown and isSelect ONLY for canned message list behavior
if (runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) {
if (event->inputEvent == INPUT_BROKER_USER_PRESS) {
isDown = true;
} else if (event->inputEvent == INPUT_BROKER_SELECT) {
isSelect = true;
}
}
if (runState == CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION)
return false;
// Handle Cancel key: go inactive, clear UI state
if (runState != CANNED_MESSAGE_RUN_STATE_INACTIVE &&
(event->inputEvent == INPUT_BROKER_CANCEL || event->inputEvent == INPUT_BROKER_ALT_LONG)) {
runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
freetext = "";
cursor = 0;
payload = 0;
currentMessageIndex = -1;
// Notify UI that we want to redraw/close this screen
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
notifyObservers(&e);
screen->forceDisplay();
return true;
}
bool handled = false;
// Handle up/down navigation
if (isUp && messagesCount > 0) {
runState = CANNED_MESSAGE_RUN_STATE_ACTION_UP;
handled = true;
} else if (isDown && messagesCount > 0) {
runState = CANNED_MESSAGE_RUN_STATE_ACTION_DOWN;
handled = true;
} else if (isSelect) {
const char *current = messages[currentMessageIndex];
// [Select Destination] triggers destination selection UI
if (strcmp(current, "[Select Destination]") == 0) {
returnToCannedList = true;
runState = CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION;
destIndex = 0;
scrollIndex = 0;
updateDestinationSelectionList(); // Make sure list is fresh
screen->forceDisplay();
return true;
}
// [Exit] returns to the main/inactive screen
if (strcmp(current, "[Exit]") == 0) {
// Set runState to inactive so we return to main UI
runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
currentMessageIndex = -1;
// Notify UI to regenerate frame set and redraw
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
notifyObservers(&e);
screen->forceDisplay();
return true;
}
// [Free Text] triggers the free text input (virtual keyboard)
#if defined(USE_VIRTUAL_KEYBOARD)
if (strcmp(current, "[-- Free Text --]") == 0) {
runState = CANNED_MESSAGE_RUN_STATE_FREETEXT;
requestFocus();
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
notifyObservers(&e);
return true;
}
#else
if (strcmp(current, "[-- Free Text --]") == 0) {
if (osk_found && screen) {
char headerBuffer[64];
if (this->dest == NODENUM_BROADCAST) {
snprintf(headerBuffer, sizeof(headerBuffer), "To: #%s", channels.getName(this->channel));
} else {
snprintf(headerBuffer, sizeof(headerBuffer), "To: @%s", getNodeName(this->dest));
}
screen->showTextInput(headerBuffer, "", 300000, [this](const std::string &text) {
if (!text.empty()) {
this->freetext = text.c_str();
this->payload = CANNED_MESSAGE_RUN_STATE_FREETEXT;
runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE;
currentMessageIndex = -1;
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->notifyObservers(&e);
screen->forceDisplay();
setIntervalFromNow(500);
return;
} else {
// Don't delete virtual keyboard immediately - it might still be executing
// Instead, just clear the callback and reset banner to stop input processing
graphics::NotificationRenderer::textInputCallback = nullptr;
graphics::NotificationRenderer::resetBanner();
// Return to inactive state
this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
this->currentMessageIndex = -1;
this->freetext = "";
this->cursor = 0;
// Force display update to show normal screen
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->notifyObservers(&e);
screen->forceDisplay();
// Schedule cleanup for next loop iteration to ensure safe deletion
setIntervalFromNow(50);
return;
}
});
return true;
}
}
#endif
// Normal canned message selection
if (runState == CANNED_MESSAGE_RUN_STATE_INACTIVE || runState == CANNED_MESSAGE_RUN_STATE_DISABLED) {
} else {
#if CANNED_MESSAGE_ADD_CONFIRMATION
const int savedIndex = currentMessageIndex;
graphics::menuHandler::showConfirmationBanner("Send message?", [this, savedIndex]() {
this->currentMessageIndex = savedIndex;
this->payload = this->runState;
this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_SELECT;
this->setIntervalFromNow(0);
});
#else
payload = runState;
runState = CANNED_MESSAGE_RUN_STATE_ACTION_SELECT;
#endif
// Do not immediately set runState; wait for confirmation
handled = true;
}
}
if (handled) {
requestFocus();
if (runState == CANNED_MESSAGE_RUN_STATE_ACTION_SELECT)
setIntervalFromNow(0);
else
runOnce();
}
return handled;
}
// Build and send a text packet, persist it locally, and switch to text-message view.
void CannedMessageModule::sendText(NodeNum dest, ChannelIndex channel, const char *message, bool wantReplies)
{
lastDest = dest;
lastChannel = channel;
lastDestSet = true;
meshtastic_MeshPacket *p = allocDataPacket();
p->to = dest;
p->channel = channel;
p->want_ack = true;
p->decoded.dest = dest; // Mirror picker: NODENUM_BROADCAST or node->num
this->lastSentNode = dest;
this->incoming = dest;
// Manually find the node by number to check PKI capability
meshtastic_NodeInfoLite *node = nullptr;
size_t numMeshNodes = nodeDB->getNumMeshNodes();
for (size_t i = 0; i < numMeshNodes; ++i) {
meshtastic_NodeInfoLite *n = nodeDB->getMeshNodeByIndex(i);
if (n && n->num == dest) {
node = n;
break;
}
}
NodeNum myNodeNum = nodeDB->getNodeNum();
if (node && node->num != myNodeNum && node->has_user && node->user.public_key.size == 32) {
p->pki_encrypted = true;
p->channel = 0; // force PKI
}
// Track this packet’s request ID for matching ACKs
this->lastRequestId = p->id;
// Copy payload
p->decoded.payload.size = strlen(message);
memcpy(p->decoded.payload.bytes, message, p->decoded.payload.size);
if (moduleConfig.canned_message.send_bell && p->decoded.payload.size < meshtastic_Constants_DATA_PAYLOAD_LEN) {
p->decoded.payload.bytes[p->decoded.payload.size++] = 7;
p->decoded.payload.bytes[p->decoded.payload.size] = '\0';
}
this->waitingForAck = true;
// Send to mesh (PKI-encrypted if conditions above matched)
service->sendToMesh(p, RX_SRC_LOCAL, true);
// Show banner immediately
if (screen) {
graphics::BannerOverlayOptions opts;
opts.message = "Sending...";
opts.durationMs = 2000;
screen->showOverlayBanner(opts);
}
// Save outgoing message
StoredMessage sm;
// Always use our local time, consistent with other paths
uint32_t nowSecs = getValidTime(RTCQuality::RTCQualityDevice, true);
sm.timestamp = (nowSecs > 0) ? nowSecs : millis() / 1000;
sm.isBootRelative = (nowSecs == 0);
sm.sender = nodeDB->getNodeNum(); // us
sm.channelIndex = channel;
size_t len = strnlen(message, MAX_MESSAGE_SIZE - 1);
sm.textOffset = MessageStore::storeText(message, len);
sm.textLength = len;
// Classify broadcast vs DM
if (dest == NODENUM_BROADCAST) {
sm.dest = NODENUM_BROADCAST;
sm.type = MessageType::BROADCAST;
} else {
sm.dest = dest;
sm.type = MessageType::DM_TO_US;
// Only add as favorite if our role is NOT CLIENT_BASE
if (config.device.role != 12) {
LOG_INFO("Proactively adding %x as favorite node", dest);
nodeDB->set_favorite(true, dest);
} else {
LOG_DEBUG("Not favoriting node %x as we are CLIENT_BASE role", dest);
}
}
sm.ackStatus = AckStatus::NONE;
messageStore.addLiveMessage(std::move(sm));
// Auto-switch thread view on outgoing message
if (sm.type == MessageType::BROADCAST) {
graphics::MessageRenderer::setThreadMode(graphics::MessageRenderer::ThreadMode::CHANNEL, sm.channelIndex);
} else {
graphics::MessageRenderer::setThreadMode(graphics::MessageRenderer::ThreadMode::DIRECT, -1, sm.dest);
}
playComboTune();
this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE;
this->payload = wantReplies ? 1 : 0;
requestFocus();
// Tell Screen to switch to TextMessage frame via UIFrameEvent
UIFrameEvent e;
e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE;
notifyObservers(&e);
}
// Draw the destination picker list with highlight, truncation, and scrollbar.
void CannedMessageModule::drawDestinationSelectionScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y)
{
requestFocus();
display->setColor(WHITE); // Always draw cleanly
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(FONT_SMALL);
// Header
int titleY = 2;
String titleText = "Select Destination";
titleText += searchQuery.length() > 0 ? " [" + searchQuery + "]" : " [ ]";
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->drawString(display->getWidth() / 2, titleY, titleText);
display->setTextAlignment(TEXT_ALIGN_LEFT);
// List Items
int rowYOffset = titleY + (FONT_HEIGHT_SMALL - 4);
int numActiveChannels = this->activeChannelIndices.size();
int totalEntries = numActiveChannels + this->filteredNodes.size();
int columns = 1;
this->visibleRows = (display->getHeight() - (titleY + FONT_HEIGHT_SMALL)) / (FONT_HEIGHT_SMALL - 4);
if (this->visibleRows < 1)
this->visibleRows = 1;
// Clamp scrolling
if (scrollIndex > totalEntries / columns)
scrollIndex = totalEntries / columns;
if (scrollIndex < 0)
scrollIndex = 0;
for (int row = 0; row < visibleRows; row++) {
int itemIndex = scrollIndex + row;
if (itemIndex >= totalEntries)
break;
int xOffset = 0;
int yOffset = row * (FONT_HEIGHT_SMALL - 4) + rowYOffset;
char entryText[64] = "";
// Draw Channels First
if (itemIndex < numActiveChannels) {
uint8_t channelIndex = this->activeChannelIndices[itemIndex];
snprintf(entryText, sizeof(entryText), "#%s", channels.getName(channelIndex));
}
// Then Draw Nodes
else {
int nodeIndex = itemIndex - numActiveChannels;
if (nodeIndex >= 0 && nodeIndex < static_cast<int>(this->filteredNodes.size())) {
meshtastic_NodeInfoLite *node = this->filteredNodes[nodeIndex].node;
if (node && node->user.long_name) {
strncpy(entryText, node->user.long_name, sizeof(entryText) - 1);
entryText[sizeof(entryText) - 1] = '\0';
}
int availWidth = display->getWidth() -
((graphics::currentResolution == graphics::ScreenResolution::High) ? 40 : 20) -
((node && node->is_favorite) ? 10 : 0);
if (availWidth < 0)
availWidth = 0;
truncateWithEllipsisToWidth(display, entryText, sizeof(entryText), availWidth);
// Prepend "* " if this is a favorite
if (node && node->is_favorite) {
size_t len = strlen(entryText);
if (len + 2 < sizeof(entryText)) {
memmove(entryText + 2, entryText, len + 1);
entryText[0] = '*';
entryText[1] = ' ';
}
}
if (node) {
if (display->getWidth() <= 64) {
snprintf(entryText, sizeof(entryText), "%s", node->user.short_name);
}
}
}
}
if (strlen(entryText) == 0 || strcmp(entryText, "Unknown") == 0)
strcpy(entryText, "?");
// Highlight background (if selected)
if (itemIndex == destIndex) {
int scrollPadding = 8; // Reserve space for scrollbar
display->fillRect(0, yOffset + 2, display->getWidth() - scrollPadding, FONT_HEIGHT_SMALL - 5);
display->setColor(BLACK);
}
// Draw entry text
display->drawString(xOffset + 2, yOffset, entryText);
display->setColor(WHITE);
// Draw key icon (after highlight)
/*
if (itemIndex >= numActiveChannels) {
int nodeIndex = itemIndex - numActiveChannels;
if (nodeIndex >= 0 && nodeIndex < static_cast<int>(this->filteredNodes.size())) {
const meshtastic_NodeInfoLite *node = this->filteredNodes[nodeIndex].node;
if (node && hasKeyForNode(node)) {
int iconX = display->getWidth() - key_symbol_width - 15;
int iconY = yOffset + (FONT_HEIGHT_SMALL - key_symbol_height) / 2;
if (itemIndex == destIndex) {
display->setColor(INVERSE);
} else {
display->setColor(WHITE);
}
display->drawXbm(iconX, iconY, key_symbol_width, key_symbol_height, key_symbol);
}
}
}
*/
}
// Scrollbar
if (totalEntries > visibleRows) {
int scrollbarHeight = visibleRows * (FONT_HEIGHT_SMALL - 4);
int totalScrollable = totalEntries;
int scrollTrackX = display->getWidth() - 6;
display->drawRect(scrollTrackX, rowYOffset, 4, scrollbarHeight);
int scrollHeight = (scrollbarHeight * visibleRows) / totalScrollable;
int scrollPos = rowYOffset + (scrollbarHeight * scrollIndex) / totalScrollable;
display->fillRect(scrollTrackX, scrollPos, 4, scrollHeight);
}
}
// Draw the canned messages list with selection highlight and emote-aware row layout.
void CannedMessageModule::drawCannedMessageListScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y,
char *buffer)
{
(void)state;
if (this->messagesCount <= 0) {
return;
}
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(FONT_SMALL);
// Precompute per-row heights based on emotes (centered if present).
const int baseRowSpacing = FONT_HEIGHT_SMALL - 4;
int topMsg;
int _visibleRows;
// Draw header (To: ...).
drawHeader(display, x, y, buffer);
// Shift message list upward by 3 pixels to reduce spacing between header and first message.
const int listYOffset = y + FONT_HEIGHT_SMALL - 3;
_visibleRows = (display->getHeight() - listYOffset) / baseRowSpacing;
// Figure out which messages are visible.
topMsg =
(messagesCount > _visibleRows && currentMessageIndex >= _visibleRows - 1) ? currentMessageIndex - _visibleRows + 2 : 0;
int countRows = std::min(messagesCount, _visibleRows);
// Draw all message rows with multi-emote support.
int yCursor = listYOffset;
for (int vis = 0; vis < countRows; vis++) {
int msgIdx = topMsg + vis;
int lineY = yCursor;
const char *msg = getMessageByIndex(msgIdx);
bool _highlight = (msgIdx == currentMessageIndex);
// Multi-emote tokenization.
std::vector<std::pair<bool, String>> tokens = freeTextModule::tokenizeMessageWithEmotes(msg);
int maxEmoteHeight = 0;
for (const auto &token : tokens) {
if (!token.first) {
continue;
}
const graphics::Emote *emote = findEmoteByLabel(token.second);
if (emote && emote->height > maxEmoteHeight) {
maxEmoteHeight = emote->height;
}
}
const int rowHeight = std::max(baseRowSpacing, maxEmoteHeight + 2);
// Vertically center based on rowHeight.
int textYOffset = (rowHeight - FONT_HEIGHT_SMALL) / 2;
#ifdef USE_EINK
int nextX = x + (_highlight ? 12 : 0);
if (_highlight)
display->drawString(x + 0, lineY + textYOffset, ">");
#else
int scrollPadding = 8;
if (_highlight) {
display->fillRect(x + 0, lineY, display->getWidth() - scrollPadding, rowHeight);
display->setColor(BLACK);
}
int nextX = x + (_highlight ? 2 : 0);
#endif
// Draw all tokens left to right.
for (const auto &token : tokens) {
if (token.first) {
// Emote rendering centralized in helper.
freeTextModule::renderEmote(display, nextX, lineY, rowHeight, token.second);
} else {
// Text.
display->drawString(nextX, lineY + textYOffset, token.second);
nextX += display->getStringWidth(token.second);
}
}
#ifndef USE_EINK
if (_highlight)
display->setColor(WHITE);
#endif
yCursor += rowHeight;
}
// Scrollbar.
if (messagesCount > _visibleRows) {
int scrollHeight = display->getHeight() - listYOffset;
int scrollTrackX = display->getWidth() - 6;
display->drawRect(scrollTrackX, listYOffset, 4, scrollHeight);
int barHeight = (scrollHeight * _visibleRows) / messagesCount;
int scrollPos = listYOffset + (scrollHeight * topMsg) / messagesCount;
display->fillRect(scrollTrackX, scrollPos, 4, barHeight);
}
}
// Map modem preset to a rough SNR quality threshold used for banner grading.
static float getSnrLimit(meshtastic_Config_LoRaConfig_ModemPreset preset)
{
switch (preset) {
case meshtastic_Config_LoRaConfig_ModemPreset_LONG_SLOW:
case meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE:
case meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST:
return -6.0f;
case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_SLOW:
case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_FAST:
return -5.5f;
case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_SLOW:
case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_FAST:
case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_TURBO:
return -4.5f;
default:
return -6.0f;
}
}
// Convert RSSI/SNR into user-facing quality label and 1-5 signal bars.
static const char *getSignalGrade(float snr, int32_t rssi, float snrLimit, int &bars)
{
// 5-bar logic: strength inside Good/Fair/Bad category
if (snr > snrLimit && rssi > -10) {
bars = 5; // very strong good
return "Good";
} else if (snr > snrLimit && rssi > -20) {
bars = 4; // normal good
return "Good";
} else if (snr > 0 && rssi > -50) {
bars = 3; // weaker good (on edge of fair)
return "Good";
} else if (snr > -10 && rssi > -100) {
bars = 2; // fair
return "Fair";
} else {
bars = 1; // bad
return "Bad";
}
}
// Process routing ACK/NACK for the most recent outbound message and show status banner.
ProcessMessage CannedMessageModule::handleReceived(const meshtastic_MeshPacket &mp)
{
// Only process routing ACK/NACK packets that are responses to our own outbound
if (mp.decoded.portnum == meshtastic_PortNum_ROUTING_APP && waitingForAck && mp.to == nodeDB->getNodeNum() &&
mp.decoded.request_id == this->lastRequestId) // only ACKs for our last sent packet
{
if (mp.decoded.request_id != 0) {
// Decode the routing response
meshtastic_Routing decoded = meshtastic_Routing_init_default;
pb_decode_from_bytes(mp.decoded.payload.bytes, mp.decoded.payload.size, meshtastic_Routing_fields, &decoded);
// Determine ACK/NACK status
bool isAck = (decoded.error_reason == meshtastic_Routing_Error_NONE);
bool isFromDest = (mp.from == this->lastSentNode);
bool wasBroadcast = (this->lastSentNode == NODENUM_BROADCAST);
// Identify the responding node
if (wasBroadcast && mp.from != nodeDB->getNodeNum()) {
this->incoming = mp.from; // relayed by another node
} else {
this->incoming = this->lastSentNode; // direct reply
}
// Final ACK/NACK logic
if (wasBroadcast) {
// Any ACK counts for broadcast
this->ack = isAck;
waitingForAck = false;
} else if (isFromDest) {
// Only ACK from destination counts as final
this->ack = isAck;
waitingForAck = false;
} else if (isAck) {
// Relay ACK → mark as RELAYED, still no final ACK
this->ack = false;
waitingForAck = false;
} else {
// Explicit failure
this->ack = false;
waitingForAck = false;
}
// Update last sent StoredMessage with ACK/NACK/RELAYED result
if (!messageStore.getMessages().empty()) {
StoredMessage &last = const_cast<StoredMessage &>(messageStore.getMessages().back());
if (last.sender == nodeDB->getNodeNum()) { // only update our own messages
if (wasBroadcast && isAck) {
last.ackStatus = AckStatus::ACKED;
} else if (isFromDest && isAck) {
last.ackStatus = AckStatus::ACKED;
} else if (!isFromDest && isAck) {
last.ackStatus = AckStatus::RELAYED;
} else {
last.ackStatus = AckStatus::NACKED;
}
}
}
// Capture radio metrics
this->lastRxRssi = mp.rx_rssi;
this->lastRxSnr = mp.rx_snr;
// Show overlay banner
if (screen) {
auto *display = screen->getDisplayDevice();
graphics::BannerOverlayOptions opts;
static char buf[128];
const char *channelName = channels.getName(this->channel);
const char *src = getNodeName(this->incoming);
char nodeName[48];
strncpy(nodeName, src, sizeof(nodeName) - 1);
nodeName[sizeof(nodeName) - 1] = '\0';
int availWidth =
display->getWidth() - ((graphics::currentResolution == graphics::ScreenResolution::High) ? 60 : 30);
if (availWidth < 0)
availWidth = 0;
truncateWithEllipsisToWidth(display, nodeName, sizeof(nodeName), availWidth);
// Calculate signal quality and bars based on preset, SNR, and RSSI
float snrLimit = getSnrLimit(config.lora.modem_preset);
int bars = 0;
const char *qualityLabel = getSignalGrade(this->lastRxSnr, this->lastRxRssi, snrLimit, bars);
if (this->ack) {
if (this->lastSentNode == NODENUM_BROADCAST) {
snprintf(buf, sizeof(buf), "Message sent to\n#%s\n\nSignal: %s",
(channelName && channelName[0]) ? channelName : "unknown", qualityLabel);
} else {
snprintf(buf, sizeof(buf), "DM sent to\n@%s\n\nSignal: %s",
(nodeName && nodeName[0]) ? nodeName : "unknown", qualityLabel);
}
} else if (isAck && !isFromDest) {
// Relay ACK banner
snprintf(buf, sizeof(buf), "DM Relayed\n(Status Unknown)\n%s\n\nSignal: %s",
(nodeName && nodeName[0]) ? nodeName : "unknown", qualityLabel);
} else {
if (this->lastSentNode == NODENUM_BROADCAST) {
snprintf(buf, sizeof(buf), "Message failed to\n#%s",
(channelName && channelName[0]) ? channelName : "unknown");
} else {
snprintf(buf, sizeof(buf), "DM failed to\n@%s", (nodeName && nodeName[0]) ? nodeName : "unknown");
}
}
opts.message = buf;
opts.durationMs = 3000;
graphics::bannerSignalBars = bars; // tell banner renderer how many bars to draw
screen->showOverlayBanner(opts); // this triggers drawNotificationBox()
}
}
}
return ProcessMessage::CONTINUE;
}
#endif
File diff suppressed because it is too large Load Diff
-16
View File
@@ -1,16 +0,0 @@
#pragma once
#if HAS_SCREEN
#include "configuration.h"
#include <utility>
#include <vector>
class OLEDDisplay;
namespace freeTextModule
{
std::vector<std::pair<bool, String>> tokenizeMessageWithEmotes(const char *msg);
void renderEmote(OLEDDisplay *display, int &nextX, int lineY, int rowHeight, const String &label);
} // namespace freeTextModule
#endif
+6 -3
View File
@@ -5,6 +5,7 @@
#include "NodeStatus.h"
#include "RTC.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "configuration.h"
#include "main.h"
#include <Throttle.h>
@@ -133,11 +134,12 @@ meshtastic_MeshPacket *NodeInfoModule::allocReply()
// Use graduated scaling based on active mesh size (10 minute base, scales with congestion coefficient)
uint32_t timeoutMs = Default::getConfiguredOrDefaultMsScaled(0, 10 * 60, nodeStatus->getNumOnline());
if (!shorterTimeout && lastSentToMesh && Throttle::isWithinTimespanMs(lastSentToMesh, timeoutMs)) {
uint32_t lastNodeInfo = transmitHistory ? transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP) : 0;
if (!shorterTimeout && lastNodeInfo && Throttle::isWithinTimespanMs(lastNodeInfo, timeoutMs)) {
LOG_DEBUG("Skip send NodeInfo since we sent it <%us ago", timeoutMs / 1000);
ignoreRequest = true; // Mark it as ignored for MeshModule
return NULL;
} else if (shorterTimeout && lastSentToMesh && Throttle::isWithinTimespanMs(lastSentToMesh, 60 * 1000)) {
} else if (shorterTimeout && lastNodeInfo && Throttle::isWithinTimespanMs(lastNodeInfo, 60 * 1000)) {
// For interactive/urgent requests (e.g., user-triggered or implicit requests), use a shorter 60s timeout
LOG_DEBUG("Skip send NodeInfo since we sent it <60s ago");
ignoreRequest = true;
@@ -159,7 +161,8 @@ meshtastic_MeshPacket *NodeInfoModule::allocReply()
strcpy(u.id, nodeDB->getNodeId().c_str());
LOG_INFO("Send owner %s/%s/%s", u.id, u.long_name, u.short_name);
lastSentToMesh = millis();
if (transmitHistory)
transmitHistory->setLastSentToMesh(meshtastic_PortNum_NODEINFO_APP);
return allocDataProtobuf(u);
}
}
-1
View File
@@ -42,7 +42,6 @@ class NodeInfoModule : public ProtobufModule<meshtastic_User>, private concurren
virtual int32_t runOnce() override;
private:
uint32_t lastSentToMesh = 0; // Last time we sent our NodeInfo to the mesh
bool shorterTimeout = false;
bool suppressReplyForCurrentRequest = false;
std::map<NodeNum, uint32_t> lastNodeInfoSeen;
+12
View File
@@ -6,6 +6,7 @@
#include "NodeDB.h"
#include "RTC.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "TypeConversions.h"
#include "airtime.h"
#include "configuration.h"
@@ -27,6 +28,15 @@ PositionModule::PositionModule()
isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others
nodeStatusObserver.observe(&nodeStatus->onNewStatus);
// Seed throttle timer from persisted transmit history so we don't re-broadcast immediately after reboot
if (transmitHistory) {
uint32_t restored = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_POSITION_APP);
if (restored != 0) {
lastGpsSend = restored;
LOG_INFO("Position: restored lastGpsSend from transmit history");
}
}
if (config.device.role != meshtastic_Config_DeviceConfig_Role_TRACKER &&
config.device.role != meshtastic_Config_DeviceConfig_Role_TAK_TRACKER) {
setIntervalFromNow(setStartDelay());
@@ -438,6 +448,8 @@ int32_t PositionModule::runOnce()
lastGpsLatitude = node->position.latitude_i;
lastGpsLongitude = node->position.longitude_i;
if (transmitHistory)
transmitHistory->setLastSentToMesh(meshtastic_PortNum_POSITION_APP);
sendOurPosition();
if (config.device.role == meshtastic_Config_DeviceConfig_Role_LOST_AND_FOUND) {
sendLostAndFoundText();
+17 -7
View File
@@ -11,6 +11,7 @@
#include "PowerFSM.h"
#include "RTC.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "UnitConversions.h"
#include "graphics/ScreenFonts.h"
#include "graphics/SharedUIDisplay.h"
@@ -19,6 +20,8 @@
#include "sleep.h"
#include <Throttle.h>
static constexpr uint16_t TX_HISTORY_KEY_AIR_QUALITY_TELEMETRY = 0x8004;
// Sensors
#include "Sensor/AddI2CSensorTemplate.h"
#include "Sensor/PMSA003ISensor.h"
@@ -108,11 +111,13 @@ int32_t AirQualityTelemetryModule::runOnce()
// Wake up the sensors that need it
LOG_INFO("Waking up sensors...");
uint32_t lastTelemetry =
transmitHistory ? transmitHistory->getLastSentToMeshMillis(TX_HISTORY_KEY_AIR_QUALITY_TELEMETRY) : 0;
for (TelemetrySensor *sensor : sensors) {
if (!sensor->canSleep()) {
LOG_DEBUG("%s sensor doesn't have sleep feature. Skipping", sensor->sensorName);
} else if (((lastSentToMesh == 0) ||
!Throttle::isWithinTimespanMs(lastSentToMesh - sensor->wakeUpTimeMs(),
} else if (((lastTelemetry == 0) ||
!Throttle::isWithinTimespanMs(lastTelemetry - sensor->wakeUpTimeMs(),
Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.air_quality_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
@@ -131,14 +136,15 @@ int32_t AirQualityTelemetryModule::runOnce()
}
}
if (((lastSentToMesh == 0) ||
!Throttle::isWithinTimespanMs(lastSentToMesh, Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.air_quality_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
if (((lastTelemetry == 0) ||
!Throttle::isWithinTimespanMs(lastTelemetry, Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.air_quality_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
airTime->isTxAllowedChannelUtil(config.device.role != meshtastic_Config_DeviceConfig_Role_SENSOR) &&
airTime->isTxAllowedAirUtil()) {
sendTelemetry();
lastSentToMesh = millis();
if (transmitHistory)
transmitHistory->setLastSentToMesh(TX_HISTORY_KEY_AIR_QUALITY_TELEMETRY);
} else if (((lastSentToPhone == 0) || !Throttle::isWithinTimespanMs(lastSentToPhone, sendToPhoneIntervalMs)) &&
(service->isToPhoneQueueEmpty())) {
// Just send to phone when it's not our time to send to mesh yet
@@ -321,6 +327,10 @@ bool AirQualityTelemetryModule::getAirQualityTelemetry(meshtastic_Telemetry *m)
meshtastic_MeshPacket *AirQualityTelemetryModule::allocReply()
{
if (currentRequest) {
if (isMultiHopBroadcastRequest() && !isSensorOrRouterRole()) {
ignoreRequest = true;
return NULL;
}
auto req = *currentRequest;
const auto &p = req.decoded;
meshtastic_Telemetry scratch;
+3 -1
View File
@@ -4,6 +4,8 @@
#pragma once
#include "BaseTelemetryModule.h"
#ifndef AIR_QUALITY_TELEMETRY_MODULE_ENABLE
#define AIR_QUALITY_TELEMETRY_MODULE_ENABLE 0
#endif
@@ -17,6 +19,7 @@
class AirQualityTelemetryModule : private concurrency::OSThread,
public ScanI2CConsumer,
public BaseTelemetryModule,
public ProtobufModule<meshtastic_Telemetry>
{
CallbackObserver<AirQualityTelemetryModule, const meshtastic::Status *> nodeStatusObserver =
@@ -65,7 +68,6 @@ class AirQualityTelemetryModule : private concurrency::OSThread,
meshtastic_MeshPacket *lastMeasurementPacket;
uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute
// uint32_t sendToPhoneIntervalMs = 1000; // Send to phone every minute
uint32_t lastSentToMesh = 0;
uint32_t lastSentToPhone = 0;
};
@@ -0,0 +1,14 @@
#pragma once
#include "NodeDB.h"
#include "configuration.h"
class BaseTelemetryModule
{
protected:
bool isSensorOrRouterRole() const
{
return config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR ||
config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER;
}
};
+14 -7
View File
@@ -7,6 +7,7 @@
#include "RTC.h"
#include "RadioLibInterface.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "configuration.h"
#include "main.h"
#include "memGet.h"
@@ -15,21 +16,23 @@
#include <meshUtils.h>
#define MAGIC_USB_BATTERY_LEVEL 101
static constexpr uint16_t TX_HISTORY_KEY_DEVICE_TELEMETRY = 0x8001;
int32_t DeviceTelemetryModule::runOnce()
{
refreshUptime();
bool isImpoliteRole =
IS_ONE_OF(config.device.role, meshtastic_Config_DeviceConfig_Role_SENSOR, meshtastic_Config_DeviceConfig_Role_ROUTER);
if (((lastSentToMesh == 0) ||
((uptimeLastMs - lastSentToMesh) >=
Default::getConfiguredOrDefaultMsScaled(moduleConfig.telemetry.device_update_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
uint32_t lastTelemetry = transmitHistory ? transmitHistory->getLastSentToMeshMillis(TX_HISTORY_KEY_DEVICE_TELEMETRY) : 0;
bool isImpoliteRole = isSensorOrRouterRole();
if (((lastTelemetry == 0) ||
((uptimeLastMs - lastTelemetry) >= Default::getConfiguredOrDefaultMsScaled(moduleConfig.telemetry.device_update_interval,
default_telemetry_broadcast_interval_secs,
numOnlineNodes))) &&
airTime->isTxAllowedChannelUtil(!isImpoliteRole) && airTime->isTxAllowedAirUtil() &&
config.device.role != meshtastic_Config_DeviceConfig_Role_CLIENT_HIDDEN &&
moduleConfig.telemetry.device_telemetry_enabled) {
sendTelemetry();
lastSentToMesh = uptimeLastMs;
if (transmitHistory)
transmitHistory->setLastSentToMesh(TX_HISTORY_KEY_DEVICE_TELEMETRY);
} else if (service->isToPhoneQueueEmpty()) {
// Just send to phone when it's not our time to send to mesh yet
// Only send while queue is empty (phone assumed connected)
@@ -60,6 +63,10 @@ bool DeviceTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPacket &
meshtastic_MeshPacket *DeviceTelemetryModule::allocReply()
{
if (currentRequest) {
if (isMultiHopBroadcastRequest() && !isSensorOrRouterRole()) {
ignoreRequest = true;
return NULL;
}
auto req = *currentRequest;
const auto &p = req.decoded;
meshtastic_Telemetry scratch;
+4 -2
View File
@@ -1,11 +1,14 @@
#pragma once
#include "../mesh/generated/meshtastic/telemetry.pb.h"
#include "BaseTelemetryModule.h"
#include "NodeDB.h"
#include "ProtobufModule.h"
#include <OLEDDisplay.h>
#include <OLEDDisplayUi.h>
class DeviceTelemetryModule : private concurrency::OSThread, public ProtobufModule<meshtastic_Telemetry>
class DeviceTelemetryModule : private concurrency::OSThread,
public BaseTelemetryModule,
public ProtobufModule<meshtastic_Telemetry>
{
CallbackObserver<DeviceTelemetryModule, const meshtastic::Status *> nodeStatusObserver =
CallbackObserver<DeviceTelemetryModule, const meshtastic::Status *>(this, &DeviceTelemetryModule::handleStatusUpdate);
@@ -48,7 +51,6 @@ class DeviceTelemetryModule : private concurrency::OSThread, public ProtobufModu
uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute
uint32_t sendStatsToPhoneIntervalMs = 15 * SECONDS_IN_MINUTE * 1000; // Send stats to phone every 15 minutes
uint32_t lastSentStatsToPhone = 0;
uint32_t lastSentToMesh = 0;
void refreshUptime()
{
+22 -9
View File
@@ -10,6 +10,7 @@
#include "PowerFSM.h"
#include "RTC.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "UnitConversions.h"
#include "buzz.h"
#include "graphics/SharedUIDisplay.h"
@@ -145,6 +146,8 @@ extern void drawCommonHeader(OLEDDisplay *display, int16_t x, int16_t y, const c
#include "graphics/ScreenFonts.h"
#include <Throttle.h>
static constexpr uint16_t TX_HISTORY_KEY_ENVIRONMENT_TELEMETRY = 0x8002;
void EnvironmentTelemetryModule::i2cScanFinished(ScanI2C *i2cScanner)
{
if (!moduleConfig.telemetry.environment_measurement_enabled && !ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE) {
@@ -297,7 +300,8 @@ int32_t EnvironmentTelemetryModule::runOnce()
// this only works on the wismesh hub with the solar option. This is not an I2C sensor, so we don't need the
// sensormap here.
#ifdef HAS_RAKPROT
result = rak9154Sensor.runOnce();
if (rak9154Sensor.hasSensor())
result = rak9154Sensor.runOnce();
#endif
#endif
}
@@ -317,14 +321,17 @@ int32_t EnvironmentTelemetryModule::runOnce()
}
}
if (((lastSentToMesh == 0) ||
!Throttle::isWithinTimespanMs(lastSentToMesh, Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.environment_update_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
uint32_t lastTelemetry =
transmitHistory ? transmitHistory->getLastSentToMeshMillis(TX_HISTORY_KEY_ENVIRONMENT_TELEMETRY) : 0;
if (((lastTelemetry == 0) ||
!Throttle::isWithinTimespanMs(lastTelemetry, Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.environment_update_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
airTime->isTxAllowedChannelUtil(config.device.role != meshtastic_Config_DeviceConfig_Role_SENSOR) &&
airTime->isTxAllowedAirUtil()) {
sendTelemetry();
lastSentToMesh = millis();
if (transmitHistory)
transmitHistory->setLastSentToMesh(TX_HISTORY_KEY_ENVIRONMENT_TELEMETRY);
} else if (((lastSentToPhone == 0) || !Throttle::isWithinTimespanMs(lastSentToPhone, sendToPhoneIntervalMs)) &&
(service->isToPhoneQueueEmpty())) {
// Just send to phone when it's not our time to send to mesh yet
@@ -567,9 +574,11 @@ bool EnvironmentTelemetryModule::getEnvironmentTelemetry(meshtastic_Telemetry *m
}
#endif
#ifdef HAS_RAKPROT
get_metrics = rak9154Sensor.getMetrics(m);
valid = valid || get_metrics;
hasSensor = true;
if (rak9154Sensor.hasSensor()) {
get_metrics = rak9154Sensor.getMetrics(m);
valid = valid || get_metrics;
hasSensor = true;
}
#endif
return valid && hasSensor;
}
@@ -577,6 +586,10 @@ bool EnvironmentTelemetryModule::getEnvironmentTelemetry(meshtastic_Telemetry *m
meshtastic_MeshPacket *EnvironmentTelemetryModule::allocReply()
{
if (currentRequest) {
if (isMultiHopBroadcastRequest() && !isSensorOrRouterRole()) {
ignoreRequest = true;
return NULL;
}
auto req = *currentRequest;
const auto &p = req.decoded;
meshtastic_Telemetry scratch;
+3 -1
View File
@@ -4,6 +4,8 @@
#pragma once
#include "BaseTelemetryModule.h"
#ifndef ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE
#define ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE 0
#endif
@@ -17,6 +19,7 @@
class EnvironmentTelemetryModule : private concurrency::OSThread,
public ScanI2CConsumer,
public BaseTelemetryModule,
public ProtobufModule<meshtastic_Telemetry>
{
CallbackObserver<EnvironmentTelemetryModule, const meshtastic::Status *> nodeStatusObserver =
@@ -65,7 +68,6 @@ class EnvironmentTelemetryModule : private concurrency::OSThread,
bool firstTime = 1;
meshtastic_MeshPacket *lastMeasurementPacket;
uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute
uint32_t lastSentToMesh = 0;
uint32_t lastSentToPhone = 0;
};
+14 -5
View File
@@ -10,6 +10,7 @@
#include "PowerFSM.h"
#include "RTC.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "UnitConversions.h"
#include "main.h"
#include "power.h"
@@ -33,6 +34,8 @@ MLX90614Sensor mlx90614Sensor;
#endif
#include <Throttle.h>
static constexpr uint16_t TX_HISTORY_KEY_HEALTH_TELEMETRY = 0x8003;
int32_t HealthTelemetryModule::runOnce()
{
if (sleepOnNextExecution == true) {
@@ -69,14 +72,16 @@ int32_t HealthTelemetryModule::runOnce()
return disable();
}
if (((lastSentToMesh == 0) ||
!Throttle::isWithinTimespanMs(lastSentToMesh, Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.health_update_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
uint32_t lastTelemetry = transmitHistory ? transmitHistory->getLastSentToMeshMillis(TX_HISTORY_KEY_HEALTH_TELEMETRY) : 0;
if (((lastTelemetry == 0) ||
!Throttle::isWithinTimespanMs(lastTelemetry, Default::getConfiguredOrDefaultMsScaled(
moduleConfig.telemetry.health_update_interval,
default_telemetry_broadcast_interval_secs, numOnlineNodes))) &&
airTime->isTxAllowedChannelUtil(config.device.role != meshtastic_Config_DeviceConfig_Role_SENSOR) &&
airTime->isTxAllowedAirUtil()) {
sendTelemetry();
lastSentToMesh = millis();
if (transmitHistory)
transmitHistory->setLastSentToMesh(TX_HISTORY_KEY_HEALTH_TELEMETRY);
} else if (((lastSentToPhone == 0) || !Throttle::isWithinTimespanMs(lastSentToPhone, sendToPhoneIntervalMs)) &&
(service->isToPhoneQueueEmpty())) {
// Just send to phone when it's not our time to send to mesh yet
@@ -192,6 +197,10 @@ bool HealthTelemetryModule::getHealthTelemetry(meshtastic_Telemetry *m)
meshtastic_MeshPacket *HealthTelemetryModule::allocReply()
{
if (currentRequest) {
if (isMultiHopBroadcastRequest() && !isSensorOrRouterRole()) {
ignoreRequest = true;
return NULL;
}
auto req = *currentRequest;
const auto &p = req.decoded;
meshtastic_Telemetry scratch;
+4 -2
View File
@@ -4,12 +4,15 @@
#pragma once
#include "../mesh/generated/meshtastic/telemetry.pb.h"
#include "BaseTelemetryModule.h"
#include "NodeDB.h"
#include "ProtobufModule.h"
#include <OLEDDisplay.h>
#include <OLEDDisplayUi.h>
class HealthTelemetryModule : private concurrency::OSThread, public ProtobufModule<meshtastic_Telemetry>
class HealthTelemetryModule : private concurrency::OSThread,
public BaseTelemetryModule,
public ProtobufModule<meshtastic_Telemetry>
{
CallbackObserver<HealthTelemetryModule, const meshtastic::Status *> nodeStatusObserver =
CallbackObserver<HealthTelemetryModule, const meshtastic::Status *>(this, &HealthTelemetryModule::handleStatusUpdate);
@@ -52,7 +55,6 @@ class HealthTelemetryModule : private concurrency::OSThread, public ProtobufModu
bool firstTime = 1;
meshtastic_MeshPacket *lastMeasurementPacket;
uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute
uint32_t lastSentToMesh = 0;
uint32_t lastSentToPhone = 0;
uint32_t sensor_read_error_count = 0;
};
+11 -2
View File
@@ -10,6 +10,7 @@
#include "PowerTelemetry.h"
#include "RTC.h"
#include "Router.h"
#include "TransmitHistory.h"
#include "graphics/SharedUIDisplay.h"
#include "main.h"
#include "power.h"
@@ -22,6 +23,8 @@
#include "graphics/ScreenFonts.h"
#include <Throttle.h>
static constexpr uint16_t TX_HISTORY_KEY_POWER_TELEMETRY = 0x8005;
namespace graphics
{
extern void drawCommonHeader(OLEDDisplay *display, int16_t x, int16_t y, const char *titleStr, bool force_no_invert,
@@ -88,10 +91,12 @@ int32_t PowerTelemetryModule::runOnce()
if (!moduleConfig.telemetry.power_measurement_enabled)
return disable();
if (((lastSentToMesh == 0) || !Throttle::isWithinTimespanMs(lastSentToMesh, sendToMeshIntervalMs)) &&
uint32_t lastTelemetry = transmitHistory ? transmitHistory->getLastSentToMeshMillis(TX_HISTORY_KEY_POWER_TELEMETRY) : 0;
if (((lastTelemetry == 0) || !Throttle::isWithinTimespanMs(lastTelemetry, sendToMeshIntervalMs)) &&
airTime->isTxAllowedAirUtil()) {
sendTelemetry();
lastSentToMesh = millis();
if (transmitHistory)
transmitHistory->setLastSentToMesh(TX_HISTORY_KEY_POWER_TELEMETRY);
} else if (((lastSentToPhone == 0) || !Throttle::isWithinTimespanMs(lastSentToPhone, sendToPhoneIntervalMs)) &&
(service->isToPhoneQueueEmpty())) {
// Just send to phone when it's not our time to send to mesh yet
@@ -217,6 +222,10 @@ bool PowerTelemetryModule::getPowerTelemetry(meshtastic_Telemetry *m)
meshtastic_MeshPacket *PowerTelemetryModule::allocReply()
{
if (currentRequest) {
if (isMultiHopBroadcastRequest() && !isSensorOrRouterRole()) {
ignoreRequest = true;
return NULL;
}
auto req = *currentRequest;
const auto &p = req.decoded;
meshtastic_Telemetry scratch;
+4 -2
View File
@@ -5,12 +5,15 @@
#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR
#include "../mesh/generated/meshtastic/telemetry.pb.h"
#include "BaseTelemetryModule.h"
#include "NodeDB.h"
#include "ProtobufModule.h"
#include <OLEDDisplay.h>
#include <OLEDDisplayUi.h>
class PowerTelemetryModule : private concurrency::OSThread, public ProtobufModule<meshtastic_Telemetry>
class PowerTelemetryModule : private concurrency::OSThread,
public BaseTelemetryModule,
public ProtobufModule<meshtastic_Telemetry>
{
CallbackObserver<PowerTelemetryModule, const meshtastic::Status *> nodeStatusObserver =
CallbackObserver<PowerTelemetryModule, const meshtastic::Status *>(this, &PowerTelemetryModule::handleStatusUpdate);
@@ -51,7 +54,6 @@ class PowerTelemetryModule : private concurrency::OSThread, public ProtobufModul
bool firstTime = 1;
meshtastic_MeshPacket *lastMeasurementPacket;
uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute
uint32_t lastSentToMesh = 0;
uint32_t lastSentToPhone = 0;
uint32_t sensor_read_error_count = 0;
};
@@ -18,6 +18,7 @@ class RAK9154Sensor : public TelemetrySensor, VoltageSensor, CurrentSensor
public:
RAK9154Sensor();
bool hasSensor() { return true; } // Not an I2C sensor; always available when HAS_RAKPROT is defined
virtual int32_t runOnce() override;
virtual bool getMetrics(meshtastic_Telemetry *measurement) override;
virtual uint16_t getBusVoltageMv() override;
+10 -3
View File
@@ -53,6 +53,9 @@ static uint8_t bytes[meshtastic_MqttClientProxyMessage_size + 30]; // 12 for cha
static bool isMqttServerAddressPrivate = false;
static bool isConnected = false;
static uint32_t lastPositionUnavailableWarning = 0;
static const uint32_t POSITION_UNAVAILABLE_WARNING_INTERVAL_MS = 15000; // 15 seconds
inline void onReceiveProto(char *topic, byte *payload, size_t length)
{
const DecodedServiceEnvelope e(payload, length);
@@ -453,7 +456,9 @@ MQTT::MQTT() : concurrency::OSThread("mqtt"), mqttQueue(MAX_MQTT_QUEUE)
enabled = true;
runASAP = true;
reconnectCount = 0;
#if !IS_RUNNING_TESTS
publishNodeInfo();
#endif
}
// preflightSleepObserver.observe(&preflightSleep);
} else {
@@ -845,12 +850,14 @@ void MQTT::perhapsReportToMap()
map_position_precision = default_map_position_precision;
}
if (Throttle::isWithinTimespanMs(last_report_to_map, map_publish_interval_msecs))
if (Throttle::isWithinTimespanMs(last_report_to_map, map_publish_interval_msecs) && last_report_to_map != 0)
return;
if (localPosition.latitude_i == 0 && localPosition.longitude_i == 0) {
last_report_to_map = millis();
LOG_WARN("MQTT Map report enabled, but no position available");
if (Throttle::isWithinTimespanMs(lastPositionUnavailableWarning, POSITION_UNAVAILABLE_WARNING_INTERVAL_MS) == false) {
LOG_WARN("MQTT Map report enabled, but no position available");
lastPositionUnavailableWarning = millis();
}
return;
}
+16 -7
View File
@@ -52,6 +52,20 @@ NimBLEServer *bleServer;
static bool passkeyShowing;
static std::atomic<uint16_t> nimbleBluetoothConnHandle{BLE_HS_CONN_HANDLE_NONE}; // BLE_HS_CONN_HANDLE_NONE means "no connection"
static void clearPairingDisplay()
{
if (!passkeyShowing) {
return;
}
passkeyShowing = false;
#if HAS_SCREEN
if (screen) {
screen->endAlert();
}
#endif
}
class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread
{
/*
@@ -630,13 +644,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks
meshtastic::BluetoothStatus newStatus(meshtastic::BluetoothStatus::ConnectionState::CONNECTED);
bluetoothStatus->updateStatus(&newStatus);
// Todo: migrate this display code back into Screen class, and observe bluetoothStatus
if (passkeyShowing) {
passkeyShowing = false;
if (screen)
screen->endAlert();
}
clearPairingDisplay();
// Store the connection handle for future use
#ifdef NIMBLE_TWO
@@ -693,6 +701,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks
meshtastic::BluetoothStatus newStatus(meshtastic::BluetoothStatus::ConnectionState::DISCONNECTED);
bluetoothStatus->updateStatus(&newStatus);
clearPairingDisplay();
if (bluetoothPhoneAPI) {
bluetoothPhoneAPI->close();
@@ -1,6 +1,6 @@
/**************************************************************************/
/*!
@file BLEDfu.cpp
@file BLEDfuSecure.cpp
@author hathach (tinyusb.org)
@section LICENSE
+1 -1
View File
@@ -1,6 +1,6 @@
/**************************************************************************/
/*!
@file BLEDfu.h
@file BLEDfuSecure.h
@author hathach (tinyusb.org)
@section LICENSE
+15 -1
View File
@@ -32,6 +32,7 @@ static uint8_t toRadioBytes[meshtastic_ToRadio_size];
static uint8_t lastToRadio[MAX_TO_FROM_RADIO_SIZE];
static uint16_t connectionHandle;
static bool passkeyShowing;
class BluetoothPhoneAPI : public PhoneAPI
{
@@ -86,6 +87,16 @@ void onDisconnect(uint16_t conn_handle, uint8_t reason)
// Notify UI (or any other interested firmware components)
meshtastic::BluetoothStatus newStatus(meshtastic::BluetoothStatus::ConnectionState::DISCONNECTED);
bluetoothStatus->updateStatus(&newStatus);
#if HAS_SCREEN
// If a pairing prompt is active, make sure we dismiss it on disconnect/cancel/failure paths.
if (passkeyShowing) {
passkeyShowing = false;
if (screen) {
screen->endAlert();
}
}
#endif
}
void onCccd(uint16_t conn_hdl, BLECharacteristic *chr, uint16_t cccd_value)
{
@@ -400,6 +411,8 @@ bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passke
});
}
#endif
passkeyShowing = true;
if (match_request) {
uint32_t start_time = millis();
while (millis() < start_time + 30000) {
@@ -451,6 +464,7 @@ void NRF52Bluetooth::onPairingCompleted(uint16_t conn_handle, uint8_t auth_statu
}
// Todo: migrate this display code back into Screen class, and observe bluetoothStatus
passkeyShowing = false;
if (screen) {
screen->endAlert();
}
@@ -464,4 +478,4 @@ void NRF52Bluetooth::sendLog(const uint8_t *logMessage, size_t length)
logRadio.indicate(logMessage, (uint16_t)length);
else
logRadio.notify(logMessage, (uint16_t)length);
}
}
+21
View File
@@ -537,6 +537,27 @@ void portduinoSetup()
}
}
// In one test, this dance seemed necessary to trigger the pin to detect properly.
if (portduino_config.lora_pa_detect_pin.enabled) {
pinMode(portduino_config.lora_pa_detect_pin.pin, INPUT_PULLDOWN);
sleep(1);
if (digitalRead(portduino_config.lora_pa_detect_pin.pin) == LOW) {
std::cout << "Pin " << portduino_config.lora_pa_detect_pin.pin << " PULLDOWN is LOW" << std::endl;
}
pinMode(portduino_config.lora_pa_detect_pin.pin, INPUT_PULLUP);
sleep(1);
if (digitalRead(portduino_config.lora_pa_detect_pin.pin) == HIGH) {
std::cout << "Pin " << portduino_config.lora_pa_detect_pin.pin << " PULLUP is HIGH, dropping PA curve" << std::endl;
portduino_config.num_pa_points = 1;
portduino_config.tx_gain_lora[0] = 0;
} else {
std::cout << "Pin " << portduino_config.lora_pa_detect_pin.pin << " PULLUP is LOW, using PA curve" << std::endl;
}
// disable bias once finished
pinMode(portduino_config.lora_pa_detect_pin.pin, INPUT);
}
// Only initialize the radio pins when dealing with real, kernel controlled SPI hardware
if (portduino_config.lora_spi_dev != "" && portduino_config.lora_spi_dev != "ch341") {
SPI.begin(portduino_config.lora_spi_dev.c_str());
+11 -4
View File
@@ -107,6 +107,7 @@ extern struct portduino_config_struct {
pinMapping lora_txen_pin = {"Lora", "TXen"};
pinMapping lora_rxen_pin = {"Lora", "RXen"};
pinMapping lora_sx126x_ant_sw_pin = {"Lora", "SX126X_ANT_SW"};
pinMapping lora_pa_detect_pin = {"Lora", "GPIO_DETECT_PA"};
std::vector<pinMapping> extra_pins = {};
// GPS
@@ -194,13 +195,14 @@ extern struct portduino_config_struct {
int maxtophone = 100;
int MaxNodes = 200;
pinMapping *all_pins[20] = {&lora_cs_pin,
pinMapping *all_pins[21] = {&lora_cs_pin,
&lora_irq_pin,
&lora_busy_pin,
&lora_reset_pin,
&lora_txen_pin,
&lora_rxen_pin,
&lora_sx126x_ant_sw_pin,
&lora_pa_detect_pin,
&displayDC,
&displayCS,
&displayBacklight,
@@ -255,18 +257,23 @@ extern struct portduino_config_struct {
out << YAML::Key << "TX_GAIN_LORA" << YAML::Value << tx_gain_lora[0];
}
out << YAML::Key << "DIO2_AS_RF_SWITCH" << YAML::Value << dio2_as_rf_switch;
if (dio2_as_rf_switch)
out << YAML::Key << "DIO2_AS_RF_SWITCH" << YAML::Value << dio2_as_rf_switch;
if (dio3_tcxo_voltage != 0)
out << YAML::Key << "DIO3_TCXO_VOLTAGE" << YAML::Value << YAML::Precision(3) << (float)dio3_tcxo_voltage / 1000;
if (lora_usb_pid != 0x5512)
out << YAML::Key << "USB_PID" << YAML::Value << YAML::Hex << lora_usb_pid;
if (lora_usb_vid != 0x1A86)
out << YAML::Key << "USB_VID" << YAML::Value << YAML::Hex << lora_usb_vid;
if (lora_spi_dev != "")
if (lora_spi_dev != "" && !(lora_spi_dev == "/dev/spidev0.0" && lora_module == use_autoconf)) {
if (lora_spi_dev.find("/dev/") != std::string::npos)
lora_spi_dev = lora_spi_dev.substr(5);
out << YAML::Key << "spidev" << YAML::Value << lora_spi_dev;
}
if (lora_usb_serial_num != "")
out << YAML::Key << "USB_Serialnum" << YAML::Value << lora_usb_serial_num;
out << YAML::Key << "spiSpeed" << YAML::Value << spiSpeed;
if (spiSpeed != 2000000)
out << YAML::Key << "spiSpeed" << YAML::Value << spiSpeed;
if (rfswitch_dio_pins[0] != RADIOLIB_NC) {
out << YAML::Key << "rfswitch_table" << YAML::Value << YAML::BeginMap;
+43
View File
@@ -0,0 +1,43 @@
#include "configuration.h"
#ifdef MESHTASTIC_ENABLE_APPROTECT
#ifdef ARCH_NRF52
#include "APProtect.h"
#include <nrf.h>
void enableAPProtect()
{
// APPROTECT register: 0x00 = enabled (protected), 0xFF = disabled (open)
// On nRF52840, UICR.APPROTECT at address 0x10001208
if (NRF_UICR->APPROTECT != 0x00) {
LOG_WARN("Enabling APPROTECT - debug port will be disabled after reset");
// UICR writes require NVMC to be in write mode
NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
;
NRF_UICR->APPROTECT = 0x00;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
;
// Return NVMC to read-only mode
NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren;
while (NRF_NVMC->READY == NVMC_READY_READY_Busy)
;
LOG_INFO("APPROTECT set, will take effect after next reset");
} else {
LOG_DEBUG("APPROTECT already enabled");
}
}
#else
// Non-nRF52 builds - no-op
void enableAPProtect()
{
LOG_DEBUG("APPROTECT not supported on this platform");
}
#endif // ARCH_NRF52
#endif // MESHTASTIC_ENABLE_APPROTECT
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#ifdef MESHTASTIC_ENABLE_APPROTECT
/**
* Enable APPROTECT on nRF52840 to block debug probe access.
* Writes NRF_UICR->APPROTECT = 0x00 if not already set.
* Must be called early in setup() before any sensitive data is loaded.
*
* WARNING: This is a one-way operation. Once APPROTECT is enabled,
* the debug port is permanently disabled. The device can still be
* re-flashed via the bootloader (USB/DFU), but SWD/JTAG access is blocked.
*/
void enableAPProtect();
#endif // MESHTASTIC_ENABLE_APPROTECT
File diff suppressed because it is too large Load Diff
+198
View File
@@ -0,0 +1,198 @@
#pragma once
#ifdef MESHTASTIC_ENCRYPTED_STORAGE
#include <cstddef>
#include <cstdint>
/**
* Encrypted storage layer for TAK secure builds.
*
* Key hierarchy:
* FICR eFuse IDs + passphrase -> SHA-256 -> KEK_v2 (16 bytes, never stored)
* KEK_v2 wraps -> DEK (Data Encryption Key, 16 bytes, random, stored in /prefs/.dek)
* DEK encrypts -> proto files via AES-128-CTR + HMAC-SHA256(KEK)
*
* Ephemeral KEK (FICR-only, no passphrase) -> wraps DEK in the unlock token only.
* Unlock token (/prefs/.unlock_token) — valid for N boots and/or M hours after provisioning.
*
* Boot flow:
* 1. initLocked() — derive ephemeral KEK, try unlock token
* 2a. Token valid → UNLOCKED (DEK in RAM, all encrypted files accessible)
* 2b. No token, no DEK file → NOT PROVISIONED (operator must call provisionPassphrase)
* 2c. No token, DEK file exists → LOCKED (operator must call unlockWithPassphrase)
* 3. provisionPassphrase() / unlockWithPassphrase() complete the unlock
* 4. lockNow() immediately invalidates the token and zeroes the DEK from RAM
*
* Encrypted proto file format ("MENC"):
* [4B] Magic 0x4D454E43 ("MENC")
* [1B] Version 0x01
* [13B] Nonce (random per write)
* [4B] Original plaintext length (LE uint32)
* [NB] AES-128-CTR ciphertext
* [32B] HMAC-SHA256(DEK, nonce || ciphertext)
* Total overhead: 54 bytes per file.
*
* DEK file format v2 ("MDEK"):
* [4B] Magic 0x4D44454B ("MDEK")
* [1B] Version 0x02
* [13B] Nonce (random per write)
* [16B] AES-128-CTR(KEK_v2, nonce, DEK)
* [32B] HMAC-SHA256(KEK_v2, "mdek-auth" || nonce || encrypted_DEK)
* Total: 66 bytes.
* Legacy v1 DEK file is 29 bytes (no magic, no HMAC) and is migrated on first passphrase set.
*
* Unlock token format ("UTOK"):
* [4B] Magic 0x55544F4B ("UTOK")
* [1B] Version 0x01
* [13B] Nonce (random per write)
* [16B] AES-128-CTR(ephemeralKEK, nonce, DEK)
* [1B] boots_remaining
* [4B] valid_until_epoch (LE uint32, 0 = no time limit)
* [32B] HMAC-SHA256(ephemeralKEK, all above fields)
* Total: 71 bytes.
*/
namespace EncryptedStorage {
// ---------------------------------------------------------------------------
// File format constants
// ---------------------------------------------------------------------------
static constexpr uint32_t MAGIC = 0x4D454E43; // "MENC" — encrypted proto files
static constexpr uint8_t VERSION = 0x01;
static constexpr size_t NONCE_SIZE = 13;
static constexpr size_t HMAC_SIZE = 32;
static constexpr size_t HEADER_SIZE = 4 + 1 + NONCE_SIZE + 4; // magic+version+nonce+plaintext_len
static constexpr size_t OVERHEAD = HEADER_SIZE + HMAC_SIZE; // 54 bytes
static constexpr size_t AES_KEY_SIZE = 16;
static constexpr size_t AES_BLOCK_SIZE = 16;
static constexpr uint32_t DEK_MAGIC_V2 = 0x4D44454B; // "MDEK"
static constexpr uint8_t DEK_VERSION_V2 = 0x02;
static constexpr size_t DEK_V1_SIZE = NONCE_SIZE + AES_KEY_SIZE; // 29 bytes
static constexpr size_t DEK_V2_SIZE = 4 + 1 + NONCE_SIZE + AES_KEY_SIZE + HMAC_SIZE; // 66 bytes
static constexpr uint32_t TOKEN_MAGIC = 0x55544F4B; // "UTOK"
static constexpr uint8_t TOKEN_VERSION = 0x01;
// Body = magic(4)+ver(1)+nonce(13)+encDEK(16)+boots(1)+epoch(4) = 39 bytes
static constexpr size_t TOKEN_BODY_SIZE = 4 + 1 + NONCE_SIZE + AES_KEY_SIZE + 1 + 4;
static constexpr size_t TOKEN_TOTAL_SIZE = TOKEN_BODY_SIZE + HMAC_SIZE; // 71 bytes
static constexpr uint8_t TOKEN_DEFAULT_BOOTS = 50;
// ---------------------------------------------------------------------------
// Passphrase-gated boot API
// ---------------------------------------------------------------------------
/**
* Boot-time init: derive ephemeral KEK and attempt to unlock via the stored token.
* Sets isUnlocked()=true if the token is present and valid.
* Must be called after fsInit(), before loadFromDisk().
*/
void initLocked();
/**
* First-time provisioning: set the device passphrase, generate a fresh DEK,
* save it wrapped with the passphrase-mixed KEK, and create an unlock token.
*
* If a legacy v1 DEK file already exists, it is migrated rather than replaced,
* preserving all previously encrypted config files.
*
* @param passphrase Raw passphrase bytes (need not be NUL-terminated)
* @param passphraseLen Length in bytes (1–32; matches the proto private_key field size)
* @param bootsRemaining Token valid for this many boots (default TOKEN_DEFAULT_BOOTS)
* @param validUntilEpoch Absolute Unix timestamp after which token expires (0 = no time limit)
* @return true on success
*/
bool provisionPassphrase(const uint8_t *passphrase, size_t passphraseLen,
uint8_t bootsRemaining = TOKEN_DEFAULT_BOOTS, uint32_t validUntilEpoch = 0);
/**
* Unlock after token expiry (or after lockNow()): derive KEK from passphrase,
* unwrap the stored DEK, and create a fresh unlock token.
*
* @param passphrase Raw passphrase bytes
* @param passphraseLen Length in bytes (1–32; matches the proto private_key field size)
* @param bootsRemaining New token valid for this many boots
* @param validUntilEpoch Absolute Unix timestamp after which token expires (0 = no time limit)
* @return true if passphrase was correct and DEK is now loaded
*/
bool unlockWithPassphrase(const uint8_t *passphrase, size_t passphraseLen,
uint8_t bootsRemaining = TOKEN_DEFAULT_BOOTS, uint32_t validUntilEpoch = 0);
/**
* Immediately lock: delete the unlock token and zero the DEK from RAM.
* The device will require the passphrase on the next boot (or connection).
*/
void lockNow();
/** Returns true if the DEK file exists (device has been provisioned). */
bool isProvisioned();
/** Returns true if the DEK is loaded in RAM (device is unlocked). */
bool isUnlocked();
/**
* Returns a short string describing why the device is locked (set during initLocked()).
* Useful for client-side diagnostics. Examples:
* "token_missing" — no unlock token file found
* "token_wrong_size" — token file exists but is corrupt
* "token_bad_magic" — wrong magic/version bytes
* "token_hmac_fail" — HMAC mismatch (tampered or wrong device)
* "token_boots_zero" — boot count exhausted
* "token_expired" — TTL expired
* "token_dek_fail" — DEK decrypt failed
* "not_provisioned" — no DEK file; needs first provisioning
* "ok" — unlocked successfully via token
*/
const char *getLockReason();
/** Boots remaining in the current unlock token (0 if not unlocked or last boot consumed). */
uint8_t getBootsRemaining();
/** Unix epoch at which the current unlock token expires (0 = no time limit or not unlocked). */
uint32_t getValidUntilEpoch();
/** Seconds remaining before next passphrase attempt is allowed (0 = can attempt now). */
uint32_t getBackoffSecondsRemaining();
// ---------------------------------------------------------------------------
// Encrypted file I/O (require isUnlocked())
// ---------------------------------------------------------------------------
/** Returns true if the file starts with the MENC magic bytes. */
bool isEncrypted(const char *filename);
/**
* Read and decrypt a file into outBuf.
* Returns true on success; sets outLen to the plaintext byte count.
*/
bool readAndDecrypt(const char *filename, uint8_t *outBuf, size_t outBufSize, size_t &outLen);
/**
* Encrypt plaintext and write to filename.
* Returns true on success.
*/
bool encryptAndWrite(const char *filename, const uint8_t *plaintext, size_t plaintextLen,
bool fullAtomic = false);
/**
* Migrate a plaintext proto file to encrypted format in-place.
* Returns true on success or if already encrypted.
*/
bool migrateFile(const char *filename);
// ---------------------------------------------------------------------------
// Legacy init (FICR-only KEK, no passphrase, no token)
// ---------------------------------------------------------------------------
/**
* Original init(): derives KEK from FICR only, loads or generates DEK.
* Retained for non-TAK builds and unit tests. Prefer initLocked() for TAK builds.
*/
bool init();
} // namespace EncryptedStorage
#endif // MESHTASTIC_ENCRYPTED_STORAGE
+5
View File
@@ -9,6 +9,7 @@
#include "MeshService.h"
#include "NodeDB.h"
#include "PowerMon.h"
#include "TransmitHistory.h"
#include "detect/LoRaRadioType.h"
#include "error.h"
#include "main.h"
@@ -245,6 +246,10 @@ void doDeepSleep(uint32_t msecToWake, bool skipPreflight = false, bool skipSaveN
nodeDB->saveToDisk();
}
// Persist broadcast transmit times so throttle survives reboot
if (transmitHistory)
transmitHistory->saveToDisk();
#ifdef PIN_POWER_EN
digitalWrite(PIN_POWER_EN, LOW);
pinMode(PIN_POWER_EN, INPUT); // power off peripherals
@@ -0,0 +1,19 @@
#include "TestUtil.h"
#include <unity.h>
static void test_placeholder()
{
TEST_ASSERT_TRUE(true);
}
extern "C" {
void setup()
{
initializeTestEnvironment();
UNITY_BEGIN();
RUN_TEST(test_placeholder);
exit(UNITY_END());
}
void loop() {}
}
+116
View File
@@ -0,0 +1,116 @@
#include "MeshModule.h"
#include "MeshTypes.h"
#include "TestUtil.h"
#include <unity.h>
// Minimal concrete subclass for testing the base class helper
class TestModule : public MeshModule
{
public:
TestModule() : MeshModule("TestModule") {}
virtual bool wantPacket(const meshtastic_MeshPacket *p) override { return true; }
using MeshModule::currentRequest;
using MeshModule::isMultiHopBroadcastRequest;
};
static TestModule *testModule;
static meshtastic_MeshPacket testPacket;
void setUp(void)
{
testModule = new TestModule();
memset(&testPacket, 0, sizeof(testPacket));
TestModule::currentRequest = &testPacket;
}
void tearDown(void)
{
TestModule::currentRequest = NULL;
delete testModule;
}
// Zero-hop broadcast (hop_limit == hop_start): should be allowed
static void test_zeroHopBroadcast_isAllowed()
{
testPacket.to = NODENUM_BROADCAST;
testPacket.hop_start = 3;
testPacket.hop_limit = 3; // Not yet relayed
TEST_ASSERT_FALSE(testModule->isMultiHopBroadcastRequest());
}
// Multi-hop broadcast (hop_limit < hop_start): should be blocked
static void test_multiHopBroadcast_isBlocked()
{
testPacket.to = NODENUM_BROADCAST;
testPacket.hop_start = 7;
testPacket.hop_limit = 4; // Already relayed 3 hops
TEST_ASSERT_TRUE(testModule->isMultiHopBroadcastRequest());
}
// Direct message (not broadcast): should always be allowed regardless of hops
static void test_directMessage_isAllowed()
{
testPacket.to = 0x12345678; // Specific node
testPacket.hop_start = 7;
testPacket.hop_limit = 4;
TEST_ASSERT_FALSE(testModule->isMultiHopBroadcastRequest());
}
// Broadcast with hop_limit == 0 (fully relayed): should be blocked
static void test_fullyRelayedBroadcast_isBlocked()
{
testPacket.to = NODENUM_BROADCAST;
testPacket.hop_start = 3;
testPacket.hop_limit = 0;
TEST_ASSERT_TRUE(testModule->isMultiHopBroadcastRequest());
}
// No current request: should not crash, should return false
static void test_noCurrentRequest_isAllowed()
{
TestModule::currentRequest = NULL;
TEST_ASSERT_FALSE(testModule->isMultiHopBroadcastRequest());
}
// Broadcast with hop_start == 0 (legacy or local): should be allowed
static void test_legacyPacket_zeroHopStart_isAllowed()
{
testPacket.to = NODENUM_BROADCAST;
testPacket.hop_start = 0;
testPacket.hop_limit = 0;
// hop_limit == hop_start, so not multi-hop
TEST_ASSERT_FALSE(testModule->isMultiHopBroadcastRequest());
}
// Single hop relayed broadcast (hop_limit = hop_start - 1): should be blocked
static void test_singleHopRelayedBroadcast_isBlocked()
{
testPacket.to = NODENUM_BROADCAST;
testPacket.hop_start = 3;
testPacket.hop_limit = 2;
TEST_ASSERT_TRUE(testModule->isMultiHopBroadcastRequest());
}
void setup()
{
initializeTestEnvironment();
UNITY_BEGIN();
RUN_TEST(test_zeroHopBroadcast_isAllowed);
RUN_TEST(test_multiHopBroadcast_isBlocked);
RUN_TEST(test_directMessage_isAllowed);
RUN_TEST(test_fullyRelayedBroadcast_isBlocked);
RUN_TEST(test_noCurrentRequest_isAllowed);
RUN_TEST(test_legacyPacket_zeroHopStart_isAllowed);
RUN_TEST(test_singleHopRelayedBroadcast_isBlocked);
exit(UNITY_END());
}
void loop() {}
+1 -1
View File
@@ -334,7 +334,7 @@ void setUp(void)
owner = meshtastic_User{.id = "!12345678"};
myNodeInfo = meshtastic_MyNodeInfo{.my_node_num = 0x12345678}; // Match the expected gateway ID in topic
localPosition =
meshtastic_Position{.has_latitude_i = true, .latitude_i = 7 * 1e7, .has_longitude_i = true, .longitude_i = 3 * 1e7};
meshtastic_Position{.has_latitude_i = true, .latitude_i = 700000000, .has_longitude_i = true, .longitude_i = 300000000};
router = mockRouter = new MockRouter();
service = mockMeshService = new MockMeshService();
+230
View File
@@ -0,0 +1,230 @@
#include "TestUtil.h"
#include "TransmitHistory.h"
#include <Throttle.h>
#include <unity.h>
// Reset the singleton between tests
static void resetTransmitHistory()
{
if (transmitHistory) {
delete transmitHistory;
transmitHistory = nullptr;
}
transmitHistory = TransmitHistory::getInstance();
}
void setUp(void)
{
resetTransmitHistory();
}
void tearDown(void) {}
static void test_setLastSentToMesh_stores_millis()
{
transmitHistory->setLastSentToMesh(meshtastic_PortNum_NODEINFO_APP);
uint32_t result = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
TEST_ASSERT_NOT_EQUAL(0, result);
// The stored millis value should be very close to current millis()
uint32_t diff = millis() - result;
TEST_ASSERT_LESS_OR_EQUAL(100, diff); // Within 100ms
}
static void test_set_overwrites_previous_value()
{
transmitHistory->setLastSentToMesh(meshtastic_PortNum_TELEMETRY_APP);
uint32_t first = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_TELEMETRY_APP);
testDelay(50);
transmitHistory->setLastSentToMesh(meshtastic_PortNum_TELEMETRY_APP);
uint32_t second = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_TELEMETRY_APP);
// The second value should be newer (larger millis)
TEST_ASSERT_GREATER_THAN(first, second);
}
// --- Throttle integration ---
static void test_throttle_blocks_within_interval()
{
transmitHistory->setLastSentToMesh(meshtastic_PortNum_NODEINFO_APP);
uint32_t lastMs = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
// Should be within a 10-minute interval (just set it)
bool withinInterval = Throttle::isWithinTimespanMs(lastMs, 10 * 60 * 1000);
TEST_ASSERT_TRUE(withinInterval);
}
static void test_throttle_allows_after_interval()
{
// Unknown key returns 0 — throttle should NOT block
uint32_t lastMs = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
TEST_ASSERT_EQUAL_UINT32(0, lastMs);
// When lastMs == 0, the module check `lastMs == 0 || !isWithinTimespan` allows sending
bool shouldSend = (lastMs == 0) || !Throttle::isWithinTimespanMs(lastMs, 10 * 60 * 1000);
TEST_ASSERT_TRUE(shouldSend);
}
static void test_throttle_blocks_after_set_then_zero_does_not()
{
// Set it — now throttle should block
transmitHistory->setLastSentToMesh(meshtastic_PortNum_TELEMETRY_APP);
uint32_t lastMs = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_TELEMETRY_APP);
bool shouldSend = (lastMs == 0) || !Throttle::isWithinTimespanMs(lastMs, 60 * 60 * 1000);
TEST_ASSERT_FALSE(shouldSend); // Should be blocked (within 1hr interval)
// Different key — should allow
uint32_t otherMs = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_POSITION_APP);
bool otherShouldSend = (otherMs == 0) || !Throttle::isWithinTimespanMs(otherMs, 60 * 60 * 1000);
TEST_ASSERT_TRUE(otherShouldSend);
}
// --- Multiple keys ---
static void test_multiple_keys_stored_independently()
{
transmitHistory->setLastSentToMesh(meshtastic_PortNum_NODEINFO_APP);
uint32_t nodeInfoInitial = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
testDelay(20);
transmitHistory->setLastSentToMesh(meshtastic_PortNum_POSITION_APP);
uint32_t positionInitial = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_POSITION_APP);
testDelay(20);
transmitHistory->setLastSentToMesh(meshtastic_PortNum_TELEMETRY_APP);
uint32_t nodeInfo = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
uint32_t position = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_POSITION_APP);
uint32_t telemetry = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_TELEMETRY_APP);
// All should be non-zero
TEST_ASSERT_NOT_EQUAL(0, nodeInfo);
TEST_ASSERT_NOT_EQUAL(0, position);
TEST_ASSERT_NOT_EQUAL(0, telemetry);
// Updating other keys should not overwrite earlier key timestamps
TEST_ASSERT_EQUAL_UINT32(nodeInfoInitial, nodeInfo);
TEST_ASSERT_EQUAL_UINT32(positionInitial, position);
}
// --- Singleton ---
static void test_getInstance_returns_same_instance()
{
TransmitHistory *a = TransmitHistory::getInstance();
TransmitHistory *b = TransmitHistory::getInstance();
TEST_ASSERT_EQUAL_PTR(a, b);
}
static void test_getInstance_creates_global()
{
if (transmitHistory) {
delete transmitHistory;
transmitHistory = nullptr;
}
TEST_ASSERT_NULL(transmitHistory);
TransmitHistory::getInstance();
TEST_ASSERT_NOT_NULL(transmitHistory);
}
// --- Persistence round-trip (loadFromDisk / saveToDisk) ---
static void test_save_and_load_round_trip()
{
// Set some values
transmitHistory->setLastSentToMesh(meshtastic_PortNum_NODEINFO_APP);
testDelay(10);
transmitHistory->setLastSentToMesh(meshtastic_PortNum_POSITION_APP);
uint32_t nodeInfoEpoch = transmitHistory->getLastSentToMeshEpoch(meshtastic_PortNum_NODEINFO_APP);
uint32_t positionEpoch = transmitHistory->getLastSentToMeshEpoch(meshtastic_PortNum_POSITION_APP);
// Force save
transmitHistory->saveToDisk();
// Reset and reload
delete transmitHistory;
transmitHistory = nullptr;
transmitHistory = TransmitHistory::getInstance();
transmitHistory->loadFromDisk();
// Epoch values should be restored (if RTC was available when set)
uint32_t restoredNodeInfo = transmitHistory->getLastSentToMeshEpoch(meshtastic_PortNum_NODEINFO_APP);
uint32_t restoredPosition = transmitHistory->getLastSentToMeshEpoch(meshtastic_PortNum_POSITION_APP);
TEST_ASSERT_EQUAL_UINT32(nodeInfoEpoch, restoredNodeInfo);
TEST_ASSERT_EQUAL_UINT32(positionEpoch, restoredPosition);
// After loadFromDisk, millis should be seeded (non-zero) for stored entries
uint32_t restoredMillis = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
if (restoredNodeInfo > 0) {
// If epoch was stored, millis should be seeded from load
TEST_ASSERT_NOT_EQUAL(0, restoredMillis);
}
}
// --- Boot without RTC scenario ---
static void test_load_seeds_millis_even_without_rtc()
{
// This tests the critical crash-reboot scenario:
// After loadFromDisk(), even if getTime() returns 0 (no RTC),
// lastMillis should be seeded so throttle blocks immediate re-broadcast.
transmitHistory->setLastSentToMesh(meshtastic_PortNum_NODEINFO_APP);
transmitHistory->saveToDisk();
// Simulate reboot: destroy and recreate
delete transmitHistory;
transmitHistory = nullptr;
transmitHistory = TransmitHistory::getInstance();
transmitHistory->loadFromDisk();
// The key insight: after load, getLastSentToMeshMillis should return non-zero
// because loadFromDisk seeds lastMillis[key] = millis() for every loaded entry.
// This ensures throttle works even without RTC.
uint32_t result = transmitHistory->getLastSentToMeshMillis(meshtastic_PortNum_NODEINFO_APP);
uint32_t epoch = transmitHistory->getLastSentToMeshEpoch(meshtastic_PortNum_NODEINFO_APP);
if (epoch > 0) {
// Data was persisted — millis must be seeded
TEST_ASSERT_NOT_EQUAL(0, result);
// And it should cause throttle to block (treating as "just sent")
bool withinInterval = Throttle::isWithinTimespanMs(result, 10 * 60 * 1000);
TEST_ASSERT_TRUE(withinInterval);
}
// If epoch == 0, RTC wasn't available — no data was saved, so nothing to restore.
// This is expected on platforms without RTC during the very first boot.
}
void setup()
{
initializeTestEnvironment();
UNITY_BEGIN();
RUN_TEST(test_setLastSentToMesh_stores_millis);
RUN_TEST(test_set_overwrites_previous_value);
RUN_TEST(test_throttle_blocks_within_interval);
RUN_TEST(test_throttle_allows_after_interval);
RUN_TEST(test_throttle_blocks_after_set_then_zero_does_not);
RUN_TEST(test_multiple_keys_stored_independently);
// Singleton
RUN_TEST(test_getInstance_returns_same_instance);
RUN_TEST(test_getInstance_creates_global);
// Persistence
RUN_TEST(test_save_and_load_round_trip);
RUN_TEST(test_load_seeds_millis_even_without_rtc);
exit(UNITY_END());
}
void loop() {}
+1 -1
View File
@@ -5,7 +5,7 @@ custom_esp32_kind =
custom_mtjson_part =
platform =
# renovate: datasource=custom.pio depName=platformio/espressif32 packageName=platformio/platform/espressif32
platformio/espressif32@6.12.0
platformio/espressif32@6.13.0
extra_scripts =
${env.extra_scripts}
@@ -31,7 +31,7 @@ build_flags =
lib_deps = ${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
# renovate: datasource=custom.pio depName=PCA9557-arduino packageName=maxpromer/library/PCA9557-arduino
maxpromer/PCA9557-arduino@1.0.0
# renovate: datasource=custom.pio depName=SensorLib packageName=lewisxhe/library/SensorLib
@@ -26,7 +26,7 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
[env:crowpanel-esp32s3-4-epaper]
extends = esp32s3_base
@@ -56,7 +56,7 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
[env:crowpanel-esp32s3-2-epaper]
extends = esp32s3_base
@@ -86,4 +86,4 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
@@ -29,7 +29,7 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
upload_speed = 115200
[env:heltec-vision-master-e213-inkhud]
@@ -32,7 +32,7 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
upload_speed = 115200
[env:heltec-vision-master-e290-inkhud]
@@ -20,5 +20,5 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-st7789 packageName=https://github.com/meshtastic/st7789 gitBranch=main
https://github.com/meshtastic/st7789/archive/bd33ea58ddfe4a5e4a66d53300ccbd38d66ac21f.zip
https://github.com/meshtastic/st7789/archive/9ee76d6b18b9a8f45a2c5cae06b1134a587691eb.zip
upload_speed = 921600
@@ -29,7 +29,7 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
upload_speed = 115200
[env:heltec-wireless-paper-inkhud]
@@ -26,5 +26,5 @@ build_flags =
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/a05c11c02862624266b61599b0d6ba93e33c6f24.zip
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
upload_speed = 115200
@@ -0,0 +1,26 @@
#ifndef Pins_Arduino_h
#define Pins_Arduino_h
#include <stdint.h>
#define USB_VID 0x303a
#define USB_PID 0x1001
// The default Wire will be mapped to PMU and RTC
static const uint8_t SDA = 18;
static const uint8_t SCL = 9;
// Default SPI will be mapped to Radio
static const uint8_t SS = -1;
static const uint8_t MOSI = 17;
static const uint8_t MISO = 6;
static const uint8_t SCK = 8;
#define SPI_MOSI (39)
#define SPI_SCK (41)
#define SPI_MISO (38)
#define SPI_CS (40)
#define SDCARD_CS SPI_CS
#endif /* Pins_Arduino_h */
@@ -0,0 +1,31 @@
[env:mini-epaper-s3]
;custom_meshtastic_hw_model =
custom_meshtastic_hw_model_slug = MINI_EPAPER_S3
custom_meshtastic_architecture = esp32-s3
custom_meshtastic_actively_supported = true
custom_meshtastic_support_level = 1
custom_meshtastic_display_name = LILYGO Mini ePaper S3 E-Ink
custom_meshtastic_images = mini-epaper-s3.svg
custom_meshtastic_tags = LilyGo
custom_meshtastic_requires_dfu = no
extends = esp32s3_base
board = mini-epaper-s3
board_check = true
upload_protocol = esptool
build_flags =
${esp32s3_base.build_flags}
-I variants/esp32s3/mini-epaper-s3
-DMINI_EPAPER_S3
-DUSE_EINK
-DEINK_DISPLAY_MODEL=GxEPD2_102
-DEINK_WIDTH=128
-DEINK_HEIGHT=80
lib_deps =
${esp32s3_base.lib_deps}
# renovate: datasource=git-refs depName=meshtastic-GxEPD2 packageName=https://github.com/meshtastic/GxEPD2 gitBranch=master
https://github.com/meshtastic/GxEPD2/archive/c7eb4c3c167cf396ef4f541cc5d4c6aa42f3c46b.zip
# renovate: datasource=custom.pio depName=SensorLib packageName=lewisxhe/library/SensorLib
lewisxhe/SensorLib@0.3.4

Some files were not shown because too many files have changed in this diff Show More