Compare commits

..
Author SHA1 Message Date
Scott Powell 3b8a67938f * NRF52BoardDCDC constructor chain fixes 2026-08-12 13:37:42 +10:00
ripplebizandGitHub e027263d1e Merge pull request #3154 from fdlamotte/nrf52_hwcrypto_init
nrf52: call nRFCrypto.begin()/end() only once
2026-08-12 12:14:21 +10:00
Huw DuddyandGitHub 34ad059afb Merge pull request #3170 from recrof/promicro-pin-tidy-up
[promicro] make pinmap more tidy, move the LoRa pins to variant.h
2026-08-11 18:43:20 +10:00
Rastislav Vysoky 5cce5cfe97 removed misleading 'GPIO' from pin numbers 2026-08-11 10:37:20 +02:00
ripplebizandGitHub fbef2ff0dc Merge pull request #3164 from weebl2000/fix-tbeam-s3-display
Fix display issues on T-beam Supreme S3
2026-08-11 14:39:39 +10:00
Rastislav Vysoky a82dc1b9da make promicro pinmap more tidy, move the LoRa pins to variant.h 2026-08-10 20:13:59 +02:00
Liam CottleandGitHub 9d8894e166 Merge pull request #3166 from recrof/debug-noise-floor-flag
move RadioLibWrapper noise_floor level message under special debug flag
2026-08-11 03:07:31 +12:00
Rastislav Vysoky 3138ad99ba move RadioLibWrapper noise_floor level message under special debug flag 2026-08-10 16:56:56 +02:00
Wessel Nieboer 32bd6d48d6 Fix T-beam Supreme S3 display 2026-08-10 13:39:16 +02:00
Huw DuddyandGitHub f6c25e6a25 Merge pull request #3158 from mepholic/bug/fix-rxgain-setting-post-agc-reset
Fix RX Boosted Gain setting after AGC reset is triggered
2026-08-10 17:31:38 +10:00
ripplebizandGitHub 9941669fd5 Merge pull request #3142 from oltaco/buildfix-userbtn
Build fix for R1 Neo and Minewsemi repeater
2026-08-10 13:30:24 +10:00
ripplebizandGitHub 0d60de6fa6 Merge pull request #3146 from oltaco/lr2021-preamble-and-irq-timeout
LR2021: add PREAMBLE_DETECTED bit and IRQ timeout logic
2026-08-10 13:29:12 +10:00
Dan Theisen 6f491f3033 RX Boosted Gain was set back to the compiled in value rather than the current/flash value set by the user when the ACG reset is triggered. This commit fixes this. 2026-08-09 18:11:35 -07:00
Florent ecb8c94560 nrf52: call nRFCrypto.begin()/end() only once 2026-08-09 14:46:23 -04:00
Huw DuddyandGitHub a1c50e15dd Merge pull request #3148 from recrof/add-missing-kiss-radio
add missing kiss radio roles, add kiss radio build to build.sh
2026-08-09 22:22:08 +10:00
Rastislav Vysoky c2d57f08c8 add missing kiss radio roles, add kiss radio build to build.sh 2026-08-09 14:17:18 +02:00
Huw DuddyandGitHub f310afb5e5 Merge pull request #3140 from entr0p1/fix/techo-lite-pins
Lilygo T-Echo Lite Pin Fixes
2026-08-09 22:06:21 +10:00
taco ce62c8b5d7 LR2021: add PREAMBLE_DETECTED bit and IRQ timeout logic 2026-08-09 21:41:22 +10:00
taco 39934d6999 minewsemi: build fix and platformio.ini tidy up
fixes minewsemi repeater failing build due to user_btn missing.
2026-08-09 18:33:27 +10:00
taco e8bbcd4580 R1 neo: remove stray lib_deps entry 2026-08-09 16:51:45 +10:00
taco b75a548d7f build fix for R1 Neo repeater
added missing declarations for user_btn and NullDisplayDriver
2026-08-09 16:50:44 +10:00
Scott Powell 727fc0512c Merge branch 'dev'
# Conflicts:
#	docs/payloads.md
2026-08-09 15:16:48 +10:00
Scott Powell 93b2db63de * version 1.17.0 2026-08-09 15:14:46 +10:00
entr0p1 5732b2edd8 Lilygo T-Echo Lite Pin Fixes
- Aligned to Lilygo's updated schematic and pin map as per https://github.com/Xinyuan-LilyGO/T-Echo-Lite/issues/14
2026-08-09 14:09:35 +10:00
ripplebizandGitHub 48df179e36 Merge pull request #3139 from oltaco/x1-flash
Add QSPIFlash support for Seeed MeshTracker X1
2026-08-09 13:52:56 +10:00
Huw DuddyandGitHub 58ebff82c0 Merge pull request #3125 from Hacuchino-hash/fix-x1-charge-status
Fix X1 charge status LED always showing charged
2026-08-09 12:54:29 +10:00
taco 9420195626 bump CustomLFS version for GD25Q64C support 2026-08-09 11:45:35 +10:00
taco 02ec123eb8 add QSPIFlash support for Seeed MeshTracker X1 2026-08-09 11:41:09 +10:00
Hacuchino-hash 2af4b3c14a Fix X1 charge status LED always showing charged 2026-08-07 08:08:08 -05:00
ripplebizandGitHub 47154f02cb Merge pull request #3122 from Hacuchino-hash/x1-notifications
Add RGB LED and haptic notifications for SenseCAP MeshTracker X1
2026-08-07 15:26:33 +10:00
Huw DuddyandGitHub 623422694b Merge pull request #3121 from liamcottle/config/disable-companion-cad
Disable CAD on Companion Firmware until it's configurable
2026-08-06 22:40:37 +10:00
Hacuchino-hash 335ebf546d Add SPA06 barometer telemetry and charge status LED for MeshTracker X1 2026-08-06 07:27:05 -05:00
Hacuchino-hash 3abe415cf7 Add RGB LED and haptic notifications for SenseCAP MeshTracker X1 2026-08-06 07:27:05 -05:00
liamcottle dee133d647 disable cad on companion until it's configurable 2026-08-07 00:19:18 +12:00
Liam CottleandGitHub 9b4a591ec4 Merge pull request #3120 from recrof/patch-2
ThinkNode M6: Remove QSPIFLASH=1 build flag to fix companion roles
2026-08-06 22:54:24 +12:00
Rastislav VysokyandGitHub e4fbd386af ThinkNode M6: Remove QSPIFLASH=1 build flag to fix companion roles
M6 doesn't have flash chip available, so companion roles fail to start.
2026-08-06 12:37:21 +02:00
ripplebizandGitHub f4ec1d48b1 Merge pull request #3112 from Hacuchino-hash/add-meshtracker-x1
Add support for Seeed SenseCAP MeshTracker X1 (LR2021)
2026-08-06 16:04:18 +10:00
Hacuchino-hash 3d6a891586 Add support for Seeed SenseCAP MeshTracker X1 (LR2021) 2026-08-05 05:50:21 -05:00
ripplebizandGitHub 84e3a67bd7 Merge pull request #3115 from oltaco/meshnology_w12
Add support for Meshnology W12 and LR2021 Wrapper
2026-08-05 15:04:00 +10:00
taco 9d4f93806d LR2021: auto-LDRO for side detectors 2026-08-05 14:23:32 +10:00
taco 36e77671a2 LR2021: fix for hardware cad and side detectors 2026-08-05 14:23:32 +10:00
taco 696a82d7c2 LR2021 multi-SF support (side detectors) 2026-08-05 14:23:32 +10:00
taco 7cc16366cb add Meshnology W12 support and LR2021 wrapper 2026-08-05 14:23:29 +10:00
Liam CottleandGitHub 8b9bee3bb7 Merge pull request #3107 from meshcore-dev/anon-req-fix
bounds check added for anon_req reply_path_len
2026-08-04 13:34:18 +12:00
fdlamotteandGitHub d6c2da98aa Merge pull request #2863 from benskigomez/fix/m6-gps-reset-pin
thinknode_m6: don't drive GPS REINIT pin so the L76K is detected
2026-08-03 21:16:59 -04:00
Scott Powell 0fd11ed223 * bounds check added for anon_req reply_path_len 2026-08-04 01:00:31 +10:00
Huw DuddyandGitHub 9d902e634a Merge pull request #3076 from MDamon/fix/lr1110-rx-timeout
LR1110: fix startReceive() passing an IRQ bit as the RX timeout 🤖🤖
2026-08-03 23:02:52 +10:00
Huw DuddyandGitHub 5d940a1dc9 Clean up comments in startReceive method
Removed unnecessary comments regarding RX timeout and IRQ mask.
2026-08-03 22:57:34 +10:00
Liam CottleandGitHub d6ee3a17f6 Merge pull request #3098 from jirogit/fix/unit-c6l-flash-mode-dio
fix: M5Stack Unit C6L boot failure caused by flash_mode=qio
2026-08-03 19:45:38 +12:00
ripplebizandGitHub 626a82fd30 Merge pull request #2824 from NickDunklee/rak-advert-hw-encryption
feat: use nrf52 hardware crypto where we can
2026-08-02 15:35:33 +10:00
me ae1b610a94 fix: M5Stack Unit C6L merged.bin fails to boot (flash_mode qio->dio)
Board manifest for esp32-c6-devkitm-1 defaults build.flash_mode to qio,
which this module's flash chip does not support -- causes a boot
crash-loop (repeated USB-Serial-JTAG reconnects) on real hardware.
Override with board_build.flash_mode = dio in the common M5Stack_Unit_C6L
section so it applies to all envs (ble/usb/repeater/room_server).
2026-08-01 22:20:20 -07:00
Mike Damon 78723d2565 LR1110: fix startReceive() passing an IRQ bit as the RX timeout
CustomLR1110::startReceive() passed RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED
(1<<4 = 16) as RadioLib's first argument, which is the RX *timeout*, not an
IRQ mask. At the LR11x0's 30.52us tick that armed the receiver for ~488us, so
it dropped out of RX before any packet could arrive and the node received
nothing at all -- while transmitting normally.

Symptoms on a SenseCAP T1000-E: tx_air_secs rising, rx_air_secs stuck at 0,
recv_errors 0, and the noise floor pinned at the -120 clamp because
getCurrentRSSI() never sampled a live receiver.

Pass RADIOLIB_LR11X0_RX_TIMEOUT_INF (continuous RX), which is what
LR11x0::startReceive() itself uses, keeping the PREAMBLE_DETECTED flag in the
reported IRQ flags as intended.

Introduced in ea5d7c8b ("LR1110: add PREAMBLE_DETECTED to reported irq flags").
Verified on two T1000-E units: with only the repeater fixed it began receiving
(last_rssi -29, SNR 17.0) while the unfixed companion stayed deaf; fixing both
brought up the link in each direction.
2026-07-30 12:14:39 -04:00
ripplebizandGitHub db232808aa Merge pull request #2688 from Che177/feature/room-server-system-posts
room_server: add room.post command for server-originated posts
2026-07-30 13:08:18 +10:00
ripplebizandGitHub 57ddada3ba Merge pull request #3004 from axhoff/agent/preserve-utf8-advert-names
Preserve UTF-8 boundaries in advert names
2026-07-30 12:59:59 +10:00
ripplebizandGitHub b797ca198e Merge pull request #3060 from entr0p1/fix/mesh-debug-active
Clean up debugs left on in platform.ini files
2026-07-30 12:35:22 +10:00
ripplebizandGitHub 6e39cff8a1 Merge pull request #3063 from oltaco/unify-irq-timeout
Unify IRQ timeout logic across all applicable radio types
2026-07-29 23:52:48 +10:00
ripplebizandGitHub 279ac78122 Merge pull request #3049 from liamcottle/feature/ethernet
Refactor Companion Interfaces + Add ThinkNode M7 Ethernet Support
2026-07-29 23:45:51 +10:00
taco 79eb7f5d8d LLCC68: add IRQ timeout logic 2026-07-29 23:34:01 +10:00
taco a3732e1c65 SX1268: add IRQ timeout logic 2026-07-29 23:34:01 +10:00
taco a5c323cc19 STM32WLx: add IRQ timeout logic 2026-07-29 23:33:51 +10:00
taco a7426de0bf LR1110: fix unnecessary IRQ clear 2026-07-29 23:18:15 +10:00
ripplebizandGitHub 9f73fbf870 Merge pull request #3062 from oltaco/fix-irq-clear
Fix unnecessary IRQ clearing
2026-07-29 22:37:30 +10:00
taco 20f55a4f42 fix unnecessary IRQ clear 2026-07-29 21:39:56 +10:00
entr0p1 d7f378b489 Clean up debugs left on in platform.ini files 2026-07-29 18:27:15 +10:00
Che177 5a04e060a5 room_server: use standard mesh debug logging 2026-07-28 21:57:42 -07:00
Liam CottleandGitHub 03b6ef4b0d Merge pull request #3047 from dg1tal/codex/docs-3044-group-privacy
Clarify hashtag privacy and group sender identity
2026-07-28 15:41:48 +12:00
Liam CottleandGitHub adc631f315 Merge pull request #3048 from entr0p1/fix/startota-failure-recovery
nRF52840 "start ota" Failure Recovery
2026-07-28 15:36:48 +12:00
Che177 3a9f19c14b room_server: add room.post system posts 2026-07-27 19:50:13 -07:00
entr0p1 4050b7d526 nRF52840 "start ota" Failure Recovery
If Bluefruit.begin fails, BLE OTA mode won't actually start and the board might require a reboot to reattempt.

Fixes:
- Bluefruit.begin returns false in NRF52Board.startOTAUpdate if OTA mode fails to start. User is notified of the fault through existing error message in CommonCLI and can reattempt "start ota" command.
2026-07-28 10:14:59 +10:00
DG1TAL 84ceabfd0d Clarify hashtag privacy and group sender identity 2026-07-27 20:07:08 +02:00
liamcottle dd778e2189 fix bluetooth toggle on ui tiny 2026-07-28 03:50:08 +12:00
liamcottle e7f2c71701 usb companion firmwares now require build flag to include usb interface 2026-07-28 03:45:02 +12:00
liamcottle 834ad722a4 remove old rak ethernet interface 2026-07-28 03:18:54 +12:00
liamcottle 203fd4e407 refactor rak13800 to new ethernet interface class 2026-07-28 03:18:54 +12:00
liamcottle e672679d6e refactored companion interfaces to allow for multiple active connection modes 2026-07-28 03:18:54 +12:00
liamcottle b4143a4402 rename class 2026-07-28 03:18:54 +12:00
liamcottle 5de857f8f8 initial ch390 ethernet support for thinknode m7 companion 2026-07-28 03:18:54 +12:00
ripplebizandGitHub c86e63d2f5 Merge pull request #2982 from meshcore-dev/config-serializer
Config serializer
2026-07-27 17:58:03 +10:00
ripplebizandGitHub 301bc10dd3 Merge pull request #3034 from meshcore-dev/ui-color-refactor
UI color refactor
2026-07-27 17:45:12 +10:00
Liam CottleandGitHub cee6d94894 Merge pull request #3040 from blowfishpro/docs/FixPayloadDocsFormatting
Increase header levels on "Payloads" documentation page to fix table of contents
2026-07-27 14:13:09 +12:00
Talia b62b421456 docs: increase header levels on payloads page to fix table of contents
mkdocs will only consider the first H1 (if any) and subheaders under it for the table of contents

this increases the header levels of everything below "important concepts" by 1 so that the table of contents correctly resolves them
2026-07-26 15:55:27 -07:00
ripplebizandGitHub e3de413a69 Merge pull request #3036 from oltaco/add-preamble-irq-flag
Fix missing PREAMBLE_DETECTED IRQ flag for all radio wrappers
2026-07-25 01:40:19 +10:00
taco 6b83de507d SX1268: add PREAMBLE_DETECTED to reported irq flags 2026-07-25 00:46:39 +10:00
taco 0d2b988f24 STM32WLx: add PREAMBLE_DETECTED to reported irq flags 2026-07-25 00:46:39 +10:00
taco c56928347f LLCC68: add PREAMBLE_DETECTED to reported irq flags 2026-07-25 00:46:39 +10:00
taco ea5d7c8bf5 LR1110: add PREAMBLE_DETECTED to reported irq flags 2026-07-25 00:46:36 +10:00
taco fae4803158 SX1262: add PREAMBLE_DETECTED to reported irq flags 2026-07-25 00:38:44 +10:00
Scott Powell f83ad03e5e * T114 display fix 2026-07-24 18:35:56 +10:00
Scott Powell 0c04a47355 * fixed for mono ST7789 display driver 2026-07-24 15:31:22 +10:00
Scott Powell 3857f45826 * monochrome displays now do _not_ invert titlebar 2026-07-24 15:14:56 +10:00
Scott Powell ee79df4c4f Merge branch 'dev' into config-serializer
# Conflicts:
#	test/mocks/Arduino.h
#	test/mocks/Stream.h
2026-07-24 15:06:48 +10:00
Liam CottleandGitHub e780cca237 Merge pull request #3033 from liamcottle/board/lilygo-tbeam-sx1276
Increase LilyGo T-Beam SX1276 channels from 8 to 40
2026-07-24 15:34:19 +12:00
liamcottle 520fa77f4f increase tbeam sx1276 max group channels from 8 to 40 2026-07-24 15:31:01 +12:00
Liam CottleandGitHub d531a98da1 Merge pull request #2819 from ViezeVingertjes/fix/kiss-modem-usb-backpressure
fix: prevent ESP32 KISS modem stalls under USB backpressure
2026-07-24 11:51:34 +12:00
Nick Dunklee 783b21bb9f Global nrf52 hardware crypto, removed from individual configs
Select nodes had this flag enabled, testing by the community
and hardware specs indicate this can be enabled global for all
node types using this chipset.

Any nodes down the line that may be quirky can be individually
disabled with `-U USE_CC310_HW_CRYPTO`.
2026-07-23 14:02:34 -06:00
Liam CottleandGitHub 8a69f34101 Merge pull request #3023 from agessaman/fix/rx-boosted-gain
fix(room_server): support RX boosted gain
2026-07-23 03:22:41 +12:00
Scott Powell 56274db4ad * build fixes for old ESP32 boards 2026-07-22 19:52:23 +10:00
Scott Powell a96a66aa99 * build fixes for NullDisplayDriver 2026-07-22 18:55:59 +10:00
Scott Powell b8504e55c6 * refactor of Color mapping in UITasks / DisplayDrivers
* color displays now with a new light theme
2026-07-22 16:03:33 +10:00
agessaman a71cc23854 fix(room_server): support RX boosted gain
The room server never supported RX boosted gain, while the repeater
does. Three consequences on SX1262/SX1268 boards:

- boosted gain was never applied to the radio at boot, so a room server
  ran in power-saving RX mode while an identical repeater ran boosted -
  a real receive-sensitivity difference with nothing pointing at it
- _prefs.rx_boosted_gain was never initialised (the prefs are memset to
  0 before defaults are set), so it defaulted to off
- 'set radio.rxgain on' replied "Error: unsupported" but CommonCLI had
  already written the value to prefs and saved them, so a stale setting
  survived reboot and was never applied

Mirror the repeater's implementation: initialise the pref default under
the same USE_SX1262/USE_SX1268 and SX126X_RX_BOOSTED_GAIN guards, apply
it during radio init, and override setRxBoostedGain() so the CLI reports
success and takes effect.

Built Heltec_v3_room_server (SX1262) and LilyGo_T3S3_sx1276_room_server
(guards compile out cleanly).
2026-07-21 12:23:20 -07:00
Scott Powell 78240e9477 * optimised: value-init not needed 2026-07-21 19:22:09 +10:00
ripplebizandGitHub 4157e43ace Merge pull request #3005 from axhoff/agent/fix-ble-reconnect
Fix bonded BLE reconnects on ESP32
2026-07-21 19:17:34 +10:00
ripplebizandGitHub 8b048ab19a Merge pull request #3007 from axhoff/agent/synchronize-ble-receive-queue
Synchronize the ESP32 BLE receive queue
2026-07-21 18:10:37 +10:00
ripplebizandGitHub 6a15e1712b Merge pull request #3006 from axhoff/agent/fix-heltec-v4-usb-companion
Enable hardware USB serial on Heltec V4
2026-07-21 17:54:22 +10:00
Liam CottleandGitHub 7124fa1439 Merge pull request #2815 from UltimateCodeWarrior/fix/tbeam-supreme-v3-oled-i2c
Fix blank OLED on T-Beam Supreme V3 (I2C bus init + 0x3D address)
2026-07-21 19:17:32 +12:00
Alexander Hoffer 4d4d7c3746 refactor: use FreeRTOS BLE receive queue 2026-07-21 07:17:01 +01:00
=UltimateCodeWarrior 0de2b4fc5f Move Supreme OLED address to variant config
Keep SH1106Display generic by relying on DISPLAY_ADDRESS while the T-Beam Supreme variant declares its 0x3D OLED address.
2026-07-20 19:24:38 -07:00
fdlamotteandGitHub d2fd1fdaa6 Merge pull request #2887 from spinda/thinknode-m3-dev
Fix GPS and LEDs on ThinkNode M3
2026-07-20 17:42:30 -04:00
NickDunkleeandGitHub 59e9a79eac Merge branch 'dev' into rak-advert-hw-encryption 2026-07-20 13:29:08 -06:00
fdlamotteandGitHub 427cd7c263 Merge pull request #2987 from entr0p1/fix/nrf52-shutdownperipherals
NRF52Board - ShutdownPeripherals() housekeeping
2026-07-20 11:53:56 -04:00
Alexander Hoffer 79dc1de6fc fix: preserve UTF-8 advert names 2026-07-20 15:47:03 +01:00
Alexander Hoffer 9fd6b419e5 fix: preserve bonded BLE reconnects 2026-07-20 15:47:03 +01:00
Alexander Hoffer 60030469c9 fix: enable Heltec V4 USB serial 2026-07-20 15:47:03 +01:00
Alexander Hoffer 3885c67c8e fix: synchronize BLE receive queue 2026-07-20 15:47:03 +01:00
Liam CottleandGitHub da67328017 Merge pull request #2990 from entr0p1/fix/xiao-nrf52-userbtn
Fix Xiao nRF52840 repeater compile failure
2026-07-21 02:09:33 +12:00
entr0p1 d2bbe4d8d3 Fix Xiao nRF52840 repeater compile failure
Compile fails due to user_btn not declared in board target.

Fixes:
- Add MomentaryButton declaration for user_btn in variants/xiao_nrf52/target.cpp
- Add momentary button helper include in variants/xiao_nrf52/target.h
- Add extern linkage for MomentaryButton -> user_btn in variants/xiao_nrf52/target.h
2026-07-20 22:43:25 +10:00
Liam CottleandGitHub a45dae928c Merge pull request #3000 from oltaco/rx-irq-timeout
fix: clear the correct IRQ flag for timeout on preamble detected on SX1262
2026-07-20 23:32:12 +12:00
taco ab5c45f516 fix: clear the correct IRQ flag for timeout on preamble detected 2026-07-20 21:05:12 +10:00
Liam CottleandGitHub c1ee9cad5b Merge pull request #2998 from oltaco/heltec-t1-bodmer
Fix: Heltec t1: add missing bodmer TFT_eSPI library
2026-07-20 22:39:17 +12:00
taco 91e65af9dd fix: heltec t1: add missing bodmer TFT_eSPI library 2026-07-20 20:28:38 +10:00
Liam CottleandGitHub 2834121b6e Merge pull request #2994 from oltaco/rx-irq-timeout
Add setter methods for preambleMillis and maxPayloadMillis on SX1262 and LR1110
2026-07-20 22:07:36 +12:00
taco 121b72712b LR1110: add setter methods for preambleMillis and payloadMillis 2026-07-20 19:52:57 +10:00
taco ae48072ff0 SX1262: add setter methods for preambleMillis and payloadMillis 2026-07-20 19:52:57 +10:00
Liam CottleandGitHub fdd4d8a610 Merge pull request #2989 from rgregg/fix-nrf52-ethernet-build
Fix nRF52 builds broken by unconditional RAK Ethernet include
2026-07-20 20:58:26 +12:00
liamcottle 8c987c8689 Merge remote-tracking branch 'official/main' into dev 2026-07-20 20:42:09 +12:00
ripplebizandGitHub dc7dd5105e Merge pull request #2977 from oltaco/rx-irq-timeout
Add IRQ timeout logic for SX1262 and LR1121
2026-07-20 14:14:02 +10:00
Ryan Gregg cc221330ba Fix nRF52 builds: guard SerialEthernetInterface with ETHERNET_ENABLED
SerialEthernetInterface.cpp is compiled for every nRF52 target because
PlatformIO builds all .cpp files under src/. It includes
SerialEthernetInterface.h, which unconditionally pulls in
<RAK13800_W5100S.h> -- a library only present in the RAK4631 Ethernet
env's lib_deps. As a result any other nRF52 board (e.g. Heltec T114)
fails to build with 'RAK13800_W5100S.h: No such file or directory'.

Wrap the contents of both files in '#ifdef ETHERNET_ENABLED' so they
compile to empty translation units on non-Ethernet builds. RAK4631
Ethernet envs define ETHERNET_ENABLED and are unaffected.

Fixes #2985
2026-07-19 10:17:08 -07:00
entr0p1 aee53a8c3e NRF52Board - ShutdownPeripherals() housekeeping
Improvements:
- Add condition to only turn off display if on (avoids wedging the shutdown on some displays)
- Reset LoRa radio before calling radio_driver.powerOff() to ensure it is in a known good state (and will accept the command)
- Ensure SPI is started so LoRa radio commands can be sent (some shutdowns can happen before this)
- Add gate for P_LORA_NSS pin defined before writing to the pin
2026-07-19 23:59:12 +10:00
taco b28bf00348 fix: setMaxPacketMillis() should return void 2026-07-19 22:06:36 +10:00
Liam CottleandGitHub a3a1aa5e3b Merge pull request #1865 from MeshEnvy/fix/python-json-parse-error
fix: JSON parsing regression in build.sh
2026-07-19 22:58:21 +12:00
ViezeVingertjesandAdam Gessaman 3b69e7873b fix: guard HWCDC serial config behind ARDUINO_USB_MODE
setTxTimeoutMs() and setTxBufferSize() are HWCDC-only APIs; calling
them on HardwareSerial (UART-bridge boards like T-Beam) fails to compile.

Co-Authored-By: Adam Gessaman <adam@gessaman.com>
2026-07-18 22:43:55 +02:00
ViezeVingertjes 39ff5b879a fix: run KISS modem unit tests in CI via native_kiss_modem env
The new test_kiss_modem suite needs KissModem headers and sources that
only native_kiss_modem provides. Scope native to test_utils and run both
envs in the unit test workflow.
2026-07-18 22:43:55 +02:00
ViezeVingertjes fb2c61f862 fix: prevent ESP32 KISS modem stalls under USB backpressure
Switch ESP32-S3 KISS modem environments to HWCDC and move outbound KISS writes to a non-blocking queued frame path so loop() and TX completion keep progressing when the host reads slowly. Add native backpressure regression tests and correct the native_kiss_modem test filter so this suite runs directly with pio test.
2026-07-18 22:43:55 +02:00
Scott Powell a0b52be4ad * RP2040 build fixes
* new prefs file now "/prefs.json"
2026-07-18 20:12:21 +10:00
Scott Powell 2189f2294c * added prefs initialisers to match original zeroed state 2026-07-18 19:22:53 +10:00
ripplebizandGitHub 795989b918 Merge pull request #2966 from Quency-D/heltec-rc32
Add Heltec rc32 board
2026-07-17 23:23:29 +10:00
fdlamotteandGitHub 4aec46b039 Merge pull request #2976 from fdlamotte/UITask_poweroff_radio_display
UI task: poweroff of radio and display moved to board
2026-07-17 08:35:06 -04:00
Florent c644720ea7 uitask: screen and radio poweroff moved to board 2026-07-17 08:29:31 -04:00
fdlamotteandGitHub 8f5a393404 Merge pull request #2975 from fdlamotte/nrf52_boards--use-shutdownPeripherals-on-TInpulse-and-TEchoBoard
nrf52_variants: override shutdownPeripherals instead of powerOff for …
2026-07-17 08:12:35 -04:00
taco 0bd871cde6 add IRQ timeout logic for LR11X0 2026-07-17 21:45:31 +10:00
Florent 84d1e24338 nrf52_variants: override shutdownPeripherals instead of powerOff for TechoLite, TInpulse and TechoBoard (protect the gate) 2026-07-17 07:36:39 -04:00
taco 79ef74ea8d add IRQ timeout logic for SX1262 2026-07-17 21:33:57 +10:00
Scott Powell d9f1e12b21 * loadSerial(), support for \n and \r 2026-07-17 21:23:40 +10:00
fdlamotteandGitHub 3a67685597 Merge pull request #2883 from fdlamotte/repeater_btn
repeater: poweroff on long press
2026-07-17 07:18:44 -04:00
taco 975a673efd add calcMaxPacketMillis 2026-07-17 21:15:09 +10:00
Scott Powell ae2667ee9e * added unit tests for ConfigSerializer 2026-07-17 20:55:30 +10:00
fdlamotteandGitHub 76c6e73fb6 Merge branch 'dev' into repeater_btn 2026-07-17 06:55:19 -04:00
fdlamotteandGitHub 3eb5451d3e Merge pull request #2906 from fdlamotte/shutdown_peripherals
Proposal: Introduce shutdownPeripherals in NRF52Board to prepare for shutdown
2026-07-17 06:53:00 -04:00
Quency-D fd7b35f457 Move the rotation input to target.cpp 2026-07-17 15:50:25 +08:00
Quency-D b26f53a263 Avoid waking display from rotary input 2026-07-17 15:35:07 +08:00
Scott Powell f515716032 * new NodePrefs for companion 2026-07-17 16:05:10 +10:00
ripplebizandGitHub 41f4d6bd91 Merge pull request #2560 from Quency-D/heltec-v4-r8
Add heltec-v4-r8 board
2026-07-17 13:54:45 +10:00
Nick Dunklee 874f0c9ff8 Minor ifdef rename as it now covers more than just Ed25519
for hardware encryption. Now `USE_CC310_HW_CRYPTO`
2026-07-16 21:44:35 -06:00
Quency-D 61a8821d3c Optimize battery voltage reading 2026-07-16 17:45:00 +08:00
Scott Powell 85285c6cbc Merge branch 'dev' into config-serializer 2026-07-16 17:22:28 +10:00
Quency-D a472cd7956 Delete duplicate pin definitions 2026-07-16 15:14:17 +08:00
Quency-D 3469e92458 Enable patch reception 2026-07-16 11:37:12 +08:00
Quency-D 05d4bd2f7f Add a rotary encoder 2026-07-15 17:45:24 +08:00
ripplebizandGitHub b55d69e57a Merge pull request #1983 from rgregg/rak-ethernet
Support for RAK ethernet module
2026-07-15 18:53:38 +10:00
Liam CottleandGitHub 1831349e5a Merge pull request #2897 from yarda/companion-add-mcu-temp-sensor
Added MCU temp sensor to the companion
2026-07-15 20:11:24 +12:00
Quency-DandGitHub 6c9f0907ee Merge pull request #17 from meshcore-dev/dev
merge Dev
2026-07-15 14:49:40 +08:00
Liam CottleandGitHub f44aede4f3 Merge pull request #2954 from liamcottle/board/thinknode-m7-neighbours
Increase ThinkNode M7 MAX_NEIGHBORS to 50
2026-07-15 16:06:58 +12:00
liamcottle a99f4a0160 increase thinknode m7 max neighbours to 50 2026-07-15 16:05:37 +12:00
Scott Powell 5a14f36e25 * ST7735 color/offset fix for Heltec Tracker V1 2026-07-15 14:00:10 +10:00
Scott Powell 63f4b173da * misc fixes 2026-07-15 13:21:44 +10:00
Jaroslav Škarvada 15e259c572 Added MCU temp sensor to the companion
Fixes #2896
2026-07-14 17:43:33 +02:00
Scott Powell 2af1e6d099 * first draft of new ConfigSerializer. (simple embedded JSON prefs) 2026-07-15 01:23:57 +10:00
Liam CottleandGitHub ea4383f90c Merge pull request #2952 from Quency-D/fix-ex-watchdog
fix  repeater watchdog
2026-07-15 02:54:58 +12:00
Nick Dunklee a9d2574039 feat: add more crypto
After soaking for a bit on the adverts without issue on multiple nodes,
I added more hardware crypto.

Supported nodes is unchanged in this PR addition, but if others can verify,
they can easily be added.

Some info on the CC310: https://docs.nordicsemi.com/r/bundle/ps_nrf9151/page/cryptocell.html

**Added:**

- AES-128 packet encryption/decryption now use hardware crypto
- HMAC-SHA-256 authentication now uses hardware crypto
- ACK hash computation and channel ID derivation now use hardware crypto
- RNG (random number generator) now uses hardware crypto rather than
  radio noise + weak software RNG (which can have issues if there's
  no surrounding radio noise.) NIST SP 800-90B certified.
  - Runs hardware self-tests on startup
  - Runs continuous health tests during operation
  - Uses thermal noise/shot noise for randomness

**Unchanged:**

- calcSharedSecret remains software - it would be a split hw/sw solution
  and added complexity for likely not a lot of gains. This only happens
  when establishing a new contact, so not too frequent to be worth it.
- ed25519_create_keypair remains software. This is only called when a
  node is first initialized. It does use the hardware RNG change, however,
  so better randomization.

Tested on (so far):

- Heltec t096

Build test on:
- Heltec t096 companion ble
- t1000e companion ble
- RAK 4631 repeater
- RAK 3401 companion BLE
- Heltec v3 companion wifi
2026-07-14 08:35:27 -06:00
Nick Dunklee 8c033a50cd Merge remote-tracking branch 'upstream/dev' into rak-advert-hw-encryption 2026-07-14 08:22:12 -06:00
Quency-D 4d0ba1516c Remove the watchdog feeding operation from each iteration of the loop to reduce power consumption. 2026-07-14 17:23:13 +08:00
Ryan Gregg 16b76bd35a Merge remote-tracking branch 'upstream/dev' into rak-ethernet
# Conflicts:
#	examples/companion_radio/main.cpp
2026-07-13 23:06:00 -07:00
Huw DuddyandGitHub 64e8e24720 Merge pull request #2951 from meshcore-dev/fast-st7735-display
Fast ST7735 Display Driver
2026-07-14 16:01:14 +10:00
ripplebizandGitHub 05fdafbb2d Merge pull request #2898 from entr0p1/fix/lilygo-techo-lite-sx1262-ldo
Lilygo T-Echo Lite - Change SX1262 from DC-DC to LDO regulator
2026-07-14 14:53:44 +10:00
ripplebizandGitHub f4ed8c711b Merge pull request #2899 from entr0p1/fix/lilygo-techo-lite-nrf-dcdc
Lilygo T-Echo Lite - nRF52840 DC-DC
2026-07-14 14:52:56 +10:00
ripplebizandGitHub dc0f837451 Merge pull request #2905 from entr0p1/fix/heltec-t114-nrf-dcdc
Heltec T114 - nRF52840 DC-DC Regulator
2026-07-14 14:52:10 +10:00
ripplebizandGitHub 7f4f03d737 Merge pull request #2946 from hpux735/stream-allocation
Add StreamSensor allocation for GroupData
2026-07-14 14:47:57 +10:00
Will Dillon 7e95c52972 Add StreamSensor allocation for GroupData
Adds a small allocation for groupdata packets for the Meshcore firmware for the StreamSensor product. It was previously a LoRaWAN platform, and we've moved to Meshcore.

Let me know when and how to demonstrate.
2026-07-13 05:54:31 -07:00
ripplebizandGitHub 219812b9f1 Merge pull request #2943 from meshcore-dev/revert-2915-main
Revert "Add StreamSensor allocation for GroupData"
2026-07-13 19:31:05 +10:00
ripplebizandGitHub d9cd3ea03a Revert "Add StreamSensor allocation for GroupData" 2026-07-13 19:30:11 +10:00
ripplebizandGitHub a517f9c24f Merge pull request #2915 from hpux735/main
Add StreamSensor allocation for GroupData
2026-07-13 18:42:54 +10:00
ripplebizandGitHub b81fb8ebe8 Merge pull request #2917 from jirogit/fix/regionmap-load-eof-handling
fix(RegionMap): load() returns actual read success instead of hardcoded true
2026-07-13 18:28:26 +10:00
ripplebizandGitHub 174bcdfbcc Merge pull request #2942 from liamcottle/board/thinknode-m9
Add support for Elecrow ThinkNode M9
2026-07-13 17:10:54 +10:00
liamcottle 87bf371cd3 initial support for thinknode m9 2026-07-13 19:07:09 +12:00
ripplebizandGitHub 4f12dc02d5 Merge pull request #2937 from benskigomez/fix/gps-timesync-millis-overflow
sensors: fix millis() rollover that stalls GPS time-sync on long-uptime nodes
2026-07-13 17:06:09 +10:00
Liam CottleandGitHub 1c5a8426e8 Merge pull request #2839 from liamcottle/board/thinknode-m7
Add support for Elecrow ThinkNode M7
2026-07-13 15:06:17 +12:00
Liam CottleandGitHub 6bd66d7dc8 Merge pull request #2940 from liamcottle/upgrade/radiolib
Update RadioLib to v7.7.1-6d893483
2026-07-13 15:03:29 +12:00
Liam CottleandGitHub e01a2565b9 Merge pull request #2936 from beala/beala/MeshTowerV2_feed_watchdog_2
Feed external hardware watchdog on Heltec Tower V2 (aka MeshTower V2) Implementation 2
2026-07-13 14:49:04 +12:00
liamcottle 17b6662aa5 update radiolib to v7.7.1-6d893483 2026-07-13 14:39:54 +12:00
Liam CottleandGitHub 55f43e52e2 Merge pull request #2935 from benskigomez/fix/m6-repeater-debug-flags
ThinkNode M6 repeater: disable leftover MESH_DEBUG/GPS_NMEA_DEBUG
2026-07-13 12:55:13 +12:00
Liam CottleandGitHub 8e0c9a241b Merge pull request #2938 from benskigomez/fix/room-server-default-password
ThinkNode M6/M1 room_server: set ROOM_PASSWORD default
2026-07-13 12:54:16 +12:00
Jody Bentley 1429d75f57 ThinkNode M6/M1 room_server: set ROOM_PASSWORD default
Without ROOM_PASSWORD the guest password defaults to empty, and a client
sending a blank password is granted read+write access (can post). Every
other board's room_server env sets ROOM_PASSWORD; the ThinkNode M6 and M1
were the only two shipping an open room. Default them to "hello" to match
the rest of the tree; operators can still change it at runtime with
'set guest.password'.
2026-07-12 18:32:09 -04:00
Jody Bentley 63731d3fbf sensors: fix millis() rollover stall in GPS time-sync + minor cleanups
next_check and next_gps_update stored a future millis() value in a signed
long and compared with a naive '>'. After the ~24.8-day millis() sign flip
the deadline sits above the wrapped millis(), so the block never runs again
and GPS->RTC time-sync (and the location cache refresh) stall permanently
until reboot. Switch to unsigned deadlines with the wrap-safe signed-
difference compare '(long)(millis() - deadline) > 0', matching the idiom in
Dispatcher::millisHasNowPassed.

Also: reorder the MicroNMEALocationProvider ctor init-list to declaration
order (silences -Wreorder) and drop the always-true 'if (_claims > 0)' guard
in claim() (claim() always runs after _claims++, so it is >= 1).
2026-07-12 18:30:40 -04:00
Alex Beal eb97a375d3 Add an instance of ExternalWatchdogManager to Tower V2 2026-07-12 16:17:23 -06:00
Jody Bentley 6343d8d96e ThinkNode M6 repeater: disable leftover MESH_DEBUG/GPS_NMEA_DEBUG
The M6 is the only board whose simple_repeater env ships with MESH_DEBUG=1
and GPS_NMEA_DEBUG=1 enabled. MESH_DEBUG=1 adds a 5-second boot delay
(examples/simple_repeater/main.cpp) plus verbose per-packet serial prints on
the hot RX/TX path; GPS_NMEA_DEBUG=1 echoes every GPS UART character to the
serial console (MicroNMEALocationProvider.h). Every sibling repeater env
(M1, M3, t1000-e, RAK, Heltec) ships these off, and the M6 room_server env
in this same file already has them commented. Comment them out to match.
2026-07-12 17:54:14 -04:00
Alex Beal 47e1ce5bae Update #defines
External watchdog support was added (but never merged) for MeshTower V1. The update's V2's #defines to follow the conventions set there and piggy back off the support already written for V1.
2026-07-12 15:50:43 -06:00
Alex Beal 07b543176b Merge branch 'dev' into pr-1446 2026-07-12 15:44:28 -06:00
jirogit 8ef369058d fix(RegionMap): distinguish clean EOF from partial read in load()
Previously load() returned true unconditionally on file-open success,
masking truncated or corrupt /regions2 files. Additionally, the first
field of each entry record (r->id) used the same success-chaining
pattern as subsequent fields, so a clean EOF at a record boundary set
success=false and would have been indistinguishable from real
corruption once the return value was fixed.

The r->id read is now split out: n==0 is a clean EOF (break, success
retains its prior value from the header read), n!=sizeof(r->id) is a
partial read or corruption (break, success=false). load() now returns
success instead of an unconditional true, so its return value reflects
the actual parse outcome.

Companion fix to #2372, which fixed the same return-true hardcoding
in save(). (#1891 originally reported this on load() but was closed
when #2372 landed — that PR only touched save(); this addresses the
load() side.)
2026-07-09 19:59:05 -07:00
Liam CottleandGitHub 102f1d2a47 Merge pull request #2913 from weebl2000/fix-typos
fix misspelled RF switch pin macros in SX1268/LLCC68/SX1276 radio wrappers
2026-07-10 12:26:28 +12:00
Will DillonandGitHub 754fcb1fae Update number_allocations.md
Adds a small allocation for groupdata packets for the Meshcore firmware for the StreamSensor product.  It was previously a LoRaWAN platform, and we've moved to Meshcore.
2026-07-09 11:43:20 -07:00
Wessel Nieboer 4605d3b6ce fix misspelled RF switch pin macros in SX1268/LLCC68/SX1276 radio wrappers 2026-07-09 16:31:28 +02:00
Quency-D 17d68e328f Add heltec rc32 board 2026-07-08 16:20:12 +08:00
Quency-DandGitHub 10d2d2a1c7 Merge pull request #16 from meshcore-dev/dev
merge Dev
2026-07-08 15:15:19 +08:00
Florent 369016acc9 introduce shutdownPeripherals in NRF52Board to prepare for shutdown 2026-07-07 10:20:03 -04:00
entr0p1 7f8522a362 Heltec T114 - nRF52840 DC-DC Regulator
- Enable DC-DC regulator on nRF52840 for Heltec T114 board (idle current reduced from ~12mA to ~9mA)
2026-07-07 17:12:59 +10:00
Liam CottleandGitHub bbb58cceb8 Merge pull request #2903 from liamcottle/ci/build-matrix
Refactor builds via GitHub Actions to be super fast
2026-07-07 14:31:28 +12:00
liamcottle 54234b5837 implement matrix builds for faster firmware releases 2026-07-07 13:23:18 +12:00
Florent fec88e1300 fix tenstar c3 repeater build 2026-07-06 12:04:42 -04:00
Florent 3ee2f77877 restore display and radio poweroff in ui 2026-07-06 08:46:57 -04:00
Florent 2efb3af69b repeater: poweroff on long press 2026-07-06 08:40:56 -04:00
fdlamotteandGitHub 9e66a2e246 Merge pull request #2895 from IoTThinks/MCdev-Fixed-poweroff-to-uA-202607
Fixed hibernate / poweroff for BLE companions and repeaters to stay at uA
2026-07-06 08:02:23 -04:00
entr0p1 4fafcd0e23 Lilygo T-Echo Lite
- Enable nRF52840 DC-DC - board idle usage reduced from ~12mA to ~7mA
2026-07-06 15:21:09 +10:00
entr0p1 584f9e909b Lilygo T-Echo Lite
- Change SX1262 to use LDO instead of DC-DC (DCC pin on SX1262 not wired in, according to schematic)
2026-07-06 14:52:18 +10:00
Kevin Le 35f654ced3 Fixed hibernate/powerOff for ESP32 boards to stay at uA 2026-07-05 23:47:27 +07:00
Kevin Le 6b205da4e9 Added missing driver/rtc_io.h 2026-07-05 23:33:56 +07:00
Kevin Le eec75eab31 Cleanup Poweroff for NRF52 boards 2026-07-05 22:10:47 +07:00
Kevin Le 7d7de88707 board->powerOff() is sufficient to power off radio, display, GPS and components 2026-07-05 21:22:13 +07:00
Kevin Le 73b7367e45 Put powerOff to NRF52Board 2026-07-05 21:20:39 +07:00
Kevin Le a92046b0eb Put powerOff and enterDeepSleep to ESP32Board 2026-07-05 21:20:13 +07:00
liamcottle 57563ab8f9 update qr code docs 2026-07-06 02:04:56 +12:00
Quency-DandGitHub 2867542cfa Merge branch 'dev' into solar-watchdog 2026-07-04 16:47:37 +08:00
Naomi Smith 3af5ffe119 Fix GPS and LEDs on ThinkNode M3
GPS support was implemented incorrectly for the ThinkNode M3. The reset
pin was being driven when it should be left floating for this unit. The
enable pin also wasn't being picked up by `MicroNMEALocationProvider`
because of a mismatch in constant naming conventions. I did a general
cleanup of the GPS and ThinkNode M3 bring-up code so that constant names
line up and "*_ACTIVE" constants are used consistently vs hardcoding
`HIGH`/`LOW`. After making these changes, serial data immediately starts
streaming in from the NMEA on boot and GPS detection just works.

LED handling was also not quite right for the ThinkNode M3. The LoRa TX
LED was being driven high to turn it on when it should actually be
driven low. I changed the code to use the `LED_STATE_ON` constant and
also added a little code to the shutdown path to properly make sure that
all LEDs are turned off.

Tested and confirmed working on real hardware.

Resolves both #1864 and #2879.
2026-07-03 12:07:19 -07:00
Jody Bentley 5c534c4399 thinknode_m6: don't drive GPS REINIT pin (fixes GPS never detected)
The M6's L76K GPS streams NMEA at 9600 baud on its own, but the firmware
reported no GPS. Root cause: pin 29 (PIN_GPS_RESET / the module's REINIT
line) was driven HIGH, which holds the L76K silent so it never emits any
sentences and detection fails.

variant.cpp drove pin 29 HIGH at boot, and because PIN_GPS_RESET was
defined, MicroNMEALocationProvider also drove it HIGH in begin(). Bench
testing on a sealed M6 (passive NMEA capture, no logic analyzer) confirmed:
pin 29 driven HIGH = 0 bytes; pin 29 floating = full NMEA stream.

Define GPS_RESET (-1) so the location provider never touches pin 29, and
stop driving it in initVariant. This matches the Meshtastic M6 variant,
which leaves the same pin as a floating input.
2026-06-29 14:49:11 -04:00
Quency-DandGitHub 341aa5e0f4 Merge pull request #14 from meshcore-dev/dev
merge Dev
2026-06-26 17:16:23 +08:00
liamcottle b975180fc8 initial support for elecrow thinknode m7 2026-06-25 16:03:27 +12:00
Nick Dunklee 7a2764ebd6 Added Heltec t096 and seeed t1000-e
Tested Heltec t096 and Seeed t1000-e, both support this
hardware feature.
2026-06-24 15:58:09 -06:00
Nick Dunklee 4ac8742ce0 feat: use RAK hardware crypto on advert processing
While working on some sensor code implementations, I ran into
some hard crashes that root-caused to the 4KB loop task stack
being exhausted.

Looking for various optimization schemes resulted in this relatively
low-lift fix. RAK3401 and RAK4631 both support hardware crypto.

Rather than loading in one of the two software crypto libs,
we can just use the onboard hardware. This is faster, should
consume less power, and in testing used a scant up to 700
bytes in the run loop vs 2.5-3KB per advert.

This change **only** affects advert verification processing, which
currently consumes a significant chunk of the 4KB run loop.

I figured such a change should likely be implemented in phases.

After soaking, this hardware crypto verification
process could be implemented across the entire MeshCore
cryptographic function on RAK nodes. Also possible other nodes
have available hardware crypto, however, I have not checked,
so future improvements may also exist there.

Tested on:
  - RAK3401 RAK 1W
  - RAK4631 19001
2026-06-23 11:39:20 -06:00
UltimateCodeWarriorand=UltimateCodeWarrior b8b6598dd3 Fix blank OLED on T-Beam Supreme V3 (I2C bus + 0x3D address)
The SH1106 OLED on the LilyGo T-Beam Supreme V3 never lights up because:

1. The primary I2C bus (Wire) that the OLED, BME280 and magnetometer share
   is never initialized. The PMU/RTC use Wire1 (via XPowersLib); nothing
   brings up Wire on PIN_BOARD_SDA/PIN_BOARD_SCL, so the display driver
   talks on the wrong default pins.
2. The OLED is at I2C address 0x3D on this board (0x3C is taken by the
   QMC6310 magnetometer), but SH1106Display::begin() only tried 0x3C.

Initialize Wire for TBEAM_SUPREME_SX1262, and have SH1106Display::begin()
prefer 0x3D (only ever used by the OLED) before falling back to 0x3C.
Backwards-compatible for boards with the OLED at 0x3C.

Closes #2609
2026-06-22 23:39:34 -07:00
Ryan Gregg a206f3e066 Merge remote-tracking branch 'upstream/dev' into rak-ethernet
# Conflicts:
#	docs/faq.md
#	examples/companion_radio/main.cpp
2026-06-20 14:39:03 -07:00
Liam CottleandGitHub e8d3c53ba1 Merge pull request #2753 from formtapez/cli-docs
Added some missing CLI commands
2026-06-13 00:17:36 +12:00
formtapez d3444e6b0b fix formatting 2026-06-12 12:14:46 +02:00
formtapez 06130dce29 added some missing CLI commands 2026-06-12 12:11:12 +02:00
Liam CottleandGitHub 55ad7689d5 Merge pull request #2748 from liamcottle/github/stale-bot
Configure GitHub Stale Bot
2026-06-12 03:24:26 +12:00
liamcottle 3b39925399 use single quotes for repo name 2026-06-12 03:20:44 +12:00
liamcottle c94ed29ca3 add github workflow to close stale issues 2026-06-12 03:18:10 +12:00
Liam CottleandGitHub 5a342c7a20 Merge pull request #2691 from NoodlesNZ/security-policy
Add Github Security policy
2026-06-11 19:25:53 +12:00
Nick Le Mouton dea5ed790f Add SECURITY.md 2026-06-05 21:25:25 +12:00
Quency-DandGitHub 8ed7be971a Merge pull request #11 from meshcore-dev/dev
merge Dev
2026-05-27 15:43:22 +08:00
Quency-D e5a3839d64 Optimize ADC readout 2026-05-27 15:12:59 +08:00
Ryan Gregg 40bd7d511b Fix companion disconnect on inbound packet; use server.accept()
EthernetServer::available() returns any socket with data, including the
already-connected client's socket. The companion path then called stop()
on what it thought was a duplicate client, closing the shared socket and
disconnecting the companion after the first packet.

Switch both SerialEthernetInterface and EthernetCLI to server.accept(),
which only returns newly-accepted sockets. Removes the IP/port duplicate
detection in the companion path (no longer reachable) and the same-socket
early-return in the CLI path.

Reported by mcode6726 on PR #1983.
2026-05-18 21:04:09 +00:00
Ryan Gregg 87bed4946c Merge remote-tracking branch 'upstream/dev' into rak-ethernet
# Conflicts:
#	examples/companion_radio/main.cpp
2026-05-18 20:57:28 +00:00
Quency-D 1ac5f359ca Added touch reset 2026-05-16 10:59:02 +08:00
Quency-D c183050935 Add heltec -v4-r8 board 2026-05-15 16:53:18 +08:00
Quency-DandGitHub ec9fe67afe Merge branch 'dev' into solar-watchdog 2026-05-09 18:08:32 +08:00
Quency-D 363ac44461 Fix external watchdog timing around sleep 2026-04-27 15:32:02 +08:00
Quency-DandGitHub 7e0d9f6f39 Merge pull request #10 from meshcore-dev/dev
merge Dev
2026-04-27 14:48:26 +08:00
Ryan Gregg a3354db521 Address PR review feedback from oltaco
- Remove extra blank line in companion_radio main.cpp before NRF52/STM32 block
- Revert unintended STM32_PLATFORM ETHERNET_ENABLED branch (no STM32 ethernet target exists, and it incorrectly included nrf52 headers)
- Drop renovate annotations from rak4631 platformio.ini (no renovate config in this repo)
2026-04-26 20:22:35 +00:00
Ryan Gregg 2a2c7a171d Merge remote-tracking branch 'upstream/dev' into rak-ethernet
# Conflicts:
#	docs/faq.md
2026-04-20 15:06:09 +00:00
Ryan Gregg 0ffe1c2cb9 bug fix: ethernet cli dropping connection after each command 2026-03-21 19:28:44 -07:00
Ryan Gregg 3c1a0941aa Fix POE boot failure on RAK4631 Ethernet builds
Drive WB_IO2 (slot power switch) HIGH via early constructor before the
Arduino framework initializes. Without this, the board brownouts on
POE-only power because the slot MOSFET isn't enabled early enough for
the RAK13800 POE module to deliver power to the baseboard.

Also remove the W5100S hardware reset pulse from Ethernet init — the
chip comes out of power-on reset cleanly, and toggling reset kills
the PHY link which breaks POE power delivery.
2026-03-20 17:56:04 -07:00
Ryan GreggandClaude Opus 4.6 eba2446747 Merge upstream/dev into rak-ethernet
Resolve conflicts: keep both Ethernet CLI and SenseCAP power-off
button code in repeater, keep both Ethernet docs and power management
CLI docs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 11:07:09 -07:00
Ryan GreggandClaude Opus 4.6 88892de864 Fix Ethernet init checking hardwareStatus before begin() and deduplicate CLI code
The Ethernet retry loop in repeater and room server checked
hardwareStatus() and linkStatus() before calling Ethernet.begin(),
which always returned EthernetNoHardware since hardware detection
only happens during begin(). Extract shared Ethernet CLI code into
EthernetCLI.h to prevent future divergence. Also fix time_t type
mismatch in companion radio Ethernet init.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:48:42 -07:00
Ryan GreggandClaude Sonnet 4.6 61ba79966b Address PR review feedback from liamcottle (second round)
- Rename eth command to eth.status for consistency with other commands
- Rename generateDeviceMac to generateEthernetMac for clarity
- Refactor ethernet_handle_command to return false by default
- Allow new TCP clients to replace existing connections (repeater, room server, SerialEthernetInterface)
- Boot companion radio without Ethernet on init failure (LoRa-only recovery mode)
- Remove > prompt from ethernet CLI for consistency with serial interface
- Fix variable redeclaration compile error in SerialEthernetInterface when ETHERNET_STATIC_IP is defined
- Fix TCP socket leak when duplicate client detection fires
- Remove dead recv_queue and adv_restart_time members from SerialEthernetInterface
- Fix port numbers in docs (port 23 for repeater/room server CLI, port 5000 for companion radio)
- Clarify eth.status command is only available in repeater and room server firmware

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 12:43:08 -07:00
Ryan Gregg 3e9ceba24a Updates based on PR review feedback from liamcottle 2026-03-10 22:35:31 -07:00
Ryan GreggandClaude Opus 4.6 ffe0853d7f Add Ethernet documentation for RAK4631 ETH support
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:58:34 -07:00
Ryan GreggandClaude Opus 4.6 aea64e1f19 Address PR review feedback for Ethernet support
- Add #pragma once to SerialEthernetInterface.h
- Rename TCP_PORT to ETH_TCP_PORT with #ifndef guard
- Fix typos: "initalizing" → "initializing"
- Fix #elif without condition → #else for STM32 block
- Replace infinite loop on ETH init failure with halt()
- Remove heartbeat Serial.print(".") output
- Remove dead beginETH() call (ETH_ENABLED, not RAK_ETH_ENABLE)
- Comment out MESH_DEBUG and ETH_DEBUG_LOGGING build flags

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:43:59 -07:00
Ryan GreggandClaude Opus 4.6 70b51bd096 Add native Ethernet support for RAK4631 repeater, room server, and companion
Add W5100S Ethernet adapter support for RAK4631-based firmware, enabling
TCP CLI access on port 23 as an alternative to BLE/Serial connections.

- New SerialEthernetInterface for nRF52 with DHCP, reconnection handling,
  and shared WB_IO2 power pin management with GPS module
- Ethernet build targets for repeater, room server, and companion firmware
- Prevent GPS from toggling WB_IO2 when Ethernet module is active
- CI build check for all three ETH firmware targets

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:43:59 -07:00
Quency-DandGitHub f9b830b5ea Merge pull request #4 from weebl2000/solar-watchdog
Address review comments
2026-03-04 11:11:08 +08:00
Wessel Nieboer 1ab8a6f6da Address review comments 2026-03-04 03:13:53 +01:00
Ben Allfree 9844b541b6 fix: JSON parsing regression in build 2026-02-26 20:37:27 -08:00
Quency-D 53ff4ed57f Fix watchdog code in repeater 2026-02-09 11:43:41 +08:00
Quency-DandGitHub 9df34e09d0 Merge branch 'dev' into solar-watchdog 2026-02-09 10:15:50 +08:00
Quency-DandGitHub 9f38835543 Merge pull request #1 from meshcore-dev/dev
Merge dev branch
2026-01-22 15:06:44 +08:00
Quency-D c89a0e9929 Add an external watchdog module 2026-01-22 15:03:40 +08:00
342 changed files with 9907 additions and 1633 deletions
@@ -25,5 +25,14 @@ runs:
- name: Extract Version from Git Tag
shell: bash
run: |
GIT_TAG_NAME="${GITHUB_REF#refs/tags/}"
echo "GIT_TAG_VERSION=${GIT_TAG_NAME##*-}" >> $GITHUB_ENV
if [[ "${GITHUB_REF}" == refs/tags/* ]]; then
# triggered by a tag push (e.g: refs/tags/companion-v1.2.3)
GIT_TAG_NAME="${GITHUB_REF#refs/tags/}"
VERSION_STRING="${GIT_TAG_NAME##*-}"
else
# triggered by a workflow dispatch (e.g: refs/heads/main)
# strip "refs/heads/" prefix and replace any remaining "/" with "-" to protect file paths
BRANCH_NAME="${GITHUB_REF#refs/heads/}"
VERSION_STRING=$(echo "$BRANCH_NAME" | tr '/' '-')
fi
echo "GIT_TAG_VERSION=${VERSION_STRING}" >> $GITHUB_ENV
@@ -10,33 +10,8 @@ on:
- 'companion-*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Clone Repo
uses: actions/checkout@v6
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Build Firmwares
env:
FIRMWARE_VERSION: ${{ env.GIT_TAG_VERSION }}
run: /usr/bin/env bash build.sh build-companion-firmwares
- name: Upload Workflow Artifacts
uses: actions/upload-artifact@v7
with:
name: companion-firmwares
path: out
- name: Create Release
uses: softprops/action-gh-release@v3
if: startsWith(github.ref, 'refs/tags/')
with:
name: Companion Firmware ${{ env.GIT_TAG_VERSION }}
body: ""
draft: true
files: out/*
build-companion-firmwares:
uses: ./.github/workflows/firmware-builder.yml
with:
firmware_type: 'companion'
release_title_prefix: 'Companion Firmware'
+5 -30
View File
@@ -10,33 +10,8 @@ on:
- 'repeater-*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Clone Repo
uses: actions/checkout@v6
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Build Firmwares
env:
FIRMWARE_VERSION: ${{ env.GIT_TAG_VERSION }}
run: /usr/bin/env bash build.sh build-repeater-firmwares
- name: Upload Workflow Artifacts
uses: actions/upload-artifact@v7
with:
name: repeater-firmwares
path: out
- name: Create Release
uses: softprops/action-gh-release@v3
if: startsWith(github.ref, 'refs/tags/')
with:
name: Repeater Firmware ${{ env.GIT_TAG_VERSION }}
body: ""
draft: true
files: out/*
build-repeater-firmwares:
uses: ./.github/workflows/firmware-builder.yml
with:
firmware_type: 'repeater'
release_title_prefix: 'Repeater Firmware'
@@ -10,33 +10,8 @@ on:
- 'room-server-*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Clone Repo
uses: actions/checkout@v6
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Build Firmwares
env:
FIRMWARE_VERSION: ${{ env.GIT_TAG_VERSION }}
run: /usr/bin/env bash build.sh build-room-server-firmwares
- name: Upload Workflow Artifacts
uses: actions/upload-artifact@v7
with:
name: room-server-firmwares
path: out
- name: Create Release
uses: softprops/action-gh-release@v3
if: startsWith(github.ref, 'refs/tags/')
with:
name: Room Server Firmware ${{ env.GIT_TAG_VERSION }}
body: ""
draft: true
files: out/*
build-room-server-firmwares:
uses: ./.github/workflows/firmware-builder.yml
with:
firmware_type: 'room-server'
release_title_prefix: 'Room Server Firmware'
+90
View File
@@ -0,0 +1,90 @@
name: Firmware Builder
on:
workflow_call:
inputs:
firmware_type:
required: true
type: string
release_title_prefix:
required: true
type: string
jobs:
generate-build-matrix:
runs-on: ubuntu-latest
outputs:
targets: ${{ steps.get-build-targets.outputs.targets }}
steps:
- name: Clone Repo
uses: actions/checkout@v6
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Get Build Targets
id: get-build-targets
run: |
# get list of firmwares to build
TARGET_LIST=$(/usr/bin/env bash build.sh get-${{ inputs.firmware_type }}-firmwares-to-build)
# convert targets separated by new line into a json array string
JSON_ARRAY=$(echo "$TARGET_LIST" | jq -R -s -c 'split("\n") | map(select(length > 0))')
# use json array as targets result
echo "targets=$JSON_ARRAY" >> $GITHUB_OUTPUT
build:
needs: generate-build-matrix
runs-on: ubuntu-latest
continue-on-error: true # don't fail entire build if one board fails to build
strategy:
matrix:
target: ${{ fromJson(needs.generate-build-matrix.outputs.targets) }}
fail-fast: false # don't cancel other builds if one board fails to build
steps:
- name: Clone Repo
uses: actions/checkout@v6
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Build Firmware
env:
FIRMWARE_VERSION: ${{ env.GIT_TAG_VERSION }}
run: /usr/bin/env bash build.sh build-firmware ${{ matrix.target }}
- name: Upload Workflow Artifacts
uses: actions/upload-artifact@v7
with:
name: "${{ matrix.target }}"
path: out
create-release:
needs: build
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/') # only create release for tagged builds
steps:
- name: Clone Repo
uses: actions/checkout@v6
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Download All Artifacts
uses: actions/download-artifact@v8
with:
merge-multiple: true
path: out
- name: Create Release
uses: softprops/action-gh-release@v3
with:
name: "${{ inputs.release_title_prefix }} ${{ env.GIT_TAG_VERSION }}"
body: ""
draft: true
files: out/*
+3
View File
@@ -31,8 +31,11 @@ jobs:
- Heltec_v3_room_server
# nRF52
- RAK_4631_companion_radio_ble
- RAK_4631_companion_radio_ethernet
- RAK_4631_repeater
- RAK_4631_repeater_ethernet
- RAK_4631_room_server
- RAK_4631_room_server_ethernet
# RP2040
- PicoW_repeater
# STM32
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
uses: ./.github/actions/setup-build-environment
- name: Run Unit Tests
run: pio test -e native -vv
run: pio test -e native -e native_kiss_modem -vv
- name: Upload Test Results
# Upload test results even if the test step failed.
+32
View File
@@ -0,0 +1,32 @@
name: 'Run Stale Bot'
on:
schedule:
- cron: '30 1 * * *' # daily at 1:30am
workflow_dispatch: {}
permissions:
actions: write
issues: write
pull-requests: write
jobs:
close-issues:
# only run on main repo, not forks
if: github.repository == 'meshcore-dev/MeshCore'
runs-on: ubuntu-latest
steps:
- name: Close Stale Issues
uses: actions/stale@v10
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
# auto close issues
days-before-issue-stale: 60
days-before-issue-close: 7
exempt-issue-labels: "keep-open"
stale-issue-label: "stale"
stale-issue-message: "This issue is stale because it has been open for 60 days with no activity. Remove the stale label or add a comment if this issue is still relevant, otherwise this issue will automatically close in 7 days."
close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
# don't auto close prs
days-before-pr-stale: -1
days-before-pr-close: -1
+57
View File
@@ -0,0 +1,57 @@
# Security Policy
## Supported Versions
Security fixes are applied to the latest release only. We do not backport
fixes to older versions.
| Version | Supported |
|---------|-----------|
| 1.15+ | ✅ |
| <1.15 | ❌ |
## Reporting a Vulnerability
**Please do not report security vulnerabilities through public GitHub issues.**
Use GitHub's private vulnerability reporting instead:
1. Go to the **Security** tab of this repository
2. Click **Report a vulnerability**
3. Fill in the details and submit
### What to include
A useful report tells us:
- Which component or file is affected
- What an attacker can do (impact) and under what conditions
- A minimal reproduction case or proof-of-concept if you have one
- Whether you believe it is remotely exploitable
You do not need a working exploit to report. An incomplete report is better
than no report.
## What to expect
This is a volunteer-maintained open-source project. We will do our best to
respond in a reasonable timeframe, but cannot commit to specific deadlines.
We ask that you give us a fair opportunity to investigate and address the
issue before any public disclosure. If you have not heard back after
**90 days**, feel free to follow up or proceed with disclosure at your
discretion.
## Scope
In scope:
- Remote code execution, memory corruption, or denial-of-service via crafted
radio packets
- Authentication or encryption bypasses
- Vulnerabilities in the packet routing or path handling logic
Out of scope:
- Physical access attacks (e.g., JTAG, UART extraction of keys)
- Regulatory compliance (duty cycle, frequency restrictions)
- Jamming or other physical-layer radio interference
- Issues in third-party libraries (RadioLib, Crypto, etc.) — report those
upstream
- "Best practice" suggestions without a demonstrated attack path
+43
View File
@@ -0,0 +1,43 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"partitions": "default_16MB.csv",
"memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_USB_CDC_ON_BOOT=1",
"-DARDUINO_USB_MODE=1",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"psram_type": "opi",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "heltec_rc32"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "Heltec RC32 (16 MB FLASH, 8 MB PSRAM)",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"use_1200bps_touch": true,
"wait_for_upload_port": true,
"require_upload_port": true,
"speed": 921600
},
"url": "https://heltec.org/",
"vendor": "Heltec"
}
+2 -2
View File
@@ -9,7 +9,7 @@
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_USB_CDC_ON_BOOT=1",
"-DARDUINO_USB_MODE=0",
"-DARDUINO_USB_MODE=1",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=1"
],
@@ -40,4 +40,4 @@
},
"url": "https://heltec.org/",
"vendor": "heltec"
}
}
+43
View File
@@ -0,0 +1,43 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"partitions": "default_16MB.csv",
"memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_USB_CDC_ON_BOOT=1",
"-DARDUINO_USB_MODE=1",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"psram_type": "opi",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "heltec_v4_r8"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "heltec_wifi_lora_32 v4 r8 (16 MB FLASH, 8 MB PSRAM)",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"use_1200bps_touch": true,
"wait_for_upload_port": true,
"require_upload_port": true,
"speed": 921600
},
"url": "https://heltec.org/",
"vendor": "heltec"
}
+43
View File
@@ -0,0 +1,43 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"partitions": "default_16MB.csv",
"memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_USB_CDC_ON_BOOT=1",
"-DARDUINO_USB_MODE=1",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"psram_type": "opi",
"hwids": [["0x303A", "0x0002"], ["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "meshnology_w12"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "heltec_wifi_lora_32 v5 (16 MB FLASH, 8 MB PSRAM)",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"use_1200bps_touch": true,
"wait_for_upload_port": true,
"require_upload_port": true,
"speed": 921600
},
"url": "https://heltec.org/",
"vendor": "heltec"
}
+60
View File
@@ -0,0 +1,60 @@
{
"build": {
"arduino": {
"ldscript": "nrf52840_s140_v7.ld"
},
"core": "nRF5",
"cpu": "cortex-m4",
"extra_flags": "-DARDUINO_WIO_WM1110 -DNRF52840_XXAA",
"f_cpu": "64000000L",
"hwids": [
["0x239A", "0x8029"],
["0x239A", "0x0029"],
["0x239A", "0x002A"],
["0x239A", "0x802A"],
["0x2886", "0x0057"]
],
"usb_product": "X1-BOOT",
"mcu": "nrf52840",
"variant": "Seeed_Mesh-Tracker-X1",
"bsp": {
"name": "adafruit"
},
"softdevice": {
"sd_flags": "-DS140",
"sd_name": "s140",
"sd_version": "7.3.0",
"sd_fwid": "0x0123"
},
"bootloader": {
"settings_addr": "0xFF000"
}
},
"connectivity": ["bluetooth"],
"debug": {
"jlink_device": "nRF52840_xxAA",
"svd_path": "nrf52840.svd",
"openocd_target": "nrf52.cfg"
},
"frameworks": ["arduino"],
"name": "Seeed SenseCAP MeshTracker X1",
"upload": {
"maximum_ram_size": 248832,
"maximum_size": 815104,
"speed": 115200,
"protocol": "nrfutil",
"protocols": [
"jlink",
"nrfjprog",
"nrfutil",
"stlink",
"cmsis-dap",
"blackmagic"
],
"use_1200bps_touch": true,
"require_upload_port": true,
"wait_for_upload_port": true
},
"url": "https://www.seeedstudio.com/SenseCAP-MeshTracker-X1-for-Meshtastic-p-6793.html",
"vendor": "Seeed Studio"
}
+42
View File
@@ -0,0 +1,42 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
"-D BOARD_HAS_PSRAM",
"-D ARDUINO_USB_CDC_ON_BOOT=0",
"-D ARDUINO_USB_MODE=0",
"-D ARDUINO_RUNNING_CORE=1",
"-D ARDUINO_EVENT_RUNNING_CORE=0"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"psram_type": "qio_opi",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "ELECROW-ThinkNode-M7"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "ELECROW ThinkNode M7",
"upload": {
"flash_size": "8MB",
"maximum_ram_size": 524288,
"maximum_size": 8388608,
"use_1200bps_touch": true,
"wait_for_upload_port": true,
"require_upload_port": true,
"speed": 921600
},
"url": "https://www.elecrow.com",
"vendor": "ELECROW"
}
+57
View File
@@ -0,0 +1,57 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"memory_type": "qio_opi",
"partitions": "default_16MB.csv"
},
"core": "esp32",
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_USB_CDC_ON_BOOT=0",
"-DARDUINO_USB_MODE=0",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=0"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"psram_type": "qio_opi",
"hwids": [
[
"0x303A",
"0x1001"
]
],
"mcu": "esp32s3",
"variant": "ELECROW-ThinkNode-M9"
},
"connectivity": [
"wifi",
"bluetooth",
"lora"
],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": [
"esp-builtin"
],
"openocd_target": "esp32s3.cfg"
},
"frameworks": [
"arduino",
"espidf"
],
"name": "elecrow-thinknode-m9",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 524288,
"maximum_size": 16777216,
"use_1200bps_touch": true,
"wait_for_upload_port": true,
"require_upload_port": true,
"speed": 921600
},
"url": "https://www.elecrow.com/thinknode-m1-meshtastic-lora-signal-transceiver-powered-by-nrf52840-with-154-screen-support-gps.html",
"vendor": "ELECROW"
}
+27 -1
View File
@@ -1,5 +1,8 @@
#!/usr/bin/env bash
# exit when any command fails
set -e
global_usage() {
cat - <<EOF
Usage:
@@ -31,6 +34,9 @@ $ sh build.sh build-repeater-firmwares
Build all chat room server firmwares
$ sh build.sh build-room-server-firmwares
Build all kiss radio firmwares
$ sh build.sh build-kiss-radio-firmwares
Environment Variables:
DISABLE_DEBUG=1: Disables all debug logging flags (MESH_DEBUG, MESH_PACKET_LOGGING, etc.)
If not set, debug flags from variant platformio.ini files are used.
@@ -93,7 +99,7 @@ get_pio_envs_ending_with_string() {
# $1 should be the environment name
get_platform_for_env() {
local env_name=$1
echo "$PIO_CONFIG_JSON" | python3 -c "
printf '%s' "$PIO_CONFIG_JSON" | python3 -c "
import sys, json, re
data = json.load(sys.stdin)
for section, options in data:
@@ -239,6 +245,17 @@ build_room_server_firmwares() {
}
build_kiss_modem_firmwares() {
# # build specific kiss radio firmwares
# build_firmware "Heltec_v3_kiss_modem"
# build_firmware "RAK_4631_kiss_modem"
# build all room server firmwares
build_all_firmwares_by_suffix "_kiss_modem"
}
build_firmwares() {
build_companion_firmwares
build_repeater_firmwares
@@ -275,4 +292,13 @@ elif [[ $1 == "build-repeater-firmwares" ]]; then
build_repeater_firmwares
elif [[ $1 == "build-room-server-firmwares" ]]; then
build_room_server_firmwares
elif [[ $1 == "build-kiss-radio-firmwares" ]]; then
build_kiss_modem_firmwares
elif [[ $1 == "get-companion-firmwares-to-build" ]]; then
get_pio_envs_ending_with_string "_companion_radio_usb"
get_pio_envs_ending_with_string "_companion_radio_ble"
elif [[ $1 == "get-repeater-firmwares-to-build" ]]; then
get_pio_envs_ending_with_string "_repeater"
elif [[ $1 == "get-room-server-firmwares-to-build" ]]; then
get_pio_envs_ending_with_string "_room_server"
fi
+49 -2
View File
@@ -19,6 +19,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore
- [GPS](#gps-when-gps-support-is-compiled-in)
- [Sensors](#sensors-when-sensor-support-is-compiled-in)
- [Bridge](#bridge-when-bridge-support-is-compiled-in)
- [Ethernet](#ethernet-when-ethernet-support-is-compiled-in)
---
@@ -28,12 +29,25 @@ This document provides an overview of CLI commands that can be sent to MeshCore
**Usage:**
- `reboot`
**Note:** No reply is sent.
---
### Power-off the node
**Usage:**
- `poweroff`, or
- `shutdown`
**Note:** No reply is sent.
---
### Reset the clock and reboot
**Usage:**
- `clkreboot`
**Note:** No reply is sent.
---
### Sync the clock with the remote device
@@ -291,7 +305,7 @@ This document provides an overview of CLI commands that can be sent to MeshCore
**Default:** Varies by board
**Note:** Max length varies. If a location is set, the max length is 24 bytes; 32 otherwise. Emoji and unicode characters may take more than one byte.
**Note:** Advertised names can use up to 23 bytes when location is included and 31 bytes otherwise. Emoji and Unicode characters may take more than one byte. Names that exceed the available advert space are truncated at a valid UTF-8 code point boundary.
---
@@ -660,10 +674,21 @@ This document provides an overview of CLI commands that can be sent to MeshCore
**Parameters:**
- `value`: Maximum flood hop count (0-64) for a packet without a scope (no region set)
**Default:** `0xFF` - indicates it hasn't been set, will track flood.max until it is.
**Default:** `64` - (`0xFF` indicates it hasn't been set, will track flood.max until it is.)
**Note:** An alternative to `region denyf *`, setting `flood.max.unscoped` to a lower value such as `3` would allow for local unscoped messages to propagate, while preventing noisy neighbors from flooding a local region.
---
#### Limit the number of hops for an advert flood message
**Usage:**
- `get flood.max.advert`
- `set flood.max.advert <value>`
**Parameters:**
- `value`: Maximum flood hop count (0-64) for an advert packet
**Default:** `8`
---
@@ -1128,3 +1153,25 @@ region save
**Note:** Returns an error on boards without power management support.
---
### Ethernet (when Ethernet support is compiled in)
Ethernet support is available on RAK4631 boards with a RAK13800 (W5100S) Ethernet module. Use the `_ethernet` firmware variants (e.g. `RAK_4631_repeater_ethernet`) to enable this feature.
---
#### View Ethernet connection status
**Usage:**
- `eth.status`
**Output:**
- `ETH: <ip>:<port>` when connected (e.g. `ETH: 192.168.1.50:23`)
- `ETH: not connected` when Ethernet is not active
**Notes:**
- Available on repeater and room server firmware only. Companion radio ethernet firmware does not expose a CLI.
- The Ethernet interface obtains an IP address via DHCP automatically on boot.
- A TCP server listens on port 23 (default) for CLI connections.
- Connect with any TCP client (e.g. `nc`, PuTTY) to access the same CLI available over serial.
---
+2
View File
@@ -440,6 +440,8 @@ Byte 0: 0x14
- Uses a secret key derived from the channel name
- It is the first 16 bytes of `sha256("#test")`
- For example hashtag channel `#test` has the key: `9cd8fcf22a47333b591d96a2b848b73f`
- Traffic is encrypted on air, but anyone who knows or guesses the channel
name can derive the key. Hashtag channels should not be treated as private.
- Used as a topic based public group chat, separate from the default public channel
3. **Private Channels**
- Uses a randomly generated 16-byte secret key
+27
View File
@@ -83,6 +83,7 @@ A list of frequently-asked questions and answers for MeshCore
- [7.5. Q: What is the format of a contact or channel QR code?](#75-q-what-is-the-format-of-a-contact-or-channel-qr-code)
- [7.6. Q: How do I connect to the companion via Wi-Fi, e.g. using a Heltec V3?](#76-q-how-do-i-connect-to-the-companion-via-wi-fi-eg-using-a-heltec-v3)
- [7.7. Q: I have a Station G2, or a Heltec V4, or an Ikoka Stick, or a radio with an EByte E22-900M30S or an EByte E22-900M33S module, what should their transmit power be set to?](#77-q-i-have-a-station-g2-or-a-heltec-v4-or-an-ikoka-stick-or-a-radio-with-an-ebyte-e22-900m30s-or-an-ebyte-e22-900m33s-module-what-should-their-transmit-power-be-set-to)
- [7.8. Q: How do I use Ethernet with a RAK4631?](#78-q-how-do-i-use-ethernet-with-a-rak4631)
## 1. Introduction
@@ -820,3 +821,29 @@ For companion radios, you can set these radios' transmit power in the smartphone
| **Ikoka Stick E22-900M33S** | 2W Model | 9 dBm | 2W | **DO NOT EXCEED** (Risk of burn out) [data sheet](https://www.cdebyte.com/pdf-down.aspx?id=4216) Refer to your local government's requirements |
| **Heltec V4** | Standard Output | 10 dBm | 22 dBm (~0.15W) | |
| | High Output | 22 dBm | 28 dBm (~0.5W to 0.6W) | |
---
### 7.8. Q: How do I use Ethernet with a RAK4631?
**A:**
MeshCore supports Ethernet on RAK4631 boards using the [RAK13800](https://docs.rakwireless.com/product-categories/wisblock/rak13800/datasheet/) WisBlock Ethernet module (based on the W5100S chip).
**Hardware required:**
- RAK4631 WisBlock Core
- RAK19007 or RAK19018 WisBlock Base Board (with an available IO slot)
- RAK13800 WisBlock Ethernet module
- Ethernet cable connected to a network with a DHCP server
**Firmware:**
Flash one of the Ethernet-enabled firmware variants:
- `RAK_4631_repeater_ethernet` - Repeater with Ethernet CLI access
- `RAK_4631_room_server_ethernet` - Room server with Ethernet CLI access
- `RAK_4631_companion_radio_ethernet` - Companion radio over Ethernet (replaces BLE)
**Connecting:**
- The device obtains an IP address via DHCP automatically on boot.
- For repeaters and room servers, connect to the device on TCP port 23 using any TCP client (e.g. `nc <ip> 23` or PuTTY in raw mode). This gives you the same CLI available over serial/USB.
- For companion radio firmware, the Ethernet interface replaces BLE as the transport to companion apps. Connect on TCP port 5000 (same as the WiFi companion radio).
- Use the `eth.status` CLI command to check connection status and see the assigned IP address.
---
+10 -4
View File
@@ -41,7 +41,7 @@ Maximum unescaped frame size: 512 bytes.
| Command | Value | Data | Description |
|-------------|--------|--------------------|-------------------------------------------------------------|
| Data | `0x00` | Raw packet | Queue packet for transmission |
| Data | `0x00` | Raw packet | Queue packet for transmission (one pending at a time) |
| TXDELAY | `0x01` | Delay (1 byte) | Transmitter keyup delay in 10ms units (default: 50 = 500ms) |
| Persistence | `0x02` | P (1 byte) | CSMA persistence parameter 0-255 (default: 63) |
| SlotTime | `0x03` | Interval (1 byte) | CSMA slot interval in 10ms units (default: 10 = 100ms) |
@@ -58,6 +58,12 @@ Maximum unescaped frame size: 512 bytes.
Data frames carry raw packet data only, with no metadata prepended. The Data command payload is limited to 255 bytes to match the MeshCore maximum transmission unit (MAX_TRANS_UNIT); frames larger than 255 bytes are silently dropped. The KISS specification recommends at least 1024 bytes for general-purpose TNCs; this modem is intended for MeshCore packets only, whose protocol MTU is 255 bytes.
Only one packet may be pending for radio transmission at a time. If the host sends a second Data frame before the first has completed, the modem responds with Error (0xF1) and TxBusy (0x07).
### Host Output Backpressure
Outbound frames are encoded into a 2-slot queue and flushed when serial output space is available; `loop()` never blocks on writes. Radio TX state advances independently of host read speed. TxDone is retained until it can be queued. If the outbound queue is full, the modem responds with Error (0xF1) and TxBusy (0x07). Hosts should read serial promptly to avoid delayed responses.
### CSMA Behavior
The TNC implements p-persistent CSMA for half-duplex operation:
@@ -156,15 +162,15 @@ Response codes use the high-bit convention: `response = command | 0x80`. Generic
| MacFailed | `0x04` | MAC verification failed |
| UnknownCmd | `0x05` | Unknown sub-command |
| EncryptFailed | `0x06` | Encryption failed |
| TxBusy | `0x07` | Transmit busy |
| TxBusy | `0x07` | Radio TX busy, or host output queue full |
### Unsolicited Events
The TNC sends these SetHardware frames without a preceding request:
**TxDone (0xF8)**: Sent after a packet has been transmitted. Contains a single byte: 0x01 for success, 0x00 for failure.
**TxDone (0xF8)**: Sent after radio transmission completes. Contains a single byte: 0x01 for success, 0x00 for failure. Delivery to the host may be delayed under serial backpressure but is not dropped.
**RxMeta (0xF9)**: Sent immediately after each standard data frame (type 0x00) with metadata for the received packet. Contains SNR (1 byte, signed, value x4 for 0.25 dB precision) followed by RSSI (1 byte, signed, dBm). Enabled by default; can be toggled with SetSignalReport. Standard KISS clients ignore this frame.
**RxMeta (0xF9)**: Sent after each standard data frame (type 0x00) with SNR (1 byte, signed, value x4) and RSSI (1 byte, signed, dBm). Queued with the data frame; omitted if the data frame cannot be queued. Enabled by default; toggle with SetSignalReport. Standard KISS clients ignore this frame.
## Data Formats
+1
View File
@@ -18,6 +18,7 @@ Once you have a working app/project, you need to be able to demonstrate it exist
| 0100 | MeshCore Open | zsylvester@monitormx.com — https://github.com/zjs81/meshcore-open |
| 0110 - 011F | Ripple | ripple_biz@protonmail.com — https://buymeacoffee.com/ripplebiz |
| 0120 | MCO Advanced | most.original.address@gmail.com — https://hdden.ru/MCOa/ |
| 0130 - 013F | StreamSensor | william@housedillon.com - https://housedillon.com/blog/lora-e5-with-seeed-fusion |
| FF00 - FFFF | -reserved for testing/dev- | |
(add rows, inside the range 0100 - FEFF for custom apps)
+29 -26
View File
@@ -23,7 +23,7 @@ NOTE: all 16 and 32-bit integer fields are Little Endian.
* Node hash: the first byte of the node's public key
# Node advertisement
## Node advertisement
This kind of payload notifies receivers that a node exists, and gives information about the node
| Field | Size (bytes) | Description |
@@ -57,7 +57,7 @@ Appdata Flags
| `0x40` | has feature 2 | Reserved for future use. |
| `0x80` | has name | appdata contains a node name |
# Acknowledgement
## Acknowledgement
An acknowledgement that a message was received. Note that for returned path messages, an acknowledgement can be sent in the "extra" payload (see [Returned Path](#returned-path)) instead of as a separate acknowledgement packet. CLI commands do not cause acknowledgement responses, neither discrete nor extra.
@@ -66,7 +66,7 @@ An acknowledgement that a message was received. Note that for returned path mess
| checksum | 4 | CRC checksum of message timestamp, text, and sender pubkey |
# Returned path, request, response, and plain text message
## Returned path, request, response, and plain text message
Returned path, request, response, and plain text messages are all formatted in the same way. See the subsection for more details about the ciphertext's associated plaintext representation.
@@ -77,7 +77,7 @@ Returned path, request, response, and plain text messages are all formatted in t
| cipher MAC | 2 | MAC for encrypted data in next field |
| ciphertext | rest of payload | encrypted message, see subsections below for details |
## Returned path
### Returned path
Returned path messages provide a description of the route a packet took from the original author. Receivers will send returned path messages to the author of the original message.
@@ -88,7 +88,7 @@ Returned path messages provide a description of the route a packet took from the
| extra type | 1 | extra, bundled payload type, eg., acknowledgement or response. Same values as in [Packet Format](./packet_format.md) |
| extra | rest of data | extra, bundled payload content, follows same format as main content defined by this document |
## Request
### Request
| Field | Size (bytes) | Description |
|--------------|-----------------|------------------------------------------|
@@ -102,7 +102,7 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v
| `0x01` | get stats | get stats of repeater or room server |
| `0x02` | keepalive | keep-alive request used for maintained connections |
### Get stats
#### Get stats
Gets information about the node, possibly including the following:
@@ -125,32 +125,32 @@ Gets information about the node, possibly including the following:
* Number posted (?)
* Number of post pushes (?)
### Get telemetry data
#### Get telemetry data
Not defined in `BaseChatMesh`. Sensor- and application-specific request payloads may be implemented by higher-level firmware.
### Get Telemetry
#### Get Telemetry
Not defined in `BaseChatMesh`.
### Get Min/Max/Ave (Sensor nodes)
#### Get Min/Max/Ave (Sensor nodes)
Not defined in `BaseChatMesh`.
### Get Access List
#### Get Access List
Not defined in `BaseChatMesh`.
### Get Neighbors
#### Get Neighbors
Not defined in `BaseChatMesh`.
### Get Owner Info
#### Get Owner Info
Not defined in `BaseChatMesh`.
## Response
### Response
| Field | Size (bytes) | Description |
|---------|-----------------|-----------------------------------|
@@ -158,7 +158,7 @@ Not defined in `BaseChatMesh`.
Response contents are opaque application data. There is no single generic response envelope beyond the encrypted payload wrapper shown above.
## Plain text message
### Plain text message
| Field | Size (bytes) | Description |
|--------------------|-----------------|-----------------------------------------------------------------------------------|
@@ -174,7 +174,7 @@ txt_type
| `0x01` | CLI command | the command text of the message |
| `0x02` | signed plain text message | first four bytes is sender pubkey prefix, followed by plain text message |
# Anonymous request
## Anonymous request
| Field | Size (bytes) | Description |
|------------------|-----------------|-------------------------------------------|
@@ -183,7 +183,7 @@ txt_type
| cipher MAC | 2 | MAC for encrypted data in next field |
| ciphertext | rest of payload | encrypted message, see below for details |
## Room server login
### Room server login
| Field | Size (bytes) | Description |
|----------------|-----------------|-------------------------------------------------------------------------------|
@@ -191,14 +191,14 @@ txt_type
| sync timestamp | 4 | sender's "sync messages SINCE x" timestamp |
| password | rest of message | password for room |
## Repeater/Sensor login
### Repeater/Sensor login
| Field | Size (bytes) | Description |
|----------------|-----------------|-------------------------------------------------------------------------------|
| timestamp | 4 | sender time (unix timestamp) |
| password | rest of message | password for repeater/sensor |
## Repeater - Regions request
### Repeater - Regions request
| Field | Size (bytes) | Description |
|----------------|--------------|------------------------------|
@@ -207,7 +207,7 @@ txt_type
| reply path len | 1 | path len for reply |
| reply path | (variable) | reply path |
## Repeater - Owner info request
### Repeater - Owner info request
| Field | Size (bytes) | Description |
|----------------|--------------|------------------------------|
@@ -216,7 +216,7 @@ txt_type
| reply path len | 1 | path len for reply |
| reply path | (variable) | reply path |
## Repeater - Clock and status request
### Repeater - Clock and status request
| Field | Size (bytes) | Description |
|----------------|--------------|------------------------------|
@@ -226,7 +226,7 @@ txt_type
| reply path | (variable) | reply path |
# Group text message
## Group text message
| Field | Size (bytes) | Description |
|--------------|-----------------|----------------------------------------------|
@@ -236,7 +236,10 @@ txt_type
The plaintext contained in the ciphertext matches the format described in [plain text message](#plain-text-message). Specifically, it consists of a four byte timestamp, a flags byte, and the message. The flags byte will generally be `0x00` because it is a "plain text message". The message will be of the form `<sender name>: <message body>` (eg., `user123: I'm on my way`).
# Group datagram
The sender name is unverified message text. Group messages contain no sender
signature, so any channel-key holder can choose any sender name.
## Group datagram
| Field | Size (bytes) | Description |
|--------------|-----------------|----------------------------------------------|
@@ -253,14 +256,14 @@ The data contained in the ciphertext uses the format below:
| data | rest of payload | (depends on data type) |
# Control data
## Control data
| Field | Size (bytes) | Description |
|--------------|-----------------|--------------------------------------------|
| flags | 1 | upper 4 bits is sub_type |
| data | rest of payload | typically unencrypted data |
## DISCOVER_REQ (sub_type)
### DISCOVER_REQ (sub_type)
| Field | Size (bytes) | Description |
|--------------|-----------------|----------------------------------------------|
@@ -269,7 +272,7 @@ The data contained in the ciphertext uses the format below:
| tag | 4 | randomly generate by sender |
| since | 4 | (optional) epoch timestamp (0 by default) |
## DISCOVER_RESP (sub_type)
### DISCOVER_RESP (sub_type)
| Field | Size (bytes) | Description |
|--------------|-----------------|--------------------------------------------|
@@ -279,6 +282,6 @@ The data contained in the ciphertext uses the format below:
| pubkey | 8 or 32 | node's ID (or prefix) |
# Custom packet
## Custom packet
Custom packets have no defined format.
+3 -1
View File
@@ -12,8 +12,10 @@ meshcore://channel/add?name=Public&secret=8b3387e9c5cdea6ac9e5edbaa115cd72
**Parameters**:
- `name`: Channel name (URL-encoded if needed)
- `name`: Channel name (URL-encoded)
- `secret`: 16-byte secret represented as 32 hex characters
- `region_scope`: Region Scope (optional, URL-encoded if provided)
- Supported by MeshCore App v1.47.0+
## Add Contact
+6 -6
View File
@@ -4,7 +4,7 @@
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/UIScreen.h>
#include <helpers/SensorManager.h>
#include <helpers/BaseSerialInterface.h>
#include <helpers/MultiSerialInterface.h>
#include <Arduino.h>
#ifdef PIN_BUZZER
@@ -25,10 +25,10 @@ enum class UIEventType {
class AbstractUITask {
protected:
mesh::MainBoard* _board;
BaseSerialInterface* _serial;
MultiSerialInterface* _interfaceManager;
bool _connected;
AbstractUITask(mesh::MainBoard* board, BaseSerialInterface* serial) : _board(board), _serial(serial) {
AbstractUITask(mesh::MainBoard* board, MultiSerialInterface* interfaceManager) : _board(board), _interfaceManager(interfaceManager) {
_connected = false;
}
@@ -36,9 +36,9 @@ public:
void setHasConnection(bool connected) { _connected = connected; }
bool hasConnection() const { return _connected; }
uint16_t getBattMilliVolts() const { return _board->getBattMilliVolts(); }
bool isSerialEnabled() const { return _serial->isEnabled(); }
void enableSerial() { _serial->enable(); }
void disableSerial() { _serial->disable(); }
bool isBluetoothEnabled() const { return _interfaceManager->isBluetoothEnabled(); }
void enableBluetooth() { _interfaceManager->enableBluetooth(); }
void disableBluetooth() { _interfaceManager->disableBluetooth(); }
virtual void msgRead(int msgcount) = 0;
virtual void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) = 0;
virtual void notify(UIEventType t = UIEventType::none) = 0;
+24 -46
View File
@@ -189,17 +189,22 @@ bool DataStore::saveMainIdentity(const mesh::LocalIdentity &identity) {
return identity_store.save("_main", identity);
}
void DataStore::loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon) {
if (_fs->exists("/new_prefs")) {
loadPrefsInt("/new_prefs", prefs, node_lat, node_lon); // new filename
} else if (_fs->exists("/node_prefs")) {
loadPrefsInt("/node_prefs", prefs, node_lat, node_lon);
savePrefs(prefs, node_lat, node_lon); // save to new filename
_fs->remove("/node_prefs"); // remove old
void DataStore::loadPrefs(NodePrefs& prefs) {
if (_fs->exists("/prefs.json")) {
File file = openRead(_fs, "/prefs.json");
if (file) {
prefs.loadSerial(file); // new Serial prefs
file.close();
}
} else if (_fs->exists("/new_prefs")) {
loadPrefsInt("/new_prefs", prefs);
if (savePrefs(prefs) ) { // save to new format
//_fs->remove("/new_prefs"); // remove old
}
}
}
void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& node_lat, double& node_lon) {
void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs) {
File file = openRead(_fs, filename);
if (file) {
uint8_t pad[8];
@@ -207,12 +212,12 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no
file.read((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
file.read((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
file.read(pad, 4); // 36
file.read((uint8_t *)&node_lat, sizeof(node_lat)); // 40
file.read((uint8_t *)&node_lon, sizeof(node_lon)); // 48
file.read((uint8_t *)&_prefs.node_lat, sizeof(_prefs.node_lat)); // 40
file.read((uint8_t *)&_prefs.node_lon, sizeof(_prefs.node_lon)); // 48
file.read((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
file.read((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
file.read((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
file.read((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62
file.read((uint8_t *)&_prefs._client_repeat, sizeof(_prefs._client_repeat)); // 62
file.read((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
file.read((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
file.read((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
@@ -234,48 +239,21 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no
file.read((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90
file.read((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121
// migrate old fields
_prefs.setRepeatEn(_prefs._client_repeat != 0);
file.close();
}
}
void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_lon) {
File file = openWrite(_fs, "/new_prefs");
bool DataStore::savePrefs(NodePrefs& _prefs) {
File file = openWrite(_fs, "/prefs.json");
if (file) {
uint8_t pad[8];
memset(pad, 0, sizeof(pad));
file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
file.write(pad, 4); // 36
file.write((uint8_t *)&node_lat, sizeof(node_lat)); // 40
file.write((uint8_t *)&node_lon, sizeof(node_lon)); // 48
file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
file.write((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62
file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78
file.write(pad, 1); // 79
file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
file.write((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84
file.write((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85
file.write((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86
file.write((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87
file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88
file.write((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89
file.write((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90
file.write((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121
bool success = _prefs.saveSerial(file);
file.close();
return success;
}
return false;
}
void DataStore::loadContacts(DataStoreHost* host) {
+3 -3
View File
@@ -19,7 +19,7 @@ class DataStore {
mesh::RTCClock* _clock;
IdentityStore identity_store;
void loadPrefsInt(const char *filename, NodePrefs& prefs, double& node_lat, double& node_lon);
void loadPrefsInt(const char *filename, NodePrefs& prefs);
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
void checkAdvBlobFile();
#endif
@@ -33,8 +33,8 @@ public:
FILESYSTEM* getSecondaryFS() const { return _fsExtra; }
bool loadMainIdentity(mesh::LocalIdentity &identity);
bool saveMainIdentity(const mesh::LocalIdentity &identity);
void loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon);
void savePrefs(const NodePrefs& prefs, double node_lat, double node_lon);
void loadPrefs(NodePrefs& prefs);
bool savePrefs(NodePrefs& prefs);
void loadContacts(DataStoreHost* host);
void saveContacts(DataStoreHost* host, bool (*filter)(const ContactInfo& c) = NULL);
void loadChannels(DataStoreHost* host);
+18 -6
View File
@@ -262,7 +262,7 @@ int MyMesh::getInterferenceThreshold() const {
return 0; // disabled for now, until currentRSSI() problem is resolved
}
bool MyMesh::getCADEnabled() const {
return true; // hardware CAD before TX (no CLI toggle on companion; enabled by default)
return false; // hardware CAD before TX (disabled by default, until configurable)
}
int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
@@ -483,7 +483,7 @@ bool MyMesh::filterRecvFloodPacket(mesh::Packet* packet) {
}
bool MyMesh::allowPacketForward(const mesh::Packet* packet) {
return _prefs.client_repeat != 0;
return _prefs.isRepeatEn();
}
void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis) {
@@ -657,6 +657,11 @@ uint8_t MyMesh::onContactRequest(const ContactInfo &contact, uint32_t sender_tim
// query other sensors -- target specific
sensors.querySensors(permissions, telemetry);
float temperature = board.getMCUTemperature();
if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
}
memcpy(reply, &sender_timestamp,
4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
@@ -871,7 +876,6 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
send_unscoped = false;
// defaults
memset(&_prefs, 0, sizeof(_prefs));
_prefs.airtime_factor = 1.0;
strcpy(_prefs.node_name, "NONAME");
_prefs.freq = LORA_FREQ;
@@ -882,6 +886,7 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
_prefs.gps_enabled = 0; // GPS disabled by default
_prefs.gps_interval = 0; // No automatic GPS updates by default
//_prefs.rx_delay_base = 10.0f; enable once new algo fixed
_prefs.setRepeatEn(false);
#if defined(USE_SX1262) || defined(USE_SX1268)
#ifdef SX126X_RX_BOOSTED_GAIN
_prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN;
@@ -926,7 +931,9 @@ void MyMesh::begin(bool has_display) {
#endif
// load persisted prefs
_store->loadPrefs(_prefs, sensors.node_lat, sensors.node_lon);
_store->loadPrefs(_prefs);
sensors.node_lat = _prefs.node_lat;
sensors.node_lon = _prefs.node_lon;
// sanitise bad pref values
_prefs.rx_delay_base = constrain(_prefs.rx_delay_base, 0, 20.0f);
@@ -1026,7 +1033,7 @@ void MyMesh::handleCmdFrame(size_t len) {
i += 40;
StrHelper::strzcpy((char *)&out_frame[i], FIRMWARE_VERSION, 20);
i += 20;
out_frame[i++] = _prefs.client_repeat; // v9+
out_frame[i++] = _prefs.isRepeatEn() ? 1 : 0; // v9+
out_frame[i++] = _prefs.path_hash_mode; // v10+
_serial->writeFrame(out_frame, i);
} else if (cmd_frame[0] == CMD_APP_START &&
@@ -1388,7 +1395,7 @@ void MyMesh::handleCmdFrame(size_t len) {
_prefs.cr = cr;
_prefs.freq = (float)freq / 1000.0;
_prefs.bw = (float)bw / 1000.0;
_prefs.client_repeat = repeat;
_prefs.setRepeatEn(repeat != 0);
savePrefs();
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
@@ -1640,6 +1647,11 @@ void MyMesh::handleCmdFrame(size_t len) {
} else if (cmd_frame[0] == CMD_SEND_TELEMETRY_REQ && len == 4) { // 'self' telemetry request
telemetry.reset();
telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
float temperature = board.getMCUTemperature();
if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
}
// query other sensors -- target specific
sensors.querySensors(0xFF, telemetry);
+7 -3
View File
@@ -8,11 +8,11 @@
#define FIRMWARE_VER_CODE 13
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "6 Jun 2026"
#define FIRMWARE_BUILD_DATE "9 Aug 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "v1.16.0"
#define FIRMWARE_VERSION "v1.17.0"
#endif
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
@@ -165,7 +165,11 @@ protected:
}
public:
void savePrefs() { _store->savePrefs(_prefs, sensors.node_lat, sensors.node_lon); }
void savePrefs() {
_prefs.node_lat = sensors.node_lat;
_prefs.node_lon = sensors.node_lon;
_store->savePrefs(_prefs);
}
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
+124 -23
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdint> // For uint8_t, uint32_t
#include <helpers/ConfigSerializer.h>
#define TELEM_MODE_DENY 0
#define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags
@@ -8,30 +9,130 @@
#define ADVERT_LOC_NONE 0
#define ADVERT_LOC_SHARE 1
struct NodePrefs { // persisted to file
float airtime_factor;
class NodePrefs : public ConfigSerializer { // persisted to file
public:
float airtime_factor = 0;
char node_name[32];
float freq;
uint8_t sf;
uint8_t cr;
uint8_t multi_acks;
uint8_t manual_add_contacts;
float bw;
int8_t tx_power_dbm;
uint8_t telemetry_mode_base;
uint8_t telemetry_mode_loc;
uint8_t telemetry_mode_env;
float rx_delay_base;
uint32_t ble_pin;
uint8_t advert_loc_policy;
uint8_t buzzer_quiet;
uint8_t gps_enabled; // GPS enabled flag (0=disabled, 1=enabled)
uint32_t gps_interval; // GPS read interval in seconds
uint8_t autoadd_config; // bitmask for auto-add contacts config
uint8_t rx_boosted_gain; // SX126x RX boosted gain mode (0=power saving, 1=boosted)
uint8_t client_repeat;
uint8_t path_hash_mode; // which path mode to use when sending
uint8_t autoadd_max_hops; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
double node_lat = 0, node_lon = 0;
float freq = 0;
uint8_t sf = 0;
uint8_t cr = 0;
uint8_t multi_acks = 0;
uint8_t manual_add_contacts = 0;
float bw = 0;
int8_t tx_power_dbm = 0;
uint8_t telemetry_mode_base = 0;
uint8_t telemetry_mode_loc = 0;
uint8_t telemetry_mode_env = 0;
float rx_delay_base = 0;
uint32_t ble_pin = 0;
uint8_t advert_loc_policy = 0;
uint8_t buzzer_quiet = 0;
uint8_t vibe_quiet = 0;
uint8_t gps_enabled = 0; // GPS enabled flag (0=disabled, 1=enabled)
uint32_t gps_interval = 0; // GPS read interval in seconds
uint8_t autoadd_config = 0; // bitmask for auto-add contacts config
uint8_t rx_boosted_gain = 0; // SX126x RX boosted gain mode (0=power saving, 1=boosted)
uint8_t _client_repeat = 0; // DEPRECATED -> use repeat.disable_fwd
uint8_t path_hash_mode = 0; // which path mode to use when sending
uint8_t autoadd_max_hops = 0; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
char default_scope_name[31];
uint8_t default_scope_key[16];
private:
class RadioPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
NodePrefs* _parent;
protected:
void structure() override {
def("freq", _parent->freq);
def("bw", _parent->bw);
def("sf", _parent->sf);
def("cr", _parent->cr);
//def("cad", _parent->cad_enabled);
//def("int_thr", _parent->interference_threshold);
def("rxgain", _parent->rx_boosted_gain);
def("fem_rxgain", _parent->rx_boosted_gain);
def("tx", _parent->tx_power_dbm);
def("af", _parent->airtime_factor);
def("rxdelay", _parent->rx_delay_base);
//def("f_txdelay", _parent->tx_delay_factor); currently hard-coded
//def("d_txdelay", _parent->direct_tx_delay_factor); currently hard-coded
//def("agc_int", _parent->agc_reset_interval);
def("hash_mode", _parent->path_hash_mode);
def("multi_ack", _parent->multi_acks);
}
public:
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
};
RadioPrefs radio;
class GPSPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
NodePrefs* _parent;
protected:
void structure() override {
def("en", _parent->gps_enabled); // boolean
def("int", _parent->gps_interval); // interval in seconds
def("adv_loc", _parent->advert_loc_policy);
}
public:
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
};
GPSPrefs gps;
class RepeatPrefs : public ConfigSerializer { // COPIED from CommonCLI (for now)
public:
uint8_t disable_fwd = 1;
protected:
void structure() override {
def("disable", disable_fwd);
//def("f_max", flood_max);
//def("f_max_uns", flood_max_unscoped);
//def("f_max_adv", flood_max_advert);
//def("loop", loop_detect);
}
};
RepeatPrefs repeat;
class CompanionPrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("auto_max", _parent->autoadd_max_hops); // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
def("defs_nm", _parent->default_scope_name, sizeof(_parent->default_scope_name));
def("defs_key", (void *) _parent->default_scope_key, sizeof(_parent->default_scope_key));
def("pin", _parent->ble_pin);
def("buzz_q", _parent->buzzer_quiet);
def("vibe_q", _parent->vibe_quiet);
def("auto_add", _parent->autoadd_config); // bitmask for auto-add contacts config
def("man_add", _parent->manual_add_contacts);
def("tel_base", _parent->telemetry_mode_base);
def("tel_loc", _parent->telemetry_mode_loc);
def("tel_env", _parent->telemetry_mode_env);
}
public:
CompanionPrefs(NodePrefs* parent) : _parent(parent) { }
};
CompanionPrefs companion;
protected:
void structure() override {
def("name", node_name, sizeof(node_name));
//def("adv_int", advert_interval);
//def("f_adv_int", flood_advert_interval);
def("lat", node_lat);
def("lon", node_lon);
def("radio", radio);
def("gps", gps);
def("repeat", repeat);
def("comp", companion);
}
public:
NodePrefs() : radio(this), gps(this), companion(this) {
node_name[0] = 0;
default_scope_name[0] = 0;
memset(default_scope_key, 0, sizeof(default_scope_key));
}
// new accessor methods
bool isRepeatEn() const { return repeat.disable_fwd == 0; }
void setRepeatEn(bool en) { repeat.disable_fwd = en ? 0 : 1; }
};
+102 -96
View File
@@ -12,19 +12,72 @@ static uint32_t _atoi(const char* sp) {
return n;
}
// interface manager
#include <helpers/MultiSerialInterface.h>
MultiSerialInterface interface_manager;
// include bluetooth interface
#if defined(BLE_PIN_CODE)
#ifdef ESP32
// include esp32 bluetooth interface
#include <helpers/esp32/SerialBLEInterface.h>
SerialBLEInterface bluetooth_interface;
#elif defined(NRF52_PLATFORM)
// include nrf52 bluetooth interface
#include <helpers/nrf52/SerialBLEInterface.h>
SerialBLEInterface bluetooth_interface;
#else
#error "SerialBLEInterface is not defined for this platform"
#endif
#endif
// include wifi interface
#ifdef WIFI_SSID
#ifndef TCP_PORT
#define TCP_PORT 5000
#endif
#ifdef ESP32
// include esp32 wifi interface
#include <helpers/esp32/SerialWifiInterface.h>
SerialWifiInterface wifi_interface;
#else
#error "SerialWifiInterface is not defined for this platform"
#endif
#endif
// include usb interface
#if defined(ENABLE_USB_INTERFACE)
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface usb_serial_interface;
#endif
// include ethernet interface
#if defined(ETHERNET_ENABLED)
#include <helpers/ethernet/EthernetInterface.h>
ETHERNET_CLASS ethernet_interface;
#endif
// include hardware serial interface
#if defined(SERIAL_RX)
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface hardware_serial_interface;
HardwareSerial companion_serial(1);
#endif
// platform file system
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include <InternalFileSystem.h>
#if defined(QSPIFLASH)
#include <CustomLFS_QSPIFlash.h>
DataStore store(InternalFS, QSPIFlash, rtc_clock);
#else
#if defined(EXTRAFS)
#include <CustomLFS.h>
CustomLFS ExtraFS(0xD4000, 0x19000, 128);
DataStore store(InternalFS, ExtraFS, rtc_clock);
#else
DataStore store(InternalFS, rtc_clock);
#endif
#if defined(EXTRAFS)
#include <CustomLFS.h>
CustomLFS ExtraFS(0xD4000, 0x19000, 128);
DataStore store(InternalFS, ExtraFS, rtc_clock);
#else
DataStore store(InternalFS, rtc_clock);
#endif
#endif
#elif defined(RP2040_PLATFORM)
#include <LittleFS.h>
@@ -34,61 +87,10 @@ static uint32_t _atoi(const char* sp) {
DataStore store(SPIFFS, rtc_clock);
#endif
#ifdef ESP32
#ifdef WIFI_SSID
#include <helpers/esp32/SerialWifiInterface.h>
SerialWifiInterface serial_interface;
#ifndef TCP_PORT
#define TCP_PORT 5000
#endif
#elif defined(BLE_PIN_CODE)
#include <helpers/esp32/SerialBLEInterface.h>
SerialBLEInterface serial_interface;
#elif defined(SERIAL_RX)
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface serial_interface;
HardwareSerial companion_serial(1);
#else
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface serial_interface;
#endif
#elif defined(RP2040_PLATFORM)
//#ifdef WIFI_SSID
// #include <helpers/rp2040/SerialWifiInterface.h>
// SerialWifiInterface serial_interface;
// #ifndef TCP_PORT
// #define TCP_PORT 5000
// #endif
// #elif defined(BLE_PIN_CODE)
// #include <helpers/rp2040/SerialBLEInterface.h>
// SerialBLEInterface serial_interface;
#if defined(SERIAL_RX)
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface serial_interface;
HardwareSerial companion_serial(1);
#else
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface serial_interface;
#endif
#elif defined(NRF52_PLATFORM)
#ifdef BLE_PIN_CODE
#include <helpers/nrf52/SerialBLEInterface.h>
SerialBLEInterface serial_interface;
#else
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface serial_interface;
#endif
#elif defined(STM32_PLATFORM)
#include <helpers/ArduinoSerialInterface.h>
ArduinoSerialInterface serial_interface;
#else
#error "need to define a serial interface"
#endif
/* GLOBAL OBJECTS */
#ifdef DISPLAY_CLASS
#include "UITask.h"
UITask ui_task(&board, &serial_interface);
UITask ui_task(&board, &interface_manager);
#endif
StdRNG fast_rng;
@@ -113,9 +115,12 @@ void halt() {
void setup() {
Serial.begin(115200);
board.begin();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.begin();
#endif
#ifdef DISPLAY_CLASS
DisplayDriver* disp = NULL;
if (display.begin()) {
@@ -155,13 +160,6 @@ void setup() {
false
#endif
);
#ifdef BLE_PIN_CODE
serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin());
#else
serial_interface.begin(Serial);
#endif
the_mesh.startInterface(serial_interface);
#elif defined(RP2040_PLATFORM)
LittleFS.begin();
store.begin();
@@ -172,22 +170,6 @@ void setup() {
false
#endif
);
//#ifdef WIFI_SSID
// WiFi.begin(WIFI_SSID, WIFI_PWD);
// serial_interface.begin(TCP_PORT);
// #elif defined(BLE_PIN_CODE)
// char dev_name[32+16];
// sprintf(dev_name, "%s%s", BLE_NAME_PREFIX, the_mesh.getNodeName());
// serial_interface.begin(dev_name, the_mesh.getBLEPin());
#if defined(SERIAL_RX)
companion_serial.setPins(SERIAL_RX, SERIAL_TX);
companion_serial.begin(115200);
serial_interface.begin(companion_serial);
#else
serial_interface.begin(Serial);
#endif
the_mesh.startInterface(serial_interface);
#elif defined(ESP32)
SPIFFS.begin(true);
store.begin();
@@ -198,7 +180,17 @@ void setup() {
false
#endif
);
#else
#error "need to define filesystem"
#endif
// add bluetooth interface
#if defined(BLE_PIN_CODE)
bluetooth_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin());
interface_manager.addInterface(InterfaceType::Bluetooth, &bluetooth_interface);
#endif
// add wifi interface
#ifdef WIFI_SSID
board.setInhibitSleep(true); // prevent sleep when WiFi is active
WiFi.setAutoReconnect(true);
@@ -214,21 +206,31 @@ void setup() {
});
WiFi.begin(WIFI_SSID, WIFI_PWD);
serial_interface.begin(TCP_PORT);
#elif defined(BLE_PIN_CODE)
serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin());
#elif defined(SERIAL_RX)
companion_serial.setPins(SERIAL_RX, SERIAL_TX);
companion_serial.begin(115200);
serial_interface.begin(companion_serial);
#else
serial_interface.begin(Serial);
#endif
the_mesh.startInterface(serial_interface);
#else
#error "need to define filesystem"
wifi_interface.begin(TCP_PORT);
interface_manager.addInterface(InterfaceType::WiFi, &wifi_interface);
#endif
// add usb interface
#if defined(ENABLE_USB_INTERFACE)
usb_serial_interface.begin(Serial);
interface_manager.addInterface(InterfaceType::USB, &usb_serial_interface);
#endif
// add ethernet interface
#if defined(ETHERNET_ENABLED)
ethernet_interface.begin();
interface_manager.addInterface(InterfaceType::Ethernet, &ethernet_interface);
#endif
// add hardware serial interface
#if defined(SERIAL_RX)
companion_serial.setPins(SERIAL_RX, SERIAL_TX);
companion_serial.begin(115200);
hardware_serial_interface.begin(companion_serial);
interface_manager.addInterface(InterfaceType::HardwareSerial, &hardware_serial_interface);
#endif
the_mesh.startInterface(interface_manager);
sensors.begin();
#if ENV_INCLUDE_GPS == 1
@@ -244,11 +246,15 @@ void setup() {
void loop() {
the_mesh.loop();
interface_manager.loop();
sensors.loop();
#ifdef DISPLAY_CLASS
ui_task.loop();
#endif
rtc_clock.tick();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.loop();
#endif
if (!the_mesh.hasPendingWork()) {
#if defined(NRF52_PLATFORM)
+62 -30
View File
@@ -53,23 +53,24 @@ public:
int render(DisplayDriver& display) override {
// meshcore logo
display.setColor(DisplayDriver::BLUE);
display.setColor(UIColor::corp_blue);
int logoWidth = 128;
display.drawXbm((display.width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// meshcore website
const char* website = "https://meshcore.io";
display.setColor(DisplayDriver::LIGHT);
display.setColor(UIColor::primary_txt);
display.setTextSize(1);
uint16_t websiteWidth = display.getTextWidth(website);
display.setCursor((display.width() - websiteWidth) / 2, 22);
display.print(website);
// version info
display.setColor(DisplayDriver::LIGHT);
display.setColor(UIColor::primary_txt);
display.setTextSize(1);
display.drawTextCentered(display.width()/2, 35, _version_info);
display.setColor(UIColor::secondary_txt);
display.setTextSize(1);
display.drawTextCentered(display.width()/2, 48, FIRMWARE_BUILD_DATE);
@@ -128,7 +129,7 @@ class HomeScreen : public UIScreen {
int iconHeight = 10;
int iconX = display.width() - iconWidth - 5; // Position the icon near the top-right corner
int iconY = 0;
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::title_txt);
// battery outline
display.drawRect(iconX, iconY, iconWidth, iconHeight);
@@ -143,7 +144,7 @@ class HomeScreen : public UIScreen {
// show muted icon if buzzer is muted
#ifdef PIN_BUZZER
if (_task->isBuzzerQuiet()) {
display.setColor(DisplayDriver::RED);
display.setColor(UIColor::warning_txt);
display.drawXbm(iconX - 9, iconY + 1, muted_icon, 8, 8);
}
#endif
@@ -188,34 +189,41 @@ public:
}
int render(DisplayDriver& display) override {
display.setColor(UIColor::title_bkg);
display.fillRect(0, 0, display.width(), 12);
char tmp[80];
// node name
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::title_txt);
char filtered_name[sizeof(_node_prefs->node_name)];
display.translateUTF8ToBlocks(filtered_name, _node_prefs->node_name, sizeof(filtered_name));
display.setCursor(0, 0);
display.setCursor(0, 2);
display.print(filtered_name);
// battery voltage
renderBatteryIndicator(display, _task->getBattMilliVolts());
// curr page indicator
if (UIColor::title_bkg == UIColor::window_bkg) {
display.setColor(UIColor::title_txt);
} else {
display.setColor(UIColor::title_bkg);
}
int y = 14;
int x = display.width() / 2 - 5 * (HomePage::Count-1);
for (uint8_t i = 0; i < HomePage::Count; i++, x += 10) {
if (i == _page) {
display.fillRect(x-1, y-1, 3, 3);
display.fillRect(x-1, y-1, 4, 4);
} else {
display.fillRect(x, y, 1, 1);
display.fillRect(x, y, 2, 2);
}
}
if (_page == HomePage::FIRST) {
display.setColor(DisplayDriver::YELLOW);
display.setColor(UIColor::primary_txt);
display.setTextSize(2);
sprintf(tmp, "MSG: %d", _task->getMsgCount());
display.drawTextCentered(display.width() / 2, 20, tmp);
display.drawTextCentered(display.width() / 2, 22, tmp);
#ifdef WIFI_SSID
IPAddress ip = WiFi.localIP();
@@ -224,19 +232,19 @@ public:
display.drawTextCentered(display.width() / 2, 54, tmp);
#endif
if (_task->hasConnection()) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::warning_txt);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 43, "< Connected >");
} else if (the_mesh.getBLEPin() != 0) { // BT pin
display.setColor(DisplayDriver::RED);
display.setColor(UIColor::warning_txt);
display.setTextSize(2);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
display.drawTextCentered(display.width() / 2, 43, tmp);
}
} else if (_page == HomePage::RECENT) {
the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE);
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::primary_txt);
int y = 20;
for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) {
auto a = &recent[i];
@@ -260,7 +268,7 @@ public:
display.print(tmp);
}
} else if (_page == HomePage::RADIO) {
display.setColor(DisplayDriver::YELLOW);
display.setColor(UIColor::primary_txt);
display.setTextSize(1);
// freq / sf
display.setCursor(0, 20);
@@ -279,15 +287,17 @@ public:
sprintf(tmp, "Noise floor: %d", radio_driver.getNoiseFloor());
display.print(tmp);
} else if (_page == HomePage::BLUETOOTH) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::corp_blue);
display.drawXbm((display.width() - 32) / 2, 18,
_task->isSerialEnabled() ? bluetooth_on : bluetooth_off,
_task->isBluetoothEnabled() ? bluetooth_on : bluetooth_off,
32, 32);
display.setColor(UIColor::secondary_txt);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL);
} else if (_page == HomePage::ADVERT) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::corp_blue);
display.drawXbm((display.width() - 32) / 2, 18, advert_icon, 32, 32);
display.setColor(UIColor::secondary_txt);
display.drawTextCentered(display.width() / 2, 64 - 11, "advert: " PRESS_LABEL);
#if ENV_INCLUDE_GPS == 1
} else if (_page == HomePage::GPS) {
@@ -305,24 +315,33 @@ public:
#else
strcpy(buf, gps_state ? "gps on" : "gps off");
#endif
display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) {
y = y + 12;
display.setColor(UIColor::secondary_txt);
display.drawTextLeftAlign(0, y, "Can't access GPS");
} else {
display.setColor(UIColor::primary_txt);
strcpy(buf, nmea->isValid()?"fix":"no fix");
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
display.setColor(UIColor::secondary_txt);
display.drawTextLeftAlign(0, y, "sat");
display.setColor(UIColor::primary_txt);
sprintf(buf, "%d", nmea->satellitesCount());
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
display.setColor(UIColor::secondary_txt);
display.drawTextLeftAlign(0, y, "pos");
display.setColor(UIColor::primary_txt);
sprintf(buf, "%.4f %.4f",
nmea->getLatitude()/1000000., nmea->getLongitude()/1000000.);
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
display.setColor(UIColor::secondary_txt);
display.drawTextLeftAlign(0, y, "alt");
display.setColor(UIColor::primary_txt);
sprintf(buf, "%.2f", nmea->getAltitude()/1000.);
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
@@ -390,7 +409,9 @@ public:
strcpy(name, "unk"); sprintf(buf, "");
}
display.setCursor(0, y);
display.setColor(UIColor::secondary_txt);
display.print(name);
display.setColor(UIColor::primary_txt);
display.setCursor(
display.width()-display.getTextWidth(buf)-1, y
);
@@ -401,11 +422,13 @@ public:
else sensors_scroll_offset = 0;
#endif
} else if (_page == HomePage::SHUTDOWN) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::corp_blue);
display.setTextSize(1);
if (_shutdown_init) {
display.setColor(UIColor::warning_txt);
display.drawTextCentered(display.width() / 2, 34, "hibernating...");
} else {
display.setColor(UIColor::secondary_txt);
display.drawXbm((display.width() - 32) / 2, 18, power_icon, 32, 32);
display.drawTextCentered(display.width() / 2, 64 - 11, "hibernate:" PRESS_LABEL);
}
@@ -426,10 +449,10 @@ public:
return true;
}
if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) {
if (_task->isSerialEnabled()) { // toggle Bluetooth on/off
_task->disableSerial();
if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off
_task->disableBluetooth();
} else {
_task->enableSerial();
_task->enableBluetooth();
}
return true;
}
@@ -498,7 +521,7 @@ public:
char tmp[16];
display.setCursor(0, 0);
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::corp_blue);
sprintf(tmp, "Unread: %d", num_unread);
display.print(tmp);
@@ -518,13 +541,13 @@ public:
display.drawRect(0, 11, display.width(), 1); // horiz line
display.setCursor(0, 14);
display.setColor(DisplayDriver::YELLOW);
display.setColor(UIColor::secondary_txt);
char filtered_origin[sizeof(p->origin)];
display.translateUTF8ToBlocks(filtered_origin, p->origin, sizeof(filtered_origin));
display.print(filtered_origin);
display.setCursor(0, 25);
display.setColor(DisplayDriver::LIGHT);
display.setColor(UIColor::primary_txt);
char filtered_msg[sizeof(p->msg)];
display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg));
display.printWordWrap(filtered_msg, display.width());
@@ -697,8 +720,7 @@ void UITask::shutdown(bool restart){
if (restart) {
_board->reboot();
} else {
_display->turnOff();
radio_driver.powerOff();
// Power off board including radio, display, GPS and components
_board->powerOff();
}
}
@@ -748,6 +770,16 @@ void UITask::loop() {
c = handleTripleClick(KEY_SELECT);
}
#endif
#if defined(UI_HAS_ROTARY_INPUT)
RotaryInputEvent rotaryEv = rotary_input.poll();
if (c == 0 && _display != NULL && _display->isOn()) {
if (rotaryEv == RotaryInputEvent::Next) {
c = KEY_NEXT;
} else if (rotaryEv == RotaryInputEvent::Prev) {
c = KEY_PREV;
}
}
#endif
#if defined(PIN_USER_BTN_ANA)
if (abs(millis() - _analogue_pin_read_millis) > 10) {
int ev = analog_btn.check();
@@ -797,9 +829,9 @@ void UITask::loop() {
_display->setTextSize(1);
int y = _display->height() / 3;
int p = _display->height() / 32;
_display->setColor(DisplayDriver::DARK);
_display->setColor(UIColor::popup_bkg);
_display->fillRect(p, y, _display->width() - p*2, y);
_display->setColor(DisplayDriver::LIGHT); // draw box border
_display->setColor(UIColor::popup_txt); // draw box border
_display->drawRect(p, y, _display->width() - p*2, y);
_display->drawTextCentered(_display->width() / 2, y + p*3, _alert);
_next_refresh = _alert_expiry; // will need refresh when alert is dismissed
@@ -836,7 +868,7 @@ void UITask::loop() {
if (_display != NULL) {
_display->startFrame();
_display->setTextSize(2);
_display->setColor(DisplayDriver::RED);
_display->setColor(UIColor::warning_txt);
_display->drawTextCentered(_display->width() / 2, 20, "Low Battery.");
_display->drawTextCentered(_display->width() / 2, 40, "Shutting Down!");
_display->endFrame();
+2 -2
View File
@@ -4,7 +4,7 @@
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/UIScreen.h>
#include <helpers/SensorManager.h>
#include <helpers/BaseSerialInterface.h>
#include <helpers/MultiSerialInterface.h>
#include <Arduino.h>
#include <helpers/sensors/LPPDataHelpers.h>
@@ -65,7 +65,7 @@ class UITask : public AbstractUITask {
public:
UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
next_batt_chck = _next_refresh = 0;
ui_started_at = 0;
curr = NULL;
+159 -20
View File
@@ -6,12 +6,19 @@
#define AUTO_OFF_MILLIS 15000 // 15 seconds
#define BOOT_SCREEN_MILLIS 3000 // 3 seconds
#ifdef PIN_STATUS_LED
#if defined(PIN_STATUS_LED) || defined(PIN_STATUS_LED_R)
#define LED_ON_MILLIS 20
#define LED_ON_MSG_MILLIS 200
#define LED_CYCLE_MILLIS 4000
#endif
#if defined(PIN_STATUS_LED_R) && defined(PIN_STATUS_LED_G) && defined(PIN_STATUS_LED_B)
#define STATUS_LED_RGB 1
#ifndef LOW_BATT_MILLIVOLTS
#define LOW_BATT_MILLIVOLTS 3500
#endif
#endif
#ifndef USER_BTN_PRESSED
#define USER_BTN_PRESSED LOW
#endif
@@ -60,6 +67,11 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no
buzzer.startup();
#endif
#ifdef HAS_DRV2605
vibration.begin();
vibration.quiet(_node_prefs->vibe_quiet);
#endif
// Initialize digital button if available
#ifdef PIN_USER_BTN
_userButton = new Button(PIN_USER_BTN, USER_BTN_PRESSED);
@@ -130,6 +142,10 @@ void UITask::clearMsgPreview() {
void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) {
_msgcount = msgcount;
#ifdef HAS_DRV2605
vibration.trigger(); // vibrate even while the app is connected (honors quiet + cooldown)
#endif
if (path_len == 0xFF) {
sprintf(_origin, "(F) %s", from_name);
} else {
@@ -167,7 +183,7 @@ void UITask::renderBatteryIndicator(uint16_t batteryMilliVolts) {
int iconHeight = 12;
int iconX = _display->width() - iconWidth - 5; // Position the icon near the top-right corner
int iconY = 0;
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
// battery outline
_display->drawRect(iconX, iconY, iconWidth, iconHeight);
@@ -188,7 +204,7 @@ void UITask::renderCurrScreen() {
_display->setTextSize(1.4);
uint16_t textWidth = _display->getTextWidth(_alert);
_display->setCursor((_display->width() - textWidth) / 2, 22);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::warning_txt);
_display->print(_alert);
_alert[0] = 0;
_need_refresh = true;
@@ -197,30 +213,29 @@ void UITask::renderCurrScreen() {
// render message preview
_display->setCursor(0, 0);
_display->setTextSize(1);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
_display->print(_node_prefs->node_name);
_display->setCursor(0, 12);
_display->setColor(DisplayDriver::YELLOW);
_display->setColor(UIColor::secondary_txt);
_display->print(_origin);
_display->setCursor(0, 24);
_display->setColor(DisplayDriver::LIGHT);
_display->print(_msg);
_display->setCursor(_display->width() - 28, 9);
_display->setTextSize(2);
_display->setColor(DisplayDriver::ORANGE);
_display->setColor(UIColor::primary_txt);
sprintf(tmp, "%d", _msgcount);
_display->print(tmp);
_display->setColor(DisplayDriver::YELLOW); // last color will be kept on T114
_display->setColor(UIColor::secondary_txt); // last color will be kept on T114
} else if ((millis() - ui_started_at) < BOOT_SCREEN_MILLIS) { // boot screen
// meshcore logo
_display->setColor(DisplayDriver::BLUE);
_display->setColor(UIColor::corp_blue);
int logoWidth = 128;
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// version info
_display->setColor(DisplayDriver::LIGHT);
_display->setColor(UIColor::primary_txt);
_display->setTextSize(1);
uint16_t textWidth = _display->getTextWidth(_version_info);
_display->setCursor((_display->width() - textWidth) / 2, 22);
@@ -229,7 +244,7 @@ void UITask::renderCurrScreen() {
// node name
_display->setCursor(0, 0);
_display->setTextSize(1);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
_display->print(_node_prefs->node_name);
// battery voltage
@@ -237,7 +252,7 @@ void UITask::renderCurrScreen() {
// freq / sf
_display->setCursor(0, 20);
_display->setColor(DisplayDriver::YELLOW);
_display->setColor(UIColor::secondary_txt);
sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf);
_display->print(tmp);
@@ -248,21 +263,127 @@ void UITask::renderCurrScreen() {
// BT pin
if (!_connected && the_mesh.getBLEPin() != 0) {
_display->setColor(DisplayDriver::RED);
_display->setColor(UIColor::warning_txt);
_display->setTextSize(2);
_display->setCursor(0, 43);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
_display->print(tmp);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
} else {
_display->setColor(DisplayDriver::LIGHT);
_display->setColor(UIColor::primary_txt);
}
}
_need_refresh = false;
}
#ifdef STATUS_LED_RGB
static void statusLedWrite(uint8_t r, uint8_t g, uint8_t b) {
analogWrite(PIN_STATUS_LED_R, r);
analogWrite(PIN_STATUS_LED_G, g);
analogWrite(PIN_STATUS_LED_B, b);
}
static void statusLedWheel(uint8_t pos) { // smooth hue sweep, 0..255
if (pos < 85) {
statusLedWrite(255 - pos * 3, pos * 3, 0);
} else if (pos < 170) {
pos -= 85;
statusLedWrite(0, 255 - pos * 3, pos * 3);
} else {
pos -= 170;
statusLedWrite(pos * 3, 0, 255 - pos * 3);
}
}
#endif
void UITask::userLedHandler() {
#ifdef PIN_STATUS_LED
#ifdef STATUS_LED_RGB
static bool booted = false;
static bool flourish_active = false;
static unsigned long flourish_until = 0;
static int prev_msgcount = 0;
static int state = 0;
static unsigned long next_change = 0;
static int last_increment = 0;
static unsigned long next_batt_check = 0;
static bool low_batt = false;
unsigned long cur_time = millis();
if (!booted) { // color sweep on boot
booted = true;
flourish_until = cur_time + 1200;
flourish_active = true;
}
if (_msgcount > prev_msgcount) { // color sweep when a new message arrives
flourish_until = cur_time + 800;
flourish_active = true;
}
prev_msgcount = _msgcount;
if (flourish_active) {
if (cur_time < flourish_until) {
statusLedWheel((cur_time % 1200) * 255 / 1200);
return;
}
statusLedWrite(0, 0, 0);
flourish_active = false;
state = 0;
next_change = cur_time;
}
if (cur_time > next_batt_check) { // battery reads are not free, keep them rare
low_batt = _board->getBattMilliVolts() < LOW_BATT_MILLIVOLTS;
next_batt_check = cur_time + 60000;
}
#ifdef EXT_CHRG_DETECT
// charge status display while docked (skipped when messages are waiting,
// so the unread indication is never masked)
static unsigned long next_pwr_check = 0;
static bool ext_powered = false, ext_charging = false;
if (cur_time > next_pwr_check) {
ext_powered = _board->isExternalPowered();
ext_charging = ext_powered && digitalRead(EXT_CHRG_DETECT) == LOW;
next_pwr_check = cur_time + 1000;
}
if (ext_powered && _msgcount == 0) {
if (ext_charging) {
// amber breathing while charging
int ph = cur_time % 2000;
int v = ph < 1000 ? ph : 2000 - ph;
uint8_t lvl = (uint8_t)(v * 255 / 1000);
statusLedWrite(lvl, (uint8_t)(lvl * 35 / 100), 0);
} else {
statusLedWrite(0, 40, 0); // dim solid green: charge complete
}
state = 0;
next_change = cur_time;
return;
}
#endif
if (cur_time > next_change) {
if (state == 0) {
state = 1;
last_increment = (_msgcount > 0) ? LED_ON_MSG_MILLIS : LED_ON_MILLIS;
next_change = cur_time + last_increment;
if (low_batt) {
statusLedWrite(255, 0, 0); // red: battery low
} else if (_msgcount > 0) {
statusLedWrite(255, 90, 0); // amber: unread messages
} else if (_connected) {
statusLedWrite(0, 0, 255); // blue: app connected
} else {
statusLedWrite(0, 255, 0); // green: heartbeat
}
} else {
state = 0;
next_change = cur_time + LED_CYCLE_MILLIS - last_increment;
statusLedWrite(0, 0, 0);
}
}
#elif defined(PIN_STATUS_LED)
static int state = 0;
static int next_change = 0;
static int last_increment = 0;
@@ -307,7 +428,7 @@ void UITask::shutdown(bool restart){
if (restart) {
_board->reboot();
} else {
radio_driver.powerOff();
// Power off board including radio, display, GPS and components
_board->powerOff();
}
}
@@ -407,8 +528,26 @@ void UITask::handleButtonDoublePress() {
void UITask::handleButtonTriplePress() {
MESH_DEBUG_PRINTLN("UITask: triple press triggered");
// Toggle buzzer quiet mode
#ifdef PIN_BUZZER
#if defined(PIN_BUZZER) && defined(HAS_DRV2605)
// cycle alert modes: Buzz+Vibe -> Buzz only -> Vibe only -> Silent
int mode = (_node_prefs->buzzer_quiet ? 2 : 0) | (_node_prefs->vibe_quiet ? 1 : 0);
mode = (mode + 1) & 3;
_node_prefs->buzzer_quiet = (mode & 2) ? 1 : 0;
_node_prefs->vibe_quiet = (mode & 1) ? 1 : 0;
buzzer.quiet(_node_prefs->buzzer_quiet);
vibration.quiet(_node_prefs->vibe_quiet);
// audible/tactile confirmation of the new mode (no screen on some boards)
if (!_node_prefs->buzzer_quiet) notify(UIEventType::ack);
if (!_node_prefs->vibe_quiet) vibration.trigger(true);
switch (mode) {
case 0: sprintf(_alert, "Alerts: Buzz+Vibe"); break;
case 1: sprintf(_alert, "Alerts: Buzz only"); break;
case 2: sprintf(_alert, "Alerts: Vibe only"); break;
default: sprintf(_alert, "Alerts: Silent"); break;
}
the_mesh.savePrefs();
_need_refresh = true;
#elif defined(PIN_BUZZER)
if (buzzer.isQuiet()) {
buzzer.quiet(false);
notify(UIEventType::ack);
@@ -420,7 +559,7 @@ void UITask::handleButtonTriplePress() {
_node_prefs->buzzer_quiet = buzzer.isQuiet();
the_mesh.savePrefs();
_need_refresh = true;
#endif
#endif
}
void UITask::handleButtonQuadruplePress() {
+8 -1
View File
@@ -14,11 +14,18 @@
#include "Button.h"
#ifdef HAS_DRV2605
#include <helpers/ui/DRV2605Vibration.h>
#endif
class UITask : public AbstractUITask {
DisplayDriver* _display;
SensorManager* _sensors;
#ifdef PIN_BUZZER
genericBuzzer buzzer;
#endif
#ifdef HAS_DRV2605
DRV2605Vibration vibration;
#endif
unsigned long _next_refresh, _auto_off;
NodePrefs* _node_prefs;
@@ -54,7 +61,7 @@ class UITask : public AbstractUITask {
public:
UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
_next_refresh = 0;
ui_started_at = 0;
}
@@ -104,7 +104,7 @@ public:
if (_status[0] == 0) return;
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::primary_txt);
// if (_needs_redraw) {
// _text_width = display.getTextWidth(_status);
+24 -20
View File
@@ -56,24 +56,24 @@ public:
int render(DisplayDriver& display) override {
if (millis() < version_after) {
// meshcore logo
display.setColor(DisplayDriver::BLUE);
display.setColor(UIColor::corp_blue);
int logoWidth = 72;
display.drawXbm(0, 0, meshcore_logo, 72, 36);
} else {
// meshcore website
const char* website = "meshcore.io";
display.setColor(DisplayDriver::LIGHT);
display.setColor(UIColor::primary_txt);
display.setTextSize(1);
uint16_t websiteWidth = display.getTextWidth(website);
display.setCursor((display.width() - websiteWidth) / 2, 9);
display.print(website);
// version info
display.setColor(DisplayDriver::LIGHT);
display.setTextSize(1);
display.drawTextCentered(display.width()/2, 18, _version_info);
display.setColor(UIColor::secondary_txt);
display.setTextSize(1);
display.drawTextCentered(display.width()/2, 27, FIRMWARE_BUILD_DATE);
}
@@ -163,7 +163,7 @@ public:
// display.print(filtered_name);
display.setColor(DisplayDriver::YELLOW);
display.setColor(UIColor::primary_txt);
display.setTextSize(2);
sprintf(tmp, "MSG: %d", _task->getMsgCount());
display.setCursor(0, 10);
@@ -180,19 +180,19 @@ public:
display.drawTextCentered(display.width() / 2, 54, tmp);
#endif
if (_task->hasConnection()) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::warning_txt);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, display.height()-8, "< Connected >");
} else if (the_mesh.getBLEPin() != 0) { // BT pin
display.setColor(DisplayDriver::RED);
display.setColor(UIColor::warning_txt);
display.setTextSize(2);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
display.drawTextCentered(display.width() / 2, display.height()-8, tmp);
}
} else if (_page == HomePage::RECENT) {
the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE);
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::primary_txt);
int y = 8;
for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) {
auto a = &recent[i];
@@ -216,7 +216,7 @@ public:
display.print(tmp);
}
} else if (_page == HomePage::RADIO) {
display.setColor(DisplayDriver::YELLOW);
display.setColor(UIColor::primary_txt);
display.setTextSize(1);
// frequency and spreading factor
display.setCursor(0, 8);
@@ -238,14 +238,14 @@ public:
display.drawTextRightAlign(display.width(), 26, tmp);
} else if (_page == HomePage::BLUETOOTH) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::corp_blue);
display.drawXbm((display.width() - 32) / 2, 8,
_task->isSerialEnabled() ? bluetooth_on : bluetooth_off,
_task->isBluetoothEnabled() ? bluetooth_on : bluetooth_off,
32, 32);
display.setTextSize(1);
// display.drawTextCentered(display.width() / 2, 40 - 11, "toggle: " PRESS_LABEL);
} else if (_page == HomePage::ADVERT) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::corp_blue);
display.drawXbm((display.width() - 32) / 2, 8, advert_icon, 32, 32);
// display.drawTextCentered(display.width() / 2, 40 - 11, "advert: " PRESS_LABEL);
#if ENV_INCLUDE_GPS == 1
@@ -264,9 +264,11 @@ public:
#else
strcpy(buf, gps_state ? "gps on" : "gps off");
#endif
display.setColor(UIColor::primary_txt);
display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) {
// y = y + 8;
display.setColor(UIColor::warning_txt);
display.drawTextLeftAlign(0, y, "Can't access GPS");
} else {
if (!gps_state || !nmea->isValid()) {
@@ -274,6 +276,7 @@ public:
} else {
sprintf(buf, "%d sat", nmea->satellitesCount());
}
display.setColor(UIColor::primary_txt);
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 8;
sprintf(buf, "lat %.4f",
@@ -349,8 +352,10 @@ public:
r.skipData(type);
strcpy(name, "unk"); sprintf(buf, "");
}
display.setColor(UIColor::secondary_txt);
display.setCursor(0, y);
display.print(name);
display.setColor(UIColor::primary_txt);
display.setCursor(
display.width()-display.getTextWidth(buf)-1, y
);
@@ -361,7 +366,7 @@ public:
else sensors_scroll_offset = 0;
#endif
} else if (_page == HomePage::SHUTDOWN) {
display.setColor(DisplayDriver::GREEN);
display.setColor(UIColor::secondary_txt);
display.setTextSize(1);
if (_shutdown_init) {
display.drawTextCentered(display.width() / 2, 20, "hibernating...");
@@ -386,10 +391,10 @@ public:
return true;
}
if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) {
if (_task->isSerialEnabled()) { // toggle Bluetooth on/off
_task->disableSerial();
if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off
_task->disableBluetooth();
} else {
_task->enableSerial();
_task->enableBluetooth();
}
return true;
}
@@ -566,8 +571,7 @@ void UITask::shutdown(bool restart){
if (restart) {
_board->reboot();
} else {
_display->turnOff();
radio_driver.powerOff();
// Power off board including radio, display, GPS and components
_board->powerOff();
}
}
@@ -673,7 +677,7 @@ void UITask::loop() {
_cached_batt_mv,
isBuzzerQuiet(),
getGPSState(),
isSerialEnabled());
isBluetoothEnabled());
bool status_dirty = _statusBar.needsRedraw();
bool content_dirty = (millis() >= _next_refresh && curr);
@@ -693,9 +697,9 @@ void UITask::loop() {
_display->setTextSize(1);
int y = _display->height() / 3;
int p = _display->height() / 32;
_display->setColor(DisplayDriver::DARK);
_display->setColor(UIColor::popup_bkg);
_display->fillRect(p, y, _display->width() - p*2, y);
_display->setColor(DisplayDriver::LIGHT); // draw box border
_display->setColor(UIColor::popup_txt); // draw box border
_display->drawRect(p, y, _display->width() - p*2, y);
_display->drawTextCentered(_display->width() / 2, y + p*3, _alert);
_next_refresh = _alert_expiry; // will need refresh when alert is dismissed
+2 -2
View File
@@ -4,7 +4,7 @@
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/UIScreen.h>
#include <helpers/SensorManager.h>
#include <helpers/BaseSerialInterface.h>
#include <helpers/MultiSerialInterface.h>
#include <Arduino.h>
#include <helpers/sensors/LPPDataHelpers.h>
@@ -71,7 +71,7 @@ class UITask : public AbstractUITask {
public:
UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
next_batt_chck = _next_refresh = 0;
_cached_batt_mv = 0;
ui_started_at = 0;
+166 -33
View File
@@ -22,6 +22,7 @@ KissModem::KissModem(Stream& serial, mesh::LocalIdentity& identity, mesh::RNG& r
_getStatsCallback = nullptr;
_config = {0, 0, 0, 0, 0};
_signal_report_enabled = true;
resetOutputQueue();
}
void KissModem::begin() {
@@ -30,37 +31,168 @@ void KissModem::begin() {
_rx_active = false;
_has_pending_tx = false;
_tx_state = TX_IDLE;
resetOutputQueue();
}
void KissModem::writeByte(uint8_t b) {
if (b == KISS_FEND) {
_serial.write(KISS_FESC);
_serial.write(KISS_TFEND);
} else if (b == KISS_FESC) {
_serial.write(KISS_FESC);
_serial.write(KISS_TFESC);
} else {
_serial.write(b);
void KissModem::resetOutputQueue() {
_tx_frame_head = 0;
_tx_frame_tail = 0;
_tx_frame_count = 0;
_tx_busy_error_pending = false;
_tx_done_pending = false;
_tx_done_result = 0;
}
void KissModem::popTxFrame() {
_tx_frame_head = (uint8_t)((_tx_frame_head + 1) % KISS_TX_FRAME_QUEUE_DEPTH);
_tx_frame_count--;
}
uint16_t KissModem::appendEscapedByte(uint8_t* dest, uint16_t idx, uint16_t max_len, uint8_t b) {
if (b == KISS_FEND || b == KISS_FESC) {
if (idx + 2 > max_len) {
return 0;
}
dest[idx++] = KISS_FESC;
dest[idx++] = (b == KISS_FEND) ? KISS_TFEND : KISS_TFESC;
return idx;
}
if (idx + 1 > max_len) {
return 0;
}
dest[idx++] = b;
return idx;
}
void KissModem::writeFrame(uint8_t type, const uint8_t* data, uint16_t len) {
_serial.write(KISS_FEND);
writeByte(type);
uint16_t KissModem::encodeFrame(uint8_t type, const uint8_t* data, uint16_t len, uint8_t* dest, uint16_t max_len) {
if (max_len < KISS_FRAME_BOUNDARY_BYTES) {
return 0;
}
uint16_t idx = 0;
dest[idx++] = KISS_FEND;
idx = appendEscapedByte(dest, idx, max_len, type);
if (idx == 0) {
return 0;
}
for (uint16_t i = 0; i < len; i++) {
writeByte(data[i]);
idx = appendEscapedByte(dest, idx, max_len, data[i]);
if (idx == 0) {
return 0;
}
}
_serial.write(KISS_FEND);
if (idx + 1 > max_len) {
return 0;
}
dest[idx++] = KISS_FEND;
return idx;
}
void KissModem::writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len) {
_serial.write(KISS_FEND);
writeByte(KISS_CMD_SETHARDWARE);
writeByte(sub_cmd);
for (uint16_t i = 0; i < len; i++) {
writeByte(data[i]);
bool KissModem::tryFlushFrames() {
while (_tx_frame_count > 0) {
const uint8_t idx = _tx_frame_head;
const uint16_t frame_len = _tx_frame_len[idx];
uint16_t written_len = _tx_frame_written[idx];
if (written_len >= frame_len) {
popTxFrame();
continue;
}
const int available = _serial.availableForWrite();
if (available <= 0) {
return false;
}
const uint16_t remaining = frame_len - written_len;
const uint16_t chunk_len = (available < (int)remaining) ? (uint16_t)available : remaining;
if (chunk_len == 0) {
return false;
}
size_t chunk_written = _serial.write(_tx_frame_buf[idx] + written_len, chunk_len);
if (chunk_written == 0) {
return false;
}
written_len += (uint16_t)chunk_written;
_tx_frame_written[idx] = written_len;
if (written_len < frame_len) {
return false;
}
popTxFrame();
}
_serial.write(KISS_FEND);
return true;
}
bool KissModem::queueFrame(uint8_t type, const uint8_t* data, uint16_t len, bool mark_busy_error) {
if (_tx_frame_count >= KISS_TX_FRAME_QUEUE_DEPTH && !tryFlushFrames()) {
if (mark_busy_error) {
_tx_busy_error_pending = true;
}
return false;
}
const uint8_t idx = _tx_frame_tail;
uint16_t frame_len = encodeFrame(type, data, len, _tx_frame_buf[idx], sizeof(_tx_frame_buf[idx]));
if (frame_len == 0) {
return false;
}
_tx_frame_len[idx] = frame_len;
_tx_frame_written[idx] = 0;
_tx_frame_tail = (uint8_t)((_tx_frame_tail + 1) % KISS_TX_FRAME_QUEUE_DEPTH);
_tx_frame_count++;
tryFlushFrames();
return true;
}
bool KissModem::queuePendingBusyError() {
if (!_tx_busy_error_pending) {
return true;
}
const uint8_t err = HW_ERR_TX_BUSY;
if (!queueHardwareFrame(HW_RESP_ERROR, &err, 1, false)) {
return false;
}
_tx_busy_error_pending = false;
return true;
}
bool KissModem::queueHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len, bool mark_busy_error) {
if (len > KISS_MAX_FRAME_SIZE) {
return false;
}
_tx_hw_payload[0] = sub_cmd;
if (len > 0) {
memcpy(_tx_hw_payload + 1, data, len);
}
return queueFrame(KISS_CMD_SETHARDWARE, _tx_hw_payload, len + 1, mark_busy_error);
}
bool KissModem::queuePendingTxDone() {
if (!_tx_done_pending) {
return true;
}
if (!queueHardwareFrame(HW_RESP_TX_DONE, &_tx_done_result, 1, false)) {
return false;
}
_tx_done_pending = false;
return true;
}
void KissModem::setTxDonePending(uint8_t result) {
_tx_done_result = result;
_tx_done_pending = true;
_tx_state = TX_DONE_PENDING;
}
bool KissModem::writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len) {
return queueHardwareFrame(sub_cmd, data, len, true);
}
void KissModem::writeHardwareError(uint8_t error_code) {
@@ -68,6 +200,8 @@ void KissModem::writeHardwareError(uint8_t error_code) {
}
void KissModem::loop() {
tryFlushFrames();
while (_serial.available()) {
uint8_t b = _serial.read();
@@ -106,6 +240,8 @@ void KissModem::loop() {
}
processTx();
tryFlushFrames();
queuePendingBusyError();
}
void KissModem::processFrame() {
@@ -295,10 +431,7 @@ void KissModem::processTx() {
_tx_timer = millis();
_tx_state = TX_SENDING;
} else {
uint8_t result = 0x00;
writeHardwareFrame(HW_RESP_TX_DONE, &result, 1);
_has_pending_tx = false;
_tx_state = TX_IDLE;
setTxDonePending(0x00);
}
}
break;
@@ -306,14 +439,15 @@ void KissModem::processTx() {
case TX_SENDING:
if (_radio.isSendComplete()) {
_radio.onSendFinished();
uint8_t result = 0x01;
writeHardwareFrame(HW_RESP_TX_DONE, &result, 1);
_has_pending_tx = false;
_tx_state = TX_IDLE;
setTxDonePending(0x01);
} else if (millis() - _tx_timer >= _radio.getEstAirtimeFor(_pending_tx_len) * KISS_TX_TIMEOUT_FACTOR) {
_radio.onSendFinished();
uint8_t result = 0x00;
writeHardwareFrame(HW_RESP_TX_DONE, &result, 1);
setTxDonePending(0x00);
}
break;
case TX_DONE_PENDING:
if (queuePendingTxDone()) {
_has_pending_tx = false;
_tx_state = TX_IDLE;
}
@@ -322,8 +456,7 @@ void KissModem::processTx() {
}
void KissModem::onPacketReceived(int8_t snr, int8_t rssi, const uint8_t* packet, uint16_t len) {
writeFrame(KISS_CMD_DATA, packet, len);
if (_signal_report_enabled) {
if (queueFrame(KISS_CMD_DATA, packet, len) && _signal_report_enabled) {
uint8_t meta[2] = { (uint8_t)snr, (uint8_t)rssi };
writeHardwareFrame(HW_RESP_RX_META, meta, 2);
}
+32 -4
View File
@@ -13,6 +13,14 @@
#define KISS_MAX_FRAME_SIZE 512
#define KISS_MAX_PACKET_SIZE 255
#define KISS_FRAME_BOUNDARY_BYTES 2
#define KISS_TYPE_BYTES 1
#define KISS_HW_SUBCMD_BYTES 1
#define KISS_MAX_ESCAPABLE_BYTES (KISS_MAX_FRAME_SIZE + KISS_TYPE_BYTES + KISS_HW_SUBCMD_BYTES)
#define KISS_MAX_ESCAPED_PAYLOAD_SIZE (2 * KISS_MAX_ESCAPABLE_BYTES)
#define KISS_MAX_ENCODED_FRAME_SIZE (KISS_FRAME_BOUNDARY_BYTES + KISS_MAX_ESCAPED_PAYLOAD_SIZE)
#define KISS_TX_FRAME_QUEUE_DEPTH 2
#define KISS_HW_MAX_PAYLOAD_SIZE (KISS_MAX_FRAME_SIZE + KISS_HW_SUBCMD_BYTES)
#define KISS_CMD_DATA 0x00
#define KISS_CMD_TXDELAY 0x01
@@ -94,7 +102,8 @@ enum TxState {
TX_WAIT_CLEAR,
TX_SLOT_WAIT,
TX_DELAY,
TX_SENDING
TX_SENDING,
TX_DONE_PENDING
};
class KissModem {
@@ -130,10 +139,28 @@ class KissModem {
RadioConfig _config;
bool _signal_report_enabled;
uint8_t _tx_frame_buf[KISS_TX_FRAME_QUEUE_DEPTH][KISS_MAX_ENCODED_FRAME_SIZE];
uint16_t _tx_frame_len[KISS_TX_FRAME_QUEUE_DEPTH];
uint16_t _tx_frame_written[KISS_TX_FRAME_QUEUE_DEPTH];
uint8_t _tx_frame_head;
uint8_t _tx_frame_tail;
uint8_t _tx_frame_count;
bool _tx_busy_error_pending;
bool _tx_done_pending;
uint8_t _tx_done_result;
uint8_t _tx_hw_payload[KISS_HW_MAX_PAYLOAD_SIZE];
void writeByte(uint8_t b);
void writeFrame(uint8_t type, const uint8_t* data, uint16_t len);
void writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len);
static uint16_t appendEscapedByte(uint8_t* dest, uint16_t idx, uint16_t max_len, uint8_t b);
static uint16_t encodeFrame(uint8_t type, const uint8_t* data, uint16_t len, uint8_t* dest, uint16_t max_len);
void resetOutputQueue();
void popTxFrame();
bool tryFlushFrames();
bool queueFrame(uint8_t type, const uint8_t* data, uint16_t len, bool mark_busy_error = true);
bool queuePendingBusyError();
bool queueHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len, bool mark_busy_error);
bool queuePendingTxDone();
void setTxDonePending(uint8_t result);
bool writeHardwareFrame(uint8_t sub_cmd, const uint8_t* data, uint16_t len);
void writeHardwareError(uint8_t error_code);
void processFrame();
void handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint16_t len);
@@ -182,4 +209,5 @@ public:
bool isTxBusy() const { return _tx_state != TX_IDLE; }
/** True only when radio is actually transmitting; use to skip recvRaw in main loop. */
bool isActuallyTransmitting() const { return _tx_state == TX_SENDING; }
bool isHostOutputBackedUp() const { return _tx_frame_count > 0 || _tx_busy_error_pending || _tx_done_pending; }
};
+7 -1
View File
@@ -20,6 +20,8 @@
#define NOISE_FLOOR_CALIB_INTERVAL_MS 2000
#define AGC_RESET_INTERVAL_MS 30000
#define USB_TX_TIMEOUT_MS 50
#define USB_TX_BUFFER_SIZE 1024
StdRNG rng;
mesh::LocalIdentity identity;
@@ -111,6 +113,10 @@ void setup() {
uint32_t start = millis();
while (!Serial && millis() - start < 3000) delay(10);
delay(100);
#if defined(ESP32) && ARDUINO_USB_MODE
Serial.setTxTimeoutMs(USB_TX_TIMEOUT_MS);
Serial.setTxBufferSize(USB_TX_BUFFER_SIZE);
#endif
modem = new KissModem(Serial, identity, rng, radio_driver, board, sensors);
#endif
@@ -126,7 +132,7 @@ void setup() {
void loop() {
modem->loop();
if (!modem->isActuallyTransmitting()) {
if (!modem->isActuallyTransmitting() && !modem->isHostOutputBackedUp()) {
if (!modem->isTxBusy()) {
if ((uint32_t)(millis() - next_agc_reset_ms) >= AGC_RESET_INTERVAL_MS) {
radio_driver.resetAGC();
+18 -17
View File
@@ -147,11 +147,10 @@ uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secr
uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
// request data has: {reply-path-len}{reply-path}
reply_path_len = *data & 63;
reply_path_hash_size = (*data >> 6) + 1;
data++;
reply_path_len = *data++;
if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding
memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
mesh::Packet::writePath(reply_path, data, reply_path_len);
// data += (uint8_t)reply_path_len * reply_path_hash_size;
memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
@@ -166,11 +165,10 @@ uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t send
uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
// request data has: {reply-path-len}{reply-path}
reply_path_len = *data & 63;
reply_path_hash_size = (*data >> 6) + 1;
data++;
reply_path_len = *data++;
if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding
memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
mesh::Packet::writePath(reply_path, data, reply_path_len);
// data += (uint8_t)reply_path_len * reply_path_hash_size;
memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
@@ -186,11 +184,10 @@ uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender
uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
// request data has: {reply-path-len}{reply-path}
reply_path_len = *data & 63;
reply_path_hash_size = (*data >> 6) + 1;
data++;
reply_path_len = *data++;
if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding
memcpy(reply_path, data, ((uint8_t)reply_path_len) * reply_path_hash_size);
mesh::Packet::writePath(reply_path, data, reply_path_len);
// data += (uint8_t)reply_path_len * reply_path_hash_size;
memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
@@ -574,7 +571,7 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
data[len] = 0; // ensure null terminator
uint8_t reply_len;
reply_path_len = -1;
reply_path_len = 0xFF;
if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood());
} else if (data[4] == ANON_REQ_TYPE_REGIONS && packet->isRouteDirect()) {
@@ -594,13 +591,12 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
} else if (reply_path_len < 0) {
} else if (reply_path_len == 0xFF) {
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
} else {
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
uint8_t path_len = ((reply_path_hash_size - 1) << 6) | (reply_path_len & 63);
if (reply) sendDirect(reply, reply_path, path_len, SERVER_RESPONSE_DELAY);
if (reply) sendDirect(reply, reply_path, reply_path_len, SERVER_RESPONSE_DELAY);
}
}
}
@@ -872,7 +868,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
#endif
// defaults
memset(&_prefs, 0, sizeof(_prefs));
_prefs.airtime_factor = 1.0;
_prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
_prefs.tx_delay_factor = 0.5f; // was 0.25f
@@ -1065,6 +1060,12 @@ bool MyMesh::setRxBoostedGain(bool enable) {
return radio_driver.setRxBoostedGainMode(enable);
}
#if defined(USE_LR2021)
bool MyMesh::configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) {
return radio_driver.configSideDetectors(sideDetSFs, num, bw);
}
#endif
void MyMesh::formatNeighborsReply(char *reply) {
char *dp = reply;
+8 -4
View File
@@ -11,6 +11,7 @@
#include <LittleFS.h>
#elif defined(ESP32)
#include <SPIFFS.h>
using File = fs::File;
#endif
#ifdef WITH_RS232_BRIDGE
@@ -69,11 +70,11 @@ struct NeighbourInfo {
};
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "6 Jun 2026"
#define FIRMWARE_BUILD_DATE "9 Aug 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "v1.16.0"
#define FIRMWARE_VERSION "v1.17.0"
#endif
#define FIRMWARE_ROLE "repeater"
@@ -91,8 +92,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
CommonCLI _cli;
uint8_t reply_data[MAX_PACKET_PAYLOAD];
uint8_t reply_path[MAX_PATH_SIZE];
int8_t reply_path_len;
uint8_t reply_path_hash_size;
uint8_t reply_path_len;
TransportKeyStore key_store;
RegionMap region_map, temp_map;
RegionEntry* load_stack[8];
@@ -254,4 +254,8 @@ public:
bool setRxBoostedGain(bool enable) override;
#if defined(USE_LR2021)
virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) override;
#endif
};
+54 -31
View File
@@ -1,4 +1,5 @@
#include "UITask.h"
#include "target.h"
#include <Arduino.h>
#include <helpers/CommonCLI.h>
@@ -9,6 +10,8 @@
#define AUTO_OFF_MILLIS 20000 // 20 seconds
#define BOOT_SCREEN_MILLIS 4000 // 4 seconds
#define POWEROFF_DELAY 3000
// 'meshcore', 128x13px
static const uint8_t meshcore_logo [] PROGMEM = {
0x3c, 0x01, 0xe3, 0xff, 0xc7, 0xff, 0x8f, 0x03, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe,
@@ -29,9 +32,14 @@ static const uint8_t meshcore_logo [] PROGMEM = {
void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version) {
_prevBtnState = HIGH;
_auto_off = millis() + AUTO_OFF_MILLIS;
_started_at = millis();
_node_prefs = node_prefs;
_display->turnOn();
#if defined(PIN_USER_BTN) && defined(DISPLAY_CLASS)
user_btn.begin();
#endif
// strip off dash and commit hash by changing dash to null terminator
// e.g: v1.2.3-abcdef -> v1.2.3
char *version = strdup(firmware_version);
@@ -47,42 +55,50 @@ void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* fi
void UITask::renderCurrScreen() {
char tmp[80];
if (millis() < BOOT_SCREEN_MILLIS) { // boot screen
if (millis() < _started_at + BOOT_SCREEN_MILLIS) { // boot screen
// meshcore logo
_display->setColor(DisplayDriver::BLUE);
_display->setColor(UIColor::corp_blue);
int logoWidth = 128;
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// meshcore website
const char* website = "https://meshcore.io";
_display->setColor(DisplayDriver::LIGHT);
_display->setColor(UIColor::primary_txt);
_display->setTextSize(1);
uint16_t websiteWidth = _display->getTextWidth(website);
_display->setCursor((_display->width() - websiteWidth) / 2, 22);
_display->print(website);
_display->drawTextCentered(_display->width() / 2, 22, website);
// version info
_display->setColor(DisplayDriver::LIGHT);
_display->setTextSize(1);
uint16_t versionWidth = _display->getTextWidth(_version_info);
_display->setCursor((_display->width() - versionWidth) / 2, 35);
_display->print(_version_info);
_display->drawTextCentered(_display->width() / 2, 35, _version_info);
// node type
const char* node_type = "< Repeater >";
uint16_t typeWidth = _display->getTextWidth(node_type);
_display->setCursor((_display->width() - typeWidth) / 2, 48);
_display->print(node_type);
} else { // home screen
// node name
_display->drawTextCentered(_display->width() / 2, 48, node_type);
} else if (_powering_off_at > 0) {
// meshcore logo
_display->setColor(UIColor::corp_blue);
int logoWidth = 128;
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// meshcore website
const char* website = "https://meshcore.io";
_display->setColor(UIColor::primary_txt);
_display->setTextSize(1);
_display->drawTextCentered(_display->width()/ 2, 22, website);
// Powering off
const char* poweroff_string = "Turning OFF";
uint16_t poffWidth = _display->getTextWidth(poweroff_string);
_display->setCursor((_display->width() - poffWidth) / 2, 48);
_display->drawTextCentered(_display->width()/2, 48, poweroff_string);
} else {
_display->setCursor(0, 0);
_display->setTextSize(1);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
_display->print(_node_prefs->node_name);
// freq / sf
_display->setCursor(0, 20);
_display->setColor(DisplayDriver::YELLOW);
sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf);
_display->print(tmp);
@@ -94,21 +110,19 @@ void UITask::renderCurrScreen() {
}
void UITask::loop() {
#ifdef PIN_USER_BTN
if (millis() >= _next_read) {
int btnState = digitalRead(PIN_USER_BTN);
if (btnState != _prevBtnState) {
if (btnState == USER_BTN_PRESSED) { // pressed?
if (_display->isOn()) {
// TODO: any action ?
} else {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
}
_prevBtnState = btnState;
#if defined(PIN_USER_BTN) && defined(DISPLAY_CLASS)
int ev = user_btn.check();
if (ev == BUTTON_EVENT_CLICK) {
if (_display->isOn()) {
// TODO: any action ?
} else {
_display->turnOn();
}
_next_read = millis() + 200; // 5 reads per second
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
} else if (ev == BUTTON_EVENT_LONG_PRESS) {
_display->turnOn();
Serial.println("Powering Off");
_powering_off_at = millis() + POWEROFF_DELAY;
}
#endif
@@ -124,4 +138,13 @@ void UITask::loop() {
_display->turnOff();
}
}
if (_powering_off_at > 0) { // power off timer armed
#ifdef LED_PIN
digitalWrite(LED_PIN, LED_STATE_ON); // switch on the led until poweroff
#endif
if (millis() > _powering_off_at) {
_board->powerOff(); // should not return
}
}
}
+4 -1
View File
@@ -4,15 +4,18 @@
#include <helpers/CommonCLI.h>
class UITask {
mesh::MainBoard* _board;
DisplayDriver* _display;
unsigned long _next_read, _next_refresh, _auto_off;
int _prevBtnState;
NodePrefs* _node_prefs;
char _version_info[32];
unsigned long _powering_off_at = 0;
unsigned long _started_at = 0;
void renderCurrScreen();
public:
UITask(DisplayDriver& display) : _display(&display) { _next_read = _next_refresh = 0; }
UITask(mesh::MainBoard& board, DisplayDriver& display) : _board(&board), _display(&display) { _next_read = _next_refresh = 0; }
void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version);
void loop();
+45 -2
View File
@@ -5,7 +5,12 @@
#ifdef DISPLAY_CLASS
#include "UITask.h"
static UITask ui_task(display);
static UITask ui_task(board, display);
#endif
#ifdef ETHERNET_ENABLED
#define ETHERNET_CLI_BANNER "MeshCore Repeater CLI"
#include <helpers/nrf52/EthernetCLI.h>
#endif
StdRNG fast_rng;
@@ -18,6 +23,9 @@ void halt() {
}
static char command[160];
#ifdef ETHERNET_ENABLED
static char ethernet_command[160];
#endif
// For power saving
unsigned long POWERSAVING_FIRSTSLEEP_SECS = 120; // The first sleep (if enabled) from boot
@@ -33,6 +41,10 @@ void setup() {
board.begin();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.begin();
#endif
#if defined(MESH_DEBUG) && defined(NRF52_PLATFORM)
// give some extra time for serial to settle so
// boot debug messages can be seen on terminal
@@ -86,6 +98,9 @@ void setup() {
mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
command[0] = 0;
#ifdef ETHERNET_ENABLED
ethernet_command[0] = 0;
#endif
sensors.begin();
@@ -95,6 +110,10 @@ void setup() {
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
#endif
#ifdef ETHERNET_ENABLED
ethernet_start_task();
#endif
// send out initial zero hop Advertisement to the mesh
#if ENABLE_ADVERT_ON_BOOT == 1
the_mesh.sendSelfAdvertisement(16000, false);
@@ -104,6 +123,7 @@ void setup() {
}
void loop() {
// Handle Serial CLI
int len = strlen(command);
while (Serial.available() && len < sizeof(command)-1) {
char c = Serial.read();
@@ -122,7 +142,14 @@ void loop() {
Serial.print('\n');
command[len - 1] = 0; // replace newline with C string null terminator
char reply[160];
reply[0] = 0;
#ifdef ETHERNET_ENABLED
if (!ethernet_handle_command(command, reply)) {
the_mesh.handleCommand(0, command, reply);
}
#else
the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
#endif
if (reply[0]) {
Serial.print(" -> "); Serial.println(reply);
}
@@ -130,7 +157,20 @@ void loop() {
command[0] = 0; // reset command buffer
}
#if defined(PIN_USER_BTN) && defined(_SEEED_SENSECAP_SOLAR_H_)
#ifdef ETHERNET_ENABLED
ethernet_loop_maintain();
if (ethernet_read_line(ethernet_command, sizeof(ethernet_command))) {
char reply[160];
reply[0] = 0;
if (!ethernet_handle_command(ethernet_command, reply)) {
the_mesh.handleCommand(0, ethernet_command, reply);
}
ethernet_send_reply(reply);
ethernet_command[0] = 0;
}
#endif
#if defined(PIN_USER_BTN) && defined(_SEEED_SENSECAP_SOLAR_H_) && !defined(DISPLAY_CLASS)
// Hold the user button to power off the SenseCAP Solar repeater.
int btnState = digitalRead(PIN_USER_BTN);
if (btnState == LOW) {
@@ -152,6 +192,9 @@ void loop() {
#endif
rtc_clock.tick();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.loop();
#endif
if (the_mesh.getNodePrefs()->powersaving_enabled && !the_mesh.hasPendingWork()) {
#if defined(NRF52_PLATFORM)
board.sleep(0); // nrf ignores seconds param, sleeps whenever possible
+43 -5
View File
@@ -39,18 +39,35 @@ struct ServerStats {
};
void MyMesh::addPost(ClientInfo *client, const char *postData) {
// TODO: suggested postData format: <title>/<descrption>
posts[next_post_idx].author = client->id; // add to cyclic queue
StrHelper::strncpy(posts[next_post_idx].text, postData, MAX_POST_TEXT_LEN);
storePost(client->id, postData);
}
posts[next_post_idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
void MyMesh::addSystemPost(const char *postData) {
if (!postData || postData[0] == 0) return;
MESH_DEBUG_PRINTLN("room.post: addSystemPost: %s", postData);
storePost(self_id, postData);
}
void MyMesh::storePost(const mesh::Identity &author, const char *postData) {
int idx = next_post_idx;
// TODO: suggested postData format: <title>/<descrption>
posts[idx].author = author; // add to cyclic queue
StrHelper::strncpy(posts[idx].text, postData, MAX_POST_TEXT_LEN);
posts[idx].post_timestamp = getRTCClock()->getCurrentTimeUnique();
MESH_DEBUG_PRINTLN("room.post: storePost idx=%d text=%s", idx, posts[idx].text);
MESH_DEBUG_PRINTLN("room.post: timestamp=%u", posts[idx].post_timestamp);
next_post_idx = (next_post_idx + 1) % MAX_UNSYNCED_POSTS;
next_push = futureMillis(PUSH_NOTIFY_DELAY_MILLIS);
_num_posted++; // stats
MESH_DEBUG_PRINTLN("room.post: next_post_idx=%d num_posted=%d push scheduled", next_post_idx, _num_posted);
}
void MyMesh::pushPostToClient(ClientInfo *client, PostInfo &post) {
MESH_DEBUG_PRINTLN("room.post: pushPostToClient text=%s", post.text);
int len = 0;
memcpy(&reply_data[len], &post.post_timestamp, 4);
len += 4; // this is a PAST timestamp... but should be accepted by client
@@ -628,7 +645,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
recv_pkt_region = NULL;
// defaults
memset(&_prefs, 0, sizeof(_prefs));
_prefs.airtime_factor = 1.0;
_prefs.rx_delay_base = 0.0f; // off by default, was 10.0
_prefs.tx_delay_factor = 0.5f; // was 0.25f;
@@ -658,6 +674,14 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
_prefs.gps_enabled = 0;
_prefs.gps_interval = 0;
_prefs.advert_loc_policy = ADVERT_LOC_PREFS;
#if defined(USE_SX1262) || defined(USE_SX1268)
#ifdef SX126X_RX_BOOSTED_GAIN
_prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN;
#else
_prefs.rx_boosted_gain = 1; // enabled by default;
#endif
#endif
_prefs.radio_fem_rxgain = 1;
next_post_idx = 0;
@@ -700,6 +724,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
radio_driver.setTxPower(_prefs.tx_power_dbm);
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
board.setLoRaFemLnaEnabled(_prefs.radio_fem_rxgain);
updateAdvertTimer();
@@ -807,6 +832,10 @@ void MyMesh::setTxPower(int8_t power_dbm) {
radio_driver.setTxPower(power_dbm);
}
bool MyMesh::setRxBoostedGain(bool enable) {
return radio_driver.setRxBoostedGainMode(enable);
}
void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
IdentityStore store(*_fs, "");
@@ -936,6 +965,15 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
Serial.printf("\n");
}
reply[0] = 0;
} else if (strncmp(command, "room.post", 9) == 0) {
char* msg = command + 9;
while (*msg == ' ') msg++;
if (*msg == 0) {
snprintf(reply, MAX_POST_TEXT_LEN, "ERR empty message");
} else {
addSystemPost(msg);
snprintf(reply, MAX_POST_TEXT_LEN, "OK");
}
} else{
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
}
+5 -2
View File
@@ -27,11 +27,11 @@
/* ------------------------------ Config -------------------------------- */
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "6 Jun 2026"
#define FIRMWARE_BUILD_DATE "9 Aug 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "v1.16.0"
#define FIRMWARE_VERSION "v1.17.0"
#endif
#ifndef LORA_FREQ
@@ -119,6 +119,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
int matching_peer_indexes[MAX_CLIENTS];
void addPost(ClientInfo* client, const char* postData);
void storePost(const mesh::Identity& author, const char* postData);
void pushPostToClient(ClientInfo* client, PostInfo& post);
uint8_t getUnsyncedCount(ClientInfo* client);
bool processAck(const uint8_t *data);
@@ -176,6 +177,7 @@ public:
MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables);
void begin(FILESYSTEM* fs);
void addSystemPost(const char* postData);
const char* getFirmwareVer() override { return FIRMWARE_VERSION; }
const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; }
@@ -206,6 +208,7 @@ public:
void dumpLogFile() override;
void setTxPower(int8_t power_dbm) override;
bool setRxBoostedGain(bool enable) override;
void formatNeighborsReply(char *reply) override {
strcpy(reply, "not supported");
+3 -5
View File
@@ -49,20 +49,19 @@ void UITask::renderCurrScreen() {
char tmp[80];
if (millis() < BOOT_SCREEN_MILLIS) { // boot screen
// meshcore logo
_display->setColor(DisplayDriver::BLUE);
_display->setColor(UIColor::corp_blue);
int logoWidth = 128;
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// meshcore website
const char* website = "https://meshcore.io";
_display->setColor(DisplayDriver::LIGHT);
_display->setColor(UIColor::primary_txt);
_display->setTextSize(1);
uint16_t websiteWidth = _display->getTextWidth(website);
_display->setCursor((_display->width() - websiteWidth) / 2, 22);
_display->print(website);
// version info
_display->setColor(DisplayDriver::LIGHT);
_display->setTextSize(1);
uint16_t versionWidth = _display->getTextWidth(_version_info);
_display->setCursor((_display->width() - versionWidth) / 2, 35);
@@ -77,12 +76,11 @@ void UITask::renderCurrScreen() {
// node name
_display->setCursor(0, 0);
_display->setTextSize(1);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
_display->print(_node_prefs->node_name);
// freq / sf
_display->setCursor(0, 20);
_display->setColor(DisplayDriver::YELLOW);
sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf);
_display->print(tmp);
+42
View File
@@ -3,6 +3,11 @@
#include "MyMesh.h"
#ifdef ETHERNET_ENABLED
#define ETHERNET_CLI_BANNER "MeshCore Room Server CLI"
#include <helpers/nrf52/EthernetCLI.h>
#endif
#ifdef DISPLAY_CLASS
#include "UITask.h"
static UITask ui_task(display);
@@ -17,6 +22,9 @@ void halt() {
}
static char command[MAX_POST_TEXT_LEN+1];
#ifdef ETHERNET_ENABLED
static char ethernet_command[MAX_POST_TEXT_LEN+1];
#endif
void setup() {
Serial.begin(115200);
@@ -24,6 +32,10 @@ void setup() {
board.begin();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.begin();
#endif
#ifdef DISPLAY_CLASS
if (display.begin()) {
display.startFrame();
@@ -67,6 +79,9 @@ void setup() {
mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
command[0] = 0;
#ifdef ETHERNET_ENABLED
ethernet_command[0] = 0;
#endif
sensors.begin();
@@ -76,6 +91,10 @@ void setup() {
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
#endif
#ifdef ETHERNET_ENABLED
ethernet_start_task();
#endif
// send out initial zero hop Advertisement to the mesh
#if ENABLE_ADVERT_ON_BOOT == 1
the_mesh.sendSelfAdvertisement(16000, false);
@@ -101,7 +120,14 @@ void loop() {
if (len > 0 && command[len - 1] == '\r') { // received complete line
command[len - 1] = 0; // replace newline with C string null terminator
char reply[160];
reply[0] = 0;
#ifdef ETHERNET_ENABLED
if (!ethernet_handle_command(command, reply)) {
the_mesh.handleCommand(0, command, reply);
}
#else
the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial!
#endif
if (reply[0]) {
Serial.print(" -> "); Serial.println(reply);
}
@@ -109,10 +135,26 @@ void loop() {
command[0] = 0; // reset command buffer
}
#ifdef ETHERNET_ENABLED
ethernet_loop_maintain();
if (ethernet_read_line(ethernet_command, sizeof(ethernet_command))) {
char reply[160];
reply[0] = 0;
if (!ethernet_handle_command(ethernet_command, reply)) {
the_mesh.handleCommand(0, ethernet_command, reply);
}
ethernet_send_reply(reply);
ethernet_command[0] = 0;
}
#endif
the_mesh.loop();
sensors.loop();
#ifdef DISPLAY_CLASS
ui_task.loop();
#endif
rtc_clock.tick();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.loop();
#endif
}
+7
View File
@@ -560,6 +560,10 @@ void setup() {
board.begin();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.begin();
#endif
if (!radio_init()) { halt(); }
fast_rng.begin(radio_driver.getRngSeed());
@@ -591,4 +595,7 @@ void setup() {
void loop() {
the_mesh.loop();
rtc_clock.tick();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.loop();
#endif
}
-1
View File
@@ -710,7 +710,6 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise
set_radio_at = revert_radio_at = 0;
// defaults
memset(&_prefs, 0, sizeof(_prefs));
_prefs.airtime_factor = 1.0;
_prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
_prefs.tx_delay_factor = 0.5f; // was 0.25f
+2 -2
View File
@@ -34,11 +34,11 @@
#define PERM_RECV_ALERTS_HI (1 << 7) // high priority alerts
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "6 Jun 2026"
#define FIRMWARE_BUILD_DATE "9 Aug 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "v1.16.0"
#define FIRMWARE_VERSION "v1.17.0"
#endif
#define FIRMWARE_ROLE "sensor"
+3 -5
View File
@@ -49,20 +49,19 @@ void UITask::renderCurrScreen() {
char tmp[80];
if (millis() < BOOT_SCREEN_MILLIS) { // boot screen
// meshcore logo
_display->setColor(DisplayDriver::BLUE);
_display->setColor(UIColor::corp_blue);
int logoWidth = 128;
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// meshcore website
const char* website = "https://meshcore.io";
_display->setColor(DisplayDriver::LIGHT);
_display->setColor(UIColor::primary_txt);
_display->setTextSize(1);
uint16_t websiteWidth = _display->getTextWidth(website);
_display->setCursor((_display->width() - websiteWidth) / 2, 22);
_display->print(website);
// version info
_display->setColor(DisplayDriver::LIGHT);
_display->setTextSize(1);
uint16_t versionWidth = _display->getTextWidth(_version_info);
_display->setCursor((_display->width() - versionWidth) / 2, 35);
@@ -77,12 +76,11 @@ void UITask::renderCurrScreen() {
// node name
_display->setCursor(0, 0);
_display->setTextSize(1);
_display->setColor(DisplayDriver::GREEN);
_display->setColor(UIColor::primary_txt);
_display->print(_node_prefs->node_name);
// freq / sf
_display->setCursor(0, 20);
_display->setColor(DisplayDriver::YELLOW);
sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf);
_display->print(tmp);
+7
View File
@@ -58,6 +58,10 @@ void setup() {
board.begin();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.begin();
#endif
#ifdef DISPLAY_CLASS
if (display.begin()) {
display.startFrame();
@@ -147,4 +151,7 @@ void loop() {
ui_task.loop();
#endif
rtc_clock.tick();
#ifdef HAS_EXTERNAL_WATCHDOG
external_watchdog.loop();
#endif
}
+22 -3
View File
@@ -19,7 +19,8 @@ monitor_speed = 115200
lib_deps =
SPI
Wire
jgromes/RadioLib @ ^7.6.0
;jgromes/RadioLib @ ^7.7.1
https://github.com/jgromes/RadioLib.git#6d8934836678d8894e3d556550475b37dce3e2b6
rweather/Crypto @ ^0.4.0
adafruit/RTClib @ ^2.1.3
melopero/Melopero RV3028 @ ^1.1.0
@@ -90,16 +91,17 @@ build_flags = ${arduino_base.build_flags}
-D NRF52_PLATFORM
-D LFS_NO_ASSERT=1
-D EXTRAFS=1
-D USE_CC310_HW_CRYPTO=1
lib_deps =
${arduino_base.lib_deps}
https://github.com/oltaco/CustomLFS#0.2.2
https://github.com/oltaco/CustomLFS#0.2.3
; ----------------- RP2040 ---------------------
[rp2040_base]
extends = arduino_base
upload_protocol = picotool
board_build.core = earlephilhower
platform = https://github.com/maxgerhardt/platform-raspberrypi.git#4e22a0d ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9
platform = https://github.com/maxgerhardt/platform-raspberrypi.git ; framework-arduinopico @ 1.50600.0+sha.6a1d13e9
build_flags = ${arduino_base.build_flags}
-D RP2040_PLATFORM
@@ -162,9 +164,26 @@ build_flags = -std=c++17
-I src
-I test/mocks
test_build_src = yes
test_ignore = test_kiss_modem
build_src_filter =
-<*>
+<../src/Utils.cpp>
+<../src/Packet.cpp>
+<../src/helpers/ConfigSerializer.cpp>
lib_deps =
google/googletest @ 1.17.0
[env:native_kiss_modem]
platform = native
test_framework = googletest
build_flags = -std=c++17
-I test/mocks
-I src
-I examples/kiss_modem
test_build_src = yes
test_filter = test_kiss_modem
build_src_filter =
-<*>
+<../examples/kiss_modem/KissModem.cpp>
lib_deps =
google/googletest @ 1.17.0
+17 -1
View File
@@ -4,6 +4,11 @@
#include <ed_25519.h>
#include <Ed25519.h>
#ifdef USE_CC310_HW_CRYPTO
#include <Adafruit_nRFCrypto.h>
#include "nrf_cc310/include/crys_ec_edw_api.h"
#endif
namespace mesh {
Identity::Identity() {
@@ -15,7 +20,18 @@ Identity::Identity(const char* pub_hex) {
}
bool Identity::verify(const uint8_t* sig, const uint8_t* message, int msg_len) const {
#if 0
#ifdef USE_CC310_HW_CRYPTO
// nRF52840 CryptoCell CC310 hardware Ed25519 verification. The software
// implementations need ~3KB of stack (which can overflow the Adafruit core's
// 4KB loop task stack from the advert receive path); the hardware path
// needs much less, around 600-700bytes. The CC310 workspace is static, faster,
// should save power at scale as well.
static CRYS_ECEDW_TempBuff_t cc310_tmp;
CRYSError_t rc = CRYS_ECEDW_Verify((uint8_t*)sig, CRYS_ECEDW_SIGNATURE_BYTES,
(uint8_t*)pub_key, CRYS_ECEDW_MOD_SIZE_IN_BYTES,
(uint8_t*)message, (size_t)msg_len, &cc310_tmp);
return rc == CRYS_OK;
#elif 0
// NOTE: memory corruption bug was found in this function!!
return ed25519_verify(sig, message, msg_len, pub_key);
#else
+85 -1
View File
@@ -2,6 +2,13 @@
#include <AES.h>
#include <SHA256.h>
#ifdef USE_CC310_HW_CRYPTO
#include <Adafruit_nRFCrypto.h>
#include "nrf_cc310/include/crys_hash.h"
#include "nrf_cc310/include/crys_hmac.h"
#include "nrf_cc310/include/ssi_aes.h"
#endif
#ifdef ARDUINO
#include <Arduino.h>
#endif
@@ -15,19 +22,52 @@ uint32_t RNG::nextInt(uint32_t _min, uint32_t _max) {
}
void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* msg, int msg_len) {
#ifdef USE_CC310_HW_CRYPTO
static CRYS_HASH_Result_t result;
CRYS_HASH(CRYS_HASH_SHA256_mode, (uint8_t*)msg, (size_t)msg_len, result);
memcpy(hash, result, hash_len);
#else
SHA256 sha;
sha.update(msg, msg_len);
sha.finalize(hash, hash_len);
#endif
}
void Utils::sha256(uint8_t *hash, size_t hash_len, const uint8_t* frag1, int frag1_len, const uint8_t* frag2, int frag2_len) {
#ifdef USE_CC310_HW_CRYPTO
static CRYS_HASHUserContext_t ctx;
static CRYS_HASH_Result_t result;
CRYS_HASH_Init(&ctx, CRYS_HASH_SHA256_mode);
CRYS_HASH_Update(&ctx, (uint8_t*)frag1, (size_t)frag1_len);
CRYS_HASH_Update(&ctx, (uint8_t*)frag2, (size_t)frag2_len);
CRYS_HASH_Finish(&ctx, result);
memcpy(hash, result, hash_len);
#else
SHA256 sha;
sha.update(frag1, frag1_len);
sha.update(frag2, frag2_len);
sha.finalize(hash, hash_len);
#endif
}
int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) {
#ifdef USE_CC310_HW_CRYPTO
static SaSiAesUserContext_t ctx;
SaSiAesUserKeyData_t keyData = { (uint8_t*)shared_secret, CIPHER_KEY_SIZE };
uint8_t* dp = dest;
const uint8_t* sp = src;
size_t dummy_out = 0;
SaSi_AesInit(&ctx, SASI_AES_DECRYPT, SASI_AES_MODE_ECB, SASI_AES_PADDING_NONE);
SaSi_AesSetKey(&ctx, SASI_AES_USER_KEY, &keyData, sizeof(keyData));
while (sp - src < src_len) {
SaSi_AesBlock(&ctx, (uint8_t*)sp, 16, dp);
dp += 16; sp += 16;
}
SaSi_AesFinish(&ctx, 0, NULL, 0, NULL, &dummy_out);
SaSi_AesFree(&ctx);
return sp - src;
#else
AES128 aes;
uint8_t* dp = dest;
const uint8_t* sp = src;
@@ -39,9 +79,32 @@ int Utils::decrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s
}
return sp - src; // will always be multiple of 16
#endif
}
int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) {
#ifdef USE_CC310_HW_CRYPTO
static SaSiAesUserContext_t ctx;
SaSiAesUserKeyData_t keyData = { (uint8_t*)shared_secret, CIPHER_KEY_SIZE };
uint8_t* dp = dest;
size_t dummy_out = 0;
SaSi_AesInit(&ctx, SASI_AES_ENCRYPT, SASI_AES_MODE_ECB, SASI_AES_PADDING_NONE);
SaSi_AesSetKey(&ctx, SASI_AES_USER_KEY, &keyData, sizeof(keyData));
while (src_len >= 16) {
SaSi_AesBlock(&ctx, (uint8_t*)src, 16, dp);
dp += 16; src += 16; src_len -= 16;
}
if (src_len > 0) { // remaining partial block — zero-pad to 16 bytes
uint8_t tmp[16] = {};
memcpy(tmp, src, src_len);
SaSi_AesBlock(&ctx, tmp, 16, dp);
dp += 16;
}
SaSi_AesFinish(&ctx, 0, NULL, 0, NULL, &dummy_out);
SaSi_AesFree(&ctx);
return dp - dest;
#else
AES128 aes;
uint8_t* dp = dest;
@@ -58,15 +121,25 @@ int Utils::encrypt(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* s
dp += 16;
}
return dp - dest; // will always be multiple of 16
#endif
}
int Utils::encryptThenMAC(const uint8_t* shared_secret, uint8_t* dest, const uint8_t* src, int src_len) {
int enc_len = encrypt(shared_secret, dest + CIPHER_MAC_SIZE, src, src_len);
#ifdef USE_CC310_HW_CRYPTO
static CRYS_HMACUserContext_t hmac_ctx;
static CRYS_HASH_Result_t hmac_result;
CRYS_HMAC_Init(&hmac_ctx, CRYS_HASH_SHA256_mode, (uint8_t*)shared_secret, PUB_KEY_SIZE);
CRYS_HMAC_Update(&hmac_ctx, dest + CIPHER_MAC_SIZE, enc_len);
CRYS_HMAC_Finish(&hmac_ctx, hmac_result);
memcpy(dest, hmac_result, CIPHER_MAC_SIZE);
#else
SHA256 sha;
sha.resetHMAC(shared_secret, PUB_KEY_SIZE);
sha.update(dest + CIPHER_MAC_SIZE, enc_len);
sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, dest, CIPHER_MAC_SIZE);
#endif
return CIPHER_MAC_SIZE + enc_len;
}
@@ -75,12 +148,23 @@ int Utils::MACThenDecrypt(const uint8_t* shared_secret, uint8_t* dest, const uin
if (src_len <= CIPHER_MAC_SIZE) return 0; // invalid src bytes
uint8_t hmac[CIPHER_MAC_SIZE];
#ifdef USE_CC310_HW_CRYPTO
{
static CRYS_HMACUserContext_t hmac_ctx;
static CRYS_HASH_Result_t hmac_result;
CRYS_HMAC_Init(&hmac_ctx, CRYS_HASH_SHA256_mode, (uint8_t*)shared_secret, PUB_KEY_SIZE);
CRYS_HMAC_Update(&hmac_ctx, (uint8_t*)(src + CIPHER_MAC_SIZE), src_len - CIPHER_MAC_SIZE);
CRYS_HMAC_Finish(&hmac_ctx, hmac_result);
memcpy(hmac, hmac_result, CIPHER_MAC_SIZE);
}
#else
{
SHA256 sha;
sha.resetHMAC(shared_secret, PUB_KEY_SIZE);
sha.update(src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE);
sha.finalizeHMAC(shared_secret, PUB_KEY_SIZE, hmac, CIPHER_MAC_SIZE);
}
#endif
if (memcmp(hmac, src, CIPHER_MAC_SIZE) == 0) {
return decrypt(shared_secret, dest, src + CIPHER_MAC_SIZE, src_len - CIPHER_MAC_SIZE);
}
@@ -150,4 +234,4 @@ int Utils::parseTextParts(char* text, const char* parts[], int max_num, char sep
return num;
}
}
}
+8 -6
View File
@@ -1,4 +1,5 @@
#include <helpers/AdvertDataHelpers.h>
#include <helpers/UTF8Helpers.h>
uint8_t AdvertDataBuilder::encodeTo(uint8_t app_data[]) {
app_data[0] = _type;
@@ -16,11 +17,12 @@
app_data[0] |= ADV_FEAT2_MASK;
memcpy(&app_data[i], &_extra2, 2); i += 2;
}
if (_name && *_name != 0) {
app_data[0] |= ADV_NAME_MASK;
const char* sp = _name;
while (*sp && i < MAX_ADVERT_DATA_SIZE) {
app_data[i++] = *sp++;
if (_name && *_name != 0) {
size_t name_len = mesh::validUtf8PrefixLength(_name, MAX_ADVERT_DATA_SIZE - i);
if (name_len > 0) {
app_data[0] |= ADV_NAME_MASK;
memcpy(&app_data[i], _name, name_len);
i += name_len;
}
}
return i;
@@ -84,4 +86,4 @@ void AdvertTimeHelper::formatRelativeTimeDiff(char dest[], int32_t seconds_from_
}
}
}
}
}
+1
View File
@@ -42,6 +42,7 @@ void AutoDiscoverRTCClock::begin(TwoWire& wire) {
}
if (i2c_probe(wire, PCF8563_ADDRESS)) {
MESH_DEBUG_PRINTLN("PCF8563: Found");
rtc_8563_success = rtc_8563.begin(&wire);
}
+1
View File
@@ -14,6 +14,7 @@ public:
virtual bool isEnabled() const = 0;
virtual bool isConnected() const = 0;
virtual void loop() {};
virtual bool isWriteBusy() const = 0;
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;
+54 -64
View File
@@ -28,16 +28,25 @@ static bool isValidName(const char *n) {
}
void CommonCLI::loadPrefs(FILESYSTEM* fs) {
if (fs->exists("/com_prefs")) {
loadPrefsInt(fs, "/com_prefs"); // new filename
} else if (fs->exists("/node_prefs")) {
loadPrefsInt(fs, "/node_prefs");
savePrefs(fs); // save to new filename
fs->remove("/node_prefs"); // remove old
if (fs->exists("/prefs.json")) {
#if defined(RP2040_PLATFORM)
File file = fs->open("/prefs.json", "r");
#else
File file = fs->open("/prefs.json");
#endif
if (file) {
_prefs->loadSerial(file); // new Serial prefs
file.close();
}
} else if (fs->exists("/com_prefs")) {
loadPrefsInt(fs, "/com_prefs");
if (savePrefs(fs)) { // save to new Serial prefs
// fs->remove("/com_prefs"); // remove old
}
}
}
void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) { // Legacy prefs loader
#if defined(RP2040_PLATFORM)
File file = fs->open(filename, "r");
#else
@@ -130,70 +139,21 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
}
}
void CommonCLI::savePrefs(FILESYSTEM* fs) {
bool CommonCLI::savePrefs(FILESYSTEM* fs) {
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
fs->remove("/com_prefs");
File file = fs->open("/com_prefs", FILE_O_WRITE);
fs->remove("/prefs.json");
File file = fs->open("/prefs.json", FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
File file = fs->open("/com_prefs", "w");
File file = fs->open("/prefs.json", "w");
#else
File file = fs->open("/com_prefs", "w", true);
File file = fs->open("/prefs.json", "w", true);
#endif
if (file) {
uint8_t pad[8];
memset(pad, 0, sizeof(pad));
file.write((uint8_t *)&_prefs->airtime_factor, sizeof(_prefs->airtime_factor)); // 0
file.write((uint8_t *)&_prefs->node_name, sizeof(_prefs->node_name)); // 4
file.write(pad, 4); // 36
file.write((uint8_t *)&_prefs->node_lat, sizeof(_prefs->node_lat)); // 40
file.write((uint8_t *)&_prefs->node_lon, sizeof(_prefs->node_lon)); // 48
file.write((uint8_t *)&_prefs->password[0], sizeof(_prefs->password)); // 56
file.write((uint8_t *)&_prefs->freq, sizeof(_prefs->freq)); // 72
file.write((uint8_t *)&_prefs->tx_power_dbm, sizeof(_prefs->tx_power_dbm)); // 76
file.write((uint8_t *)&_prefs->disable_fwd, sizeof(_prefs->disable_fwd)); // 77
file.write((uint8_t *)&_prefs->advert_interval, sizeof(_prefs->advert_interval)); // 78
file.write(pad, 1); // 79 : 1 byte unused (rx_boosted_gain moved to end)
file.write((uint8_t *)&_prefs->rx_delay_base, sizeof(_prefs->rx_delay_base)); // 80
file.write((uint8_t *)&_prefs->tx_delay_factor, sizeof(_prefs->tx_delay_factor)); // 84
file.write((uint8_t *)&_prefs->guest_password[0], sizeof(_prefs->guest_password)); // 88
file.write((uint8_t *)&_prefs->direct_tx_delay_factor, sizeof(_prefs->direct_tx_delay_factor)); // 104
file.write(pad, 4); // 108 : 4 byte unused
file.write((uint8_t *)&_prefs->sf, sizeof(_prefs->sf)); // 112
file.write((uint8_t *)&_prefs->cr, sizeof(_prefs->cr)); // 113
file.write((uint8_t *)&_prefs->allow_read_only, sizeof(_prefs->allow_read_only)); // 114
file.write((uint8_t *)&_prefs->multi_acks, sizeof(_prefs->multi_acks)); // 115
file.write((uint8_t *)&_prefs->bw, sizeof(_prefs->bw)); // 116
file.write((uint8_t *)&_prefs->agc_reset_interval, sizeof(_prefs->agc_reset_interval)); // 120
file.write((uint8_t *)&_prefs->path_hash_mode, sizeof(_prefs->path_hash_mode)); // 121
file.write((uint8_t *)&_prefs->loop_detect, sizeof(_prefs->loop_detect)); // 122
file.write(pad, 1); // 123
file.write((uint8_t *)&_prefs->flood_max, sizeof(_prefs->flood_max)); // 124
file.write((uint8_t *)&_prefs->flood_advert_interval, sizeof(_prefs->flood_advert_interval)); // 125
file.write((uint8_t *)&_prefs->interference_threshold, sizeof(_prefs->interference_threshold)); // 126
file.write((uint8_t *)&_prefs->bridge_enabled, sizeof(_prefs->bridge_enabled)); // 127
file.write((uint8_t *)&_prefs->bridge_delay, sizeof(_prefs->bridge_delay)); // 128
file.write((uint8_t *)&_prefs->bridge_pkt_src, sizeof(_prefs->bridge_pkt_src)); // 130
file.write((uint8_t *)&_prefs->bridge_baud, sizeof(_prefs->bridge_baud)); // 131
file.write((uint8_t *)&_prefs->bridge_channel, sizeof(_prefs->bridge_channel)); // 135
file.write((uint8_t *)&_prefs->bridge_secret, sizeof(_prefs->bridge_secret)); // 136
file.write((uint8_t *)&_prefs->powersaving_enabled, sizeof(_prefs->powersaving_enabled)); // 152
file.write(pad, 3); // 153
file.write((uint8_t *)&_prefs->gps_enabled, sizeof(_prefs->gps_enabled)); // 156
file.write((uint8_t *)&_prefs->gps_interval, sizeof(_prefs->gps_interval)); // 157
file.write((uint8_t *)&_prefs->advert_loc_policy, sizeof(_prefs->advert_loc_policy)); // 161
file.write((uint8_t *)&_prefs->discovery_mod_timestamp, sizeof(_prefs->discovery_mod_timestamp)); // 162
file.write((uint8_t *)&_prefs->adc_multiplier, sizeof(_prefs->adc_multiplier)); // 166
file.write((uint8_t *)_prefs->owner_info, sizeof(_prefs->owner_info)); // 170
file.write((uint8_t *)&_prefs->rx_boosted_gain, sizeof(_prefs->rx_boosted_gain)); // 290
file.write((uint8_t *)&_prefs->flood_max_unscoped, sizeof(_prefs->flood_max_unscoped)); // 291
file.write((uint8_t *)&_prefs->flood_max_advert, sizeof(_prefs->flood_max_advert)); // 292
file.write((uint8_t *)&_prefs->radio_fem_rxgain, sizeof(_prefs->radio_fem_rxgain)); // 293
file.write((uint8_t *)&_prefs->cad_enabled, sizeof(_prefs->cad_enabled)); // 294
// next: 295
bool success = _prefs->saveSerial(file);
file.close();
return success;
}
return false;
}
#define MIN_LOCAL_ADVERT_INTERVAL 60
@@ -793,6 +753,28 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
_prefs->adc_multiplier = 0.0f;
strcpy(reply, "Error: unsupported");
};
#if defined(USE_LR2021)
} else if (memcmp(config, "extra.sf ", 9) == 0) {
strcpy(tmp, &config[9]);
const char *parts[4];
uint8_t sideDetSFs[4];
int num = mesh::Utils::parseTextParts(tmp, parts, 4);
if (num > 3) {
sprintf(reply, "Invalid extra SF config");
} else {
for (int i = 0; i < num; i++) {
sideDetSFs[i] = atoi(parts[i]);
}
sideDetSFs[num] = 0;
if (_callbacks->configSideDetectors(sideDetSFs, num, _prefs->bw)) {
for (int i = 0; i <= num; i++) _prefs->extra_sf[i] = sideDetSFs[i];
savePrefs();
sprintf(reply, "OK - extra SFs set");
} else {
sprintf(reply, "Invalid extra SF config");
}
}
#endif
} else {
strcpy(reply, "unknown config: ");
StrHelper::strncpy(&reply[16], config, 160-17);
@@ -962,6 +944,14 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
#else
strcpy(reply, "ERROR: Power management not supported");
#endif
} else if (memcmp(config, "extra.sf", 8) == 0) {
char* tmp = reply;
for (int i = 0; i < 3 && _prefs->extra_sf[i] != 0; i++) {
tmp += sprintf(tmp, "%s%d", (i == 0) ? "" : ",", _prefs->extra_sf[i]);
}
if (tmp == reply) {
sprintf(reply, "No extra SF configured");
}
} else {
sprintf(reply, "??: %s", config);
}
+169 -38
View File
@@ -5,6 +5,7 @@
#include <helpers/SensorManager.h>
#include <helpers/ClientACL.h>
#include <helpers/RegionMap.h>
#include <helpers/ConfigSerializer.h>
#if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE)
#define WITH_BRIDGE
@@ -19,52 +20,176 @@
#define LOOP_DETECT_MODERATE 2
#define LOOP_DETECT_STRICT 3
struct NodePrefs { // persisted to file
float airtime_factor;
class NodePrefs : public ConfigSerializer {
public:
// in-memory backing data
float airtime_factor = 0;
char node_name[32];
double node_lat, node_lon;
double node_lat = 0, node_lon = 0;
char password[16];
float freq;
int8_t tx_power_dbm;
uint8_t disable_fwd;
uint8_t advert_interval; // minutes / 2
uint8_t flood_advert_interval; // hours
float rx_delay_base;
float tx_delay_factor;
float freq = 0;
int8_t tx_power_dbm = 0;
uint8_t disable_fwd = 0;
uint8_t advert_interval = 0; // minutes / 2
uint8_t flood_advert_interval = 0; // hours
float rx_delay_base = 0;
float tx_delay_factor = 0;
char guest_password[16];
float direct_tx_delay_factor;
float direct_tx_delay_factor = 0;
uint32_t guard;
uint8_t sf;
uint8_t cr;
uint8_t allow_read_only;
uint8_t multi_acks;
float bw;
uint8_t flood_max;
uint8_t flood_max_unscoped;
uint8_t flood_max_advert;
uint8_t interference_threshold;
uint8_t agc_reset_interval; // secs / 4
uint8_t sf = 0;
uint8_t cr = 0;
uint8_t allow_read_only = 0;
uint8_t multi_acks = 0;
float bw = 0;
uint8_t flood_max = 0;
uint8_t flood_max_unscoped = 0;
uint8_t flood_max_advert = 0;
uint8_t interference_threshold = 0;
uint8_t agc_reset_interval = 0; // secs / 4
// Bridge settings
uint8_t bridge_enabled; // boolean
uint16_t bridge_delay; // milliseconds (default 500 ms)
uint8_t bridge_pkt_src; // 0 = logTx, 1 = logRx (default logTx)
uint32_t bridge_baud; // 9600, 19200, 38400, 57600, 115200 (default 115200)
uint8_t bridge_channel; // 1-14 (ESP-NOW only)
uint8_t bridge_enabled = 0; // boolean
uint16_t bridge_delay = 0; // milliseconds (default 500 ms)
uint8_t bridge_pkt_src = 0; // 0 = logTx, 1 = logRx (default logTx)
uint32_t bridge_baud = 0; // 9600, 19200, 38400, 57600, 115200 (default 115200)
uint8_t bridge_channel = 0; // 1-14 (ESP-NOW only)
char bridge_secret[16]; // for XOR encryption of bridge packets (ESP-NOW only)
// Power setting
uint8_t powersaving_enabled; // boolean
uint8_t powersaving_enabled = 0; // boolean
// Gps settings
uint8_t gps_enabled;
uint32_t gps_interval; // in seconds
uint8_t advert_loc_policy;
uint32_t discovery_mod_timestamp;
float adc_multiplier;
uint8_t gps_enabled = 0;
uint32_t gps_interval = 0; // in seconds
uint8_t advert_loc_policy = 0;
uint32_t discovery_mod_timestamp = 0;
float adc_multiplier = 0;
char owner_info[120];
uint8_t rx_boosted_gain; // power settings
uint8_t radio_fem_rxgain; // LoRa FEM RX gain setting
uint8_t path_hash_mode; // which path mode to use when sending
uint8_t loop_detect;
uint8_t cad_enabled; // hardware Channel Activity Detection before TX (boolean)
uint8_t rx_boosted_gain = 0; // power settings
uint8_t radio_fem_rxgain = 0; // LoRa FEM RX gain setting
uint8_t path_hash_mode = 0; // which path mode to use when sending
uint8_t loop_detect = 0;
uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean)
uint8_t extra_sf[4];
private:
class RadioPrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("freq", _parent->freq);
def("bw", _parent->bw);
def("sf", _parent->sf);
def("cr", _parent->cr);
def("cad", _parent->cad_enabled);
def("int_thr", _parent->interference_threshold);
def("rxgain", _parent->rx_boosted_gain);
def("fem_rxgain", _parent->rx_boosted_gain);
def("tx", _parent->tx_power_dbm);
def("af", _parent->airtime_factor);
def("rxdelay", _parent->rx_delay_base);
def("f_txdelay", _parent->tx_delay_factor);
def("d_txdelay", _parent->direct_tx_delay_factor);
def("agc_int", _parent->agc_reset_interval);
def("hash_mode", _parent->path_hash_mode);
def("multi_ack", _parent->multi_acks);
}
public:
RadioPrefs(NodePrefs* parent) : _parent(parent) { }
};
RadioPrefs radio;
class BridgePrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("en", _parent->bridge_enabled); // boolean
def("delay", _parent->bridge_delay); // milliseconds (default 500 ms)
def("src", _parent->bridge_pkt_src); // 0 = logTx, 1 = logRx (default logTx)
def("baud", _parent->bridge_baud); // 9600, 19200, 38400, 57600, 115200 (default 115200)
def("ch", _parent->bridge_channel); // 1-14 (ESP-NOW only)
def("secret", _parent->bridge_secret, sizeof(_parent->bridge_secret)); // for XOR encryption of bridge packets (ESP-NOW only)
}
public:
BridgePrefs(NodePrefs* parent) : _parent(parent) { }
};
BridgePrefs bridge;
class GPSPrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("en", _parent->gps_enabled); // boolean
def("int", _parent->gps_interval); // interval in seconds
def("adv_loc", _parent->advert_loc_policy);
}
public:
GPSPrefs(NodePrefs* parent) : _parent(parent) { }
};
GPSPrefs gps;
class PowerPrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("adc_mult", _parent->adc_multiplier);
def("pwr_sav_en", _parent->powersaving_enabled);
}
public:
PowerPrefs(NodePrefs* parent) : _parent(parent) { }
};
PowerPrefs power;
class RepeatPrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("disable", _parent->disable_fwd);
def("f_max", _parent->flood_max);
def("f_max_uns", _parent->flood_max_unscoped);
def("f_max_adv", _parent->flood_max_advert);
def("loop", _parent->loop_detect);
}
public:
RepeatPrefs(NodePrefs* parent) : _parent(parent) { }
};
RepeatPrefs repeat;
class RoomPrefs : public ConfigSerializer {
NodePrefs* _parent;
protected:
void structure() override {
def("rd_only", _parent->allow_read_only);
}
public:
RoomPrefs(NodePrefs* parent) : _parent(parent) { }
};
RoomPrefs room;
protected:
void structure() override {
def("name", node_name, sizeof(node_name));
def("pass", password, sizeof(password));
def("guest", guest_password, sizeof(guest_password));
def("owner", owner_info, sizeof(owner_info));
def("adv_int", advert_interval);
def("f_adv_int", flood_advert_interval);
def("lat", node_lat);
def("lon", node_lon);
def("radio", radio);
def("bridge", bridge);
def("gps", gps);
def("repeat", repeat);
def("room", room);
def("power", power);
}
public:
NodePrefs() : ConfigSerializer(), bridge(this), gps(this), radio(this), power(this), repeat(this), room(this) {
node_name[0] = 0;
password[0] = 0;
guest_password[0] = 0;
bridge_secret[0] = 0;
owner_info[0] = 0;
}
};
class CommonCLICallbacks {
@@ -114,6 +239,12 @@ public:
virtual bool setRxBoostedGain(bool enable) {
return false; // CommonCLI reports unsupported if not overridden by wrapper
};
#if defined(USE_LR2021)
virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) {
return false; // Override in wrapper
}
#endif
};
class CommonCLI {
@@ -139,7 +270,7 @@ public:
: _board(&board), _rtc(&rtc), _sensors(&sensors), _region_map(&region_map), _acl(&acl), _prefs(prefs), _callbacks(callbacks) { }
void loadPrefs(FILESYSTEM* _fs);
void savePrefs(FILESYSTEM* _fs);
bool savePrefs(FILESYSTEM* _fs);
void handleCommand(uint32_t sender_timestamp, char* command, char* reply);
uint8_t buildAdvertData(uint8_t node_type, uint8_t* app_data);
};
+331
View File
@@ -0,0 +1,331 @@
#include "ConfigSerializer.h"
bool ConfigSerializer::saveSerial(Stream& s) {
Context context(&s, OP::WRITE);
_context = &context; // set the context for structure() call
s.print("{"); // root object
_first = true;
structure();
if (s.print("}") != 1) context.success = false; // failure detect
_context = NULL;
return context.success;
}
#define TOK_ERROR -1
#define TOK_EOF 0
#define TOK_KEY 1
#define TOK_VALUE 2
#define TOK_START_OBJ 3
#define TOK_END_OBJ 4
#define TOK_WHITESPACE 5
static bool is_whitespace(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
static bool is_key_char(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
}
static bool is_value_char(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c == '-' || c == '.';
}
#define EXPECT_OPEN_BRACE 0
#define EXPECT_KEY 1
#define EXPECT_VAL_OR_OBJ 2
#define EXPECT_STRING_VAL 3
#define EXPECT_STRING_ESCAPE 4
#define EXPECT_COMMA_OR_CLOSE 5
#define EXPECT_COMMA_OR_KEY 6
#define EXPECT_COMMA_OR_KEY_OR_CLOSE 7
int ConfigSerializer::Context::readNext() {
char c;
if (pending) {
c = pending;
pending = 0;
} else {
if (_f->available() == 0) return TOK_EOF;
int n = _f->read();
if (n < 0) return TOK_EOF;
c = (char)n;
}
switch (rd_mode) {
case EXPECT_OPEN_BRACE:
if (c == '{') { rd_mode = EXPECT_KEY; return TOK_START_OBJ; }
if (is_whitespace(c)) return TOK_WHITESPACE;
return TOK_ERROR;
case EXPECT_COMMA_OR_KEY_OR_CLOSE:
if (c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; }
case EXPECT_COMMA_OR_KEY:
if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; }
case EXPECT_KEY:
if (rd_len > 0 && c == ':') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_VAL_OR_OBJ; return TOK_KEY; }
if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE;
if (rd_len < CONFIG_MAX_KEYLEN-1 && is_key_char(c)) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
return TOK_ERROR;
case EXPECT_VAL_OR_OBJ:
if (rd_len == 0 && is_whitespace(c)) return TOK_WHITESPACE;
if (rd_len == 0 && c == '"') { rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; }
if (rd_len == 0 && c == '{') { rd_mode = EXPECT_KEY; return TOK_START_OBJ; }
if (is_value_char(c) && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
if (rd_len > 0 && (c == ',' || c == '}' || is_whitespace(c))) { pending = c; rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_VALUE; }
return TOK_ERROR;
case EXPECT_STRING_ESCAPE:
if ((c == 'n') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = '\n'; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; }
if ((c == 'r') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = '\r'; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; }
if ((c == '"' || c == '\\' || c == '/') && rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; rd_mode = EXPECT_STRING_VAL; return TOK_WHITESPACE; }
return TOK_ERROR; // unsupport escape
case EXPECT_STRING_VAL:
if (c == '"') { rd_buf[rd_len] = 0; rd_len = 0; rd_mode = EXPECT_COMMA_OR_CLOSE; return TOK_VALUE; }
if (c == '\\') { rd_mode = EXPECT_STRING_ESCAPE; return TOK_WHITESPACE; }
if (rd_len < CONFIG_MAX_TOKEN_LEN-1) { rd_buf[rd_len++] = c; return TOK_WHITESPACE; }
return TOK_ERROR;
case EXPECT_COMMA_OR_CLOSE:
if (c == ',') { rd_mode = EXPECT_KEY; return TOK_WHITESPACE; }
if (c == '}') { rd_mode = EXPECT_COMMA_OR_KEY_OR_CLOSE; return TOK_END_OBJ; }
if (is_whitespace(c)) return TOK_WHITESPACE;
return TOK_ERROR;
}
return TOK_ERROR; // unknown mode
}
bool ConfigSerializer::loadSerial(Stream& s) {
Context context(&s, OP::READ);
_context = &context; // set the context for structure() call
uint8_t sp = 0; // object nesting stack pointer
int next_tok;
// parse the Json file
while ((next_tok = context.readNext()) > TOK_EOF) {
if (next_tok == TOK_KEY) {
context.setKey(sp, context.getToken());
} else if (next_tok == TOK_VALUE) {
_depth = 1; // re-run the structure() hierarchy again (looking for specific key, at specific depth)
structure();
} else if (next_tok == TOK_START_OBJ) {
if (sp < CONFIG_MAX_DEPTH - 1) {
sp++;
} else {
//Serial.printf("Error: max nesting reached"); // TODO: debug logging
context.success = false;
break;
}
} else if (next_tok == TOK_END_OBJ) {
if (sp > 0) {
sp--;
} else {
//Serial.printf("Error: too many closing '}'"); // TODO: debug logging
context.success = false;
break;
}
}
}
if (sp != 0 || next_tok == TOK_ERROR) {
context.success = false; // unmatched { }, or other parse error
}
_context = NULL;
return context.success;
}
void ConfigSerializer::writeComma() {
if (_first) {
_first = false;
} else {
_context->file()->print(","); // comma separated properties
}
}
#include <Utils.h>
void ConfigSerializer::def(const char* key, void* value, size_t len) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":\"");
mesh::Utils::printHex(*_context->file(), (uint8_t*) value, len);
_context->file()->print("\"");
} else {
if (_context->keyMatch(_depth, key)) {
memset(value, 0, len);
mesh::Utils::fromHex((uint8_t *)value, len, _context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, char* value, size_t max_len) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":\"");
char c;
while ((c = *value++) != 0) { // TODO: handle UTF-8 encoding
if (c == '"') {
_context->file()->print("\\\"");
} else if (c == '\\') {
_context->file()->print("\\\\");
} else if (c == '\n') {
_context->file()->print("\\n");
} else if (c == '\r') {
_context->file()->print("\\r");
} else {
_context->file()->print(c);
}
}
_context->file()->print("\"");
} else {
if (_context->keyMatch(_depth, key)) {
strncpy(value, _context->getToken(), max_len - 1);
value[max_len - 1] = 0;
}
}
}
void ConfigSerializer::def(const char* key, int32_t& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print(value);
} else {
if (_context->keyMatch(_depth, key)) {
value = atol(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, uint32_t& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print(value);
} else {
if (_context->keyMatch(_depth, key)) {
value = atol(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, int16_t& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print((int32_t) value, 10);
} else {
if (_context->keyMatch(_depth, key)) {
value = atol(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, uint16_t& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print((uint32_t) value, 10);
} else {
if (_context->keyMatch(_depth, key)) {
value = atoi(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, uint8_t& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print((uint32_t) value, 10);
} else {
if (_context->keyMatch(_depth, key)) {
value = atoi(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, int8_t& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print((int32_t) value, 10);
} else {
if (_context->keyMatch(_depth, key)) {
value = atoi(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, bool& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
_context->file()->print(value ? "true" : "false");
} else {
if (_context->keyMatch(_depth, key)) {
value = strcmp(_context->getToken(), "true") == 0 || atoi(_context->getToken()) != 0; // 'true' or a non-zero number
}
}
}
void ConfigSerializer::def(const char* key, double& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
if (value == 0.0) {
_context->file()->print("0"); // shorter encoding
} else {
_context->file()->print(value, 6); // REVISIT: how many dec places?
}
} else {
if (_context->keyMatch(_depth, key)) {
value = atof(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, float& value) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":");
if (value == 0.0f) {
_context->file()->print("0"); // shorter encoding
} else {
_context->file()->print(value, 4); // REVISIT: how many dec places?
}
} else {
if (_context->keyMatch(_depth, key)) {
value = (float) atof(_context->getToken());
}
}
}
void ConfigSerializer::def(const char* key, ConfigSerializer& sub_obj) {
if (_context->op() == OP::WRITE) {
writeComma();
_context->file()->print(key);
_context->file()->print(":{");
sub_obj._context = _context; // inherit the Context
sub_obj._first = true;
sub_obj.structure(); // recurse into sub object
if (_context->file()->print("}") != 1) _context->success = false; // failure detect
} else {
if (_context->keyMatch(_depth, key)) {
sub_obj._context = _context; // inherit the Context
sub_obj._depth = _depth + 1;
sub_obj.structure(); // recurse into sub object
}
}
}
+68
View File
@@ -0,0 +1,68 @@
#pragma once
#include <Arduino.h>
#ifndef CONFIG_MAX_DEPTH
#define CONFIG_MAX_DEPTH 8
#endif
#ifndef CONFIG_MAX_KEYLEN
#define CONFIG_MAX_KEYLEN 16
#endif
#ifndef CONFIG_MAX_TOKEN_LEN
#define CONFIG_MAX_TOKEN_LEN 128
#endif
class ConfigSerializer {
bool _first;
int8_t _depth;
enum OP { READ, WRITE };
class Context {
Stream* _f;
OP _op;
uint8_t rd_len;
uint8_t rd_mode;
char pending;
char rd_buf[CONFIG_MAX_TOKEN_LEN];
char _keys[CONFIG_MAX_DEPTH][CONFIG_MAX_KEYLEN];
public:
bool success = true;
Context(Stream* f, OP op) : _f(f), _op(op) { rd_buf[rd_len = 0] = 0; rd_mode = 0; pending = 0; }
OP op() const { return _op; }
Stream* file() const { return _f; }
int readNext();
const char* getToken() const { return rd_buf; }
bool keyMatch(int8_t depth, const char* key) { return strcmp(key, _keys[depth]) == 0; }
void setKey(uint8_t depth, const char* key) { strcpy(_keys[depth], key); }
};
Context* _context = NULL;
void writeComma();
protected:
ConfigSerializer() { }
void def(const char* key, char* value, size_t max_len); // max_len inclusive of null
void def(const char* key, void* value, size_t len); // binary blob (encoded in hex)
void def(const char* key, int32_t& value);
void def(const char* key, int16_t& value);
void def(const char* key, int8_t& value);
void def(const char* key, uint32_t& value);
void def(const char* key, uint16_t& value);
void def(const char* key, uint8_t& value);
void def(const char* key, float& value);
void def(const char* key, double& value);
void def(const char* key, bool& value);
void def(const char* key, ConfigSerializer& sub_obj);
virtual void structure() = 0;
public:
bool loadSerial(Stream& s);
bool saveSerial(Stream& s);
};
+42
View File
@@ -1,6 +1,7 @@
#ifdef ESP_PLATFORM
#include "ESP32Board.h"
#include <target.h>
#if defined(ADMIN_PASSWORD) && !defined(DISABLE_WIFI_OTA) // Repeater or Room Server only
#include <WiFi.h>
@@ -44,4 +45,45 @@ bool ESP32Board::startOTAUpdate(const char* id, char reply[]) {
}
#endif
void ESP32Board::powerOff() {
enterDeepSleep(0); // Do not wakeup
}
void ESP32Board::enterDeepSleep(uint32_t secs) {
// Power off the display if any
#ifdef DISPLAY_CLASS
display.turnOff();
#endif
// Power off LoRa
radio_driver.powerOff();
// Keep LoRa inactive during deepsleep
digitalWrite(P_LORA_NSS, HIGH);
#if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6)
gpio_hold_en((gpio_num_t)P_LORA_NSS);
#else
rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS);
#endif
// Power off GPS if any
if (sensors.getLocationProvider() != NULL) {
sensors.getLocationProvider()->stop();
}
// Flush serial buffers
Serial.flush();
delay(100);
// Clear stale wakeup sources to avoid ghost wakeup
// This is required when Power Management and automatic lightsleep are enabled
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL);
if (secs > 0) {
esp_sleep_enable_timer_wakeup(secs * 1000000ULL);
}
// Finally set ESP32 into deepsleep
esp_deep_sleep_start(); // CPU halts here and never returns!
}
#endif
+4
View File
@@ -14,6 +14,7 @@
#include <Wire.h>
#include "soc/rtc.h"
#include "esp_system.h"
#include <driver/rtc_io.h>
class ESP32Board : public mesh::MainBoard {
protected:
@@ -62,6 +63,9 @@ public:
return raw / 4;
}
virtual void powerOff() override;
void enterDeepSleep(uint32_t secs);
uint32_t getIRQGpio() override {
return P_LORA_DIO_1; // default for SX1262
}
+12
View File
@@ -0,0 +1,12 @@
#pragma once
class ExternalWatchdogManager {
protected:
unsigned long last_feed_watchdog;
public:
ExternalWatchdogManager() { last_feed_watchdog = 0; }
virtual bool begin() { return false; }
virtual void loop() { }
virtual unsigned long getIntervalMs() const { return 0; }
virtual void feed() { }
};
-30
View File
@@ -15,8 +15,6 @@
#include "ESP32Board.h"
#include <driver/rtc_io.h>
class MeshadventurerBoard : public ESP32Board {
public:
@@ -35,34 +33,6 @@ public:
}
}
void enterDeepSleep(uint32_t secs, int pin_wake_btn = -1) {
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
// Make sure the DIO1 and NSS GPIOs are held on required levels during deep sleep
rtc_gpio_set_direction((gpio_num_t)P_LORA_DIO_1, RTC_GPIO_MODE_INPUT_ONLY);
rtc_gpio_pulldown_en((gpio_num_t)P_LORA_DIO_1);
rtc_gpio_hold_en((gpio_num_t)P_LORA_NSS);
if (pin_wake_btn < 0) {
esp_sleep_enable_ext1_wakeup( (1L << P_LORA_DIO_1), ESP_EXT1_WAKEUP_ANY_HIGH); // wake up on: recv LoRa packet
} else {
esp_sleep_enable_ext1_wakeup( (1L << P_LORA_DIO_1) | (1L << pin_wake_btn), ESP_EXT1_WAKEUP_ANY_HIGH); // wake up on: recv LoRa packet OR wake btn
}
if (secs > 0) {
esp_sleep_enable_timer_wakeup(secs * 1000000);
}
// Finally set ESP32 into sleep
esp_deep_sleep_start(); // CPU halts here and never returns!
}
void powerOff() override {
// TODO: re-enable this when there is a definite wake-up source pin:
// enterDeepSleep(0);
}
uint16_t getBattMilliVolts() override {
analogReadResolution(12);
+200
View File
@@ -0,0 +1,200 @@
#pragma once
#include "BaseSerialInterface.h"
#ifndef MAX_INTERFACES
// ble, usb, wifi, ethernet
#define MAX_INTERFACES 4
#endif
enum class InterfaceType : uint8_t {
NONE,
Bluetooth,
USB,
WiFi,
Ethernet,
HardwareSerial
};
class MultiSerialInterface : public BaseSerialInterface {
private:
struct RegisteredInterface {
InterfaceType type = InterfaceType::NONE;
BaseSerialInterface* instance = nullptr;
};
bool _enabled = false;
RegisteredInterface _interfaces[MAX_INTERFACES] = {};
public:
bool addInterface(InterfaceType type, BaseSerialInterface* iface) {
// make sure an interface was provided
if(iface == nullptr){
return false;
}
// put it in the first free slot
for(int i = 0; i < MAX_INTERFACES; i++){
if(_interfaces[i].instance == nullptr){
_interfaces[i].instance = iface;
_interfaces[i].type = type;
return true;
}
}
// no free slots available
return false;
}
bool removeInterface(BaseSerialInterface* iface) {
// make sure an interface was provided
if(iface == nullptr){
return false;
}
// find and remove interface
for(int i = 0; i < MAX_INTERFACES; i++){
if(_interfaces[i].instance == iface){
_interfaces[i] = {};
return true;
}
}
// interface not found
return false;
}
void enableBluetooth() {
for(auto iface : _interfaces){
if(iface.instance && iface.type == InterfaceType::Bluetooth){
iface.instance->enable();
}
}
}
void disableBluetooth() {
for(auto iface : _interfaces){
if(iface.instance && iface.type == InterfaceType::Bluetooth){
iface.instance->disable();
}
}
}
bool isBluetoothEnabled() {
for(auto iface : _interfaces){
if(iface.instance && iface.type == InterfaceType::Bluetooth){
return iface.instance->isEnabled();
}
}
return false;
}
// enable all interfaces
void enable() override {
_enabled = true;
for(auto iface : _interfaces){
if(iface.instance){
iface.instance->enable();
}
}
}
// disable all interfaces
void disable() override {
_enabled = false;
for(auto iface : _interfaces){
if(iface.instance){
iface.instance->disable();
}
}
}
bool isEnabled() const override {
return _enabled;
}
bool isConnected() const override {
// not connected when disabled
if(!_enabled){
return false;
}
// check if any interface is connected
for(auto iface : _interfaces){
if(iface.instance && iface.instance->isConnected()) {
return true;
}
}
// nothing connected
return false;
}
// loop all interfaces
void loop() override {
for(auto iface : _interfaces){
if(iface.instance){
iface.instance->loop();
}
}
}
bool isWriteBusy() const override {
// not busy when disabled
if(!_enabled){
return false;
}
// check if any interface is busy
for(auto iface : _interfaces){
if(iface.instance && iface.instance->isEnabled() && iface.instance->isWriteBusy()){
return true;
}
}
// nothing busy
return false;
}
size_t writeFrame(const uint8_t src[], size_t len) override {
// don't write when disabled or nothing provided
if(!_enabled || len == 0){
return 0;
}
// write frame to all enabled interfaces
bool allSuccessful = true;
for(auto iface : _interfaces){
if(iface.instance && iface.instance->isEnabled()){
if(iface.instance->writeFrame(src, len) != len){
allSuccessful = false;
}
}
}
// report success if all writes completed successfully
return allSuccessful ? len : 0;
}
size_t checkRecvFrame(uint8_t dest[]) override {
// don't read when disabled
if(!_enabled){
return 0;
}
// try to read a frame from any enabled interface
for(auto iface : _interfaces){
if(iface.instance && iface.instance->isEnabled()){
size_t frameSize = iface.instance->checkRecvFrame(dest);
if(frameSize > 0){
return frameSize;
}
}
}
// no frame received
return 0;
}
};
+95 -8
View File
@@ -1,9 +1,14 @@
#if defined(NRF52_PLATFORM)
#include "NRF52Board.h"
#include <target.h>
#include <bluefruit.h>
#include <nrf_soc.h>
#ifdef USE_CC310_HW_CRYPTO
#include <Adafruit_nRFCrypto.h>
#endif
static BLEDfu bledfu;
static void connect_callback(uint16_t conn_handle) {
@@ -20,6 +25,11 @@ static void disconnect_callback(uint16_t conn_handle, uint8_t reason) {
void NRF52Board::begin() {
startup_reason = BD_STARTUP_NORMAL;
#ifdef USE_CC310_HW_CRYPTO
// CC310 TRNG is higher quality and environment-independent vs radio RSSI noise.
nRFCrypto.begin();
#endif
}
#ifdef NRF52_POWER_MANAGEMENT
@@ -279,16 +289,29 @@ void NRF52Board::sleep(uint32_t secs) {
// Temperature from NRF52 MCU
float NRF52Board::getMCUTemperature() {
NRF_TEMP->TASKS_START = 1; // Start temperature measurement
long startTime = millis();
while (NRF_TEMP->EVENTS_DATARDY == 0) { // Wait for completion. Should complete in 50us
if(millis() - startTime > 5) { // To wait 5ms just in case
NRF_TEMP->TASKS_STOP = 1;
uint8_t sd_enabled = 0;
sd_softdevice_is_enabled(&sd_enabled);
if (sd_enabled) {
uint32_t err_code;
int32_t temp;
err_code = sd_temp_get(&temp);
if (err_code == NRF_SUCCESS) {
return (float)temp * 0.25f;
} else {
return NAN;
}
} else {
NRF_TEMP->TASKS_START = 1; // Start temperature measurement
long startTime = millis();
while (NRF_TEMP->EVENTS_DATARDY == 0) { // Wait for completion. Should complete in 50us
if(millis() - startTime > 5) { // To wait 5ms just in case
NRF_TEMP->TASKS_STOP = 1;
return NAN;
}
}
}
NRF_TEMP->EVENTS_DATARDY = 0; // Clear event flag
int32_t temp = NRF_TEMP->TEMP; // In 0.25 *C units
@@ -297,6 +320,69 @@ float NRF52Board::getMCUTemperature() {
return temp * 0.25f; // Convert to *C
}
void NRF52Board::shutdownPeripherals() {
// Power off the display if any
#ifdef DISPLAY_CLASS
if (display.isOn()) {
display.turnOff();
}
#endif
// Prep LoRa radio for power down
#ifdef P_LORA_RESET
digitalWrite(P_LORA_RESET, HIGH); // preload OUT latch so pinMode can't glitch NRESET low
pinMode(P_LORA_RESET, OUTPUT);
digitalWrite(P_LORA_RESET, LOW); // deliberate hardware reset (datasheet: >=100us)
delayMicroseconds(200);
digitalWrite(P_LORA_RESET, HIGH);
#endif
#if defined(P_LORA_SCLK) && defined(P_LORA_MISO) && defined(P_LORA_MOSI)
SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);
SPI.begin(); // SPI may not be started on some shutdown paths, need it to shut down radio
#endif
#ifdef P_LORA_BUSY
pinMode(P_LORA_BUSY, INPUT);
uint32_t started_at = millis();
while (digitalRead(P_LORA_BUSY) && millis() - started_at < 10) {} //wait for radio to be ready
#endif
#ifdef P_LORA_NSS
pinMode(P_LORA_NSS, OUTPUT);
digitalWrite(P_LORA_NSS, HIGH);
#endif
// Power off LoRa
radio_driver.powerOff();
// Keep LoRa inactive during deepsleep
#ifdef P_LORA_NSS
digitalWrite(P_LORA_NSS, HIGH);
#endif
// Power off GPS if any
if(sensors.getLocationProvider() != NULL) {
sensors.getLocationProvider()->stop();
}
#ifdef USE_CC310_HW_CRYPTO
nRFCrypto.end();
#endif
// Flush serial buffers
Serial.flush();
delay(100);
}
void NRF52Board::powerOff() {
shutdownPeripherals();
// Enter SYSTEMOFF
uint8_t sd_enabled = 0;
sd_softdevice_is_enabled(&sd_enabled);
if (sd_enabled) { // SoftDevice is enabled
sd_power_system_off();
} else { // SoftDevice is not enable
NRF_POWER->SYSTEMOFF = POWER_SYSTEMOFF_SYSTEMOFF_Enter;
}
}
bool NRF52Board::getBootloaderVersion(char* out, size_t max_len) {
static const char BOOTLOADER_MARKER[] = "UF2 Bootloader ";
const uint8_t* flash = (const uint8_t*)0x000FB000; // earliest known info.txt location is 0xFB90B, latest is 0xFCC4B
@@ -323,7 +409,8 @@ bool NRF52Board::startOTAUpdate(const char *id, char reply[]) {
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.configPrphConn(92, BLE_GAP_EVENT_LENGTH_MIN, 16, 16);
Bluefruit.begin(1, 0);
if (!Bluefruit.begin(1, 0)) return false;
// Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
// Set the BLE device name
+8 -4
View File
@@ -31,7 +31,7 @@ class NRF52Board : public mesh::MainBoard {
protected:
uint8_t startup_reason;
char *ota_name;
const char *ota_name;
#ifdef NRF52_POWER_MANAGEMENT
uint32_t reset_reason; // RESETREAS register value
@@ -45,11 +45,13 @@ protected:
#endif
public:
NRF52Board(char *otaname) : ota_name(otaname) {}
NRF52Board(const char *otaname) : ota_name(otaname) {}
virtual void begin();
virtual uint8_t getStartupReason() const override { return startup_reason; }
virtual float getMCUTemperature() override;
virtual void reboot() override { NVIC_SystemReset(); }
virtual void shutdownPeripherals();
virtual void powerOff() override;
virtual bool getBootloaderVersion(char* version, size_t max_len) override;
virtual bool startOTAUpdate(const char *id, char reply[]) override;
virtual void sleep(uint32_t secs) override;
@@ -71,9 +73,11 @@ public:
* hardware requirements are met, this subclass can be used to enable the DC/DC
* regulator.
*/
class NRF52BoardDCDC : virtual public NRF52Board {
class NRF52BoardDCDC : public NRF52Board {
public:
NRF52BoardDCDC() {}
NRF52BoardDCDC() : NRF52Board(NULL) {}
NRF52BoardDCDC(const char *otaname) : NRF52Board(otaname) {}
virtual void begin() override;
};
#endif
+5 -3
View File
@@ -93,13 +93,15 @@ bool RegionMap::load(FILESYSTEM* _fs, const char* path) {
while (num_regions < MAX_REGION_ENTRIES) {
auto r = &regions[num_regions];
success = file.read((uint8_t *) &r->id, sizeof(r->id)) == sizeof(r->id);
int n = file.read((uint8_t *) &r->id, sizeof(r->id));
if (n == 0) break; // clean EOF
success = (n == sizeof(r->id));
success = success && file.read((uint8_t *) &r->parent, sizeof(r->parent)) == sizeof(r->parent);
success = success && file.read((uint8_t *) r->name, sizeof(r->name)) == sizeof(r->name);
success = success && file.read((uint8_t *) &r->flags, sizeof(r->flags)) == sizeof(r->flags);
success = success && file.read(pad, sizeof(pad)) == sizeof(pad);
if (!success) break; // EOF
if (!success) break; // partial read or corruption
if (r->id >= next_id) { // make sure next_id is valid
next_id = r->id + 1;
@@ -108,7 +110,7 @@ bool RegionMap::load(FILESYSTEM* _fs, const char* path) {
}
}
file.close();
return true;
return success;
}
}
return false; // failed
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
namespace mesh {
inline bool isUtf8Continuation(uint8_t byte) {
return (byte & 0xC0) == 0x80;
}
inline size_t validUtf8PrefixLength(const char* text, size_t max_bytes) {
if (text == nullptr) return 0;
size_t offset = 0;
while (text[offset] != '\0') {
const uint8_t first = static_cast<uint8_t>(text[offset]);
size_t sequence_length = 0;
if (first <= 0x7F) {
sequence_length = 1;
} else if (first >= 0xC2 && first <= 0xDF) {
sequence_length = 2;
} else if (first >= 0xE0 && first <= 0xEF) {
sequence_length = 3;
} else if (first >= 0xF0 && first <= 0xF4) {
sequence_length = 4;
} else {
break;
}
if (offset + sequence_length > max_bytes) break;
bool complete = true;
for (size_t i = 1; i < sequence_length; i++) {
if (text[offset + i] == '\0' || !isUtf8Continuation(static_cast<uint8_t>(text[offset + i]))) {
complete = false;
break;
}
}
if (!complete) break;
if (sequence_length == 3) {
const uint8_t second = static_cast<uint8_t>(text[offset + 1]);
if ((first == 0xE0 && second < 0xA0) || (first == 0xED && second > 0x9F)) break;
} else if (sequence_length == 4) {
const uint8_t second = static_cast<uint8_t>(text[offset + 1]);
if ((first == 0xF0 && second < 0x90) || (first == 0xF4 && second > 0x8F)) break;
}
offset += sequence_length;
}
return offset;
}
} // namespace mesh
+18 -20
View File
@@ -103,10 +103,9 @@ void SerialBLEInterface::onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param
void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
BLE_DEBUG_PRINTLN("onDisconnect()");
deviceConnected = false;
if (_isEnabled) {
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
// loop() will detect this on next loop, and set deviceConnected to false
}
}
@@ -118,17 +117,24 @@ void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gat
if (len > MAX_FRAME_SIZE) {
BLE_DEBUG_PRINTLN("ERROR: onWrite(), frame too big, len=%d", len);
} else if (recv_queue_len >= FRAME_QUEUE_SIZE) {
BLE_DEBUG_PRINTLN("ERROR: onWrite(), recv_queue is full!");
} else {
recv_queue[recv_queue_len].len = len;
memcpy(recv_queue[recv_queue_len].buf, rxValue, len);
recv_queue_len++;
Frame frame = {};
frame.len = len;
memcpy(frame.buf, rxValue, len);
if (xQueueSend(recv_queue, &frame, 0) != pdTRUE) {
BLE_DEBUG_PRINTLN("ERROR: onWrite(), recv_queue is full!");
}
}
}
// ---------- public methods
void SerialBLEInterface::clearBuffers() {
xQueueReset(recv_queue);
send_queue_len = 0;
}
void SerialBLEInterface::enable() {
if (_isEnabled) return;
@@ -202,21 +208,13 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
}
}
if (recv_queue_len > 0) { // check recv queue
size_t len = recv_queue[0].len; // take from top of queue
memcpy(dest, recv_queue[0].buf, len);
BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", len, (uint32_t) dest[0]);
recv_queue_len--;
for (int i = 0; i < recv_queue_len; i++) { // delete top item from queue
recv_queue[i] = recv_queue[i + 1];
}
return len;
Frame frame;
if (xQueueReceive(recv_queue, &frame, 0) == pdTRUE) {
memcpy(dest, frame.buf, frame.len);
BLE_DEBUG_PRINTLN("readBytes: sz=%d, hdr=%d", (uint32_t) frame.len, (uint32_t) dest[0]);
return frame.len;
}
if (pServer->getConnectedCount() == 0) deviceConnected = false;
if (deviceConnected != oldDeviceConnected) {
if (!deviceConnected) { // disconnecting
clearBuffers();
+10 -4
View File
@@ -5,6 +5,8 @@
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLEServerCallbacks, BLECharacteristicCallbacks {
BLEServer *pServer;
@@ -24,12 +26,13 @@ class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLE
};
#define FRAME_QUEUE_SIZE 4
int recv_queue_len;
Frame recv_queue[FRAME_QUEUE_SIZE];
StaticQueue_t recv_queue_state;
uint8_t recv_queue_storage[FRAME_QUEUE_SIZE * sizeof(Frame)];
QueueHandle_t recv_queue;
int send_queue_len;
Frame send_queue[FRAME_QUEUE_SIZE];
void clearBuffers() { recv_queue_len = 0; send_queue_len = 0; }
void clearBuffers();
protected:
// BLESecurityCallbacks methods
@@ -58,7 +61,10 @@ public:
_isEnabled = false;
_last_write = 0;
last_conn_id = 0;
send_queue_len = recv_queue_len = 0;
recv_queue = xQueueCreateStatic(
FRAME_QUEUE_SIZE, sizeof(Frame), recv_queue_storage, &recv_queue_state
);
send_queue_len = 0;
}
/**
+10
View File
@@ -16,6 +16,16 @@ void TBeamBoard::begin() {
ESP32Board::begin();
#ifdef TBEAM_SUPREME_SX1262
// On the T-Beam S3 Supreme the PMU + RTC sit on Wire1 (GPIO 42/41, brought
// up by XPowersLib), while the SH1106 OLED and the BME280/QMC6310 sensors
// sit on the primary bus, Wire (GPIO PIN_BOARD_SDA/PIN_BOARD_SCL). Nothing
// else initialises Wire on this board, so the display driver would
// otherwise talk on the wrong (default) pins and display.begin() fails,
// leaving the screen blank. Bring the OLED bus up here.
Wire.begin(PIN_BOARD_SDA, PIN_BOARD_SCL);
#endif
power_init();
//Configure user button
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#if defined(ETHERNET_ENABLED)
#if defined(ETHERNET_USE_CH390)
#include "helpers/ethernet/ch390/CH390EthernetInterface.h"
#elif defined(ETHERNET_USE_RAK13800)
#include "helpers/ethernet/RAK13800/RAK13800EthernetInterface.h"
#else
#error "ETHERNET_ENABLED is defined, but no specific driver flag (e.g. ETHERNET_USE_CH390) was provided!"
#endif
#endif
@@ -0,0 +1,109 @@
#include "RAK13800EthernetInterface.h"
#include "../../nrf52/EthernetMac.h"
#include <SPI.h>
#include <EthernetUdp.h>
#define PIN_SPI1_MISO (29) // (0 + 29)
#define PIN_SPI1_MOSI (30) // (0 + 30)
#define PIN_SPI1_SCK (3) // (0 + 3)
SPIClass ETHERNET_SPI_PORT(NRF_SPIM1, PIN_SPI1_MISO, PIN_SPI1_SCK, PIN_SPI1_MOSI);
#define PIN_ETHERNET_POWER_EN WB_IO2 // output, high to enable
#define PIN_ETHERNET_RESET 21
#define PIN_ETHERNET_SS 26
bool RAK13800EthernetInterface::begin() {
// WB_IO2 (power enable) is already driven HIGH by early constructor
// in RAK4631Board.cpp to support POE boot.
// Skip hardware reset — the W5100S comes out of power-on reset cleanly,
// and toggling reset kills the PHY link which breaks POE power.
#ifdef PIN_ETHERNET_RESET
pinMode(PIN_ETHERNET_RESET, OUTPUT);
digitalWrite(PIN_ETHERNET_RESET, HIGH);
#endif
// generate mac address
uint8_t mac[6];
generateEthernetMac(mac);
ETHERNET_DEBUG_PRINTLN(
"Ethernet MAC: %02X:%02X:%02X:%02X:%02X:%02X",
mac[0],
mac[1],
mac[2],
mac[3],
mac[4],
mac[5]);
ETHERNET_SPI_PORT.begin();
Ethernet.init(ETHERNET_SPI_PORT, PIN_ETHERNET_SS);
// Use static IP if build flags are defined, otherwise DHCP
#if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET) && defined(ETHERNET_STATIC_DNS)
IPAddress ip(ETHERNET_STATIC_IP);
IPAddress gateway(ETHERNET_STATIC_GATEWAY);
IPAddress subnet(ETHERNET_STATIC_SUBNET);
IPAddress dns(ETHERNET_STATIC_DNS);
Ethernet.begin(mac, ip, dns, gateway, subnet);
#else
if (Ethernet.begin(mac) == 0) {
ETHERNET_DEBUG_PRINTLN("Failed to initialize RAK13800 hardware.");
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
ETHERNET_DEBUG_PRINTLN("Ethernet hardware not found.");
} else if (Ethernet.linkStatus() == LinkOFF) {
ETHERNET_DEBUG_PRINTLN("Ethernet cable not connected.");
} else {
ETHERNET_DEBUG_PRINTLN("DHCP failed for unknown reason.");
}
return false;
}
#endif
ETHERNET_DEBUG_PRINTLN("Ethernet begin complete");
ETHERNET_DEBUG_PRINT_IP("IP Address", Ethernet.localIP());
ETHERNET_DEBUG_PRINT_IP("Subnet Mask", Ethernet.subnetMask());
ETHERNET_DEBUG_PRINT_IP("Gateway", Ethernet.gatewayIP());
ETHERNET_DEBUG_PRINT_IP("DNS", Ethernet.dnsServerIP());
server.begin();
ETHERNET_DEBUG_PRINTLN("listening on TCP port: %d", ETHERNET_TCP_PORT);
return true;
}
int RAK13800EthernetInterface::available() {
return client.available();
}
int RAK13800EthernetInterface::read() {
return client.read();
}
size_t RAK13800EthernetInterface::write(const uint8_t *buf, size_t size) {
return client.write(buf, size);
}
bool RAK13800EthernetInterface::isConnected() const {
return _isConnected;
}
void RAK13800EthernetInterface::loop() {
Ethernet.maintain();
auto newClient = server.accept();
if (newClient) {
IPAddress remoteIp = newClient.remoteIP();
uint16_t remotePort = newClient.remotePort();
ETHERNET_DEBUG_PRINTLN("New client accepted %u.%u.%u.%u:%u", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3], remotePort);
if (client) {
ETHERNET_DEBUG_PRINTLN("Closing previous client");
client.stop();
}
client = newClient;
onClientConnected();
}
_isConnected = client.connected();
}
@@ -0,0 +1,27 @@
#pragma once
#include "../SerialEthernetInterface.h"
#include <SPI.h>
#include <RAK13800_W5100S.h>
class RAK13800EthernetInterface : public SerialEthernetInterface {
bool _isConnected;
EthernetServer server;
EthernetClient client;
public:
RAK13800EthernetInterface() : server(EthernetServer(ETHERNET_TCP_PORT)) {
_isConnected = false;
}
bool begin();
void loop() override;
// BaseSerialInterface methods
bool isConnected() const override;
int available() override;
int read() override;
size_t write(const uint8_t *buf, size_t size) override;
};
@@ -0,0 +1,140 @@
#include "SerialEthernetInterface.h"
#define RECV_STATE_IDLE 0
#define RECV_STATE_HDR_FOUND 1
#define RECV_STATE_LEN1_FOUND 2
#define RECV_STATE_LEN2_FOUND 3
bool SerialEthernetInterface::begin() {
return true;
}
void SerialEthernetInterface::enable() {
if (_isEnabled) return;
_isEnabled = true;
clearBuffers();
}
void SerialEthernetInterface::disable() {
_isEnabled = false;
}
size_t SerialEthernetInterface::writeFrame(const uint8_t src[], size_t len) {
if (len > MAX_FRAME_SIZE) {
ETHERNET_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d\n", len);
return 0;
}
if (isConnected() && len > 0) {
if (send_queue_len >= FRAME_QUEUE_SIZE) {
ETHERNET_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
return 0;
}
send_queue[send_queue_len].len = len; // add to send queue
memcpy(send_queue[send_queue_len].buf, src, len);
send_queue_len++;
return len;
}
return 0;
}
bool SerialEthernetInterface::isWriteBusy() const {
return false;
}
void SerialEthernetInterface::onClientConnected() {
_state = RECV_STATE_IDLE;
_frame_len = 0;
_rx_len = 0;
}
size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) {
if (isConnected()) {
if (send_queue_len > 0) { // first, check send queue
_last_write = millis();
int len = send_queue[0].len;
#if ETHERNET_RAW_LINE
ETHERNET_DEBUG_PRINTLN("TX line len=%d", len);
client.write(send_queue[0].buf, len);
client.write("\r\n", 2);
#else
uint8_t pkt[3+len]; // use same header as serial interface so client can delimit frames
pkt[0] = '>';
pkt[1] = (len & 0xFF); // LSB
pkt[2] = (len >> 8); // MSB
memcpy(&pkt[3], send_queue[0].buf, send_queue[0].len);
ETHERNET_DEBUG_PRINTLN("Sending frame len=%d", len);
#if ETHERNET_DEBUG_LOGGING && ARDUINO
ETHERNET_DEBUG_PRINTLN("TX frame len=%d", len);
#endif
write(pkt, 3 + len);
#endif
send_queue_len--;
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
send_queue[i] = send_queue[i + 1];
}
} else {
while (available()) {
int c = read();
if (c < 0) break;
#if ETHERNET_RAW_LINE
if (c == '\r' || c == '\n') {
if (_rx_len == 0) {
continue;
}
uint16_t out_len = _rx_len;
if (out_len > MAX_FRAME_SIZE) out_len = MAX_FRAME_SIZE;
memcpy(dest, _rx_buf, out_len);
_rx_len = 0;
return out_len;
}
if (_rx_len < MAX_FRAME_SIZE) {
_rx_buf[_rx_len] = (uint8_t)c;
_rx_len++;
}
#else
switch (_state) {
case RECV_STATE_IDLE:
if (c == '<') {
_state = RECV_STATE_HDR_FOUND;
}
break;
case RECV_STATE_HDR_FOUND:
_frame_len = (uint8_t)c;
_state = RECV_STATE_LEN1_FOUND;
break;
case RECV_STATE_LEN1_FOUND:
_frame_len |= ((uint16_t)c) << 8;
_rx_len = 0;
_state = _frame_len > 0 ? RECV_STATE_LEN2_FOUND : RECV_STATE_IDLE;
break;
default:
if (_rx_len < MAX_FRAME_SIZE) {
_rx_buf[_rx_len] = (uint8_t)c;
}
_rx_len++;
if (_rx_len >= _frame_len) {
if (_frame_len > MAX_FRAME_SIZE) {
_frame_len = MAX_FRAME_SIZE;
}
#if ETHERNET_DEBUG_LOGGING && ARDUINO
ETHERNET_DEBUG_PRINTLN("RX frame len=%d", _frame_len);
#endif
memcpy(dest, _rx_buf, _frame_len);
_state = RECV_STATE_IDLE;
return _frame_len;
}
}
#endif
}
}
}
return 0;
}
@@ -0,0 +1,75 @@
#pragma once
#include "../BaseSerialInterface.h"
#ifndef ETHERNET_TCP_PORT
#define ETHERNET_TCP_PORT 5000
#endif
// define ETHERNET_RAW_LINE=1 to use raw line-based CLI instead of framed packets
class SerialEthernetInterface : public BaseSerialInterface {
bool _isEnabled;
unsigned long _last_write;
uint8_t _state;
uint16_t _frame_len;
uint16_t _rx_len;
uint8_t _rx_buf[MAX_FRAME_SIZE];
struct Frame {
uint8_t len;
uint8_t buf[MAX_FRAME_SIZE];
};
#define FRAME_QUEUE_SIZE 4
int send_queue_len;
Frame send_queue[FRAME_QUEUE_SIZE];
void clearBuffers() {
send_queue_len = 0;
_state = 0;
_frame_len = 0;
_rx_len = 0;
}
protected:
public:
SerialEthernetInterface() {
_isEnabled = false;
_last_write = 0;
send_queue_len = 0;
_state = 0;
_frame_len = 0;
_rx_len = 0;
}
bool begin();
void onClientConnected();
// BaseSerialInterface methods
void enable() override;
void disable() override;
bool isEnabled() const override { return _isEnabled; }
bool isConnected() const override;
bool isWriteBusy() const override;
size_t writeFrame(const uint8_t src[], size_t len) override;
size_t checkRecvFrame(uint8_t dest[]) override;
virtual int available() = 0;
virtual int read() = 0;
virtual size_t write(const uint8_t *buf, size_t size) = 0;
};
#if ETHERNET_DEBUG_LOGGING && ARDUINO
#include <Arduino.h>
#define ETHERNET_DEBUG_PRINT(F, ...) Serial.printf("ETH: " F, ##__VA_ARGS__)
#define ETHERNET_DEBUG_PRINTLN(F, ...) Serial.printf("ETH: " F "\n", ##__VA_ARGS__)
#define ETHERNET_DEBUG_PRINT_IP(name, ip) Serial.printf("ETH: " name ": %u.%u.%u.%u" "\n", ip[0], ip[1], ip[2], ip[3])
#else
#define ETHERNET_DEBUG_PRINT(...) {}
#define ETHERNET_DEBUG_PRINTLN(...) {}
#define ETHERNET_DEBUG_PRINT_IP(...) {}
#endif
@@ -0,0 +1,94 @@
#include "CH390EthernetInterface.h"
void onWiFiEvent(WiFiEvent_t event) {
switch(event){
case ARDUINO_EVENT_ETH_START:
ETHERNET_DEBUG_PRINTLN("Ethernet Started");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
ETHERNET_DEBUG_PRINTLN("Ethernet Connected");
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
ETHERNET_DEBUG_PRINTLN("Ethernet Disconnected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
ETHERNET_DEBUG_PRINTLN("Ethernet Got IP");
ETHERNET_DEBUG_PRINT_IP("IP Address", CH390.localIP());
ETHERNET_DEBUG_PRINT_IP("Subnet Mask", CH390.subnetMask());
ETHERNET_DEBUG_PRINT_IP("Gateway", CH390.gatewayIP());
ETHERNET_DEBUG_PRINT_IP("DNS", CH390.dnsIP());
ETHERNET_DEBUG_PRINTLN("MAC Address: %s", CH390.macAddress().c_str());
break;
default:
break;
}
}
bool CH390EthernetInterface::begin() {
// listen to ethernet events
WiFi.onEvent(onWiFiEvent);
// Init CH390
ch390_config_t config = CH390_DEFAULT_CONFIG();
config.spi_miso_gpio = ETH_MISO_PIN;
config.spi_mosi_gpio = ETH_MOSI_PIN;
config.spi_sck_gpio = ETH_SCLK_PIN;
config.spi_cs_gpio = ETH_CS_PIN;
config.int_gpio = ETH_INT_PIN;
if (!CH390.begin(config)) {
ETHERNET_DEBUG_PRINTLN("Failed to initialize CH390 hardware.");
return false;
}
// Setup Static IP if build flags are present
#if defined(ETHERNET_STATIC_IP) && defined(ETHERNET_STATIC_GATEWAY) && defined(ETHERNET_STATIC_SUBNET)
IPAddress ip(ETHERNET_STATIC_IP);
IPAddress gw(ETHERNET_STATIC_GATEWAY);
IPAddress sn(ETHERNET_STATIC_SUBNET);
CH390.config(ip, gw, sn);
#endif
// Start Server
server.begin(ETHERNET_TCP_PORT);
ETHERNET_DEBUG_PRINTLN("listening on TCP port: %d", ETHERNET_TCP_PORT);
return true;
}
int CH390EthernetInterface::available() {
return client.available();
}
int CH390EthernetInterface::read() {
return client.read();
}
size_t CH390EthernetInterface::write(const uint8_t *buf, size_t size) {
return client.write(buf, size);
}
bool CH390EthernetInterface::isConnected() const {
return _isConnected;
}
void CH390EthernetInterface::loop() {
if (server.hasClient()) {
auto newClient = server.available();
if (newClient) {
IPAddress remoteIp = newClient.remoteIP();
uint16_t remotePort = newClient.remotePort();
ETHERNET_DEBUG_PRINTLN("New client accepted %u.%u.%u.%u:%u", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3], remotePort);
if (client) {
ETHERNET_DEBUG_PRINTLN("Closing previous client");
client.stop();
}
client = newClient;
onClientConnected();
}
}
_isConnected = client.connected();
}
@@ -0,0 +1,30 @@
#pragma once
#include "../SerialEthernetInterface.h"
#include <SPI.h>
#include <WiFi.h>
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <ESP32_CH390.h>
class CH390EthernetInterface : public SerialEthernetInterface {
bool _isConnected;
WiFiServer server;
WiFiClient client;
public:
CH390EthernetInterface(){
_isConnected = false;
}
bool begin();
void loop() override;
// BaseSerialInterface methods
bool isConnected() const override;
int available() override;
int read() override;
size_t write(const uint8_t *buf, size_t size) override;
};
+157
View File
@@ -0,0 +1,157 @@
#pragma once
#ifdef ETHERNET_ENABLED
#include <Arduino.h>
#include <SPI.h>
#include <RAK13800_W5100S.h>
#include <helpers/nrf52/EthernetMac.h>
#define PIN_SPI1_MISO (29)
#define PIN_SPI1_MOSI (30)
#define PIN_SPI1_SCK (3)
static SPIClass ETHERNET_SPI_PORT(NRF_SPIM1, PIN_SPI1_MISO, PIN_SPI1_SCK, PIN_SPI1_MOSI);
#define PIN_ETHERNET_POWER_EN WB_IO2
#define PIN_ETHERNET_RESET 21
#define PIN_ETHERNET_SS 26
#ifndef ETHERNET_TCP_PORT
#define ETHERNET_TCP_PORT 23 // telnet port for CLI access
#endif
#ifndef ETHERNET_CLI_BANNER
#define ETHERNET_CLI_BANNER "MeshCore CLI"
#endif
#define ETHERNET_RETRY_INTERVAL_MS 30000
static EthernetServer ethernet_server(ETHERNET_TCP_PORT);
static EthernetClient ethernet_client;
static volatile bool ethernet_running = false;
// FreeRTOS task: handles hw init, DHCP, and retries in the background
static void ethernet_task(void* param) {
(void)param;
Serial.println("ETH: Initializing hardware");
// WB_IO2 (power enable) is already driven HIGH by early constructor
// in RAK4631Board.cpp to support POE boot.
// Skip hardware reset — the W5100S comes out of power-on reset cleanly,
// and toggling reset kills the PHY link which breaks POE power.
pinMode(PIN_ETHERNET_RESET, OUTPUT);
digitalWrite(PIN_ETHERNET_RESET, HIGH);
ETHERNET_SPI_PORT.begin();
Ethernet.init(ETHERNET_SPI_PORT, PIN_ETHERNET_SS);
uint8_t mac[6];
generateEthernetMac(mac);
Serial.printf("ETH: MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
// Retry loop: keep trying until we get an IP
while (!ethernet_running) {
Serial.println("ETH: Attempting DHCP...");
if (Ethernet.begin(mac, 10000, 2000) == 0) {
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("ETH: Hardware not found, giving up");
vTaskDelete(NULL);
return;
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("ETH: Cable not connected, will retry");
} else {
Serial.println("ETH: DHCP failed, will retry");
}
vTaskDelay(pdMS_TO_TICKS(ETHERNET_RETRY_INTERVAL_MS));
continue;
}
IPAddress ip = Ethernet.localIP();
Serial.printf("ETH: IP: %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
Serial.printf("ETH: Listening on TCP port %d\n", ETHERNET_TCP_PORT);
ethernet_server.begin();
ethernet_running = true;
}
// DHCP succeeded, task is done
vTaskDelete(NULL);
}
static void ethernet_start_task() {
xTaskCreate(ethernet_task, "eth_init", 1024, NULL, 1, NULL);
}
// Format ethernet status into reply buffer. Returns true if command was handled.
static bool ethernet_handle_command(const char* command, char* reply) {
if (strcmp(command, "eth.status") == 0) {
if (!ethernet_running) {
strcpy(reply, "ETH: not connected");
} else {
IPAddress ip = Ethernet.localIP();
sprintf(reply, "ETH: %u.%u.%u.%u:%d", ip[0], ip[1], ip[2], ip[3], ETHERNET_TCP_PORT);
}
return true;
}
return false;
}
// Check for new TCP client connections, replacing any existing connection.
// Use accept() (not available()) so we only see newly-accepted sockets;
// available() also returns existing connected sockets that have data, which
// would force us to disambiguate every inbound packet from a real new client.
static void ethernet_check_client() {
auto newClient = ethernet_server.accept();
if (newClient) {
if (ethernet_client) ethernet_client.stop();
ethernet_client = newClient;
IPAddress ip = ethernet_client.remoteIP();
Serial.printf("ETH: Client connected from %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
ethernet_client.println(ETHERNET_CLI_BANNER);
}
}
// Call from loop() to maintain DHCP and check for new clients
static void ethernet_loop_maintain() {
if (ethernet_running) {
ethernet_check_client();
Ethernet.maintain();
}
}
// Read a line from the Ethernet client into the command buffer.
// Returns true when a complete line is ready to process (command is null-terminated).
// The caller should process the command and then reset ethernet_command[0] = 0.
static bool ethernet_read_line(char* ethernet_command, size_t buf_size) {
if (!ethernet_running || !ethernet_client || !ethernet_client.connected()) return false;
int elen = strlen(ethernet_command);
while (ethernet_client.available() && elen < (int)buf_size - 1) {
char c = ethernet_client.read();
if (c == '\n' && elen == 0) continue; // ignore leading LF (from CR+LF)
if (c == '\r' || c == '\n') { ethernet_command[elen++] = '\r'; break; }
ethernet_command[elen++] = c;
ethernet_command[elen] = 0;
}
if (elen == (int)buf_size - 1) {
ethernet_command[buf_size - 1] = '\r';
}
if (elen > 0 && ethernet_command[elen - 1] == '\r') {
ethernet_command[elen - 1] = 0;
ethernet_client.println();
return true;
}
return false;
}
// Send a reply to the Ethernet client
static void ethernet_send_reply(const char* reply) {
if (reply[0]) {
ethernet_client.print(" -> "); ethernet_client.println(reply);
}
}
#endif // ETHERNET_ENABLED
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <Arduino.h>
static inline void generateEthernetMac(uint8_t mac[6]) {
uint32_t device_id = NRF_FICR->DEVICEID[0];
mac[0] = 0x02;
mac[1] = 0x92;
mac[2] = 0x1F;
mac[3] = (device_id >> 16) & 0xFF;
mac[4] = (device_id >> 8) & 0xFF;
mac[5] = device_id & 0xFF;
}
+63 -10
View File
@@ -2,10 +2,12 @@
#include <RadioLib.h>
#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received
#define SX126X_IRQ_PREAMBLE_DETECTED 0x04
class CustomLLCC68 : public LLCC68 {
uint32_t _preambleMillis = 66;
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
public:
CustomLLCC68(Module *mod) : LLCC68(mod) { }
@@ -66,11 +68,11 @@ class CustomLLCC68 : public LLCC68 {
setRxBoostedGainMode(SX126X_RX_BOOSTED_GAIN);
#endif
#if defined(SX126X_RXEN) || defined(SX126X_TXEN)
#ifndef SX1262X_RXEN
#define SX1262X_RXEN RADIOLIB_NC
#ifndef SX126X_RXEN
#define SX126X_RXEN RADIOLIB_NC
#endif
#ifndef SX1262X_TXEN
#define SX1262X_TXEN RADIOLIB_NC
#ifndef SX126X_TXEN
#define SX126X_TXEN RADIOLIB_NC
#endif
setRfSwitchPins(SX126X_RXEN, SX126X_TXEN);
#endif
@@ -78,10 +80,61 @@ class CustomLLCC68 : public LLCC68 {
return true; // success
}
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags
return LLCC68::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
}
bool isReceiving() {
uint16_t irq = getIrqFlags();
bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED);
return detected;
uint32_t irq = getIrqFlags();
bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2
bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4
bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5
uint32_t now = millis();
if (hdrErr) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0;
_headerSeen = false;
return false;
}
if (!header && _headerSeen) {
// something cleared the header flag, reset our state.
_activityAt = 0; _headerSeen = false;
return false;
}
if (header) {
if (!_headerSeen) { _headerSeen = true; _activityAt = now; };
if (now - _activityAt > _maxPayloadMillis) {
MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis);
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0; _headerSeen = false;
return false;
}
return true;
}
if (preamble) {
if (_activityAt == 0) _activityAt = now;
if (now - _activityAt > _preambleMillis) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED);
_activityAt = 0;
MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis);
return false;
}
return true;
}
_activityAt = 0; _headerSeen = false;
return false;
}
void setPreambleMillis(uint32_t preambleMillis) {
_preambleMillis = preambleMillis;
MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis);
}
void setMaxPayloadMillis(uint32_t payloadMillis) {
_maxPayloadMillis = payloadMillis;
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
}
bool getRxBoostedGainMode() {
@@ -14,6 +14,10 @@ public:
((CustomLLCC68 *)_radio)->setBandwidth(bw);
((CustomLLCC68 *)_radio)->setCodingRate(cr);
updatePreamble(sf);
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomLLCC68 *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomLLCC68 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool isReceivingPacket() override {
+58 -4
View File
@@ -4,6 +4,10 @@
#include "MeshCore.h"
class CustomLR1110 : public LR1110 {
uint32_t _preambleMillis = 66;
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
bool _rx_boosted = false;
public:
@@ -31,11 +35,61 @@ class CustomLR1110 : public LR1110 {
bool getRxBoostedGainMode() const { return _rx_boosted; }
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags.
return LR1110::startReceive(RADIOLIB_LR11X0_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
}
bool isReceiving() {
uint16_t irq = getIrqStatus();
bool detected = ((irq & RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID) || (irq & RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED));
return detected;
uint32_t irq = getIrqStatus();
bool preamble = irq & RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED; // bit 4
bool header = irq & RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID; // bit 5
bool hdrErr = irq & RADIOLIB_LR11X0_IRQ_HEADER_ERR; // bit 6
uint32_t now = millis();
if (hdrErr) {
clearIrqState(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID | RADIOLIB_LR11X0_IRQ_HEADER_ERR);
_activityAt = 0;
_headerSeen = false;
return false;
}
if (!header && _headerSeen) {
// something cleared the header flag, reset our state.
_activityAt = 0; _headerSeen = false;
return false;
}
if (header) {
if (!_headerSeen) { _headerSeen = true; _activityAt = now; };
if (now - _activityAt > _maxPayloadMillis) {
MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis);
clearIrqState(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR11X0_IRQ_SYNC_WORD_HEADER_VALID | RADIOLIB_LR11X0_IRQ_HEADER_ERR);
_activityAt = 0; _headerSeen = false;
return false;
}
return true;
}
if (preamble) {
if (_activityAt == 0) _activityAt = now;
if (now - _activityAt > _preambleMillis) {
clearIrqState(RADIOLIB_LR11X0_IRQ_PREAMBLE_DETECTED);
_activityAt = 0;
MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis);
return false;
}
return true;
}
_activityAt = 0; _headerSeen = false;
return false;
}
void setPreambleMillis(uint32_t preambleMillis) {
_preambleMillis = preambleMillis;
MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis);
}
void setMaxPayloadMillis(uint32_t payloadMillis) {
_maxPayloadMillis = payloadMillis;
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
}
uint8_t getSpreadingFactor() const { return spreadingFactor; }
};
};
+5 -1
View File
@@ -14,9 +14,11 @@ public:
((CustomLR1110 *)_radio)->setBandwidth(bw);
((CustomLR1110 *)_radio)->setCodingRate(cr);
updatePreamble(sf);
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomLR1110 *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomLR1110 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1110 *)_radio)->getFreqMHz()); }
bool isReceivingPacket() override {
return ((CustomLR1110 *)_radio)->isReceiving();
}
@@ -47,4 +49,6 @@ public:
bool getRxBoostedGainMode() const override {
return ((CustomLR1110 *)_radio)->getRxBoostedGainMode();
}
void doResetAGC() override { lr11x0ResetAGC((LR11x0 *)_radio, ((CustomLR1110 *)_radio)->getFreqMHz(), getRxBoostedGainMode()); }
};
+131
View File
@@ -0,0 +1,131 @@
#pragma once
#include <RadioLib.h>
#include "MeshCore.h"
class CustomLR2021 : public LR2021 {
uint32_t _preambleMillis = 66;
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
bool _rx_boosted = false;
public:
CustomLR2021(Module *mod) : LR2021(mod) { irqDioNum = LR2021_IRQ_DIO; }
bool std_init(SPIClass* spi = NULL)
{
#ifdef LR2021_TCXO_VOLTAGE
float tcxo = LR2021_TCXO_VOLTAGE;
#else
float tcxo = 1.6f;
#endif
#ifdef LORA_CR
uint8_t cr = LORA_CR;
#else
uint8_t cr = 5;
#endif
#if defined(P_LORA_SCLK)
#ifdef NRF52_PLATFORM
if (spi) { spi->setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI); spi->begin(); }
#elif defined(RP2040_PLATFORM)
if (spi) {
spi->setMISO(P_LORA_MISO);
//spi->setCS(P_LORA_NSS); // Setting CS results in freeze
spi->setSCK(P_LORA_SCLK);
spi->setMOSI(P_LORA_MOSI);
spi->begin();
}
#else
if (spi) spi->begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
#endif
#endif
int status = begin(LORA_FREQ, LORA_BW, LORA_SF, cr, RADIOLIB_LR2021_LORA_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, tcxo);
// if radio init fails with -707/-706, try again with tcxo voltage set to 0.0f
if (status == RADIOLIB_ERR_SPI_CMD_FAILED || status == RADIOLIB_ERR_SPI_CMD_INVALID) {
tcxo = 0.0f;
status = begin(LORA_FREQ, LORA_BW, LORA_SF, cr, RADIOLIB_LR2021_LORA_SYNC_WORD_PRIVATE, LORA_TX_POWER, 16, tcxo);
}
if (status != RADIOLIB_ERR_NONE) {
Serial.print("ERROR: radio init failed: ");
Serial.println(status);
return false; // fail
}
setCRC(2);
explicitHeader();
#ifdef LR2021_RX_BOOSTED_GAIN
setRxBoostedGainMode(LR2021_RX_BOOSTED_GAIN);
#endif
return true; // success
}
float getFreqMHz() const { return freqMHz; }
bool getRxBoostedGainMode() const { return _rx_boosted; }
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags
return LR2021::startReceive(RADIOLIB_LR2021_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
}
bool isReceiving() {
uint32_t irq = getIrqStatus();
bool preamble = irq & RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED; // bit 5
bool header = irq & RADIOLIB_LR2021_IRQ_LORA_HEADER_VALID; // bit 6
bool hdrErr = irq & RADIOLIB_LR2021_IRQ_LORA_HDR_CRC_ERROR; // bit 9
uint32_t now = millis();
if (hdrErr) {
clearIrqFlags(RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR2021_IRQ_LORA_HEADER_VALID | RADIOLIB_LR2021_IRQ_LORA_HDR_CRC_ERROR);
_activityAt = 0;
_headerSeen = false;
return false;
}
if (!header && _headerSeen) {
// something cleared the header flag, reset our state.
_activityAt = 0; _headerSeen = false;
return false;
}
if (header) {
if (!_headerSeen) { _headerSeen = true; _activityAt = now; };
if (now - _activityAt > _maxPayloadMillis) {
MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis);
clearIrqFlags(RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED | RADIOLIB_LR2021_IRQ_LORA_HEADER_VALID | RADIOLIB_LR2021_IRQ_LORA_HDR_CRC_ERROR);
_activityAt = 0; _headerSeen = false;
return false;
}
return true;
}
if (preamble) {
if (_activityAt == 0) _activityAt = now;
if (now - _activityAt > _preambleMillis) {
clearIrqFlags(RADIOLIB_LR2021_IRQ_PREAMBLE_DETECTED);
_activityAt = 0;
MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis);
return false;
}
return true;
}
_activityAt = 0; _headerSeen = false;
return false;
}
void setPreambleMillis(uint32_t preambleMillis) {
_preambleMillis = preambleMillis;
MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis);
}
void setMaxPayloadMillis(uint32_t payloadMillis) {
_maxPayloadMillis = payloadMillis;
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
}
uint8_t getSpreadingFactor() const { return spreadingFactor; }
};
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include "CustomLR2021.h"
#include "RadioLibWrappers.h"
#ifndef USE_LR2021
#define USE_LR2021
#endif
#ifndef LR2021_RX_BOOST_LEVEL
#define LR2021_RX_BOOST_LEVEL 7
#endif
class CustomLR2021Wrapper : public RadioLibWrapper {
public:
CustomLR2021Wrapper(CustomLR2021& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
void setParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
((CustomLR2021 *)_radio)->setFrequency(freq);
((CustomLR2021 *)_radio)->setSpreadingFactor(sf);
((CustomLR2021 *)_radio)->setBandwidth(bw);
((CustomLR2021 *)_radio)->setCodingRate(cr);
updatePreamble(sf);
applySideDetectorConfig();
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomLR2021 *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomLR2021 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool configSideDetectors(const uint8_t* sideDetSFs, uint8_t num, float bw) override {
LR2021LoRaSideDetector_t tmp[3];
uint8_t sf = getSpreadingFactor();
if (sf >= 10 && num > 1) { return false; } // only 1 side detector allowed when primary SF >= 10
for (int i = 0; i < num; i++) {
if (sideDetSFs[i] > 12 || sideDetSFs[i] < 5) { return false; } // must be valid SF
if (sideDetSFs[i] <= sf) { return false; } // must be < primary SF
if (sideDetSFs[i] > sf + 4) { return false; } // span must not be > 4
tmp[i].sf = sideDetSFs[i];
float tSym = calcTsym(tmp[i].sf, bw);
if (tSym >= 16.0f) {
tmp[i].ldro = true;
} else {
tmp[i].ldro = false;
}
tmp[i].invertIQ = false;
tmp[i].syncWord = 0x12;
}
int16_t status = ((CustomLR2021 *)_radio)->setSideDetector(tmp, num);
RadioLibWrapper::idle(); // trigger startReceive()
MESH_DEBUG_PRINTLN("setSideDetector() returned %d", status);
if (status == RADIOLIB_ERR_NONE) {
for (int i = 0; i < num; i++) { _sideDet[i] = tmp[i]; }
_numSideDet = num;
} else {
return false;
}
return true;
}
int16_t applySideDetectorConfig() {
int16_t status = ((CustomLR2021 *)_radio)->setSideDetector(_sideDet, _numSideDet);
RadioLibWrapper::idle(); // trigger startReceive()
return status;
}
float calcTsym(uint8_t sf, float bw) {
float tSym = (float)(uint32_t(1) << sf) / (float)bw;
return tSym;
}
bool isReceivingPacket() override {
return ((CustomLR2021 *)_radio)->isReceiving();
}
float getCurrentRSSI() override {
float rssi = -110;
((CustomLR2021 *)_radio)->getRssiInst(&rssi);
return rssi;
}
void onSendFinished() override {
RadioLibWrapper::onSendFinished();
_radio->setPreambleLength(preambleLengthForSF(getSpreadingFactor())); // overcomes weird issues with small and big pkts
}
float getLastRSSI() const override { return ((CustomLR2021 *)_radio)->getRSSI(); }
float getLastSNR() const override { return ((CustomLR2021 *)_radio)->getSNR(); }
uint8_t getSpreadingFactor() const override { return ((CustomLR2021 *)_radio)->getSpreadingFactor(); }
bool setRxBoostedGainMode(bool en) override {
((CustomLR2021 *)_radio)->standby(); // LR2021 must be in standby to accept setRxBoostedGainMode
int16_t status = ((CustomLR2021 *)_radio)->setRxBoostedGainMode(en ? LR2021_RX_BOOST_LEVEL: 0);
RadioLibWrapper::idle(); // trigger startReceive()
return status == RADIOLIB_ERR_NONE;
}
bool getRxBoostedGainMode() const override {
return ((CustomLR2021 *)_radio)->getRxBoostedGainMode();
}
protected:
LR2021LoRaSideDetector_t _sideDet[3];
size_t _numSideDet = 0;
};
+61 -7
View File
@@ -2,16 +2,70 @@
#include <RadioLib.h>
#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received
#define SX126X_IRQ_PREAMBLE_DETECTED 0x04
class CustomSTM32WLx : public STM32WLx {
uint32_t _preambleMillis = 66;
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
public:
CustomSTM32WLx(STM32WLx_Module *mod) : STM32WLx(mod) { }
bool isReceiving() {
uint16_t irq = getIrqFlags();
bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED);
return detected;
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags
return STM32WLx::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
}
bool isReceiving() {
uint32_t irq = getIrqFlags();
bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2
bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4
bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5
uint32_t now = millis();
if (hdrErr) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0;
_headerSeen = false;
return false;
}
if (!header && _headerSeen) {
// something cleared the header flag, reset our state.
_activityAt = 0; _headerSeen = false;
return false;
}
if (header) {
if (!_headerSeen) { _headerSeen = true; _activityAt = now; };
if (now - _activityAt > _maxPayloadMillis) {
MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis);
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0; _headerSeen = false;
return false;
}
return true;
}
if (preamble) {
if (_activityAt == 0) _activityAt = now;
if (now - _activityAt > _preambleMillis) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED);
_activityAt = 0;
MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis);
return false;
}
return true;
}
_activityAt = 0; _headerSeen = false;
return false;
}
void setPreambleMillis(uint32_t preambleMillis) {
_preambleMillis = preambleMillis;
MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis);
}
void setMaxPayloadMillis(uint32_t payloadMillis) {
_maxPayloadMillis = payloadMillis;
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
}
};
+4 -1
View File
@@ -15,6 +15,9 @@ public:
((CustomSTM32WLx *)_radio)->setBandwidth(bw);
((CustomSTM32WLx *)_radio)->setCodingRate(cr);
updatePreamble(sf);
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomSTM32WLx *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomSTM32WLx *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool isReceivingPacket() override {
@@ -32,5 +35,5 @@ public:
}
uint8_t getSpreadingFactor() const override { return ((CustomSTM32WLx *)_radio)->spreadingFactor; }
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); }
};
+59 -6
View File
@@ -3,10 +3,12 @@
#include <RadioLib.h>
#include "MeshCore.h"
#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received
#define SX126X_IRQ_PREAMBLE_DETECTED 0x04
class CustomSX1262 : public SX1262 {
uint32_t _preambleMillis = 66;
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
public:
CustomSX1262(Module *mod) : SX1262(mod) { }
@@ -98,10 +100,61 @@ class CustomSX1262 : public SX1262 {
return true; // success
}
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags
return SX1262::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
}
bool isReceiving() {
uint16_t irq = getIrqFlags();
bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED);
return detected;
uint32_t irq = getIrqFlags();
bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2
bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4
bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5
uint32_t now = millis();
if (hdrErr) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0;
_headerSeen = false;
return false;
}
if (!header && _headerSeen) {
// something cleared the header flag, reset our state.
_activityAt = 0; _headerSeen = false;
return false;
}
if (header) {
if (!_headerSeen) { _headerSeen = true; _activityAt = now; };
if (now - _activityAt > _maxPayloadMillis) {
MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis);
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0; _headerSeen = false;
return false;
}
return true;
}
if (preamble) {
if (_activityAt == 0) _activityAt = now;
if (now - _activityAt > _preambleMillis) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED);
_activityAt = 0;
MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis);
return false;
}
return true;
}
_activityAt = 0; _headerSeen = false;
return false;
}
void setPreambleMillis(uint32_t preambleMillis) {
_preambleMillis = preambleMillis;
MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis);
}
void setMaxPayloadMillis(uint32_t payloadMillis) {
_maxPayloadMillis = payloadMillis;
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
}
bool getRxBoostedGainMode() {
+5 -2
View File
@@ -18,6 +18,9 @@ public:
((CustomSX1262 *)_radio)->setBandwidth(bw);
((CustomSX1262 *)_radio)->setCodingRate(cr);
updatePreamble(sf);
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomSX1262 *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomSX1262 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool isReceivingPacket() override {
@@ -38,12 +41,12 @@ public:
((CustomSX1262 *)_radio)->sleep(false);
}
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
bool setRxBoostedGainMode(bool en) override {
return ((CustomSX1262 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
bool getRxBoostedGainMode() const override {
return ((CustomSX1262 *)_radio)->getRxBoostedGainMode();
}
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); }
};
+65 -11
View File
@@ -2,10 +2,12 @@
#include <RadioLib.h>
#define SX126X_IRQ_HEADER_VALID 0b0000010000 // 4 4 valid LoRa header received
#define SX126X_IRQ_PREAMBLE_DETECTED 0x04
class CustomSX1268 : public SX1268 {
uint32_t _preambleMillis = 66;
uint32_t _maxPayloadMillis = 3934;
uint32_t _activityAt = 0;
bool _headerSeen = false;
public:
CustomSX1268(Module *mod) : SX1268(mod) { }
@@ -66,11 +68,11 @@ class CustomSX1268 : public SX1268 {
setRxBoostedGainMode(SX126X_RX_BOOSTED_GAIN);
#endif
#if defined(SX126X_RXEN) || defined(SX126X_TXEN)
#ifndef SX1262X_RXEN
#define SX1262X_RXEN RADIOLIB_NC
#ifndef SX126X_RXEN
#define SX126X_RXEN RADIOLIB_NC
#endif
#ifndef SX1262X_TXEN
#define SX1262X_TXEN RADIOLIB_NC
#ifndef SX126X_TXEN
#define SX126X_TXEN RADIOLIB_NC
#endif
setRfSwitchPins(SX126X_RXEN, SX126X_TXEN);
#endif
@@ -78,12 +80,64 @@ class CustomSX1268 : public SX1268 {
return true; // success
}
bool isReceiving() {
uint16_t irq = getIrqFlags();
bool detected = (irq & SX126X_IRQ_HEADER_VALID) || (irq & SX126X_IRQ_PREAMBLE_DETECTED);
return detected;
int16_t startReceive() override {
// include the PREAMBLE_DETECTED irq bit in reported flags
return SX1268::startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED), RADIOLIB_IRQ_RX_DEFAULT_MASK, 0);
}
bool isReceiving() {
uint32_t irq = getIrqFlags();
bool preamble = irq & RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED; // bit 2
bool header = irq & RADIOLIB_SX126X_IRQ_HEADER_VALID; // bit 4
bool hdrErr = irq & RADIOLIB_SX126X_IRQ_HEADER_ERR; // bit 5
uint32_t now = millis();
if (hdrErr) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0;
_headerSeen = false;
return false;
}
if (!header && _headerSeen) {
// something cleared the header flag, reset our state.
_activityAt = 0; _headerSeen = false;
return false;
}
if (header) {
if (!_headerSeen) { _headerSeen = true; _activityAt = now; };
if (now - _activityAt > _maxPayloadMillis) {
MESH_DEBUG_PRINTLN("Clearing header IRQ after %ums", _maxPayloadMillis);
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED | RADIOLIB_SX126X_IRQ_HEADER_VALID | RADIOLIB_SX126X_IRQ_HEADER_ERR | RADIOLIB_SX126X_IRQ_SYNC_WORD_VALID);
_activityAt = 0; _headerSeen = false;
return false;
}
return true;
}
if (preamble) {
if (_activityAt == 0) _activityAt = now;
if (now - _activityAt > _preambleMillis) {
clearIrqFlags(RADIOLIB_SX126X_IRQ_PREAMBLE_DETECTED);
_activityAt = 0;
MESH_DEBUG_PRINTLN("Clearing preamble IRQ after %ums", _preambleMillis);
return false;
}
return true;
}
_activityAt = 0; _headerSeen = false;
return false;
}
void setPreambleMillis(uint32_t preambleMillis) {
_preambleMillis = preambleMillis;
MESH_DEBUG_PRINTLN("Set _preambleMillis=%u", _preambleMillis);
}
void setMaxPayloadMillis(uint32_t payloadMillis) {
_maxPayloadMillis = payloadMillis;
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
}
bool getRxBoostedGainMode() {
uint8_t rxGain = 0;
readRegister(RADIOLIB_SX126X_REG_RX_GAIN, &rxGain, 1);
+5 -2
View File
@@ -18,6 +18,9 @@ public:
((CustomSX1268 *)_radio)->setBandwidth(bw);
((CustomSX1268 *)_radio)->setCodingRate(cr);
updatePreamble(sf);
PacketMillis pm = calcMaxPacketMillis(sf, bw, cr, preambleLengthForSF(sf));
((CustomSX1268 *)_radio)->setPreambleMillis(pm.preambleMillis);
((CustomSX1268 *)_radio)->setMaxPayloadMillis(pm.payloadMillis);
}
bool isReceivingPacket() override {
@@ -35,12 +38,12 @@ public:
}
uint8_t getSpreadingFactor() const override { return ((CustomSX1268 *)_radio)->spreadingFactor; }
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
bool setRxBoostedGainMode(bool en) override {
return ((CustomSX1268 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
}
bool getRxBoostedGainMode() const override {
return ((CustomSX1268 *)_radio)->getRxBoostedGainMode();
}
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio, getRxBoostedGainMode()); }
};
+6 -6
View File
@@ -50,14 +50,14 @@ class CustomSX1276 : public SX1276 {
setCurrentLimit(SX127X_CURRENT_LIMIT);
#endif
#if defined(SX176X_RXEN) || defined(SX176X_TXEN)
#ifndef SX176X_RXEN
#define SX176X_RXEN RADIOLIB_NC
#if defined(SX127X_RXEN) || defined(SX127X_TXEN)
#ifndef SX127X_RXEN
#define SX127X_RXEN RADIOLIB_NC
#endif
#ifndef SX176X_TXEN
#define SX176X_TXEN RADIOLIB_NC
#ifndef SX127X_TXEN
#define SX127X_TXEN RADIOLIB_NC
#endif
setRfSwitchPins(SX176X_RXEN, SX176X_TXEN);
setRfSwitchPins(SX127X_RXEN, SX127X_TXEN);
#endif
setCRC(1);
+2 -2
View File
@@ -5,7 +5,7 @@
// Full receiver reset for LR11x0-family chips (LR1110, LR1120, LR1121).
// Warm sleep powers down analog, calibrate(0x3F) refreshes all calibration blocks,
// then re-applies RX settings that calibration may reset.
inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz) {
inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz, bool rx_boost_gain) {
radio->sleep(true, 0);
radio->standby(RADIOLIB_LR11X0_STANDBY_RC, true);
@@ -16,6 +16,6 @@ inline void lr11x0ResetAGC(LR11x0* radio, float freqMHz) {
radio->calibrateImageRejection(freqMHz - 4.0f, freqMHz + 4.0f);
#ifdef RX_BOOSTED_GAIN
radio->setRxBoostedGainMode(RX_BOOSTED_GAIN);
radio->setRxBoostedGainMode(rx_boost_gain);
#endif
}

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