Compare commits

..

261 Commits

Author SHA1 Message Date
pelgraine d601edd0ce meshpocket morse port 2026-04-19 12:34:46 +10:00
pelgraine a378f4f1aa Heltec Meshpocket: initial BLE companion port 2026-04-16 23:18:10 +10:00
pelgraine 1c4d5a0daa updated readme for clarity, esp re meck remote wifi repeaters functionality 2026-04-12 23:20:11 +10:00
pelgraine df6c977ee4 updated readme 2026-04-12 23:13:27 +10:00
pelgraine 7e9e69dd67 renamed WIP folders 2026-04-12 23:06:31 +10:00
pelgraine 6d7fd54b83 reordered emojis and improved scrolling in tdpro emojipicker; build emoji picker functionality into vkb for t5s3 2026-04-12 22:01:17 +10:00
pelgraine d2ce070a3f fix wifi companion builds sync bug & add planning for future 1000+ contacts load 2026-04-12 21:04:35 +10:00
pelgraine 44b68c40af tdpro platformio - removed unncessary helpers/esp32/SerialBLEInterface.cpp from build filters for wifi and standalone envs 2026-04-12 20:52:31 +10:00
pelgraine a4e8c31a16 fiiiiixed the contacts add and delete and toggle fav issues for real this time 2026-04-12 20:42:45 +10:00
pelgraine 8d69b69e1f fix contact limits in readme 2026-04-12 18:22:35 +10:00
pelgraine 0c032429eb Added new emoji to emoji picker; bug fixes for larger battery capacities recognition regression; updated readme for clarity on contacts add; updated firmware version; fix stupid blob storage size & buffer issue so now you can add contacts from last heard finally!!! Updated readme accordingly 2026-04-12 18:15:33 +10:00
pelgraine c578dcadc8 T5S3 - fixed touch selector fav contacts bug
TDPro - Update firmware build date

Contactsscreen.h — five changes:

- EPOCH_2026 = 1735689600UL constant added (Jan 1 2026 UTC), used in sort
  and formatAge.

- typeChar replaced by typeStr returning const char*, with "RS" for room
  servers (previously "S", easily confused with sensors). prefix buffer
  bumped to [5], all three snprintf calls updated to %s.

- Hop display: out_path_len == 0xFF branch now performs a live lookup
  against the 12 most recently heard advert paths (via
  getRecentlyHeard). Matches on first 7 bytes of pub_key, extracts hop
  count with a bph-aware sanity cap (64/bph max) to reject impossible
  values. Shows "~D" for direct flood neighbours, "~N" for N-hop flood
  path, "?" if not in the recent-heard cache. Resets to "?" on reboot
  until each contact re-advertises — intentional, ensures hop count is
  always fresh.

- Sort: _filteredTs now stores contact.lastmod (our local receive time)
  instead of contact.last_advert_timestamp (sender's claimed time).
  lastmod values below EPOCH_2026 are stored as 0 so stale repeaters
  with unsynced clocks and contacts received before our own timesync
  sink to the bottom of the list.

- formatAge rewritten: rejects timestamp == 0, timestamp < EPOCH_2026,
  and now < timestamp (all show "--" instead of wrapping or displaying
  garbage). Arithmetic changed from int to uint32_t, eliminating the
  signed overflow path that produced negative hour values. Age display
  call site switched from last_advert_timestamp to lastmod, so display
  self-corrects after a GPS or 4G timesync.
2026-04-12 12:44:10 +10:00
pelgraine ec42ac73a8 removed non-Meck v4 build 2026-04-12 09:25:38 +10:00
pelgraine aacf8c777f prelim techo card WIP files while I wait for hardware to arrive. claude putting excessive comments in platformio descriptors 2026-04-12 09:24:37 +10:00
pelgraine 570776478c merge tdeck pro max WIP variant into dev 2026-04-12 09:01:22 +10:00
pelgraine 4c654c99c6 remote wifi repeater updates - removed unnecessary envs for v4; setup v3 for remote wifi repeater role 2026-04-11 09:58:50 +10:00
pelgraine f436f5ba50 t5s3 contact limit fix 2026-04-09 12:18:29 +10:00
pelgraine 0252204d73 cpu fix for heltec v4 remote repeater build headless 2026-04-08 20:51:44 +10:00
pelgraine 595f0073f9 TDeckBoard.cpp — both * 3 / 2 thresholds changed to > designCapacity_mAh, so FCC=3000 with DC=2500 now triggers the Qmax + stored FCC correction.
SerialBLEInterface.cpp — added esp_bt.h include and three esp_ble_tx_power_set calls at +9 dBm after BLEDevice::init(), covering default, advertising, and scan power types.

MyMesh.h — FIRMWARE_VER_CODE bumped from 10 → 11.
MyMesh.cpp — The RESP_CODE_DEVICE_INFO frame construction now:
Byte 2: sends 0xFF (sentinel) when MAX_CONTACTS > 510, otherwise the normal MAX_CONTACTS / 2. Older apps interpret 0xFF as 510 contacts — completely harmless.
Bytes 80-81 (new, appended after the version string): uint16_t little-endian with the true MAX_CONTACTS value. Apps that understand v11+ read it here. Apps < v11 ignore trailing bytes — the BLE/serial frame protocol is length-delimited, so extra bytes at the tail are safe.

platformio.ini — Both BLE builds (meck_audio_ble, meck_4g_ble) bumped from 510 → 2000.

mymesh.cpp: writeContactRespFrame return type change (return _serial->writeFrame() result)
checkSerialInterface() batch-fill loop.
2026-04-07 20:04:36 +10:00
pelgraine 8aa0f0388e meck wifi remote repeater heltec v4 2026-04-05 21:14:52 +10:00
pelgraine b070af39cc t5s3 wifi remote repeater 2026-04-05 08:57:47 +10:00
pelgraine c939aa577b fix prior env sensor manager build filter for remote repeater envs 2026-04-04 12:38:06 +11:00
pelgraine abccfe154e improve remote wifi repeater compile time 2026-04-04 12:16:52 +11:00
pelgraine 23733ca555 improve tdpro all builds compilation time but esp for remote repeater envs 2026-04-04 12:08:17 +11:00
pelgraine 9d45ac52eb fix wifi repeater and remote repeater ota process, update firmware version platiformio 2026-04-04 11:40:25 +11:00
pelgraine 424e152d4b simple remote wifi repeater v0.2 & remote repeater path hash mode improvements 2026-04-04 10:51:48 +11:00
pelgraine c687133b05 tdpro refined file export contacts selection json 2026-03-31 02:49:57 +11:00
pelgraine c7d0449181 remove sleep for remote repeater 2026-03-30 13:20:31 +11:00
pelgraine 9ddb692806 fix mqttsubscribe 2026-03-30 13:11:54 +11:00
pelgraine 0cab2ddfa7 fix tdpro remote admin display and lora init sd card mix 2026-03-30 13:02:31 +11:00
pelgraine d07ad71d5d tdpro remote 4g repeater admin via web app 2026-03-30 12:23:02 +11:00
pelgraine b4983e48f0 set custom contact paths 2026-03-29 17:06:45 +11:00
pelgraine b991eb0fe7 bumped up max contacts for BLE companions to 510 2026-03-29 16:15:55 +11:00
pelgraine c15b30079c update f send key for previously recorded voice notes 2026-03-29 14:49:31 +11:00
pelgraine 9d7cbd4866 tdpro audio only - voice notes over lora - 5 seconds stage 1 2026-03-29 14:04:54 +11:00
pelgraine b9283af7fc update serial settings guide 2026-03-28 01:41:40 +11:00
pelgraine 39cd30890b update readme for new v1.5 features 2026-03-28 01:41:16 +11:00
pelgraine 902577ed10 update build date 2026-03-28 01:11:26 +11:00
pelgraine ce93cfa033 sd file manager ota system 2026-03-27 03:36:20 +11:00
pelgraine 2be399f65a undo accidental battery size change commit 2026-03-27 02:59:51 +11:00
pelgraine 5679cda38e tdpro touch paches - dialpad touch system conflict fix and longpress changed to 750ms 2026-03-27 02:43:06 +11:00
pelgraine 1ea883783c update firmware version for incoming ota file handler updates 2026-03-27 02:29:09 +11:00
pelgraine bf8cf32bc2 speed up ble sync time; fix version in tdpro platformio 2026-03-27 01:56:17 +11:00
pelgraine 465a29bb23 fix bootindex method so ereader subdirectory files are recognised and pre-cache is completed properly 2026-03-27 00:58:02 +11:00
pelgraine 81eca29b69 implement meshcore PR 2151 changes 2026-03-27 00:43:10 +11:00
pelgraine 342cf4e745 tdpro large font pref option; various large font ui fixes; fix fcc recognition in t5s3 to match 1500 2026-03-26 15:34:09 +11:00
pelgraine c52a190ace update build date 2026-03-26 00:56:20 +11:00
pelgraine a7bc7a4733 t5s3 only lightsleep mode 2026-03-25 20:17:42 +11:00
pelgraine 47a0d2cc95 Update README.md
Made it really stupidly clear that this is vibecoded
2026-03-25 19:57:47 +11:00
pelgraine 5dda0b686e Incorporate PR 2044 and 2141; tdpro alarm screen - needs 44khz mp3 for sounds 2026-03-25 19:57:35 +11:00
pelgraine 60dcd6a89e tdpro - remove hint after boot for non-first time flash 2026-03-25 07:25:48 +11:00
pelgraine 19efb52521 udpate readme 2026-03-23 15:16:57 +11:00
pelgraine 81ef3ea3c5 update hint text for nav hint for first-time flashers; fix spiffs failure for first-time flash boot 2026-03-23 14:59:31 +11:00
pelgraine 6f07b7a372 update readme to do 2026-03-23 13:36:54 +11:00
pelgraine b0f74b101a tdpro - update firmware build date; improve keyboard responsiveness after boot 2026-03-23 13:33:23 +11:00
pelgraine 06a064538e fix lock screen bug cpupowermanager issue 2026-03-22 22:56:28 +11:00
pelgraine 166a433353 td pro - fix missing F discover prompt on home screen for standalone variants 2026-03-22 19:58:12 +11:00
pelgraine 735fefd203 update readme 2026-03-22 18:50:59 +11:00
pelgraine ed5cda4f44 readme update for v1.3 2026-03-22 18:49:38 +11:00
pelgraine b208af83f6 t5s3 ota 2026-03-22 16:11:37 +11:00
pelgraine bad821ac4b tdpro ota update firmware functionality implemented; roomserver ui sender name display fix and speed up delivery time 2026-03-22 13:16:25 +11:00
pelgraine 8839012153 firmware build date 2026-03-22 11:49:47 +11:00
pelgraine 0958ef079e Fix T5S3 word wrap regression ereader; persist dark mode, portrait mode, baudrate, and auto lock timer in data store 2026-03-22 11:48:57 +11:00
pelgraine 0bf2826110 roomserver additions stage 2 and dm ui functionality updates 2026-03-22 10:51:59 +11:00
pelgraine c2840a43aa roomserver additions stage 1; dms ui functionality improvements; removed t-deck plus device variant 2026-03-21 21:27:20 +11:00
pelgraine e8a8be521a update firmware version and build date 2026-03-21 18:39:06 +11:00
pelgraine a627fbe0e9 t5s3 - fix for del channel ui and touch function 2026-03-20 23:20:20 +11:00
pelgraine 17f8233402 fix readme typo in last heard 2026-03-20 21:36:08 +11:00
pelgraine 1c9e9079f0 Merge branch 'dev' 2026-03-20 21:31:03 +11:00
pelgraine 69dc62fa78 update readme and txt reader guides for Meck v1.2 2026-03-20 21:17:18 +11:00
pelgraine f118a0949f fix td pro platformio version whioops; tdpro reader screen ui fix - press enter to go to page 2026-03-20 20:52:39 +11:00
pelgraine f78824cdc4 tdpro & t5s3 pro - lock screen power saving improvements; fix stupid stupid merged firmware - bug 2026-03-20 20:22:07 +11:00
pelgraine f81de07830 t5s3 - improved cardkb notes rendering; fix notes generic filename save type 2026-03-20 08:05:23 +11:00
pelgraine 3ae988c0bb t5s3 cardkb support; update firmware build date 2026-03-20 06:23:05 +11:00
pelgraine 5bed26cb72 mostly t5s3 and some tdpro fixes - chunked save infrastructure, chunked save implementation, non-blocking lazy save, favourite contacts edit double confirmation added, hibernate 4g modem properly 2026-03-20 05:27:20 +11:00
pelgraine c28d22e6cc Update README.md
Add discord link
2026-03-20 03:41:43 +11:00
pelgraine 8e1f2a3a87 t5s3 - last heard touch fix; lock screen 15 min refresh fix; update firmware build date 2026-03-19 17:05:40 +11:00
pelgraine 6d1447a45c fix accidental battery size commit from tdeckboard.h 2026-03-18 22:29:26 +11:00
pelgraine 77c92b3567 td pro: footer consistency text updates; improve key polling responsiveness; Add Last Heard screen, access by pressing h key; update mymesh firmware version and date 2026-03-18 22:22:11 +11:00
pelgraine 6db7b672ca t5s3 - improvements for page navigation to text reader 2026-03-17 19:17:51 +11:00
pelgraine 046cce6f43 tdpro - bugfix for slow responsiveness occurring if key is pressed during toaster popup message 2026-03-17 18:55:10 +11:00
pelgraine c2c2d8cf21 tdpro - reduce occurrences of slow key responsiveness on boot 2026-03-17 18:42:12 +11:00
pelgraine 148f8cea4f tdpro lock screen stage 2 - auto lock settings preferences implemented 2026-03-17 17:42:10 +11:00
pelgraine cd69ea546f tdpro lock screen stage 1 - double click user/boot to lock/unlock screen 2026-03-17 16:56:55 +11:00
pelgraine 7780a0d76e tdpro intial touch file selector implementation stage 1 2026-03-17 16:35:44 +11:00
pelgraine 33a3352692 tdpro - improved cpu usage for maps and increased key responsiveness after boot; updated firmware date and build 2026-03-17 15:46:42 +11:00
pelgraine 4004acf15d tdpro darkmode regression bugfixes; update readme 2026-03-15 15:36:18 +11:00
pelgraine 0b9402b530 updated readme for v.1.1 changes 2026-03-15 14:50:24 +11:00
pelgraine e55799f8a5 tdpro settings screen updates and ui changes; gps baudrate selector kept to settings screen only; firmware version and build date updated 2026-03-15 14:41:03 +11:00
pelgraine 0549efa627 tdpro v1.0 gps debug fix 2026-03-15 14:17:05 +11:00
pelgraine a52cf166cb update firmware build date 2026-03-14 20:14:38 +11:00
pelgraine facffe9f07 t5s3 settings screen fix for add channels; t5s3 home screen new message screen refresh fix 2026-03-14 20:14:13 +11:00
pelgraine 148fb7f001 t5s3 minor ui settings screen channel delete fixes 2026-03-14 15:36:40 +11:00
pelgraine 509411630b update readme 2026-03-13 23:20:22 +11:00
pelgraine a1ce8ca4d4 Has gps flag for tdpro to fix audio standalone compile bug 2026-03-13 22:50:24 +11:00
pelgraine b77059706b tdpro dark mode 2026-03-13 22:50:24 +11:00
pelgraine a6f0052b89 t5s3 standalone clock sync over serial 2026-03-13 22:50:24 +11:00
pelgraine 120c0a739b update firmware build date; t5s3 home ui fix for standalone build 2026-03-13 22:50:24 +11:00
pelgraine 816e41d63a tdpro - reduced redundant offline queue size to free up kb in standalone builds only 2026-03-13 22:50:24 +11:00
pelgraine 68d10f088f t5s3 standalone env, no wifi, no ble, no gps 2026-03-13 22:50:24 +11:00
pelgraine 2f0c8909b9 t5s3 webreader screen ui fixes 2026-03-13 22:50:24 +11:00
pelgraine c60255a44d fix repeater admin screen timeout buffer t5s3; minor ui fixes web reader screen t5s3 2026-03-13 22:50:24 +11:00
pelgraine 9040873526 script to create merged firmware automatically 2026-03-13 22:50:24 +11:00
pelgraine a564957a82 t5s3 portrait mode text fix 2026-03-13 22:50:24 +11:00
pelgraine b55892431d t5s3 portrait mode and dark mode 2026-03-13 22:50:24 +11:00
pelgraine dc5331702d 55s3 ghosting improvement 2026-03-13 22:50:24 +11:00
pelgraine 88a887eba2 t5s3 text reader screen 2026-03-13 22:50:24 +11:00
pelgraine b1218223e6 reader screen word wrap fixes t5s3 2026-03-13 22:50:24 +11:00
pelgraine 0971cd6015 t5s3 removed battery icon and replaced with text because it's ugly 2026-03-13 22:50:24 +11:00
pelgraine 81eb558868 t5s3 web reader ui fixes 2026-03-13 22:50:24 +11:00
pelgraine 74b24f1222 t5s3 wifi companion 2026-03-13 22:50:24 +11:00
pelgraine 182231deeb home ui icons t5s3; repeater path view tap method 2026-03-13 22:50:24 +11:00
pelgraine 3372c4aa1d t5s3 ui, screen refresh and ghosting fixes 2026-03-13 22:50:24 +11:00
pelgraine 467773366b t5s3 keyboard bug fix 2026-03-13 22:50:23 +11:00
pelgraine 753d125384 t5s3 touch mapping fix; ui fixed for repeateradminscreen; highlighting fixed for notes and discovery screen; t5s3 initial virtual keyboard implementation 2026-03-13 22:50:23 +11:00
pelgraine 8b78eac17f lock screen and lock screen clock t5s3 2026-03-13 22:50:23 +11:00
pelgraine 565c2a4c9b ui fixes including discover screen; clock fix 2026-03-13 22:50:23 +11:00
pelgraine 7ae9c47006 t5s3 ui fixes; t5s3 initial ble and wifi companion build envs 2026-03-13 22:50:23 +11:00
pelgraine 2a0497e5ba lower brightness to 4 for best darkroom reading; first prelim touch implementation; ui improvements 2026-03-13 22:50:23 +11:00
pelgraine 479673e90f LilyGo T5 S3 Epaper Pro No GPS version implementation stage 1 - H752-B; set backlight double click boot to 153 full brightness on, triple click to 40 brightness, double click off 2026-03-13 22:50:23 +11:00
pelgraine 9b15458927 Update README.md 2026-03-08 00:41:51 +11:00
pelgraine 85ccdf526e Update README.md 2026-03-08 00:40:47 +11:00
pelgraine c0dd59834c updated firmware version and date 2026-03-07 15:56:16 +11:00
pelgraine 90a4f5f881 multi.acks 1 set default for new firmware installs; can set rxdelay, int.thresh, gps.baud and multi.acks prefs over serial; adjust preamble length dependant on SF setting; updated serial settings guide and Meck Readme accordingly 2026-03-07 15:53:50 +11:00
pelgraine b27acb3252 multi-byte path implementation to bring Meck up to speed with Meshcore v1.14; fix regression of ui display in last msg rcd repeater hop count view and also update it for 2 byte nodes 2026-03-07 05:02:22 +11:00
pelgraine 580484e0ad update firmware version and date to v0.9.9 in prep for multibyte testing 2026-03-07 03:21:10 +11:00
pelgraine 9d7fbc3134 updated photo sizes in Launcher flash guide 2026-03-06 22:15:17 +11:00
pelgraine b859f8f168 Added guide to flashing Meck via Launcher 2026-03-06 22:10:38 +11:00
pelgraine 190b40c2ce fixed regression with previously committed missing code from webreaderscreen h 2026-03-06 18:26:32 +11:00
pelgraine 859919348d fix serial settings loop regression argh 2026-03-05 19:13:29 +11:00
pelgraine e91ad4bac4 repeater admin login regression bugfix and timing response improvements 2026-03-05 18:04:28 +11:00
pelgraine db58f8cf87 add additional firmware version update to v0.9.8 for impending bugfixes 2026-03-05 17:51:27 +11:00
pelgraine a74b1c3f7a fix accidental leftover preseed discovery code 2026-03-05 17:44:05 +11:00
pelgraine 12477af8c7 fix serial monitor loop issue 2026-03-04 19:47:19 +11:00
pelgraine 49d399c4d6 updated firmware build date 2026-03-04 19:25:01 +11:00
pelgraine 33f2e0fc6e proper discover node function working 2026-03-04 18:55:13 +11:00
pelgraine 7685de4be6 fix wifi connection path; enable phone hotspot connection pairing 2026-03-04 18:36:39 +11:00
pelgraine 3f4da4bc2b Enable settings setup over serial - see guide for details 2026-03-04 07:56:35 +11:00
pelgraine fe949235d9 fixed stupid persistent contacts saved bug in datastore; prelim contacts discovery function 2026-03-04 07:16:07 +11:00
pelgraine d92fdc9ffe updated accidental regression in settings - readded autoadd contacts settings; added wifi on off option to settings 2026-03-03 23:17:41 +11:00
pelgraine 3a6673edea attempt to fix contacts persistency error bug 2026-03-03 22:38:40 +11:00
pelgraine e2a04892f4 updated uitask for wifi companions 2026-03-03 22:07:39 +11:00
pelgraine 31db349305 new wifi companions with wifi setup in onboarding; update firmware version and date accordingly 2026-03-03 21:59:30 +11:00
pelgraine b444a664c5 removed gpsaiding references 2026-03-03 20:57:26 +11:00
pelgraine 4e4c6cba80 Removed GPSaiding as was causing device to lose fix 2026-03-03 17:26:12 +11:00
pelgraine a178d43046 refined gpsaiding integration now that gpsdutycycle is deleted 2026-03-02 20:01:10 +11:00
pelgraine 36c5fafec6 removed gps cycle due to slow or no fix from cold start frequency 2026-03-02 19:49:03 +11:00
pelgraine 5260f0ccea commented out setting for ringtone as appears to be impossible to silence 2026-03-02 07:42:56 +11:00
pelgraine edf3fb7fff commented out setting for ringtone as appears to be impossible to silence 2026-03-02 07:38:28 +11:00
pelgraine 129a75ed4e update firmware version and date; 2026-03-02 07:33:46 +11:00
pelgraine 1ecda1a8f5 fix qmax entries so fcc is limited to 2000mah and not 3000mah 2026-03-01 23:49:02 +11:00
pelgraine 4bb721e060 implementing low battery brownout protection to prevent contacts file corruption caused by low voltage reboot loop; board goes to sleep at 2800mv 2026-03-01 23:28:49 +11:00
pelgraine 4646fd6bd9 ringtone 2026-03-01 23:16:54 +11:00
pelgraine d1104d0b9c Hopefully faster gps fix after cold boot 2026-03-01 22:54:26 +11:00
pelgraine 513715e472 add contacts settings in settings 2026-03-01 14:11:39 +11:00
pelgraine 1dfab7d9a6 Add image and update README for T-Deck Pro 2026-03-01 13:39:26 +11:00
pelgraine 4724cded26 changed map labels so non ascii characters aren't displayed to make it more readable; implemented fix to prevent contacts rewrite if crash occurs during boot 2026-03-01 12:46:52 +11:00
pelgraine 74d5bfef70 fix labels and map icon rendering 2026-03-01 12:36:35 +11:00
pelgraine e9540bcf23 maps! version 1 - g key to access 2026-03-01 11:38:20 +11:00
pelgraine 2163a4c56c sync new message message read or unread notification display better between device ui and ble app; keep in channel after message sent, moved sent toaster popup to in channel 2026-03-01 08:01:47 +11:00
pelgraine a536196fd7 Added telemetry print to repeater admin including battery and temperature status 2026-02-27 23:09:51 +11:00
pelgraine 01a7ab80eb reoeater admin menu functions overhaul and expansion 2026-02-27 22:36:40 +11:00
pelgraine 44fe5da876 updated web app guide to note new search function and IRC details 2026-02-27 20:13:59 +11:00
pelgraine 652d853b0c updated sms and phone app guide with new call changes 2026-02-27 20:11:12 +11:00
pelgraine fdfac73427 updated readme to accommodate the several new changes in v0.9.5 2026-02-27 20:04:25 +11:00
pelgraine 351c23cc44 new emojis 2026-02-27 18:36:19 +11:00
pelgraine 6cad4f8610 press R in message channel screen view to select a message to reply directly to; update firmware version and date 2026-02-27 08:32:20 +11:00
pelgraine 6d8a01b593 fixed repeater path view regression so it's now back to being able to see 20 hops 2026-02-26 19:45:08 +11:00
pelgraine d5bc958621 Able to copy repeater path bytes into new message 2026-02-26 16:17:00 +11:00
pelgraine 14e29eb600 fix contacts screen nav bar regression 2026-02-26 14:33:29 +11:00
pelgraine 7915e5ef0b Changed max contacts handling to psram so Audio BLE is 400 → 500 contacts, 20 channels (Near BLE protocol max (510)). Audio Standalone350 → 1500 (40 channels → 20) PSRAM-backed. 4G BLE env is 400 → 500 with 20 channels (Near BLE protocol max (510)). 4G Standalone is 600 → 1500 contacts with 20 channels - PSRAM-backed 2026-02-26 14:14:39 +11:00
pelgraine 623f3eaec4 fix screen refresh when modem ready indicated 2026-02-26 02:35:55 +11:00
pelgraine 0b2b7e61b4 uncommented meck web reader in audio ble env option 2026-02-26 02:24:29 +11:00
pelgraine d159318b00 Fixed in-call screen and call ended notifications; fixed dial number screen print responsiveness; fixed firmware version 4G text issue caused by - instead of . 2026-02-26 02:19:10 +11:00
pelgraine 197b6de4a6 added Favourites filter to mesh Contacts scren; fixed regression with dropped in-call screen; fixed 0 key recognition 2026-02-25 23:50:52 +11:00
pelgraine db7c5778a1 removed redundant duplicate firmware version 2026-02-25 22:49:23 +11:00
pelgraine db0fb1d4c6 implemented search functionality with DuckDuckGo Lite 2026-02-25 22:39:53 +11:00
pelgraine 90b9045a90 contacts export function - save to SD card from contacts screen with toaster pop up confimation once completed 2026-02-25 22:19:44 +11:00
pelgraine fd33aa8d28 phone touchscreen dialpad now available, initial iteration for alterative to keyboard number text entry; contacts export from Contacts screen to save to sd card 2026-02-25 21:57:46 +11:00
pelgraine 3652970969 fix last message overflow rendering 2026-02-25 20:42:56 +11:00
pelgraine 7f03d6fbea added extra phone screen to allow phone or sms inbox selection to enabling dialing of non-contact numbers 2026-02-25 20:26:05 +11:00
pelgraine 049017cd2d Add apn database to enable modem to connect to network without wifi, same with updates to modem manager; adustments to settings screen to show imei, carrier, apn information; updated new no-ble 4G standalone env 2026-02-25 19:59:32 +11:00
pelgraine 2a72723eff update firmware version and build date 2026-02-25 19:34:59 +11:00
pelgraine ccb4280ae2 updated bq27220 function for better fcc battery readings; updates to webreader to enable epub downloads to sd 2026-02-25 19:14:56 +11:00
pelgraine 668aff8105 fixed stupid ui spacing 2026-02-24 15:06:17 +11:00
pelgraine 47a6dbc74b updated sms and phone app readme to match main 2026-02-24 14:49:01 +11:00
pelgraine 99c686acf2 updated home screen ui to read Phone instead of SMS 2026-02-24 14:47:49 +11:00
pelgraine 5de518d5f4 increased last seen msg rcd hop path view count limit and added scroll bar to path view 2026-02-24 14:07:57 +11:00
pelgraine a9b37ab697 updated firmware version and date now that we've got phone calls as well 2026-02-24 14:02:53 +11:00
pelgraine 28337c41c9 phone calls! woo 2026-02-24 14:01:58 +11:00
pelgraine c5e10ad8ea updated readme to include license info 2026-02-24 10:03:50 +11:00
pelgraine ad196b7674 initial download epub functionality; add scroll and screen refresh to review longer bookmarks and history list web app home screen 2026-02-24 09:39:01 +11:00
pelgraine d7bb0b2024 ui updates; updated firmware date 2026-02-24 09:10:52 +11:00
pelgraine d5b79cf0b4 fix ble error loop crash in serialbleinterface and main; same ble crash fix in webreaderscreen 2026-02-24 02:17:42 +11:00
pelgraine ea04d515ea html spacing display cleanup 2026-02-24 01:11:51 +11:00
pelgraine 7d9ac3a827 added toaster popup confirmation for when a bookmark is saved 2026-02-24 00:54:24 +11:00
pelgraine 241854a707 limited url retries and added url referrer on all requests to try to address CF 525 error when browsing 2026-02-24 00:35:54 +11:00
pelgraine f289788242 increase web display max links; fix to encode spaces as %20 in web url entry so you just type a space and it will translate it for you 2026-02-24 00:00:29 +11:00
pelgraine 17347a1e9d revised approach to nav bar view 2026-02-23 19:08:43 +11:00
pelgraine da3bf06004 ui fixes for web reader - primarily nav bar 2026-02-23 18:44:11 +11:00
pelgraine 0d750fbb19 updated firmware version; added basic irc functionality to web reader app with irc.eastmesh.au as the default suggestion 2026-02-23 18:25:46 +11:00
pelgraine 7f8f70655d Added battery temperature to battery gauge page display. Updated firmware date 2026-02-23 08:48:06 +11:00
pelgraine 6e417d1f3e removed reference to pin 45 goal in readme as now backlight won't be happening until TD Pro Max 2026-02-22 17:36:56 +11:00
pelgraine 38eb4b854b updated roadmap and future planning details in readme 2026-02-22 17:36:04 +11:00
pelgraine e64011112e fix for intermitted sd card failure bug - "patch explicitly deselects all three SPI bus peers (e-ink, LoRa, SD) before init, adds a 100ms stabilization delay, and retries up to 3 times with 250ms settle between attempts" 2026-02-22 17:29:21 +11:00
pelgraine 97f9fc9eee revising firmware version and commenting out meck_web_reader in platformio until I fix the innumerable bugs for it in dev branch 2026-02-22 17:14:27 +11:00
pelgraine 4a1fe3b190 updated firmware version in platformio; added ble pin display to ble home page in ui; updates to try fixing form login functionality in web reader 2026-02-22 16:47:13 +11:00
pelgraine 2024dc2a1b fixed hibernate screen ui display bug 2026-02-22 00:15:44 +11:00
pelgraine 27b8ea603f preliminary html web reader app stage 1 2026-02-22 00:10:02 +11:00
pelgraine b812ff75a9 edited sms app guide 2026-02-20 22:29:27 +11:00
pelgraine 4477d5c812 updated slight eink refresh lag; minor nav bar ui fixes to sms app; added sms app guide 2026-02-20 22:27:59 +11:00
pelgraine f06a1f5499 Sms app implementation phase 2 - add contact in message view screen; time of message displayed fix using 4G modem network sync - need to wait about 10-ish seconds after boot for auto network clock sync 2026-02-20 22:03:06 +11:00
pelgraine 458db8d4c4 implement sms app v1 attempt 1 4g variant only 2026-02-20 08:07:47 +11:00
pelgraine 2576a6590b codebase into one branch consolidation 2026-02-20 06:23:59 +11:00
pelgraine 5cc9feb3e9 fix ble send message buffer handling 2026-02-20 05:53:39 +11:00
pelgraine d76fa04613 updated firmware version and date; same changes as main branch implementing repeater hop path view for last most recent channel msg rcd 2026-02-20 05:47:00 +11:00
pelgraine 5473f29eec scroll bar in channel message view - W or S for up down 2026-02-20 05:01:20 +11:00
pelgraine b85172bcc4 fix ble message history bug app to device 2026-02-20 04:44:06 +11:00
pelgraine 3a32555add changed wording of light flash on off to make it slightly clearer 2026-02-17 20:14:12 +11:00
pelgraine 034cc64f8c update uitasks to enable keyboard pulse light notifcation 2026-02-17 19:53:50 +11:00
pelgraine 16bc0ed69d update settingscreen to enable keyboard pulse light 2026-02-17 19:51:51 +11:00
pelgraine 644eb432b5 update node prefs to enable keyboard pulse light 2026-02-17 19:50:06 +11:00
pelgraine f2956e9d26 changed firmware version date; changed render battery indicator back to meshcore app display method 2026-02-17 18:55:10 +11:00
pelgraine 8e83155698 45 m sleep timer; track queing from sub folders; better wav file name data extraction 2026-02-16 18:28:18 +11:00
pelgraine cd594c4116 updated firmware version and date 2026-02-16 18:10:59 +11:00
pelgraine b43ffe9578 msgread fix and newmsg alert suppression when in repeater admin login page 2026-02-16 17:58:46 +11:00
pelgraine d4b1824b1c using different HAS_BQ27220 for renderbatteryindicator 2026-02-15 19:33:19 +11:00
pelgraine 9809f47d29 battery charge estimated runtime fix - 2 to 3 charge discharge cycles needed for full calibration to 1400mah 2026-02-15 09:19:43 +11:00
pelgraine bf89da0eb5 incorporated battery gauge view on home screen including estimated run time duration 2026-02-15 07:48:48 +11:00
pelgraine aa2e1af999 improvements to bookmark and cache optimisation for load times super fast and reduced serial output 2026-02-15 01:39:14 +11:00
pelgraine 472b0ee662 fixed background audio play and >> icon regression 2026-02-15 01:27:47 +11:00
pelgraine 1f5cbbd4db same repeater admin fixes as main 2026-02-15 01:02:35 +11:00
pelgraine f451b49226 minor text alignment fix 2026-02-14 16:21:38 +11:00
pelgraine d10aa2c571 fixed home view so that pin isn't shown when ble off. Add instructions for keyboard nav to home screen 2026-02-14 16:16:17 +11:00
pelgraine a2e099f095 fixed home view so that pin isn't shown when ble off. Add instructions for keyboard nav to home screen 2026-02-14 16:06:39 +11:00
pelgraine e5e41ff50b ui fixes for audiobook player, firmware version number updates, subdirectory support for both ereader and audiobook player file lists 2026-02-14 15:43:13 +11:00
pelgraine 2dc6977c20 updated audiobook player guide 2026-02-14 14:32:06 +11:00
pelgraine 5c540e9092 fixed settings page so corrected radio preset list options available and custom frequency edits refined. 2026-02-14 14:13:43 +11:00
pelgraine 670efa75b0 Fixed heap allocation order to sort out ble pairing for audiobook player version. Expanded char in uitask to allow firmware version suffix to display in splash screen. 2026-02-14 11:25:21 +11:00
pelgraine 3a486832c8 Merge branch 'main' into audio-player 2026-02-14 10:41:33 +11:00
pelgraine 0a892f2dad changed to hybrid render battery indicator method 2026-02-14 10:41:03 +11:00
pelgraine 7f75ea8309 Merge branch 'main' into audio-player 2026-02-14 10:17:58 +11:00
pelgraine b1e3f2ac28 Back to original serialbleinterface to start afresh 2026-02-14 10:17:11 +11:00
pelgraine ddfe05ad20 m4b incompatibility workaround by renaming file extension to m4a when playing 2026-02-14 01:49:25 +11:00
pelgraine d51ca6db0b "Updated home screen 'background audio playing' icon to >> for clarity" 2026-02-14 01:05:01 +11:00
pelgraine 3ab8191d19 amened ble connection parameter (battery-saving) fix that was causing performance issues; updated firrmware date in mymesh; ui update for audiobook player; audiobook player now lkeeps playing on exit unless you pause it so background audio is enabled 2026-02-14 00:17:44 +11:00
pelgraine 546ce55c2b Gave up on trying to extract cover art from mp3 files and removed debug logs. Updated firmware version to match variant type 2026-02-13 23:27:32 +11:00
pelgraine 1f46bc1970 updated simple audio player ui to make control/nav more evident and i2s reset to try accommodate sample rate diffs between files added 2026-02-13 22:53:35 +11:00
pelgraine db8a73004e audiobook function redo - initial success - attempt 1 2026-02-13 22:38:37 +11:00
pelgraine 209a2f1693 updated firmware version 2026-02-13 21:02:33 +11:00
pelgraine 4683711877 added firmware version build flag to stop device unbonding on new firmware version flash via vscode 2026-02-13 18:43:23 +11:00
pelgraine 9610277b83 ble battery life extension improvements and firmware bond ble pairing bug fix:
- Bond clearing on firmware version change (lines 38-67) — stores the firmware version string in SPIFFS at /ble_ver. On boot, if it doesn't match, all stored bonds are wiped. This fixes the forget/re-pair issue after flashing. Normal reboots keep pairing intact.
- TX power -3 dBm (line 73).
Connection parameter negotiation (lines 137-147) — latency=4 for power saving when connected.
- Advertising intervals 300ms/600ms (three places) — compromise between discovery speed and power.
- No controller power-down — the header file is unchanged from stock.
2026-02-13 18:40:51 +11:00
pelgraine 745efc4cc1 updated firmware version and date 2026-02-13 18:37:34 +11:00
pelgraine 7223395740 Improved device ui battery rendering for more accurate battery indicator 2026-02-13 18:36:17 +11:00
pelgraine 9ef1fa4f1b moved cpu.begin to earlier to reduce risk of brownout boot stuck at low voltage 2026-02-13 18:29:06 +11:00
pelgraine 2dd5c4f59f Slight nav bar ui change in notes mode and improved rename function responsiveness 2026-02-12 21:04:05 +11:00
pelgraine ee2a27258b improved cursor tracking and rename file handling implented with r key in Notes file list view 2026-02-12 20:45:41 +11:00
pelgraine 5b868d51ca improved responsiveness and cursor tracking in notes function. updated firmware version in mymesh. 2026-02-12 20:32:21 +11:00
pelgraine 220006c229 "Increased buffer size. Shift+WASD → cursor nav in editing mode.
Shift+Backspace → save (editing), delete (reading/file list).
Shift+Enter → rename from file list.
RTC time passed via setTimestamp() when opening notes."
2026-02-12 20:18:57 +11:00
pelgraine a60f4146d5 Create, edit, save and delete txt notes from the N menu from any home view screen 2026-02-12 19:41:59 +11:00
pelgraine 017b170e81 Moved epubprocessor files to better tree location and fixed txt file accented character rendering 2026-02-11 20:07:38 +11:00
169 changed files with 47314 additions and 4249 deletions
+78
View File
@@ -0,0 +1,78 @@
## Audiobook Player (Audio variant only)
Press **P** from the home screen to open the audiobook player.
Place `.mp3`, `.m4b`, `.m4a`, or `.wav` files in `/audiobooks/` on the SD card.
Files can be organised into subfolders (e.g. by author) — use **Enter** to
browse into folders and **.. (up)** to go back.
| Key | Action |
|-----|--------|
| W / S | Scroll file list / Volume up-down |
| Enter | Select book or folder / Play-Pause |
| A | Seek back 30 seconds |
| D | Seek forward 30 seconds |
| [ | Previous chapter (M4B only) |
| ] | Next chapter (M4B only) |
| Q | Leave player (audio continues) / Close book (when paused) / Exit (from file list) |
### Recommended Format
**MP3 is the recommended format.** M4B/M4A files are supported but currently
have playback issues with the ESP32-audioI2S library — some files may fail to
decode or produce silence. MP3 files play reliably and are the safest choice.
MP3 files should be encoded at a **44100 Hz sample rate**. Lower sample rates
(e.g. 22050 Hz) can cause distortion or playback failure due to ESP32-S3 I2S
hardware limitations.
**Bookmarks** are saved automatically every 30 seconds during playback and when
you stop or exit. Reopening a book resumes from your last position.
**Cover art** from M4B files is displayed as dithered monochrome on the e-ink
screen, along with title, author, and chapter information.
**Metadata caching** — the first time you open the audiobook player, it reads
title and author tags from each file (which can take a few seconds with many
files). This metadata is cached to the SD card so subsequent visits load
near-instantly. If you add or remove files the cache updates automatically.
### Background Playback
Audio continues playing when you leave the audiobook player screen. Press **Q**
while audio is playing to return to the home screen — a **>>** indicator will
appear in the status bar next to the battery icon to show that audio is active
in the background. Press **P** at any time to return to the player screen and
resume control.
If you pause or stop playback first and then press **Q**, the book is closed
and you're returned to the file list instead.
### Audio Hardware
The audiobook player uses the PCM5102A I2S DAC on the audio variant of the
T-Deck Pro (I2S pins: BCLK=7, DOUT=8, LRC=9). Audio is output via the 3.5mm
headphone jack.
> **Note:** The audiobook player is not available on the 4G modem variant
> due to I2S pin conflicts.
### SD Card Folder Structure
```
SD Card
├── audiobooks/
│ ├── .bookmarks/ (auto-created, stores resume positions)
│ │ ├── mybook.bmk
│ │ └── another.bmk
│ ├── .metacache (auto-created, speeds up file list loading)
│ ├── Ann Leckie/
│ │ ├── Ancillary Justice.mp3
│ │ └── Ancillary Sword.mp3
│ ├── Iain M. Banks/
│ │ └── The Algebraist.mp3
│ ├── mybook.mp3
│ └── podcast.mp3
├── books/ (existing — text reader)
│ └── ...
└── ...
```
+64
View File
@@ -0,0 +1,64 @@
# PlatformIO monitor filter: automatic clock sync for Meck devices
#
# When a Meck device boots with no valid RTC time, it prints "MECK_CLOCK_REQ"
# over serial. This filter watches for that line and responds immediately
# with "clock sync <epoch>\r\n", setting the device's real-time clock to
# the host computer's current time.
#
# The sync is completely transparent — the user just sees it happen in the
# boot log. If the RTC already has valid time, the device never sends the
# request and this filter does nothing.
#
# Install: place this file in <project>/monitor/filter_clock_sync.py
# Enable: add "clock_sync" to monitor_filters in platformio.ini
#
# Works with: PlatformIO Core >= 6.0
import time
from platformio.device.monitor.filters.base import DeviceFilter
class ClockSync(DeviceFilter):
NAME = "clock_sync"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._buf = bytearray()
self._synced = False
def rx(self, text):
"""Called with each chunk of data received from the device."""
if self._synced:
return text
# Accumulate into a line buffer to detect MECK_CLOCK_REQ
if isinstance(text, str):
self._buf.extend(text.encode("utf-8", errors="replace"))
else:
self._buf.extend(text)
if b"MECK_CLOCK_REQ" in self._buf:
epoch = int(time.time())
response = "clock sync {}\r\n".format(epoch)
try:
# Write directly to the serial port
self.miniterm.serial.write(response.encode("utf-8"))
except Exception as e:
# Fallback: shouldn't happen, but don't crash the monitor
import sys
print(
"\n[clock_sync] Failed to auto-sync: {}".format(e),
file=sys.stderr,
)
self._synced = True
self._buf = bytearray()
elif len(self._buf) > 2048:
# Prevent unbounded growth — keep tail only
self._buf = self._buf[-256:]
return text
def tx(self, text):
"""Called with each chunk of data sent from terminal to device."""
return text
+845 -48
View File
File diff suppressed because it is too large Load Diff
+206
View File
@@ -0,0 +1,206 @@
## SMS & Phone App (4G variant only) - Meck v0.9.5
Press **T** from the home screen to open the SMS & Phone app.
Requires a nano SIM card inserted in the T-Deck Pro V1.1 4G modem slot and an
SD card formatted as FAT32. The modem registers on the cellular network
automatically at boot — the red LED on the board indicates the modem is
powered. The modem (and its red LED) can be switched off and on from the
settings screen. After each modem startup, the system clock syncs from the
cellular network, which takes roughly 15 seconds.
### App Menu
The SMS & Phone app opens to a landing screen with two options:
| Option | Description |
|--------|-------------|
| **Phone** | Open the phone dialer to call any number |
| **SMS Inbox** | Open the SMS inbox for messaging and calling saved contacts |
Use **W / S** to select an option and **Enter** to confirm. Press **Q** to
return to the home screen.
### Key Mapping
| Context | Key | Action |
|---------|-----|--------|
| Home screen | T | Open SMS & Phone app |
| App menu | W / S | Select Phone or SMS Inbox |
| App menu | Enter | Open selected option |
| App menu | Q | Back to home screen |
| Inbox | W / S | Scroll conversations |
| Inbox | Enter | Open conversation |
| Inbox | C | Compose new SMS (enter phone number) |
| Inbox | D | Open contacts directory |
| Inbox | Q | Back to app menu |
| Conversation | W / S | Scroll messages |
| Conversation | C | Reply to this conversation |
| Conversation | F | Call this number |
| Conversation | A | Add or edit contact name for this number |
| Conversation | Q | Back to inbox |
| Compose | Enter | Send SMS (from body) / Confirm phone number (from phone input) |
| Compose | Shift+Del | Cancel and return |
| Contacts | W / S | Scroll contact list |
| Contacts | Enter | Compose SMS to selected contact |
| Contacts | F | Call selected contact |
| Contacts | Q | Back to inbox |
| Edit Contact | Enter | Save contact name |
| Edit Contact | Shift+Del | Cancel without saving |
| Phone Dialer | 09, *, +, # | Enter phone number (see input methods below) |
| Phone Dialer | Enter | Place call |
| Phone Dialer | Backspace | Delete last digit |
| Phone Dialer | Q | Back to app menu |
| Dialing | Enter or Q | Cancel / hang up |
| Incoming Call | Enter | Answer call |
| Incoming Call | Q | Reject call |
| In Call | Enter or Q | Hang up |
| In Call | W / S | Volume up / down (05) |
| In Call | 09, *, # | Send DTMF tone |
### Sending an SMS
There are three ways to start a new message:
1. **From inbox** — press **C**, type the destination phone number, press
**Enter**, then type your message and press **Enter** to send.
2. **From a conversation** — press **C** to reply. The recipient is
pre-filled so you go straight to typing the message body.
3. **From the contacts directory** — press **D** from the inbox, scroll to a
contact, and press **Enter**. The compose screen opens with the number
pre-filled.
Messages are limited to 160 characters (standard SMS). A character counter is
shown in the footer while composing.
### Making a Phone Call
There are three ways to start a call:
1. **From the phone dialer** — select **Phone** from the app menu to open the
dialer. Enter a phone number and press **Enter** to call. This is the
easiest way to call a number you haven't messaged before.
2. **From a conversation** — open a conversation and press **F**. You can call
any number you have previously exchanged messages with, whether or not it is
saved as a named contact.
3. **From the contacts directory** — press **D** from the inbox, scroll to a
contact, and press **F**.
The display switches to a dialing screen showing the contact name (or phone
number) and an animated progress indicator. Once the remote party answers, the
screen transitions to the in-call view with a live call timer.
During an active call, **W** and **S** adjust the speaker volume (05). The
number keys **09**, **\***, and **#** send DTMF tones for navigating phone
menus and voicemail systems. Press **Enter** or **Q** to hang up.
Audio is routed through the A7682E modem's internal codec to the board speaker
and microphone — no headphones or external audio hardware are required.
### Phone Dialer Input Methods
The phone dialer supports three ways to enter digits:
1. **Direct key press** — press the keyboard letter that corresponds to each
number using the silk-screened labels on the T-Deck Pro keys:
| Key | Digit | | Key | Digit | | Key | Digit |
|-----|-------|-|-----|-------|-|-----|-------|
| W | 1 | | S | 4 | | Z | 7 |
| E | 2 | | D | 5 | | X | 8 |
| R | 3 | | F | 6 | | C | 9 |
| A | * | | O | + | | Mic | 0 |
2. **Touchscreen tap** — tap the on-screen number buttons directly. Note: this
currently requires fairly precise taps on the numbers themselves.
3. **Sym+key** — the standard symbol entry method (e.g. Sym+W for 1, Sym+S for
4, etc.)
### Receiving a Phone Call
When an incoming call arrives, the app automatically switches to the incoming
call screen regardless of which view is active. A short alert and buzzer
notification are triggered. The caller's name is shown if saved in contacts,
otherwise the raw phone number is displayed.
Press **Enter** to answer or **Q** to reject the call. If the call is not
answered it is logged as a missed call and a "Missed: ..." alert is shown
briefly.
### Contacts
The contacts directory lets you assign display names to phone numbers.
Names appear in the inbox list, conversation headers, call screens, and
compose screen instead of raw numbers.
To add or edit a contact, open a conversation with that number and press **A**.
Type the display name and press **Enter** to save. Names can be up to 23
characters long.
Contacts are stored as a plain text file at `/sms/contacts.txt` on the SD card
in `phone=Display Name` format — one per line, human-editable. Up to 30
contacts are supported.
### Conversation History
Messages are saved to the SD card automatically and persist across reboots.
Each phone number gets its own file under `/sms/` on the SD card. The inbox
shows the most recent 20 conversations sorted by last activity. Within a
conversation, the most recent 30 messages are loaded with the newest at the
bottom (chat-style). Sent messages are shown with `>>>` and received messages
with `<<<`.
Message timestamps use the cellular network clock (synced via NITZ roughly 15
seconds after each modem startup) and display as relative times (e.g. 5m, 2h,
1d). If the modem is toggled off and back on, the clock re-syncs automatically.
### Modem Power Control
The 4G modem can be toggled on or off from the settings screen. Scroll to
**4G Modem: ON/OFF** and press **Enter** to toggle. Switching the modem off
kills its red status LED and stops all cellular activity. The setting persists
to SD card and is respected on subsequent boots — if disabled, the modem and
LED stay off until re-enabled. The SMS & Phone app remains accessible when the
modem is off but will not be able to send or receive messages or calls.
### Signal Indicator
A signal strength indicator is shown in the top-right corner of all SMS and
call screens. Bars are derived from the modem's CSQ (signal quality) reading,
updated every 30 seconds. The modem state (REG, READY, OFF, etc.) is shown
when not yet connected. During a call, the signal indicator remains visible.
### IMEI, Carrier & APN
The 4G modem's IMEI, current carrier name, and APN are displayed at the bottom
of the settings screen (press **S** from the home screen), alongside your node
ID and firmware version.
### SD Card Structure
```
SD Card
├── sms/
│ ├── contacts.txt (plain text, phone=Name format)
│ ├── modem.cfg (0 or 1, modem enable state)
│ ├── 0412345678.sms (binary message log per phone number)
│ └── 0498765432.sms
├── books/ (text reader)
├── audiobooks/ (audio variant only)
└── ...
```
### Troubleshooting
| Symptom | Likely Cause |
|---------|-------------|
| Modem icon stays at REG / never reaches READY | SIM not inserted, no signal, or SIM requires PIN unlock (not currently supported) |
| Timestamps show `---` | Modem clock hasn't synced yet (wait ~15 seconds after modem startup), or messages were saved before clock sync was available |
| Red LED stays on after disabling modem | Toggle the setting off, then reboot — the boot sequence ensures power is cut when disabled |
| SMS sends but no delivery | Check signal strength; below 5 bars is marginal. Move to better coverage |
| Call drops immediately after dialing | Check signal strength and ensure the SIM plan supports voice calls |
| No audio during call | The A7682E routes audio through its own codec; ensure the board speaker is not obstructed. Try adjusting volume with W/S |
> **Note:** The SMS & Phone app is only available on the 4G modem variant of
> the T-Deck Pro. It is not present on the audio or standalone BLE builds due
> to shared GPIO pin conflicts between the A7682E modem and PCM5102A DAC.
+490
View File
@@ -0,0 +1,490 @@
# Meck Serial Settings Guide
Configure your T-Deck Pro's Meck firmware over USB serial — no companion app needed. Plug in a USB-C cable, open a serial terminal, and you have full access to every setting on the device.
## Getting Started
### What You Need
- T-Deck Pro running Meck firmware
- USB-C cable
- A serial terminal application:
- **Windows:** PuTTY, TeraTerm, or the Arduino IDE Serial Monitor
- **macOS:** `screen`, CoolTerm, or the Arduino IDE Serial Monitor
- **Linux:** `screen`, `minicom`, `picocom`, or the Arduino IDE Serial Monitor
### Connection Settings
| Parameter | Value |
|-----------|-------|
| Baud rate | 115200 |
| Data bits | 8 |
| Parity | None |
| Stop bits | 1 |
| Line ending | CR (carriage return) or CR+LF |
### Quick Start (macOS / Linux)
```
screen /dev/ttyACM0 115200
```
On macOS the port is typically `/dev/cu.usbmodem*`. On Linux it is usually `/dev/ttyACM0` or `/dev/ttyUSB0`.
### Quick Start (Arduino IDE)
Open **Tools → Serial Monitor**, set baud to **115200** and line ending to **Carriage Return** or **Both NL & CR**.
Once connected, type `help` and press Enter to confirm everything is working.
---
## Command Reference
All commands follow a simple pattern: `get` to read, `set` to write.
### Viewing Settings
| Command | Description |
|---------|-------------|
| `get all` | Dump every setting at once |
| `get name` | Device name |
| `get freq` | Radio frequency (MHz) |
| `get bw` | Bandwidth (kHz) |
| `get sf` | Spreading factor |
| `get cr` | Coding rate |
| `get tx` | TX power (dBm) |
| `get radio` | All radio params in one line |
| `get utc` | UTC offset (hours) |
| `get notify` | Keyboard flash notification (on/off) |
| `get largefont` | Larger font mode (on/off) |
| `get gps` | GPS status and interval |
| `get pin` | BLE pairing PIN |
| `get path.hash.mode` | Path hash size (0=1-byte, 1=2-byte, 2=3-byte) |
| `get rxdelay` | Rx delay base (0=disabled) |
| `get af` | Airtime factor |
| `get multi.acks` | Redundant ACKs (0 or 1) |
| `get int.thresh` | Interference threshold (0=disabled) |
| `get tx.fail.reset` | TX fail reset threshold (0=disabled, default 3) |
| `get rx.fail.reboot` | RX stuck reboot threshold (0=disabled, default 3) |
| `get gps.baud` | GPS baud rate (0=compile-time default) |
| `get channels` | List all channels with index numbers |
| `get presets` | List all radio presets with parameters |
| `get pubkey` | Device public key (hex) |
| `get firmware` | Firmware version string |
| `clock` | Current RTC time (UTC + epoch) |
**4G variant only:**
| Command | Description |
|---------|-------------|
| `get modem` | Modem enabled/disabled |
| `get apn` | Current APN |
| `get imei` | Device IMEI |
### Changing Settings
#### Device Name
```
set name MyNode
```
Names cannot contain these characters: `[ ] / \ : , ? *`
#### Radio Parameters (Individual)
Each of these applies immediately — no reboot required.
```
set freq 910.525
set bw 62.5
set sf 7
set cr 5
set tx 22
```
Valid ranges:
| Parameter | Min | Max |
|-----------|-----|-----|
| freq | 400.0 | 928.0 |
| bw | 7.8 | 500.0 |
| sf | 5 | 12 |
| cr | 5 | 8 |
| tx | 1 | Board max (typically 22) |
#### Radio Parameters (All at Once)
Set frequency, bandwidth, spreading factor, and coding rate in a single command:
```
set radio 910.525 62.5 7 5
```
#### Radio Presets
The easiest way to configure your radio. First, list the available presets:
```
get presets
```
This prints a numbered list like:
```
Available radio presets:
0 Australia 915.800 MHz BW250.0 SF10 CR5 TX22
1 Australia (Narrow) 916.575 MHz BW62.5 SF7 CR8 TX22
...
14 USA/Canada (Recommended) 910.525 MHz BW62.5 SF7 CR5 TX22
15 Vietnam 920.250 MHz BW250.0 SF11 CR5 TX22
```
Apply a preset by name or number:
```
set preset USA/Canada (Recommended)
set preset 14
```
Preset names are case-insensitive, so `set preset australia` works too. The preset applies all five radio parameters (freq, bw, sf, cr, tx) and takes effect immediately.
#### UTC Offset
```
set utc 10
```
Range: -12 to +14.
#### Keyboard Notification Flash
Toggle whether the keyboard backlight flashes when a new message arrives:
```
set notify on
set notify off
```
#### Larger Font Mode
Toggle larger text on channel messages, contacts, DM inbox, and repeater admin screens:
```
set largefont on
set largefont off
```
#### BLE PIN
```
set pin 123456
```
#### Path Hash Mode
Controls the byte size of each repeater's identity stamp in forwarded flood packets. Larger hashes reduce collisions at the cost of fewer maximum hops.
```
set path.hash.mode 1
```
| Mode | Bytes/hop | Max hops | Notes |
|------|-----------|----------|-------|
| 0 | 1 | 64 | Legacy — prone to hash collisions in larger networks |
| 1 | 2 | 32 | Recommended — effectively eliminates collisions |
| 2 | 3 | 21 | Maximum precision, rarely needed |
Nodes with different modes can coexist — the mode only affects packets your node originates. The hash size is encoded in each packet's header, so receiving nodes adapt automatically.
### Mesh Tuning
These settings control how the device participates in the mesh network. They take effect immediately — no reboot required (except `gps.baud`).
#### Rx Delay (rxdelay)
Delays processing of flood packets based on signal quality. Stronger signals are processed first; weaker copies wait longer and are typically discarded as duplicates. Direct messages are always processed immediately.
```
set rxdelay 3
```
Range: 020 (0 = disabled, default). Higher values create larger timing differences between strong and weak signals. Values below 1.0 have no practical effect. See the [MeshSydney wiki](https://meshsydney.com/wiki) for detailed tuning profiles.
#### Airtime Factor (af)
Adjusts how long certain internal timing windows remain open. Does not change the LoRa radio parameters (SF, BW, CR) — those remain as configured.
```
set af 1.0
```
Range: 09 (default: 1.0). Keep this value consistent across nodes in your mesh for best coherence.
#### Multiple Acknowledgments (multi.acks)
Sends redundant ACK packets for direct messages. When enabled, two ACKs are sent (a multi-ack first, then the standard ACK), improving delivery confirmation reliability.
```
set multi.acks 1
```
Values: 0 (single ACK) or 1 (redundant ACKs, default).
#### Interference Threshold (int.thresh)
Enables channel activity scanning before transmitting. Not recommended unless your device is in a high RF interference environment — specifically where the noise floor is low but shows significant fluctuations indicating interference. Enabling this adds approximately 4 seconds of receive delay per packet.
```
set int.thresh 14
set int.thresh 0
```
Values: 0 (disabled, default) or 14+ (14 is the typical setting). Values between 113 are not functional and will be rejected.
#### TX Fail Reset Threshold (tx.fail.reset)
Automatically resets the radio hardware after this many consecutive failed transmission attempts. This recovers from "zombie radio" states where the SX1262 stops responding to send commands.
```
set tx.fail.reset 3
set tx.fail.reset 0
```
Values: 0 (disabled) or 110 (default: 3). After the threshold is reached, the radio is reset and the failed packet is re-queued.
#### RX Stuck Reboot Threshold (rx.fail.reboot)
Automatically reboots the device after this many consecutive RX-stuck recovery failures. An RX-stuck event occurs when the radio is not in receive mode for 8 seconds despite automatic recovery attempts.
```
set rx.fail.reboot 3
set rx.fail.reboot 0
```
Values: 0 (disabled) or 110 (default: 3). A full device reboot is a last resort — this should only trigger in rare cases of persistent radio hardware malfunction.
#### GPS Baud Rate (gps.baud)
Override the GPS serial baud rate. The default (0) uses the compile-time value of 38400. **Requires a reboot to take effect** — the GPS serial port is only configured at startup.
```
set gps.baud 9600
set gps.baud 0
```
Valid rates: 0 (default), 4800, 9600, 19200, 38400, 57600, 115200.
### Channel Management
#### List Channels
```
get channels
```
Output:
```
[0] #public
[1] #meck-test
[2] #local-group
```
#### Add a Hashtag Channel
```
set channel.add meck-test
```
The `#` prefix is added automatically if you omit it. The channel's encryption key is derived from the name (SHA-256), matching the same method used by the on-device Settings screen and companion apps.
#### Delete a Channel
```
set channel.del 2
```
Channels are referenced by their index number (shown in `get channels`). Channel 0 (public) cannot be deleted. Remaining channels are automatically compacted after deletion.
### 4G Modem (4G Variant Only)
#### Enable / Disable Modem
```
set modem on
set modem off
```
#### Set APN
```
set apn telstra.internet
```
To clear a custom APN and revert to auto-detection on next boot:
```
set apn
```
### Clock Sync
Set the device's real-time clock from a Unix timestamp. This is especially important for the T5S3 E-Paper Pro which has no GPS to auto-set the clock. These are standalone commands (not `get`/`set` prefixed) — matching the same `clock sync` command used on MeshCore repeaters.
#### View Current Time
```
clock
```
Output:
```
> 2026-03-13 04:22:15 UTC (epoch: 1773554535)
```
If the clock has never been set:
```
> not set (epoch: 0)
```
#### Sync Clock from Serial
```
clock sync 1773554535
```
The value must be a Unix epoch timestamp in the 20242036 range.
**Quick one-liner from your terminal (macOS / Linux / WSL):**
```
echo "clock sync $(date +%s)" > /dev/ttyACM0
```
Or paste directly into the Arduino IDE Serial Monitor:
```
clock sync 1773554535
```
**Tip:** On macOS/Linux, run `date +%s` to get the current epoch. On Windows PowerShell: `[int](Get-Date -UFormat %s)`.
#### Boot-Time Auto-Sync (T5S3)
When the T5S3 boots with no valid RTC time and detects a USB serial host is connected, it sends a `MECK_CLOCK_REQ` handshake over serial. If you're using PlatformIO's serial monitor (`pio device monitor`), the built-in `clock_sync` monitor filter responds automatically with the host computer's current time — no user action required. The sync appears transparently in the boot log:
```
MECK_CLOCK_REQ
(Waiting 3s for clock sync from host...)
> Clock synced to 1773554535
```
If no USB host is connected (e.g. running on battery), the sync window is skipped entirely with no boot delay.
**Manual fallback:** If you're using a serial terminal that doesn't have the filter (e.g. `screen`, PuTTY), you can paste a `clock sync` command during the 3-second window, or any time after boot:
```
clock sync $(date +%s)
```
### System Commands
| Command | Description |
|---------|-------------|
| `reboot` | Restart the device |
| `rebuild` | Erase filesystem, re-save identity + prefs + contacts + channels |
| `erase` | Format the filesystem (caution: loses everything) |
| `ls UserData/` | List files on internal filesystem |
| `ls ExtraFS/` | List files on secondary filesystem |
| `cat UserData/<path>` | Dump file contents as hex |
| `rm UserData/<path>` | Delete a file |
| `help` | Show command summary |
---
## Common Workflows
### First-Time Setup
Plug in your new T-Deck Pro and run through these commands to get on the air:
```
set name YourCallsign
set preset Australia
set utc 10
set channel.add local-group
get all
```
### Switching to a New Region
Moving from Australia to the US? One command:
```
set preset USA/Canada (Recommended)
```
Verify with:
```
get radio
```
### Custom Radio Configuration
If none of the presets match your local group or you need specific parameters, set them directly. You can do it all in one command:
```
set radio 916.575 62.5 8 8
set tx 20
```
Or one parameter at a time if you're only adjusting part of your config:
```
set freq 916.575
set bw 62.5
set sf 8
set cr 8
set tx 20
```
Both approaches apply immediately. Confirm with `get radio` to double-check everything took:
```
get radio
> freq=916.575 bw=62.5 sf=8 cr=8 tx=20
```
### Troubleshooting Radio Settings
If you're not sure what went wrong, dump everything:
```
get all
```
Compare the radio section against what others in your area are using. If you need to match exact parameters from another node:
```
set radio 916.575 62.5 7 8
set tx 22
```
### Backing Up Your Settings
Use `get all` to capture a snapshot of your configuration. Copy the serial output and save it — you can manually re-enter the settings after a firmware update or device reset if your SD card backup isn't available.
---
## Tips
- **All radio changes apply live.** There is no need to reboot after changing frequency, bandwidth, spreading factor, coding rate, or TX power. The radio reconfigures on the fly.
- **Preset selection by number is faster.** Once you've seen `get presets`, use the index number instead of typing the full name.
- **Settings are persisted immediately.** Every `set` command writes to flash. If power is lost, your settings are safe.
- **SD card backup is automatic.** If your T-Deck Pro has an SD card inserted, settings are backed up after every change. On a fresh flash, settings restore automatically from the SD card.
- **The `get all` command is your friend.** When in doubt, dump everything and check.
+16 -6
View File
@@ -2,7 +2,7 @@
## Overview
This adds a text reader accessible via the **R** key from the home screen.
This adds a text reader accessible via the **E** key from the home screen.
**Features:**
- Browse `.txt` and `.epub` files from `/books/` folder on SD card
@@ -13,17 +13,27 @@ This adds a text reader accessible via the **R** key from the home screen.
- Index files cached to SD for instant re-opens
- Bookmark indicator (`*`) on files with saved positions
**Key Mapping:**
**Key Mapping (T-Deck Pro):**
| Context | Key | Action |
|---------|-----|--------|
| Home screen | E | Open text reader |
| File list | W/S | Navigate up/down |
| File list | Enter | Open selected file |
| File list | Tap / Enter | Open selected file |
| File list | Q | Back to home screen |
| Reading | W/A | Previous page |
| Reading | S/D/Space/Enter | Next page |
| Reading | S/D/Space | Next page |
| Reading | Enter | Go to page number (type digits, Enter to confirm, Q to cancel) |
| Reading | Q | Close book → file list |
| Reading | C | Enter compose mode |
**Touch Gestures (T5S3):**
| Context | Gesture | Action |
|---------|---------|--------|
| File list | Swipe up/down | Scroll file list |
| File list | Tap | Open selected book |
| Reading | Tap | Next page |
| Reading | Swipe left/right | Next / previous page |
| Reading | Tap footer | Go to page number (via virtual keyboard) |
| Reading | Long press | Close book → file list |
---
@@ -113,4 +123,4 @@ The conversion is handled by three components:
- Page content is pre-read from SD into a memory buffer during `handleInput()`, then rendered from buffer during `render()` — this avoids SPI bus conflicts during display refresh
- Layout metrics (chars per line, lines per page) are calculated dynamically from the display driver's font metrics on first entry
- EPUB conversion runs synchronously in `openBook()` — the e-ink splash screen keeps the user informed while the ESP32 processes the archive
- ZIP extraction uses the ESP32-S3's hardware-optimised ROM `tinfl` inflate, avoiding external compression library dependencies and the linker conflicts they cause
- ZIP extraction uses the ESP32-S3's hardware-optimised ROM `tinfl` inflate, avoiding external compression library dependencies and the linker conflicts they cause
+181
View File
@@ -0,0 +1,181 @@
# Web Reader & IRC - Meck v0.9.5
Press **B** from the home screen to open the web reader. The web reader is
available on the BLE and 4G variants. It is excluded from the standalone audio
variant to preserve zero-radio-power design.
The web reader home screen provides access to the **IRC client**, the **URL
bar**, your **bookmarks**, and browsing **history**. Use **W / S** to navigate
the list and **Enter** to select an item.
## Web Browser
A text-centric web browser ("reader mode") that fetches pages over WiFi,
strips HTML to readable text, extracts links as numbered references, and
paginates content for the e-ink display. Still very much in development, but
already useful for text-heavy websites.
Includes basic web search via **DuckDuckGo Lite** — type a search query into
the URL bar and it will be sent to DuckDuckGo.
### EPUB Downloads
If you follow a link to an `.epub` file, it will be saved directly to the
`/books/` folder on your SD card. You can then read it in the e-book reader
(press **E** from the home screen).
### Bookmarks
Press **K** while on a page to save a bookmark. Bookmarks appear on the web
reader home screen below the URL bar. To delete a bookmark, open the browser
home screen, scroll down to the bookmark, and press **Delete**.
### Cookies & History
Press **X** to clear cookies and browsing history.
---
## IRC Client
The IRC client lets you connect to IRC networks directly from the device. It
is accessed from the web reader home screen — select **IRC Chat** (the first
item) and press **Enter**.
If you are not currently connected, the IRC setup screen opens where you can
configure the server, port, nickname, and channel. If you are already
connected, you go straight to the chat view.
### IRC Setup
The setup screen has five fields. Use **W / S** to navigate between them and
press **Enter** to edit a field (type the value, then **Enter** to confirm).
| Field | Description | Default |
|-------|-------------|---------|
| Host | IRC server hostname (e.g. `irc.libera.chat`) | — |
| Port | Server port. Use `6697` for TLS or `6667` for plain | 6697 |
| Nick | Your IRC nickname (max 16 characters) | — |
| Channel | Channel to join, including the `#` (e.g. `#meshcore`) | — |
| Connect | Select and press Enter to connect | — |
TLS is used automatically when the port is 6697. Other ports connect without
encryption.
Configuration is saved to the SD card at `/web/irc.cfg` and restored on next
launch, so you only need to enter server details once.
If WiFi is not connected when you press Connect, you'll be taken to the WiFi
setup screen first.
### IRC Chat View
Once connected and joined to the channel, you'll see messages in a scrollable
chat view. The channel name and connection status are shown at the top.
| Key | Action |
|-----|--------|
| Enter | Start composing a message (type, then Enter to send) |
| Backspace | Delete last character while composing; exit compose if empty |
| W / S | Scroll up (older) / down (newer) through messages |
| X | Disconnect from IRC and return to web reader home |
| Q | Return to web reader home (connection stays alive in background) |
The IRC connection remains active when you press **Q** to go back to the web
reader home screen. You'll see the connection status and channel name displayed
on the IRC Chat line. Select it and press Enter to return to the chat. Press
**X** from the chat view to disconnect.
The client automatically reconnects if the connection drops (10-second delay
between attempts) and detects dead connections after 5 minutes of inactivity
via ping timeout.
Messages are stored in a circular buffer of 64 messages. Older messages are
discarded as new ones arrive.
---
## Key Bindings
### From Home Screen
| Key | Action |
|-----|--------|
| `b` | Open web reader |
### Web Reader - Home View
| Key | Action |
|-----|--------|
| `w` / `s` | Navigate up/down in IRC / URL bar / bookmarks / history |
| `Enter` | Select IRC Chat, activate URL bar, or open bookmark/history item |
| Type | Enter URL (when URL bar is active) |
| `q` | Exit to firmware home |
### Web Reader - Reading View
| Key | Action |
|-----|--------|
| `w` / `a` | Previous page |
| `s` / `d` / `Space` | Next page |
| `l` or `Enter` | Enter link selection (type link number) |
| `g` | Go to new URL (return to web reader home) |
| `k` | Bookmark current page |
| `x` | Clear cookies and history |
| `q` | Back to web reader home |
### Web Reader - WiFi Setup
| Key | Action |
|-----|--------|
| `w` / `s` | Navigate SSID list |
| `Enter` | Select SSID / submit password / retry |
| Type | Enter WiFi password |
| `q` | Back |
### IRC - Setup View
| Key | Action |
|-----|--------|
| `w` / `s` | Navigate fields (Host / Port / Nick / Channel / Connect) |
| `Enter` | Edit selected field, or connect (when on Connect button) |
| Type | Enter field value (when editing) |
| `Backspace` | Delete last character (when editing) |
| `q` | Back to web reader home |
### IRC - Chat View
| Key | Action |
|-----|--------|
| `Enter` | Start composing / send message |
| `Backspace` | Delete character / exit compose if empty |
| `w` / `s` | Scroll older / newer messages |
| `x` | Disconnect and return to web reader home |
| `q` | Back to web reader home (stays connected) |
---
## WiFi
The web reader and IRC client both use WiFi for network access. On first use,
you'll be taken to the WiFi setup screen to scan for networks and enter a
password. Credentials are saved to `/web/wifi.cfg` on the SD card and used for
auto-reconnect on subsequent launches.
On the 4G variant, the web reader currently uses WiFi. A future update will add
PPP support via the A7682E cellular modem, allowing the browser and IRC to work
over cellular data without WiFi.
---
## SD Card Structure
```
/web/
wifi.cfg - Saved WiFi credentials (auto-reconnect)
bookmarks.txt - One URL per line
history.txt - Recent URLs, newest first
irc.cfg - IRC server/port/nick/channel config
```
---
## Conditional Compilation
All web reader code is wrapped in `#ifdef MECK_WEB_READER` guards. The flag is set:
- **meck_audio_ble**: Yes (`-D MECK_WEB_READER=1`) — WiFi available via BLE radio stack
- **meck_4g_ble**: Yes (`-D MECK_WEB_READER=1`) — WiFi now, PPP via A7682E in future
- **meck_4g_standalone**: Yes (`-D MECK_WEB_READER=1`) — WiFi works better without BLE (no teardown needed, more free heap)
- **meck_audio_standalone**: No — excluded to preserve zero-radio-power design
+1 -1
View File
@@ -39,7 +39,7 @@
"frameworks": ["arduino"],
"name": "Heltec nrf (Adafruit BSP)",
"upload": {
"maximum_ram_size": 248832,
"maximum_ram_size": 235520,
"maximum_size": 815104,
"speed": 115200,
"protocol": "nrfutil",
+48
View File
@@ -0,0 +1,48 @@
{
"build": {
"arduino": {
"ldscript": "nrf52840_s140_v6.ld"
},
"core": "nRF5",
"cpu": "cortex-m4",
"extra_flags": [
"-DARDUINO_NRF52840_TECHO_CARD",
"-DNRF52840_XXAA",
"-DNRF52_SERIES"
],
"f_cpu": "64000000L",
"hwids": [["0x239A", "0x8029"]],
"mcu": "nrf52840",
"variant": "lilygo_techo_card",
"bsp": {
"name": "adafruit"
},
"softdevice": {
"sd_name": "s140",
"sd_version": "6.1.1",
"sd_fwid": "0x00B6"
},
"usb_product": "T-Echo Card"
},
"connectivity": ["bluetooth", "lora"],
"debug": {
"jlink_device": "nRF52840_xxAA",
"openocd_target": "nrf52840"
},
"frameworks": ["arduino"],
"name": "LilyGo T-Echo Card (nRF52840, SX1262, 4MB Flash)",
"upload": {
"flash_size": "796KB",
"maximum_ram_size": 248832,
"maximum_size": 815104,
"native_usb": true,
"protocol": "nrfutil",
"protocols": ["nrfutil", "jlink", "cmsis-dap"],
"require_upload_port": true,
"speed": 115200,
"use_1200bps_touch": true,
"wait_for_upload_port": true
},
"url": "https://github.com/Xinyuan-LilyGO/T-Echo-Card",
"vendor": "LILYGO"
}
+40
View File
@@ -0,0 +1,40 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"memory_type": "qio_qspi",
"partitions": "default_16MB.csv"
},
"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",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "esp32s3"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"default_tool": "esp-builtin",
"onboard_tools": ["esp-builtin"],
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "LilyGo T-Deck Pro MAX (16MB Flash 8MB QSPI PSRAM)",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"require_upload_port": true,
"speed": 921600
},
"url": "https://www.lilygo.cc/products/t-deck-pro",
"vendor": "LilyGo"
}
+38
View File
@@ -0,0 +1,38 @@
{
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
"memory_type": "qio_opi",
"partitions": "default_16MB.csv"
},
"core": "esp32",
"extra_flags": [
"-DBOARD_HAS_PSRAM",
"-DARDUINO_RUNNING_CORE=1",
"-DARDUINO_EVENT_RUNNING_CORE=0",
"-DARDUINO_USB_CDC_ON_BOOT=1",
"-DARDUINO_USB_MODE=1"
],
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
"hwids": [["0x303A", "0x1001"]],
"mcu": "esp32s3",
"variant": "esp32s3"
},
"connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino", "espidf"],
"name": "LilyGo T5S3 E-Paper Pro",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"require_upload_port": true,
"speed": 921600
},
"url": "https://lilygo.cc/products/t5-e-paper-s3-pro",
"vendor": "LILYGO"
}
+5
View File
@@ -0,0 +1,5 @@
6818ce5f77dd45bb90facf753ba81d81.s1.eu.hivemq.cloud
8883
meckremote
yourpassword
heltec-wifi-1
+2
View File
@@ -0,0 +1,2 @@
SSID
Password
+101
View File
@@ -0,0 +1,101 @@
# How to Flash Meck Firmware Using Launcher over WiFi
## How to Install Launcher on Your T-Deck Pro
First, ensure your SD card is inserted into your T-Deck Pro. Your SD card should already have been formatted as FAT32.
1. Plug your T-Deck Pro into your computer via USB-C.
2. Go to [https://bmorcelli.github.io/Launcher/webflasher.html](https://bmorcelli.github.io/Launcher/webflasher.html) in Chrome browser.
3. Click on **LilyGo** under Choose a Vendor.
4. Click on **T-Deck Pro**.
5. Click on **Connect**.
6. In the serial connect popup, click on your device in the list (likely starts with "USB JTAG/serial debug unit"), and click **Connect**. Wait a few seconds for it to connect.
7. Click the **Install T-Deck Pro** popup.
8. Click **Next**. (Don't worry about ticking the Erase Device checkbox.)
9. Click **Install**.
### If You Don't Already Have a Meck Firmware File
Download one from [https://github.com/pelgraine/Meck/releases](https://github.com/pelgraine/Meck/releases).
## How to Install a New Meck Firmware .bin File via Launcher
After flashing using [https://bmorcelli.github.io/Launcher/webflasher.html](https://bmorcelli.github.io/Launcher/webflasher.html), your Pro will reboot itself automatically and display the main Launcher home screen, with the SD card option highlighted.
<img src="images/01_launcher_home.jpg" alt="Launcher home screen" width="200">
Either tap **NEXT** on the device screen twice or tap on the WUI button, and tap **SEL**.
<img src="images/02_wui_selected.jpg" alt="WUI selected" width="200">
Tap on **My Network** on the pop-up menu. Press **NEXT/SEL** as needed to highlight and select your WiFi SSID.
Enter your WiFi SSID details.
Once connected, your device will display the WebUI connection screen with the T-Deck Pro IP address.
Open a browser on your computer — Chrome, Firefox, or Safari will do, but Firefox tends to be easiest — and type in the IP address displayed on your T-Deck Pro into your computer browser address bar, and press enter.
<img src="images/03_webui_ip.jpg" alt="WebUI IP address screen" width="200">
In this instance, for example, I would type `192.168.1.118`, and once I've pressed enter, the address bar now displays `http://192.168.1.118/` (as per the photo). If you're having trouble loading the IP address page, double check your browser hasn't automatically changed it to `https`. If it has, delete the `s` out of the URL and hit enter to load the page.
Login to the browser page with the username **admin** and password **launcher**, and click **Login**. The browser will refresh and display your SD card file list.
<img src="images/04_browser_login.jpg" alt="Browser login" width="450">
<img src="images/05_send_files.png" alt="SD card file list with Send Files button" width="450">
Scroll down to the bottom of the browser page, and click the **Send Files** button.
Your computer/device will load the file browser. Navigate to wherever you've previously saved your new Meck firmware `.bin` file, select the bin file, and click **Open**.
Wait for the blue loading bar on the bottom of the browser page to finish, and then check you can see the file name in the list in green. Also worth checking the file is at least 1.2MB — if it is under 1MB, the file hasn't uploaded properly and you will need to go through the **Send Files** button to try uploading it again.
<img src="images/06_check_file_uploaded.png" alt="Check file uploaded" width="450">
You can then either close the browser window or just leave it. Go back to your T-Deck Pro and press **SEL** to disconnect the WUI mode.
<img src="images/07_disconnect_wui.png" alt="Disconnect WUI" width="200">
Either press **PREV** twice to navigate to it and then press **SEL** again to open, or tap right on the **SD** button to open the SD card menu.
<img src="images/08_sd_button.jpg" alt="SD button on Launcher home" width="200">
The Launcher SD file browser will open. You will most likely have to tap **Page Down** at least twice to scroll to where the name of your new file is.
<img src="images/09_sd_file_list.png" alt="SD file list page 1" width="200">
<img src="images/10_page_down.png" alt="Page Down to find file" width="200">
Either press **NEXT** to navigate until the new file is highlighted with the `>`, or just tap right on the file name, and press **SEL** to bring up the file menu.
<img src="images/11_select_file.png" alt="Select the firmware file" width="200">
The first option on the file menu list will be **>Install**. You can either tap right on **Install** or tap **SEL**.
<img src="images/12_install_option.png" alt="Install option" width="200">
**Wait for the firmware to finish installing.** It will reboot itself automatically.
<img src="images/13_installing_fw.jpg" alt="Installing firmware" width="200">
> **Note:** On first flash of a new firmware version, the "Loading…" screen will most likely display for about 70 seconds. This is a known bug. **Please be patient** if this is the first time loading your new Meck firmware.
<img src="images/14_loading_screen.png" alt="Loading screen" width="200">
On every boot, the firmware will scan your SD card and `/books` folder for any new `.txt` or `.epub` files that haven't yet been cached. It's usually very quick even if you have a lot of ebook files, and even faster after the first boot.
<img src="images/15_indexing_pages.jpg" alt="Indexing pages" width="200">
You'll then see the firmware version splash screen for a split second.
<img src="images/16_version_splash.jpg" alt="Version splash screen" width="200">
Then the Meck home screen will display, and you're good to go. Here's an example of what the Meck 4G WiFi companion firmware home screen looks like:
<img src="images/17_meck_home.jpg" alt="Meck home screen" width="200">
> **Tip:** Every time you reset the device, the Launcher splash screen will display. Wait about six seconds if you just want the Meck firmware to boot by default. Otherwise, tap the **LAUNCHER** text at the bottom to boot back into the Launcher home screen, to get access to the SD menu and WUI menu again.
<img src="images/18_launcher_boot.jpg" alt="Launcher boot screen" width="200">
Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 394 KiB

+6 -1
View File
@@ -40,14 +40,19 @@ public:
void enableSerial() { _serial->enable(); }
void disableSerial() { _serial->disable(); }
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 newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount,
const uint8_t* path = nullptr, int8_t snr = 0) = 0;
virtual void notify(UIEventType t = UIEventType::none) = 0;
virtual void loop() = 0;
virtual void showAlert(const char* text, int duration_millis) {}
virtual void forceRefresh() {}
virtual void addSentChannelMessage(uint8_t channel_idx, const char* sender, const char* text) {}
// Mark a channel as read when BLE companion app syncs a message
virtual void markChannelReadFromBLE(uint8_t channel_idx) {}
// Repeater admin callbacks (from MyMesh)
virtual void onAdminLoginResult(bool success, uint8_t permissions, uint32_t server_time) {}
virtual void onAdminCliResponse(const char* from_name, const char* text) {}
virtual void onAdminTelemetryResult(const uint8_t* data, uint8_t len) {}
};
+385 -50
View File
@@ -2,7 +2,7 @@
#include "DataStore.h"
#if defined(EXTRAFS) || defined(QSPIFLASH)
#define MAX_BLOBRECS 100
#define MAX_BLOBRECS 1000
#else
#define MAX_BLOBRECS 20
#endif
@@ -230,6 +230,72 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no
file.read((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87
file.read((uint8_t *)&_prefs.utc_offset_hours, sizeof(_prefs.utc_offset_hours)); // 88
// Fields added later — may not exist in older prefs files
if (file.read((uint8_t *)&_prefs.kb_flash_notify, sizeof(_prefs.kb_flash_notify)) != sizeof(_prefs.kb_flash_notify)) {
_prefs.kb_flash_notify = 0; // default OFF for old files
}
if (file.read((uint8_t *)&_prefs.ringtone_enabled, sizeof(_prefs.ringtone_enabled)) != sizeof(_prefs.ringtone_enabled)) {
_prefs.ringtone_enabled = 0; // default OFF for old files
}
// Clamp booleans to 0/1 in case of garbage
if (_prefs.kb_flash_notify > 1) _prefs.kb_flash_notify = 0;
if (_prefs.ringtone_enabled > 1) _prefs.ringtone_enabled = 0;
// v1.14+ fields — may not exist in older prefs files
if (file.read((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)) != sizeof(_prefs.path_hash_mode)) {
_prefs.path_hash_mode = 0; // default: legacy 1-byte
}
if (file.read((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)) != sizeof(_prefs.autoadd_max_hops)) {
_prefs.autoadd_max_hops = 0; // default: no limit
}
if (_prefs.path_hash_mode > 2) _prefs.path_hash_mode = 0;
if (_prefs.autoadd_max_hops > 64) _prefs.autoadd_max_hops = 0;
// v1.1+ Meck fields — may not exist in older prefs files
if (file.read((uint8_t *)&_prefs.gps_baudrate, sizeof(_prefs.gps_baudrate)) != sizeof(_prefs.gps_baudrate)) {
_prefs.gps_baudrate = 0; // default: use compile-time GPS_BAUDRATE
}
if (file.read((uint8_t *)&_prefs.interference_threshold, sizeof(_prefs.interference_threshold)) != sizeof(_prefs.interference_threshold)) {
_prefs.interference_threshold = 0; // default: disabled
}
if (file.read((uint8_t *)&_prefs.dark_mode, sizeof(_prefs.dark_mode)) != sizeof(_prefs.dark_mode)) {
_prefs.dark_mode = 0; // default: light mode
}
if (file.read((uint8_t *)&_prefs.portrait_mode, sizeof(_prefs.portrait_mode)) != sizeof(_prefs.portrait_mode)) {
_prefs.portrait_mode = 0; // default: landscape
}
if (file.read((uint8_t *)&_prefs.auto_lock_minutes, sizeof(_prefs.auto_lock_minutes)) != sizeof(_prefs.auto_lock_minutes)) {
_prefs.auto_lock_minutes = 0; // default: disabled
}
if (file.read((uint8_t *)&_prefs.hint_shown, sizeof(_prefs.hint_shown)) != sizeof(_prefs.hint_shown)) {
_prefs.hint_shown = 0; // default: show boot hint
}
if (file.read((uint8_t *)&_prefs.large_font, sizeof(_prefs.large_font)) != sizeof(_prefs.large_font)) {
_prefs.large_font = 0; // default: tiny font
}
if (file.read((uint8_t *)&_prefs.tx_fail_reset_threshold, sizeof(_prefs.tx_fail_reset_threshold)) != sizeof(_prefs.tx_fail_reset_threshold)) {
_prefs.tx_fail_reset_threshold = 3; // default: 3
}
if (file.read((uint8_t *)&_prefs.rx_fail_reboot_threshold, sizeof(_prefs.rx_fail_reboot_threshold)) != sizeof(_prefs.rx_fail_reboot_threshold)) {
_prefs.rx_fail_reboot_threshold = 3; // default: 3
}
// Clamp to valid ranges
if (_prefs.dark_mode > 1) _prefs.dark_mode = 0;
if (_prefs.portrait_mode > 1) _prefs.portrait_mode = 0;
if (_prefs.hint_shown > 1) _prefs.hint_shown = 0;
if (_prefs.large_font > 1) _prefs.large_font = 0;
if (_prefs.tx_fail_reset_threshold > 10) _prefs.tx_fail_reset_threshold = 3;
if (_prefs.rx_fail_reboot_threshold > 10) _prefs.rx_fail_reboot_threshold = 3;
// auto_lock_minutes: only accept known options (0, 2, 5, 10, 15, 30)
{
uint8_t alm = _prefs.auto_lock_minutes;
if (alm != 0 && alm != 2 && alm != 5 && alm != 10 && alm != 15 && alm != 30) {
_prefs.auto_lock_minutes = 0;
}
}
file.close();
}
}
@@ -265,14 +331,75 @@ void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_
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.utc_offset_hours, sizeof(_prefs.utc_offset_hours)); // 88
file.write((uint8_t *)&_prefs.kb_flash_notify, sizeof(_prefs.kb_flash_notify)); // 89
file.write((uint8_t *)&_prefs.ringtone_enabled, sizeof(_prefs.ringtone_enabled)); // 90
file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 91
file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 92
file.write((uint8_t *)&_prefs.gps_baudrate, sizeof(_prefs.gps_baudrate)); // 93
file.write((uint8_t *)&_prefs.interference_threshold, sizeof(_prefs.interference_threshold)); // 97
file.write((uint8_t *)&_prefs.dark_mode, sizeof(_prefs.dark_mode)); // 98
file.write((uint8_t *)&_prefs.portrait_mode, sizeof(_prefs.portrait_mode)); // 99
file.write((uint8_t *)&_prefs.auto_lock_minutes, sizeof(_prefs.auto_lock_minutes)); // 100
file.write((uint8_t *)&_prefs.hint_shown, sizeof(_prefs.hint_shown)); // 101
file.write((uint8_t *)&_prefs.large_font, sizeof(_prefs.large_font)); // 102
file.write((uint8_t *)&_prefs.tx_fail_reset_threshold, sizeof(_prefs.tx_fail_reset_threshold)); // 103
file.write((uint8_t *)&_prefs.rx_fail_reboot_threshold, sizeof(_prefs.rx_fail_reboot_threshold)); // 104
file.close();
}
}
void DataStore::loadContacts(DataStoreHost* host) {
File file = openRead(_getContactsChannelsFS(), "/contacts3");
FILESYSTEM* fs = _getContactsChannelsFS();
// --- Crash recovery ---
// If /contacts3 is missing but /contacts3.tmp exists, a crash occurred
// after removing the original but before the rename completed.
// The .tmp file has the valid data — promote it.
if (!fs->exists("/contacts3") && fs->exists("/contacts3.tmp")) {
Serial.println("DataStore: recovering contacts from .tmp file");
fs->rename("/contacts3.tmp", "/contacts3");
}
// If both exist, a crash occurred before the old file was removed.
// The original /contacts3 is still valid — just clean up the orphan.
if (fs->exists("/contacts3.tmp")) {
fs->remove("/contacts3.tmp");
}
File file = openRead(fs, "/contacts3");
if (file) {
// --- Truncation guard ---
// If the file is smaller than one full contact record (152 bytes),
// it was truncated by a crash/brown-out. Discard it and try the
// .tmp backup if available.
size_t fsize = file.size();
if (fsize > 0 && fsize < 152) {
Serial.printf("DataStore: contacts3 truncated (%d bytes < 152), discarding\n", (int)fsize);
file.close();
fs->remove("/contacts3");
if (fs->exists("/contacts3.tmp")) {
File tmp = openRead(fs, "/contacts3.tmp");
if (tmp && tmp.size() >= 152) {
Serial.println("DataStore: recovering from .tmp after truncation");
tmp.close();
fs->rename("/contacts3.tmp", "/contacts3");
file = openRead(fs, "/contacts3");
if (!file) return; // give up
} else {
if (tmp) tmp.close();
Serial.println("DataStore: no valid contacts backup — starting fresh");
return;
}
} else {
Serial.println("DataStore: no .tmp backup — starting fresh");
return;
}
} else if (fsize == 0) {
// Empty file — nothing to load
file.close();
return;
}
bool full = false;
while (!full) {
ContactInfo c;
@@ -302,36 +429,192 @@ File file = openRead(_getContactsChannelsFS(), "/contacts3");
}
void DataStore::saveContacts(DataStoreHost* host) {
File file = openWrite(_getContactsChannelsFS(), "/contacts3");
if (file) {
uint32_t idx = 0;
ContactInfo c;
uint8_t unused = 0;
FILESYSTEM* fs = _getContactsChannelsFS();
const char* finalPath = "/contacts3";
const char* tmpPath = "/contacts3.tmp";
while (host->getContactForSave(idx, c)) {
bool success = (file.write(c.id.pub_key, 32) == 32);
success = success && (file.write((uint8_t *)&c.name, 32) == 32);
success = success && (file.write(&c.type, 1) == 1);
success = success && (file.write(&c.flags, 1) == 1);
success = success && (file.write(&unused, 1) == 1);
success = success && (file.write((uint8_t *)&c.sync_since, 4) == 4);
success = success && (file.write((uint8_t *)&c.out_path_len, 1) == 1);
success = success && (file.write((uint8_t *)&c.last_advert_timestamp, 4) == 4);
success = success && (file.write(c.out_path, 64) == 64);
success = success && (file.write((uint8_t *)&c.lastmod, 4) == 4);
success = success && (file.write((uint8_t *)&c.gps_lat, 4) == 4);
success = success && (file.write((uint8_t *)&c.gps_lon, 4) == 4);
// --- Step 1: Write all contacts to a temporary file ---
File file = openWrite(fs, tmpPath);
if (!file) {
Serial.println("DataStore: saveContacts FAILED — cannot open tmp file");
return;
}
if (!success) break; // write failed
uint32_t idx = 0;
ContactInfo c;
uint8_t unused = 0;
uint32_t recordsWritten = 0;
bool writeOk = true;
idx++; // advance to next contact
while (host->getContactForSave(idx, c)) {
bool success = (file.write(c.id.pub_key, 32) == 32);
success = success && (file.write((uint8_t *)&c.name, 32) == 32);
success = success && (file.write(&c.type, 1) == 1);
success = success && (file.write(&c.flags, 1) == 1);
success = success && (file.write(&unused, 1) == 1);
success = success && (file.write((uint8_t *)&c.sync_since, 4) == 4);
success = success && (file.write((uint8_t *)&c.out_path_len, 1) == 1);
success = success && (file.write((uint8_t *)&c.last_advert_timestamp, 4) == 4);
success = success && (file.write(c.out_path, 64) == 64);
success = success && (file.write((uint8_t *)&c.lastmod, 4) == 4);
success = success && (file.write((uint8_t *)&c.gps_lat, 4) == 4);
success = success && (file.write((uint8_t *)&c.gps_lon, 4) == 4);
if (!success) {
writeOk = false;
Serial.printf("DataStore: saveContacts write error at record %d\n", idx);
break;
}
file.close();
recordsWritten++;
idx++;
}
file.close();
// --- Step 2: Verify the write completed ---
// Reopen read-only to get true on-disk size (SPIFFS file.size() is unreliable before close)
size_t expectedBytes = recordsWritten * 152; // 152 bytes per contact record
File verify = openRead(fs, tmpPath);
size_t bytesWritten = verify ? verify.size() : 0;
if (verify) verify.close();
if (!writeOk || bytesWritten != expectedBytes) {
Serial.printf("DataStore: saveContacts ABORTED — wrote %d bytes, expected %d (%d records)\n",
(int)bytesWritten, (int)expectedBytes, recordsWritten);
fs->remove(tmpPath); // Clean up failed tmp file
return; // Original /contacts3 is untouched
}
// --- Step 3: Replace original with verified temp file ---
fs->remove(finalPath);
if (fs->rename(tmpPath, finalPath)) {
Serial.printf("DataStore: saved %d contacts (%d bytes)\n", recordsWritten, (int)bytesWritten);
} else {
// Rename failed — tmp file still has the good data
Serial.println("DataStore: rename failed, tmp file preserved");
}
}
// =========================================================================
// Chunked contact save — non-blocking across multiple loop iterations
// =========================================================================
bool DataStore::beginSaveContacts(DataStoreHost* host) {
if (_saveInProgress) return false; // Already saving
FILESYSTEM* fs = _getContactsChannelsFS();
// Defensive cleanup in case a previous save didn't reach finishSaveContacts()
if (_saveFile) {
_saveFile->close();
delete _saveFile;
_saveFile = nullptr;
}
_saveFile = new File(openWrite(fs, "/contacts3.tmp"));
if (!_saveFile || !*_saveFile) {
Serial.println("DataStore: chunked save FAILED — cannot open tmp file");
if (_saveFile) { delete _saveFile; _saveFile = nullptr; }
return false;
}
_saveHost = host;
_saveIdx = 0;
_saveRecordsWritten = 0;
_saveWriteOk = true;
_saveInProgress = true;
Serial.println("DataStore: chunked save started");
return true;
}
bool DataStore::saveContactsChunk(int batchSize) {
if (!_saveInProgress || !_saveWriteOk) return false;
ContactInfo c;
uint8_t unused = 0;
int written = 0;
while (written < batchSize && _saveHost->getContactForSave(_saveIdx, c)) {
bool success = (_saveFile->write(c.id.pub_key, 32) == 32);
success = success && (_saveFile->write((uint8_t *)&c.name, 32) == 32);
success = success && (_saveFile->write(&c.type, 1) == 1);
success = success && (_saveFile->write(&c.flags, 1) == 1);
success = success && (_saveFile->write(&unused, 1) == 1);
success = success && (_saveFile->write((uint8_t *)&c.sync_since, 4) == 4);
success = success && (_saveFile->write((uint8_t *)&c.out_path_len, 1) == 1);
success = success && (_saveFile->write((uint8_t *)&c.last_advert_timestamp, 4) == 4);
success = success && (_saveFile->write(c.out_path, 64) == 64);
success = success && (_saveFile->write((uint8_t *)&c.lastmod, 4) == 4);
success = success && (_saveFile->write((uint8_t *)&c.gps_lat, 4) == 4);
success = success && (_saveFile->write((uint8_t *)&c.gps_lon, 4) == 4);
if (!success) {
_saveWriteOk = false;
Serial.printf("DataStore: chunked save write error at record %d\n", _saveIdx);
return false; // Error — finishSaveContacts will clean up
}
_saveRecordsWritten++;
_saveIdx++;
written++;
}
// Check if there are more contacts to write
ContactInfo peek;
if (_saveHost->getContactForSave(_saveIdx, peek)) {
return true; // More to write
}
return false; // Done
}
void DataStore::finishSaveContacts() {
if (!_saveInProgress) return;
if (_saveFile) {
_saveFile->close();
delete _saveFile;
_saveFile = nullptr;
}
_saveInProgress = false;
FILESYSTEM* fs = _getContactsChannelsFS();
const char* finalPath = "/contacts3";
const char* tmpPath = "/contacts3.tmp";
// Verify
size_t expectedBytes = _saveRecordsWritten * 152;
File verify = openRead(fs, tmpPath);
size_t bytesWritten = verify ? verify.size() : 0;
if (verify) verify.close();
if (!_saveWriteOk || bytesWritten != expectedBytes) {
Serial.printf("DataStore: chunked save ABORTED — wrote %d bytes, expected %d (%d records)\n",
(int)bytesWritten, (int)expectedBytes, _saveRecordsWritten);
fs->remove(tmpPath);
return;
}
fs->remove(finalPath);
if (fs->rename(tmpPath, finalPath)) {
Serial.printf("DataStore: saved %d contacts (%d bytes, chunked)\n",
_saveRecordsWritten, (int)bytesWritten);
} else {
Serial.println("DataStore: rename failed, tmp file preserved");
}
}
void DataStore::loadChannels(DataStoreHost* host) {
File file = openRead(_getContactsChannelsFS(), "/channels2");
FILESYSTEM* fs = _getContactsChannelsFS();
// Crash recovery (same pattern as contacts)
if (!fs->exists("/channels2") && fs->exists("/channels2.tmp")) {
Serial.println("DataStore: recovering channels from .tmp file");
fs->rename("/channels2.tmp", "/channels2");
}
if (fs->exists("/channels2.tmp")) {
fs->remove("/channels2.tmp");
}
File file = openRead(fs, "/channels2");
if (file) {
bool full = false;
uint8_t channel_idx = 0;
@@ -356,22 +639,54 @@ void DataStore::loadChannels(DataStoreHost* host) {
}
void DataStore::saveChannels(DataStoreHost* host) {
File file = openWrite(_getContactsChannelsFS(), "/channels2");
if (file) {
uint8_t channel_idx = 0;
ChannelDetails ch;
uint8_t unused[4];
memset(unused, 0, 4);
FILESYSTEM* fs = _getContactsChannelsFS();
const char* finalPath = "/channels2";
const char* tmpPath = "/channels2.tmp";
while (host->getChannelForSave(channel_idx, ch)) {
bool success = (file.write(unused, 4) == 4);
success = success && (file.write((uint8_t *)ch.name, 32) == 32);
success = success && (file.write((uint8_t *)ch.channel.secret, 32) == 32);
File file = openWrite(fs, tmpPath);
if (!file) {
Serial.println("DataStore: saveChannels FAILED — cannot open tmp file");
return;
}
if (!success) break; // write failed
channel_idx++;
uint8_t channel_idx = 0;
ChannelDetails ch;
uint8_t unused[4];
memset(unused, 0, 4);
bool writeOk = true;
while (host->getChannelForSave(channel_idx, ch)) {
bool success = (file.write(unused, 4) == 4);
success = success && (file.write((uint8_t *)ch.name, 32) == 32);
success = success && (file.write((uint8_t *)ch.channel.secret, 32) == 32);
if (!success) {
writeOk = false;
Serial.printf("DataStore: saveChannels write error at channel %d\n", channel_idx);
break;
}
file.close();
channel_idx++;
}
file.close();
// Reopen read-only to get true on-disk size (SPIFFS file.size() is unreliable before close)
size_t expectedBytes = channel_idx * 68; // 4 + 32 + 32 = 68 bytes per channel
File verify = openRead(fs, tmpPath);
size_t bytesWritten = verify ? verify.size() : 0;
if (verify) verify.close();
if (!writeOk || bytesWritten != expectedBytes) {
Serial.printf("DataStore: saveChannels ABORTED — wrote %d bytes, expected %d\n",
(int)bytesWritten, (int)expectedBytes);
fs->remove(tmpPath);
return;
}
fs->remove(finalPath);
if (fs->rename(tmpPath, finalPath)) {
Serial.printf("DataStore: saved %d channels (%d bytes)\n", channel_idx, (int)bytesWritten);
} else {
Serial.println("DataStore: channels rename failed, tmp file preserved");
}
}
@@ -387,16 +702,27 @@ struct BlobRec {
};
void DataStore::checkAdvBlobFile() {
if (!_getContactsChannelsFS()->exists("/adv_blobs")) {
File file = openWrite(_getContactsChannelsFS(), "/adv_blobs");
if (file) {
BlobRec zeroes;
memset(&zeroes, 0, sizeof(zeroes));
for (int i = 0; i < MAX_BLOBRECS; i++) { // pre-allocate to fixed size
file.write((uint8_t *) &zeroes, sizeof(zeroes));
}
file.close();
FILESYSTEM* fs = _getContactsChannelsFS();
size_t expectedSize = (size_t)MAX_BLOBRECS * sizeof(BlobRec);
if (fs->exists("/adv_blobs")) {
File existing = openRead(fs, "/adv_blobs");
size_t actualSize = existing ? (size_t)existing.size() : 0;
if (existing) existing.close();
if (actualSize == expectedSize) return; // already correct size
Serial.printf("[DataStore] adv_blobs wrong size (%u vs %u) — recreating\n",
(unsigned)actualSize, (unsigned)expectedSize);
fs->remove("/adv_blobs"); // delete undersized (or oversized) file
}
File file = openWrite(fs, "/adv_blobs");
if (file) {
BlobRec zeroes;
memset(&zeroes, 0, sizeof(zeroes));
for (int i = 0; i < MAX_BLOBRECS; i++) {
file.write((uint8_t *) &zeroes, sizeof(zeroes));
}
file.close();
}
}
@@ -569,10 +895,14 @@ uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_b
if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
mesh::Utils::toHex(fname, key, key_len);
// Prefer SD card (_fsExtra) — unlimited file count vs SPIFFS ~100-200 file limit.
// Fall back to SPIFFS (_fs) for devices without SD.
FILESYSTEM* blobFs = (_fsExtra != nullptr) ? _fsExtra : _fs;
sprintf(path, "/bl/%s", fname);
if (_fs->exists(path)) {
File f = openRead(_fs, path);
if (blobFs->exists(path)) {
File f = openRead(blobFs, path);
if (f) {
int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!!
f.close();
@@ -588,15 +918,20 @@ bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src
if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix)
mesh::Utils::toHex(fname, key, key_len);
// Prefer SD card (_fsExtra) — unlimited file count vs SPIFFS ~100-200 file limit.
FILESYSTEM* blobFs = (_fsExtra != nullptr) ? _fsExtra : _fs;
blobFs->mkdir("/bl"); // ensure directory exists on chosen filesystem
sprintf(path, "/bl/%s", fname);
File f = openWrite(_fs, path);
File f = openWrite(blobFs, path);
if (f) {
int n = f.write(src_buf, len);
f.close();
if (n == len) return true; // success!
_fs->remove(path); // blob was only partially written!
blobFs->remove(path); // blob was only partially written!
}
return false; // error
}
+20 -1
View File
@@ -24,6 +24,17 @@ class DataStore {
void checkAdvBlobFile();
#endif
// Chunked save state
// Stored as a pointer (allocated in beginSaveContacts, freed in
// finishSaveContacts) because Adafruit_LittleFS::File has no default
// constructor — we can't keep one as a default-initialized value member.
File* _saveFile = nullptr;
DataStoreHost* _saveHost = nullptr;
uint32_t _saveIdx = 0;
uint32_t _saveRecordsWritten = 0;
bool _saveInProgress = false;
bool _saveWriteOk = true;
public:
DataStore(FILESYSTEM& fs, mesh::RTCClock& clock);
DataStore(FILESYSTEM& fs, FILESYSTEM& fsExtra, mesh::RTCClock& clock);
@@ -37,6 +48,14 @@ public:
void savePrefs(const NodePrefs& prefs, double node_lat, double node_lon);
void loadContacts(DataStoreHost* host);
void saveContacts(DataStoreHost* host);
// Chunked save — splits contact write across multiple loop iterations
// to prevent blocking the main loop for 500ms+ on large contact lists.
// Call beginSaveContacts(), then saveContactsChunk() each loop until it
// returns false (done), then finishSaveContacts() to verify and commit.
bool beginSaveContacts(DataStoreHost* host);
bool saveContactsChunk(int batchSize = 20); // returns true if more to write
void finishSaveContacts();
bool isSaveInProgress() const { return _saveInProgress; }
void loadChannels(DataStoreHost* host);
void saveChannels(DataStoreHost* host);
void migrateToSecondaryFS();
@@ -51,4 +70,4 @@ public:
private:
FILESYSTEM* _getContactsChannelsFS() const { if (_fsExtra) return _fsExtra; return _fs;};
};
};
File diff suppressed because it is too large Load Diff
+101 -8
View File
@@ -5,14 +5,14 @@
#include "AbstractUITask.h"
/*------------ Frame Protocol --------------*/
#define FIRMWARE_VER_CODE 8
#define FIRMWARE_VER_CODE 11
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "11 Feb 2026"
#define FIRMWARE_BUILD_DATE "16 April 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "Meck v0.8.4"
#define FIRMWARE_VERSION "Meck v1.7"
#endif
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
@@ -70,6 +70,11 @@
#include <helpers/BaseChatMesh.h>
#include <helpers/TransportKeyStore.h>
// Custom path lock flag — bit 7 of ContactInfo.flags
// When set, onContactPathRecv skips auto-updating this contact's out_path.
// Bits 0-6 remain available (bit 0 = favourite, bits 1-3 = telemetry perms).
#define CONTACT_FLAG_CUSTOM_PATH 0x80
/* -------------------------------------------------------------------------------------- */
#define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
@@ -77,13 +82,24 @@
#define REQ_TYPE_GET_TELEMETRY_DATA 0x03
struct AdvertPath {
uint8_t pubkey_prefix[7];
uint8_t pubkey_prefix[8];
uint8_t path_len;
uint8_t type; // ADV_TYPE_* (Chat/Repeater/Room/Sensor)
char name[32];
uint32_t recv_timestamp;
uint8_t path[MAX_PATH_SIZE];
};
// Discovery scan — transient buffer for on-device node discovery
#define MAX_DISCOVERED_NODES 20
struct DiscoveredNode {
ContactInfo contact;
uint8_t path_len;
int8_t snr; // SNR × 4 from active discovery response (0 if pre-seeded)
bool already_in_contacts; // true if contact was auto-added or already known
};
class MyMesh : public BaseChatMesh, public DataStoreHost {
public:
MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui=NULL);
@@ -101,6 +117,23 @@ public:
void enterCLIRescue();
int getRecentlyHeard(AdvertPath dest[], int max_num);
// Discovery scan — on-device node discovery
void startDiscovery(uint32_t duration_ms = 30000);
void stopDiscovery();
bool isDiscoveryActive() const { return _discoveryActive; }
int getDiscoveredCount() const { return _discoveredCount; }
const DiscoveredNode& getDiscovered(int idx) const { return _discovered[idx]; }
bool addDiscoveredToContacts(int idx); // promote a discovered node into contacts
// Last Heard — public wrappers for contact add/remove from UI
void scheduleLazyContactSave();
int getContactBlob(const uint8_t key[], int key_len, uint8_t dest_buf[]) {
return getBlobByKey(key, key_len, dest_buf);
}
// Force-add a contact from a raw advert blob, bypassing auto-add settings.
// Used by Last Heard and Discovery when the user explicitly selects a node to add.
bool forceImportContact(const uint8_t* blob, uint8_t len);
// Queue a sent channel message for BLE app sync
void queueSentChannelMessage(uint8_t channel_idx, uint32_t timestamp, const char* sender, const char* text);
@@ -108,19 +141,59 @@ public:
// Send a direct message from the UI (no BLE dependency)
bool uiSendDirectMessage(uint32_t contact_idx, const char* text);
// Send raw binary data to a contact (PAYLOAD_TYPE_RAW_CUSTOM, direct route only)
// Used for dz0ny VE3 voice protocol: voice packets (0x56) and fetch requests (0x72)
bool uiSendRawToContact(uint32_t contact_idx, const uint8_t* data, uint8_t len);
// Voice-over-LoRa: callback for incoming raw voice packets (dz0ny VE3 protocol)
// magic 0x56 = voice data packet, 0x72 = fetch request
typedef void (*VoiceRawHandler)(uint8_t magic, const uint8_t* payload, uint8_t len);
void setVoiceHandler(VoiceRawHandler h) { _voiceHandler = h; }
// Voice-over-LoRa: callback for incoming VE3 envelope in a DM
// Called with sender name and the VE3 text (e.g. "VE3:a:1:3:2")
typedef void (*VoiceEnvelopeHandler)(const char* senderName, const char* ve3Text);
void setVoiceEnvelopeHandler(VoiceEnvelopeHandler h) { _voiceEnvHandler = h; }
// Defer contact saves while voice packets are being received
// (SD writes block SPI bus shared with LoRa radio)
void setDeferSaves(bool defer) { _deferSaves = defer; }
bool isDeferSaves() const { return _deferSaves; }
// Repeater admin - UI-initiated operations
bool uiLoginToRepeater(uint32_t contact_idx, const char* password);
bool uiLoginToRepeater(uint32_t contact_idx, const char* password, uint32_t& est_timeout_ms);
bool uiSendCliCommand(uint32_t contact_idx, const char* command);
bool uiSendTelemetryRequest(uint32_t contact_idx);
int getAdminContactIdx() const { return _admin_contact_idx; }
// Custom path editor — set or clear a manually configured path for a contact
// When locked, automatic path discovery will not overwrite this contact's path.
bool setCustomPath(int contactIdx, const uint8_t* path, uint8_t pathLen, bool lock);
void clearCustomPath(int contactIdx);
#ifdef HELTEC_MESH_POCKET
// Power saving: check if there is pending work (outbound packets queued, etc.)
// Used by main.cpp loop to decide whether board.sleep() is safe.
// Adapted from MeshCore PR #2286 (IoTThinks) — substitutes getOutboundCount(0xFFFFFFFF)
// for upstream's getOutboundTotal() which doesn't exist in this tree.
bool hasPendingWork() const;
#endif
protected:
float getAirtimeBudgetFactor() const override;
int getInterferenceThreshold() const override;
uint8_t getTxFailResetThreshold() const override;
uint8_t getRxFailRebootThreshold() const override;
void onRxUnrecoverable() override;
int calcRxDelay(float score, uint32_t air_time) const override;
uint32_t getRetransmitDelay(const mesh::Packet *packet) override;
uint32_t getDirectRetransmitDelay(const mesh::Packet *packet) override;
uint8_t getExtraAckTransmitCount() const override;
uint8_t getAutoAddMaxHops() const override;
bool filterRecvFloodPacket(mesh::Packet* packet) override;
uint8_t getPathHashSize() const override { return _prefs.path_hash_mode + 1; }
void sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis=0) override;
void sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis=0) override;
@@ -181,7 +254,7 @@ private:
void writeOKFrame();
void writeErrFrame(uint8_t err_code);
void writeDisabledFrame();
void writeContactRespFrame(uint8_t code, const ContactInfo &contact);
size_t writeContactRespFrame(uint8_t code, const ContactInfo &contact);
void updateContactFromFrame(ContactInfo &contact, uint32_t& last_mod, const uint8_t *frame, int len);
void addToOfflineQueue(const uint8_t frame[], int len);
int getFromOfflineQueue(uint8_t frame[]);
@@ -197,6 +270,10 @@ private:
DataStore* _store;
NodePrefs _prefs;
VoiceRawHandler _voiceHandler = nullptr;
VoiceEnvelopeHandler _voiceEnvHandler = nullptr;
mutable bool _forceNextImport = false;
bool _deferSaves = false;
uint32_t pending_login;
uint32_t pending_status;
uint32_t pending_telemetry, pending_discovery; // pending _TELEMETRY_REQ
@@ -240,8 +317,17 @@ private:
AckTableEntry expected_ack_table[EXPECTED_ACK_TABLE_SIZE]; // circular table
int next_ack_idx;
#define ADVERT_PATH_TABLE_SIZE 16
AdvertPath advert_paths[ADVERT_PATH_TABLE_SIZE]; // circular table
// Advert path table: stores paths we've heard back to us for sorting/recency.
// ESP32 variants (T-Deck Pro, T5S3, Heltec V4) have PSRAM, so can afford the
// large 1000-entry table (~50KB). nRF52 companion builds (Heltec Meshpocket,
// T-Echo Card) have no PSRAM and only 256KB total SRAM shared with BLE, so
// use a much smaller table sized for realistic handheld usage.
#if defined(ESP32)
#define ADVERT_PATH_TABLE_SIZE 1000
#else
#define ADVERT_PATH_TABLE_SIZE 50
#endif
AdvertPath* advert_paths; // PSRAM-allocated (ESP32) or heap-allocated (nRF52) in begin()
// Sent message repeat tracking
#define SENT_TRACK_SIZE 4
@@ -256,6 +342,13 @@ private:
SentMsgTrack _sent_track[SENT_TRACK_SIZE];
int _sent_track_idx; // next slot in circular buffer
int _admin_contact_idx; // contact index for active admin session (-1 if none)
// Discovery scan state
DiscoveredNode _discovered[MAX_DISCOVERED_NODES];
int _discoveredCount;
bool _discoveryActive;
unsigned long _discoveryTimeout;
uint32_t _discoveryTag; // random correlation tag for active discovery
};
extern MyMesh the_mesh;
+47
View File
@@ -29,4 +29,51 @@ struct NodePrefs { // persisted to file
uint32_t gps_interval; // GPS read interval in seconds
uint8_t autoadd_config; // bitmask for auto-add contacts config
int8_t utc_offset_hours; // UTC offset in hours (-12 to +14), default 0
uint8_t kb_flash_notify; // Keyboard backlight flash on new message (0=off, 1=on)
uint8_t ringtone_enabled; // Ringtone on incoming call (0=off, 1=on) — 4G only
uint8_t path_hash_mode; // 0=1-byte (legacy), 1=2-byte, 2=3-byte path hashes
uint8_t autoadd_max_hops; // 0=no limit, N=up to N-1 hops (max 64)
uint32_t gps_baudrate; // GPS baud rate (0 = use compile-time GPS_BAUDRATE default)
uint8_t interference_threshold; // Interference threshold in dB (0=disabled, 14+=enabled)
uint8_t dark_mode; // 0=off (white bg), 1=on (black bg)
uint8_t portrait_mode; // 0=landscape, 1=portrait — T5S3 only
uint8_t auto_lock_minutes; // 0=disabled, 2/5/10/15/30=auto-lock after idle
uint8_t hint_shown; // 0=show nav hint on boot, 1=already shown (dismiss permanently)
uint8_t large_font; // 0=tiny (built-in 6x8), 1=larger (FreeSans9pt) — T-Deck Pro only
uint8_t tx_fail_reset_threshold; // 0=disabled, 1-10, default 3
uint8_t rx_fail_reboot_threshold; // 0=disabled, 1-10, default 3
// --- Font helpers (inline, no overhead) ---
// Returns the DisplayDriver text-size index for "small/body" text.
// T-Deck Pro: 0 = built-in 6×8, 1 = FreeSans9pt.
// T5S3: both 0 and 1 are 12pt fonts (regular vs bold) with identical line
// height, so large_font has no layout effect there.
inline uint8_t smallTextSize() const {
return large_font ? 1 : 0;
}
// Returns the virtual-coordinate line height matching smallTextSize().
// T-Deck Pro size 0 → 9 (6×8 + 1px gap), size 1 → 11 (9pt ascent+descent).
// T5S3 size 0/1 → same 12pt height → always 9 in virtual coords.
inline int smallLineH() const {
#if defined(LilyGo_T5S3_EPaper_Pro)
return 9;
#else
return large_font ? 11 : 9;
#endif
}
// Returns the Y offset for selection highlight fillRect (T-Deck Pro only).
// Size 0 (built-in font): cursor positions at top-left, +5 offset in
// setCursor places text below → fillRect at y+5 aligns with text.
// Size 1 (FreeSans9pt): cursor positions at baseline, ascenders render
// upward → fillRect must start above baseline to cover ascenders.
// T5S3: always 0 (both sizes use baseline fonts with highlight at y).
inline int smallHighlightOff() const {
#if defined(LilyGo_T5S3_EPaper_Pro)
return 0;
#else
return large_font ? -2 : 5;
#endif
}
};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,372 @@
#pragma once
// =============================================================================
// ApnDatabase.h - Embedded APN Lookup Table
//
// Maps MCC/MNC (Mobile Country Code / Mobile Network Code) to default APN
// settings for common carriers worldwide. Compiled directly into flash (~3KB)
// so users never need to manually install a lookup file.
//
// The modem queries IMSI via AT+CIMI to extract MCC (3 digits) + MNC (2-3
// digits), then looks up the APN here. If not found, falls back to the
// modem's existing PDP context (AT+CGDCONT?) or user-configured APN.
//
// To add a carrier: append to APN_DATABASE[] with the MCC+MNC as a single
// integer. MNC can be 2 or 3 digits:
// MCC=310, MNC=260 → mccmnc = 310260
// MCC=505, MNC=01 → mccmnc = 50501
//
// Guard: HAS_4G_MODEM
// =============================================================================
#ifdef HAS_4G_MODEM
#ifndef APN_DATABASE_H
#define APN_DATABASE_H
struct ApnEntry {
uint32_t mccmnc; // MCC+MNC as integer (e.g. 310260 for T-Mobile US)
const char* apn; // APN string
const char* carrier; // Human-readable carrier name (for debug/display)
};
// ---------------------------------------------------------------------------
// APN Database — sorted by MCC for binary search potential (not required)
//
// Sources: carrier documentation, GSMA databases, community wikis.
// This covers ~120 major carriers across key regions. Users with less
// common carriers can set APN manually in Settings.
// ---------------------------------------------------------------------------
static const ApnEntry APN_DATABASE[] = {
// =========================================================================
// Australia (MCC 505)
// =========================================================================
{ 50501, "telstra.internet", "Telstra" },
{ 50502, "yesinternet", "Optus" },
{ 50503, "vfinternet.au", "Vodafone AU" },
{ 50506, "3netaccess", "Three AU" },
{ 50507, "telstra.internet", "Vodafone AU (MVNO)" }, // Many MVNOs on Telstra
{ 50510, "telstra.internet", "Norfolk Tel" },
{ 50512, "3netaccess", "Amaysim" }, // Optus MVNO
{ 50514, "yesinternet", "Aussie Broadband" }, // Optus MVNO
{ 50590, "yesinternet", "Optus MVNO" },
// =========================================================================
// New Zealand (MCC 530)
// =========================================================================
{ 53001, "internet", "Vodafone NZ" },
{ 53005, "internet", "Spark NZ" },
{ 53024, "internet", "2degrees" },
// =========================================================================
// United States (MCC 310, 311, 312, 313, 316)
// =========================================================================
{ 310012, "fast.t-mobile.com", "Verizon (old)" },
{ 310026, "fast.t-mobile.com", "T-Mobile US" },
{ 310030, "fast.t-mobile.com", "T-Mobile US" },
{ 310032, "fast.t-mobile.com", "T-Mobile US" },
{ 310060, "fast.t-mobile.com", "T-Mobile US" },
{ 310160, "fast.t-mobile.com", "T-Mobile US" },
{ 310200, "fast.t-mobile.com", "T-Mobile US" },
{ 310210, "fast.t-mobile.com", "T-Mobile US" },
{ 310220, "fast.t-mobile.com", "T-Mobile US" },
{ 310230, "fast.t-mobile.com", "T-Mobile US" },
{ 310240, "fast.t-mobile.com", "T-Mobile US" },
{ 310250, "fast.t-mobile.com", "T-Mobile US" },
{ 310260, "fast.t-mobile.com", "T-Mobile US" },
{ 310270, "fast.t-mobile.com", "T-Mobile US" },
{ 310310, "fast.t-mobile.com", "T-Mobile US" },
{ 310490, "fast.t-mobile.com", "T-Mobile US" },
{ 310530, "fast.t-mobile.com", "T-Mobile US" },
{ 310580, "fast.t-mobile.com", "T-Mobile US" },
{ 310660, "fast.t-mobile.com", "T-Mobile US" },
{ 310800, "fast.t-mobile.com", "T-Mobile US" },
{ 311480, "vzwinternet", "Verizon" },
{ 311481, "vzwinternet", "Verizon" },
{ 311482, "vzwinternet", "Verizon" },
{ 311483, "vzwinternet", "Verizon" },
{ 311484, "vzwinternet", "Verizon" },
{ 311489, "vzwinternet", "Verizon" },
{ 310410, "fast.t-mobile.com", "AT&T (migrated)" },
{ 310120, "att.mvno", "AT&T (Sprint)" },
{ 312530, "iot.1nce.net", "1NCE IoT" },
{ 310120, "tfdata", "Tracfone" },
// =========================================================================
// Canada (MCC 302)
// =========================================================================
{ 30220, "internet.com", "Rogers" },
{ 30221, "internet.com", "Rogers" },
{ 30237, "internet.com", "Rogers" },
{ 30272, "internet.com", "Rogers" },
{ 30234, "sp.telus.com", "Telus" },
{ 30286, "sp.telus.com", "Telus" },
{ 30236, "sp.telus.com", "Telus" },
{ 30261, "sp.bell.ca", "Bell" },
{ 30263, "sp.bell.ca", "Bell" },
{ 30267, "sp.bell.ca", "Bell" },
{ 30268, "fido-core-appl1.apn", "Fido" },
{ 30278, "internet.com", "SaskTel" },
{ 30266, "sp.mb.com", "MTS" },
// =========================================================================
// United Kingdom (MCC 234, 235)
// =========================================================================
{ 23410, "o2-internet", "O2 UK" },
{ 23415, "three.co.uk", "Vodafone UK" },
{ 23420, "three.co.uk", "Three UK" },
{ 23430, "everywhere", "EE" },
{ 23431, "everywhere", "EE" },
{ 23432, "everywhere", "EE" },
{ 23433, "everywhere", "EE" },
{ 23450, "data.lycamobile.co.uk","Lycamobile UK" },
{ 23486, "three.co.uk", "Three UK" },
// =========================================================================
// Germany (MCC 262)
// =========================================================================
{ 26201, "internet.t-mobile", "Telekom DE" },
{ 26202, "web.vodafone.de", "Vodafone DE" },
{ 26203, "internet", "O2 DE" },
{ 26207, "internet", "O2 DE" },
// =========================================================================
// France (MCC 208)
// =========================================================================
{ 20801, "orange", "Orange FR" },
{ 20810, "sl2sfr", "SFR" },
{ 20815, "free", "Free Mobile" },
{ 20820, "ofnew.fr", "Bouygues" },
// =========================================================================
// Italy (MCC 222)
// =========================================================================
{ 22201, "mobile.vodafone.it", "TIM" },
{ 22210, "mobile.vodafone.it", "Vodafone IT" },
{ 22250, "internet.it", "Iliad IT" },
{ 22288, "internet.wind", "WindTre" },
{ 22299, "internet.wind", "WindTre" },
// =========================================================================
// Spain (MCC 214)
// =========================================================================
{ 21401, "internet", "Vodafone ES" },
{ 21403, "internet", "Orange ES" },
{ 21404, "internet", "Yoigo" },
{ 21407, "internet", "Movistar" },
// =========================================================================
// Netherlands (MCC 204)
// =========================================================================
{ 20404, "internet", "Vodafone NL" },
{ 20408, "internet", "KPN" },
{ 20412, "internet", "Telfort" },
{ 20416, "internet", "T-Mobile NL" },
{ 20420, "internet", "T-Mobile NL" },
// =========================================================================
// Sweden (MCC 240)
// =========================================================================
{ 24001, "internet.telia.se", "Telia SE" },
{ 24002, "tre.se", "Three SE" },
{ 24007, "internet.telenor.se", "Telenor SE" },
// =========================================================================
// Norway (MCC 242)
// =========================================================================
{ 24201, "internet.telenor.no", "Telenor NO" },
{ 24202, "internet.netcom.no", "Telia NO" },
// =========================================================================
// Denmark (MCC 238)
// =========================================================================
{ 23801, "internet", "TDC" },
{ 23802, "internet", "Telenor DK" },
{ 23806, "internet", "Three DK" },
{ 23820, "internet", "Telia DK" },
// =========================================================================
// Switzerland (MCC 228)
// =========================================================================
{ 22801, "gprs.swisscom.ch", "Swisscom" },
{ 22802, "internet", "Sunrise" },
{ 22803, "internet", "Salt" },
// =========================================================================
// Austria (MCC 232)
// =========================================================================
{ 23201, "a1.net", "A1" },
{ 23203, "web.one.at", "Three AT" },
{ 23205, "web", "T-Mobile AT" },
// =========================================================================
// Japan (MCC 440, 441)
// =========================================================================
{ 44010, "spmode.ne.jp", "NTT Docomo" },
{ 44020, "plus.4g", "SoftBank" },
{ 44051, "au.au-net.ne.jp", "KDDI au" },
// =========================================================================
// South Korea (MCC 450)
// =========================================================================
{ 45005, "lte.sktelecom.com", "SK Telecom" },
{ 45006, "lte.ktfwing.com", "KT" },
{ 45008, "lte.lguplus.co.kr", "LG U+" },
// =========================================================================
// India (MCC 404, 405)
// =========================================================================
{ 40445, "airtelgprs.com", "Airtel" },
{ 40410, "airtelgprs.com", "Airtel" },
{ 40411, "www", "Vodafone IN (Vi)" },
{ 40413, "www", "Vodafone IN (Vi)" },
{ 40486, "www", "Vodafone IN (Vi)" },
{ 40553, "jionet", "Jio" },
{ 40554, "jionet", "Jio" },
{ 40512, "bsnlnet", "BSNL" },
// =========================================================================
// Singapore (MCC 525)
// =========================================================================
{ 52501, "internet", "Singtel" },
{ 52503, "internet", "M1" },
{ 52505, "internet", "StarHub" },
// =========================================================================
// Hong Kong (MCC 454)
// =========================================================================
{ 45400, "internet", "CSL" },
{ 45406, "internet", "SmarTone" },
{ 45412, "internet", "CMHK" },
// =========================================================================
// Brazil (MCC 724)
// =========================================================================
{ 72405, "claro.com.br", "Claro BR" },
{ 72406, "wap.oi.com.br", "Vivo" },
{ 72410, "wap.oi.com.br", "Vivo" },
{ 72411, "wap.oi.com.br", "Vivo" },
{ 72415, "internet.tim.br", "TIM BR" },
{ 72431, "gprs.oi.com.br", "Oi" },
// =========================================================================
// Mexico (MCC 334)
// =========================================================================
{ 33402, "internet.itelcel.com","Telcel" },
{ 33403, "internet.movistar.mx","Movistar MX" },
{ 33404, "internet.att.net.mx", "AT&T MX" },
// =========================================================================
// South Africa (MCC 655)
// =========================================================================
{ 65501, "internet", "Vodacom" },
{ 65502, "internet", "Telkom ZA" },
{ 65507, "internet", "Cell C" },
{ 65510, "internet", "MTN ZA" },
// =========================================================================
// Philippines (MCC 515)
// =========================================================================
{ 51502, "internet.globe.com.ph","Globe" },
{ 51503, "internet", "Smart" },
{ 51505, "internet", "Sun Cellular" },
// =========================================================================
// Thailand (MCC 520)
// =========================================================================
{ 52001, "internet", "AIS" },
{ 52004, "internet", "TrueMove" },
{ 52005, "internet", "dtac" },
// =========================================================================
// Indonesia (MCC 510)
// =========================================================================
{ 51001, "internet", "Telkomsel" },
{ 51010, "internet", "Telkomsel" },
{ 51011, "3gprs", "XL Axiata" },
{ 51028, "3gprs", "XL Axiata (Axis)" },
// =========================================================================
// Malaysia (MCC 502)
// =========================================================================
{ 50212, "celcom3g", "Celcom" },
{ 50213, "celcom3g", "Celcom" },
{ 50216, "internet", "Digi" },
{ 50219, "celcom3g", "Celcom" },
// =========================================================================
// Czech Republic (MCC 230)
// =========================================================================
{ 23001, "internet.t-mobile.cz","T-Mobile CZ" },
{ 23002, "internet", "O2 CZ" },
{ 23003, "internet.vodafone.cz","Vodafone CZ" },
// =========================================================================
// Poland (MCC 260)
// =========================================================================
{ 26001, "internet", "Plus PL" },
{ 26002, "internet", "T-Mobile PL" },
{ 26003, "internet", "Orange PL" },
{ 26006, "internet", "Play" },
// =========================================================================
// Portugal (MCC 268)
// =========================================================================
{ 26801, "internet", "Vodafone PT" },
{ 26803, "internet", "NOS" },
{ 26806, "internet", "MEO" },
// =========================================================================
// Ireland (MCC 272)
// =========================================================================
{ 27201, "internet", "Vodafone IE" },
{ 27202, "open.internet", "Three IE" },
{ 27205, "three.ie", "Three IE" },
// =========================================================================
// IoT / Global SIMs
// =========================================================================
{ 901028, "iot.1nce.net", "1NCE (IoT)" },
{ 90143, "hologram", "Hologram" },
};
#define APN_DATABASE_SIZE (sizeof(APN_DATABASE) / sizeof(APN_DATABASE[0]))
// ---------------------------------------------------------------------------
// Lookup function — returns nullptr if not found
// ---------------------------------------------------------------------------
inline const ApnEntry* apnLookup(uint32_t mccmnc) {
for (int i = 0; i < (int)APN_DATABASE_SIZE; i++) {
if (APN_DATABASE[i].mccmnc == mccmnc) {
return &APN_DATABASE[i];
}
}
return nullptr;
}
// Parse IMSI string into MCC+MNC. Tries 3-digit MNC first (6-digit mccmnc),
// falls back to 2-digit MNC (5-digit mccmnc) if not found.
inline const ApnEntry* apnLookupFromIMSI(const char* imsi) {
if (!imsi || strlen(imsi) < 5) return nullptr;
// Extract MCC (always 3 digits)
uint32_t mcc = (imsi[0] - '0') * 100 + (imsi[1] - '0') * 10 + (imsi[2] - '0');
// Try 3-digit MNC first (more specific)
if (strlen(imsi) >= 6) {
uint32_t mnc3 = (imsi[3] - '0') * 100 + (imsi[4] - '0') * 10 + (imsi[5] - '0');
uint32_t mccmnc6 = mcc * 1000 + mnc3;
const ApnEntry* entry = apnLookup(mccmnc6);
if (entry) return entry;
}
// Fall back to 2-digit MNC
uint32_t mnc2 = (imsi[3] - '0') * 10 + (imsi[4] - '0');
uint32_t mccmnc5 = mcc * 100 + mnc2;
return apnLookup(mccmnc5);
}
#endif // APN_DATABASE_H
#endif // HAS_4G_MODEM
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,122 @@
#pragma once
// =============================================================================
// CardKBKeyboard — M5Stack CardKB (or compatible) I2C keyboard driver
//
// Polls 0x5F on the shared I2C bus via QWIIC connector.
// Maps CardKB special key codes to Meck key constants.
//
// Usage:
// CardKBKeyboard cardkb;
// if (cardkb.begin()) { /* detected */ }
// char key = cardkb.readKey(); // returns 0 if no key
// =============================================================================
#if defined(LilyGo_T5S3_EPaper_Pro) && defined(MECK_CARDKB)
#ifndef CARDKB_KEYBOARD_H
#define CARDKB_KEYBOARD_H
#include <Arduino.h>
#include <Wire.h>
#include "variant.h" // For I2C_SDA, I2C_SCL (bus recovery)
// I2C address (defined in variant.h, fallback here)
#ifndef CARDKB_I2C_ADDR
#define CARDKB_I2C_ADDR 0x5F
#endif
// CardKB special key codes (from M5Stack documentation)
#define CARDKB_KEY_UP 0xB5
#define CARDKB_KEY_DOWN 0xB6
#define CARDKB_KEY_LEFT 0xB4
#define CARDKB_KEY_RIGHT 0xB7
#define CARDKB_KEY_TAB 0x09
#define CARDKB_KEY_ESC 0x1B
#define CARDKB_KEY_BS 0x08
#define CARDKB_KEY_ENTER 0x0D
#define CARDKB_KEY_DEL 0x7F
#define CARDKB_KEY_FN 0x00 // Fn modifier (swallowed by CardKB internally)
class CardKBKeyboard {
public:
CardKBKeyboard() : _detected(false) {}
// Probe for CardKB on the I2C bus. Call after Wire.begin().
bool begin() {
Wire.beginTransmission(CARDKB_I2C_ADDR);
_detected = (Wire.endTransmission() == 0);
if (_detected) {
Serial.println("[CardKB] Detected at 0x5F");
}
return _detected;
}
// Re-probe (e.g. for hot-plug detection every few seconds)
bool probe() {
Wire.beginTransmission(CARDKB_I2C_ADDR);
_detected = (Wire.endTransmission() == 0);
return _detected;
}
bool isDetected() const { return _detected; }
// Poll for a keypress. Returns 0 if no key available.
// Returns raw ASCII for printable chars, or Meck KEY_* constants for nav keys.
// Throttled to avoid flooding I2C bus — polls at most every 50ms.
// On read failure, backs off 500ms and re-inits Wire to recover bus state.
char readKey() {
if (!_detected) return 0;
unsigned long now = millis();
if (now - _lastPoll < _pollInterval) return 0;
_lastPoll = now;
Wire.requestFrom((uint8_t)CARDKB_I2C_ADDR, (uint8_t)1);
if (!Wire.available()) {
_errorCount++;
if (_errorCount >= 3) {
// I2C bus may be stuck — re-init to recover
Wire.begin(I2C_SDA, I2C_SCL);
Wire.setClock(100000);
_pollInterval = 500; // Back off for 500ms
_errorCount = 0;
Serial.println("[CardKB] I2C error recovery — bus re-init");
}
return 0;
}
_errorCount = 0;
_pollInterval = 50; // Normal polling rate
uint8_t raw = Wire.read();
if (raw == 0) return 0;
// Map CardKB special keys to Meck constants
switch (raw) {
case CARDKB_KEY_UP: return 0xF2; // KEY_PREV
case CARDKB_KEY_DOWN: return 0xF1; // KEY_NEXT
case CARDKB_KEY_LEFT: return 0xF3; // KEY_LEFT
case CARDKB_KEY_RIGHT: return 0xF4; // KEY_RIGHT
case CARDKB_KEY_ENTER: return '\r';
case CARDKB_KEY_BS: return '\b';
case CARDKB_KEY_DEL: return '\b'; // Treat delete same as backspace
case CARDKB_KEY_ESC: return 0x1B; // ESC — handled by caller
case CARDKB_KEY_TAB: return 0x09; // Tab — available for future use
default:
// Printable ASCII — pass through unchanged
if (raw >= 0x20 && raw <= 0x7E) {
return (char)raw;
}
// Unknown code — ignore
return 0;
}
}
private:
bool _detected;
unsigned long _lastPoll = 0;
unsigned long _pollInterval = 50; // ms between polls (increases on error)
uint8_t _errorCount = 0;
};
#endif // CARDKB_KEYBOARD_H
#endif // LilyGo_T5S3_EPaper_Pro && MECK_CARDKB
File diff suppressed because it is too large Load Diff
+256 -52
View File
@@ -4,7 +4,11 @@
#include <helpers/ui/DisplayDriver.h>
#include <MeshCore.h>
// Forward declarations
// Timestamps before this (Jan 1 2026 UTC) are treated as invalid/unsynced
#define EPOCH_2026 1735689600UL
// Forward declarations — MyMesh.h (which defines AdvertPath) is always
// included by the translation unit before this header.
class UITask;
class MyMesh;
extern MyMesh the_mesh;
@@ -18,6 +22,7 @@ public:
FILTER_REPEATER,
FILTER_ROOM, // Room servers
FILTER_SENSOR,
FILTER_FAVOURITE, // Contacts marked as favourite (any type)
FILTER_COUNT // keep last
};
@@ -30,15 +35,24 @@ private:
// Cached filtered contact indices for efficient scrolling
// We rebuild this on filter change or when entering the screen
static const int MAX_VISIBLE = 400; // matches MAX_CONTACTS build flag
uint16_t _filteredIdx[MAX_VISIBLE]; // indices into contact table
uint32_t _filteredTs[MAX_VISIBLE]; // cached last_advert_timestamp for sorting
// Arrays allocated in PSRAM when available (supports 1000+ contacts)
uint16_t* _filteredIdx; // indices into contact table
uint32_t* _filteredTs; // cached lastmod for sorting
int _filteredCount; // how many contacts match current filter
AdvertPath _hopBuf[40]; // recently heard advert paths for hop-count display
int _hopBufCount;
bool _cacheValid;
// How many rows fit on screen (computed during render)
int _rowsPerPage;
// Pointer to per-contact DM unread array (owned by UITask, set via setter)
const uint8_t* _dmUnread = nullptr;
// --- Select mode state ---
bool _selectMode;
uint8_t* _selectedBits; // Bitfield: 1 bit per MAX_CONTACTS raw index
// --- helpers ---
static const char* filterLabel(FilterMode f) {
@@ -48,20 +62,21 @@ private:
case FILTER_REPEATER: return "Rptr";
case FILTER_ROOM: return "Room";
case FILTER_SENSOR: return "Sens";
case FILTER_FAVOURITE: return "Fav";
default: return "?";
}
}
static char typeChar(uint8_t adv_type) {
static const char* typeStr(uint8_t adv_type) {
switch (adv_type) {
case ADV_TYPE_CHAT: return 'C';
case ADV_TYPE_REPEATER: return 'R';
case ADV_TYPE_ROOM: return 'S'; // Server
default: return '?';
case ADV_TYPE_CHAT: return "C";
case ADV_TYPE_REPEATER: return "R";
case ADV_TYPE_ROOM: return "RS";
default: return "?";
}
}
bool matchesFilter(uint8_t adv_type) const {
bool matchesFilter(uint8_t adv_type, uint8_t flags = 0) const {
switch (_filter) {
case FILTER_ALL: return true;
case FILTER_CHAT: return adv_type == ADV_TYPE_CHAT;
@@ -70,6 +85,7 @@ private:
case FILTER_SENSOR: return (adv_type != ADV_TYPE_CHAT &&
adv_type != ADV_TYPE_REPEATER &&
adv_type != ADV_TYPE_ROOM);
case FILTER_FAVOURITE: return (flags & 0x01) != 0;
default: return true;
}
}
@@ -78,17 +94,18 @@ private:
_filteredCount = 0;
uint32_t numContacts = the_mesh.getNumContacts();
ContactInfo contact;
for (uint32_t i = 0; i < numContacts && _filteredCount < MAX_VISIBLE; i++) {
for (uint32_t i = 0; i < numContacts && _filteredCount < MAX_CONTACTS; i++) {
if (the_mesh.getContactByIdx(i, contact)) {
if (matchesFilter(contact.type)) {
if (matchesFilter(contact.type, contact.flags)) {
_filteredIdx[_filteredCount] = (uint16_t)i;
_filteredTs[_filteredCount] = contact.last_advert_timestamp;
// Use lastmod (our receive time) for sort/age; pre-2026 or zero → 0 sinks to bottom
_filteredTs[_filteredCount] = (contact.lastmod >= EPOCH_2026) ? contact.lastmod : 0;
_filteredCount++;
}
}
}
// Sort by last_advert_timestamp descending (most recently seen first)
// Simple insertion sort — fine for up to 400 entries on ESP32
// Sort by lastmod descending (most recently heard first; pre-2026/unsynced sink to bottom)
// Insertion sort fine for up to ~1000 entries on ESP32
for (int i = 1; i < _filteredCount; i++) {
uint16_t tmpIdx = _filteredIdx[i];
uint32_t tmpTs = _filteredTs[i];
@@ -102,38 +119,64 @@ private:
_filteredTs[j + 1] = tmpTs;
}
_cacheValid = true;
// Refresh hop-count cache from the 12 most recently heard adverts
_hopBufCount = the_mesh.getRecentlyHeard(_hopBuf, 40);
// Clamp scroll position
if (_scrollPos >= _filteredCount) {
_scrollPos = (_filteredCount > 0) ? _filteredCount - 1 : 0;
}
}
// Format seconds-ago as compact string: "3s" "5m" "2h" "4d" "??"
// Format seconds-ago as compact string: "3s" "5m" "2h" "4d" "--"
static void formatAge(char* buf, size_t bufLen, uint32_t now, uint32_t timestamp) {
if (timestamp == 0) {
if (timestamp == 0 || timestamp < EPOCH_2026 || now < timestamp) {
strncpy(buf, "--", bufLen);
return;
}
int secs = (int)(now - timestamp);
if (secs < 0) secs = 0;
uint32_t secs = now - timestamp;
if (secs < 60) {
snprintf(buf, bufLen, "%ds", secs);
snprintf(buf, bufLen, "%ds", (int)secs);
} else if (secs < 3600) {
snprintf(buf, bufLen, "%dm", secs / 60);
snprintf(buf, bufLen, "%dm", (int)(secs / 60));
} else if (secs < 86400) {
snprintf(buf, bufLen, "%dh", secs / 3600);
snprintf(buf, bufLen, "%dh", (int)(secs / 3600));
} else {
snprintf(buf, bufLen, "%dd", secs / 86400);
snprintf(buf, bufLen, "%dd", (int)(secs / 86400));
}
}
// --- Bitfield helpers ---
bool isSelectedRaw(int rawIdx) const {
if (rawIdx < 0 || rawIdx >= MAX_CONTACTS) return false;
return (_selectedBits[rawIdx / 8] & (1 << (rawIdx % 8))) != 0;
}
void setSelectedRaw(int rawIdx, bool sel) {
if (rawIdx < 0 || rawIdx >= MAX_CONTACTS) return;
if (sel) _selectedBits[rawIdx / 8] |= (1 << (rawIdx % 8));
else _selectedBits[rawIdx / 8] &= ~(1 << (rawIdx % 8));
}
public:
ContactsScreen(UITask* task, mesh::RTCClock* rtc)
: _task(task), _rtc(rtc), _scrollPos(0), _filter(FILTER_ALL),
_filteredCount(0), _cacheValid(false), _rowsPerPage(5) {}
_filteredCount(0), _cacheValid(false), _rowsPerPage(5),
_selectMode(false), _hopBufCount(0) {
#if defined(ESP32) && defined(BOARD_HAS_PSRAM)
_filteredIdx = (uint16_t*)ps_calloc(MAX_CONTACTS, sizeof(uint16_t));
_filteredTs = (uint32_t*)ps_calloc(MAX_CONTACTS, sizeof(uint32_t));
_selectedBits = (uint8_t*)ps_calloc((MAX_CONTACTS + 7) / 8, 1);
#else
_filteredIdx = new uint16_t[MAX_CONTACTS]();
_filteredTs = new uint32_t[MAX_CONTACTS]();
_selectedBits = new uint8_t[(MAX_CONTACTS + 7) / 8]();
#endif
}
void invalidateCache() { _cacheValid = false; }
// Set pointer to per-contact DM unread array (called by UITask after allocation)
void setDMUnreadPtr(const uint8_t* ptr) { _dmUnread = ptr; }
void resetScroll() {
_scrollPos = 0;
_cacheValid = false;
@@ -141,6 +184,83 @@ public:
FilterMode getFilter() const { return _filter; }
// --- Select mode API ---
bool isInSelectMode() const { return _selectMode; }
void enterSelectMode() {
_selectMode = true;
memset(_selectedBits, 0, (MAX_CONTACTS + 7) / 8);
// Pre-select the currently highlighted contact
if (_filteredCount > 0 && _scrollPos < _filteredCount) {
setSelectedRaw(_filteredIdx[_scrollPos], true);
}
}
void exitSelectMode() {
_selectMode = false;
memset(_selectedBits, 0, (MAX_CONTACTS + 7) / 8);
}
void toggleSelected() {
if (_filteredCount == 0 || _scrollPos >= _filteredCount) return;
int rawIdx = _filteredIdx[_scrollPos];
setSelectedRaw(rawIdx, !isSelectedRaw(rawIdx));
}
void selectAll() {
for (int i = 0; i < _filteredCount; i++) {
setSelectedRaw(_filteredIdx[i], true);
}
}
void deselectAll() {
memset(_selectedBits, 0, (MAX_CONTACTS + 7) / 8);
}
int getSelectedCount() const {
int count = 0;
for (int i = 0; i < _filteredCount; i++) {
if (isSelectedRaw(_filteredIdx[i])) count++;
}
return count;
}
// Fill outBuf with raw contact table indices of selected contacts
int getSelectedRawIndices(uint16_t* outBuf, int maxOut) const {
int count = 0;
for (int i = 0; i < _filteredCount && count < maxOut; i++) {
if (isSelectedRaw(_filteredIdx[i])) {
outBuf[count++] = _filteredIdx[i];
}
}
return count;
}
// Tap-to-select: given virtual Y, select contact row.
// Returns: 0=miss, 1=moved, 2=tapped current row.
int selectRowAtVY(int vy) {
if (_filteredCount == 0) return 0;
const int headerH = 14, footerH = 14, lineH = the_mesh.getNodePrefs()->smallLineH();
#if defined(LilyGo_T5S3_EPaper_Pro)
const int bodyTop = headerH;
#else
const int bodyTop = headerH + the_mesh.getNodePrefs()->smallHighlightOff();
#endif
if (vy < bodyTop || vy >= 128 - footerH) return 0;
int maxVisible = (128 - headerH - footerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_scrollPos - maxVisible / 2,
_filteredCount - maxVisible));
int tappedRow = startIdx + (vy - bodyTop) / lineH;
if (tappedRow < 0 || tappedRow >= _filteredCount) return 0;
if (tappedRow == _scrollPos) return 2;
_scrollPos = tappedRow;
return 1;
}
// Get the raw contact table index for the currently highlighted item
// Returns -1 if no valid selection
int getSelectedContactIdx() const {
@@ -177,7 +297,12 @@ public:
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setCursor(0, 0);
snprintf(tmp, sizeof(tmp), "Contacts [%s]", filterLabel(_filter));
if (_selectMode) {
int selCount = getSelectedCount();
snprintf(tmp, sizeof(tmp), "%d Selected [%s]", selCount, filterLabel(_filter));
} else {
snprintf(tmp, sizeof(tmp), "Contacts [%s]", filterLabel(_filter));
}
display.print(tmp);
// Count on right: All → total/max, filtered → matched/total
@@ -193,8 +318,8 @@ public:
display.drawRect(0, 11, display.width(), 1);
// === Body - contact rows ===
display.setTextSize(0); // tiny font for compact rows
int lineHeight = 9; // 8px font + 1px gap
display.setTextSize(the_mesh.getNodePrefs()->smallTextSize()); // tiny font for compact rows
int lineHeight = the_mesh.getNodePrefs()->smallLineH(); // 8px font + 1px gap
int headerHeight = 14;
int footerHeight = 14;
int maxY = display.height() - footerHeight;
@@ -208,7 +333,11 @@ public:
display.setCursor(0, y);
display.print("No contacts");
display.setCursor(0, y + lineHeight);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.print("Swipe to change filter");
#else
display.print("A/D: Change filter");
#endif
} else {
// Center visible window around selected item (TextReaderScreen pattern)
int maxVisible = (maxY - headerHeight) / lineHeight;
@@ -222,11 +351,16 @@ public:
if (!the_mesh.getContactByIdx(_filteredIdx[i], contact)) continue;
bool selected = (i == _scrollPos);
bool sel = _selectMode && isSelectedRaw(_filteredIdx[i]);
// Highlight: fill LIGHT rect first, then draw DARK text on top
if (selected) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y + 5, display.width(), lineHeight);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.fillRect(0, y, display.width(), lineHeight);
#else
display.fillRect(0, y + the_mesh.getNodePrefs()->smallHighlightOff(), display.width(), lineHeight);
#endif
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
@@ -235,12 +369,16 @@ public:
// Set cursor AFTER fillRect so text draws on top of highlight
display.setCursor(0, y);
// Prefix: "> " for selected, type char + space for others
char prefix[4];
if (selected) {
snprintf(prefix, sizeof(prefix), ">%c", typeChar(contact.type));
// Prefix: select mode uses * for selected, normal uses > for cursor
char prefix[5];
if (_selectMode) {
snprintf(prefix, sizeof(prefix), "%c%s",
sel ? '*' : (selected ? '>' : ' '),
typeStr(contact.type));
} else if (selected) {
snprintf(prefix, sizeof(prefix), ">%s", typeStr(contact.type));
} else {
snprintf(prefix, sizeof(prefix), " %c", typeChar(contact.type));
snprintf(prefix, sizeof(prefix), " %s", typeStr(contact.type));
}
display.print(prefix);
@@ -250,18 +388,47 @@ public:
// Reserve space for hops + age on right side
char hopStr[6];
if (contact.out_path_len == 0xFF || contact.out_path_len == 0) {
strcpy(hopStr, "D"); // direct
if (contact.out_path_len == 0xFF) {
// No confirmed direct path — look up flood hop estimate from recent advert cache
hopStr[0] = '?'; hopStr[1] = '\0'; // default
for (int h = 0; h < _hopBufCount; h++) {
if (memcmp(contact.id.pub_key, _hopBuf[h].pubkey_prefix, 7) == 0) {
uint8_t bph = (_hopBuf[h].path_len >> 6) + 1;
uint8_t hops = _hopBuf[h].path_len & 0x3F;
uint8_t max_hops = 64 / bph; // sanity cap based on path encoding
if (hops <= max_hops) {
if (hops == 0)
strcpy(hopStr, "~D");
else
snprintf(hopStr, sizeof(hopStr), "~%d", (int)hops);
}
break;
}
}
} else if (contact.out_path_len == 0) {
bool customDirect = (contact.flags & CONTACT_FLAG_CUSTOM_PATH) != 0;
strcpy(hopStr, customDirect ? "D*" : "D");
} else {
snprintf(hopStr, sizeof(hopStr), "%d", contact.out_path_len);
int hops = contact.out_path_len & 0x3F; // lower 6 bits = hop count
bool customPath = (contact.flags & CONTACT_FLAG_CUSTOM_PATH) != 0;
if (customPath) {
snprintf(hopStr, sizeof(hopStr), "%d*", hops); // asterisk = custom/locked path
} else {
snprintf(hopStr, sizeof(hopStr), "%d", hops);
}
}
char ageStr[6];
formatAge(ageStr, sizeof(ageStr), now, contact.last_advert_timestamp);
formatAge(ageStr, sizeof(ageStr), now, contact.lastmod);
// Build right-side string: "hops age"
char rightStr[14];
snprintf(rightStr, sizeof(rightStr), "%sh %s", hopStr, ageStr);
// Build right-side string: "*N hops age" if unread, else "hops age"
int dmCount = (_dmUnread && _filteredIdx[i] < MAX_CONTACTS) ? _dmUnread[_filteredIdx[i]] : 0;
char rightStr[20];
if (dmCount > 0) {
snprintf(rightStr, sizeof(rightStr), "*%d %sh %s", dmCount, hopStr, ageStr);
} else {
snprintf(rightStr, sizeof(rightStr), "%sh %s", hopStr, ageStr);
}
int rightWidth = display.getTextWidth(rightStr) + 2;
// Name region: after prefix + small gap, before right info
@@ -286,19 +453,33 @@ public:
display.drawRect(0, footerY - 2, display.width(), 1);
display.setColor(DisplayDriver::YELLOW);
// Left: Q:Back
#if defined(LilyGo_T5S3_EPaper_Pro)
display.setCursor(0, footerY);
display.print("Q:Back");
// Center: A/D:Filter
const char* mid = "A/D:Filtr";
display.setCursor((display.width() - display.getTextWidth(mid)) / 2, footerY);
display.print(mid);
// Right: W/S:Scroll
const char* right = "W/S:Scrll";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
if (_selectMode) {
display.print("Swipe:All/Clr");
const char* right = "Tap:Tog Hold:Exit";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
} else {
display.print("Swipe:Filter");
const char* right = "Hold:DM/Admin";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
}
#else
display.setCursor(0, footerY);
if (_selectMode) {
display.print("A:All D:Clr");
const char* right = "X:Exp F:Fav Q:Done";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
} else {
display.print("Q:Bk A/D:Filter");
const char* right = "P:Path Ent:Sel";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
}
#endif
return 5000; // e-ink: next render after 5s
}
@@ -320,6 +501,29 @@ public:
}
}
// --- Select mode key handling ---
if (_selectMode) {
// Enter/tap: toggle selection on current contact
if (c == 13 || c == KEY_ENTER) {
toggleSelected();
return true;
}
// A: select all in current filter
if (c == 'a' || c == 'A') {
selectAll();
return true;
}
// D: deselect all
if (c == 'd' || c == 'D') {
deselectAll();
return true;
}
// Q, X, F, Backspace — handled by main.cpp (needs mesh/SD access)
return false;
}
// --- Normal mode key handling ---
// A - previous filter
if (c == 'a' || c == 'A') {
_filter = (FilterMode)(((int)_filter + FILTER_COUNT - 1) % FILTER_COUNT);
@@ -0,0 +1,247 @@
#pragma once
#include <helpers/ui/UIScreen.h>
#include <helpers/ui/DisplayDriver.h>
#include <helpers/AdvertDataHelpers.h>
#include <MeshCore.h>
// Forward declarations
class UITask;
class MyMesh;
extern MyMesh the_mesh;
class DiscoveryScreen : public UIScreen {
UITask* _task;
mesh::RTCClock* _rtc;
int _scrollPos;
int _rowsPerPage;
static char typeChar(uint8_t adv_type) {
switch (adv_type) {
case ADV_TYPE_CHAT: return 'C';
case ADV_TYPE_REPEATER: return 'R';
case ADV_TYPE_ROOM: return 'S';
case ADV_TYPE_SENSOR: return 'N';
default: return '?';
}
}
static const char* typeLabel(uint8_t adv_type) {
switch (adv_type) {
case ADV_TYPE_CHAT: return "Chat";
case ADV_TYPE_REPEATER: return "Rptr";
case ADV_TYPE_ROOM: return "Room";
case ADV_TYPE_SENSOR: return "Sens";
default: return "?";
}
}
public:
DiscoveryScreen(UITask* task, mesh::RTCClock* rtc)
: _task(task), _rtc(rtc), _scrollPos(0), _rowsPerPage(5) {}
void resetScroll() { _scrollPos = 0; }
int getSelectedIdx() const { return _scrollPos; }
// Tap-to-select: given virtual Y, select discovered node row.
// Returns: 0=miss, 1=moved, 2=tapped current row.
int selectRowAtVY(int vy) {
int count = the_mesh.getDiscoveredCount();
if (count == 0) return 0;
const int headerH = 14, footerH = 14, lineH = the_mesh.getNodePrefs()->smallLineH();
#if defined(LilyGo_T5S3_EPaper_Pro)
const int bodyTop = headerH;
#else
const int bodyTop = headerH + the_mesh.getNodePrefs()->smallHighlightOff();
#endif
if (vy < bodyTop || vy >= 128 - footerH) return 0;
int maxVisible = (128 - headerH - footerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_scrollPos - maxVisible / 2,
count - maxVisible));
int tappedRow = startIdx + (vy - bodyTop) / lineH;
if (tappedRow < 0 || tappedRow >= count) return 0;
if (tappedRow == _scrollPos) return 2;
_scrollPos = tappedRow;
return 1;
}
int render(DisplayDriver& display) override {
int count = the_mesh.getDiscoveredCount();
bool active = the_mesh.isDiscoveryActive();
// === Header ===
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setCursor(0, 0);
char hdr[32];
if (active) {
snprintf(hdr, sizeof(hdr), "Scanning... %d found", count);
} else {
snprintf(hdr, sizeof(hdr), "Scan done: %d found", count);
}
display.print(hdr);
// Divider
display.drawRect(0, 11, display.width(), 1);
// === Body — discovered node rows ===
display.setTextSize(the_mesh.getNodePrefs()->smallTextSize()); // tiny font for compact rows
int lineHeight = the_mesh.getNodePrefs()->smallLineH();
int headerHeight = 14;
int footerHeight = 14;
int maxY = display.height() - footerHeight;
int y = headerHeight;
int rowsDrawn = 0;
if (count == 0) {
display.setColor(DisplayDriver::LIGHT);
display.setCursor(4, 28);
display.print(active ? "Listening for adverts..." : "No nodes found");
if (!active) {
display.setCursor(4, 38);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.print("Long press: Rescan");
#else
display.print("F: Scan again Q: Back");
#endif
}
} else {
// Center visible window around selected item
int maxVisible = (maxY - headerHeight) / lineHeight;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_scrollPos - maxVisible / 2,
count - maxVisible));
int endIdx = min(count, startIdx + maxVisible);
for (int i = startIdx; i < endIdx && y + lineHeight <= maxY; i++) {
const DiscoveredNode& node = the_mesh.getDiscovered(i);
bool selected = (i == _scrollPos);
// Highlight selected row
if (selected) {
display.setColor(DisplayDriver::LIGHT);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.fillRect(0, y, display.width(), lineHeight);
#else
display.fillRect(0, y + the_mesh.getNodePrefs()->smallHighlightOff(), display.width(), lineHeight);
#endif
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(0, y);
// Prefix: cursor + type
char prefix[4];
if (selected) {
snprintf(prefix, sizeof(prefix), ">%c", typeChar(node.contact.type));
} else {
snprintf(prefix, sizeof(prefix), " %c", typeChar(node.contact.type));
}
display.print(prefix);
// Build right-side info: SNR or hop count + status
char rightStr[16];
if (node.snr != 0) {
// Active discovery result — show SNR in dB (value is ×4 scaled)
int snr_db = node.snr / 4;
if (node.already_in_contacts) {
snprintf(rightStr, sizeof(rightStr), "%ddB [+]", snr_db);
} else {
snprintf(rightStr, sizeof(rightStr), "%ddB", snr_db);
}
} else {
// Pre-seeded from cache — show hop count
if (node.already_in_contacts) {
snprintf(rightStr, sizeof(rightStr), "%dh [+]", node.path_len & 63);
} else {
snprintf(rightStr, sizeof(rightStr), "%dh", node.path_len & 63);
}
}
int rightWidth = display.getTextWidth(rightStr) + 2;
// Name (truncated with ellipsis)
char filteredName[32];
display.translateUTF8ToBlocks(filteredName, node.contact.name, sizeof(filteredName));
int nameX = display.getTextWidth(prefix) + 2;
int nameMaxW = display.width() - nameX - rightWidth - 2;
display.drawTextEllipsized(nameX, y, nameMaxW, filteredName);
// Right-aligned info
display.setCursor(display.width() - rightWidth, y);
display.print(rightStr);
y += lineHeight;
rowsDrawn++;
}
_rowsPerPage = (rowsDrawn > 0) ? rowsDrawn : 1;
}
display.setTextSize(1); // restore for footer
// === Footer ===
int footerY = display.height() - 12;
display.drawRect(0, footerY - 2, display.width(), 1);
display.setColor(DisplayDriver::YELLOW);
display.setCursor(0, footerY);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.print("Swipe:Scroll");
const char* mid = "Tap:Add";
display.setCursor((display.width() - display.getTextWidth(mid)) / 2, footerY);
display.print(mid);
const char* right = "Hold:Rescan";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#else
display.print("Q:Bk F:Rescan");
const char* right = "Tap/Ent:Add";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#endif
// Faster refresh while actively scanning
return active ? 1000 : 5000;
}
bool handleInput(char c) override {
int count = the_mesh.getDiscoveredCount();
// W - scroll up
if (c == 'w' || c == 'W' || c == 0xF2) {
if (_scrollPos > 0) {
_scrollPos--;
return true;
}
}
// S - scroll down
if (c == 's' || c == 'S' || c == 0xF1) {
if (_scrollPos < count - 1) {
_scrollPos++;
return true;
}
}
// F - rescan (handled here as well as in main.cpp for consistency)
if (c == 'f') {
the_mesh.startDiscovery();
_scrollPos = 0;
return true;
}
// Enter - handled by main.cpp for alert feedback
return false; // Q/back and Enter handled by main.cpp
}
};
+376 -56
View File
@@ -3,7 +3,7 @@
// Emoji sprites for e-ink display - dual size
// Large (12x12) for compose/picker, Small (10x10) for channel view
// MSB-first, 2 bytes per row
// 46 total emoji: joy/thumbsup/frown first, then 43 original (telephone removed)
// 76 total emoji: joy/thumbsup/frown first, then 43 original, then 19 new, then 11 newest
#include <stdint.h>
#ifdef ESP32
@@ -15,11 +15,11 @@
#define EMOJI_SM_W 10
#define EMOJI_SM_H 10
#define EMOJI_COUNT 46
#define EMOJI_COUNT 76
// Escape codes in 0x80+ range - safe from keyboard ASCII (32-126)
#define EMOJI_ESCAPE_START 0x80
#define EMOJI_ESCAPE_END 0xAD // 0x80 + 45
#define EMOJI_ESCAPE_END 0xCB // 0x80 + 75
#define EMOJI_PAD_BYTE 0x7F // DEL, not typeable (key < 127 guard)
// ======== LARGE 12x12 SPRITES ========
@@ -36,6 +36,14 @@ static const uint8_t emoji_lg_thumbsup[] PROGMEM = {
static const uint8_t emoji_lg_frown[] PROGMEM = {
0x1F,0x80, 0x20,0x40, 0x59,0xA0, 0x59,0xA0, 0x80,0x10, 0x9F,0x90, 0xA0,0x50, 0x40,0x20, 0x20,0x40, 0x1F,0x80, 0x00,0x00, 0x00,0x00,
};
// [65] loudly_crying 😭
static const uint8_t emoji_lg_loudly_crying[] PROGMEM = {
0x1F,0x80, 0x20,0x40, 0x5B,0x40, 0x5B,0x20, 0x80,0x10, 0x9F,0x10, 0xA0,0x90, 0x60,0xC0, 0xA0,0xA0, 0x1F,0x00, 0x40,0x40, 0x00,0x00,
};
// [66] heart ♥️
static const uint8_t emoji_lg_heart[] PROGMEM = {
0x00,0x00, 0x73,0x80, 0xFF,0xC0, 0xFF,0xC0, 0xFF,0xC0, 0x7F,0x80, 0x3F,0x00, 0x1E,0x00, 0x0C,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00,
};
// [3] wireless
static const uint8_t emoji_lg_wireless[] PROGMEM = {
0x00,0x00, 0x3F,0xC0, 0x60,0x60, 0xC0,0x30, 0x0F,0x00, 0x19,0x80, 0x30,0xC0, 0x00,0x00, 0x06,0x00, 0x0F,0x00, 0x06,0x00, 0x00,0x00,
@@ -208,18 +216,144 @@ static const uint8_t emoji_lg_peach[] PROGMEM = {
static const uint8_t emoji_lg_racing_car[] PROGMEM = {
0x00,0x00, 0x00,0x00, 0x00,0x00, 0x07,0x80, 0x0F,0xC0, 0x7F,0xE0, 0xFF,0xF0, 0xFF,0xF0, 0x6F,0x60, 0x49,0x20, 0x00,0x00, 0x00,0x00,
};
// [46] mouse 🐭
static const uint8_t emoji_lg_mouse[] PROGMEM = {
0x30,0xC0, 0x79,0xE0, 0x79,0xE0, 0x3F,0xC0, 0x49,0x20, 0x80,0x10, 0x86,0x10, 0x89,0x10, 0x40,0x20, 0x20,0x40, 0x1F,0x80, 0x00,0x00,
};
// [47] mushroom 🍄
static const uint8_t emoji_lg_mushroom[] PROGMEM = {
0x1F,0x80, 0x3F,0xC0, 0x7F,0xE0, 0xE6,0x70, 0xE6,0x70, 0x7F,0xE0, 0x3F,0xC0, 0x0F,0x00, 0x0F,0x00, 0x0F,0x00, 0x1F,0x80, 0x00,0x00,
};
// [48] biohazard ☣️
static const uint8_t emoji_lg_biohazard[] PROGMEM = {
0x0F,0x00, 0x1F,0x80, 0x3F,0xC0, 0x1F,0x80, 0x0F,0x00, 0x66,0x60, 0x76,0xE0, 0x70,0xE0, 0x79,0xE0, 0x39,0xC0, 0x19,0x80, 0x00,0x00,
};
// [49] panda 🐼
static const uint8_t emoji_lg_panda[] PROGMEM = {
0x00,0x00, 0x60,0x60, 0xF0,0xF0, 0xF0,0xF0, 0x7F,0xE0, 0x59,0xA0, 0x59,0xA0, 0x40,0x20, 0x46,0x20, 0x20,0x40, 0x1F,0x80, 0x00,0x00,
};
// [50] anger 💢
static const uint8_t emoji_lg_anger[] PROGMEM = {
0x00,0x00, 0x3C,0xC0, 0x3C,0xC0, 0x30,0xC0, 0x30,0x00, 0x00,0x00, 0x00,0x00, 0x00,0xC0, 0x30,0xC0, 0x33,0xC0, 0x33,0xC0, 0x00,0x00,
};
// [51] dragon_face 🐲
static const uint8_t emoji_lg_dragon_face[] PROGMEM = {
0xC0,0x30, 0xE0,0x70, 0x76,0xE0, 0x3F,0xC0, 0x69,0x60, 0x40,0x20, 0x4F,0x20, 0x29,0x40, 0x30,0xC0, 0x1F,0x80, 0x00,0x00, 0x00,0x00,
};
// [52] pager 📟
static const uint8_t emoji_lg_pager[] PROGMEM = {
0x00,0x00, 0x7F,0xE0, 0x40,0x20, 0x5F,0xA0, 0x5F,0xA0, 0x40,0x20, 0x5B,0x20, 0x5B,0x20, 0x40,0x20, 0x7F,0xE0, 0x00,0x00, 0x00,0x00,
};
// [53] bee 🐝
static const uint8_t emoji_lg_bee[] PROGMEM = {
0x00,0x00, 0x19,0x80, 0x19,0x80, 0x3F,0x80, 0x7F,0xC0, 0x7F,0xE0, 0x7F,0xE0, 0x7F,0xC0, 0x3F,0x80, 0x1F,0x40, 0x0A,0x00, 0x00,0x00,
};
// [54] bulb 💡
static const uint8_t emoji_lg_bulb[] PROGMEM = {
0x1F,0x80, 0x20,0x40, 0x40,0x20, 0x40,0x20, 0x40,0x20, 0x20,0x40, 0x30,0xC0, 0x1F,0x80, 0x16,0x80, 0x1F,0x80, 0x0F,0x00, 0x00,0x00,
};
// [55] cat 🐱
static const uint8_t emoji_lg_cat[] PROGMEM = {
0x40,0x20, 0x60,0x60, 0x70,0xE0, 0x3F,0xC0, 0x59,0xA0, 0x40,0x20, 0x40,0x20, 0x46,0x20, 0x29,0x40, 0x30,0xC0, 0x1F,0x80, 0x00,0x00,
};
// [56] fleur ⚜️
static const uint8_t emoji_lg_fleur[] PROGMEM = {
0x06,0x00, 0x06,0x00, 0x0F,0x00, 0x6F,0x60, 0xF6,0xF0, 0xF6,0xF0, 0x76,0xE0, 0x3F,0xC0, 0x1F,0x80, 0x0F,0x00, 0x19,0x80, 0x00,0x00,
};
// [57] moon 🌔
static const uint8_t emoji_lg_moon[] PROGMEM = {
0x1F,0x80, 0x3F,0xC0, 0x7F,0xE0, 0x7F,0x80, 0xFF,0x80, 0xFF,0x00, 0xFF,0x00, 0xFF,0x80, 0x7F,0x80, 0x7F,0xE0, 0x3F,0xC0, 0x1F,0x80,
};
// [58] coffee ☕
static const uint8_t emoji_lg_coffee[] PROGMEM = {
0x24,0x80, 0x12,0x40, 0x00,0x00, 0x7F,0xC0, 0x40,0x70, 0x40,0x50, 0x40,0x50, 0x40,0x70, 0x7F,0xC0, 0x00,0x00, 0xFF,0xC0, 0x00,0x00,
};
// [59] tooth 🦷
static const uint8_t emoji_lg_tooth[] PROGMEM = {
0x3F,0xC0, 0x7F,0xE0, 0xFF,0xF0, 0xFF,0xF0, 0xFF,0xF0, 0x7F,0xE0, 0x3F,0xC0, 0x3F,0xC0, 0x39,0xC0, 0x39,0xC0, 0x30,0xC0, 0x20,0x40,
};
// [60] pretzel 🥨
static const uint8_t emoji_lg_pretzel[] PROGMEM = {
0x39,0xC0, 0x46,0x20, 0x80,0x20, 0x86,0x10, 0x49,0x20, 0x30,0xC0, 0x30,0xC0, 0x49,0x20, 0x86,0x10, 0x80,0x10, 0x46,0x20, 0x39,0xC0,
};
// [61] abacus 🧮
static const uint8_t emoji_lg_abacus[] PROGMEM = {
0xFF,0xF0, 0x80,0x10, 0xB6,0x50, 0x80,0x10, 0xA6,0x90, 0x80,0x10, 0x94,0xD0, 0x80,0x10, 0xB2,0x50, 0x80,0x10, 0xFF,0xF0, 0x00,0x00,
};
// [62] moai 🗿
static const uint8_t emoji_lg_moai[] PROGMEM = {
0x3F,0xC0, 0x7F,0xC0, 0x7F,0xC0, 0x39,0xC0, 0x39,0xC0, 0x3F,0xC0, 0x27,0x40, 0x3F,0x80, 0x2F,0x00, 0x3F,0x00, 0x3F,0x00, 0x1E,0x00,
};
// [63] tipping 💁
static const uint8_t emoji_lg_tipping[] PROGMEM = {
0x1E,0x00, 0x3F,0x00, 0x3F,0x00, 0x1E,0x00, 0x0C,0x00, 0x1E,0x00, 0x3F,0x00, 0x7F,0x80, 0x0C,0xE0, 0x0D,0xE0, 0x12,0xE0, 0x33,0x00,
};
// [64] hedgehog 🦔
static const uint8_t emoji_lg_hedgehog[] PROGMEM = {
0x00,0x00, 0x0A,0x80, 0x15,0x40, 0x2A,0xA0, 0x55,0x60, 0x7E,0xF0, 0xDB,0x90, 0xFF,0xD0, 0x7F,0xE0, 0x3F,0xC0, 0x24,0x80, 0x00,0x00,
};
// [67] diamond_suit ♦️
static const uint8_t emoji_lg_diamond_suit[] PROGMEM = {
0x00,0x00, 0x04,0x00, 0x0E,0x00, 0x1F,0x00, 0x3F,0x80, 0x7F,0xC0, 0x3F,0x80, 0x1F,0x00, 0x0E,0x00, 0x04,0x00, 0x00,0x00, 0x00,0x00,
};
// [68] spade_suit ♠️
static const uint8_t emoji_lg_spade_suit[] PROGMEM = {
0x04,0x00, 0x0E,0x00, 0x1F,0x00, 0x3F,0x80, 0x7F,0xC0, 0xFF,0xE0, 0xFF,0xE0, 0x7F,0xC0, 0x15,0x00, 0x04,0x00, 0x0E,0x00, 0x00,0x00,
};
// [69] pizza 🍕
static const uint8_t emoji_lg_pizza[] PROGMEM = {
0x02,0x00, 0x06,0x00, 0x0F,0x00, 0x0B,0x00, 0x1F,0x80, 0x1D,0x80, 0x3F,0xC0, 0x2F,0x40, 0x7F,0xE0, 0x7F,0xE0, 0xFF,0xF0, 0x00,0x00,
};
// [70] four_leaf_clover 🍀
static const uint8_t emoji_lg_four_leaf_clover[] PROGMEM = {
0x0C,0x00, 0x1E,0x00, 0x1E,0x00, 0x6D,0x80, 0xF3,0xC0, 0xF3,0xC0, 0x6D,0x80, 0x1E,0x00, 0x1E,0x00, 0x0C,0x00, 0x06,0x00, 0x00,0x00,
};
// [71] cloud ☁️
static const uint8_t emoji_lg_cloud[] PROGMEM = {
0x00,0x00, 0x1C,0x00, 0x3E,0x00, 0x7F,0x80, 0xFF,0xC0, 0xFF,0xE0, 0xFF,0xE0, 0x7F,0xC0, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00,
};
// [72] rocket 🚀
static const uint8_t emoji_lg_rocket[] PROGMEM = {
0x04,0x00, 0x0E,0x00, 0x1F,0x00, 0x1B,0x00, 0x1B,0x00, 0x3F,0x80, 0x7F,0xC0, 0x5F,0x40, 0x9F,0x20, 0x0E,0x00, 0x15,0x00, 0x00,0x00,
};
// [73] passport_control 🛂
static const uint8_t emoji_lg_passport_control[] PROGMEM = {
0x3F,0xC0, 0x40,0x20, 0x46,0x20, 0x4F,0x20, 0x46,0x20, 0x40,0x20, 0x44,0x20, 0x4E,0x20, 0x5F,0x20, 0x40,0x20, 0x3F,0xC0, 0x00,0x00,
};
// [74] eight_spoked_asterisk ✳️
static const uint8_t emoji_lg_eight_spoked_asterisk[] PROGMEM = {
0x7F,0xE0, 0x84,0x10, 0xA4,0x90, 0x95,0x10, 0x8E,0x10, 0xFF,0xD0, 0x8E,0x10, 0x95,0x10, 0xA4,0x90, 0x84,0x10, 0x7F,0xE0, 0x00,0x00,
};
// [75] signal_strength 📶
static const uint8_t emoji_lg_signal_strength[] PROGMEM = {
0x00,0x20, 0x00,0x20, 0x00,0xA0, 0x00,0xA0, 0x02,0xA0, 0x02,0xA0, 0x0A,0xA0, 0x0A,0xA0, 0x2A,0xA0, 0x2A,0xA0, 0xAA,0xA0, 0xAA,0xA0,
};
static const uint8_t* const EMOJI_SPRITES_LG[] PROGMEM = {
emoji_lg_joy, emoji_lg_thumbsup, emoji_lg_frown,
// Faces/emotion first
emoji_lg_joy, emoji_lg_frown, emoji_lg_loudly_crying,
emoji_lg_grimace, emoji_lg_zany_face, emoji_lg_cowboy,
// Thumbsup + heart
emoji_lg_thumbsup, emoji_lg_heart,
// Everything else in original relative order
emoji_lg_wireless, emoji_lg_infinity, emoji_lg_trex, emoji_lg_skull, emoji_lg_cross,
emoji_lg_lightning, emoji_lg_tophat, emoji_lg_motorcycle, emoji_lg_seedling, emoji_lg_flag_au,
emoji_lg_umbrella, emoji_lg_nazar, emoji_lg_globe, emoji_lg_radioactive, emoji_lg_cow,
emoji_lg_alien, emoji_lg_invader, emoji_lg_dagger, emoji_lg_grimace,
emoji_lg_alien, emoji_lg_invader, emoji_lg_dagger,
emoji_lg_mountain, emoji_lg_end_arrow, emoji_lg_hollow_circle, emoji_lg_dragon, emoji_lg_globe_meridians,
emoji_lg_eggplant, emoji_lg_shield, emoji_lg_goggles, emoji_lg_lizard, emoji_lg_zany_face,
emoji_lg_eggplant, emoji_lg_shield, emoji_lg_goggles, emoji_lg_lizard,
emoji_lg_kangaroo, emoji_lg_feather, emoji_lg_bright, emoji_lg_part_alt, emoji_lg_motorboat,
emoji_lg_domino, emoji_lg_satellite, emoji_lg_customs, emoji_lg_cowboy, emoji_lg_wheel,
emoji_lg_domino, emoji_lg_satellite, emoji_lg_customs, emoji_lg_wheel,
emoji_lg_koala, emoji_lg_control_knobs, emoji_lg_peach, emoji_lg_racing_car,
emoji_lg_mouse, emoji_lg_mushroom, emoji_lg_biohazard, emoji_lg_panda,
emoji_lg_anger, emoji_lg_dragon_face, emoji_lg_pager, emoji_lg_bee,
emoji_lg_bulb, emoji_lg_cat, emoji_lg_fleur, emoji_lg_moon,
emoji_lg_coffee, emoji_lg_tooth, emoji_lg_pretzel, emoji_lg_abacus,
emoji_lg_moai, emoji_lg_tipping, emoji_lg_hedgehog,
emoji_lg_diamond_suit, emoji_lg_spade_suit, emoji_lg_pizza, emoji_lg_four_leaf_clover,
emoji_lg_cloud, emoji_lg_rocket, emoji_lg_passport_control,
emoji_lg_eight_spoked_asterisk, emoji_lg_signal_strength,
};
// ======== SMALL 10x10 SPRITES ========
@@ -362,74 +496,248 @@ static const uint8_t emoji_sm_peach[] PROGMEM = {
static const uint8_t emoji_sm_racing_car[] PROGMEM = {
0x00,0x00, 0x00,0x00, 0x0E,0x00, 0x1F,0x00, 0x7F,0x80, 0xFF,0xC0, 0xFF,0xC0, 0x5E,0x80, 0x00,0x00, 0x00,0x00,
};
// [46] mouse 🐭
static const uint8_t emoji_sm_mouse[] PROGMEM = {
0x61,0x80, 0xF3,0xC0, 0x7F,0x80, 0x92,0x40, 0x80,0x40, 0x8C,0x40, 0x52,0x80, 0x40,0x80, 0x3F,0x00, 0x00,0x00,
};
// [47] mushroom 🍄
static const uint8_t emoji_sm_mushroom[] PROGMEM = {
0x3F,0x00, 0x7F,0x80, 0xED,0xC0, 0xED,0xC0, 0x7F,0x80, 0x3F,0x00, 0x1E,0x00, 0x1E,0x00, 0x3F,0x00, 0x00,0x00,
};
// [48] biohazard ☣️
static const uint8_t emoji_sm_biohazard[] PROGMEM = {
0x1E,0x00, 0x3F,0x00, 0x3F,0x00, 0x1E,0x00, 0x6D,0x80, 0x73,0x80, 0x73,0x80, 0x7B,0x80, 0x33,0x00, 0x00,0x00,
};
// [49] panda 🐼
static const uint8_t emoji_sm_panda[] PROGMEM = {
0xC0,0xC0, 0xF3,0xC0, 0x7F,0x80, 0xB3,0x40, 0xB3,0x40, 0x80,0x40, 0x4C,0x80, 0x21,0x00, 0x3F,0x00, 0x00,0x00,
};
// [50] anger 💢
static const uint8_t emoji_sm_anger[] PROGMEM = {
0x00,0x00, 0x73,0x00, 0x73,0x00, 0x63,0x00, 0x60,0x00, 0x01,0x80, 0x63,0x00, 0x67,0x00, 0x67,0x00, 0x00,0x00,
};
// [51] dragon_face 🐲
static const uint8_t emoji_sm_dragon_face[] PROGMEM = {
0xC0,0xC0, 0xED,0xC0, 0x7F,0x80, 0x52,0x80, 0x40,0x80, 0x4C,0x80, 0x33,0x00, 0x2D,0x00, 0x1E,0x00, 0x00,0x00,
};
// [52] pager 📟
static const uint8_t emoji_sm_pager[] PROGMEM = {
0x00,0x00, 0x7F,0x80, 0x40,0x80, 0x5E,0x80, 0x40,0x80, 0x5A,0x80, 0x5A,0x80, 0x40,0x80, 0x7F,0x80, 0x00,0x00,
};
// [53] bee 🐝
static const uint8_t emoji_sm_bee[] PROGMEM = {
0x33,0x00, 0x33,0x00, 0x7F,0x00, 0xFF,0x80, 0xFF,0xC0, 0xFF,0x80, 0x7F,0x00, 0x3E,0x80, 0x14,0x00, 0x00,0x00,
};
// [54] bulb 💡
static const uint8_t emoji_sm_bulb[] PROGMEM = {
0x3F,0x00, 0x40,0x80, 0x80,0x40, 0x80,0x40, 0x40,0x80, 0x33,0x00, 0x3F,0x00, 0x1E,0x00, 0x1E,0x00, 0x00,0x00,
};
// [55] cat 🐱
static const uint8_t emoji_sm_cat[] PROGMEM = {
0x80,0x40, 0xC0,0xC0, 0x7F,0x80, 0xB3,0x40, 0x80,0x40, 0x8C,0x40, 0x52,0x80, 0x61,0x80, 0x3F,0x00, 0x00,0x00,
};
// [56] fleur ⚜️
static const uint8_t emoji_sm_fleur[] PROGMEM = {
0x0C,0x00, 0x0C,0x00, 0x6D,0x80, 0xED,0xC0, 0xED,0xC0, 0x6D,0x80, 0x3F,0x00, 0x1E,0x00, 0x33,0x00, 0x00,0x00,
};
// [57] moon 🌔
static const uint8_t emoji_sm_moon[] PROGMEM = {
0x3F,0x00, 0x7F,0x80, 0xFF,0x80, 0xFE,0x00, 0xFE,0x00, 0xFE,0x00, 0xFE,0x00, 0xFF,0x80, 0x7F,0x80, 0x3F,0x00,
};
// [58] coffee ☕
static const uint8_t emoji_sm_coffee[] PROGMEM = {
0x49,0x00, 0x24,0x80, 0x00,0x00, 0xFF,0x00, 0x81,0xC0, 0x81,0x40, 0x81,0xC0, 0xFF,0x00, 0x00,0x00, 0xFE,0x00,
};
// [59] tooth 🦷
static const uint8_t emoji_sm_tooth[] PROGMEM = {
0x7F,0x80, 0xFF,0xC0, 0xFF,0xC0, 0xFF,0xC0, 0x7F,0x80, 0x3F,0x00, 0x3B,0x80, 0x31,0x80, 0x20,0x80, 0x00,0x00,
};
// [60] pretzel 🥨
static const uint8_t emoji_sm_pretzel[] PROGMEM = {
0x73,0x80, 0x9E,0x40, 0x8C,0x40, 0x52,0x80, 0x33,0x00, 0x33,0x00, 0x52,0x80, 0x8C,0x40, 0x9E,0x40, 0x73,0x80,
};
// [61] abacus 🧮
static const uint8_t emoji_sm_abacus[] PROGMEM = {
0xFF,0xC0, 0x80,0x40, 0xB5,0x40, 0x80,0x40, 0xAD,0x40, 0x80,0x40, 0xAB,0x40, 0x80,0x40, 0xFF,0xC0, 0x00,0x00,
};
// [62] moai 🗿
static const uint8_t emoji_sm_moai[] PROGMEM = {
0x7F,0x00, 0x7F,0x00, 0x33,0x00, 0x33,0x00, 0x3F,0x00, 0x2E,0x00, 0x3E,0x00, 0x3E,0x00, 0x3E,0x00, 0x1C,0x00,
};
// [63] tipping 💁
static const uint8_t emoji_sm_tipping[] PROGMEM = {
0x3C,0x00, 0x7E,0x00, 0x7E,0x00, 0x3C,0x00, 0x18,0x00, 0x3C,0x00, 0x7E,0x00, 0x1B,0x80, 0x1B,0x80, 0x36,0x00,
};
// [64] hedgehog 🦔
static const uint8_t emoji_sm_hedgehog[] PROGMEM = {
0x15,0x00, 0x2A,0x80, 0x55,0x40, 0xFF,0xC0, 0xDB,0x40, 0xFF,0x80, 0x7F,0x80, 0x3F,0x00, 0x24,0x00, 0x00,0x00,
};
// [65] loudly_crying 😭
static const uint8_t emoji_sm_loudly_crying[] PROGMEM = {
0x3E,0x00, 0x41,0x00, 0xB6,0x80, 0x80,0x40, 0xBE,0x40, 0x81,0x40, 0x63,0x00, 0x9C,0x80, 0x00,0x00, 0x00,0x00,
};
// [66] heart ♥️
static const uint8_t emoji_sm_heart[] PROGMEM = {
0x00,0x00, 0x6C,0x00, 0xFE,0x00, 0xFE,0x00, 0x7C,0x00, 0x38,0x00, 0x10,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00,
};
// [67] diamond_suit ♦️
static const uint8_t emoji_sm_diamond_suit[] PROGMEM = {
0x00,0x00, 0x08,0x00, 0x1C,0x00, 0x3E,0x00, 0x7F,0x00, 0x3E,0x00, 0x1C,0x00, 0x08,0x00, 0x00,0x00, 0x00,0x00,
};
// [68] spade_suit ♠️
static const uint8_t emoji_sm_spade_suit[] PROGMEM = {
0x08,0x00, 0x1C,0x00, 0x3E,0x00, 0x7F,0x00, 0xFF,0x80, 0xFF,0x80, 0x2A,0x00, 0x08,0x00, 0x1C,0x00, 0x00,0x00,
};
// [69] pizza 🍕
static const uint8_t emoji_sm_pizza[] PROGMEM = {
0x08,0x00, 0x1C,0x00, 0x14,0x00, 0x3E,0x00, 0x36,0x00, 0x6D,0x00, 0x7F,0x00, 0xFF,0x80, 0xFF,0x80, 0x00,0x00,
};
// [70] four_leaf_clover 🍀
static const uint8_t emoji_sm_four_leaf_clover[] PROGMEM = {
0x18,0x00, 0x3C,0x00, 0xDB,0x00, 0xE7,0x00, 0xE7,0x00, 0xDB,0x00, 0x3C,0x00, 0x18,0x00, 0x0C,0x00, 0x00,0x00,
};
// [71] cloud ☁️
static const uint8_t emoji_sm_cloud[] PROGMEM = {
0x00,0x00, 0x38,0x00, 0x7E,0x00, 0xFF,0x00, 0xFF,0x80, 0xFF,0x80, 0x7F,0x00, 0x00,0x00, 0x00,0x00, 0x00,0x00,
};
// [72] rocket 🚀
static const uint8_t emoji_sm_rocket[] PROGMEM = {
0x08,0x00, 0x1C,0x00, 0x36,0x00, 0x36,0x00, 0x7F,0x00, 0xBE,0x80, 0x3E,0x00, 0x1C,0x00, 0x2A,0x00, 0x00,0x00,
};
// [73] passport_control 🛂
static const uint8_t emoji_sm_passport_control[] PROGMEM = {
0x7F,0x80, 0x80,0x40, 0x8C,0x40, 0x9E,0x40, 0x8C,0x40, 0x80,0x40, 0x9C,0x40, 0xBE,0x40, 0x80,0x40, 0x7F,0x80,
};
// [74] eight_spoked_asterisk ✳️
static const uint8_t emoji_sm_eight_spoked_asterisk[] PROGMEM = {
0x7F,0x80, 0x84,0x40, 0xA5,0x40, 0x9E,0x40, 0xFF,0xC0, 0x9E,0x40, 0xA5,0x40, 0x84,0x40, 0x7F,0x80, 0x00,0x00,
};
// [75] signal_strength 📶
static const uint8_t emoji_sm_signal_strength[] PROGMEM = {
0x00,0x80, 0x00,0x80, 0x02,0x80, 0x02,0x80, 0x0A,0x80, 0x0A,0x80, 0x2A,0x80, 0x2A,0x80, 0xAA,0x80, 0xAA,0x80,
};
static const uint8_t* const EMOJI_SPRITES_SM[] PROGMEM = {
emoji_sm_joy, emoji_sm_thumbsup, emoji_sm_frown,
// Faces/emotion first
emoji_sm_joy, emoji_sm_frown, emoji_sm_loudly_crying,
emoji_sm_grimace, emoji_sm_zany_face, emoji_sm_cowboy,
// Thumbsup + heart
emoji_sm_thumbsup, emoji_sm_heart,
// Everything else in original relative order
emoji_sm_wireless, emoji_sm_infinity, emoji_sm_trex, emoji_sm_skull, emoji_sm_cross,
emoji_sm_lightning, emoji_sm_tophat, emoji_sm_motorcycle, emoji_sm_seedling, emoji_sm_flag_au,
emoji_sm_umbrella, emoji_sm_nazar, emoji_sm_globe, emoji_sm_radioactive, emoji_sm_cow,
emoji_sm_alien, emoji_sm_invader, emoji_sm_dagger, emoji_sm_grimace,
emoji_sm_alien, emoji_sm_invader, emoji_sm_dagger,
emoji_sm_mountain, emoji_sm_end_arrow, emoji_sm_hollow_circle, emoji_sm_dragon, emoji_sm_globe_meridians,
emoji_sm_eggplant, emoji_sm_shield, emoji_sm_goggles, emoji_sm_lizard, emoji_sm_zany_face,
emoji_sm_eggplant, emoji_sm_shield, emoji_sm_goggles, emoji_sm_lizard,
emoji_sm_kangaroo, emoji_sm_feather, emoji_sm_bright, emoji_sm_part_alt, emoji_sm_motorboat,
emoji_sm_domino, emoji_sm_satellite, emoji_sm_customs, emoji_sm_cowboy, emoji_sm_wheel,
emoji_sm_domino, emoji_sm_satellite, emoji_sm_customs, emoji_sm_wheel,
emoji_sm_koala, emoji_sm_control_knobs, emoji_sm_peach, emoji_sm_racing_car,
emoji_sm_mouse, emoji_sm_mushroom, emoji_sm_biohazard, emoji_sm_panda,
emoji_sm_anger, emoji_sm_dragon_face, emoji_sm_pager, emoji_sm_bee,
emoji_sm_bulb, emoji_sm_cat, emoji_sm_fleur, emoji_sm_moon,
emoji_sm_coffee, emoji_sm_tooth, emoji_sm_pretzel, emoji_sm_abacus,
emoji_sm_moai, emoji_sm_tipping, emoji_sm_hedgehog,
emoji_sm_diamond_suit, emoji_sm_spade_suit, emoji_sm_pizza, emoji_sm_four_leaf_clover,
emoji_sm_cloud, emoji_sm_rocket, emoji_sm_passport_control,
emoji_sm_eight_spoked_asterisk, emoji_sm_signal_strength,
};
// ---- Codepoint lookup for UTF-8 conversion ----
struct EmojiCodepoint { uint32_t cp; uint32_t cp2; uint8_t escape; };
static const EmojiCodepoint EMOJI_CODEPOINTS[EMOJI_COUNT] = {
// Faces/emotion first
{ 0x1F602, 0x0000, 0x80 }, // joy
{ 0x1F44D, 0x0000, 0x81 }, // thumbsup
{ 0x2639, 0x0000, 0x82 }, // frown
{ 0x1F6DC, 0x0000, 0x83 }, // wireless
{ 0x267E, 0x0000, 0x84 }, // infinity
{ 0x1F996, 0x0000, 0x85 }, // trex
{ 0x2620, 0x0000, 0x86 }, // skull
{ 0x271D, 0x0000, 0x87 }, // cross
{ 0x26A1, 0x0000, 0x88 }, // lightning
{ 0x1F3A9, 0x0000, 0x89 }, // tophat
{ 0x1F3CD, 0x0000, 0x8A }, // motorcycle
{ 0x1F331, 0x0000, 0x8B }, // seedling
{ 0x1F1E6, 0x1F1FA, 0x8C }, // flag_au
{ 0x2602, 0x0000, 0x8D }, // umbrella
{ 0x1F9FF, 0x0000, 0x8E }, // nazar
{ 0x1F30F, 0x0000, 0x8F }, // globe
{ 0x2622, 0x0000, 0x90 }, // radioactive
{ 0x1F404, 0x0000, 0x91 }, // cow
{ 0x1F47D, 0x0000, 0x92 }, // alien
{ 0x1F47E, 0x0000, 0x93 }, // invader
{ 0x1F5E1, 0x0000, 0x94 }, // dagger
{ 0x1F62C, 0x0000, 0x95 }, // grimace
{ 0x26F0, 0x0000, 0x96 }, // mountain
{ 0x1F51A, 0x0000, 0x97 }, // end_arrow
{ 0x2B55, 0x0000, 0x98 }, // hollow_circle
{ 0x1F409, 0x0000, 0x99 }, // dragon
{ 0x1F310, 0x0000, 0x9A }, // globe_meridians
{ 0x1F346, 0x0000, 0x9B }, // eggplant
{ 0x1F6E1, 0x0000, 0x9C }, // shield
{ 0x1F97D, 0x0000, 0x9D }, // goggles
{ 0x1F98E, 0x0000, 0x9E }, // lizard
{ 0x1F92A, 0x0000, 0x9F }, // zany_face
{ 0x1F998, 0x0000, 0xA0 }, // kangaroo
{ 0x1FAB6, 0x0000, 0xA1 }, // feather
{ 0x1F506, 0x0000, 0xA2 }, // bright
{ 0x303D, 0x0000, 0xA3 }, // part_alt
{ 0x1F6E5, 0x0000, 0xA4 }, // motorboat
{ 0x1F030, 0x0000, 0xA5 }, // domino
{ 0x1F4E1, 0x0000, 0xA6 }, // satellite
{ 0x1F6C3, 0x0000, 0xA7 }, // customs
{ 0x1F920, 0x0000, 0xA8 }, // cowboy
{ 0x1F6DE, 0x0000, 0xA9 }, // wheel
{ 0x1F428, 0x0000, 0xAA }, // koala
{ 0x1F39B, 0x0000, 0xAB }, // control_knobs
{ 0x1F351, 0x0000, 0xAC }, // peach
{ 0x1F3CE, 0x0000, 0xAD }, // racing_car
{ 0x2639, 0x0000, 0x81 }, // frown
{ 0x1F62D, 0x0000, 0x82 }, // loudly_crying
{ 0x1F62C, 0x0000, 0x83 }, // grimace
{ 0x1F92A, 0x0000, 0x84 }, // zany_face
{ 0x1F920, 0x0000, 0x85 }, // cowboy
// Thumbsup + heart
{ 0x1F44D, 0x0000, 0x86 }, // thumbsup
{ 0x2665, 0x0000, 0x87 }, // heart
// Everything else in original relative order
{ 0x1F6DC, 0x0000, 0x88 }, // wireless
{ 0x267E, 0x0000, 0x89 }, // infinity
{ 0x1F996, 0x0000, 0x8A }, // trex
{ 0x2620, 0x0000, 0x8B }, // skull
{ 0x271D, 0x0000, 0x8C }, // cross
{ 0x26A1, 0x0000, 0x8D }, // lightning
{ 0x1F3A9, 0x0000, 0x8E }, // tophat
{ 0x1F3CD, 0x0000, 0x8F }, // motorcycle
{ 0x1F331, 0x0000, 0x90 }, // seedling
{ 0x1F1E6, 0x1F1FA, 0x91 }, // flag_au
{ 0x2602, 0x0000, 0x92 }, // umbrella
{ 0x1F9FF, 0x0000, 0x93 }, // nazar
{ 0x1F30F, 0x0000, 0x94 }, // globe
{ 0x2622, 0x0000, 0x95 }, // radioactive
{ 0x1F404, 0x0000, 0x96 }, // cow
{ 0x1F47D, 0x0000, 0x97 }, // alien
{ 0x1F47E, 0x0000, 0x98 }, // invader
{ 0x1F5E1, 0x0000, 0x99 }, // dagger
{ 0x26F0, 0x0000, 0x9A }, // mountain
{ 0x1F51A, 0x0000, 0x9B }, // end_arrow
{ 0x2B55, 0x0000, 0x9C }, // hollow_circle
{ 0x1F409, 0x0000, 0x9D }, // dragon
{ 0x1F310, 0x0000, 0x9E }, // globe_meridians
{ 0x1F346, 0x0000, 0x9F }, // eggplant
{ 0x1F6E1, 0x0000, 0xA0 }, // shield
{ 0x1F97D, 0x0000, 0xA1 }, // goggles
{ 0x1F98E, 0x0000, 0xA2 }, // lizard
{ 0x1F998, 0x0000, 0xA3 }, // kangaroo
{ 0x1FAB6, 0x0000, 0xA4 }, // feather
{ 0x1F506, 0x0000, 0xA5 }, // bright
{ 0x303D, 0x0000, 0xA6 }, // part_alt
{ 0x1F6E5, 0x0000, 0xA7 }, // motorboat
{ 0x1F030, 0x0000, 0xA8 }, // domino
{ 0x1F4E1, 0x0000, 0xA9 }, // satellite
{ 0x1F6C3, 0x0000, 0xAA }, // customs
{ 0x1F6DE, 0x0000, 0xAB }, // wheel
{ 0x1F428, 0x0000, 0xAC }, // koala
{ 0x1F39B, 0x0000, 0xAD }, // control_knobs
{ 0x1F351, 0x0000, 0xAE }, // peach
{ 0x1F3CE, 0x0000, 0xAF }, // racing_car
{ 0x1F42D, 0x0000, 0xB0 }, // mouse
{ 0x1F344, 0x0000, 0xB1 }, // mushroom
{ 0x2623, 0x0000, 0xB2 }, // biohazard
{ 0x1F43C, 0x0000, 0xB3 }, // panda
{ 0x1F4A2, 0x0000, 0xB4 }, // anger
{ 0x1F432, 0x0000, 0xB5 }, // dragon_face
{ 0x1F4DF, 0x0000, 0xB6 }, // pager
{ 0x1F41D, 0x0000, 0xB7 }, // bee
{ 0x1F4A1, 0x0000, 0xB8 }, // bulb
{ 0x1F431, 0x0000, 0xB9 }, // cat
{ 0x269C, 0x0000, 0xBA }, // fleur
{ 0x1F314, 0x0000, 0xBB }, // moon
{ 0x2615, 0x0000, 0xBC }, // coffee
{ 0x1F9B7, 0x0000, 0xBD }, // tooth
{ 0x1F968, 0x0000, 0xBE }, // pretzel
{ 0x1F9EE, 0x0000, 0xBF }, // abacus
{ 0x1F5FF, 0x0000, 0xC0 }, // moai
{ 0x1F481, 0x0000, 0xC1 }, // tipping
{ 0x1F994, 0x0000, 0xC2 }, // hedgehog
{ 0x2666, 0x0000, 0xC3 }, // diamond_suit
{ 0x2660, 0x0000, 0xC4 }, // spade_suit
{ 0x1F355, 0x0000, 0xC5 }, // pizza
{ 0x1F340, 0x0000, 0xC6 }, // four_leaf_clover
{ 0x2601, 0x0000, 0xC7 }, // cloud
{ 0x1F680, 0x0000, 0xC8 }, // rocket
{ 0x1F6C2, 0x0000, 0xC9 }, // passport_control
{ 0x2733, 0x0000, 0xCA }, // eight_spoked_asterisk
{ 0x1F4F6, 0x0000, 0xCB }, // signal_strength
};
// ---- Helper functions ----
// Alias table: extra codepoints that map to existing emoji escape bytes.
// Used for variant codepoints (e.g. MWD node identifier 🂎 U+1F08E -> domino sprite)
struct EmojiAlias { uint32_t cp; uint8_t escape; };
#define EMOJI_ALIAS_COUNT 1
static const EmojiAlias EMOJI_ALIASES[EMOJI_ALIAS_COUNT] = {
{ 0x1F08E, 0xA8 }, // domino tile (MWD node signifier) -> domino sprite
};
static uint32_t emojiDecodeUtf8(const uint8_t* s, int remaining, int* bytes_consumed) {
uint8_t b0 = s[0];
if (b0 < 0x80) { *bytes_consumed = 1; return b0; }
@@ -483,6 +791,18 @@ static void emojiSanitize(const char* src, char* dst, int dstLen) {
found = true; break;
}
}
if (!found) {
// Check alias table for variant codepoints
for (int a = 0; a < EMOJI_ALIAS_COUNT; a++) {
if (EMOJI_ALIASES[a].cp == cp) {
dst[di++] = EMOJI_ALIASES[a].escape;
si += consumed;
// Skip trailing variation selector U+FE0F
if (si + 2 < srcLen && s[si] == 0xEF && s[si+1] == 0xB8 && s[si+2] == 0x8F) si += 3;
found = true; break;
}
}
}
if (!found) si += consumed; // Skip unknown multi-byte chars
} else {
dst[di++] = (char)b;
@@ -2,8 +2,8 @@
// =============================================================================
// EpubProcessor.h - Convert EPUB files to plain text for TextReaderScreen
//
// Pipeline: EPUB (ZIP) container.xml OPF spine extract chapters
// strip XHTML tags concatenated plain text cached .txt on SD
// Pipeline: EPUB (ZIP) → container.xml → OPF spine → extract chapters →
// strip XHTML tags → concatenated plain text → cached .txt on SD
//
// The resulting .txt file is placed in /books/ and picked up automatically
// by TextReaderScreen's existing pagination, indexing, and bookmarking.
@@ -14,6 +14,7 @@
#include <SD.h>
#include <FS.h>
#include "EpubZipReader.h"
#include "Utf8CP437.h"
// Maximum chapters in spine (most novels have 20-80)
#define EPUB_MAX_CHAPTERS 200
@@ -426,7 +427,7 @@ private:
//
// Handles:
// - Tag removal (everything between < and >)
// - <p>, <br>, <div>, <h1>-<h6> newlines
// - <p>, <br>, <div>, <h1>-<h6> → newlines
// - HTML entity decoding (&amp; &lt; &gt; &quot; &apos; &#NNN; &#xHH;)
// - Collapse multiple whitespace/newlines
// - Skip <head>, <style>, <script> content entirely
@@ -547,9 +548,9 @@ private:
}
}
// Handle UTF-8 multi-byte sequences (smart quotes, em dashes, etc.)
// These appear as raw bytes in XHTML and must be mapped to ASCII
// since the e-ink font only supports ASCII characters.
// Handle UTF-8 multi-byte sequences (smart quotes, em dashes, accented chars, etc.)
// These appear as raw bytes in XHTML. Typographic chars are mapped to ASCII;
// accented Latin chars are preserved as UTF-8 for CP437 rendering on e-ink.
if ((uint8_t)c >= 0xC0) {
uint32_t codepoint = 0;
int extraBytes = 0;
@@ -579,7 +580,8 @@ private:
if (valid && extraBytes > 0) {
p += extraBytes; // Skip continuation bytes (loop increments past lead byte)
// Map Unicode codepoints to ASCII equivalents
// Map Unicode codepoints to displayable equivalents
// Typographic chars → ASCII, accented chars → preserved as UTF-8
char mapped = 0;
switch (codepoint) {
case 0x2018: case 0x2019: mapped = '\''; break; // Smart single quotes
@@ -598,6 +600,21 @@ private:
default:
if (codepoint >= 0x20 && codepoint < 0x7F) {
mapped = (char)codepoint; // Basic ASCII range
} else if (unicodeToCP437(codepoint)) {
// Accented character that the e-ink font can render via CP437.
// Preserve as UTF-8 in the output; the text reader will decode
// and map to CP437 at render time.
if (codepoint <= 0x7FF) {
output[outPos++] = 0xC0 | (codepoint >> 6);
output[outPos++] = 0x80 | (codepoint & 0x3F);
} else if (codepoint <= 0xFFFF) {
output[outPos++] = 0xE0 | (codepoint >> 12);
output[outPos++] = 0x80 | ((codepoint >> 6) & 0x3F);
output[outPos++] = 0x80 | (codepoint & 0x3F);
}
lastWasNewline = false;
lastWasSpace = false;
continue; // Already wrote to output
} else {
continue; // Skip unmappable characters
}
@@ -608,7 +625,7 @@ private:
continue; // Skip malformed UTF-8
}
} else if ((uint8_t)c >= 0x80) {
// Stray continuation byte (0x80-0xBF) skip
// Stray continuation byte (0x80-0xBF) — skip
continue;
}
@@ -683,6 +700,37 @@ private:
if (entityLen == 5 && strncmp(entity, "ldquo", 5) == 0) return '"';
if (entityLen == 5 && strncmp(entity, "rdquo", 5) == 0) return '"';
// Common accented character entities → CP437 bytes for built-in font
if (entityLen == 6 && strncmp(entity, "eacute", 6) == 0) return (char)0x82; // é
if (entityLen == 6 && strncmp(entity, "egrave", 6) == 0) return (char)0x8A; // è
if (entityLen == 5 && strncmp(entity, "ecirc", 5) == 0) return (char)0x88; // ê
if (entityLen == 4 && strncmp(entity, "euml", 4) == 0) return (char)0x89; // ë
if (entityLen == 6 && strncmp(entity, "agrave", 6) == 0) return (char)0x85; // à
if (entityLen == 6 && strncmp(entity, "aacute", 6) == 0) return (char)0xA0; // á
if (entityLen == 5 && strncmp(entity, "acirc", 5) == 0) return (char)0x83; // â
if (entityLen == 4 && strncmp(entity, "auml", 4) == 0) return (char)0x84; // ä
if (entityLen == 6 && strncmp(entity, "ccedil", 6) == 0) return (char)0x87; // ç
if (entityLen == 6 && strncmp(entity, "iacute", 6) == 0) return (char)0xA1; // í
if (entityLen == 5 && strncmp(entity, "icirc", 5) == 0) return (char)0x8C; // î
if (entityLen == 4 && strncmp(entity, "iuml", 4) == 0) return (char)0x8B; // ï
if (entityLen == 6 && strncmp(entity, "igrave", 6) == 0) return (char)0x8D; // ì
if (entityLen == 6 && strncmp(entity, "oacute", 6) == 0) return (char)0xA2; // ó
if (entityLen == 5 && strncmp(entity, "ocirc", 5) == 0) return (char)0x93; // ô
if (entityLen == 4 && strncmp(entity, "ouml", 4) == 0) return (char)0x94; // ö
if (entityLen == 6 && strncmp(entity, "ograve", 6) == 0) return (char)0x95; // ò
if (entityLen == 6 && strncmp(entity, "uacute", 6) == 0) return (char)0xA3; // ú
if (entityLen == 5 && strncmp(entity, "ucirc", 5) == 0) return (char)0x96; // û
if (entityLen == 4 && strncmp(entity, "uuml", 4) == 0) return (char)0x81; // ü
if (entityLen == 6 && strncmp(entity, "ugrave", 6) == 0) return (char)0x97; // ù
if (entityLen == 6 && strncmp(entity, "ntilde", 6) == 0) return (char)0xA4; // ñ
if (entityLen == 6 && strncmp(entity, "Eacute", 6) == 0) return (char)0x90; // É
if (entityLen == 6 && strncmp(entity, "Ccedil", 6) == 0) return (char)0x80; // Ç
if (entityLen == 6 && strncmp(entity, "Ntilde", 6) == 0) return (char)0xA5; // Ñ
if (entityLen == 4 && strncmp(entity, "Auml", 4) == 0) return (char)0x8E; // Ä
if (entityLen == 4 && strncmp(entity, "Ouml", 4) == 0) return (char)0x99; // Ö
if (entityLen == 4 && strncmp(entity, "Uuml", 4) == 0) return (char)0x9A; // Ü
if (entityLen == 5 && strncmp(entity, "szlig", 5) == 0) return (char)0xE1; // ß
// Numeric entities: &#NNN; or &#xHH;
if (entityLen >= 2 && entity[0] == '#') {
int codepoint = 0;
@@ -701,14 +749,13 @@ private:
if (ch >= '0' && ch <= '9') codepoint = codepoint * 10 + (ch - '0');
}
}
// Map to ASCII (best effort - e-ink font is ASCII only)
// Map to displayable character (best effort)
if (codepoint >= 32 && codepoint < 127) return (char)codepoint;
if (codepoint == 160) return ' '; // non-breaking space
if (codepoint == 8211 || codepoint == 8212) return '-'; // en/em dash
if (codepoint == 8216 || codepoint == 8217) return '\''; // smart quotes
if (codepoint == 8220 || codepoint == 8221) return '"'; // smart quotes
if (codepoint == 8230) return '.'; // ellipsis
if (codepoint == 8226) return '*'; // bullet
// Try CP437 mapping for accented characters.
// The byte value will be passed through to the built-in font.
uint8_t cp437 = unicodeToCP437(codepoint);
if (cp437) return (char)cp437;
// Unknown codepoint > 127: skip it
return ' ';
}
@@ -0,0 +1,249 @@
#pragma once
#include <helpers/ui/UIScreen.h>
#include <helpers/ui/DisplayDriver.h>
#include <helpers/AdvertDataHelpers.h>
#include <MeshCore.h>
extern MyMesh the_mesh;
// ==========================================================================
// Last Heard Screen — passive advert list
// Shows all recently heard nodes from the advert path table, sorted by
// recency. Unlike Discovery (active zero-hop scan), this is purely passive
// — it shows nodes whose adverts have been received over time.
// ==========================================================================
// Display cap — we never need to show all 200 storage entries at once
#define LAST_HEARD_DISPLAY_SIZE 100
class LastHeardScreen : public UIScreen {
mesh::RTCClock* _rtc;
int _scrollPos;
// Local sorted copy of advert paths (PSRAM-allocated, refreshed each render)
AdvertPath* _entries;
int _count;
static char typeChar(uint8_t adv_type) {
switch (adv_type) {
case ADV_TYPE_CHAT: return 'C';
case ADV_TYPE_REPEATER: return 'R';
case ADV_TYPE_ROOM: return 'S';
case ADV_TYPE_SENSOR: return 'N';
default: return '?';
}
}
// Format age as human-readable string (e.g. "2m", "1h", "3d")
static void formatAge(uint32_t now, uint32_t timestamp, char* buf, int bufLen) {
if (timestamp == 0 || now < timestamp) {
snprintf(buf, bufLen, "---");
return;
}
uint32_t age = now - timestamp;
if (age < 60) snprintf(buf, bufLen, "%ds", age);
else if (age < 3600) snprintf(buf, bufLen, "%dm", age / 60);
else if (age < 86400) snprintf(buf, bufLen, "%dh", age / 3600);
else snprintf(buf, bufLen, "%dd", age / 86400);
}
public:
LastHeardScreen(mesh::RTCClock* rtc)
: _rtc(rtc), _scrollPos(0), _count(0) {
#if defined(ESP32)
// ESP32 variants have PSRAM — allocate the entries buffer there
_entries = (AdvertPath*)ps_calloc(LAST_HEARD_DISPLAY_SIZE, sizeof(AdvertPath));
#else
// nRF52 has no PSRAM — fall back to regular heap. At 100 entries × ~84
// bytes each this is ~8.4KB, manageable within Meshpocket's SRAM budget.
_entries = (AdvertPath*)calloc(LAST_HEARD_DISPLAY_SIZE, sizeof(AdvertPath));
#endif
}
void resetScroll() { _scrollPos = 0; }
int getSelectedIdx() const { return _scrollPos; }
// Check if selected node is already in contacts
bool isSelectedInContacts() const {
if (_scrollPos < 0 || _scrollPos >= _count) return false;
return the_mesh.lookupContactByPubKey(_entries[_scrollPos].pubkey_prefix, 8) != nullptr;
}
// Get selected entry (for add/delete operations)
const AdvertPath* getSelectedEntry() const {
if (_scrollPos < 0 || _scrollPos >= _count) return nullptr;
return &_entries[_scrollPos];
}
// Tap-to-select: given virtual Y, select row.
// Returns: 0=miss, 1=moved, 2=tapped current row.
int selectRowAtVY(int vy) {
if (_count == 0) return 0;
const int headerH = 14, footerH = 14, lineH = the_mesh.getNodePrefs()->smallLineH();
#if defined(LilyGo_T5S3_EPaper_Pro)
const int bodyTop = headerH;
#else
const int bodyTop = headerH + the_mesh.getNodePrefs()->smallHighlightOff();
#endif
if (vy < bodyTop || vy >= 128 - footerH) return 0;
int maxVisible = (128 - headerH - footerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_scrollPos - maxVisible / 2,
_count - maxVisible));
int tappedRow = startIdx + (vy - bodyTop) / lineH;
if (tappedRow < 0 || tappedRow >= _count) return 0;
if (tappedRow == _scrollPos) return 2;
_scrollPos = tappedRow;
return 1;
}
int render(DisplayDriver& display) override {
// Refresh sorted list from mesh
_count = the_mesh.getRecentlyHeard(_entries, LAST_HEARD_DISPLAY_SIZE);
// Filter out empty entries (recv_timestamp == 0)
int validCount = 0;
for (int i = 0; i < _count; i++) {
if (_entries[i].recv_timestamp > 0) validCount++;
else break; // sorted by recency, so first zero means rest are empty
}
_count = validCount;
if (_scrollPos >= _count) _scrollPos = max(0, _count - 1);
uint32_t now = _rtc->getCurrentTime();
// === Header ===
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setCursor(0, 0);
char hdr[32];
snprintf(hdr, sizeof(hdr), "Last Heard: %d nodes", _count);
display.print(hdr);
display.drawRect(0, 11, display.width(), 1);
// === Body — node rows ===
display.setTextSize(the_mesh.getNodePrefs()->smallTextSize());
int lineHeight = the_mesh.getNodePrefs()->smallLineH();
int headerHeight = 14;
int footerHeight = 14;
int maxY = display.height() - footerHeight;
int y = headerHeight;
if (_count == 0) {
display.setColor(DisplayDriver::LIGHT);
display.setCursor(4, 28);
display.print("No adverts received yet");
display.setCursor(4, 38);
display.print("Nodes appear as adverts arrive");
} else {
int maxVisible = (maxY - headerHeight) / lineHeight;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_scrollPos - maxVisible / 2,
_count - maxVisible));
int endIdx = min(_count, startIdx + maxVisible);
for (int i = startIdx; i < endIdx && y + lineHeight <= maxY; i++) {
const AdvertPath& entry = _entries[i];
bool selected = (i == _scrollPos);
// Highlight selected row
if (selected) {
display.setColor(DisplayDriver::LIGHT);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.fillRect(0, y, display.width(), lineHeight);
#else
display.fillRect(0, y + the_mesh.getNodePrefs()->smallHighlightOff(), display.width(), lineHeight);
#endif
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(0, y);
// Prefix: cursor + type char
char prefix[4];
snprintf(prefix, sizeof(prefix), "%c%c",
selected ? '>' : ' ', typeChar(entry.type));
display.print(prefix);
// Right side: age + hops + [★] for favourites, [+] for other contacts
char rightStr[20];
char ageBuf[8];
formatAge(now, entry.recv_timestamp, ageBuf, sizeof(ageBuf));
ContactInfo* ci = the_mesh.lookupContactByPubKey(entry.pubkey_prefix, 8);
bool inContacts = (ci != nullptr);
bool isFav = inContacts && (ci->flags & 0x01);
if (isFav) {
snprintf(rightStr, sizeof(rightStr), "%s %dh [*]", ageBuf, entry.path_len & 63);
} else if (inContacts) {
snprintf(rightStr, sizeof(rightStr), "%s %dh [+]", ageBuf, entry.path_len & 63);
} else {
snprintf(rightStr, sizeof(rightStr), "%s %dh", ageBuf, entry.path_len & 63);
}
int rightWidth = display.getTextWidth(rightStr) + 2;
// Name (truncated with ellipsis)
char filteredName[32];
display.translateUTF8ToBlocks(filteredName, entry.name, sizeof(filteredName));
int nameX = display.getTextWidth(prefix) + 2;
int nameMaxW = display.width() - nameX - rightWidth - 2;
display.drawTextEllipsized(nameX, y, nameMaxW, filteredName);
// Right-aligned info
display.setCursor(display.width() - rightWidth, y);
display.print(rightStr);
y += lineHeight;
}
}
display.setTextSize(1);
// === Footer ===
int footerY = display.height() - 12;
display.drawRect(0, footerY - 2, display.width(), 1);
display.setColor(DisplayDriver::YELLOW);
display.setCursor(0, footerY);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.print("Swipe:Scroll");
const char* right = "Tap:Add/Del";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#else
display.print("Q:Bk");
const char* right = "Tap/Ent:Add/Del";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#endif
return 5000; // refresh every 5s to update ages
}
bool handleInput(char c) override {
// Scroll up
if (c == 'w' || c == 'W' || c == 0xF2) {
if (_scrollPos > 0) { _scrollPos--; return true; }
return false;
}
// Scroll down
if (c == 's' || c == 'S' || c == 0xF1) {
if (_scrollPos < _count - 1) { _scrollPos++; return true; }
return false;
}
// Enter — handled by main.cpp (needs access to private MyMesh methods)
// Q — handled by main.cpp (navigation)
return false;
}
};
@@ -0,0 +1,651 @@
#pragma once
// =============================================================================
// M4BMetadata.h - Lightweight MP4/M4B atom parser for metadata extraction
//
// Walks the MP4 atom (box) tree to extract:
// - Title (moov/udta/meta/ilst/©nam)
// - Author (moov/udta/meta/ilst/©ART)
// - Cover art (moov/udta/meta/ilst/covr) - JPEG offset+size within file
// - Duration (moov/mvhd timescale + duration)
// - Chapter markers (moov/udta/chpl) - Nero-style chapter list
//
// Designed for embedded use: no dynamic allocation, reads directly from SD
// via Arduino File API, uses a small stack buffer for atom headers.
//
// Usage:
// M4BMetadata meta;
// File f = SD.open("/audiobooks/mybook.m4b");
// if (meta.parse(f)) {
// Serial.printf("Title: %s\n", meta.title);
// Serial.printf("Author: %s\n", meta.author);
// if (meta.hasCoverArt) {
// // JPEG data is at meta.coverOffset, meta.coverSize bytes
// }
// }
// f.close();
// =============================================================================
#include <SD.h>
// Maximum metadata string lengths (including null terminator)
#define M4B_MAX_TITLE 128
#define M4B_MAX_AUTHOR 64
#define M4B_MAX_CHAPTERS 100
struct M4BChapter {
uint32_t startMs; // Chapter start time in milliseconds
char name[48]; // Chapter title (truncated to fit)
};
class M4BMetadata {
public:
// Extracted metadata
char title[M4B_MAX_TITLE];
char author[M4B_MAX_AUTHOR];
bool hasCoverArt;
uint32_t coverOffset; // Byte offset of JPEG/PNG data within file
uint32_t coverSize; // Size of cover image data in bytes
uint8_t coverFormat; // 13=JPEG, 14=PNG (from MP4 well-known type)
uint32_t durationMs; // Total duration in milliseconds
uint32_t sampleRate; // Audio sample rate (from audio stsd)
uint32_t bitrate; // Approximate bitrate in bps
// Chapter data
M4BChapter chapters[M4B_MAX_CHAPTERS];
int chapterCount;
M4BMetadata() { clear(); }
void clear() {
title[0] = '\0';
author[0] = '\0';
hasCoverArt = false;
coverOffset = 0;
coverSize = 0;
coverFormat = 0;
durationMs = 0;
sampleRate = 44100;
bitrate = 0;
chapterCount = 0;
}
// Parse an open file. Returns true if at least title or duration was found.
// File position is NOT preserved — caller should seek as needed afterward.
bool parse(File& file) {
clear();
if (!file || file.size() < 8) return false;
_fileSize = file.size();
// Walk top-level atoms looking for 'moov'
uint32_t pos = 0;
while (pos < _fileSize) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
if (hdr.type == ATOM_MOOV) {
parseMoov(file, hdr.dataOffset, hdr.dataOffset + hdr.dataSize);
break; // moov found and parsed, we're done
}
// Skip to next top-level atom
pos += hdr.size;
if (hdr.size == 0) break; // size=0 means "extends to EOF"
}
return (title[0] != '\0' || durationMs > 0);
}
// Get chapter index for a given playback position (milliseconds).
// Returns -1 if no chapters or position is before first chapter.
int getChapterForPosition(uint32_t positionMs) const {
if (chapterCount == 0) return -1;
int ch = 0;
for (int i = 1; i < chapterCount; i++) {
if (chapters[i].startMs > positionMs) break;
ch = i;
}
return ch;
}
// Get the start position of the next chapter after the given position.
// Returns 0 if no next chapter.
uint32_t getNextChapterMs(uint32_t positionMs) const {
for (int i = 0; i < chapterCount; i++) {
if (chapters[i].startMs > positionMs) return chapters[i].startMs;
}
return 0;
}
// Get the start position of the current or previous chapter.
uint32_t getPrevChapterMs(uint32_t positionMs) const {
uint32_t prev = 0;
for (int i = 0; i < chapterCount; i++) {
if (chapters[i].startMs >= positionMs) break;
prev = chapters[i].startMs;
}
return prev;
}
private:
uint32_t _fileSize;
// MP4 atom type codes (big-endian FourCC)
static constexpr uint32_t ATOM_MOOV = 0x6D6F6F76; // 'moov'
static constexpr uint32_t ATOM_MVHD = 0x6D766864; // 'mvhd'
static constexpr uint32_t ATOM_UDTA = 0x75647461; // 'udta'
static constexpr uint32_t ATOM_META = 0x6D657461; // 'meta'
static constexpr uint32_t ATOM_ILST = 0x696C7374; // 'ilst'
static constexpr uint32_t ATOM_NAM = 0xA96E616D; // '©nam'
static constexpr uint32_t ATOM_ART = 0xA9415254; // '©ART'
static constexpr uint32_t ATOM_COVR = 0x636F7672; // 'covr'
static constexpr uint32_t ATOM_DATA = 0x64617461; // 'data'
static constexpr uint32_t ATOM_CHPL = 0x6368706C; // 'chpl' (Nero chapters)
static constexpr uint32_t ATOM_TRAK = 0x7472616B; // 'trak'
static constexpr uint32_t ATOM_MDIA = 0x6D646961; // 'mdia'
static constexpr uint32_t ATOM_MDHD = 0x6D646864; // 'mdhd'
static constexpr uint32_t ATOM_HDLR = 0x68646C72; // 'hdlr'
struct AtomHeader {
uint32_t type;
uint64_t size; // Total atom size including header
uint32_t dataOffset; // File offset where data begins (after header)
uint64_t dataSize; // size - header_length
};
// Read a 32-bit big-endian value from file at current position
static uint32_t readU32BE(File& file) {
uint8_t buf[4];
file.read(buf, 4);
return ((uint32_t)buf[0] << 24) | ((uint32_t)buf[1] << 16) |
((uint32_t)buf[2] << 8) | buf[3];
}
// Read a 64-bit big-endian value
static uint64_t readU64BE(File& file) {
uint32_t hi = readU32BE(file);
uint32_t lo = readU32BE(file);
return ((uint64_t)hi << 32) | lo;
}
// Read a 16-bit big-endian value
static uint16_t readU16BE(File& file) {
uint8_t buf[2];
file.read(buf, 2);
return ((uint16_t)buf[0] << 8) | buf[1];
}
// Read atom header at given file offset
bool readAtomHeader(File& file, uint32_t offset, AtomHeader& hdr) {
if (offset + 8 > _fileSize) return false;
file.seek(offset);
uint32_t size32 = readU32BE(file);
hdr.type = readU32BE(file);
if (size32 == 1) {
// 64-bit extended size
if (offset + 16 > _fileSize) return false;
hdr.size = readU64BE(file);
hdr.dataOffset = offset + 16;
hdr.dataSize = (hdr.size > 16) ? hdr.size - 16 : 0;
} else if (size32 == 0) {
// Atom extends to end of file
hdr.size = _fileSize - offset;
hdr.dataOffset = offset + 8;
hdr.dataSize = hdr.size - 8;
} else {
hdr.size = size32;
hdr.dataOffset = offset + 8;
hdr.dataSize = (size32 > 8) ? size32 - 8 : 0;
}
return true;
}
// Parse the moov container atom
void parseMoov(File& file, uint32_t start, uint32_t end) {
uint32_t pos = start;
while (pos < end) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
switch (hdr.type) {
case ATOM_MVHD:
parseMvhd(file, hdr.dataOffset, (uint32_t)hdr.dataSize);
break;
case ATOM_UDTA:
parseUdta(file, hdr.dataOffset, hdr.dataOffset + (uint32_t)hdr.dataSize);
break;
case ATOM_TRAK:
break;
}
pos += (uint32_t)hdr.size;
}
}
// Parse mvhd (movie header) for duration
void parseMvhd(File& file, uint32_t offset, uint32_t size) {
file.seek(offset);
uint8_t version = file.read();
if (version == 0) {
file.seek(offset + 4); // skip version(1) + flags(3)
/* create_time */ readU32BE(file);
/* modify_time */ readU32BE(file);
uint32_t timescale = readU32BE(file);
uint32_t duration = readU32BE(file);
if (timescale > 0) {
durationMs = (uint32_t)((uint64_t)duration * 1000 / timescale);
}
} else if (version == 1) {
file.seek(offset + 4);
/* create_time */ readU64BE(file);
/* modify_time */ readU64BE(file);
uint32_t timescale = readU32BE(file);
uint64_t duration = readU64BE(file);
if (timescale > 0) {
durationMs = (uint32_t)(duration * 1000 / timescale);
}
}
}
// Parse udta container — contains meta and/or chpl
void parseUdta(File& file, uint32_t start, uint32_t end) {
uint32_t pos = start;
while (pos < end) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
if (hdr.type == ATOM_META) {
parseMeta(file, hdr.dataOffset + 4,
hdr.dataOffset + (uint32_t)hdr.dataSize);
} else if (hdr.type == ATOM_CHPL) {
parseChpl(file, hdr.dataOffset, (uint32_t)hdr.dataSize);
}
pos += (uint32_t)hdr.size;
}
}
// Parse meta container — contains hdlr + ilst
void parseMeta(File& file, uint32_t start, uint32_t end) {
uint32_t pos = start;
while (pos < end) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
if (hdr.type == ATOM_ILST) {
parseIlst(file, hdr.dataOffset, hdr.dataOffset + (uint32_t)hdr.dataSize);
}
pos += (uint32_t)hdr.size;
}
}
// Parse ilst (iTunes metadata list) — contains ©nam, ©ART, covr etc.
void parseIlst(File& file, uint32_t start, uint32_t end) {
uint32_t pos = start;
while (pos < end) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
switch (hdr.type) {
case ATOM_NAM:
extractTextData(file, hdr.dataOffset,
hdr.dataOffset + (uint32_t)hdr.dataSize,
title, M4B_MAX_TITLE);
break;
case ATOM_ART:
extractTextData(file, hdr.dataOffset,
hdr.dataOffset + (uint32_t)hdr.dataSize,
author, M4B_MAX_AUTHOR);
break;
case ATOM_COVR:
extractCoverData(file, hdr.dataOffset,
hdr.dataOffset + (uint32_t)hdr.dataSize);
break;
}
pos += (uint32_t)hdr.size;
}
}
// Extract text from a 'data' sub-atom within an ilst entry.
void extractTextData(File& file, uint32_t start, uint32_t end,
char* dest, int maxLen) {
uint32_t pos = start;
while (pos < end) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
if (hdr.type == ATOM_DATA && hdr.dataSize > 8) {
uint32_t textOffset = hdr.dataOffset + 8;
uint32_t textLen = (uint32_t)hdr.dataSize - 8;
if (textLen > (uint32_t)(maxLen - 1)) textLen = maxLen - 1;
file.seek(textOffset);
file.read((uint8_t*)dest, textLen);
dest[textLen] = '\0';
return;
}
pos += (uint32_t)hdr.size;
}
}
// Extract cover art location from 'data' sub-atom within covr.
void extractCoverData(File& file, uint32_t start, uint32_t end) {
uint32_t pos = start;
while (pos < end) {
AtomHeader hdr;
if (!readAtomHeader(file, pos, hdr)) break;
if (hdr.size < 8) break;
if (hdr.type == ATOM_DATA && hdr.dataSize > 8) {
file.seek(hdr.dataOffset);
uint32_t typeIndicator = readU32BE(file);
uint8_t wellKnownType = typeIndicator & 0xFF;
coverOffset = hdr.dataOffset + 8;
coverSize = (uint32_t)hdr.dataSize - 8;
coverFormat = wellKnownType; // 13=JPEG, 14=PNG
hasCoverArt = (coverSize > 0);
Serial.printf("M4B: Cover art found - %s, %u bytes at offset %u\n",
wellKnownType == 13 ? "JPEG" :
wellKnownType == 14 ? "PNG" : "unknown",
coverSize, coverOffset);
return;
}
pos += (uint32_t)hdr.size;
}
}
// =====================================================================
// ID3v2 Parser for MP3 files
// =====================================================================
public:
// Parse ID3v2 tags from an MP3 file. Extracts title (TIT2), artist
// (TPE1), and cover art (APIC). Fills the same metadata fields as
// the M4B parser so decodeCoverArt() works unchanged.
bool parseID3v2(File& file) {
clear();
if (!file || file.size() < 10) return false;
file.seek(0);
uint8_t hdr[10];
if (file.read(hdr, 10) != 10) return false;
// Verify "ID3" magic
if (hdr[0] != 'I' || hdr[1] != 'D' || hdr[2] != '3') {
Serial.println("ID3: No ID3v2 header found");
return false;
}
uint8_t versionMajor = hdr[3]; // 3 = ID3v2.3, 4 = ID3v2.4
bool v24 = (versionMajor == 4);
bool hasExtHeader = (hdr[5] & 0x40) != 0;
// Tag size is syncsafe integer (4 x 7-bit bytes)
uint32_t tagSize = ((uint32_t)(hdr[6] & 0x7F) << 21) |
((uint32_t)(hdr[7] & 0x7F) << 14) |
((uint32_t)(hdr[8] & 0x7F) << 7) |
(hdr[9] & 0x7F);
uint32_t tagEnd = 10 + tagSize;
if (tagEnd > file.size()) tagEnd = file.size();
Serial.printf("ID3: v2.%d, %u bytes\n", versionMajor, tagSize);
// Skip extended header if present
uint32_t pos = 10;
if (hasExtHeader && pos + 4 < tagEnd) {
file.seek(pos);
uint32_t extSize;
if (v24) {
uint8_t eb[4];
file.read(eb, 4);
extSize = ((uint32_t)(eb[0] & 0x7F) << 21) |
((uint32_t)(eb[1] & 0x7F) << 14) |
((uint32_t)(eb[2] & 0x7F) << 7) |
(eb[3] & 0x7F);
} else {
extSize = readU32BE(file) + 4;
}
pos += extSize;
}
// Walk ID3v2 frames
bool foundTitle = false, foundArtist = false, foundCover = false;
while (pos + 10 < tagEnd) {
file.seek(pos);
uint8_t fhdr[10];
if (file.read(fhdr, 10) != 10) break;
if (fhdr[0] == 0) break;
char frameId[5] = { (char)fhdr[0], (char)fhdr[1],
(char)fhdr[2], (char)fhdr[3], '\0' };
uint32_t frameSize;
if (v24) {
frameSize = ((uint32_t)(fhdr[4] & 0x7F) << 21) |
((uint32_t)(fhdr[5] & 0x7F) << 14) |
((uint32_t)(fhdr[6] & 0x7F) << 7) |
(fhdr[7] & 0x7F);
} else {
frameSize = ((uint32_t)fhdr[4] << 24) | ((uint32_t)fhdr[5] << 16) |
((uint32_t)fhdr[6] << 8) | fhdr[7];
}
if (frameSize == 0 || pos + 10 + frameSize > tagEnd) break;
uint32_t dataStart = pos + 10;
// --- TIT2 (Title) ---
if (!foundTitle && strcmp(frameId, "TIT2") == 0 && frameSize > 1) {
id3ExtractText(file, dataStart, frameSize, title, M4B_MAX_TITLE);
foundTitle = (title[0] != '\0');
}
// --- TPE1 (Artist/Author) ---
if (!foundArtist && strcmp(frameId, "TPE1") == 0 && frameSize > 1) {
id3ExtractText(file, dataStart, frameSize, author, M4B_MAX_AUTHOR);
foundArtist = (author[0] != '\0');
}
// --- APIC (Attached Picture) ---
if (!foundCover && strcmp(frameId, "APIC") == 0 && frameSize > 20) {
id3ExtractAPIC(file, dataStart, frameSize);
foundCover = hasCoverArt;
}
pos = dataStart + frameSize;
// Early exit once we have everything
if (foundTitle && foundArtist && foundCover) break;
}
if (foundTitle) Serial.printf("ID3: Title: %s\n", title);
if (foundArtist) Serial.printf("ID3: Author: %s\n", author);
return (foundTitle || foundCover);
}
private:
// Extract text from a TIT2/TPE1 frame.
// Format: encoding(1) + text data
void id3ExtractText(File& file, uint32_t offset, uint32_t size,
char* dest, int maxLen) {
file.seek(offset);
uint8_t encoding = file.read();
uint32_t textLen = size - 1;
if (textLen == 0) return;
if (encoding == 0 || encoding == 3) {
// ISO-8859-1 or UTF-8 — read directly
uint32_t readLen = (textLen < (uint32_t)(maxLen - 1))
? textLen : (uint32_t)(maxLen - 1);
file.read((uint8_t*)dest, readLen);
dest[readLen] = '\0';
// Strip trailing nulls
while (readLen > 0 && dest[readLen - 1] == '\0') readLen--;
dest[readLen] = '\0';
}
else if (encoding == 1 || encoding == 2) {
// UTF-16 (with or without BOM) — crude ASCII extraction
// Static buffer to avoid stack overflow (loopTask has limited stack)
static uint8_t u16buf[128];
uint32_t readLen = (textLen > sizeof(u16buf)) ? sizeof(u16buf) : textLen;
file.read(u16buf, readLen);
uint32_t srcStart = 0;
// Skip BOM if present
if (readLen >= 2 && ((u16buf[0] == 0xFF && u16buf[1] == 0xFE) ||
(u16buf[0] == 0xFE && u16buf[1] == 0xFF))) {
srcStart = 2;
}
bool littleEndian = (srcStart >= 2 && u16buf[0] == 0xFF);
int dstIdx = 0;
for (uint32_t i = srcStart; i + 1 < readLen && dstIdx < maxLen - 1; i += 2) {
uint8_t lo = littleEndian ? u16buf[i] : u16buf[i + 1];
uint8_t hi = littleEndian ? u16buf[i + 1] : u16buf[i];
if (lo == 0 && hi == 0) break; // null terminator
if (hi == 0 && lo >= 0x20 && lo < 0x7F) {
dest[dstIdx++] = (char)lo;
} else {
dest[dstIdx++] = '?';
}
}
dest[dstIdx] = '\0';
}
}
// Extract APIC (cover art) frame.
// Format: encoding(1) + MIME(null-term) + picType(1) + desc(null-term) + imageData
void id3ExtractAPIC(File& file, uint32_t offset, uint32_t frameSize) {
file.seek(offset);
uint8_t encoding = file.read();
// Read MIME type (null-terminated ASCII)
char mime[32] = {0};
int mimeLen = 0;
while (mimeLen < 31) {
int b = file.read();
if (b < 0) return; // Read error
if (b == 0) break; // Null terminator = end of MIME string
mime[mimeLen++] = (char)b;
}
mime[mimeLen] = '\0';
// Picture type (1 byte)
uint8_t picType = file.read();
(void)picType;
// Skip description (null-terminated, encoding-dependent)
if (encoding == 0 || encoding == 3) {
// Single-byte null terminator
while (true) {
int b = file.read();
if (b < 0) return; // Read error
if (b == 0) break; // Null terminator
}
} else {
// UTF-16: double-null terminator
while (true) {
int b1 = file.read();
int b2 = file.read();
if (b1 < 0 || b2 < 0) return; // Read error
if (b1 == 0 && b2 == 0) break; // Double-null terminator
}
}
// Everything from here to end of frame is image data
uint32_t imgOffset = file.position();
uint32_t imgEnd = offset + frameSize;
if (imgOffset >= imgEnd) return;
uint32_t imgSize = imgEnd - imgOffset;
// Determine format from MIME type
bool isJpeg = (strstr(mime, "jpeg") || strstr(mime, "jpg"));
bool isPng = (strstr(mime, "png") != nullptr);
// Also detect by magic bytes if MIME is generic
if (!isJpeg && !isPng && imgSize > 4) {
file.seek(imgOffset);
uint8_t magic[4];
file.read(magic, 4);
if (magic[0] == 0xFF && magic[1] == 0xD8) isJpeg = true;
else if (magic[0] == 0x89 && magic[1] == 'P' &&
magic[2] == 'N' && magic[3] == 'G') isPng = true;
}
coverOffset = imgOffset;
coverSize = imgSize;
coverFormat = isJpeg ? 13 : (isPng ? 14 : 0);
hasCoverArt = (imgSize > 100 && (isJpeg || isPng));
if (hasCoverArt) {
Serial.printf("ID3: Cover %s, %u bytes\n",
isJpeg ? "JPEG" : "PNG", imgSize);
}
}
// Parse Nero-style chapter list (chpl atom).
void parseChpl(File& file, uint32_t offset, uint32_t size) {
if (size < 9) return;
file.seek(offset);
uint8_t version = file.read();
file.read(); // flags byte 1
file.read(); // flags byte 2
file.read(); // flags byte 3
file.read(); // reserved
uint32_t count;
if (version == 1) {
count = readU32BE(file);
} else {
count = file.read();
}
if (count > M4B_MAX_CHAPTERS) count = M4B_MAX_CHAPTERS;
chapterCount = 0;
for (uint32_t i = 0; i < count; i++) {
if (!file.available()) break;
uint64_t timestamp = readU64BE(file);
uint32_t startMs = (uint32_t)(timestamp / 10000); // 100ns -> ms
uint8_t nameLen = file.read();
if (nameLen == 0 || !file.available()) break;
M4BChapter& ch = chapters[chapterCount];
ch.startMs = startMs;
uint8_t readLen = (nameLen < sizeof(ch.name) - 1) ? nameLen : sizeof(ch.name) - 1;
file.read((uint8_t*)ch.name, readLen);
ch.name[readLen] = '\0';
if (nameLen > readLen) {
file.seek(file.position() + (nameLen - readLen));
}
chapterCount++;
}
Serial.printf("M4B: Found %d chapters\n", chapterCount);
}
};
+916
View File
@@ -0,0 +1,916 @@
#pragma once
// =============================================================================
// MapScreen — OSM Tile Map for T-Deck Pro E-Ink Display
// =============================================================================
//
// Renders standard OSM "slippy map" PNG tiles from SD card onto the e-ink
// display at native 240×320 resolution (bypassing the 128×128 logical grid).
//
// Tiles are B&W PNGs stored at /tiles/{zoom}/{x}/{y}.png — the same format
// used by Ripple, tdeck-maps, and MTD-Script tile downloaders.
//
// REQUIREMENTS:
// 1. Add PNGdec library to platformio.ini:
// lib_deps = ... bitbank2/PNGdec@^1.0.1
//
// 2. Add raw display access to GxEPDDisplay.h (public section):
// // --- Raw pixel access for MapScreen (bypasses scaling) ---
// void drawPixelRaw(int16_t x, int16_t y, uint16_t color) {
// display.drawPixel(x, y, color);
// }
// int16_t rawWidth() { return display.width(); }
// int16_t rawHeight() { return display.height(); }
// // Force endFrame() to push to display even if CRC unchanged
// // (needed because drawPixelRaw bypasses CRC tracking)
// void invalidateFrameCRC() { last_display_crc_value = 0; }
//
// 3. Add to UITask.h:
// #include "MapScreen.h"
// UIScreen* map_screen;
// void gotoMapScreen();
// bool isOnMapScreen() const { return curr == map_screen; }
// UIScreen* getMapScreen() const { return map_screen; }
//
// 4. Initialise in UITask::begin():
// map_screen = new MapScreen(this);
//
// 5. Implement UITask::gotoMapScreen() following gotoTextReader() pattern.
//
// 6. Hook 'g' key in main.cpp for GPS/Map access:
// case 'g':
// if (ui_task.isOnMapScreen()) {
// // Already on map — 'g' re-centers on GPS
// ui_task.injectKey('g');
// } else {
// Serial.println("Opening map");
// {
// MapScreen* ms = (MapScreen*)ui_task.getMapScreen();
// if (ms) {
// ms->setSDReady(sdCardReady);
// ms->setGPSPosition(sensors.node_lat,
// sensors.node_lon);
// // Populate contact markers via iterator
// ms->clearMarkers();
// ContactsIterator it = the_mesh.startContactsIterator();
// ContactInfo ci;
// while (it.hasNext(&the_mesh, ci)) {
// double lat = ((double)ci.gps_lat) / 1000000.0;
// double lon = ((double)ci.gps_lon) / 1000000.0;
// ms->addMarker(lat, lon, ci.name, ci.type);
// }
// }
// }
// ui_task.gotoMapScreen();
// }
// break;
//
// 7. Route WASD/zoom keys to map screen in main.cpp (in existing handlers):
// For 'w', 's', 'a', 'd' cases, add:
// if (ui_task.isOnMapScreen()) { ui_task.injectKey(key); break; }
// For the default case, add map screen passthrough:
// if (ui_task.isOnMapScreen()) { ui_task.injectKey(key); break; }
// This covers +, -, i, o, g (re-center) keys too.
//
// TILE SOURCES (B&W recommended for e-ink):
// - MTD-Script: github.com/fistulareffigy/MTD-Script
// - tdeck-maps: github.com/JustDr00py/tdeck-maps
// - Stamen Toner style gives best e-ink contrast
// =============================================================================
#include <Arduino.h>
#include <SD.h>
#include <PNGdec.h>
#undef local // PNGdec's zutil.h defines 'local' as 'static' — breaks any variable named 'local'
#include <helpers/ui/UIScreen.h>
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/GxEPDDisplay.h>
// ---------------------------------------------------------------------------
// Layout constants (physical pixel coordinates, 240×320 display)
// ---------------------------------------------------------------------------
#define MAP_DISPLAY_W 240
#define MAP_DISPLAY_H 320
// Footer bar occupies the bottom — matches other screens' setTextSize(1) footer
#define MAP_FOOTER_H 24 // ~24px at bottom for nav hints
#define MAP_VIEWPORT_Y 0 // Map starts at top
#define MAP_VIEWPORT_H (MAP_DISPLAY_H - MAP_FOOTER_H) // 296px for map
#define MAP_TILE_SIZE 256 // Standard OSM tile size in pixels
#define MAP_DEFAULT_ZOOM 13
#define MAP_MIN_ZOOM 1
#define MAP_MAX_ZOOM 17
// PNG decode buffer size — 256×256 RGB = 196KB, but PNGdec streams row-by-row
// We only need a line buffer. Allocate in PSRAM for safety.
#define MAP_PNG_BUF_SIZE (65536) // 64KB for PNG file read buffer
// Tile path on SD card
#define MAP_TILE_ROOT "/tiles"
// Contact type (for label display — matches AdvertDataHelpers.h)
#ifndef ADV_TYPE_REPEATER
#define ADV_TYPE_REPEATER 2
#endif
// Pan step: fraction of viewport to move per keypress
#define MAP_PAN_FRACTION 4 // 1/4 of viewport per press
// Max contact markers (PSRAM-allocated, ~37 bytes each)
#define MAP_MAX_MARKERS 500
class MapScreen : public UIScreen {
public:
MapScreen(UITask* task)
: _task(task),
_einkDisplay(nullptr),
_sdReady(false),
_needsRedraw(true),
_hasFix(false),
_centerLat(-33.8688), // Default: Sydney (most Ripple users)
_centerLon(151.2093),
_gpsLat(0.0),
_gpsLon(0.0),
_zoom(MAP_DEFAULT_ZOOM),
_zoomMin(MAP_MIN_ZOOM),
_zoomMax(MAP_MAX_ZOOM),
_pngBuf(nullptr),
_lineBuf(nullptr),
_tileFound(false)
{
// Marker array and PNG buffers are deferred to enter() to avoid
// consuming 20KB+ PSRAM at boot when the map may never be opened.
_markers = nullptr;
_numMarkers = 0;
}
~MapScreen() {
if (_pngBuf) { free(_pngBuf); _pngBuf = nullptr; }
if (_lineBuf) { free(_lineBuf); _lineBuf = nullptr; }
if (_markers) { free(_markers); _markers = nullptr; }
}
void setSDReady(bool ready) { _sdReady = ready; }
// Set initial GPS position (called when opening map — centers viewport)
void setGPSPosition(double lat, double lon) {
if (lat != 0.0 || lon != 0.0) {
_gpsLat = lat;
_gpsLon = lon;
_centerLat = lat;
_centerLon = lon;
_hasFix = true;
_needsRedraw = true;
}
}
// Update own GPS position without moving viewport (called periodically)
void updateGPSPosition(double lat, double lon) {
if (lat == 0.0 && lon == 0.0) return;
if (lat != _gpsLat || lon != _gpsLon) {
_gpsLat = lat;
_gpsLon = lon;
_hasFix = true;
_needsRedraw = true; // Redraw to move own-position marker
}
}
// Add a location marker (call once per contact before entering map)
void clearMarkers() { _numMarkers = 0; }
void addMarker(double lat, double lon, const char* name = "", uint8_t type = 0) {
// Lazy-allocate markers on first use (deferred from constructor)
if (!_markers) {
_markers = (MapMarker*)ps_calloc(MAP_MAX_MARKERS, sizeof(MapMarker));
if (!_markers) return; // Alloc failed — skip silently
}
if (_numMarkers >= MAP_MAX_MARKERS) return;
if (lat == 0.0 && lon == 0.0) return; // Skip no-location contacts
_markers[_numMarkers].lat = lat;
_markers[_numMarkers].lon = lon;
_markers[_numMarkers].type = type;
strncpy(_markers[_numMarkers].name, name, sizeof(_markers[0].name) - 1);
_markers[_numMarkers].name[sizeof(_markers[0].name) - 1] = '\0';
_numMarkers++;
}
// Refresh contact markers (called periodically from main loop)
// Clears and rebuilds — caller iterates contacts and calls addMarker()
int getNumMarkers() const { return _numMarkers; }
// Called when navigating to map screen
void enter(DisplayDriver& display) {
_einkDisplay = static_cast<GxEPDDisplay*>(&display);
_needsRedraw = true;
// Allocate marker array in PSRAM on first use (~20KB)
if (!_markers) {
_markers = (MapMarker*)ps_calloc(MAP_MAX_MARKERS, sizeof(MapMarker));
if (_markers) {
Serial.printf("MapScreen: markers allocated (%d × %d = %d bytes PSRAM)\n",
MAP_MAX_MARKERS, (int)sizeof(MapMarker),
MAP_MAX_MARKERS * (int)sizeof(MapMarker));
} else {
Serial.println("MapScreen: marker PSRAM alloc FAILED");
}
}
// Allocate PNG read buffer in PSRAM on first use
if (!_pngBuf) {
_pngBuf = (uint8_t*)ps_malloc(MAP_PNG_BUF_SIZE);
if (!_pngBuf) {
Serial.println("MapScreen: PSRAM alloc failed, trying heap");
_pngBuf = (uint8_t*)malloc(MAP_PNG_BUF_SIZE);
}
if (_pngBuf) {
Serial.printf("MapScreen: PNG buffer allocated (%d bytes)\n", MAP_PNG_BUF_SIZE);
} else {
Serial.println("MapScreen: PNG buffer alloc FAILED");
}
}
// Allocate scanline decode buffer in PSRAM (512 bytes — avoids stack
// allocation inside the PNGdec callback which is called 256× per tile)
if (!_lineBuf) {
_lineBuf = (uint16_t*)ps_malloc(MAP_TILE_SIZE * sizeof(uint16_t));
if (!_lineBuf) {
_lineBuf = (uint16_t*)malloc(MAP_TILE_SIZE * sizeof(uint16_t));
}
if (_lineBuf) {
Serial.println("MapScreen: lineBuf allocated");
} else {
Serial.println("MapScreen: lineBuf alloc FAILED");
}
}
// Detect available zoom levels from SD card directories
detectZoomRange();
}
// ---- UIScreen interface ----
int render(DisplayDriver& display) override {
if (!_einkDisplay) {
_einkDisplay = static_cast<GxEPDDisplay*>(&display);
}
if (!_sdReady) {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
display.setCursor(10, 20);
display.print("SD card not found");
display.setCursor(10, 35);
display.print("Insert SD with");
display.setCursor(10, 48);
display.print("/tiles/{z}/{x}/{y}.png");
return 5000;
}
// Always render tiles — UITask clears the buffer via startFrame() before
// calling us, so we must redraw every time (e.g. after alert overlays)
bool wasRedraw = _needsRedraw;
_needsRedraw = false;
// Render map tiles into the viewport
renderMapViewport();
// Overlay contact markers
renderContactMarkers();
// Crosshair at viewport center
renderCrosshair();
// Footer bar (uses normal display API with scaling)
renderFooter(display);
// Raw pixel writes bypass CRC tracking — force refresh
_einkDisplay->invalidateFrameCRC();
// If user panned/zoomed, allow quick re-render; otherwise idle longer
return wasRedraw ? 1000 : 30000;
}
bool handleInput(char c) override {
// Pan distances in degrees — adaptive to zoom level
// At zoom Z, one tile covers 360/2^Z degrees of longitude
double tileLonSpan = 360.0 / (1 << _zoom);
double tileLatSpan = tileLonSpan * cos(_centerLat * PI / 180.0); // Rough approx
// Pan by 1/MAP_PAN_FRACTION of viewport (viewport ≈ 1 tile)
double panLon = tileLonSpan / MAP_PAN_FRACTION;
double panLat = tileLatSpan / MAP_PAN_FRACTION;
switch (c) {
// ---- WASD panning ----
case 'w':
case 'W':
_centerLat += panLat;
if (_centerLat > 85.05) _centerLat = 85.05; // Web Mercator limit
_needsRedraw = true;
return true;
case 's':
case 'S':
_centerLat -= panLat;
if (_centerLat < -85.05) _centerLat = -85.05;
_needsRedraw = true;
return true;
case 'a':
case 'A':
_centerLon -= panLon;
if (_centerLon < -180.0) _centerLon += 360.0;
_needsRedraw = true;
return true;
case 'd':
case 'D':
_centerLon += panLon;
if (_centerLon > 180.0) _centerLon -= 360.0;
_needsRedraw = true;
return true;
// ---- Zoom controls ----
case 'z':
case 'Z':
if (_zoom < _zoomMax) {
_zoom++;
_needsRedraw = true;
Serial.printf("MapScreen: zoom in -> %d\n", _zoom);
}
return true;
case 'x':
case 'X':
if (_zoom > _zoomMin) {
_zoom--;
_needsRedraw = true;
Serial.printf("MapScreen: zoom out -> %d\n", _zoom);
}
return true;
// ---- Re-center on GPS fix ----
case 'g':
if (_hasFix) {
_centerLat = _gpsLat;
_centerLon = _gpsLon;
_needsRedraw = true;
Serial.println("MapScreen: re-center on GPS");
}
return true;
default:
return false;
}
}
private:
UITask* _task;
GxEPDDisplay* _einkDisplay;
bool _sdReady;
bool _needsRedraw;
bool _hasFix;
// Map state
double _centerLat;
double _centerLon;
double _gpsLat; // Own GPS position (separate from viewport center)
double _gpsLon;
int _zoom;
int _zoomMin; // Detected from SD card
int _zoomMax; // Detected from SD card
// PNG decode buffer (PSRAM)
uint8_t* _pngBuf;
uint16_t* _lineBuf; // Scanline RGB565 buffer for PNG decode (PSRAM)
bool _tileFound; // Did last tile load succeed?
// PNGdec instance
PNG _png;
// Contacts for marker overlay
struct MapMarker {
double lat;
double lon;
char name[20]; // Truncated display name
uint8_t type; // ADV_TYPE_CHAT, ADV_TYPE_REPEATER, etc.
};
MapMarker* _markers = nullptr; // PSRAM-allocated
int _numMarkers = 0;
// ---- Rendering state passed to PNG callback ----
// PNGdec calls our callback per scanline — we need to know where to draw.
// Also carries a PNG* so the static callback can call getLineAsRGB565().
struct DrawContext {
GxEPDDisplay* display;
PNG* png; // Pointer to the decoder (for getLineAsRGB565)
int offsetX; // Screen X offset for this tile
int offsetY; // Screen Y offset for this tile
int viewportY; // Top of viewport (MAP_VIEWPORT_Y)
int viewportH; // Height of viewport (MAP_VIEWPORT_H)
uint16_t* lineBuf; // Scanline decode buffer (PSRAM-allocated, avoids 512B stack usage per callback)
};
DrawContext _drawCtx;
// ==========================================================================
// Detect available zoom levels from /tiles/{z}/ directories on SD
// ==========================================================================
void detectZoomRange() {
if (!_sdReady) return;
_zoomMin = MAP_MAX_ZOOM;
_zoomMax = MAP_MIN_ZOOM;
char path[32];
for (int z = MAP_MIN_ZOOM; z <= MAP_MAX_ZOOM; z++) {
snprintf(path, sizeof(path), MAP_TILE_ROOT "/%d", z);
if (SD.exists(path)) {
if (z < _zoomMin) _zoomMin = z;
if (z > _zoomMax) _zoomMax = z;
}
}
// If no tiles found, reset to defaults
if (_zoomMin > _zoomMax) {
_zoomMin = MAP_MIN_ZOOM;
_zoomMax = MAP_MAX_ZOOM;
Serial.println("MapScreen: no tile directories found");
} else {
Serial.printf("MapScreen: detected zoom range %d-%d\n", _zoomMin, _zoomMax);
}
// Clamp current zoom to available range
if (_zoom > _zoomMax) _zoom = _zoomMax;
if (_zoom < _zoomMin) _zoom = _zoomMin;
}
// ==========================================================================
// Tile coordinate math (Web Mercator / Slippy Map convention)
// ==========================================================================
// Convert lat/lon to tile X,Y and sub-tile pixel offset at given zoom
static void latLonToTileXY(double lat, double lon, int zoom,
int& tileX, int& tileY,
int& pixelX, int& pixelY)
{
int n = 1 << zoom;
// Tile X (longitude is linear)
double x = (lon + 180.0) / 360.0 * n;
tileX = (int)floor(x);
pixelX = (int)((x - tileX) * MAP_TILE_SIZE);
// Tile Y (latitude uses Mercator projection)
double latRad = lat * PI / 180.0;
double y = (1.0 - log(tan(latRad) + 1.0 / cos(latRad)) / PI) / 2.0 * n;
tileY = (int)floor(y);
pixelY = (int)((y - tileY) * MAP_TILE_SIZE);
}
// Convert tile X,Y + pixel offset back to lat/lon
static void tileXYToLatLon(int tileX, int tileY, int pixelX, int pixelY,
int zoom, double& lat, double& lon)
{
int n = 1 << zoom;
double x = tileX + (double)pixelX / MAP_TILE_SIZE;
double y = tileY + (double)pixelY / MAP_TILE_SIZE;
lon = x / n * 360.0 - 180.0;
double latRad = atan(sinh(PI * (1.0 - 2.0 * y / n)));
lat = latRad * 180.0 / PI;
}
// Convert a lat/lon to pixel position within the current viewport
// Returns false if off-screen
bool latLonToScreen(double lat, double lon, int& screenX, int& screenY) {
int centerTileX, centerTileY, centerPixelX, centerPixelY;
latLonToTileXY(_centerLat, _centerLon, _zoom,
centerTileX, centerTileY, centerPixelX, centerPixelY);
int targetTileX, targetTileY, targetPixelX, targetPixelY;
latLonToTileXY(lat, lon, _zoom,
targetTileX, targetTileY, targetPixelX, targetPixelY);
// Calculate pixel delta from center
int dx = (targetTileX - centerTileX) * MAP_TILE_SIZE + (targetPixelX - centerPixelX);
int dy = (targetTileY - centerTileY) * MAP_TILE_SIZE + (targetPixelY - centerPixelY);
screenX = MAP_DISPLAY_W / 2 + dx;
screenY = MAP_VIEWPORT_Y + MAP_VIEWPORT_H / 2 + dy;
return (screenX >= 0 && screenX < MAP_DISPLAY_W &&
screenY >= MAP_VIEWPORT_Y && screenY < MAP_VIEWPORT_Y + MAP_VIEWPORT_H);
}
// ==========================================================================
// Tile loading and rendering
// ==========================================================================
// Build tile file path: /tiles/{zoom}/{x}/{y}.png
static void buildTilePath(char* buf, int bufSize, int zoom, int x, int y) {
snprintf(buf, bufSize, MAP_TILE_ROOT "/%d/%d/%d.png", zoom, x, y);
}
// Load a PNG tile from SD and decode it directly to the display
// screenX, screenY = top-left corner on display where this tile goes
bool loadAndRenderTile(int tileX, int tileY, int screenX, int screenY) {
if (!_pngBuf || !_lineBuf || !_einkDisplay) return false;
char path[64];
buildTilePath(path, sizeof(path), _zoom, tileX, tileY);
// Check existence first to avoid noisy ESP32 VFS error logs
if (!SD.exists(path)) return false;
File f = SD.open(path, FILE_READ);
if (!f) return false;
// Read entire PNG into buffer
int fileSize = f.size();
if (fileSize > MAP_PNG_BUF_SIZE) {
Serial.printf("MapScreen: tile too large: %s (%d bytes)\n", path, fileSize);
f.close();
return false;
}
int bytesRead = f.read(_pngBuf, fileSize);
f.close();
if (bytesRead != fileSize) {
Serial.printf("MapScreen: short read: %s (%d/%d)\n", path, bytesRead, fileSize);
return false;
}
// Set up draw context for the PNG callback
_drawCtx.display = _einkDisplay;
_drawCtx.png = &_png;
_drawCtx.offsetX = screenX;
_drawCtx.offsetY = screenY;
_drawCtx.viewportY = MAP_VIEWPORT_Y;
_drawCtx.viewportH = MAP_VIEWPORT_H;
_drawCtx.lineBuf = _lineBuf;
// Open PNG from memory buffer
int rc = _png.openRAM(_pngBuf, fileSize, pngDrawCallback);
if (rc != PNG_SUCCESS) {
Serial.printf("MapScreen: PNG open failed: %s (rc=%d)\n", path, rc);
return false;
}
// Decode — triggers pngDrawCallback for each scanline.
// First arg is user pointer, passed as pDraw->pUser in callback.
rc = _png.decode(&_drawCtx, 0);
_png.close();
if (rc != PNG_SUCCESS) {
Serial.printf("MapScreen: PNG decode failed: %s (rc=%d)\n", path, rc);
return false;
}
return true;
}
// PNGdec scanline callback — called once per row of the decoded image.
// Draws directly to the e-ink display at raw pixel coordinates.
// Uses getLineAsRGB565 with correct (little) endianness for ESP32.
static int pngDrawCallback(PNGDRAW* pDraw) {
DrawContext* ctx = (DrawContext*)pDraw->pUser;
if (!ctx || !ctx->display || !ctx->png || !ctx->lineBuf) return 0;
int screenY = ctx->offsetY + pDraw->y;
// Clip to viewport vertically
if (screenY < ctx->viewportY || screenY >= ctx->viewportY + ctx->viewportH) return 1;
// Debug: log format on first row of first tile only
if (pDraw->y == 0 && ctx->offsetX >= 0 && ctx->offsetY >= 0) {
static bool logged = false;
if (!logged) {
Serial.printf("MapScreen: PNG iBpp=%d iWidth=%d\n", pDraw->iBpp, pDraw->iWidth);
logged = true;
}
}
uint16_t lineWidth = pDraw->iWidth;
if (lineWidth > MAP_TILE_SIZE) lineWidth = MAP_TILE_SIZE;
ctx->png->getLineAsRGB565(pDraw, ctx->lineBuf, PNG_RGB565_LITTLE_ENDIAN, 0xFFFFFFFF);
for (int x = 0; x < lineWidth; x++) {
int screenX = ctx->offsetX + x;
if (screenX < 0 || screenX >= MAP_DISPLAY_W) continue;
// RGB565 little-endian on ESP32: standard bit layout
// R[15:11] G[10:5] B[4:0]
uint16_t pixel = ctx->lineBuf[x];
// For B&W tiles this is 0x0000 (black) or 0xFFFF (white)
// Simple threshold on full 16-bit value handles both cleanly
uint16_t color = (pixel > 0x7FFF) ? GxEPD_WHITE : GxEPD_BLACK;
ctx->display->drawPixelRaw(screenX, screenY, color);
}
return 1;
}
// ==========================================================================
// Viewport rendering — stitch tiles to fill the screen
// ==========================================================================
void renderMapViewport() {
if (!_einkDisplay) return;
// Find which tile the center point falls in
int centerTileX, centerTileY, centerPixelX, centerPixelY;
latLonToTileXY(_centerLat, _centerLon, _zoom,
centerTileX, centerTileY, centerPixelX, centerPixelY);
Serial.printf("MapScreen: center tile %d/%d/%d px(%d,%d)\n",
_zoom, centerTileX, centerTileY, centerPixelX, centerPixelY);
// Screen position where the center tile's (0,0) corner should be placed
// such that the GPS point ends up at viewport center
int viewCenterX = MAP_DISPLAY_W / 2;
int viewCenterY = MAP_VIEWPORT_Y + MAP_VIEWPORT_H / 2;
int baseTileScreenX = viewCenterX - centerPixelX;
int baseTileScreenY = viewCenterY - centerPixelY;
// Determine tile grid range needed to cover the entire viewport
int startDX = 0, startDY = 0;
int endDX = 0, endDY = 0;
while (baseTileScreenX + startDX * MAP_TILE_SIZE > 0) startDX--;
while (baseTileScreenY + startDY * MAP_TILE_SIZE > MAP_VIEWPORT_Y) startDY--;
while (baseTileScreenX + (endDX + 1) * MAP_TILE_SIZE < MAP_DISPLAY_W) endDX++;
while (baseTileScreenY + (endDY + 1) * MAP_TILE_SIZE < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) endDY++;
int maxTile = (1 << _zoom) - 1;
int loaded = 0, missing = 0;
for (int dy = startDY; dy <= endDY; dy++) {
for (int dx = startDX; dx <= endDX; dx++) {
int tx = centerTileX + dx;
int ty = centerTileY + dy;
// Longitude wraps
if (tx < 0) tx += (1 << _zoom);
if (tx > maxTile) tx -= (1 << _zoom);
// Latitude doesn't wrap — skip out-of-range
if (ty < 0 || ty > maxTile) continue;
int screenX = baseTileScreenX + dx * MAP_TILE_SIZE;
int screenY = baseTileScreenY + dy * MAP_TILE_SIZE;
if (loadAndRenderTile(tx, ty, screenX, screenY)) {
loaded++;
} else {
missing++;
}
yield(); // Feed WDT between tiles — each tile can take 1-2s at 80MHz
}
}
Serial.printf("MapScreen: rendered %d tiles, %d missing\n", loaded, missing);
_tileFound = (loaded > 0);
}
// ==========================================================================
// Contact marker overlay
// ==========================================================================
void renderContactMarkers() {
if (!_einkDisplay || !_markers) return;
int visible = 0;
for (int i = 0; i < _numMarkers; i++) {
int sx, sy;
if (latLonToScreen(_markers[i].lat, _markers[i].lon, sx, sy)) {
int r = markerRadius();
drawDiamond(sx, sy, r);
// Draw name label for repeaters (and at higher zoom for all contacts)
if (_markers[i].name[0] != '\0' &&
(_markers[i].type == ADV_TYPE_REPEATER || _zoom >= 14)) {
drawLabel(sx, sy - r - 2, _markers[i].name);
}
visible++;
}
}
// Render own GPS position as a distinct marker (circle)
if (_hasFix) {
int sx, sy;
if (latLonToScreen(_gpsLat, _gpsLon, sx, sy)) {
drawOwnPosition(sx, sy);
visible++;
}
}
}
// Marker radius scaled by zoom level
// z10→3px, z11→4, z12→5, z13→6, z14→7, z15→8, z16→9, z17→10
int markerRadius() {
int r = _zoom - 7;
if (r < 3) r = 3;
if (r > 10) r = 10;
return r;
}
// Draw a filled diamond marker at screen coordinates with given radius
void drawDiamond(int cx, int cy, int r) {
// White outline first (1px larger than fill)
for (int dy = -(r + 1); dy <= (r + 1); dy++) {
int span = (r + 1) - abs(dy);
int innerSpan = r - abs(dy);
for (int dx = -span; dx <= span; dx++) {
if (abs(dy) <= r && abs(dx) <= innerSpan) continue;
int px = cx + dx, py = cy + dy;
if (px >= 0 && px < MAP_DISPLAY_W &&
py >= MAP_VIEWPORT_Y && py < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
_einkDisplay->drawPixelRaw(px, py, GxEPD_WHITE);
}
}
}
// Filled black diamond
for (int dy = -r; dy <= r; dy++) {
int span = r - abs(dy);
for (int dx = -span; dx <= span; dx++) {
int px = cx + dx, py = cy + dy;
if (px >= 0 && px < MAP_DISPLAY_W &&
py >= MAP_VIEWPORT_Y && py < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
_einkDisplay->drawPixelRaw(px, py, GxEPD_BLACK);
}
}
}
}
// Strip non-ASCII characters (emoji, flags, symbols) from label text.
// Copies only printable ASCII (0x20-0x7E) into dest buffer.
// Skips leading whitespace after stripping. Returns length.
static int extractAsciiLabel(const char* src, char* dest, int destSize) {
int j = 0;
for (int i = 0; src[i] != '\0' && j < destSize - 1; i++) {
uint8_t ch = (uint8_t)src[i];
if (ch >= 0x20 && ch <= 0x7E) {
dest[j++] = src[i];
}
// Skip continuation bytes of multi-byte UTF-8 sequences
}
dest[j] = '\0';
// Trim leading spaces (left after stripping emoji prefix)
int start = 0;
while (dest[start] == ' ') start++;
if (start > 0) {
memmove(dest, dest + start, j - start + 1);
j -= start;
}
return j;
}
// Draw a text label above a marker with white background for readability
// Built-in font is 5×7 pixels per character
void drawLabel(int cx, int topY, const char* text) {
// Clean emoji/non-ASCII from label
char clean[24];
int len = extractAsciiLabel(text, clean, sizeof(clean));
if (len == 0) return; // Nothing printable
if (len > 14) len = 14; // Truncate long names
clean[len] = '\0';
int textW = len * 6; // 5px char + 1px spacing
int textH = 8; // 7px + 1px padding
int lx = cx - textW / 2;
int ly = topY - textH;
// Clamp to viewport
if (lx < 1) lx = 1;
if (lx + textW >= MAP_DISPLAY_W - 1) lx = MAP_DISPLAY_W - textW - 1;
if (ly < MAP_VIEWPORT_Y) ly = MAP_VIEWPORT_Y;
if (ly + textH >= MAP_VIEWPORT_Y + MAP_VIEWPORT_H) return;
// White background rectangle
for (int y = ly - 1; y <= ly + textH; y++) {
for (int x = lx - 1; x <= lx + textW; x++) {
if (x >= 0 && x < MAP_DISPLAY_W &&
y >= MAP_VIEWPORT_Y && y < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
_einkDisplay->drawPixelRaw(x, y, GxEPD_WHITE);
}
}
}
// Draw text using raw font rendering
_einkDisplay->drawTextRaw(lx, ly, clean, GxEPD_BLACK);
}
// Draw own-position marker: bold circle with filled center dot
// Fixed size (doesn't scale with zoom) so it's always clearly visible
void drawOwnPosition(int cx, int cy) {
int r = 8; // Outer radius — always prominent
// White halo (clears map underneath)
for (int dy = -(r + 2); dy <= (r + 2); dy++) {
for (int dx = -(r + 2); dx <= (r + 2); dx++) {
if (dx * dx + dy * dy <= (r + 2) * (r + 2)) {
int px = cx + dx, py = cy + dy;
if (px >= 0 && px < MAP_DISPLAY_W &&
py >= MAP_VIEWPORT_Y && py < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
_einkDisplay->drawPixelRaw(px, py, GxEPD_WHITE);
}
}
}
}
// Thick black circle outline (2px wide ring)
for (int dy = -r; dy <= r; dy++) {
for (int dx = -r; dx <= r; dx++) {
int d2 = dx * dx + dy * dy;
if (d2 >= (r - 2) * (r - 2) && d2 <= r * r) {
int px = cx + dx, py = cy + dy;
if (px >= 0 && px < MAP_DISPLAY_W &&
py >= MAP_VIEWPORT_Y && py < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
_einkDisplay->drawPixelRaw(px, py, GxEPD_BLACK);
}
}
}
}
// Filled black center dot (radius 3)
for (int dy = -3; dy <= 3; dy++) {
for (int dx = -3; dx <= 3; dx++) {
if (dx * dx + dy * dy <= 9) {
int px = cx + dx, py = cy + dy;
if (px >= 0 && px < MAP_DISPLAY_W &&
py >= MAP_VIEWPORT_Y && py < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
_einkDisplay->drawPixelRaw(px, py, GxEPD_BLACK);
}
}
}
}
}
// ==========================================================================
// Crosshair at viewport center
// ==========================================================================
void renderCrosshair() {
if (!_einkDisplay) return;
int cx = MAP_DISPLAY_W / 2;
int cy = MAP_VIEWPORT_Y + MAP_VIEWPORT_H / 2;
int len = markerRadius() + 2; // Scales with zoom
// Draw thin crosshair: black line with white border for contrast
// Horizontal arm
for (int x = cx - len; x <= cx + len; x++) {
if (x >= 0 && x < MAP_DISPLAY_W) {
if (cy - 1 >= MAP_VIEWPORT_Y)
_einkDisplay->drawPixelRaw(x, cy - 1, GxEPD_WHITE);
if (cy + 1 < MAP_VIEWPORT_Y + MAP_VIEWPORT_H)
_einkDisplay->drawPixelRaw(x, cy + 1, GxEPD_WHITE);
_einkDisplay->drawPixelRaw(x, cy, GxEPD_BLACK);
}
}
// Vertical arm
for (int y = cy - len; y <= cy + len; y++) {
if (y >= MAP_VIEWPORT_Y && y < MAP_VIEWPORT_Y + MAP_VIEWPORT_H) {
if (cx - 1 >= 0)
_einkDisplay->drawPixelRaw(cx - 1, y, GxEPD_WHITE);
if (cx + 1 < MAP_DISPLAY_W)
_einkDisplay->drawPixelRaw(cx + 1, y, GxEPD_WHITE);
_einkDisplay->drawPixelRaw(cx, y, GxEPD_BLACK);
}
}
}
// ==========================================================================
// Footer bar — zoom level, GPS status, navigation hints
// ==========================================================================
void renderFooter(DisplayDriver& display) {
// Use the standard footer pattern: setTextSize(1) at height()-12
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
int footerY = display.height() - 12;
// Separator line
display.drawRect(0, footerY - 2, display.width(), 1);
// Left: zoom level
char left[8];
snprintf(left, sizeof(left), "Z%d", _zoom);
display.setCursor(0, footerY);
display.print(left);
// Right: navigation hint
const char* right = "WASD:pan Z/X:zoom";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
}
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,266 @@
#pragma once
// =============================================================================
// ModemManager - A7682E 4G Modem Driver for T-Deck Pro (V1.1 4G variant)
//
// Runs AT commands on a dedicated FreeRTOS task (Core 0, priority 1) to never
// block the mesh radio loop. Communicates with main loop via lock-free queues.
//
// Supports: SMS send/receive, voice call dial/answer/hangup/DTMF
//
// Guard: HAS_4G_MODEM (defined only for the 4G build environment)
// =============================================================================
#ifdef HAS_4G_MODEM
#ifndef MODEM_MANAGER_H
#define MODEM_MANAGER_H
#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include "variant.h"
#include "ApnDatabase.h"
// ---------------------------------------------------------------------------
// Modem pins (from variant.h, always defined for reference)
// MODEM_POWER_EN 41 Board 6609 enable
// MODEM_PWRKEY 40 Power key toggle
// MODEM_RST 9 Reset (shared with I2S BCLK on audio board)
// MODEM_RI 7 Ring indicator (shared with I2S DOUT on audio)
// MODEM_DTR 8 Data terminal ready (shared with I2S LRC on audio)
// MODEM_RX 10 UART RX (shared with PIN_PERF_POWERON)
// MODEM_TX 11 UART TX
// ---------------------------------------------------------------------------
// SMS field limits
#define SMS_PHONE_LEN 20
#define SMS_BODY_LEN 161 // 160 chars + null
// Task configuration
#define MODEM_TASK_PRIORITY 1 // Below mesh (default loop = priority 1 on core 1)
#define MODEM_TASK_STACK_SIZE 6144 // Increased for call handling
#define MODEM_TASK_CORE 0 // Run on core 0 (mesh runs on core 1)
// Queue sizes
#define MODEM_SEND_QUEUE_SIZE 4
#define MODEM_RECV_QUEUE_SIZE 8
#define MODEM_CALL_CMD_QUEUE_SIZE 4
#define MODEM_CALL_EVT_QUEUE_SIZE 4
// ---------------------------------------------------------------------------
// Modem state machine
// ---------------------------------------------------------------------------
enum class ModemState {
OFF,
POWERING_ON,
INITIALIZING,
REGISTERING,
READY,
ERROR,
SENDING_SMS,
// Voice call states
DIALING, // ATD sent, waiting for connect/carrier
RINGING_IN, // Incoming call detected (RING URC)
IN_CALL // Voice call active
};
// ---------------------------------------------------------------------------
// SMS structures (unchanged)
// ---------------------------------------------------------------------------
// Outgoing SMS (queued from main loop to modem task)
struct SMSOutgoing {
char phone[SMS_PHONE_LEN];
char body[SMS_BODY_LEN];
};
// Incoming SMS (queued from modem task to main loop)
struct SMSIncoming {
char phone[SMS_PHONE_LEN];
char body[SMS_BODY_LEN];
uint32_t timestamp; // epoch seconds (from modem RTC or millis-based)
};
// ---------------------------------------------------------------------------
// Voice call structures
// ---------------------------------------------------------------------------
// Commands from main loop → modem task
enum class CallCmd : uint8_t {
DIAL, // Initiate outgoing call
ANSWER, // Answer incoming call
HANGUP, // End active call or reject incoming
DTMF, // Send DTMF tone during call
SET_VOLUME // Set speaker volume
};
struct CallCommand {
CallCmd cmd;
char phone[SMS_PHONE_LEN]; // Used by DIAL
char dtmf; // Used by DTMF (single digit: 0-9, *, #)
uint8_t volume; // Used by SET_VOLUME (0-5)
};
// Events from modem task → main loop
enum class CallEventType : uint8_t {
INCOMING, // Incoming call ringing (+CLIP parsed)
CONNECTED, // Call answered / outgoing connected
ENDED, // Call ended (local hangup, remote hangup, or no carrier)
MISSED, // Incoming call ended before answer
BUSY, // Outgoing call got busy signal
NO_ANSWER, // Outgoing call not answered
DIAL_FAILED // ATD command failed
};
struct CallEvent {
CallEventType type;
char phone[SMS_PHONE_LEN]; // Caller/callee number (from +CLIP or dial)
uint32_t duration; // Call duration in seconds (for ENDED)
};
// ---------------------------------------------------------------------------
// ModemManager class
// ---------------------------------------------------------------------------
class ModemManager {
public:
void begin();
void shutdown();
// --- SMS API (unchanged) ---
bool sendSMS(const char* phone, const char* body);
bool recvSMS(SMSIncoming& out);
// --- Voice Call API ---
bool dialCall(const char* phone); // Queue outgoing call
bool answerCall(); // Answer incoming call
bool hangupCall(); // End active / reject incoming
bool sendDTMF(char digit); // Send DTMF during call
bool setCallVolume(uint8_t level); // Set volume 0-5
bool pollCallEvent(CallEvent& out); // Poll from main loop
// Ringtone control — called from main loop
void setRingtoneEnabled(bool en) { _ringtoneEnabled = en; }
bool isRingtoneEnabled() const { return _ringtoneEnabled; }
// --- State queries (lock-free reads) ---
ModemState getState() const { return _state; }
int getSignalBars() const; // 0-5
int getCSQ() const { return _csq; }
bool isReady() const { return _state == ModemState::READY; }
bool isInCall() const { return _state == ModemState::IN_CALL; }
bool isRinging() const { return _state == ModemState::RINGING_IN; }
bool isDialing() const { return _state == ModemState::DIALING; }
bool isCallActive() const {
return _state == ModemState::IN_CALL ||
_state == ModemState::DIALING ||
_state == ModemState::RINGING_IN;
}
const char* getOperator() const { return _operator; }
const char* getCallPhone() const { return _callPhone; }
uint32_t getCallStartTime() const { return _callStartTime; }
// --- Device info (populated during init) ---
const char* getIMEI() const { return _imei; }
const char* getIMSI() const { return _imsi; }
const char* getAPN() const { return _apn; }
const char* getAPNSource() const { return _apnSource; } // "auto", "network", "user", "none"
// --- APN configuration ---
// Set APN manually (overrides auto-detection). Persists to SD.
void setAPN(const char* apn);
// Load user-configured APN from SD card. Returns true if found.
static bool loadAPNConfig(char* apnOut, int maxLen);
// Save user-configured APN to SD card.
static void saveAPNConfig(const char* apn);
// Pause/resume polling — used by web reader to avoid Core 0 contention
// during WiFi TLS handshakes. While paused, the task skips AT commands
// (SMS poll, CSQ poll) but still drains URCs and handles call commands
// so incoming calls aren't missed.
void pausePolling() { _paused = true; }
void resumePolling() { _paused = false; }
bool isPaused() const { return _paused; }
static const char* stateToString(ModemState s);
// Persistent enable/disable config (SD file /sms/modem.cfg)
static bool loadEnabledConfig();
static void saveEnabledConfig(bool enabled);
private:
volatile ModemState _state = ModemState::OFF;
volatile int _csq = 99; // 99 = unknown
volatile bool _paused = false; // Suppresses AT polling when true
char _operator[24] = {0};
// Device identity (populated during Phase 2 init)
char _imei[20] = {0}; // IMEI from AT+GSN
char _imsi[20] = {0}; // IMSI from AT+CIMI (for APN lookup)
char _apn[64] = {0}; // Active APN
char _apnSource[8] = {0}; // "auto", "network", "user", "none"
// Call state (written by modem task, read by main loop)
char _callPhone[SMS_PHONE_LEN] = {0}; // Current call number
volatile uint32_t _callStartTime = 0; // millis() when call connected
// Ringtone state
volatile bool _ringtoneEnabled = false;
bool _ringing = false; // Shadow of RINGING_IN for tone logic
unsigned long _nextRingTone = 0; // Next tone burst timestamp (modem task)
bool _toneActive = false; // Is a tone currently sounding
TaskHandle_t _taskHandle = nullptr;
// SMS queues
QueueHandle_t _sendQueue = nullptr;
QueueHandle_t _recvQueue = nullptr;
// Call queues
QueueHandle_t _callCmdQueue = nullptr; // main loop → modem task
QueueHandle_t _callEvtQueue = nullptr; // modem task → main loop
SemaphoreHandle_t _uartMutex = nullptr;
// URC line buffer (accumulated between AT commands)
static const int URC_BUF_SIZE = 256;
char _urcBuf[URC_BUF_SIZE];
int _urcPos = 0;
// UART AT command helpers (called only from modem task)
bool modemPowerOn();
bool sendAT(const char* cmd, const char* expect, uint32_t timeout_ms = 2000);
bool waitResponse(const char* expect, uint32_t timeout_ms, char* buf = nullptr, size_t bufLen = 0);
void pollCSQ();
void pollIncomingSMS();
bool doSendSMS(const char* phone, const char* body);
// URC (unsolicited result code) handling
void drainURCs(); // Read available UART data, process complete lines
void processURCLine(const char* line); // Handle a single URC line
// APN resolution (called from modem task during init)
void resolveAPN(); // Auto-detect APN from network/IMSI/user config
// Call control (called from modem task)
bool doDialCall(const char* phone);
bool doAnswerCall();
bool doHangup();
bool doSendDTMF(char digit);
bool doSetVolume(uint8_t level);
void queueCallEvent(CallEventType type, const char* phone = nullptr, uint32_t duration = 0);
void handleRingtone(); // Play tone bursts while incoming call rings
// FreeRTOS task
static void taskEntry(void* param);
void taskLoop();
};
// Global singleton
extern ModemManager modemManager;
#endif // MODEM_MANAGER_H
#endif // HAS_4G_MODEM
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,805 @@
#pragma once
#include <helpers/ui/UIScreen.h>
#include <helpers/ui/DisplayDriver.h>
#include <MeshCore.h>
#include <Packet.h>
// Forward declarations
class UITask;
class MyMesh;
extern MyMesh the_mesh;
class PathEditorScreen : public UIScreen {
public:
enum EditorState {
STATE_MAIN,
STATE_PICK_HOP
};
// Main-state menu items (dynamic, built each render)
enum MenuItem {
MENU_MODE = 0, // "Mode: 1B/hop" or "Mode: 2B/hop"
// After mode: hop lines (MENU_HOP_BASE + i)
// Then: action items
MENU_HOP_BASE = 1,
// Dynamic items after hops:
MENU_ADD_HOP = 100,
MENU_SET_DIRECT,
MENU_REMOVE_LAST,
MENU_CLEAR_PATH,
MENU_SAVE_EXIT
};
private:
UITask* _task;
mesh::RTCClock* _rtc;
int _contactIdx; // Index into contact table
char _contactName[32]; // Contact name for header
EditorState _state;
int _menuSel; // Selected menu item index (0-based in visible list)
int _menuCount; // Total visible menu items
// Path being edited (working copy)
uint8_t _pathBuf[MAX_PATH_SIZE];
uint8_t _pathLen; // Encoded: bits[7:6]=mode, bits[5:0]=hops
int _hopCount; // Decoded hop count
int _bytesPerHop; // 1 or 2
// Repeater picker state
static const int MAX_REPEATERS = 200;
uint16_t* _repIdx; // Indices into contact table (PSRAM)
int _repCount; // Number of repeaters found
int _repSel; // Selected repeater in picker
int _repScroll; // Scroll offset in picker
bool _dirty; // Path has been modified
bool _wantExit; // Set by Save & Exit — caller should navigate back
bool _directLocked; // True = path is explicitly set to direct (0 hops, locked)
// --- helpers ---
void decodePath() {
_hopCount = _pathLen & 0x3F;
uint8_t mode = (_pathLen >> 6) & 0x03;
_bytesPerHop = mode + 1;
}
uint8_t encodePath() const {
uint8_t mode = (_bytesPerHop - 1) & 0x03;
return (mode << 6) | (_hopCount & 0x3F);
}
void buildRepeaterList() {
_repCount = 0;
uint32_t numContacts = the_mesh.getNumContacts();
ContactInfo c;
for (uint32_t i = 0; i < numContacts && _repCount < MAX_REPEATERS; i++) {
if (the_mesh.getContactByIdx(i, c)) {
if (c.type == ADV_TYPE_REPEATER) {
_repIdx[_repCount++] = (uint16_t)i;
}
}
}
}
// Look up a contact name by matching pub_key prefix bytes
bool findNameForHop(int hopIndex, char* name, size_t nameLen) const {
if (hopIndex < 0 || hopIndex >= _hopCount) return false;
int offset = hopIndex * _bytesPerHop;
uint32_t numContacts = the_mesh.getNumContacts();
ContactInfo c;
for (uint32_t i = 0; i < numContacts; i++) {
if (the_mesh.getContactByIdx(i, c)) {
bool match = true;
for (int b = 0; b < _bytesPerHop; b++) {
if (c.id.pub_key[b] != _pathBuf[offset + b]) {
match = false;
break;
}
}
if (match) {
strncpy(name, c.name, nameLen);
name[nameLen - 1] = '\0';
return true;
}
}
}
return false;
}
// Build the visible menu items list and return count
// Menu layout:
// 0: Mode selector
// 1..hopCount: each hop
// hopCount+1: Add hop
// hopCount+2: Remove last (only if hops > 0)
// hopCount+2 or +3: Clear path (only if custom path flag set or hops > 0)
// last: Save & Exit
int buildMenuCount() const {
int count = 1; // Mode selector
count += _hopCount; // One per hop
if (_hopCount < 8) count++; // Add hop (max 8 hops)
count++; // Set Direct (always visible)
if (_hopCount > 0) count++; // Remove last
if (_hopCount > 0 || _directLocked || isCustomPathSet()) count++; // Clear path
count++; // Save & Exit
return count;
}
// Map a menu index to a MenuItem enum
MenuItem menuItemAt(int idx) const {
if (idx == 0) return MENU_MODE;
int pos = 1;
// Hop lines
for (int h = 0; h < _hopCount; h++) {
if (idx == pos) return (MenuItem)(MENU_HOP_BASE + h);
pos++;
}
// Add hop
if (_hopCount < 8) {
if (idx == pos) return MENU_ADD_HOP;
pos++;
}
// Set Direct
if (idx == pos) return MENU_SET_DIRECT;
pos++;
// Remove last
if (_hopCount > 0) {
if (idx == pos) return MENU_REMOVE_LAST;
pos++;
}
// Clear path
if (_hopCount > 0 || _directLocked || isCustomPathSet()) {
if (idx == pos) return MENU_CLEAR_PATH;
pos++;
}
// Save & Exit
return MENU_SAVE_EXIT;
}
bool isCustomPathSet() const {
ContactInfo c;
if (!the_mesh.getContactByIdx(_contactIdx, c)) return false;
return (c.flags & CONTACT_FLAG_CUSTOM_PATH) != 0;
}
public:
PathEditorScreen(UITask* task, mesh::RTCClock* rtc)
: _task(task), _rtc(rtc), _contactIdx(-1), _state(STATE_MAIN),
_menuSel(0), _menuCount(1), _pathLen(0), _hopCount(0),
_bytesPerHop(1), _repCount(0), _repSel(0), _repScroll(0),
_dirty(false), _wantExit(false), _directLocked(false) {
memset(_contactName, 0, sizeof(_contactName));
memset(_pathBuf, 0, sizeof(_pathBuf));
#if defined(ESP32) && defined(BOARD_HAS_PSRAM)
_repIdx = (uint16_t*)ps_calloc(MAX_REPEATERS, sizeof(uint16_t));
#else
_repIdx = new uint16_t[MAX_REPEATERS]();
#endif
}
void openForContact(int contactIdx) {
_contactIdx = contactIdx;
_state = STATE_MAIN;
_menuSel = 0;
_repSel = 0;
_repScroll = 0;
_dirty = false;
_wantExit = false;
_directLocked = false;
// Load contact info
ContactInfo c;
if (the_mesh.getContactByIdx(contactIdx, c)) {
strncpy(_contactName, c.name, sizeof(_contactName) - 1);
_contactName[sizeof(_contactName) - 1] = '\0';
// Copy current path
if (c.out_path_len != OUT_PATH_UNKNOWN) {
_pathLen = c.out_path_len;
decodePath();
int byteLen = _hopCount * _bytesPerHop;
if (byteLen > MAX_PATH_SIZE) byteLen = MAX_PATH_SIZE;
memcpy(_pathBuf, c.out_path, byteLen);
// Detect existing direct-locked path
if (_hopCount == 0 && (c.flags & CONTACT_FLAG_CUSTOM_PATH)) {
_directLocked = true;
}
} else {
_pathLen = 0;
_hopCount = 0;
_bytesPerHop = 1;
memset(_pathBuf, 0, sizeof(_pathBuf));
}
} else {
strcpy(_contactName, "Unknown");
_pathLen = 0;
_hopCount = 0;
_bytesPerHop = 1;
}
_menuCount = buildMenuCount();
}
int render(DisplayDriver& display) override {
if (_state == STATE_PICK_HOP) {
return renderPicker(display);
}
return renderMain(display);
}
int renderMain(DisplayDriver& display) {
char tmp[64];
// === Header ===
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setCursor(0, 0);
snprintf(tmp, sizeof(tmp), "Path: %s", _contactName);
// Truncate if too long
if (display.getTextWidth(tmp) > display.width() - 4) {
snprintf(tmp, sizeof(tmp), "Path: %.12s..", _contactName);
}
display.print(tmp);
// Show lock icon or dirty indicator on right
if (_dirty) {
const char* mod = "[*]";
display.setCursor(display.width() - display.getTextWidth(mod) - 2, 0);
display.print(mod);
} else if (isCustomPathSet()) {
const char* lock = "[L]";
display.setCursor(display.width() - display.getTextWidth(lock) - 2, 0);
display.print(lock);
}
display.drawRect(0, 11, display.width(), 1);
// === Body ===
display.setTextSize(0);
int lineH = 9;
int headerH = 14;
int footerH = 14;
int maxY = display.height() - footerH;
int y = headerH;
_menuCount = buildMenuCount();
// Center visible window around selected item
int maxVisible = (maxY - headerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_menuSel - maxVisible / 2, _menuCount - maxVisible));
if (startIdx < 0) startIdx = 0;
int endIdx = min(_menuCount, startIdx + maxVisible);
for (int i = startIdx; i < endIdx && y + lineH <= maxY; i++) {
bool selected = (i == _menuSel);
MenuItem item = menuItemAt(i);
if (selected) {
display.setColor(DisplayDriver::LIGHT);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.fillRect(0, y, display.width(), lineH);
#else
display.fillRect(0, y + 5, display.width(), lineH);
#endif
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(2, y);
char prefix = selected ? '>' : ' ';
switch (item) {
case MENU_MODE:
if (_directLocked) {
snprintf(tmp, sizeof(tmp), "%c Mode: DIRECT", prefix);
} else {
snprintf(tmp, sizeof(tmp), "%c Mode: %dB/hop", prefix, _bytesPerHop);
}
display.print(tmp);
// Show hint on right
if (!_directLocked) {
const char* hint = "(A/D)";
display.setCursor(display.width() - display.getTextWidth(hint) - 4, y);
display.print(hint);
}
break;
case MENU_ADD_HOP:
snprintf(tmp, sizeof(tmp), "%c + Add hop...", prefix);
display.print(tmp);
break;
case MENU_SET_DIRECT:
if (_directLocked) {
snprintf(tmp, sizeof(tmp), "%c * Direct (set)", prefix);
} else {
snprintf(tmp, sizeof(tmp), "%c * Set Direct", prefix);
}
display.print(tmp);
break;
case MENU_REMOVE_LAST:
snprintf(tmp, sizeof(tmp), "%c - Remove last hop", prefix);
display.print(tmp);
break;
case MENU_CLEAR_PATH:
snprintf(tmp, sizeof(tmp), "%c Clear custom path", prefix);
display.print(tmp);
break;
case MENU_SAVE_EXIT:
snprintf(tmp, sizeof(tmp), "%c Save & Exit", prefix);
display.print(tmp);
break;
default:
// Hop line: MENU_HOP_BASE + hopIndex
if (item >= MENU_HOP_BASE && item < MENU_HOP_BASE + 64) {
int hopIdx = item - MENU_HOP_BASE;
char hopName[24];
int offset = hopIdx * _bytesPerHop;
if (findNameForHop(hopIdx, hopName, sizeof(hopName))) {
if (_bytesPerHop == 1) {
snprintf(tmp, sizeof(tmp), "%c %d: %s (%02X)", prefix, hopIdx + 1,
hopName, _pathBuf[offset]);
} else {
snprintf(tmp, sizeof(tmp), "%c %d: %s (%02X%02X)", prefix, hopIdx + 1,
hopName, _pathBuf[offset], _pathBuf[offset + 1]);
}
} else {
if (_bytesPerHop == 1) {
snprintf(tmp, sizeof(tmp), "%c %d: ??? (%02X)", prefix, hopIdx + 1,
_pathBuf[offset]);
} else {
snprintf(tmp, sizeof(tmp), "%c %d: ??? (%02X%02X)", prefix, hopIdx + 1,
_pathBuf[offset], _pathBuf[offset + 1]);
}
}
display.drawTextEllipsized(2, y, display.width() - 4, tmp);
}
break;
}
y += lineH;
}
// === Footer ===
display.setTextSize(1);
int footerY = display.height() - 12;
display.drawRect(0, footerY - 2, display.width(), 1);
display.setColor(DisplayDriver::YELLOW);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.setCursor(0, footerY);
display.print("Swipe:Nav");
const char* right = "Hold:Select";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#else
display.setCursor(0, footerY);
display.print("Q:Bk W/S:Nav");
const char* right = "Enter:Sel";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#endif
return 5000;
}
int renderPicker(DisplayDriver& display) {
char tmp[64];
// === Header ===
display.setTextSize(1);
display.setColor(DisplayDriver::GREEN);
display.setCursor(0, 0);
snprintf(tmp, sizeof(tmp), "Select Repeater (%d)", _repCount);
display.print(tmp);
display.drawRect(0, 11, display.width(), 1);
// === Body ===
display.setTextSize(0);
int lineH = 9;
int headerH = 14;
int footerH = 14;
int maxY = display.height() - footerH;
int y = headerH;
if (_repCount == 0) {
display.setColor(DisplayDriver::LIGHT);
display.setCursor(0, y);
display.print("No repeaters in contacts");
display.setCursor(0, y + lineH);
display.print("Add repeaters first");
} else {
int maxVisible = (maxY - headerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_repSel - maxVisible / 2, _repCount - maxVisible));
if (startIdx < 0) startIdx = 0;
int endIdx = min(_repCount, startIdx + maxVisible);
for (int i = startIdx; i < endIdx && y + lineH <= maxY; i++) {
ContactInfo c;
if (!the_mesh.getContactByIdx(_repIdx[i], c)) continue;
bool selected = (i == _repSel);
if (selected) {
display.setColor(DisplayDriver::LIGHT);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.fillRect(0, y, display.width(), lineH);
#else
display.fillRect(0, y + 5, display.width(), lineH);
#endif
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(2, y);
char prefix = selected ? '>' : ' ';
if (_bytesPerHop == 1) {
snprintf(tmp, sizeof(tmp), "%c %s (%02X)", prefix, c.name, c.id.pub_key[0]);
} else {
snprintf(tmp, sizeof(tmp), "%c %s (%02X%02X)", prefix, c.name,
c.id.pub_key[0], c.id.pub_key[1]);
}
display.drawTextEllipsized(2, y, display.width() - 4, tmp);
y += lineH;
}
}
// === Footer ===
display.setTextSize(1);
int footerY = display.height() - 12;
display.drawRect(0, footerY - 2, display.width(), 1);
display.setColor(DisplayDriver::YELLOW);
#if defined(LilyGo_T5S3_EPaper_Pro)
display.setCursor(0, footerY);
display.print("Swipe:Scroll");
const char* right = "Hold:Add Back:Cancel";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#else
display.setCursor(0, footerY);
display.print("Q:Cancel W/S:Scroll");
const char* right = "Enter:Add";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
#endif
return 5000;
}
bool handleInput(char c) override {
if (_state == STATE_PICK_HOP) {
return handlePickerInput(c);
}
return handleMainInput(c);
}
bool handleMainInput(char c) {
// W - scroll up
if (c == 'w' || c == 'W' || c == 0xF2) {
if (_menuSel > 0) {
_menuSel--;
return true;
}
return false;
}
// S - scroll down
if (c == 's' || c == 'S' || c == 0xF1) {
if (_menuSel < _menuCount - 1) {
_menuSel++;
return true;
}
return false;
}
// A/D — toggle mode (only when Mode item is selected and not direct-locked)
if (c == 'a' || c == 'A' || c == 'd' || c == 'D') {
MenuItem item = menuItemAt(_menuSel);
if (item == MENU_MODE && !_directLocked) {
// Toggle between 1-byte and 2-byte
if (_bytesPerHop == 1) {
switchMode(2);
} else {
switchMode(1);
}
_dirty = true;
_menuCount = buildMenuCount();
return true;
}
return false;
}
// Enter - select
if (c == 13 || c == KEY_ENTER || c == '\r') {
MenuItem item = menuItemAt(_menuSel);
switch (item) {
case MENU_MODE:
// Toggle mode on Enter too (no-op if direct locked)
if (!_directLocked) {
if (_bytesPerHop == 1) {
switchMode(2);
} else {
switchMode(1);
}
_dirty = true;
_menuCount = buildMenuCount();
}
return true;
case MENU_ADD_HOP:
// Enter picker mode — adding a hop clears direct lock
_directLocked = false;
buildRepeaterList();
_repSel = 0;
_repScroll = 0;
_state = STATE_PICK_HOP;
return true;
case MENU_SET_DIRECT:
// Set path to direct (0 hops, locked)
_hopCount = 0;
_pathLen = 0;
memset(_pathBuf, 0, sizeof(_pathBuf));
_directLocked = true;
_dirty = true;
_menuCount = buildMenuCount();
return true;
case MENU_REMOVE_LAST:
if (_hopCount > 0) {
_hopCount--;
_pathLen = encodePath();
_dirty = true;
_menuCount = buildMenuCount();
// Clamp selection
if (_menuSel >= _menuCount) _menuSel = _menuCount - 1;
}
return true;
case MENU_CLEAR_PATH:
_hopCount = 0;
_pathLen = 0;
_directLocked = false;
memset(_pathBuf, 0, sizeof(_pathBuf));
_dirty = true;
_menuCount = buildMenuCount();
_menuSel = 0;
return true;
case MENU_SAVE_EXIT:
savePath();
_wantExit = true; // Signal to main.cpp to navigate back to contacts
return true;
default:
// Hop line — no action (could add remove-specific-hop later)
break;
}
return true;
}
// Q - back (discard changes or prompt?)
// For simplicity, just go back without saving
if (c == 'q' || c == 'Q') {
// Return to contacts screen without saving
// The UITask will handle this via the key falling through
return false; // Let UITask handle Q as back
}
return false;
}
bool handlePickerInput(char c) {
// W - scroll up
if (c == 'w' || c == 'W' || c == 0xF2) {
if (_repSel > 0) {
_repSel--;
return true;
}
return false;
}
// S - scroll down
if (c == 's' || c == 'S' || c == 0xF1) {
if (_repSel < _repCount - 1) {
_repSel++;
return true;
}
return false;
}
// Enter - add selected repeater as hop
if (c == 13 || c == KEY_ENTER || c == '\r') {
if (_repCount > 0 && _repSel >= 0 && _repSel < _repCount) {
addHopFromContact(_repIdx[_repSel]);
}
_state = STATE_MAIN;
_menuCount = buildMenuCount();
return true;
}
// Q - cancel picker, return to main
if (c == 'q' || c == 'Q') {
_state = STATE_MAIN;
return true;
}
return false;
}
// Tap-to-select for T5S3 touch
int selectRowAtVY(int vy) {
if (_state == STATE_PICK_HOP) {
return selectPickerRowAtVY(vy);
}
return selectMainRowAtVY(vy);
}
int selectMainRowAtVY(int vy) {
if (_menuCount == 0) return 0;
const int headerH = 14, footerH = 14, lineH = 9;
#if defined(LilyGo_T5S3_EPaper_Pro)
const int bodyTop = headerH;
#else
const int bodyTop = headerH + 5;
#endif
if (vy < bodyTop || vy >= 128 - footerH) return 0;
int maxVisible = (128 - headerH - footerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_menuSel - maxVisible / 2, _menuCount - maxVisible));
if (startIdx < 0) startIdx = 0;
int tappedRow = startIdx + (vy - bodyTop) / lineH;
if (tappedRow < 0 || tappedRow >= _menuCount) return 0;
if (tappedRow == _menuSel) return 2;
_menuSel = tappedRow;
return 1;
}
int selectPickerRowAtVY(int vy) {
if (_repCount == 0) return 0;
const int headerH = 14, footerH = 14, lineH = 9;
#if defined(LilyGo_T5S3_EPaper_Pro)
const int bodyTop = headerH;
#else
const int bodyTop = headerH + 5;
#endif
if (vy < bodyTop || vy >= 128 - footerH) return 0;
int maxVisible = (128 - headerH - footerH) / lineH;
if (maxVisible < 3) maxVisible = 3;
int startIdx = max(0, min(_repSel - maxVisible / 2, _repCount - maxVisible));
if (startIdx < 0) startIdx = 0;
int tappedRow = startIdx + (vy - bodyTop) / lineH;
if (tappedRow < 0 || tappedRow >= _repCount) return 0;
if (tappedRow == _repSel) return 2;
_repSel = tappedRow;
return 1;
}
EditorState getState() const { return _state; }
bool isDirty() const { return _dirty; }
bool wantsExit() const { return _wantExit; }
private:
void switchMode(int newBytesPerHop) {
if (newBytesPerHop == _bytesPerHop) return;
if (_hopCount > 0) {
// Rebuild path buffer for new mode
// We need the full pub_keys to re-extract the right prefix bytes
uint8_t newBuf[MAX_PATH_SIZE];
memset(newBuf, 0, sizeof(newBuf));
int newHopCount = 0;
for (int h = 0; h < _hopCount && newHopCount < 8; h++) {
int oldOffset = h * _bytesPerHop;
// Try to find the contact that matches this hop
uint32_t numContacts = the_mesh.getNumContacts();
ContactInfo c;
bool found = false;
for (uint32_t i = 0; i < numContacts; i++) {
if (the_mesh.getContactByIdx(i, c)) {
bool match = true;
for (int b = 0; b < _bytesPerHop; b++) {
if (c.id.pub_key[b] != _pathBuf[oldOffset + b]) {
match = false;
break;
}
}
if (match) {
// Found the contact — copy new prefix size
int newOffset = newHopCount * newBytesPerHop;
for (int b = 0; b < newBytesPerHop; b++) {
newBuf[newOffset + b] = c.id.pub_key[b];
}
newHopCount++;
found = true;
break;
}
}
}
if (!found) {
// Contact not found — copy what we can
int newOffset = newHopCount * newBytesPerHop;
int oldOff = h * _bytesPerHop;
for (int b = 0; b < newBytesPerHop; b++) {
if (b < _bytesPerHop) {
newBuf[newOffset + b] = _pathBuf[oldOff + b];
} else {
newBuf[newOffset + b] = 0x00; // pad with zero
}
}
newHopCount++;
}
}
_hopCount = newHopCount;
memcpy(_pathBuf, newBuf, sizeof(newBuf));
}
_bytesPerHop = newBytesPerHop;
_pathLen = encodePath();
}
void addHopFromContact(uint16_t contactTableIdx) {
if (_hopCount >= 8) return;
ContactInfo c;
if (!the_mesh.getContactByIdx(contactTableIdx, c)) return;
int offset = _hopCount * _bytesPerHop;
if (offset + _bytesPerHop > MAX_PATH_SIZE) return;
for (int b = 0; b < _bytesPerHop; b++) {
_pathBuf[offset + b] = c.id.pub_key[b];
}
_hopCount++;
_pathLen = encodePath();
_dirty = true;
}
void savePath() {
if (_contactIdx < 0) return;
if (_directLocked) {
// Set as direct (0 hops) with lock — prevents flood routing
the_mesh.setCustomPath(_contactIdx, _pathBuf, 0, true);
Serial.printf("PathEditor: set DIRECT path for contact %d (%s)\n",
_contactIdx, _contactName);
} else if (_hopCount > 0) {
// Set custom path with lock
the_mesh.setCustomPath(_contactIdx, _pathBuf, encodePath(), true);
Serial.printf("PathEditor: saved %d-hop %dB/hop path for contact %d (%s)\n",
_hopCount, _bytesPerHop, _contactIdx, _contactName);
} else {
// Clear custom path — revert to auto-discovery
the_mesh.clearCustomPath(_contactIdx);
Serial.printf("PathEditor: cleared custom path for contact %d (%s)\n",
_contactIdx, _contactName);
}
// Trigger contact save to SD
the_mesh.saveContacts();
_dirty = false;
}
};
@@ -0,0 +1,34 @@
#pragma once
// ---------------------------------------------------------------------------
// Radio presets — shared between SettingsScreen (UI) and MyMesh (Serial CLI)
// ---------------------------------------------------------------------------
struct RadioPreset {
const char* name;
float freq;
float bw;
uint8_t sf;
uint8_t cr;
uint8_t tx_power;
};
static const RadioPreset RADIO_PRESETS[] = {
{ "Australia", 915.800f, 250.0f, 10, 5, 22 },
{ "Australia (Narrow)", 916.575f, 62.5f, 7, 8, 22 },
{ "Australia: SA, WA", 923.125f, 62.5f, 8, 8, 22 },
{ "Australia: QLD", 923.125f, 62.5f, 8, 5, 22 },
{ "EU/UK (Narrow)", 869.618f, 62.5f, 8, 8, 14 },
{ "EU/UK (Long Range)", 869.525f, 250.0f, 11, 5, 14 },
{ "EU/UK (Medium Range)", 869.525f, 250.0f, 10, 5, 14 },
{ "Czech Republic (Narrow)",869.432f, 62.5f, 7, 5, 14 },
{ "EU 433 (Long Range)", 433.650f, 250.0f, 11, 5, 14 },
{ "New Zealand", 917.375f, 250.0f, 11, 5, 22 },
{ "New Zealand (Narrow)", 917.375f, 62.5f, 7, 5, 22 },
{ "Portugal 433", 433.375f, 62.5f, 9, 6, 14 },
{ "Portugal 868", 869.618f, 62.5f, 7, 6, 14 },
{ "Switzerland", 869.618f, 62.5f, 8, 8, 14 },
{ "USA/Canada (Recommended)",910.525f, 62.5f, 7, 5, 22 },
{ "Vietnam", 920.250f, 250.0f, 11, 5, 22 },
};
#define NUM_RADIO_PRESETS (sizeof(RADIO_PRESETS) / sizeof(RADIO_PRESETS[0]))
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
#ifdef HAS_4G_MODEM
#include "SMSContacts.h"
// Global singleton
SMSContactStore smsContacts;
#endif // HAS_4G_MODEM
@@ -0,0 +1,176 @@
#pragma once
// =============================================================================
// SMSContacts - Phone-to-name lookup for SMS contacts (4G variant)
//
// Stores contacts in /sms/contacts.txt on SD card.
// Format: one contact per line as "phone=Display Name"
//
// Completely separate from mesh ContactInfo / IdentityStore.
//
// Guard: HAS_4G_MODEM
// =============================================================================
#ifdef HAS_4G_MODEM
#ifndef SMS_CONTACTS_H
#define SMS_CONTACTS_H
#include <Arduino.h>
#include <SD.h>
#define SMS_CONTACT_NAME_LEN 24
#define SMS_CONTACT_MAX 30
#define SMS_CONTACTS_FILE "/sms/contacts.txt"
struct SMSContact {
char phone[20]; // matches SMS_PHONE_LEN
char name[SMS_CONTACT_NAME_LEN];
bool valid;
};
class SMSContactStore {
public:
void begin() {
_count = 0;
memset(_contacts, 0, sizeof(_contacts));
load();
}
// Look up a name by phone number. Returns nullptr if not found.
const char* lookup(const char* phone) const {
for (int i = 0; i < _count; i++) {
if (_contacts[i].valid && strcmp(_contacts[i].phone, phone) == 0) {
return _contacts[i].name;
}
}
return nullptr;
}
// Fill buf with display name if found, otherwise copy phone number.
// Returns true if a name was found.
bool displayName(const char* phone, char* buf, size_t bufLen) const {
const char* name = lookup(phone);
if (name && name[0]) {
strncpy(buf, name, bufLen - 1);
buf[bufLen - 1] = '\0';
return true;
}
strncpy(buf, phone, bufLen - 1);
buf[bufLen - 1] = '\0';
return false;
}
// Add or update a contact. Returns true on success.
bool set(const char* phone, const char* name) {
// Update existing
for (int i = 0; i < _count; i++) {
if (_contacts[i].valid && strcmp(_contacts[i].phone, phone) == 0) {
strncpy(_contacts[i].name, name, SMS_CONTACT_NAME_LEN - 1);
_contacts[i].name[SMS_CONTACT_NAME_LEN - 1] = '\0';
save();
return true;
}
}
// Add new
if (_count >= SMS_CONTACT_MAX) return false;
strncpy(_contacts[_count].phone, phone, sizeof(_contacts[_count].phone) - 1);
_contacts[_count].phone[sizeof(_contacts[_count].phone) - 1] = '\0';
strncpy(_contacts[_count].name, name, SMS_CONTACT_NAME_LEN - 1);
_contacts[_count].name[SMS_CONTACT_NAME_LEN - 1] = '\0';
_contacts[_count].valid = true;
_count++;
save();
return true;
}
// Remove a contact by phone number
bool remove(const char* phone) {
for (int i = 0; i < _count; i++) {
if (_contacts[i].valid && strcmp(_contacts[i].phone, phone) == 0) {
for (int j = i; j < _count - 1; j++) {
_contacts[j] = _contacts[j + 1];
}
_count--;
memset(&_contacts[_count], 0, sizeof(SMSContact));
save();
return true;
}
}
return false;
}
// Accessors for list browsing
int count() const { return _count; }
const SMSContact& get(int index) const { return _contacts[index]; }
// Check if a contact exists
bool exists(const char* phone) const { return lookup(phone) != nullptr; }
private:
SMSContact _contacts[SMS_CONTACT_MAX];
int _count = 0;
void load() {
File f = SD.open(SMS_CONTACTS_FILE, FILE_READ);
if (!f) {
Serial.println("[SMSContacts] No contacts file, starting fresh");
return;
}
char line[64];
while (f.available() && _count < SMS_CONTACT_MAX) {
int pos = 0;
while (f.available() && pos < (int)sizeof(line) - 1) {
char c = f.read();
if (c == '\n' || c == '\r') break;
line[pos++] = c;
}
line[pos] = '\0';
if (pos == 0) continue;
// Consume trailing CR/LF
while (f.available()) {
int pk = f.peek();
if (pk == '\n' || pk == '\r') { f.read(); continue; }
break;
}
// Parse "phone=name"
char* eq = strchr(line, '=');
if (!eq) continue;
*eq = '\0';
const char* phone = line;
const char* name = eq + 1;
if (strlen(phone) == 0 || strlen(name) == 0) continue;
strncpy(_contacts[_count].phone, phone, sizeof(_contacts[_count].phone) - 1);
strncpy(_contacts[_count].name, name, SMS_CONTACT_NAME_LEN - 1);
_contacts[_count].valid = true;
_count++;
}
f.close();
Serial.printf("[SMSContacts] Loaded %d contacts\n", _count);
}
void save() {
if (!SD.exists("/sms")) SD.mkdir("/sms");
File f = SD.open(SMS_CONTACTS_FILE, FILE_WRITE);
if (!f) {
Serial.println("[SMSContacts] Failed to write contacts file");
return;
}
for (int i = 0; i < _count; i++) {
if (!_contacts[i].valid) continue;
f.print(_contacts[i].phone);
f.print('=');
f.println(_contacts[i].name);
}
f.close();
}
};
// Global singleton
extern SMSContactStore smsContacts;
#endif // SMS_CONTACTS_H
#endif // HAS_4G_MODEM
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,196 @@
#ifdef HAS_4G_MODEM
#include "SMSStore.h"
#include <Mesh.h> // For MESH_DEBUG_PRINTLN
#include "target.h" // For SDCARD_CS macro
// Global singleton
SMSStore smsStore;
void SMSStore::begin() {
// Ensure SMS directory exists
if (!SD.exists(SMS_DIR)) {
SD.mkdir(SMS_DIR);
MESH_DEBUG_PRINTLN("[SMSStore] created %s", SMS_DIR);
}
_ready = true;
MESH_DEBUG_PRINTLN("[SMSStore] ready");
}
void SMSStore::phoneToFilename(const char* phone, char* out, size_t outLen) {
// Convert phone number to safe filename: strip non-alphanumeric, prefix with dir
// e.g. "+1234567890" -> "/sms/p1234567890.sms"
char safe[SMS_PHONE_LEN];
int j = 0;
for (int i = 0; phone[i] && j < SMS_PHONE_LEN - 1; i++) {
char c = phone[i];
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
safe[j++] = c;
}
}
safe[j] = '\0';
snprintf(out, outLen, "%s/p%s.sms", SMS_DIR, safe);
}
bool SMSStore::saveMessage(const char* phone, const char* body, bool isSent, uint32_t timestamp) {
if (!_ready) return false;
char filepath[64];
phoneToFilename(phone, filepath, sizeof(filepath));
// Build record
SMSRecord rec;
memset(&rec, 0, sizeof(rec));
rec.timestamp = timestamp;
rec.isSent = isSent ? 1 : 0;
rec.bodyLen = strlen(body);
if (rec.bodyLen >= SMS_BODY_LEN) rec.bodyLen = SMS_BODY_LEN - 1;
strncpy(rec.phone, phone, SMS_PHONE_LEN - 1);
strncpy(rec.body, body, SMS_BODY_LEN - 1);
// Append to file
File f = SD.open(filepath, FILE_APPEND);
if (!f) {
// Try creating
f = SD.open(filepath, FILE_WRITE);
if (!f) {
MESH_DEBUG_PRINTLN("[SMSStore] can't open %s", filepath);
return false;
}
}
size_t written = f.write((uint8_t*)&rec, sizeof(rec));
f.close();
// Release SD CS
digitalWrite(SDCARD_CS, HIGH);
return written == sizeof(rec);
}
int SMSStore::loadConversations(SMSConversation* out, int maxCount) {
if (!_ready) return 0;
File dir = SD.open(SMS_DIR);
if (!dir || !dir.isDirectory()) return 0;
int count = 0;
File entry;
while ((entry = dir.openNextFile()) && count < maxCount) {
const char* name = entry.name();
// Only process .sms files
if (!strstr(name, ".sms")) { entry.close(); continue; }
size_t fileSize = entry.size();
if (fileSize < sizeof(SMSRecord)) { entry.close(); continue; }
int numRecords = fileSize / sizeof(SMSRecord);
// Read the last record for preview
SMSRecord lastRec;
entry.seek(fileSize - sizeof(SMSRecord));
if (entry.read((uint8_t*)&lastRec, sizeof(SMSRecord)) != sizeof(SMSRecord)) {
entry.close();
continue;
}
SMSConversation& conv = out[count];
memset(&conv, 0, sizeof(SMSConversation));
strncpy(conv.phone, lastRec.phone, SMS_PHONE_LEN - 1);
strncpy(conv.preview, lastRec.body, 39);
conv.preview[39] = '\0';
conv.lastTimestamp = lastRec.timestamp;
conv.messageCount = numRecords;
conv.unreadCount = 0; // TODO: track read state
conv.valid = true;
count++;
entry.close();
}
dir.close();
// Release SD CS
digitalWrite(SDCARD_CS, HIGH);
// Sort by most recent (simple bubble sort, small N)
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - 1 - i; j++) {
if (out[j].lastTimestamp < out[j + 1].lastTimestamp) {
SMSConversation tmp = out[j];
out[j] = out[j + 1];
out[j + 1] = tmp;
}
}
}
return count;
}
int SMSStore::loadMessages(const char* phone, SMSMessage* out, int maxCount) {
if (!_ready) return 0;
char filepath[64];
phoneToFilename(phone, filepath, sizeof(filepath));
File f = SD.open(filepath, FILE_READ);
if (!f) return 0;
size_t fileSize = f.size();
int numRecords = fileSize / sizeof(SMSRecord);
// Load from end of file (most recent N messages), in chronological order
int startIdx = numRecords > maxCount ? numRecords - maxCount : 0;
// Read chronologically (oldest first) for chat-style display
SMSRecord rec;
int outIdx = 0;
for (int i = startIdx; i < numRecords && outIdx < maxCount; i++) {
f.seek(i * sizeof(SMSRecord));
if (f.read((uint8_t*)&rec, sizeof(SMSRecord)) != sizeof(SMSRecord)) continue;
out[outIdx].timestamp = rec.timestamp;
out[outIdx].isSent = rec.isSent != 0;
out[outIdx].valid = true;
strncpy(out[outIdx].phone, rec.phone, SMS_PHONE_LEN - 1);
strncpy(out[outIdx].body, rec.body, SMS_BODY_LEN - 1);
outIdx++;
}
f.close();
digitalWrite(SDCARD_CS, HIGH);
return outIdx;
}
bool SMSStore::deleteConversation(const char* phone) {
if (!_ready) return false;
char filepath[64];
phoneToFilename(phone, filepath, sizeof(filepath));
bool ok = SD.remove(filepath);
digitalWrite(SDCARD_CS, HIGH);
return ok;
}
int SMSStore::getMessageCount(const char* phone) {
if (!_ready) return 0;
char filepath[64];
phoneToFilename(phone, filepath, sizeof(filepath));
File f = SD.open(filepath, FILE_READ);
if (!f) return 0;
int count = f.size() / sizeof(SMSRecord);
f.close();
digitalWrite(SDCARD_CS, HIGH);
return count;
}
#endif // HAS_4G_MODEM
@@ -0,0 +1,87 @@
#pragma once
// =============================================================================
// SMSStore - SD card backed SMS message storage
//
// Stores sent and received messages in /sms/ on the SD card.
// Each conversation is a separate file named by phone number (sanitised).
// Messages are appended as fixed-size records for simple random access.
//
// Guard: HAS_4G_MODEM
// =============================================================================
#ifdef HAS_4G_MODEM
#ifndef SMS_STORE_H
#define SMS_STORE_H
#include <Arduino.h>
#include <SD.h>
#define SMS_PHONE_LEN 20
#define SMS_BODY_LEN 161
#define SMS_MAX_CONVERSATIONS 20
#define SMS_DIR "/sms"
// Fixed-size on-disk record (256 bytes, easy alignment)
struct SMSRecord {
uint32_t timestamp; // epoch seconds
uint8_t isSent; // 1=sent, 0=received
uint8_t reserved[2];
uint8_t bodyLen; // actual length of body
char phone[SMS_PHONE_LEN]; // 20
char body[SMS_BODY_LEN]; // 161
uint8_t padding[256 - 4 - 3 - 1 - SMS_PHONE_LEN - SMS_BODY_LEN];
};
// In-memory message for UI
struct SMSMessage {
uint32_t timestamp;
bool isSent;
bool valid;
char phone[SMS_PHONE_LEN];
char body[SMS_BODY_LEN];
};
// Conversation summary for inbox view
struct SMSConversation {
char phone[SMS_PHONE_LEN];
char preview[40]; // last message preview
uint32_t lastTimestamp;
int messageCount;
int unreadCount;
bool valid;
};
class SMSStore {
public:
void begin();
bool isReady() const { return _ready; }
// Save a message (sent or received)
bool saveMessage(const char* phone, const char* body, bool isSent, uint32_t timestamp);
// Load conversation list (sorted by most recent)
int loadConversations(SMSConversation* out, int maxCount);
// Load messages for a specific phone number (chronological, oldest first)
int loadMessages(const char* phone, SMSMessage* out, int maxCount);
// Delete all messages for a phone number
bool deleteConversation(const char* phone);
// Get total message count for a phone number
int getMessageCount(const char* phone);
private:
bool _ready = false;
// Convert phone number to safe filename
void phoneToFilename(const char* phone, char* out, size_t outLen);
};
// Global singleton
extern SMSStore smsStore;
#endif // SMS_STORE_H
#endif // HAS_4G_MODEM
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,128 @@
#pragma once
// =============================================================================
// TouchInput - Minimal CST328/CST3530 touch driver for T-Deck Pro
//
// Uses raw I2C reads on the shared Wire bus. No external library needed.
// Protocol confirmed via raw serial capture from actual hardware:
//
// Register 0xD000, 7 bytes:
// buf[0]: event flags (0xAB = idle/no touch, other = active touch)
// buf[1]: X coordinate high data
// buf[2]: Y coordinate high data
// buf[3]: X low nibble (bits 7:4) | Y low nibble (bits 3:0)
// buf[4]: pressure
// buf[5]: touch count (& 0x7F), typically 0x01 for single touch
// buf[6]: 0xAB always (check byte, ignore)
//
// Coordinate formula:
// x = (buf[1] << 4) | ((buf[3] >> 4) & 0x0F) → 0..239
// y = (buf[2] << 4) | (buf[3] & 0x0F) → 0..319
//
// Hardware: CST328 at 0x1A, INT=GPIO12, RST=GPIO38 (V1.1)
//
// Guard: HAS_TOUCHSCREEN
// =============================================================================
#ifdef HAS_TOUCHSCREEN
#ifndef TOUCH_INPUT_H
#define TOUCH_INPUT_H
#include <Arduino.h>
#include <Wire.h>
class TouchInput {
public:
static const uint8_t TOUCH_ADDR = 0x1A;
TouchInput(TwoWire* wire = &Wire)
: _wire(wire), _intPin(-1), _initialized(false), _debugCount(0), _lastPoll(0) {}
bool begin(int intPin) {
_intPin = intPin;
pinMode(_intPin, INPUT);
// Verify the touch controller is present on the bus
_wire->beginTransmission(TOUCH_ADDR);
uint8_t err = _wire->endTransmission();
if (err != 0) {
Serial.printf("[Touch] CST328 not found at 0x%02X (err=%d)\n", TOUCH_ADDR, err);
return false;
}
Serial.printf("[Touch] CST328 found at 0x%02X, INT=GPIO%d\n", TOUCH_ADDR, _intPin);
_initialized = true;
return true;
}
bool isReady() const { return _initialized; }
// Poll for touch. Returns true if a finger is down, fills x and y.
// Coordinates are in physical display space (0-239 X, 0-319 Y).
// NOTE: CST328 INT pin is pulse-based, not level. We cannot rely on
// digitalRead(INT) for touch state. Instead, always read and check buf[0].
bool getPoint(int16_t &x, int16_t &y) {
if (!_initialized) return false;
// Rate limit: poll at most every 20ms (50 Hz) to avoid I2C bus congestion
unsigned long now = millis();
if (now - _lastPoll < 20) return false;
_lastPoll = now;
uint8_t buf[7];
memset(buf, 0, sizeof(buf));
// Write register address 0xD000
_wire->beginTransmission(TOUCH_ADDR);
_wire->write(0xD0);
_wire->write(0x00);
if (_wire->endTransmission(false) != 0) return false;
// Read 7 bytes of touch data
uint8_t received = _wire->requestFrom(TOUCH_ADDR, (uint8_t)7);
if (received < 7) return false;
for (int i = 0; i < 7; i++) buf[i] = _wire->read();
// buf[0] == 0xAB means idle (no touch active)
if (buf[0] == 0xAB) return false;
// buf[0] == 0x00 can appear on finger-up transition — ignore
if (buf[0] == 0x00) return false;
// Touch count from buf[5]
uint8_t count = buf[5] & 0x7F;
if (count == 0 || count > 5) return false;
// Parse coordinates (CST226/CST328 format confirmed by hardware capture)
// x = (buf[1] << 4) | high nibble of buf[3]
// y = (buf[2] << 4) | low nibble of buf[3]
int16_t tx = ((int16_t)buf[1] << 4) | ((buf[3] >> 4) & 0x0F);
int16_t ty = ((int16_t)buf[2] << 4) | (buf[3] & 0x0F);
// Sanity check (panel is 240x320)
if (tx < 0 || tx > 260 || ty < 0 || ty > 340) return false;
// Debug: log first 20 touch events with parsed coordinates
if (_debugCount < 50) {
Serial.printf("[Touch] Raw: %02X %02X %02X %02X %02X %02X %02X → x=%d y=%d\n",
buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
tx, ty);
_debugCount++;
}
x = tx;
y = ty;
return true;
}
private:
TwoWire* _wire;
int _intPin;
bool _initialized;
int _debugCount;
unsigned long _lastPoll;
};
#endif // TOUCH_INPUT_H
#endif // HAS_TOUCHSCREEN
File diff suppressed because it is too large Load Diff
+222 -1
View File
@@ -22,6 +22,25 @@
#include "../AbstractUITask.h"
#include "../NodePrefs.h"
#ifdef HAS_4G_MODEM
#include "SMSScreen.h"
#endif
#ifdef MECK_WEB_READER
#include "WebReaderScreen.h"
#endif
#ifdef MECK_AUDIO_VARIANT
#include "AlarmScreen.h"
#endif
#if defined(LilyGo_T5S3_EPaper_Pro)
#include "VirtualKeyboard.h"
#endif
// MapScreen.h included in UITask.cpp and main.cpp only (PNGdec headers
// conflict with BLE if pulled into the global include chain)
class UITask : public AbstractUITask {
DisplayDriver* _display;
SensorManager* _sensors;
@@ -32,11 +51,21 @@ class UITask : public AbstractUITask {
GenericVibration vibration;
#endif
unsigned long _next_refresh, _auto_off;
unsigned long _kb_flash_off_at; // Keyboard flash turn-off timer
#ifdef HAS_4G_MODEM
bool _incomingCallRinging; // Currently ringing (incoming call)
unsigned long _nextCallFlash; // Next LED toggle time
bool _callFlashState; // Current LED state during ring
#endif
NodePrefs* _node_prefs;
char _alert[80];
unsigned long _alert_expiry;
bool _hintActive = false; // Boot navigation hint overlay
unsigned long _hintExpiry = 0; // Auto-dismiss time for hint
bool _pendingBootHint = false; // Deferred hint — show after splash screen
int _msgcount;
unsigned long ui_started_at, next_batt_chck;
uint8_t _low_batt_count = 0; // Consecutive low-voltage readings for debounce
int next_backlight_btn_check = 0;
#ifdef PIN_STATUS_LED
int led_state = 0;
@@ -50,12 +79,81 @@ class UITask : public AbstractUITask {
UIScreen* splash;
UIScreen* home;
#ifndef HELTEC_MESH_POCKET
UIScreen* msg_preview;
#endif
UIScreen* channel_screen; // Channel message history screen
UIScreen* contacts_screen; // Contacts list screen
UIScreen* text_reader; // *** NEW: Text reader screen ***
UIScreen* notes_screen; // Notes editor screen
UIScreen* settings_screen; // Settings/onboarding screen
UIScreen* audiobook_screen; // Audiobook player screen (null if not available)
#ifdef MECK_AUDIO_VARIANT
UIScreen* alarm_screen; // Alarm clock screen (audio variant only)
UIScreen* voice_screen; // Voice message screen (audio variant only)
#endif
#ifdef HAS_4G_MODEM
UIScreen* sms_screen; // SMS messaging screen (4G variant only)
#endif
UIScreen* repeater_admin; // Repeater admin screen
UIScreen* path_editor; // Custom path editor screen (lazy-init)
UIScreen* discovery_screen; // Node discovery scan screen
UIScreen* last_heard_screen; // Last heard passive advert list
#ifdef MECK_WEB_READER
UIScreen* web_reader; // Web reader screen (lazy-init, WiFi required)
#endif
UIScreen* map_screen; // Map tile screen (GPS + SD card tiles)
UIScreen* curr;
bool _homeShowingTiles = false; // Set by HomeScreen render when tile grid is visible
int _tileGridVY = 44; // Virtual Y of tile grid top (updated each render)
#if defined(LilyGo_T5S3_EPaper_Pro)
UIScreen* lock_screen; // Lock screen (big clock + battery + unread)
UIScreen* _screenBeforeLock = nullptr;
bool _locked = false;
unsigned long _lastInputMillis = 0; // Auto-lock idle tracking
unsigned long _lastLockRefresh = 0; // Periodic lock screen clock update
VirtualKeyboard _vkb;
bool _vkbActive = false;
UIScreen* _screenBeforeVKB = nullptr;
unsigned long _vkbOpenedAt = 0;
// Powersaving: light sleep when locked + idle (standalone only — no BLE/WiFi)
// Wakes on LoRa packet (DIO1), boot button (GPIO0), or 30-min timer
#if !defined(BLE_PIN_CODE) && !defined(MECK_WIFI_COMPANION)
unsigned long _psLastActive = 0; // millis() at last wake or lock entry
unsigned long _psNextSleepSecs = 60; // Seconds before first sleep (60s), then 5s cycles
#endif
#ifdef MECK_CARDKB
bool _cardkbDetected = false;
#endif
#elif defined(LilyGo_TDeck_Pro)
UIScreen* lock_screen; // Lock screen (big clock + battery + unread)
UIScreen* _screenBeforeLock = nullptr;
bool _locked = false;
unsigned long _lastInputMillis = 0; // Auto-lock idle tracking
unsigned long _lastLockRefresh = 0; // Periodic lock screen clock update
#endif
// --- Message dedup ring buffer (suppress retry spam at UI level) ---
#define MSG_DEDUP_SIZE 8
#define MSG_DEDUP_WINDOW_MS 60000 // 60 seconds
struct MsgDedup {
uint32_t name_hash;
uint32_t text_hash;
unsigned long millis;
};
MsgDedup _dedup[MSG_DEDUP_SIZE];
int _dedupIdx = 0;
// --- Per-contact DM unread tracking ---
uint8_t* _dmUnread = nullptr; // PSRAM-allocated, MAX_CONTACTS entries
static uint32_t simpleHash(const char* s) {
uint32_t h = 5381;
while (*s) { h = ((h << 5) + h) ^ (uint8_t)*s++; }
return h;
}
void userLedHandler();
@@ -71,6 +169,12 @@ public:
UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
next_batt_chck = _next_refresh = 0;
_kb_flash_off_at = 0;
#ifdef HAS_4G_MODEM
_incomingCallRinging = false;
_nextCallFlash = 0;
_callFlashState = false;
#endif
ui_started_at = 0;
curr = NULL;
}
@@ -78,19 +182,104 @@ public:
void gotoHomeScreen();
void gotoChannelScreen(); // Navigate to channel message screen
void gotoDMTab(); // Navigate directly to DM tab on channel screen
void gotoDMConversation(const char* contactName, int contactIdx = -1, uint8_t perms = 0);
void gotoContactsScreen(); // Navigate to contacts list
void gotoTextReader(); // *** NEW: Navigate to text reader ***
void gotoNotesScreen(); // Navigate to notes editor
void gotoSettingsScreen(); // Navigate to settings
void gotoOnboarding(); // Navigate to settings in onboarding mode
void gotoAudiobookPlayer(); // Navigate to audiobook player
#ifdef MECK_AUDIO_VARIANT
void gotoAlarmScreen(); // Navigate to alarm clock
void gotoVoiceScreen(); // Navigate to voice message recorder
#endif
void gotoRepeaterAdmin(int contactIdx); // Navigate to repeater admin
void gotoRepeaterAdminDirect(int contactIdx); // Auto-login admin (L key from conversation)
void gotoPathEditor(int contactIdx); // Navigate to custom path editor
void gotoDiscoveryScreen(); // Navigate to node discovery scan
void gotoLastHeardScreen(); // Navigate to last heard passive list
#if HAS_GPS
void gotoMapScreen(); // Navigate to map tile screen
#endif
#ifdef MECK_WEB_READER
void gotoWebReader(); // Navigate to web reader (browser)
#endif
#ifdef HAS_4G_MODEM
void gotoSMSScreen();
bool isOnSMSScreen() const { return curr == sms_screen; }
SMSScreen* getSMSScreen() const { return (SMSScreen*)sms_screen; }
#endif
void showAlert(const char* text, int duration_millis) override;
void forceRefresh() override { _next_refresh = 100; }
void showBootHint(bool immediate = false); // Show navigation hint overlay on first boot
void dismissBootHint(); // Dismiss hint and save preference
bool isHintActive() const { return _hintActive; }
// Wake display and extend auto-off timer. Call this when handling keys
// outside of injectKey() to prevent display auto-off during direct input.
void keepAlive() {
if (_display != NULL && !_display->isOn()) _display->turnOn();
_auto_off = millis() + 15000; // matches AUTO_OFF_MILLIS default
}
int getMsgCount() const { return _msgcount; }
int getUnreadMsgCount() const; // Per-channel unread tracking (standalone)
// Per-contact DM unread tracking
bool hasDMUnread(int contactIdx) const;
int getDMUnreadCount(int contactIdx) const;
void clearDMUnread(int contactIdx);
// Flag: suppress room→conversation redirect on next login (L key admin access)
bool _skipRoomRedirect = false;
bool hasDisplay() const { return _display != NULL; }
bool isButtonPressed() const;
bool isOnChannelScreen() const { return curr == channel_screen; }
bool isOnContactsScreen() const { return curr == contacts_screen; }
bool isOnTextReader() const { return curr == text_reader; } // *** NEW ***
bool isOnHomeScreen() const { return curr == home; }
bool isHomeShowingTiles() const { return _homeShowingTiles; }
void setHomeShowingTiles(bool v) { _homeShowingTiles = v; }
int getTileGridVY() const { return _tileGridVY; }
void setTileGridVY(int vy) { _tileGridVY = vy; }
bool isOnNotesScreen() const { return curr == notes_screen; }
bool isOnSettingsScreen() const { return curr == settings_screen; }
bool isOnAudiobookPlayer() const { return curr == audiobook_screen; }
#ifdef MECK_AUDIO_VARIANT
bool isOnAlarmScreen() const { return curr == alarm_screen; }
bool isOnVoiceScreen() const { return curr == voice_screen; }
#endif
bool isOnRepeaterAdmin() const { return curr == repeater_admin; }
bool isOnPathEditor() const { return curr == path_editor; }
bool isOnDiscoveryScreen() const { return curr == discovery_screen; }
bool isOnLastHeardScreen() const { return curr == last_heard_screen; }
bool isOnMapScreen() const { return curr == map_screen; }
#if defined(LilyGo_T5S3_EPaper_Pro) || defined(LilyGo_TDeck_Pro)
bool isLocked() const { return _locked; }
void lockScreen();
void unlockScreen();
#endif
#if defined(LilyGo_T5S3_EPaper_Pro)
bool isVKBActive() const { return _vkbActive; }
unsigned long vkbOpenedAt() const { return _vkbOpenedAt; }
VirtualKeyboard& getVKB() { return _vkb; }
void showVirtualKeyboard(VKBPurpose purpose, const char* label, const char* initial, int maxLen, int contextIdx = 0);
void onVKBSubmit();
void onVKBCancel();
#ifdef MECK_CARDKB
void setCardKBDetected(bool v) { _cardkbDetected = v; }
bool hasCardKB() const { return _cardkbDetected; }
void feedCardKBChar(char c);
#endif
#endif
#ifdef MECK_WEB_READER
bool isOnWebReader() const { return curr == web_reader; }
#endif
#ifdef MECK_AUDIO_VARIANT
// Check if audio is playing/paused in the background (for status indicators)
bool isAudioPlayingInBackground() const;
bool isAudioPausedInBackground() const;
#endif
uint8_t getChannelScreenViewIdx() const;
void toggleBuzzer();
@@ -99,24 +288,56 @@ public:
// Check if home screen is in an editing mode (e.g. UTC offset editor)
bool isEditingHomeScreen() const;
// Check if home screen is showing the Recent Adverts page
bool isHomeOnRecentPage() const;
// Inject a key press from external source (e.g., keyboard)
void injectKey(char c);
// Add a sent message to the channel screen history
void addSentChannelMessage(uint8_t channel_idx, const char* sender, const char* text) override;
void addSentDM(const char* recipientName, const char* sender, const char* text);
// Mark channel as read when BLE companion app syncs messages
void markChannelReadFromBLE(uint8_t channel_idx) override;
// Repeater admin callbacks
void onAdminLoginResult(bool success, uint8_t permissions, uint32_t server_time) override;
void onAdminCliResponse(const char* from_name, const char* text) override;
void onAdminTelemetryResult(const uint8_t* data, uint8_t len) override;
// Get current screen for checking state
UIScreen* getCurrentScreen() const { return curr; }
#ifndef HELTEC_MESH_POCKET
UIScreen* getMsgPreviewScreen() const { return msg_preview; }
#endif
UIScreen* getTextReaderScreen() const { return text_reader; } // *** NEW ***
UIScreen* getNotesScreen() const { return notes_screen; }
UIScreen* getContactsScreen() const { return contacts_screen; }
UIScreen* getChannelScreen() const { return channel_screen; }
UIScreen* getSettingsScreen() const { return settings_screen; }
NodePrefs* getNodePrefs() const { return _node_prefs; }
UIScreen* getAudiobookScreen() const { return audiobook_screen; }
void setAudiobookScreen(UIScreen* s) { audiobook_screen = s; }
#ifdef MECK_AUDIO_VARIANT
UIScreen* getAlarmScreen() const { return alarm_screen; }
void setAlarmScreen(UIScreen* s) { alarm_screen = s; }
UIScreen* getVoiceScreen() const { return voice_screen; }
void setVoiceScreen(UIScreen* s) { voice_screen = s; }
#endif
UIScreen* getRepeaterAdminScreen() const { return repeater_admin; }
UIScreen* getPathEditorScreen() const { return path_editor; }
UIScreen* getDiscoveryScreen() const { return discovery_screen; }
UIScreen* getLastHeardScreen() const { return last_heard_screen; }
UIScreen* getMapScreen() const { return map_screen; }
#ifdef MECK_WEB_READER
UIScreen* getWebReaderScreen() const { return web_reader; }
#endif
// from AbstractUITask
void msgRead(int msgcount) override;
void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override;
void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount,
const uint8_t* path = nullptr, int8_t snr = 0) override;
void notify(UIEventType t = UIEventType::none) override;
void loop() override;
+152
View File
@@ -0,0 +1,152 @@
#pragma once
// =============================================================================
// Utf8CP437.h - UTF-8 decoding and Unicode-to-CP437 mapping
//
// The Adafruit GFX built-in 6x8 font uses the CP437 character set for codes
// 128-255. This header provides utilities to:
// 1. Decode UTF-8 multi-byte sequences into Unicode codepoints
// 2. Map Unicode codepoints to CP437 byte values for display
//
// Used by both EpubProcessor (at XHTML→text conversion time) and
// TextReaderScreen (at render time for plain .txt files).
// =============================================================================
// Map a Unicode codepoint to its CP437 equivalent byte.
// Returns the CP437 byte (0x80-0xFF) for supported accented characters,
// the codepoint itself for ASCII (0x20-0x7E), or 0 if unmappable.
inline uint8_t unicodeToCP437(uint32_t cp) {
// ASCII passthrough
if (cp >= 0x20 && cp < 0x7F) return (uint8_t)cp;
switch (cp) {
// Uppercase accented
case 0x00C7: return 0x80; // Ç
case 0x00C9: return 0x90; // É
case 0x00C4: return 0x8E; // Ä
case 0x00C5: return 0x8F; // Å
case 0x00C6: return 0x92; // Æ
case 0x00D6: return 0x99; // Ö
case 0x00DC: return 0x9A; // Ü
case 0x00D1: return 0xA5; // Ñ
// Lowercase accented
case 0x00E9: return 0x82; // é
case 0x00E2: return 0x83; // â
case 0x00E4: return 0x84; // ä
case 0x00E0: return 0x85; // à
case 0x00E5: return 0x86; // å
case 0x00E7: return 0x87; // ç
case 0x00EA: return 0x88; // ê
case 0x00EB: return 0x89; // ë
case 0x00E8: return 0x8A; // è
case 0x00EF: return 0x8B; // ï
case 0x00EE: return 0x8C; // î
case 0x00EC: return 0x8D; // ì
case 0x00E6: return 0x91; // æ
case 0x00F4: return 0x93; // ô
case 0x00F6: return 0x94; // ö
case 0x00F2: return 0x95; // ò
case 0x00FB: return 0x96; // û
case 0x00F9: return 0x97; // ù
case 0x00FF: return 0x98; // ÿ
case 0x00FC: return 0x81; // ü
case 0x00E1: return 0xA0; // á
case 0x00ED: return 0xA1; // í
case 0x00F3: return 0xA2; // ó
case 0x00FA: return 0xA3; // ú
case 0x00F1: return 0xA4; // ñ
// Currency / symbols
case 0x00A2: return 0x9B; // ¢
case 0x00A3: return 0x9C; // £
case 0x00A5: return 0x9D; // ¥
case 0x00BF: return 0xA8; // ¿
case 0x00A1: return 0xAD; // ¡
case 0x00AB: return 0xAE; // «
case 0x00BB: return 0xAF; // »
case 0x00B0: return 0xF8; // °
case 0x00B1: return 0xF1; // ±
case 0x00B5: return 0xE6; // µ
case 0x00DF: return 0xE1; // ß
// Typographic (smart quotes, dashes, etc.)
case 0x2018: case 0x2019: return '\''; // Smart single quotes
case 0x201C: case 0x201D: return '"'; // Smart double quotes
case 0x2013: case 0x2014: return '-'; // En/em dash
case 0x2010: case 0x2011: case 0x2012: case 0x2015: return '-'; // Hyphens/bars
case 0x2026: return 0xFD; // Ellipsis (CP437 has no …, use ²? no, skip)
case 0x2022: return 0x07; // Bullet → CP437 bullet
case 0x00A0: return ' '; // Non-breaking space
case 0x2039: case 0x203A: return '\''; // Single guillemets
case 0x2032: return '\''; // Prime
case 0x2033: return '"'; // Double prime
default: return 0; // Unmappable
}
}
// Decode a single UTF-8 character from a byte buffer.
// Returns the Unicode codepoint and advances *pos past the full sequence.
// If the sequence is invalid, returns 0xFFFD (replacement char) and advances by 1.
//
// buf: input buffer
// bufLen: total buffer length
// pos: pointer to current position (updated on return)
inline uint32_t decodeUtf8Char(const char* buf, int bufLen, int* pos) {
int i = *pos;
if (i >= bufLen) return 0;
uint8_t c = (uint8_t)buf[i];
// ASCII (single byte)
if (c < 0x80) {
*pos = i + 1;
return c;
}
// Continuation byte without lead byte — skip
if (c < 0xC0) {
*pos = i + 1;
return 0xFFFD;
}
uint32_t codepoint;
int extraBytes;
if ((c & 0xE0) == 0xC0) {
codepoint = c & 0x1F;
extraBytes = 1;
} else if ((c & 0xF0) == 0xE0) {
codepoint = c & 0x0F;
extraBytes = 2;
} else if ((c & 0xF8) == 0xF0) {
codepoint = c & 0x07;
extraBytes = 3;
} else {
*pos = i + 1;
return 0xFFFD;
}
// Verify we have enough bytes and they're valid continuation bytes
if (i + extraBytes >= bufLen) {
*pos = i + 1;
return 0xFFFD;
}
for (int b = 1; b <= extraBytes; b++) {
uint8_t cb = (uint8_t)buf[i + b];
if ((cb & 0xC0) != 0x80) {
*pos = i + 1;
return 0xFFFD;
}
codepoint = (codepoint << 6) | (cb & 0x3F);
}
*pos = i + 1 + extraBytes;
return codepoint;
}
// Check if a byte is a UTF-8 continuation byte (10xxxxxx)
inline bool isUtf8Continuation(uint8_t c) {
return (c & 0xC0) == 0x80;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+92 -49
View File
@@ -1,7 +1,7 @@
#pragma once
// Emoji Picker with scrolling grid and scroll bar
// 5 columns, 4 visible rows, scrollable through all 46 emoji
// 5 columns, 4 visible rows, scrollable through all 76 emoji
// WASD navigation, Enter to select, $/Q/Backspace to cancel
#include <helpers/ui/DisplayDriver.h>
@@ -12,52 +12,85 @@
#define EMOJI_PICKER_TOTAL_ROWS ((EMOJI_COUNT + EMOJI_PICKER_COLS - 1) / EMOJI_PICKER_COLS)
static const char* EMOJI_LABELS[EMOJI_COUNT] = {
// Faces/emotion
"Lol", // 0 joy
"Like", // 1 thumbsup
"Sad", // 2 frown
"WiFi", // 3 wireless
"Inf", // 4 infinity
"Rex", // 5 trex
"Skul", // 6 skull
"Cros", // 7 cross
"Bolt", // 8 lightning
"Hat", // 9 tophat
"Moto", // 10 motorcycle
"Leaf", // 11 seedling
"AU", // 12 flag_au
"Umbr", // 13 umbrella
"Eye", // 14 nazar
"Glob", // 15 globe
"Rad", // 16 radioactive
"Cow", // 17 cow
"ET", // 18 alien
"Inv", // 19 invader
"Dagr", // 20 dagger
"Grim", // 21 grimace
"Mtn", // 22 mountain
"End", // 23 end_arrow
"Ring", // 24 hollow_circle
"Drag", // 25 dragon
"Web", // 26 globe_meridians
"Eggp", // 27 eggplant
"Shld", // 28 shield
"Gogl", // 29 goggles
"Lzrd", // 30 lizard
"Zany", // 31 zany_face
"Roo", // 32 kangaroo
"Fthr", // 33 feather
"Sun", // 34 bright
"Wave", // 35 part_alt
"Boat", // 36 motorboat
"Domi", // 37 domino
"Dish", // 38 satellite
"Pass", // 39 customs
"Cowb", // 40 cowboy
"Whl", // 41 wheel
"Koal", // 42 koala
"Knob", // 43 control_knobs
"Pch", // 44 peach
"Race", // 45 racing_car
"Sad", // 1 frown
"Cry", // 2 loudly_crying
"Grim", // 3 grimace
"Zany", // 4 zany_face
"Cowb", // 5 cowboy
// Thumbsup + heart
"Like", // 6 thumbsup
"Love", // 7 heart
// Everything else
"WiFi", // 8 wireless
"Inf", // 9 infinity
"Rex", // 10 trex
"Skul", // 11 skull
"Cros", // 12 cross
"Bolt", // 13 lightning
"Hat", // 14 tophat
"Moto", // 15 motorcycle
"Leaf", // 16 seedling
"AU", // 17 flag_au
"Umbr", // 18 umbrella
"Eye", // 19 nazar
"Glob", // 20 globe
"Rad", // 21 radioactive
"Cow", // 22 cow
"ET", // 23 alien
"Inv", // 24 invader
"Dagr", // 25 dagger
"Mtn", // 26 mountain
"End", // 27 end_arrow
"Ring", // 28 hollow_circle
"Drag", // 29 dragon
"Web", // 30 globe_meridians
"Eggp", // 31 eggplant
"Shld", // 32 shield
"Gogl", // 33 goggles
"Lzrd", // 34 lizard
"Roo", // 35 kangaroo
"Fthr", // 36 feather
"Sun", // 37 bright
"Wave", // 38 part_alt
"Boat", // 39 motorboat
"Domi", // 40 domino
"Dish", // 41 satellite
"Pass", // 42 customs
"Whl", // 43 wheel
"Koal", // 44 koala
"Knob", // 45 control_knobs
"Pch", // 46 peach
"Race", // 47 racing_car
"Mous", // 48 mouse
"Shrm", // 49 mushroom
"Bio", // 50 biohazard
"Pnda", // 51 panda
"Bang", // 52 anger
"DrgF", // 53 dragon_face
"Pagr", // 54 pager
"Bee", // 55 bee
"Bulb", // 56 bulb
"Cat", // 57 cat
"Flur", // 58 fleur
"Moon", // 59 moon
"Cafe", // 60 coffee
"Toth", // 61 tooth
"Prtz", // 62 pretzel
"Abac", // 63 abacus
"Moai", // 64 moai
"Hiii", // 65 tipping
"Hedg", // 66 hedgehog
"Diam", // 67 diamond_suit
"Spde", // 68 spade_suit
"Piza", // 69 pizza
"Luck", // 70 four_leaf_clover
"Cld", // 71 cloud
"Rckt", // 72 rocket
"HFC", // 73 passport_control
"Star", // 74 eight_spoked_asterisk
"Sig", // 75 signal_strength
};
struct EmojiPicker {
@@ -86,13 +119,23 @@ struct EmojiPicker {
switch (key) {
case 'w': case 'W': case 0xF2:
if (row > 0) cursor -= EMOJI_PICKER_COLS;
if (row > 0) {
cursor -= EMOJI_PICKER_COLS;
} else {
// Wrap to last row, same column
int target = (EMOJI_PICKER_TOTAL_ROWS - 1) * EMOJI_PICKER_COLS + col;
cursor = (target >= EMOJI_COUNT) ? EMOJI_COUNT - 1 : target;
}
break;
case 's': case 'S': case 0xF1:
if (cursor + EMOJI_PICKER_COLS < EMOJI_COUNT)
if (cursor + EMOJI_PICKER_COLS < EMOJI_COUNT) {
cursor += EMOJI_PICKER_COLS;
else if (row < EMOJI_PICKER_TOTAL_ROWS - 1)
} else if (row < EMOJI_PICKER_TOTAL_ROWS - 1) {
cursor = EMOJI_COUNT - 1;
} else {
// Wrap to first row, same column
cursor = col;
}
break;
case 'a': case 'A':
if (cursor > 0) cursor--;
@@ -0,0 +1,63 @@
#pragma once
// =============================================================================
// HomeIcons — 12x12 icon sprites for T5S3 home screen tiles
// MSB-first, 2 bytes per row (same format as emoji sprites)
// =============================================================================
#include <stdint.h>
#ifdef ESP32
#include <pgmspace.h>
#endif
#define HOME_ICON_W 12
#define HOME_ICON_H 12
// ✉️ Envelope (Messages)
static const uint8_t icon_envelope[] PROGMEM = {
0xFF,0xF0, 0x80,0x10, 0xC0,0x30, 0xA0,0x50, 0x90,0x90, 0x89,0x10,
0x86,0x10, 0x80,0x10, 0x80,0x10, 0x80,0x10, 0x80,0x10, 0xFF,0xF0,
};
// 👥 People (Contacts)
static const uint8_t icon_people[] PROGMEM = {
0x31,0x80, 0x7B,0xC0, 0x7B,0xC0, 0x31,0x80, 0x00,0x00, 0x7B,0xC0,
0xFD,0xE0, 0xFD,0xE0, 0x7B,0xC0, 0x00,0x00, 0x00,0x00, 0x00,0x00,
};
// 🎚 Sliders (Settings)
static const uint8_t icon_gear[] PROGMEM = {
0x22,0x20, 0x22,0x20, 0x72,0x70, 0x72,0x70, 0x27,0x20, 0x27,0x20,
0x22,0x20, 0x72,0x20, 0x72,0x70, 0x22,0x70, 0x22,0x20, 0x22,0x20,
};
// 📖 Book (Reader)
static const uint8_t icon_book[] PROGMEM = {
0x7F,0xC0, 0x41,0x40, 0x5D,0x40, 0x5D,0x40, 0x41,0x40, 0x5D,0x40,
0x5D,0x40, 0x41,0x40, 0x5D,0x40, 0x41,0x40, 0x7F,0xC0, 0x00,0x00,
};
// 🗒 Notepad (Notes)
static const uint8_t icon_notepad[] PROGMEM = {
0x3F,0xC0, 0x20,0x40, 0x2F,0x40, 0x20,0x40, 0x2F,0x40, 0x20,0x40,
0x2F,0x40, 0x20,0x40, 0x2F,0x40, 0x20,0x40, 0x3F,0xC0, 0x00,0x00,
};
// 🔍 Magnifying glass (Discover)
static const uint8_t icon_search[] PROGMEM = {
0x3C,0x00, 0x42,0x00, 0x81,0x00, 0x81,0x00, 0x81,0x00, 0x42,0x00,
0x3C,0x00, 0x03,0x00, 0x01,0x80, 0x00,0xC0, 0x00,0x40, 0x00,0x00,
};
// ⏰ Alarm Clock (AlarmScreen) — 12x12 home tile icon
static const uint8_t icon_alarm[] PROGMEM = {
0x40,0x40, 0x9E,0x20, 0x20,0x80, 0x44,0x40, 0x44,0x40, 0x46,0x40,
0x40,0x40, 0x20,0x80, 0x1F,0x00, 0x00,0x00, 0x20,0x40, 0x40,0x20,
};
// 🔔 Bell — 7x8 status bar indicator (alarm enabled)
// MSB-first, 1 byte per row
#define BELL_ICON_W 7
#define BELL_ICON_H 8
static const uint8_t icon_bell_small[] PROGMEM = {
0x10, 0x38, 0x7C, 0x7C, 0x7C, 0xFE, 0x00, 0x10,
};
@@ -0,0 +1,538 @@
#pragma once
// =============================================================================
// VirtualKeyboard — On-screen QWERTY keyboard for T5S3 (touch-only devices)
//
// Renders in virtual coordinate space (128×128). Touch hit testing converts
// physical GT911 coords (960×540) to virtual coords.
//
// Usage:
// keyboard.open("To: General", "", 137); // label, initial text, max len
// keyboard.render(display); // in render loop
// keyboard.handleTap(vx, vy); // on touch tap (virtual coords)
// if (keyboard.status() == VKB_SUBMITTED) { ... keyboard.getText() ... }
// =============================================================================
#if defined(LilyGo_T5S3_EPaper_Pro)
#ifndef VIRTUAL_KEYBOARD_H
#define VIRTUAL_KEYBOARD_H
#include <Arduino.h>
#include <helpers/ui/DisplayDriver.h>
#include "EmojiSprites.h"
enum VKBStatus { VKB_EDITING, VKB_SUBMITTED, VKB_CANCELLED };
// What the keyboard is being used for (dispatch on submit)
enum VKBPurpose {
VKB_CHANNEL_MSG, // Send to channel
VKB_DM, // Direct message to contact
VKB_ADMIN_PASSWORD, // Repeater admin login
VKB_ADMIN_CLI, // Repeater admin CLI command
VKB_NOTES, // Insert text into notes
VKB_SETTINGS_NAME, // Edit node name
VKB_SETTINGS_TEXT, // Generic settings text edit (channel name, freq, APN)
VKB_WIFI_PASSWORD, // WiFi password entry (settings screen)
#ifdef MECK_WEB_READER
VKB_WEB_URL, // Web reader URL entry
VKB_WEB_SEARCH, // Web reader DuckDuckGo search query
VKB_WEB_WIFI_PASS, // Web reader WiFi password
VKB_WEB_LINK, // Web reader link number entry
#endif
VKB_TEXT_PAGE, // Text reader: go to page number
};
class VirtualKeyboard {
public:
static const int MAX_TEXT = 140;
VirtualKeyboard() : _status(VKB_CANCELLED), _purpose(VKB_CHANNEL_MSG),
_contextIdx(0), _textLen(0), _shifted(false), _symbols(false),
_emojiMode(false), _emojiScroll(0) {
_text[0] = '\0';
_label[0] = '\0';
}
void open(VKBPurpose purpose, const char* label, const char* initial, int maxLen, int contextIdx = 0) {
_purpose = purpose;
_contextIdx = contextIdx;
_status = VKB_EDITING;
_shifted = false;
_symbols = false;
_emojiMode = false;
_emojiScroll = 0;
_maxLen = (maxLen > 0 && maxLen < MAX_TEXT) ? maxLen : MAX_TEXT;
strncpy(_label, label, sizeof(_label) - 1);
_label[sizeof(_label) - 1] = '\0';
if (initial && initial[0]) {
strncpy(_text, initial, _maxLen);
_text[_maxLen] = '\0';
_textLen = strlen(_text);
} else {
_text[0] = '\0';
_textLen = 0;
}
}
VKBStatus status() const { return _status; }
VKBPurpose purpose() const { return _purpose; }
int contextIdx() const { return _contextIdx; }
const char* getText() const { return _text; }
int getTextLen() const { return _textLen; }
bool isActive() const { return _status == VKB_EDITING; }
// --- Render keyboard + input field ---
void render(DisplayDriver& display) {
// Header label (To: channel, DM: name, etc.)
display.setTextSize(0);
display.setColor(DisplayDriver::GREEN);
display.setCursor(2, 0);
display.print(_label);
// Input text field
display.setColor(DisplayDriver::LIGHT);
display.drawRect(0, 10, 128, 18); // Border
// Render text with inline emoji sprites
renderTextField(display);
// Character count
{
char countBuf[12];
snprintf(countBuf, sizeof(countBuf), "%d/%d", _textLen, _maxLen);
int cw = display.getTextWidth(countBuf);
display.setCursor(128 - cw - 2, 0);
display.setColor(DisplayDriver::LIGHT);
display.print(countBuf);
}
// Separator
display.drawRect(0, 30, 128, 1);
if (_emojiMode) {
renderEmojiGrid(display);
return;
}
// --- Draw keyboard rows ---
const char* const* layout = getLayout();
for (int row = 0; row < 3; row++) {
int numKeys = strlen(layout[row]);
int rowY = KEY_START_Y + row * (KEY_H + KEY_GAP);
// Calculate key width and starting X for this row
int totalW = numKeys * KEY_W + (numKeys - 1) * KEY_GAP;
int startX = (128 - totalW) / 2;
for (int k = 0; k < numKeys; k++) {
int kx = startX + k * (KEY_W + KEY_GAP);
char ch = layout[row][k];
// Draw key background (inverted for special keys)
bool special = (ch == '<' || ch == '^' || ch == '~' || ch == '>' || ch == '\x01');
if (special) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(kx, rowY + 1, KEY_W, KEY_H - 1);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
display.drawRect(kx, rowY + 1, KEY_W, KEY_H - 1);
}
// Draw key label
char keyLabel[2] = { ch, '\0' };
// Remap special chars to display labels
if (ch == '<') keyLabel[0] = '<'; // Backspace
if (ch == '^') keyLabel[0] = '^'; // Shift
if (ch == '>') keyLabel[0] = '>'; // Enter
if (ch == '~') {
// Space key — don't draw individual label
} else if (ch == '\x01') {
// Symbol toggle in row — show "ab" hint
int lx = kx + KEY_W / 2 - display.getTextWidth("ab") / 2;
display.setCursor(lx, rowY + 2);
display.print("ab");
} else {
int lx = kx + KEY_W / 2 - display.getTextWidth(keyLabel) / 2;
display.setCursor(lx, rowY + 2);
display.print(keyLabel);
}
// Restore color
display.setColor(DisplayDriver::LIGHT);
}
}
// Draw row 4 with variable-width keys
int r4y = KEY_START_Y + 3 * (KEY_H + KEY_GAP);
drawRow4(display, r4y);
// Shift/symbol indicator
display.setTextSize(0);
display.setColor(DisplayDriver::GREEN);
if (_shifted) {
display.setCursor(2, 126);
display.print("SHIFT");
} else if (_symbols) {
display.setCursor(2, 126);
display.print("123");
}
}
// --- Handle touch tap (virtual coordinates) ---
// Returns true if the tap was consumed
bool handleTap(int vx, int vy) {
if (_status != VKB_EDITING) return false;
if (_emojiMode) return handleEmojiTap(vx, vy);
// Check keyboard rows 0-2
const char* const* layout = getLayout();
for (int row = 0; row < 3; row++) {
int numKeys = strlen(layout[row]);
int rowY = KEY_START_Y + row * (KEY_H + KEY_GAP);
if (vy < rowY || vy >= rowY + KEY_H) continue;
int totalW = numKeys * KEY_W + (numKeys - 1) * KEY_GAP;
int startX = (128 - totalW) / 2;
for (int k = 0; k < numKeys; k++) {
int kx = startX + k * (KEY_W + KEY_GAP);
if (vx >= kx && vx < kx + KEY_W) {
char ch = layout[row][k];
processKey(ch);
return true;
}
}
return true; // Tap was in row area but between keys — consume
}
// Check row 4 (variable width keys)
int r4y = KEY_START_Y + 3 * (KEY_H + KEY_GAP);
if (vy >= r4y && vy < r4y + KEY_H) {
return handleRow4Tap(vx);
}
return false;
}
// Swipe up on keyboard = cancel
void cancel() { _status = VKB_CANCELLED; }
// --- Feed a raw ASCII character from an external physical keyboard ---
// Maps standard ASCII control chars to internal VKB actions.
// Returns true if the character was consumed.
#ifdef MECK_CARDKB
bool feedChar(char c) {
if (_status != VKB_EDITING) return false;
switch (c) {
case '\r': processKey('>'); return true; // Enter → submit
case '\b': processKey('<'); return true; // Backspace
case 0x7F: processKey('<'); return true; // Delete → backspace
case 0x1B: _status = VKB_CANCELLED; return true; // ESC → cancel
case ' ': processKey('~'); return true; // Space
default:
// Printable ASCII → insert directly
if (c >= 0x20 && c <= 0x7E) {
if (_textLen < _maxLen) {
_text[_textLen++] = c;
_text[_textLen] = '\0';
}
return true;
}
return false; // Non-printable / nav keys — not consumed
}
}
#endif
private:
VKBStatus _status;
VKBPurpose _purpose;
int _contextIdx;
char _text[MAX_TEXT + 1];
int _textLen;
int _maxLen;
char _label[40];
bool _shifted;
bool _symbols;
bool _emojiMode;
int _emojiScroll;
// Emoji grid constants (virtual coords)
static const int EMJ_COLS = 8;
static const int EMJ_CELL = 15; // 12px sprite + 3px gap
static const int EMJ_GRID_X = 4;
static const int EMJ_GRID_Y = 34;
static const int EMJ_VIS_ROWS = 5;
int emojiTotalRows() const { return (EMOJI_COUNT + EMJ_COLS - 1) / EMJ_COLS; }
int emojiMaxScroll() const { int m = emojiTotalRows() - EMJ_VIS_ROWS; return m < 0 ? 0 : m; }
void renderEmojiGrid(DisplayDriver& display) {
display.setTextSize(0);
for (int vr = 0; vr < EMJ_VIS_ROWS; vr++) {
int absRow = _emojiScroll + vr;
if (absRow >= emojiTotalRows()) break;
for (int col = 0; col < EMJ_COLS; col++) {
int idx = absRow * EMJ_COLS + col;
if (idx >= EMOJI_COUNT) break;
int cx = EMJ_GRID_X + col * EMJ_CELL;
int cy = EMJ_GRID_Y + vr * EMJ_CELL;
display.setColor(DisplayDriver::LIGHT);
const uint8_t* sprite = (const uint8_t*)pgm_read_ptr(&EMOJI_SPRITES_LG[idx]);
if (sprite) {
display.drawXbm(cx + 1, cy + 1, sprite, EMOJI_LG_W, EMOJI_LG_H);
}
}
}
// Footer: [Back] [▲] page/total [▼]
int fy = EMJ_GRID_Y + EMJ_VIS_ROWS * EMJ_CELL + 2;
display.setColor(DisplayDriver::LIGHT);
display.drawRect(0, fy - 1, 128, 1);
// Back button (inverted)
display.fillRect(4, fy + 1, 30, 12);
display.setColor(DisplayDriver::DARK);
int bw = display.getTextWidth("Back");
display.setCursor(4 + (30 - bw) / 2, fy + 2);
display.print("Back");
display.setColor(DisplayDriver::LIGHT);
// Scroll arrows (only if scrollable)
if (emojiTotalRows() > EMJ_VIS_ROWS) {
// Up arrow
if (_emojiScroll > 0) {
display.fillRect(50, fy + 1, 12, 12);
display.setColor(DisplayDriver::DARK);
display.setCursor(53, fy + 2);
display.print("^");
display.setColor(DisplayDriver::LIGHT);
}
// Page info
char pg[8];
snprintf(pg, sizeof(pg), "%d/%d", _emojiScroll + 1, emojiMaxScroll() + 1);
int pw = display.getTextWidth(pg);
display.setCursor(75 - pw / 2, fy + 2);
display.print(pg);
// Down arrow
if (_emojiScroll < emojiMaxScroll()) {
display.fillRect(90, fy + 1, 12, 12);
display.setColor(DisplayDriver::DARK);
display.setCursor(93, fy + 2);
display.print("v");
display.setColor(DisplayDriver::LIGHT);
}
}
}
bool handleEmojiTap(int vx, int vy) {
int fy = EMJ_GRID_Y + EMJ_VIS_ROWS * EMJ_CELL + 2;
// Footer area
if (vy >= fy) {
if (vx >= 4 && vx < 34) {
// Back button
_emojiMode = false;
return true;
}
if (vx >= 50 && vx < 62 && _emojiScroll > 0) {
_emojiScroll--;
return true;
}
if (vx >= 90 && vx < 102 && _emojiScroll < emojiMaxScroll()) {
_emojiScroll++;
return true;
}
return true; // Consume tap in footer
}
// Grid area
if (vy >= EMJ_GRID_Y && vy < EMJ_GRID_Y + EMJ_VIS_ROWS * EMJ_CELL) {
int col = (vx - EMJ_GRID_X) / EMJ_CELL;
int vr = (vy - EMJ_GRID_Y) / EMJ_CELL;
if (col < 0 || col >= EMJ_COLS || vr < 0 || vr >= EMJ_VIS_ROWS) return true;
int idx = (_emojiScroll + vr) * EMJ_COLS + col;
if (idx >= 0 && idx < EMOJI_COUNT) {
insertEmoji(idx);
_emojiMode = false;
}
return true;
}
return true; // Consume any tap while in emoji mode
}
void insertEmoji(int idx) {
// Insert as UTF-8 directly (not escape bytes) so sent messages are valid
uint8_t utf8[8];
int len = emojiEncodeUtf8(EMOJI_CODEPOINTS[idx].cp, utf8);
if (EMOJI_CODEPOINTS[idx].cp2 != 0)
len += emojiEncodeUtf8(EMOJI_CODEPOINTS[idx].cp2, utf8 + len);
if (_textLen + len > _maxLen) return;
memcpy(_text + _textLen, utf8, len);
_textLen += len;
_text[_textLen] = '\0';
}
// Render text field with inline emoji sprites (10×10)
void renderTextField(DisplayDriver& display) {
// Convert UTF-8 emoji to escape bytes for sprite lookup
char sanitized[MAX_TEXT + 1];
emojiSanitize(_text, sanitized, sizeof(sanitized));
int x = 2;
int maxX = 124;
display.setColor(DisplayDriver::LIGHT);
display.setTextSize(0);
for (int i = 0; sanitized[i] && x < maxX; i++) {
uint8_t b = (uint8_t)sanitized[i];
if (b == EMOJI_PAD_BYTE) continue;
if (isEmojiEscape(b)) {
const uint8_t* sprite = getEmojiSpriteSm(b);
if (sprite && x + EMOJI_SM_W < maxX) {
display.drawXbm(x, 14, sprite, EMOJI_SM_W, EMOJI_SM_H);
x += EMOJI_SM_W + 1;
}
} else {
char ch[2] = { (char)b, '\0' };
display.setCursor(x, 12);
display.print(ch);
x += display.getTextWidth(ch);
}
}
// Blinking cursor
if (x < maxX) {
display.setCursor(x, 12);
display.print("_");
}
}
// Layout constants (virtual coords)
static const int KEY_W = 11;
static const int KEY_H = 19;
static const int KEY_GAP = 1;
static const int KEY_START_Y = 34;
// Key layouts — rows 0-2 as char arrays
// Special: ^ = shift, < = backspace, \x01 = sym toggle, \x02 = emoji, > = enter, ~ = space
const char* const* getLayout() const {
static const char* const lower[3] = { "qwertyuiop", "asdfghjkl", "^zxcvbnm<" };
static const char* const upper[3] = { "QWERTYUIOP", "ASDFGHJKL", "^ZXCVBNM<" };
static const char* const syms[3] = { "1234567890", "-/:;()@$&#", "\x01.,?!'\"_<" };
return _symbols ? syms : (_shifted ? upper : lower);
}
// Row 4: variable-width keys [#/ABC] [,] [$] [SPACE] [.] [Enter]
// Defined by physical zones, not the char-array approach
struct R4Key { int x; int w; char ch; const char* label; };
void drawRow4(DisplayDriver& display, int y) {
const R4Key keys[] = {
{ 4, 20, '\x01', _symbols ? "ABC" : "123" },
{ 26, 11, ',', "," },
{ 39, 11, '\x02', "$" },
{ 52, 37, '~', "space" },
{ 91, 11, '.', "." },
{ 104, 20, '>', "Send" }
};
for (int i = 0; i < 6; i++) {
bool special = (keys[i].ch == '\x01' || keys[i].ch == '>' || keys[i].ch == '\x02');
if (special) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(keys[i].x, y + 1, keys[i].w, KEY_H - 1);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
display.drawRect(keys[i].x, y + 1, keys[i].w, KEY_H - 1);
}
// Center label in key
display.setTextSize(0);
int lw = display.getTextWidth(keys[i].label);
int lx = keys[i].x + (keys[i].w - lw) / 2;
display.setCursor(lx, y + 2);
display.print(keys[i].label);
display.setColor(DisplayDriver::LIGHT);
}
}
bool handleRow4Tap(int vx) {
const R4Key keys[] = {
{ 4, 20, '\x01', nullptr },
{ 26, 11, ',', nullptr },
{ 39, 11, '\x02', nullptr },
{ 52, 37, '~', nullptr },
{ 91, 11, '.', nullptr },
{ 104, 20, '>', nullptr }
};
for (int i = 0; i < 6; i++) {
if (vx >= keys[i].x && vx < keys[i].x + keys[i].w) {
processKey(keys[i].ch);
return true;
}
}
return true; // Consume tap in row area
}
void processKey(char ch) {
if (ch == '^') {
// Shift toggle
_shifted = !_shifted;
_symbols = false;
} else if (ch == '\x01') {
// Symbol/letter toggle
_symbols = !_symbols;
_shifted = false;
} else if (ch == '\x02') {
// Emoji picker toggle
_emojiMode = !_emojiMode;
_emojiScroll = 0;
} else if (ch == '<') {
// Backspace — UTF-8 aware (walk back past continuation bytes 10xxxxxx)
if (_textLen > 0) {
_textLen--;
while (_textLen > 0 && ((uint8_t)_text[_textLen] & 0xC0) == 0x80) {
_textLen--;
}
_text[_textLen] = '\0';
}
} else if (ch == '>') {
// Enter/Send
_status = VKB_SUBMITTED;
} else if (ch == '~') {
// Space
if (_textLen < _maxLen) {
_text[_textLen++] = ' ';
_text[_textLen] = '\0';
}
} else {
// Regular character
if (_textLen < _maxLen) {
_text[_textLen++] = ch;
_text[_textLen] = '\0';
// Auto-unshift after typing one character
if (_shifted) _shifted = false;
}
}
}
};
#endif // VIRTUAL_KEYBOARD_H
#endif // LilyGo_T5S3_EPaper_Pro
@@ -0,0 +1,16 @@
// WebReaderDeps.cpp
// -----------------------------------------------------------------------
// PlatformIO library dependency finder (LDF) hint file.
//
// The web reader's WiFi/HTTP includes live in WebReaderScreen.h (header-only),
// but PlatformIO's LDF can't always trace framework library dependencies
// through conditional #include chains in headers. This .cpp file exposes
// the includes at the top level where the scanner reliably finds them.
//
// No actual code here — just #include directives for the dependency finder.
// -----------------------------------------------------------------------
#ifdef MECK_WEB_READER
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#endif
+561 -71
View File
@@ -1,8 +1,11 @@
#include "UITask.h"
#include <helpers/TxtDataHelpers.h>
#include "../MyMesh.h"
#include "NotesScreen.h"
#include "RepeaterAdminScreen.h"
#include "MapScreen.h"
#include "target.h"
#ifdef WIFI_SSID
#if defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
#include <WiFi.h>
#endif
@@ -34,11 +37,18 @@
#include "ContactsScreen.h"
#include "TextReaderScreen.h"
#include "SettingsScreen.h"
#ifdef MECK_AUDIO_VARIANT
#include "AudiobookPlayerScreen.h"
#endif
#ifdef HAS_4G_MODEM
#include "SMSScreen.h"
#include "ModemManager.h"
#endif
class SplashScreen : public UIScreen {
UITask* _task;
unsigned long dismiss_after;
char _version_info[12];
char _version_info[24];
public:
SplashScreen(UITask* task) : _task(task) {
@@ -85,13 +95,20 @@ class HomeScreen : public UIScreen {
FIRST,
RECENT,
RADIO,
#ifdef BLE_PIN_CODE
BLUETOOTH,
#elif defined(MECK_WIFI_COMPANION)
WIFI_STATUS,
#endif
ADVERT,
#if ENV_INCLUDE_GPS == 1
GPS,
#endif
#if UI_SENSORS_PAGE == 1
SENSORS,
#endif
#if HAS_BQ27220
BATTERY,
#endif
SHUTDOWN,
Count // keep as last
@@ -103,12 +120,13 @@ class HomeScreen : public UIScreen {
NodePrefs* _node_prefs;
uint8_t _page;
bool _shutdown_init;
unsigned long _shutdown_at; // earliest time to proceed with shutdown (after e-ink refresh)
bool _editing_utc;
int8_t _saved_utc_offset; // for cancel/undo
AdvertPath recent[UI_RECENT_LIST_SIZE];
void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) {
void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts, int* outIconX = nullptr) {
// Use voltage-based estimation to match BLE app readings
uint8_t batteryPercentage = 0;
if (batteryMilliVolts > 0) {
@@ -137,6 +155,8 @@ void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts)
int iconX = display.width() - totalWidth;
int iconY = 0; // vertically align with node name text
if (outIconX) *outIconX = iconX;
// battery outline
display.drawRect(iconX, iconY, iconWidth, iconHeight);
@@ -156,6 +176,24 @@ void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts)
display.setTextSize(1); // restore default text size
}
#ifdef MECK_AUDIO_VARIANT
// ---- Audio background playback indicator ----
// Shows a small play symbol to the left of the battery icon when an
// audiobook is actively playing in the background.
// Uses the font renderer (not manual pixel drawing) since it handles
// the e-ink coordinate scaling correctly.
void renderAudioIndicator(DisplayDriver& display, int batteryLeftX) {
if (!_task->isAudioPlayingInBackground()) return;
display.setColor(DisplayDriver::GREEN);
display.setTextSize(0); // tiny font (same as clock & battery %)
int x = batteryLeftX - display.getTextWidth(">>") - 2;
display.setCursor(x, -3); // align vertically with battery text
display.print(">>");
display.setTextSize(1); // restore
}
#endif
CayenneLPP sensors_lpp;
int sensors_nb = 0;
bool sensors_scroll = false;
@@ -186,7 +224,7 @@ void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts)
public:
HomeScreen(UITask* task, mesh::RTCClock* rtc, SensorManager* sensors, NodePrefs* node_prefs)
: _task(task), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _page(0),
_shutdown_init(false), _editing_utc(false), _saved_utc_offset(0), sensors_lpp(200) { }
_shutdown_init(false), _shutdown_at(0), _editing_utc(false), _saved_utc_offset(0), sensors_lpp(200) { }
bool isEditingUTC() const { return _editing_utc; }
void cancelEditUTC() {
@@ -197,23 +235,31 @@ public:
}
void poll() override {
if (_shutdown_init && !_task->isButtonPressed()) { // must wait for USR button to be released
if (_shutdown_init && millis() >= _shutdown_at && !_task->isButtonPressed()) {
_task->shutdown();
}
}
int render(DisplayDriver& display) override {
char tmp[80];
// node name
display.setTextSize(1);
// node name (tinyfont to avoid overlapping clock)
display.setTextSize(0);
display.setColor(DisplayDriver::GREEN);
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, -3);
display.print(filtered_name);
// battery voltage
#ifdef MECK_AUDIO_VARIANT
int battLeftX = display.width(); // default if battery doesn't render
renderBatteryIndicator(display, _task->getBattMilliVolts(), &battLeftX);
// audio background playback indicator (>> icon next to battery)
renderAudioIndicator(display, battLeftX);
#else
renderBatteryIndicator(display, _task->getBattMilliVolts());
#endif
// centered clock (tinyfont) - only show when time is valid
{
@@ -250,28 +296,70 @@ public:
}
if (_page == HomePage::FIRST) {
int y = 20;
display.setColor(DisplayDriver::YELLOW);
display.setTextSize(2);
sprintf(tmp, "MSG: %d", _task->getMsgCount());
display.drawTextCentered(display.width() / 2, 20, tmp);
sprintf(tmp, "MSG: %d", _task->getUnreadMsgCount());
display.drawTextCentered(display.width() / 2, y, tmp);
y += 18;
#ifdef WIFI_SSID
#if defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
IPAddress ip = WiFi.localIP();
snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 54, tmp);
if (ip != IPAddress(0,0,0,0)) {
snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d:%d", ip[0], ip[1], ip[2], ip[3], TCP_PORT);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, y, tmp);
y += 12;
}
#endif
#if defined(BLE_PIN_CODE) || defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
if (_task->hasConnection()) {
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 43, "< Connected >");
} else if (the_mesh.getBLEPin() != 0) { // BT pin
display.drawTextCentered(display.width() / 2, y, "< Connected >");
y += 12;
#ifdef BLE_PIN_CODE
} else if (_task->isSerialEnabled() && the_mesh.getBLEPin() != 0) {
display.setColor(DisplayDriver::RED);
display.setTextSize(2);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
display.drawTextCentered(display.width() / 2, 43, tmp);
display.drawTextCentered(display.width() / 2, y, tmp);
y += 18;
#endif
}
#endif
// Menu shortcuts - tinyfont monospaced grid
y += 6;
display.setColor(DisplayDriver::LIGHT);
display.setTextSize(0); // tinyfont 6x8 monospaced
display.drawTextCentered(display.width() / 2, y, "Press:");
y += 12;
display.drawTextCentered(display.width() / 2, y, "[M] Messages [C] Contacts ");
y += 10;
display.drawTextCentered(display.width() / 2, y, "[N] Notes [S] Settings ");
y += 10;
display.drawTextCentered(display.width() / 2, y, "[E] Reader [G] Maps ");
y += 10;
#if defined(HAS_4G_MODEM) && defined(MECK_WEB_READER)
display.drawTextCentered(display.width() / 2, y, "[T] Phone [B] Browser ");
#elif defined(HAS_4G_MODEM)
display.drawTextCentered(display.width() / 2, y, "[T] Phone ");
#elif defined(MECK_AUDIO_VARIANT) && defined(MECK_WEB_READER)
display.drawTextCentered(display.width() / 2, y, "[P] Audiobooks [B] Browser ");
#elif defined(MECK_AUDIO_VARIANT)
display.drawTextCentered(display.width() / 2, y, "[P] Audiobooks ");
#elif defined(MECK_WEB_READER)
display.drawTextCentered(display.width() / 2, y, "[B] Browser ");
#else
y -= 10; // reclaim the row for standalone
#endif
y += 14;
// Nav hint
display.setColor(DisplayDriver::GREEN);
display.drawTextCentered(display.width() / 2, y, "Press A/D to cycle home views");
display.setTextSize(1); // restore
} else if (_page == HomePage::RECENT) {
the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE);
display.setColor(DisplayDriver::GREEN);
@@ -316,34 +404,83 @@ public:
display.setCursor(0, 53);
sprintf(tmp, "Noise floor: %d", radio_driver.getNoiseFloor());
display.print(tmp);
#ifdef BLE_PIN_CODE
} else if (_page == HomePage::BLUETOOTH) {
display.setColor(DisplayDriver::GREEN);
display.drawXbm((display.width() - 32) / 2, 18,
_task->isSerialEnabled() ? bluetooth_on : bluetooth_off,
32, 32);
if (_task->hasConnection()) {
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 53, "< Connected >");
} else if (_task->isSerialEnabled() && the_mesh.getBLEPin() != 0) {
display.setColor(DisplayDriver::RED);
display.setTextSize(2);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
display.drawTextCentered(display.width() / 2, 53, tmp);
}
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL);
display.drawTextCentered(display.width() / 2, 72, "toggle: " PRESS_LABEL);
#endif
#ifdef MECK_WIFI_COMPANION
} else if (_page == HomePage::WIFI_STATUS) {
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, 18, "WiFi Companion");
int wy = 36;
display.setTextSize(0);
if (WiFi.status() == WL_CONNECTED) {
display.setColor(DisplayDriver::GREEN);
snprintf(tmp, sizeof(tmp), "SSID: %s", WiFi.SSID().c_str());
display.drawTextCentered(display.width() / 2, wy, tmp);
wy += 10;
IPAddress ip = WiFi.localIP();
snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
display.drawTextCentered(display.width() / 2, wy, tmp);
wy += 10;
snprintf(tmp, sizeof(tmp), "Port: %d", TCP_PORT);
display.drawTextCentered(display.width() / 2, wy, tmp);
wy += 12;
if (_task->hasConnection()) {
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, wy, "< App Connected >");
} else {
display.setColor(DisplayDriver::YELLOW);
display.setTextSize(1);
display.drawTextCentered(display.width() / 2, wy, "Waiting for app...");
}
} else {
display.setColor(DisplayDriver::RED);
display.drawTextCentered(display.width() / 2, wy, "Not connected");
wy += 12;
display.setColor(DisplayDriver::LIGHT);
display.drawTextCentered(display.width() / 2, wy, "Configure in Settings");
}
display.setTextSize(1);
#endif
} else if (_page == HomePage::ADVERT) {
display.setColor(DisplayDriver::GREEN);
display.drawXbm((display.width() - 32) / 2, 18, advert_icon, 32, 32);
display.drawTextCentered(display.width() / 2, 64 - 11, "advert: " PRESS_LABEL);
#if ENV_INCLUDE_GPS == 1
} else if (_page == HomePage::GPS) {
extern GPSStreamCounter gpsStream;
LocationProvider* nmea = sensors.getLocationProvider();
char buf[50];
int y = 18;
bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH);
if (gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
// GPS state line
if (!_node_prefs->gps_enabled) {
strcpy(buf, "gps off");
} else {
strcpy(buf, gps_state ? "gps on" : "gps off");
strcpy(buf, "gps on");
}
#else
strcpy(buf, gps_state ? "gps on" : "gps off");
#endif
display.drawTextLeftAlign(0, y, buf);
if (nmea == NULL) {
y = y + 12;
display.drawTextLeftAlign(0, y, "Can't access GPS");
@@ -355,6 +492,19 @@ public:
sprintf(buf, "%d", nmea->satellitesCount());
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
// NMEA sentence counter — confirms baud rate and data flow
display.drawTextLeftAlign(0, y, "sentences");
if (_node_prefs->gps_enabled) {
uint16_t sps = gpsStream.getSentencesPerSec();
uint32_t total = gpsStream.getSentenceCount();
sprintf(buf, "%u/s (%lu)", sps, (unsigned long)total);
} else {
strcpy(buf, "hw off");
}
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
display.drawTextLeftAlign(0, y, "pos");
sprintf(buf, "%.4f %.4f",
nmea->getLatitude()/1000000., nmea->getLongitude()/1000000.);
@@ -473,6 +623,68 @@ public:
}
if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb;
else sensors_scroll_offset = 0;
#endif
#if HAS_BQ27220
} else if (_page == HomePage::BATTERY) {
char buf[30];
int y = 18;
// Title
display.setColor(DisplayDriver::GREEN);
display.drawTextCentered(display.width() / 2, y, "Battery Gauge");
y += 12;
display.setColor(DisplayDriver::LIGHT);
// Time to empty
uint16_t tte = board.getTimeToEmpty();
display.drawTextLeftAlign(0, y, "remaining");
if (tte == 0xFFFF || tte == 0) {
strcpy(buf, tte == 0 ? "depleted" : "charging");
} else if (tte >= 60) {
sprintf(buf, "%dh %dm", tte / 60, tte % 60);
} else {
sprintf(buf, "%d min", tte);
}
display.drawTextRightAlign(display.width()-1, y, buf);
y += 10;
// Average current
int16_t avgCur = board.getAvgCurrent();
display.drawTextLeftAlign(0, y, "avg current");
sprintf(buf, "%d mA", avgCur);
display.drawTextRightAlign(display.width()-1, y, buf);
y += 10;
// Average power
int16_t avgPow = board.getAvgPower();
display.drawTextLeftAlign(0, y, "avg power");
sprintf(buf, "%d mW", avgPow);
display.drawTextRightAlign(display.width()-1, y, buf);
y += 10;
// Voltage (already available)
uint16_t mv = board.getBattMilliVolts();
display.drawTextLeftAlign(0, y, "voltage");
sprintf(buf, "%d.%03d V", mv / 1000, mv % 1000);
display.drawTextRightAlign(display.width()-1, y, buf);
y += 10;
// Remaining capacity (clamped to design capacity — gauge FCC may be
// stale from factory defaults until a full charge cycle re-learns it)
uint16_t remCap = board.getRemainingCapacity();
uint16_t desCap = board.getDesignCapacity();
if (desCap > 0 && remCap > desCap) remCap = desCap;
display.drawTextLeftAlign(0, y, "remaining cap");
sprintf(buf, "%d mAh", remCap);
display.drawTextRightAlign(display.width()-1, y, buf);
y += 10;
// Battery temperature
int16_t battTemp = board.getBattTemperature();
display.drawTextLeftAlign(0, y, "temperature");
sprintf(buf, "%d.%d C", battTemp / 10, abs(battTemp % 10));
display.drawTextRightAlign(display.width()-1, y, buf);
#endif
} else if (_page == HomePage::SHUTDOWN) {
display.setColor(DisplayDriver::GREEN);
@@ -533,6 +745,7 @@ public:
}
return true;
}
#ifdef BLE_PIN_CODE
if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) {
if (_task->isSerialEnabled()) { // toggle Bluetooth on/off
_task->disableSerial();
@@ -541,6 +754,7 @@ public:
}
return true;
}
#endif
if (c == KEY_ENTER && _page == HomePage::ADVERT) {
_task->notify(UIEventType::ack);
if (the_mesh.advert()) {
@@ -569,7 +783,8 @@ public:
}
#endif
if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) {
_shutdown_init = true; // need to wait for button to be released
_shutdown_init = true;
_shutdown_at = millis() + 900; // allow e-ink refresh (644ms) before shutdown
return true;
}
return false;
@@ -708,6 +923,17 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no
vibration.begin();
#endif
// Keyboard backlight for message flash notifications
#ifdef KB_BL_PIN
pinMode(KB_BL_PIN, OUTPUT);
digitalWrite(KB_BL_PIN, LOW);
#endif
#ifdef HAS_4G_MODEM
// Sync ringtone enabled state to modem manager
modemManager.setRingtoneEnabled(node_prefs->ringtone_enabled);
#endif
ui_started_at = millis();
_alert_expiry = 0;
@@ -717,7 +943,14 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no
channel_screen = new ChannelScreen(this, &rtc_clock);
contacts_screen = new ContactsScreen(this, &rtc_clock);
text_reader = new TextReaderScreen(this);
notes_screen = new NotesScreen(this);
settings_screen = new SettingsScreen(this, &rtc_clock, node_prefs);
repeater_admin = nullptr; // Lazy-initialized on first use to preserve heap for audio
audiobook_screen = nullptr; // Created and assigned from main.cpp if audio hardware present
#ifdef HAS_4G_MODEM
sms_screen = new SMSScreen(this);
#endif
map_screen = new MapScreen(this);
setCurrScreen(splash);
}
@@ -759,12 +992,13 @@ switch(t){
void UITask::msgRead(int msgcount) {
_msgcount = msgcount;
if (msgcount == 0) {
if (msgcount == 0 && curr == msg_preview) {
gotoHomeScreen();
}
}
void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) {
void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount,
const uint8_t* path) {
_msgcount = msgcount;
// Add to preview screen (for notifications on non-keyboard devices)
@@ -782,15 +1016,25 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i
}
}
// Add to channel history screen with channel index
((ChannelScreen *) channel_screen)->addMessage(channel_idx, path_len, from_name, text);
// Add to channel history screen with channel index and path data
((ChannelScreen *) channel_screen)->addMessage(channel_idx, path_len, from_name, text, path);
// If user is currently viewing this channel, mark it as read immediately
// (they can see the message arrive in real-time)
if (isOnChannelScreen() &&
((ChannelScreen *) channel_screen)->getViewChannelIdx() == channel_idx) {
((ChannelScreen *) channel_screen)->markChannelRead(channel_idx);
}
#if defined(LilyGo_TDeck_Pro)
// T-Deck Pro: Don't interrupt user with popup - just show brief notification
// Messages are stored in channel history, accessible via 'M' key
char alertBuf[40];
snprintf(alertBuf, sizeof(alertBuf), "New: %s", from_name);
showAlert(alertBuf, 2000);
// Suppress alert entirely on admin screen - it needs focused interaction
if (!isOnRepeaterAdmin()) {
char alertBuf[40];
snprintf(alertBuf, sizeof(alertBuf), "New: %s", from_name);
showAlert(alertBuf, 2000);
}
#else
// Other devices: Show full preview screen (legacy behavior)
setCurrScreen(msg_preview);
@@ -805,6 +1049,14 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i
_next_refresh = 100; // trigger refresh
}
}
// Keyboard flash notification
#ifdef KB_BL_PIN
if (_node_prefs->kb_flash_notify) {
digitalWrite(KB_BL_PIN, HIGH);
_kb_flash_off_at = millis() + 200; // 200ms flash
}
#endif
}
void UITask::userLedHandler() {
@@ -854,8 +1106,32 @@ void UITask::shutdown(bool restart){
if (restart) {
_board->reboot();
} else {
_display->turnOff();
// Disable BLE if active
if (_serial != NULL && _serial->isEnabled()) {
_serial->disable();
}
// Disable WiFi if active
#ifdef WIFI_SSID
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
#endif
// Disable GPS if active
#if ENV_INCLUDE_GPS == 1
{
if (_sensors != NULL && _node_prefs != NULL && _node_prefs->gps_enabled) {
_sensors->setSettingValue("gps", "0");
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, !GPS_EN_ACTIVE);
#endif
}
}
#endif
// Power off LoRa radio, display, and board
radio_driver.powerOff();
_display->turnOff();
_board->powerOff();
}
}
@@ -940,6 +1216,63 @@ void UITask::loop() {
userLedHandler();
// Turn off keyboard flash after timeout
#ifdef KB_BL_PIN
if (_kb_flash_off_at && millis() >= _kb_flash_off_at) {
#ifdef HAS_4G_MODEM
// Don't turn off LED if incoming call flash is active
if (!_incomingCallRinging) {
digitalWrite(KB_BL_PIN, LOW);
}
#else
digitalWrite(KB_BL_PIN, LOW);
#endif
_kb_flash_off_at = 0;
}
#endif
// Incoming call LED flash — rapid repeated pulse while ringing
#if defined(HAS_4G_MODEM) && defined(KB_BL_PIN)
{
bool ringing = modemManager.isRinging();
if (ringing && !_incomingCallRinging) {
// Ringing just started
_incomingCallRinging = true;
_callFlashState = false;
_nextCallFlash = 0; // Start immediately
// Wake display for incoming call
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + 60000; // Keep display on while ringing (60s)
} else if (!ringing && _incomingCallRinging) {
// Ringing stopped
_incomingCallRinging = false;
// Only turn off LED if message flash isn't also active
if (!_kb_flash_off_at) {
digitalWrite(KB_BL_PIN, LOW);
}
_callFlashState = false;
}
// Rapid LED flash while ringing (if kb_flash_notify is ON)
if (_incomingCallRinging && _node_prefs->kb_flash_notify) {
unsigned long now = millis();
if (now >= _nextCallFlash) {
_callFlashState = !_callFlashState;
digitalWrite(KB_BL_PIN, _callFlashState ? HIGH : LOW);
// 250ms on, 250ms off — fast pulse to distinguish from single msg flash
_nextCallFlash = now + 250;
}
// Extend auto-off while ringing
_auto_off = millis() + 60000;
}
}
#endif
#ifdef PIN_BUZZER
if (buzzer.isPlaying()) buzzer.loop();
#endif
@@ -980,10 +1313,11 @@ if (curr) curr->poll();
if (millis() > next_batt_chck) {
uint16_t milliVolts = getBattMilliVolts();
if (milliVolts > 0 && milliVolts < AUTO_SHUTDOWN_MILLIVOLTS) {
_low_batt_count++;
if (_low_batt_count >= 3) { // 3 consecutive low readings (~24s) to avoid transient sags
// show low battery shutdown alert
// we should only do this for eink displays, which will persist after power loss
#if defined(THINKNODE_M1) || defined(LILYGO_TECHO)
// show low battery shutdown alert on e-ink (persists after power loss)
#if defined(THINKNODE_M1) || defined(LILYGO_TECHO) || defined(LilyGo_TDeck_Pro)
if (_display != NULL) {
_display->startFrame();
_display->setTextSize(2);
@@ -995,7 +1329,9 @@ if (curr) curr->poll();
#endif
shutdown();
}
} else {
_low_batt_count = 0;
}
next_batt_chck = millis() + 8000;
}
@@ -1037,39 +1373,38 @@ char UITask::handleTripleClick(char c) {
}
bool UITask::getGPSState() {
if (_sensors != NULL) {
int num = _sensors->getNumSettings();
for (int i = 0; i < num; i++) {
if (strcmp(_sensors->getSettingName(i), "gps") == 0) {
return !strcmp(_sensors->getSettingValue(i), "1");
}
}
}
return false;
#if ENV_INCLUDE_GPS == 1
return _node_prefs != NULL && _node_prefs->gps_enabled;
#else
return false;
#endif
}
void UITask::toggleGPS() {
#if ENV_INCLUDE_GPS == 1
if (_sensors != NULL) {
// toggle GPS on/off
int num = _sensors->getNumSettings();
for (int i = 0; i < num; i++) {
if (strcmp(_sensors->getSettingName(i), "gps") == 0) {
if (strcmp(_sensors->getSettingValue(i), "1") == 0) {
_sensors->setSettingValue("gps", "0");
_node_prefs->gps_enabled = 0;
notify(UIEventType::ack);
} else {
_sensors->setSettingValue("gps", "1");
_node_prefs->gps_enabled = 1;
notify(UIEventType::ack);
}
the_mesh.savePrefs();
showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800);
_next_refresh = 0;
break;
if (_node_prefs->gps_enabled) {
// Disable GPS — cut hardware power
_sensors->setSettingValue("gps", "0");
_node_prefs->gps_enabled = 0;
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, !GPS_EN_ACTIVE);
#endif
notify(UIEventType::ack);
} else {
// Enable GPS — power on hardware
_sensors->setSettingValue("gps", "1");
_node_prefs->gps_enabled = 1;
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, GPS_EN_ACTIVE);
#endif
notify(UIEventType::ack);
}
the_mesh.savePrefs();
showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800);
_next_refresh = 0;
}
}
#endif
}
void UITask::toggleBuzzer() {
@@ -1126,6 +1461,10 @@ bool UITask::isEditingHomeScreen() const {
void UITask::gotoChannelScreen() {
((ChannelScreen *) channel_screen)->resetScroll();
// Mark the currently viewed channel as read
((ChannelScreen *) channel_screen)->markChannelRead(
((ChannelScreen *) channel_screen)->getViewChannelIdx()
);
setCurrScreen(channel_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
@@ -1157,8 +1496,21 @@ void UITask::gotoTextReader() {
_next_refresh = 100;
}
void UITask::gotoNotesScreen() {
NotesScreen* notes = (NotesScreen*)notes_screen;
if (_display != NULL) {
notes->enter(*_display);
}
setCurrScreen(notes_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS;
_next_refresh = 100;
}
void UITask::gotoSettingsScreen() {
((SettingsScreen*)settings_screen)->enter();
((SettingsScreen *) settings_screen)->enter();
setCurrScreen(settings_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
@@ -1168,7 +1520,7 @@ void UITask::gotoSettingsScreen() {
}
void UITask::gotoOnboarding() {
((SettingsScreen*)settings_screen)->enterOnboarding();
((SettingsScreen *) settings_screen)->enterOnboarding();
setCurrScreen(settings_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
@@ -1177,10 +1529,43 @@ void UITask::gotoOnboarding() {
_next_refresh = 100;
}
void UITask::gotoAudiobookPlayer() {
#ifdef MECK_AUDIO_VARIANT
if (audiobook_screen == nullptr) return; // No audio hardware
AudiobookPlayerScreen* abPlayer = (AudiobookPlayerScreen*)audiobook_screen;
if (_display != NULL) {
abPlayer->enter(*_display);
}
setCurrScreen(audiobook_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS;
_next_refresh = 100;
#endif
}
#ifdef HAS_4G_MODEM
void UITask::gotoSMSScreen() {
SMSScreen* smsScr = (SMSScreen*)sms_screen;
smsScr->activate();
setCurrScreen(sms_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS;
_next_refresh = 100;
}
#endif
uint8_t UITask::getChannelScreenViewIdx() const {
return ((ChannelScreen *) channel_screen)->getViewChannelIdx();
}
int UITask::getUnreadMsgCount() const {
return ((ChannelScreen *) channel_screen)->getTotalUnread();
}
void UITask::addSentChannelMessage(uint8_t channel_idx, const char* sender, const char* text) {
// Format the message as "Sender: message"
char formattedMsg[CHANNEL_MSG_TEXT_LEN];
@@ -1188,4 +1573,109 @@ void UITask::addSentChannelMessage(uint8_t channel_idx, const char* sender, cons
// Add to channel history with path_len=0 (local message)
((ChannelScreen *) channel_screen)->addMessage(channel_idx, 0, sender, formattedMsg);
}
}
void UITask::markChannelReadFromBLE(uint8_t channel_idx) {
((ChannelScreen *) channel_screen)->markChannelRead(channel_idx);
// Trigger a refresh so the home screen unread count updates in real-time
_next_refresh = millis() + 200;
}
void UITask::gotoRepeaterAdmin(int contactIdx) {
// Lazy-initialize on first use (same pattern as audiobook player)
if (repeater_admin == nullptr) {
repeater_admin = new RepeaterAdminScreen(this, &rtc_clock);
}
// Get contact name for the screen header
ContactInfo contact;
char name[32] = "Unknown";
if (the_mesh.getContactByIdx(contactIdx, contact)) {
strncpy(name, contact.name, sizeof(name) - 1);
name[sizeof(name) - 1] = '\0';
}
RepeaterAdminScreen* admin = (RepeaterAdminScreen*)repeater_admin;
admin->openForContact(contactIdx, name);
setCurrScreen(repeater_admin);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS;
_next_refresh = 100;
}
#ifdef MECK_WEB_READER
void UITask::gotoWebReader() {
// Lazy-initialize on first use (same pattern as audiobook player)
if (web_reader == nullptr) {
Serial.printf("WebReader: lazy init - free heap: %d, largest block: %d\n",
ESP.getFreeHeap(), ESP.getMaxAllocHeap());
web_reader = new WebReaderScreen(this);
Serial.printf("WebReader: init complete - free heap: %d\n", ESP.getFreeHeap());
}
WebReaderScreen* wr = (WebReaderScreen*)web_reader;
if (_display != NULL) {
wr->enter(*_display);
}
// Heap diagnostic — check state after web reader entry (WiFi connects later)
Serial.printf("[HEAP] WebReader enter - free: %u, largest: %u, PSRAM: %u\n",
ESP.getFreeHeap(), ESP.getMaxAllocHeap(), ESP.getFreePsram());
setCurrScreen(web_reader);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS;
_next_refresh = 100;
}
#endif
void UITask::gotoMapScreen() {
MapScreen* map = (MapScreen*)map_screen;
if (_display != NULL) {
map->enter(*_display);
}
setCurrScreen(map_screen);
if (_display != NULL && !_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS;
_next_refresh = 100;
}
void UITask::onAdminLoginResult(bool success, uint8_t permissions, uint32_t server_time) {
if (repeater_admin && isOnRepeaterAdmin()) {
((RepeaterAdminScreen*)repeater_admin)->onLoginResult(success, permissions, server_time);
_next_refresh = 100; // trigger re-render
}
}
void UITask::onAdminCliResponse(const char* from_name, const char* text) {
if (repeater_admin && isOnRepeaterAdmin()) {
((RepeaterAdminScreen*)repeater_admin)->onCliResponse(text);
_next_refresh = 100; // trigger re-render
}
}
void UITask::onAdminTelemetryResult(const uint8_t* data, uint8_t len) {
Serial.printf("[UITask] onAdminTelemetryResult: %d bytes, onAdmin=%d\n", len, isOnRepeaterAdmin());
if (repeater_admin && isOnRepeaterAdmin()) {
((RepeaterAdminScreen*)repeater_admin)->onTelemetryResult(data, len);
_next_refresh = 100; // trigger re-render
}
}
#ifdef MECK_AUDIO_VARIANT
bool UITask::isAudioPlayingInBackground() const {
if (!audiobook_screen) return false;
AudiobookPlayerScreen* player = (AudiobookPlayerScreen*)audiobook_screen;
return player->isAudioActive();
}
bool UITask::isAudioPausedInBackground() const {
if (!audiobook_screen) return false;
AudiobookPlayerScreen* player = (AudiobookPlayerScreen*)audiobook_screen;
return player->isBookOpen() && !player->isAudioActive();
}
#endif
+372
View File
@@ -0,0 +1,372 @@
#pragma once
// =============================================================================
// ApnDatabase.h - Embedded APN Lookup Table
//
// Maps MCC/MNC (Mobile Country Code / Mobile Network Code) to default APN
// settings for common carriers worldwide. Compiled directly into flash (~3KB)
// so users never need to manually install a lookup file.
//
// The modem queries IMSI via AT+CIMI to extract MCC (3 digits) + MNC (2-3
// digits), then looks up the APN here. If not found, falls back to the
// modem's existing PDP context (AT+CGDCONT?) or user-configured APN.
//
// To add a carrier: append to APN_DATABASE[] with the MCC+MNC as a single
// integer. MNC can be 2 or 3 digits:
// MCC=310, MNC=260 → mccmnc = 310260
// MCC=505, MNC=01 → mccmnc = 50501
//
// Guard: HAS_4G_MODEM
// =============================================================================
#ifdef HAS_4G_MODEM
#ifndef APN_DATABASE_H
#define APN_DATABASE_H
struct ApnEntry {
uint32_t mccmnc; // MCC+MNC as integer (e.g. 310260 for T-Mobile US)
const char* apn; // APN string
const char* carrier; // Human-readable carrier name (for debug/display)
};
// ---------------------------------------------------------------------------
// APN Database — sorted by MCC for binary search potential (not required)
//
// Sources: carrier documentation, GSMA databases, community wikis.
// This covers ~120 major carriers across key regions. Users with less
// common carriers can set APN manually in Settings.
// ---------------------------------------------------------------------------
static const ApnEntry APN_DATABASE[] = {
// =========================================================================
// Australia (MCC 505)
// =========================================================================
{ 50501, "telstra.internet", "Telstra" },
{ 50502, "yesinternet", "Optus" },
{ 50503, "vfinternet.au", "Vodafone AU" },
{ 50506, "3netaccess", "Three AU" },
{ 50507, "telstra.internet", "Vodafone AU (MVNO)" }, // Many MVNOs on Telstra
{ 50510, "telstra.internet", "Norfolk Tel" },
{ 50512, "3netaccess", "Amaysim" }, // Optus MVNO
{ 50514, "yesinternet", "Aussie Broadband" }, // Optus MVNO
{ 50590, "yesinternet", "Optus MVNO" },
// =========================================================================
// New Zealand (MCC 530)
// =========================================================================
{ 53001, "internet", "Vodafone NZ" },
{ 53005, "internet", "Spark NZ" },
{ 53024, "internet", "2degrees" },
// =========================================================================
// United States (MCC 310, 311, 312, 313, 316)
// =========================================================================
{ 310012, "fast.t-mobile.com", "Verizon (old)" },
{ 310026, "fast.t-mobile.com", "T-Mobile US" },
{ 310030, "fast.t-mobile.com", "T-Mobile US" },
{ 310032, "fast.t-mobile.com", "T-Mobile US" },
{ 310060, "fast.t-mobile.com", "T-Mobile US" },
{ 310160, "fast.t-mobile.com", "T-Mobile US" },
{ 310200, "fast.t-mobile.com", "T-Mobile US" },
{ 310210, "fast.t-mobile.com", "T-Mobile US" },
{ 310220, "fast.t-mobile.com", "T-Mobile US" },
{ 310230, "fast.t-mobile.com", "T-Mobile US" },
{ 310240, "fast.t-mobile.com", "T-Mobile US" },
{ 310250, "fast.t-mobile.com", "T-Mobile US" },
{ 310260, "fast.t-mobile.com", "T-Mobile US" },
{ 310270, "fast.t-mobile.com", "T-Mobile US" },
{ 310310, "fast.t-mobile.com", "T-Mobile US" },
{ 310490, "fast.t-mobile.com", "T-Mobile US" },
{ 310530, "fast.t-mobile.com", "T-Mobile US" },
{ 310580, "fast.t-mobile.com", "T-Mobile US" },
{ 310660, "fast.t-mobile.com", "T-Mobile US" },
{ 310800, "fast.t-mobile.com", "T-Mobile US" },
{ 311480, "vzwinternet", "Verizon" },
{ 311481, "vzwinternet", "Verizon" },
{ 311482, "vzwinternet", "Verizon" },
{ 311483, "vzwinternet", "Verizon" },
{ 311484, "vzwinternet", "Verizon" },
{ 311489, "vzwinternet", "Verizon" },
{ 310410, "fast.t-mobile.com", "AT&T (migrated)" },
{ 310120, "att.mvno", "AT&T (Sprint)" },
{ 312530, "iot.1nce.net", "1NCE IoT" },
{ 310120, "tfdata", "Tracfone" },
// =========================================================================
// Canada (MCC 302)
// =========================================================================
{ 30220, "internet.com", "Rogers" },
{ 30221, "internet.com", "Rogers" },
{ 30237, "internet.com", "Rogers" },
{ 30272, "internet.com", "Rogers" },
{ 30234, "sp.telus.com", "Telus" },
{ 30286, "sp.telus.com", "Telus" },
{ 30236, "sp.telus.com", "Telus" },
{ 30261, "sp.bell.ca", "Bell" },
{ 30263, "sp.bell.ca", "Bell" },
{ 30267, "sp.bell.ca", "Bell" },
{ 30268, "fido-core-appl1.apn", "Fido" },
{ 30278, "internet.com", "SaskTel" },
{ 30266, "sp.mb.com", "MTS" },
// =========================================================================
// United Kingdom (MCC 234, 235)
// =========================================================================
{ 23410, "o2-internet", "O2 UK" },
{ 23415, "three.co.uk", "Vodafone UK" },
{ 23420, "three.co.uk", "Three UK" },
{ 23430, "everywhere", "EE" },
{ 23431, "everywhere", "EE" },
{ 23432, "everywhere", "EE" },
{ 23433, "everywhere", "EE" },
{ 23450, "data.lycamobile.co.uk","Lycamobile UK" },
{ 23486, "three.co.uk", "Three UK" },
// =========================================================================
// Germany (MCC 262)
// =========================================================================
{ 26201, "internet.t-mobile", "Telekom DE" },
{ 26202, "web.vodafone.de", "Vodafone DE" },
{ 26203, "internet", "O2 DE" },
{ 26207, "internet", "O2 DE" },
// =========================================================================
// France (MCC 208)
// =========================================================================
{ 20801, "orange", "Orange FR" },
{ 20810, "sl2sfr", "SFR" },
{ 20815, "free", "Free Mobile" },
{ 20820, "ofnew.fr", "Bouygues" },
// =========================================================================
// Italy (MCC 222)
// =========================================================================
{ 22201, "mobile.vodafone.it", "TIM" },
{ 22210, "mobile.vodafone.it", "Vodafone IT" },
{ 22250, "internet.it", "Iliad IT" },
{ 22288, "internet.wind", "WindTre" },
{ 22299, "internet.wind", "WindTre" },
// =========================================================================
// Spain (MCC 214)
// =========================================================================
{ 21401, "internet", "Vodafone ES" },
{ 21403, "internet", "Orange ES" },
{ 21404, "internet", "Yoigo" },
{ 21407, "internet", "Movistar" },
// =========================================================================
// Netherlands (MCC 204)
// =========================================================================
{ 20404, "internet", "Vodafone NL" },
{ 20408, "internet", "KPN" },
{ 20412, "internet", "Telfort" },
{ 20416, "internet", "T-Mobile NL" },
{ 20420, "internet", "T-Mobile NL" },
// =========================================================================
// Sweden (MCC 240)
// =========================================================================
{ 24001, "internet.telia.se", "Telia SE" },
{ 24002, "tre.se", "Three SE" },
{ 24007, "internet.telenor.se", "Telenor SE" },
// =========================================================================
// Norway (MCC 242)
// =========================================================================
{ 24201, "internet.telenor.no", "Telenor NO" },
{ 24202, "internet.netcom.no", "Telia NO" },
// =========================================================================
// Denmark (MCC 238)
// =========================================================================
{ 23801, "internet", "TDC" },
{ 23802, "internet", "Telenor DK" },
{ 23806, "internet", "Three DK" },
{ 23820, "internet", "Telia DK" },
// =========================================================================
// Switzerland (MCC 228)
// =========================================================================
{ 22801, "gprs.swisscom.ch", "Swisscom" },
{ 22802, "internet", "Sunrise" },
{ 22803, "internet", "Salt" },
// =========================================================================
// Austria (MCC 232)
// =========================================================================
{ 23201, "a1.net", "A1" },
{ 23203, "web.one.at", "Three AT" },
{ 23205, "web", "T-Mobile AT" },
// =========================================================================
// Japan (MCC 440, 441)
// =========================================================================
{ 44010, "spmode.ne.jp", "NTT Docomo" },
{ 44020, "plus.4g", "SoftBank" },
{ 44051, "au.au-net.ne.jp", "KDDI au" },
// =========================================================================
// South Korea (MCC 450)
// =========================================================================
{ 45005, "lte.sktelecom.com", "SK Telecom" },
{ 45006, "lte.ktfwing.com", "KT" },
{ 45008, "lte.lguplus.co.kr", "LG U+" },
// =========================================================================
// India (MCC 404, 405)
// =========================================================================
{ 40445, "airtelgprs.com", "Airtel" },
{ 40410, "airtelgprs.com", "Airtel" },
{ 40411, "www", "Vodafone IN (Vi)" },
{ 40413, "www", "Vodafone IN (Vi)" },
{ 40486, "www", "Vodafone IN (Vi)" },
{ 40553, "jionet", "Jio" },
{ 40554, "jionet", "Jio" },
{ 40512, "bsnlnet", "BSNL" },
// =========================================================================
// Singapore (MCC 525)
// =========================================================================
{ 52501, "internet", "Singtel" },
{ 52503, "internet", "M1" },
{ 52505, "internet", "StarHub" },
// =========================================================================
// Hong Kong (MCC 454)
// =========================================================================
{ 45400, "internet", "CSL" },
{ 45406, "internet", "SmarTone" },
{ 45412, "internet", "CMHK" },
// =========================================================================
// Brazil (MCC 724)
// =========================================================================
{ 72405, "claro.com.br", "Claro BR" },
{ 72406, "wap.oi.com.br", "Vivo" },
{ 72410, "wap.oi.com.br", "Vivo" },
{ 72411, "wap.oi.com.br", "Vivo" },
{ 72415, "internet.tim.br", "TIM BR" },
{ 72431, "gprs.oi.com.br", "Oi" },
// =========================================================================
// Mexico (MCC 334)
// =========================================================================
{ 33402, "internet.itelcel.com","Telcel" },
{ 33403, "internet.movistar.mx","Movistar MX" },
{ 33404, "internet.att.net.mx", "AT&T MX" },
// =========================================================================
// South Africa (MCC 655)
// =========================================================================
{ 65501, "internet", "Vodacom" },
{ 65502, "internet", "Telkom ZA" },
{ 65507, "internet", "Cell C" },
{ 65510, "internet", "MTN ZA" },
// =========================================================================
// Philippines (MCC 515)
// =========================================================================
{ 51502, "internet.globe.com.ph","Globe" },
{ 51503, "internet", "Smart" },
{ 51505, "internet", "Sun Cellular" },
// =========================================================================
// Thailand (MCC 520)
// =========================================================================
{ 52001, "internet", "AIS" },
{ 52004, "internet", "TrueMove" },
{ 52005, "internet", "dtac" },
// =========================================================================
// Indonesia (MCC 510)
// =========================================================================
{ 51001, "internet", "Telkomsel" },
{ 51010, "internet", "Telkomsel" },
{ 51011, "3gprs", "XL Axiata" },
{ 51028, "3gprs", "XL Axiata (Axis)" },
// =========================================================================
// Malaysia (MCC 502)
// =========================================================================
{ 50212, "celcom3g", "Celcom" },
{ 50213, "celcom3g", "Celcom" },
{ 50216, "internet", "Digi" },
{ 50219, "celcom3g", "Celcom" },
// =========================================================================
// Czech Republic (MCC 230)
// =========================================================================
{ 23001, "internet.t-mobile.cz","T-Mobile CZ" },
{ 23002, "internet", "O2 CZ" },
{ 23003, "internet.vodafone.cz","Vodafone CZ" },
// =========================================================================
// Poland (MCC 260)
// =========================================================================
{ 26001, "internet", "Plus PL" },
{ 26002, "internet", "T-Mobile PL" },
{ 26003, "internet", "Orange PL" },
{ 26006, "internet", "Play" },
// =========================================================================
// Portugal (MCC 268)
// =========================================================================
{ 26801, "internet", "Vodafone PT" },
{ 26803, "internet", "NOS" },
{ 26806, "internet", "MEO" },
// =========================================================================
// Ireland (MCC 272)
// =========================================================================
{ 27201, "internet", "Vodafone IE" },
{ 27202, "open.internet", "Three IE" },
{ 27205, "three.ie", "Three IE" },
// =========================================================================
// IoT / Global SIMs
// =========================================================================
{ 901028, "iot.1nce.net", "1NCE (IoT)" },
{ 90143, "hologram", "Hologram" },
};
#define APN_DATABASE_SIZE (sizeof(APN_DATABASE) / sizeof(APN_DATABASE[0]))
// ---------------------------------------------------------------------------
// Lookup function — returns nullptr if not found
// ---------------------------------------------------------------------------
inline const ApnEntry* apnLookup(uint32_t mccmnc) {
for (int i = 0; i < (int)APN_DATABASE_SIZE; i++) {
if (APN_DATABASE[i].mccmnc == mccmnc) {
return &APN_DATABASE[i];
}
}
return nullptr;
}
// Parse IMSI string into MCC+MNC. Tries 3-digit MNC first (6-digit mccmnc),
// falls back to 2-digit MNC (5-digit mccmnc) if not found.
inline const ApnEntry* apnLookupFromIMSI(const char* imsi) {
if (!imsi || strlen(imsi) < 5) return nullptr;
// Extract MCC (always 3 digits)
uint32_t mcc = (imsi[0] - '0') * 100 + (imsi[1] - '0') * 10 + (imsi[2] - '0');
// Try 3-digit MNC first (more specific)
if (strlen(imsi) >= 6) {
uint32_t mnc3 = (imsi[3] - '0') * 100 + (imsi[4] - '0') * 10 + (imsi[5] - '0');
uint32_t mccmnc6 = mcc * 1000 + mnc3;
const ApnEntry* entry = apnLookup(mccmnc6);
if (entry) return entry;
}
// Fall back to 2-digit MNC
uint32_t mnc2 = (imsi[3] - '0') * 10 + (imsi[4] - '0');
uint32_t mccmnc5 = mcc * 100 + mnc2;
return apnLookup(mccmnc5);
}
#endif // APN_DATABASE_H
#endif // HAS_4G_MODEM
+227
View File
@@ -0,0 +1,227 @@
#pragma once
// =============================================================================
// CellularMQTT — A7682E Modem + MQTT via native AT commands
// =============================================================================
#ifdef HAS_4G_MODEM
#ifndef CELLULAR_MQTT_H
#define CELLULAR_MQTT_H
#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include "variant.h"
#include "ApnDatabase.h"
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
#define MQTT_TOPIC_MAX 80
#define MQTT_PAYLOAD_MAX 512
#define MQTT_CLIENT_ID_MAX 32
#define CMD_QUEUE_SIZE 4
#define RSP_QUEUE_SIZE 4
#define TELEMETRY_INTERVAL 60000
#define CELL_TASK_PRIORITY 1
#define CELL_TASK_STACK_SIZE 8192
#define CELL_TASK_CORE 0
#define MQTT_RECONNECT_MIN 5000
#define MQTT_RECONNECT_MAX 300000
#define MQTT_PUB_FAIL_MAX 5
#define OTA_CHUNK_SIZE 1024
// ---------------------------------------------------------------------------
// State machine
// ---------------------------------------------------------------------------
enum class CellState : uint8_t {
OFF,
POWERING_ON,
INITIALIZING,
REGISTERING,
DATA_ACTIVATING,
MQTT_STARTING,
MQTT_CONNECTING,
CONNECTED,
RECONNECTING,
OTA_IN_PROGRESS,
ERROR
};
// ---------------------------------------------------------------------------
// Queue message types
// ---------------------------------------------------------------------------
struct MQTTCommand {
char cmd[MQTT_PAYLOAD_MAX];
};
struct MQTTResponse {
char topic[MQTT_TOPIC_MAX];
char payload[MQTT_PAYLOAD_MAX];
};
// ---------------------------------------------------------------------------
// MQTT config (loaded from SD: /remote/mqtt.cfg)
// ---------------------------------------------------------------------------
struct MQTTConfig {
char broker[80];
uint16_t port;
char username[40];
char password[40];
char deviceId[MQTT_CLIENT_ID_MAX];
};
// ---------------------------------------------------------------------------
// Telemetry snapshot
// ---------------------------------------------------------------------------
struct TelemetryData {
uint32_t uptime_secs;
uint16_t battery_mv;
uint8_t battery_pct;
int16_t temperature;
int csq;
uint8_t neighbor_count;
float freq;
float bw;
uint8_t sf;
uint8_t cr;
uint8_t tx_power;
char node_name[32];
char apn[40];
char oper[24];
bool mqtt_connected;
};
// ---------------------------------------------------------------------------
// CellularMQTT class
// ---------------------------------------------------------------------------
class CellularMQTT {
public:
void begin();
void stop();
// --- Queue API (called from main loop) ---
bool recvCommand(MQTTCommand& out);
bool sendResponse(const char* topic, const char* payload);
// --- Telemetry ---
void updateTelemetry(const TelemetryData& data);
// --- OTA ---
void requestOTA(const char* url);
bool isOTAInProgress() const { return _state == CellState::OTA_IN_PROGRESS; }
// --- State queries ---
CellState getState() const { return _state; }
bool isConnected() const { return _state == CellState::CONNECTED; }
int getCSQ() const { return _csq; }
int getSignalBars() const;
const char* getOperator() const { return _operator; }
const char* getIPAddress() const { return _ipAddr; }
const char* getBroker() const { return _config.broker; }
const char* getAPN() const { return _apn; }
const char* getRspTopic() const { return _topicRsp; }
const char* stateString() const;
uint32_t getLastCmdTime() const { return _lastCmdTime; }
static bool loadConfig(MQTTConfig& cfg);
private:
volatile CellState _state = CellState::OFF;
volatile int _csq = 99;
volatile uint32_t _lastCmdTime = 0;
char _operator[24] = {0};
char _ipAddr[20] = {0};
char _imei[20] = {0};
char _imsi[20] = {0};
char _apn[64] = {0};
MQTTConfig _config = {};
TelemetryData _telemetry = {};
SemaphoreHandle_t _telemetryMutex = nullptr;
char _topicCmd[MQTT_TOPIC_MAX] = {0};
char _topicRsp[MQTT_TOPIC_MAX] = {0};
char _topicTelem[MQTT_TOPIC_MAX] = {0};
char _topicOta[MQTT_TOPIC_MAX] = {0};
TaskHandle_t _taskHandle = nullptr;
QueueHandle_t _cmdQueue = nullptr;
QueueHandle_t _rspQueue = nullptr;
SemaphoreHandle_t _uartMutex = nullptr;
uint8_t _pubFailCount = 0;
static const int AT_BUF_SIZE = 512;
char _atBuf[AT_BUF_SIZE];
static const int URC_BUF_SIZE = 600;
char _urcBuf[URC_BUF_SIZE];
int _urcPos = 0;
enum MqttRxState { RX_IDLE, RX_WAIT_TOPIC, RX_WAIT_PAYLOAD };
MqttRxState _rxState = RX_IDLE;
int _rxTopicLen = 0;
int _rxPayloadLen = 0;
char _rxTopic[MQTT_TOPIC_MAX];
char _rxPayload[MQTT_PAYLOAD_MAX];
uint32_t _reconnectDelay = MQTT_RECONNECT_MIN;
// OTA state
volatile bool _otaPending = false;
char _otaUrl[256] = {0};
// --- Modem UART helpers ---
bool modemPowerOn();
bool sendAT(const char* cmd, const char* expect, uint32_t timeout_ms = 2000);
bool waitResponse(const char* expect, uint32_t timeout_ms, char* buf = nullptr, size_t bufLen = 0);
bool waitPrompt(uint32_t timeout_ms = 5000);
void drainURCs();
void processURCLine(const char* line);
// --- Data connection ---
void resolveAPN();
bool activateData();
// --- MQTT operations ---
bool mqttStart();
bool mqttConnect();
bool mqttSubscribe(const char* topic);
bool mqttPublish(const char* topic, const char* payload);
void mqttDisconnect();
// --- URC handlers ---
void handleMqttRxStart(const char* line);
void handleMqttRxTopic(const char* data, int len);
void handleMqttRxPayload(const char* data, int len);
void handleMqttRxEnd();
void handleMqttConnLost(const char* line);
// --- OTA operations (modem task only) ---
void performOTA();
int httpGet(const char* url);
bool httpReadChunk(int offset, int len, uint8_t* dest, int* bytesRead);
void httpTerm();
int readRawBytes(uint8_t* dest, int count, uint32_t timeout_ms);
// --- Task ---
static void taskEntry(void* param);
void taskLoop();
};
extern CellularMQTT cellularMQTT;
#endif // CELLULAR_MQTT_H
#endif // HAS_4G_MODEM
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -68,11 +68,11 @@ struct NeighbourInfo {
};
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "30 Nov 2025"
#define FIRMWARE_BUILD_DATE "3 April 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "v1.11.0"
#define FIRMWARE_VERSION "v0.2"
#endif
#define FIRMWARE_ROLE "repeater"
+126 -25
View File
@@ -2,7 +2,21 @@
#include <Arduino.h>
#include <helpers/CommonCLI.h>
#define AUTO_OFF_MILLIS 20000 // 20 seconds
#ifdef HAS_4G_MODEM
#include "CellularMQTT.h"
#endif
#ifdef MECK_WIFI_REMOTE
#include "WiFiMQTT.h"
#endif
#if defined(HAS_4G_MODEM) || defined(MECK_WIFI_REMOTE)
#define AUTO_OFF_DISABLED true
#else
#define AUTO_OFF_DISABLED false
#endif
#define AUTO_OFF_MILLIS 20000 // 20 seconds (ignored when AUTO_OFF_DISABLED)
#define BOOT_SCREEN_MILLIS 4000 // 4 seconds
// 'meshcore', 128x13px
@@ -28,55 +42,144 @@ void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* fi
_node_prefs = node_prefs;
_display->turnOn();
// 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);
char *dash = strchr(version, '-');
if(dash){
*dash = 0;
}
if (dash) *dash = 0;
// v1.2.3 (1 Jan 2025)
sprintf(_version_info, "%s (%s)", version, build_date);
snprintf(_version_info, sizeof(_version_info), "%s (%s)", version, build_date);
free(version);
}
void UITask::renderCurrScreen() {
char tmp[80];
if (millis() < BOOT_SCREEN_MILLIS) { // boot screen
// meshcore logo
if (millis() < BOOT_SCREEN_MILLIS) {
// Boot screen — logo + version
_display->setColor(DisplayDriver::BLUE);
int logoWidth = 128;
_display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13);
// version info
_display->setColor(DisplayDriver::LIGHT);
_display->setTextSize(1);
uint16_t versionWidth = _display->getTextWidth(_version_info);
_display->setCursor((_display->width() - versionWidth) / 2, 22);
_display->print(_version_info);
// node type
#if defined(HAS_4G_MODEM)
const char* node_type = "< Remote Repeater >";
#elif defined(MECK_WIFI_REMOTE)
const char* node_type = "< WiFi Repeater >";
#else
const char* node_type = "< Repeater >";
#endif
uint16_t typeWidth = _display->getTextWidth(node_type);
_display->setCursor((_display->width() - typeWidth) / 2, 35);
_display->print(node_type);
} else { // home screen
// node name
} else {
// Home screen — node info + connection status
_display->setCursor(0, 0);
_display->setTextSize(1);
_display->setColor(DisplayDriver::GREEN);
_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);
// bw / cr
_display->setCursor(0, 30);
sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr);
_display->print(tmp);
// --- Cellular status (4G variant) ---
#ifdef HAS_4G_MODEM
int y = 44;
_display->setCursor(0, y);
_display->setColor(DisplayDriver::LIGHT);
sprintf(tmp, "4G: %s", cellularMQTT.stateString());
_display->print(tmp);
y += 10;
_display->setCursor(0, y);
sprintf(tmp, "CSQ: %d (%d bars)", cellularMQTT.getCSQ(), cellularMQTT.getSignalBars());
_display->print(tmp);
y += 10;
const char* oper = cellularMQTT.getOperator();
if (oper[0]) {
_display->setCursor(0, y);
sprintf(tmp, "Op: %.16s", oper);
_display->print(tmp);
y += 10;
}
_display->setCursor(0, y);
_display->setColor(cellularMQTT.isConnected() ? DisplayDriver::GREEN : DisplayDriver::YELLOW);
sprintf(tmp, "MQTT: %s", cellularMQTT.isConnected() ? "Connected" : "---");
_display->print(tmp);
y += 10;
const char* ip4g = cellularMQTT.getIPAddress();
if (ip4g[0]) {
_display->setColor(DisplayDriver::LIGHT);
_display->setCursor(0, y);
sprintf(tmp, "IP: %s", ip4g);
_display->print(tmp);
y += 10;
}
uint32_t upSec = millis() / 1000;
uint32_t upH = upSec / 3600;
uint32_t upM = (upSec % 3600) / 60;
_display->setColor(DisplayDriver::LIGHT);
_display->setCursor(0, y);
sprintf(tmp, "Up: %luh %lum Heap:%dk", upH, upM, ESP.getFreeHeap() / 1024);
_display->print(tmp);
#endif
// --- WiFi status (WiFi variant) ---
#ifdef MECK_WIFI_REMOTE
int y = 44;
_display->setCursor(0, y);
_display->setColor(DisplayDriver::LIGHT);
sprintf(tmp, "WiFi: %s", wifiMQTT.stateString());
_display->print(tmp);
y += 10;
_display->setCursor(0, y);
sprintf(tmp, "RSSI: %d (%d bars)", wifiMQTT.getRSSI(), wifiMQTT.getSignalBars());
_display->print(tmp);
y += 10;
_display->setCursor(0, y);
sprintf(tmp, "SSID: %.16s", wifiMQTT.getSSID());
_display->print(tmp);
y += 10;
_display->setCursor(0, y);
_display->setColor(wifiMQTT.isConnected() ? DisplayDriver::GREEN : DisplayDriver::YELLOW);
sprintf(tmp, "MQTT: %s", wifiMQTT.isConnected() ? "Connected" : "---");
_display->print(tmp);
y += 10;
const char* ipWifi = wifiMQTT.getIPAddress();
if (ipWifi[0]) {
_display->setColor(DisplayDriver::LIGHT);
_display->setCursor(0, y);
sprintf(tmp, "IP: %s", ipWifi);
_display->print(tmp);
y += 10;
}
uint32_t upSec = millis() / 1000;
uint32_t upH = upSec / 3600;
uint32_t upM = (upSec % 3600) / 60;
_display->setColor(DisplayDriver::LIGHT);
_display->setCursor(0, y);
sprintf(tmp, "Up: %luh %lum Heap:%dk", upH, upM, ESP.getFreeHeap() / 1024);
_display->print(tmp);
#endif
}
}
@@ -85,17 +188,15 @@ void UITask::loop() {
if (millis() >= _next_read) {
int btnState = digitalRead(PIN_USER_BTN);
if (btnState != _prevBtnState) {
if (btnState == LOW) { // pressed?
if (_display->isOn()) {
// TODO: any action ?
} else {
if (btnState == LOW) {
if (!_display->isOn()) {
_display->turnOn();
}
_auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer
_auto_off = millis() + AUTO_OFF_MILLIS;
}
_prevBtnState = btnState;
}
_next_read = millis() + 200; // 5 reads per second
_next_read = millis() + 200;
}
#endif
@@ -105,10 +206,10 @@ void UITask::loop() {
renderCurrScreen();
_display->endFrame();
_next_refresh = millis() + 1000; // refresh every second
_next_refresh = millis() + 10000;
}
if (millis() > _auto_off) {
if (!AUTO_OFF_DISABLED && millis() > _auto_off) {
_display->turnOff();
}
}
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ class UITask {
unsigned long _next_read, _next_refresh, _auto_off;
int _prevBtnState;
NodePrefs* _node_prefs;
char _version_info[32];
char _version_info[48];
void renderCurrScreen();
public:
File diff suppressed because it is too large Load Diff
+198 -8
View File
@@ -1,8 +1,20 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <time.h>
#include "MyMesh.h"
#ifdef HAS_4G_MODEM
#include <SD.h>
#include "CellularMQTT.h"
#endif
#ifdef MECK_WIFI_REMOTE
#if defined(HAS_SDCARD) || defined(SDCARD_CS)
#include <SD.h>
#endif
#include "WiFiMQTT.h"
#endif
#ifdef DISPLAY_CLASS
#include "UITask.h"
static UITask ui_task(display);
@@ -23,6 +35,10 @@ static char command[160];
unsigned long lastActive = 0; // mark last active time
unsigned long nextSleepinSecs = 120; // next sleep in seconds. The first sleep (if enabled) is after 2 minutes from boot
#if (defined(HAS_4G_MODEM) || defined(MECK_WIFI_REMOTE)) && (defined(HAS_SDCARD) || defined(SDCARD_CS))
static bool sdCardReady = false;
#endif
void setup() {
Serial.begin(115200);
delay(1000);
@@ -83,6 +99,72 @@ void setup() {
the_mesh.begin(fs);
// ---------------------------------------------------------------------------
// SD card init — needed for MQTT config on devices with SD slots.
// T-Deck Pro: SD shares display SPI bus (HSPI via displaySpi)
// T5S3: SD shares LoRa SPI bus (SCK=14, MOSI=13, MISO=21)
// Heltec V4 and others without SD: config lives in SPIFFS (already init'd)
// ---------------------------------------------------------------------------
#if (defined(HAS_4G_MODEM) || defined(MECK_WIFI_REMOTE)) && (defined(HAS_SDCARD) || defined(SDCARD_CS))
{
// Deselect all SPI devices before SD init to prevent bus contention
#ifdef SDCARD_CS
pinMode(SDCARD_CS, OUTPUT);
digitalWrite(SDCARD_CS, HIGH);
#endif
#ifdef PIN_DISPLAY_CS
pinMode(PIN_DISPLAY_CS, OUTPUT);
digitalWrite(PIN_DISPLAY_CS, HIGH);
#endif
#ifdef P_LORA_NSS
pinMode(P_LORA_NSS, OUTPUT);
digitalWrite(P_LORA_NSS, HIGH);
#endif
delay(100);
for (int i = 0; i < 3; i++) {
#if defined(LilyGo_T5S3_EPaper_Pro)
// T5S3: SD shares LoRa SPI bus — create local HSPI reference
static SPIClass sdSpi(HSPI);
sdSpi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI, SDCARD_CS);
if (SD.begin(SDCARD_CS, sdSpi, 4000000)) { sdCardReady = true; break; }
#elif defined(SDCARD_CS)
extern SPIClass displaySpi;
if (SD.begin(SDCARD_CS, displaySpi)) { sdCardReady = true; break; }
#else
if (SD.begin(SPI_CS)) { sdCardReady = true; break; }
#endif
delay(200);
}
Serial.printf("SD card: %s\n", sdCardReady ? "ready" : "FAILED");
}
#endif
// Start MQTT backhaul
#ifdef HAS_4G_MODEM
if (sdCardReady) {
cellularMQTT.begin();
Serial.println("Cellular MQTT starting...");
} else {
Serial.println("Cellular MQTT skipped — no SD card for config");
}
#endif
#ifdef MECK_WIFI_REMOTE
#if defined(HAS_SDCARD) || defined(SDCARD_CS)
if (sdCardReady) {
wifiMQTT.begin();
Serial.println("WiFi MQTT starting...");
} else {
Serial.println("WiFi MQTT skipped — no SD card for config");
}
#else
// No SD card slot — config lives in SPIFFS (already initialized above)
wifiMQTT.begin();
Serial.println("WiFi MQTT starting (SPIFFS config)...");
#endif
#endif
#ifdef DISPLAY_CLASS
ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION);
#endif
@@ -118,6 +200,112 @@ void loop() {
command[0] = 0; // reset command buffer
}
// ---------------------------------------------------------------------------
// MQTT → CLI bridge: process incoming commands from MQTT (cellular)
// ---------------------------------------------------------------------------
#ifdef HAS_4G_MODEM
{
MQTTCommand mqttCmd;
while (cellularMQTT.recvCommand(mqttCmd)) {
Serial.printf("[MQTT] CLI: %s\n", mqttCmd.cmd);
char reply[512];
reply[0] = '\0';
the_mesh.handleCommand((uint32_t)time(nullptr), mqttCmd.cmd, reply);
if (reply[0] == '\0') strcpy(reply, "OK");
cellularMQTT.sendResponse(cellularMQTT.getRspTopic(), reply);
Serial.printf("[MQTT] Reply: %.80s\n", reply);
}
}
// Periodic telemetry snapshot for cellular MQTT
{
static unsigned long lastTelemUpdate = 0;
if (millis() - lastTelemUpdate > 10000) {
NodePrefs* p = the_mesh.getNodePrefs();
TelemetryData td;
memset(&td, 0, sizeof(td));
td.uptime_secs = millis() / 1000;
td.battery_mv = board.getBattMilliVolts();
#ifdef HAS_BQ27220
td.battery_pct = board.getBatteryPercent();
td.temperature = board.getBattTemperature();
#else
td.battery_pct = 0;
td.temperature = 0;
#endif
td.csq = cellularMQTT.getCSQ();
td.freq = p->freq;
td.bw = p->bw;
td.sf = p->sf;
td.cr = p->cr;
td.tx_power = p->tx_power_dbm;
strncpy(td.node_name, p->node_name, sizeof(td.node_name) - 1);
strncpy(td.apn, cellularMQTT.getAPN(), sizeof(td.apn) - 1);
strncpy(td.oper, cellularMQTT.getOperator(), sizeof(td.oper) - 1);
td.mqtt_connected = cellularMQTT.isConnected();
td.neighbor_count = 0; // TODO: expose from MyMesh
cellularMQTT.updateTelemetry(td);
lastTelemUpdate = millis();
}
}
#endif
// ---------------------------------------------------------------------------
// MQTT → CLI bridge: process incoming commands from MQTT (WiFi)
// ---------------------------------------------------------------------------
#ifdef MECK_WIFI_REMOTE
wifiMQTT.loop();
{
MQTTCommand mqttCmd;
while (wifiMQTT.recvCommand(mqttCmd)) {
Serial.printf("[MQTT] CLI: %s\n", mqttCmd.cmd);
char reply[512];
reply[0] = '\0';
the_mesh.handleCommand((uint32_t)time(nullptr), mqttCmd.cmd, reply);
if (reply[0] == '\0') strcpy(reply, "OK");
wifiMQTT.sendResponse(wifiMQTT.getRspTopic(), reply);
Serial.printf("[MQTT] Reply: %.80s\n", reply);
}
}
// Periodic telemetry snapshot for WiFi MQTT
{
static unsigned long lastTelemUpdate = 0;
if (millis() - lastTelemUpdate > 10000) {
NodePrefs* p = the_mesh.getNodePrefs();
TelemetryData td;
memset(&td, 0, sizeof(td));
td.uptime_secs = millis() / 1000;
td.battery_mv = board.getBattMilliVolts();
#ifdef HAS_BQ27220
td.battery_pct = board.getBatteryPercent();
td.temperature = board.getBattTemperature();
#else
td.battery_pct = 0;
td.temperature = 0;
#endif
td.rssi = wifiMQTT.getRSSI();
td.freq = p->freq;
td.bw = p->bw;
td.sf = p->sf;
td.cr = p->cr;
td.tx_power = p->tx_power_dbm;
strncpy(td.node_name, p->node_name, sizeof(td.node_name) - 1);
td.mqtt_connected = wifiMQTT.isConnected();
td.neighbor_count = 0;
wifiMQTT.updateTelemetry(td);
lastTelemUpdate = millis();
}
}
#endif
the_mesh.loop();
sensors.loop();
#ifdef DISPLAY_CLASS
@@ -125,14 +313,16 @@ void loop() {
#endif
rtc_clock.tick();
if (the_mesh.getNodePrefs()->powersaving_enabled && // To check if power saving is enabled
the_mesh.millisHasNowPassed(lastActive + nextSleepinSecs * 1000)) { // To check if it is time to sleep
if (!the_mesh.hasPendingWork()) { // No pending work. Safe to sleep
board.sleep(1800); // To sleep. Wake up after 30 minutes or when receiving a LoRa packet
#if !defined(HAS_4G_MODEM) && !defined(MECK_WIFI_REMOTE)
if (the_mesh.getNodePrefs()->powersaving_enabled &&
the_mesh.millisHasNowPassed(lastActive + nextSleepinSecs * 1000)) {
if (!the_mesh.hasPendingWork()) {
board.sleep(1800);
lastActive = millis();
nextSleepinSecs = 5; // Default: To work for 5s and sleep again
nextSleepinSecs = 5;
} else {
nextSleepinSecs += 5; // When there is pending work, to work another 5s
nextSleepinSecs += 5;
}
}
}
#endif
}
+509
View File
@@ -0,0 +1,509 @@
#ifdef MECK_WIFI_REMOTE
#include "WiFiMQTT.h"
#include <esp_mac.h>
#include <Update.h>
#include <HTTPClient.h>
#include "target.h"
WiFiMQTT wifiMQTT;
#define WIFI_CONFIG_FILE "/remote/wifi.cfg"
#define MQTT_CONFIG_FILE "/remote/mqtt.cfg"
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
void WiFiMQTT::begin() {
Serial.println("[WiFi] begin()");
_state = WiFiMQTTState::OFF;
_cmdHead = _cmdTail = 0;
_rspHead = _rspTail = 0;
_activeNetwork = 0;
if (!loadConfig(_config)) {
Serial.println("[WiFi] ERROR: Missing config files — cannot start");
_state = WiFiMQTTState::ERROR;
return;
}
Serial.printf("[WiFi] Config: %d network(s), broker=%s:%d id=%s\n",
_config.networkCount, _config.broker, _config.port, _config.deviceId);
for (int i = 0; i < _config.networkCount; i++) {
Serial.printf("[WiFi] %d: %s\n", i + 1, _config.networks[i].ssid);
}
snprintf(_topicCmd, sizeof(_topicCmd), "meck/%s/cmd", _config.deviceId);
snprintf(_topicRsp, sizeof(_topicRsp), "meck/%s/rsp", _config.deviceId);
snprintf(_topicTelem, sizeof(_topicTelem), "meck/%s/telemetry", _config.deviceId);
snprintf(_topicOta, sizeof(_topicOta), "meck/%s/ota", _config.deviceId);
// Configure TLS — skip server cert verification (same as cellular)
_wifiClient.setInsecure();
_mqttClient.setClient(_wifiClient);
_mqttClient.setServer(_config.broker, _config.port);
_mqttClient.setCallback(mqttCallback);
_mqttClient.setBufferSize(MQTT_PAYLOAD_MAX + MQTT_TOPIC_MAX);
_state = WiFiMQTTState::WIFI_CONNECTING;
}
void WiFiMQTT::loop() {
if (_state == WiFiMQTTState::OFF || _state == WiFiMQTTState::ERROR) return;
// Check for pending OTA
if (_otaPending && _state == WiFiMQTTState::CONNECTED) {
performOTA();
return;
}
// WiFi connection management
if (WiFi.status() != WL_CONNECTED) {
if (_state == WiFiMQTTState::CONNECTED || _state == WiFiMQTTState::MQTT_CONNECTING) {
Serial.println("[WiFi] Connection lost");
_state = WiFiMQTTState::WIFI_CONNECTING;
}
if (millis() - _lastWifiAttempt > WIFI_RECONNECT_MS) {
connectWiFi();
_lastWifiAttempt = millis();
}
return;
}
// WiFi is up — check MQTT
if (!_mqttClient.connected()) {
if (_state == WiFiMQTTState::CONNECTED) {
Serial.println("[WiFi] MQTT disconnected");
}
_state = WiFiMQTTState::MQTT_CONNECTING;
if (millis() - _lastMqttAttempt > MQTT_RECONNECT_MS) {
connectMQTT();
_lastMqttAttempt = millis();
}
return;
}
// Connected — run MQTT loop
_mqttClient.loop();
// Publish queued responses
publishQueuedResponses();
// Periodic RSSI
if (millis() - _lastRSSI > 30000) {
_rssi = WiFi.RSSI();
_lastRSSI = millis();
}
// Periodic telemetry
if (millis() - _lastTelem > TELEMETRY_INTERVAL) {
publishTelemetry();
_lastTelem = millis();
}
}
bool WiFiMQTT::recvCommand(MQTTCommand& out) {
if (_cmdHead == _cmdTail) return false;
memcpy(&out, &_cmdBuf[_cmdTail], sizeof(MQTTCommand));
_cmdTail = (_cmdTail + 1) % CMD_QUEUE_SIZE;
return true;
}
bool WiFiMQTT::sendResponse(const char* topic, const char* payload) {
int next = (_rspHead + 1) % RSP_QUEUE_SIZE;
if (next == _rspTail) return false; // Full
memset(&_rspBuf[_rspHead], 0, sizeof(MQTTResponse));
strncpy(_rspBuf[_rspHead].topic, topic, MQTT_TOPIC_MAX - 1);
strncpy(_rspBuf[_rspHead].payload, payload, MQTT_PAYLOAD_MAX - 1);
_rspHead = next;
return true;
}
void WiFiMQTT::updateTelemetry(const TelemetryData& data) {
memcpy(&_telemetry, &data, sizeof(data));
}
void WiFiMQTT::requestOTA(const char* url) {
if (_state == WiFiMQTTState::OTA_IN_PROGRESS) return;
strncpy(_otaUrl, url, sizeof(_otaUrl) - 1);
_otaUrl[sizeof(_otaUrl) - 1] = '\0';
_otaPending = true;
Serial.printf("[OTA] Requested: %s\n", url);
}
int WiFiMQTT::getSignalBars() const {
if (_rssi == 0) return 0;
if (_rssi > -50) return 5;
if (_rssi > -60) return 4;
if (_rssi > -70) return 3;
if (_rssi > -80) return 2;
return 1;
}
const char* WiFiMQTT::stateString() const {
switch (_state) {
case WiFiMQTTState::OFF: return "OFF";
case WiFiMQTTState::WIFI_CONNECTING: return "WiFi...";
case WiFiMQTTState::WIFI_CONNECTED: return "WiFi OK";
case WiFiMQTTState::MQTT_CONNECTING: return "MQTT...";
case WiFiMQTTState::CONNECTED: return "CONNECTED";
case WiFiMQTTState::OTA_IN_PROGRESS: return "OTA";
case WiFiMQTTState::ERROR: return "ERROR";
default: return "???";
}
}
// ---------------------------------------------------------------------------
// Config files
//
// /remote/wifi.cfg — SSID/password pairs, two lines each:
// HomeNetwork
// HomePassword
// BackupNetwork
// BackupPassword
//
// /remote/mqtt.cfg — same format as cellular variant
// ---------------------------------------------------------------------------
bool WiFiMQTT::loadConfig(WiFiMQTTConfig& cfg) {
memset(&cfg, 0, sizeof(cfg));
// Determine filesystem: SD if available, otherwise SPIFFS
// Heltec V4 and other headless boards have no SD slot — config lives in SPIFFS.
// Upload config files via: pio run -t uploadfs (with data/ folder)
#if defined(HAS_SDCARD) || defined(SDCARD_CS)
fs::FS& configFS = SD;
Serial.println("[WiFi] Config source: SD card");
#else
fs::FS& configFS = SPIFFS;
Serial.println("[WiFi] Config source: SPIFFS");
#endif
// WiFi config: read SSID/password pairs
File wf = configFS.open(WIFI_CONFIG_FILE, FILE_READ);
if (!wf) {
Serial.printf("[WiFi] No %s\n", WIFI_CONFIG_FILE);
return false;
}
cfg.networkCount = 0;
while (wf.available() && cfg.networkCount < MAX_WIFI_NETWORKS) {
String ssid = wf.readStringUntil('\n'); ssid.trim();
if (ssid.length() == 0) break;
String pass = wf.readStringUntil('\n'); pass.trim();
strncpy(cfg.networks[cfg.networkCount].ssid, ssid.c_str(), sizeof(cfg.networks[0].ssid) - 1);
strncpy(cfg.networks[cfg.networkCount].password, pass.c_str(), sizeof(cfg.networks[0].password) - 1);
cfg.networkCount++;
}
wf.close();
if (cfg.networkCount == 0) {
Serial.println("[WiFi] No networks in wifi.cfg");
return false;
}
// MQTT config: /remote/mqtt.cfg (same format as cellular)
File mf = configFS.open(MQTT_CONFIG_FILE, FILE_READ);
if (!mf) {
Serial.printf("[WiFi] No %s\n", MQTT_CONFIG_FILE);
return false;
}
String line;
line = mf.readStringUntil('\n'); line.trim();
strncpy(cfg.broker, line.c_str(), sizeof(cfg.broker) - 1);
line = mf.readStringUntil('\n'); line.trim();
cfg.port = line.length() > 0 ? line.toInt() : 8883;
line = mf.readStringUntil('\n'); line.trim();
strncpy(cfg.username, line.c_str(), sizeof(cfg.username) - 1);
line = mf.readStringUntil('\n'); line.trim();
strncpy(cfg.password, line.c_str(), sizeof(cfg.password) - 1);
if (mf.available()) {
line = mf.readStringUntil('\n'); line.trim();
if (line.length() > 0) {
strncpy(cfg.deviceId, line.c_str(), sizeof(cfg.deviceId) - 1);
}
}
mf.close();
// Auto-generate device ID if not provided
if (cfg.deviceId[0] == '\0') {
uint8_t mac[6];
esp_efuse_mac_get_default(mac);
snprintf(cfg.deviceId, sizeof(cfg.deviceId), "meck-%02x%02x%02x%02x",
mac[2], mac[3], mac[4], mac[5]);
}
return cfg.broker[0] != '\0';
}
// ---------------------------------------------------------------------------
// WiFi connection — tries each configured network in order
// ---------------------------------------------------------------------------
bool WiFiMQTT::connectWiFi() {
WiFi.mode(WIFI_STA);
for (int n = 0; n < _config.networkCount; n++) {
Serial.printf("[WiFi] Trying %s (%d/%d)...\n",
_config.networks[n].ssid, n + 1, _config.networkCount);
WiFi.begin(_config.networks[n].ssid, _config.networks[n].password);
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < 10000) {
delay(100);
}
if (WiFi.status() == WL_CONNECTED) {
IPAddress ip = WiFi.localIP();
snprintf(_ipAddr, sizeof(_ipAddr), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
_rssi = WiFi.RSSI();
_activeNetwork = n;
Serial.printf("[WiFi] Connected to %s — IP: %s RSSI: %d\n",
_config.networks[n].ssid, _ipAddr, _rssi);
if (WiFi.status() == WL_CONNECTED) {
IPAddress ip = WiFi.localIP();
snprintf(_ipAddr, sizeof(_ipAddr), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
_rssi = WiFi.RSSI();
_activeNetwork = n;
Serial.printf("[WiFi] Connected to %s — IP: %s RSSI: %d\n",
_config.networks[n].ssid, _ipAddr, _rssi);
// Sync clock via NTP
configTime(0, 0, "pool.ntp.org", "time.google.com");
Serial.print("[WiFi] NTP sync...");
int tries = 0;
while (time(nullptr) < 1700000000 && tries < 20) {
delay(500);
tries++;
}
time_t now = time(nullptr);
if (now > 1700000000) {
extern AutoDiscoverRTCClock rtc_clock;
rtc_clock.setCurrentTime((uint32_t)now);
Serial.printf(" OK (%lu)\n", (unsigned long)now);
} else {
Serial.println(" timeout");
}
_state = WiFiMQTTState::WIFI_CONNECTED;
return true;
}
}
WiFi.disconnect();
delay(500);
}
Serial.println("[WiFi] All networks failed");
return false;
}
// ---------------------------------------------------------------------------
// MQTT connection
// ---------------------------------------------------------------------------
bool WiFiMQTT::connectMQTT() {
Serial.printf("[WiFi] MQTT connecting to %s:%d...\n", _config.broker, _config.port);
char clientId[48];
snprintf(clientId, sizeof(clientId), "%s-%lu", _config.deviceId, millis() & 0xFFFF);
if (_mqttClient.connect(clientId, _config.username, _config.password)) {
Serial.println("[WiFi] MQTT connected!");
_mqttClient.subscribe(_topicCmd, 1);
_mqttClient.subscribe(_topicOta, 1);
_state = WiFiMQTTState::CONNECTED;
// Publish boot event
_mqttClient.publish(_topicTelem, "{\"event\":\"boot\",\"state\":\"connected\"}", true);
return true;
}
Serial.printf("[WiFi] MQTT connect failed, rc=%d\n", _mqttClient.state());
return false;
}
// ---------------------------------------------------------------------------
// MQTT message callback
// ---------------------------------------------------------------------------
void WiFiMQTT::mqttCallback(char* topic, byte* payload, unsigned int length) {
wifiMQTT.onMessage(topic, payload, length);
}
void WiFiMQTT::onMessage(char* topic, byte* payload, unsigned int length) {
char buf[MQTT_PAYLOAD_MAX];
int len = (length < MQTT_PAYLOAD_MAX - 1) ? length : MQTT_PAYLOAD_MAX - 1;
memcpy(buf, payload, len);
buf[len] = '\0';
Serial.printf("[WiFi] RX [%s]: %.80s\n", topic, buf);
if (strstr(topic, "/cmd")) {
int next = (_cmdHead + 1) % CMD_QUEUE_SIZE;
if (next != _cmdTail) {
memset(&_cmdBuf[_cmdHead], 0, sizeof(MQTTCommand));
strncpy(_cmdBuf[_cmdHead].cmd, buf, MQTT_PAYLOAD_MAX - 1);
_cmdHead = next;
Serial.printf("[WiFi] Queued CLI: %s\n", buf);
} else {
Serial.println("[WiFi] Command queue full");
}
} else if (strstr(topic, "/ota")) {
requestOTA(buf);
}
}
// ---------------------------------------------------------------------------
// Publish helpers
// ---------------------------------------------------------------------------
void WiFiMQTT::publishQueuedResponses() {
while (_rspHead != _rspTail) {
_mqttClient.publish(_rspBuf[_rspTail].topic, _rspBuf[_rspTail].payload);
_rspTail = (_rspTail + 1) % RSP_QUEUE_SIZE;
}
}
void WiFiMQTT::publishTelemetry() {
_rssi = WiFi.RSSI();
char json[400];
snprintf(json, sizeof(json),
"{\"uptime\":%lu,\"batt_mv\":%d,\"batt_pct\":%d,\"temp\":%.1f,"
"\"rssi\":%d,\"bars\":%d,\"neighbors\":%d,"
"\"freq\":%.3f,\"bw\":%.1f,\"sf\":%d,\"cr\":%d,\"tx\":%d,"
"\"name\":\"%s\",\"ip\":\"%s\",\"ssid\":\"%s\","
"\"heap\":%d}",
_telemetry.uptime_secs, _telemetry.battery_mv, _telemetry.battery_pct,
_telemetry.temperature / 10.0f,
_rssi, getSignalBars(), _telemetry.neighbor_count,
_telemetry.freq, _telemetry.bw, _telemetry.sf, _telemetry.cr, _telemetry.tx_power,
_telemetry.node_name, _ipAddr, _config.networks[_activeNetwork].ssid,
ESP.getFreeHeap());
_mqttClient.publish(_topicTelem, json);
}
// ---------------------------------------------------------------------------
// OTA — HTTP download over WiFi + ESP32 flash
// ---------------------------------------------------------------------------
void WiFiMQTT::performOTA() {
_otaPending = false;
_state = WiFiMQTTState::OTA_IN_PROGRESS;
Serial.printf("[OTA] URL: %s\n", _otaUrl);
_mqttClient.publish(_topicRsp, "OTA: Starting download...");
_mqttClient.loop();
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.setTimeout(180000);
if (!http.begin(_wifiClient, _otaUrl)) {
Serial.println("[OTA] HTTP begin failed");
_mqttClient.publish(_topicRsp, "OTA: HTTP begin failed");
_state = WiFiMQTTState::CONNECTED;
return;
}
int httpCode = http.GET();
if (httpCode != HTTP_CODE_OK) {
Serial.printf("[OTA] HTTP error: %d\n", httpCode);
char msg[60];
snprintf(msg, sizeof(msg), "OTA: HTTP error %d", httpCode);
_mqttClient.publish(_topicRsp, msg);
http.end();
_state = WiFiMQTTState::CONNECTED;
return;
}
int fileSize = http.getSize();
if (fileSize <= 0) {
Serial.println("[OTA] Unknown content length");
_mqttClient.publish(_topicRsp, "OTA: Unknown file size");
http.end();
_state = WiFiMQTTState::CONNECTED;
return;
}
Serial.printf("[OTA] File size: %d bytes\n", fileSize);
if (!Update.begin(fileSize)) {
Serial.printf("[OTA] Update.begin failed: %s\n", Update.errorString());
_mqttClient.publish(_topicRsp, "OTA: Flash init failed");
http.end();
_state = WiFiMQTTState::CONNECTED;
return;
}
WiFiClient* stream = http.getStreamPtr();
uint8_t buf[1024];
int offset = 0;
int lastPct = -1;
while (offset < fileSize) {
int avail = stream->available();
if (avail <= 0) {
if (!stream->connected()) break;
delay(10);
continue;
}
int toRead = (avail < (int)sizeof(buf)) ? avail : sizeof(buf);
int got = stream->readBytes(buf, toRead);
if (got <= 0) break;
size_t written = Update.write(buf, got);
if (written != (size_t)got) {
Serial.printf("[OTA] Write failed: %d of %d\n", written, got);
break;
}
offset += got;
int pct = (offset * 100) / fileSize;
if (pct / 10 != lastPct / 10) {
Serial.printf("[OTA] Progress: %d%% (%d/%d)\n", pct, offset, fileSize);
char msg[60];
snprintf(msg, sizeof(msg), "OTA: Flashing %d%%", pct);
_mqttClient.publish(_topicRsp, msg);
_mqttClient.loop();
lastPct = pct;
}
delay(1);
}
http.end();
if (offset < fileSize) {
Serial.printf("[OTA] Incomplete: %d of %d\n", offset, fileSize);
Update.abort();
_mqttClient.publish(_topicRsp, "OTA: Download incomplete");
_state = WiFiMQTTState::CONNECTED;
return;
}
if (!Update.end(true)) {
Serial.printf("[OTA] Update.end failed: %s\n", Update.errorString());
_mqttClient.publish(_topicRsp, "OTA: Verification failed");
_state = WiFiMQTTState::CONNECTED;
return;
}
Serial.println("[OTA] SUCCESS — rebooting in 3 seconds");
_mqttClient.publish(_topicRsp, "OTA: Success! Rebooting...");
_mqttClient.loop();
delay(3000);
ESP.restart();
}
#endif // MECK_WIFI_REMOTE
+191
View File
@@ -0,0 +1,191 @@
#pragma once
// =============================================================================
// WiFiMQTT — WiFi + MQTT for audio variant remote repeater
//
// Same interface as CellularMQTT but uses ESP32 native WiFi + PubSubClient.
// No modem, no AT commands, no FreeRTOS task — runs in the main loop.
//
// Supports multiple WiFi networks in wifi.cfg (SSID/password pairs).
// Tries each in order on connect/reconnect.
//
// Guard: MECK_WIFI_REMOTE (set in platformio env build_flags)
// =============================================================================
#ifdef MECK_WIFI_REMOTE
#ifndef WIFI_MQTT_H
#define WIFI_MQTT_H
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#if defined(HAS_SDCARD) || defined(SDCARD_CS)
#include <SD.h>
#endif
#include <SPIFFS.h>
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
#define MQTT_TOPIC_MAX 80
#define MQTT_PAYLOAD_MAX 512
#define MQTT_CLIENT_ID_MAX 32
#define CMD_QUEUE_SIZE 8
#define RSP_QUEUE_SIZE 8
#define MAX_WIFI_NETWORKS 4
#define TELEMETRY_INTERVAL 60000 // 60 seconds
#define WIFI_RECONNECT_MS 10000 // 10 seconds between WiFi reconnect attempts
#define MQTT_RECONNECT_MS 5000 // 5 seconds between MQTT reconnect attempts
// ---------------------------------------------------------------------------
// State machine
// ---------------------------------------------------------------------------
enum class WiFiMQTTState : uint8_t {
OFF,
WIFI_CONNECTING,
WIFI_CONNECTED,
MQTT_CONNECTING,
CONNECTED,
OTA_IN_PROGRESS,
ERROR
};
// ---------------------------------------------------------------------------
// Queue message types (same as CellularMQTT for compatibility)
// ---------------------------------------------------------------------------
struct MQTTCommand {
char cmd[MQTT_PAYLOAD_MAX];
};
struct MQTTResponse {
char topic[MQTT_TOPIC_MAX];
char payload[MQTT_PAYLOAD_MAX];
};
// ---------------------------------------------------------------------------
// Config (loaded from SD)
// ---------------------------------------------------------------------------
struct WiFiNetwork {
char ssid[40];
char password[64];
};
struct WiFiMQTTConfig {
WiFiNetwork networks[MAX_WIFI_NETWORKS];
int networkCount;
char broker[80];
uint16_t port; // 8883 for MQTT TLS
char username[40];
char password[40];
char deviceId[MQTT_CLIENT_ID_MAX];
};
// ---------------------------------------------------------------------------
// Telemetry snapshot
// ---------------------------------------------------------------------------
struct TelemetryData {
uint32_t uptime_secs;
uint16_t battery_mv;
uint8_t battery_pct;
int16_t temperature;
int rssi;
uint8_t neighbor_count;
float freq;
float bw;
uint8_t sf;
uint8_t cr;
uint8_t tx_power;
char node_name[32];
bool mqtt_connected;
};
// ---------------------------------------------------------------------------
// WiFiMQTT class
// ---------------------------------------------------------------------------
class WiFiMQTT {
public:
void begin();
void loop(); // Call from main loop — handles WiFi, MQTT, publish/subscribe
// --- Queue API (called from main loop) ---
bool recvCommand(MQTTCommand& out);
bool sendResponse(const char* topic, const char* payload);
// --- Telemetry ---
void updateTelemetry(const TelemetryData& data);
// --- OTA ---
void requestOTA(const char* url);
bool isOTAInProgress() const { return _state == WiFiMQTTState::OTA_IN_PROGRESS; }
// --- State queries ---
WiFiMQTTState getState() const { return _state; }
bool isConnected() const { return _state == WiFiMQTTState::CONNECTED; }
int getRSSI() const { return _rssi; }
int getSignalBars() const;
const char* getSSID() const { return _config.networks[_activeNetwork].ssid; }
const char* getIPAddress() const { return _ipAddr; }
const char* getBroker() const { return _config.broker; }
const char* getRspTopic() const { return _topicRsp; }
const char* stateString() const;
static bool loadConfig(WiFiMQTTConfig& cfg);
private:
WiFiMQTTState _state = WiFiMQTTState::OFF;
int _rssi = 0;
int _activeNetwork = 0;
char _ipAddr[20] = {0};
WiFiMQTTConfig _config = {};
TelemetryData _telemetry = {};
// Topic strings
char _topicCmd[MQTT_TOPIC_MAX] = {0};
char _topicRsp[MQTT_TOPIC_MAX] = {0};
char _topicTelem[MQTT_TOPIC_MAX] = {0};
char _topicOta[MQTT_TOPIC_MAX] = {0};
// Command/response ring buffers (no FreeRTOS queues needed — single-threaded)
MQTTCommand _cmdBuf[CMD_QUEUE_SIZE];
int _cmdHead = 0, _cmdTail = 0;
MQTTResponse _rspBuf[RSP_QUEUE_SIZE];
int _rspHead = 0, _rspTail = 0;
// MQTT client stack
WiFiClientSecure _wifiClient;
PubSubClient _mqttClient;
// Timers
unsigned long _lastWifiAttempt = 0;
unsigned long _lastMqttAttempt = 0;
unsigned long _lastTelem = 0;
unsigned long _lastRSSI = 0;
// OTA state
bool _otaPending = false;
char _otaUrl[256] = {0};
// --- Internal ---
bool connectWiFi();
bool connectMQTT();
void publishTelemetry();
void publishQueuedResponses();
void performOTA();
// PubSubClient callback (static → instance)
static void mqttCallback(char* topic, byte* payload, unsigned int length);
void onMessage(char* topic, byte* payload, unsigned int length);
};
extern WiFiMQTT wifiMQTT;
#endif // WIFI_MQTT_H
#endif // MECK_WIFI_REMOTE
+159
View File
@@ -0,0 +1,159 @@
"""
PlatformIO post-build script: merge bootloader + partitions + firmware + SPIFFS
into a single flashable binary.
Includes a pre-formatted empty SPIFFS image so first-boot doesn't need to
format the partition (which takes 1-2 minutes on 16MB flash).
Output: .pio/build/<env>/firmware_merged.bin
Flash: esptool.py --chip esp32s3 write_flash 0x0 firmware_merged.bin
Place this file in the project root alongside platformio.ini.
Add to each environment (or the base section):
extra_scripts = post:merge_firmware.py
"""
Import("env")
def find_spiffs_partition(partitions_bin):
"""Parse compiled partitions.bin to find SPIFFS partition offset and size.
ESP32 partition entry format (32 bytes each):
0xAA50 magic, type, subtype, offset(u32le), size(u32le), label(16), flags(u32le)
SPIFFS: type=0x01(data), subtype=0x82(spiffs)
"""
import struct
with open(partitions_bin, "rb") as f:
data = f.read()
for i in range(0, len(data) - 32, 32):
magic = struct.unpack_from("<H", data, i)[0]
if magic != 0xAA50:
continue
ptype = data[i + 2]
subtype = data[i + 3]
offset = struct.unpack_from("<I", data, i + 4)[0]
size = struct.unpack_from("<I", data, i + 8)[0]
label = data[i + 12:i + 28].split(b'\x00')[0].decode("ascii", errors="ignore")
if ptype == 0x01 and subtype == 0x82: # data/spiffs
return offset, size, label
return None, None, None
def build_spiffs_image(env, size):
"""Generate an empty formatted SPIFFS image using mkspiffs."""
import subprocess, os, tempfile, glob
build_dir = env.subst("$BUILD_DIR")
spiffs_bin = os.path.join(build_dir, "spiffs_empty.bin")
# If already generated for this build, reuse it
if os.path.isfile(spiffs_bin) and os.path.getsize(spiffs_bin) == size:
return spiffs_bin
# Find mkspiffs in PlatformIO packages
pio_home = os.path.expanduser("~/.platformio")
mkspiffs_paths = glob.glob(os.path.join(pio_home, "packages", "tool-mkspiffs*", "mkspiffs*"))
if not mkspiffs_paths:
# Also check platform-specific tool paths
mkspiffs_paths = glob.glob(os.path.join(pio_home, "packages", "tool-mklittlefs*", "mkspiffs*"))
mkspiffs = None
for p in mkspiffs_paths:
if os.path.isfile(p) and os.access(p, os.X_OK):
mkspiffs = p
break
if not mkspiffs:
print("[merge] WARNING: mkspiffs not found, skipping SPIFFS image")
return None
# Create empty data directory for mkspiffs
data_dir = os.path.join(build_dir, "_empty_spiffs_data")
os.makedirs(data_dir, exist_ok=True)
# SPIFFS block/page sizes — ESP32 Arduino defaults
block_size = 4096
page_size = 256
cmd = [
mkspiffs,
"-c", data_dir,
"-b", str(block_size),
"-p", str(page_size),
"-s", str(size),
spiffs_bin,
]
print(f"[merge] Generating empty SPIFFS image ({size // 1024} KB)...")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0 and os.path.isfile(spiffs_bin):
print(f"[merge] SPIFFS image OK: {spiffs_bin}")
return spiffs_bin
else:
print(f"[merge] mkspiffs failed: {result.stderr}")
return None
def merge_bin(source, target, env):
import subprocess, os
build_dir = env.subst("$BUILD_DIR")
env_name = env.subst("$PIOENV")
bootloader = os.path.join(build_dir, "bootloader.bin")
partitions = os.path.join(build_dir, "partitions.bin")
firmware = os.path.join(build_dir, "firmware.bin")
output = os.path.join(build_dir, "firmware-merged.bin")
# Verify all inputs exist
for f in [bootloader, partitions, firmware]:
if not os.path.isfile(f):
print(f"[merge] WARNING: {f} not found, skipping merge")
return
# Read flash settings from board config
flash_mode = env.BoardConfig().get("build.flash_mode", "qio")
flash_freq = env.BoardConfig().get("build.f_flash", "80000000L").rstrip("L")
flash_size = env.BoardConfig().get("upload.flash_size", "16MB")
mcu = env.BoardConfig().get("build.mcu", "esp32s3")
# Convert numeric frequency to esptool format
freq_map = {"80000000": "80m", "40000000": "40m", "26000000": "26m", "20000000": "20m"}
flash_freq_str = freq_map.get(flash_freq, "80m")
cmd = [
env.subst("$PYTHONEXE"), "-m", "esptool",
"--chip", mcu,
"merge_bin",
"-o", output,
"--flash_mode", flash_mode,
"--flash_freq", flash_freq_str,
"--flash_size", flash_size,
"0x0", bootloader,
"0x8000", partitions,
"0x10000", firmware,
]
# Try to include a pre-formatted SPIFFS image (eliminates 1-2 min first-boot format)
spiffs_offset, spiffs_size, spiffs_label = find_spiffs_partition(partitions)
if spiffs_offset and spiffs_size:
spiffs_bin = build_spiffs_image(env, spiffs_size)
if spiffs_bin:
cmd.extend([f"0x{spiffs_offset:x}", spiffs_bin])
print(f"[merge] Including SPIFFS image at 0x{spiffs_offset:x} ({spiffs_size // 1024} KB)")
else:
print("[merge] No SPIFFS partition found in partition table, skipping SPIFFS image")
print(f"\n[merge] Creating merged firmware for {env_name}...")
print(f"[merge] {' '.join(cmd[-8:])}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
size_kb = os.path.getsize(output) / 1024
print(f"[merge] OK: {output} ({size_kb:.0f} KB)")
else:
print(f"[merge] FAILED: {result.stderr}")
env.AddPostAction("$BUILD_DIR/firmware.bin", merge_bin)
+7 -5
View File
@@ -27,6 +27,7 @@ build_flags = -w -DNDEBUG -DRADIOLIB_STATIC_ONLY=1 -DRADIOLIB_GODMODE=1
-D LORA_FREQ=869.525
-D LORA_BW=250
-D LORA_SF=11
-D ENABLE_ADVERT_ON_BOOT=1
-D ENABLE_PRIVATE_KEY_IMPORT=1 ; NOTE: comment these out for more secure firmware
-D ENABLE_PRIVATE_KEY_EXPORT=1
-D RADIOLIB_EXCLUDE_CC1101=1
@@ -55,9 +56,10 @@ build_src_filter =
[esp32_base]
extends = arduino_base
platform = platformio/espressif32@6.11.0
monitor_filters = esp32_exception_decoder
monitor_filters = esp32_exception_decoder, clock_sync
extra_scripts = merge-bin.py
build_flags = ${arduino_base.build_flags}
-D ESP32_PLATFORM
; -D ESP32_CPU_FREQ=80 ; change it to your need
build_src_filter = ${arduino_base.build_src_filter}
@@ -67,10 +69,10 @@ lib_deps =
file://arch/esp32/AsyncElegantOTA
; esp32c6 uses arduino framework 3.x
; WARNING: experimental. pioarduino on esp32c6 needs work - it's not considered stable and has issues.
; WARNING: experimental. May not work as stable as other platforms.
[esp32c6_base]
extends = esp32_base
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.12/platform-espressif32.zip
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.13-1/platform-espressif32.zip
; ----------------- NRF52 ---------------------
@@ -79,7 +81,7 @@ extends = arduino_base
platform = nordicnrf52
platform_packages =
framework-arduinoadafruitnrf52 @ 1.10700.0
extra_scripts =
extra_scripts =
create-uf2.py
arch/nrf52/extra_scripts/patch_bluefruit.py
build_flags = ${arduino_base.build_flags}
@@ -147,4 +149,4 @@ lib_deps =
adafruit/Adafruit_VL53L0X @ ^1.2.4
stevemarple/MicroNMEA @ ^2.0.6
adafruit/Adafruit BME680 Library @ ^2.0.4
adafruit/Adafruit BMP085 Library @ ^1.2.4
adafruit/Adafruit BMP085 Library @ ^1.2.4
BIN
View File
Binary file not shown.
+48 -11
View File
@@ -36,7 +36,7 @@ uint32_t Dispatcher::getCADFailRetryDelay() const {
return 200;
}
uint32_t Dispatcher::getCADFailMaxDuration() const {
return 4000; // 4 seconds
return 6000; // 6 seconds
}
void Dispatcher::loop() {
@@ -52,10 +52,28 @@ void Dispatcher::loop() {
prev_isrecv_mode = is_recv;
if (!is_recv) {
radio_nonrx_start = _ms->getMillis();
} else {
rx_stuck_count = 0; // radio recovered — reset counter
}
}
if (!is_recv && _ms->getMillis() - radio_nonrx_start > 8000) { // radio has not been in Rx mode for 8 seconds!
_err_flags |= ERR_EVENT_STARTRX_TIMEOUT;
rx_stuck_count++;
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): RX stuck (attempt %d), calling onRxStuck()", getLogDateTime(), rx_stuck_count);
onRxStuck();
uint8_t reboot_threshold = getRxFailRebootThreshold();
if (reboot_threshold > 0 && rx_stuck_count >= reboot_threshold) {
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): RX unrecoverable after %d attempts", getLogDateTime(), rx_stuck_count);
onRxUnrecoverable();
}
// Reset state to give recovery the full 8s window before re-triggering
radio_nonrx_start = _ms->getMillis();
prev_isrecv_mode = true;
cad_busy_start = 0;
next_agc_reset_time = futureMillis(getAGCResetInterval());
}
if (outbound) { // waiting for outbound send to be completed
@@ -68,7 +86,7 @@ void Dispatcher::loop() {
next_tx_time = futureMillis(t * getAirtimeBudgetFactor());
_radio->onSendFinished();
logTx(outbound, 2 + outbound->path_len + outbound->payload_len);
logTx(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
if (outbound->isRouteFlood()) {
n_sent_flood++;
} else {
@@ -80,7 +98,7 @@ void Dispatcher::loop() {
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): WARNING: outbound packed send timed out!", getLogDateTime());
_radio->onSendFinished();
logTxFail(outbound, 2 + outbound->path_len + outbound->payload_len);
logTxFail(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
releasePacket(outbound); // return to pool
outbound = NULL;
@@ -141,12 +159,13 @@ void Dispatcher::checkRecv() {
}
pkt->path_len = raw[i++];
if (pkt->path_len > MAX_PATH_SIZE || i + pkt->path_len > len) {
uint16_t path_byte_len = pkt->getPathByteLen();
if (path_byte_len > MAX_PATH_SIZE || i + path_byte_len > len) {
MESH_DEBUG_PRINTLN("%s Dispatcher::checkRecv(): partial or corrupt packet received, len=%d", getLogDateTime(), len);
_mgr->free(pkt); // put back into pool
pkt = NULL;
} else {
memcpy(pkt->path, &raw[i], pkt->path_len); i += pkt->path_len;
memcpy(pkt->path, &raw[i], path_byte_len); i += path_byte_len;
pkt->payload_len = len - i; // payload is remainder
if (pkt->payload_len > sizeof(pkt->payload)) {
@@ -258,7 +277,8 @@ void Dispatcher::checkSend() {
memcpy(&raw[len], &outbound->transport_codes[1], 2); len += 2;
}
raw[len++] = outbound->path_len;
memcpy(&raw[len], outbound->path, outbound->path_len); len += outbound->path_len;
uint16_t out_pbl = outbound->getPathByteLen();
memcpy(&raw[len], outbound->path, out_pbl); len += out_pbl;
if (len + outbound->payload_len > MAX_TRANS_UNIT) {
MESH_DEBUG_PRINTLN("%s Dispatcher::checkSend(): FATAL: Invalid packet queued... too long, len=%d", getLogDateTime(), len + outbound->payload_len);
@@ -271,14 +291,31 @@ void Dispatcher::checkSend() {
outbound_start = _ms->getMillis();
bool success = _radio->startSendRaw(raw, len);
if (!success) {
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): ERROR: send start failed!", getLogDateTime());
MESH_DEBUG_PRINTLN("%s Dispatcher::checkSend(): ERROR: send start failed!", getLogDateTime());
logTxFail(outbound, outbound->getRawLength());
releasePacket(outbound); // return to pool
// re-queue packet for retry instead of dropping it
int retry_delay = getCADFailRetryDelay();
unsigned long retry_time = futureMillis(retry_delay);
_mgr->queueOutbound(outbound, 0, retry_time);
outbound = NULL;
next_tx_time = retry_time;
// count consecutive failures and reset radio if stuck
uint8_t threshold = getTxFailResetThreshold();
if (threshold > 0) {
tx_fail_count++;
if (tx_fail_count >= threshold) {
MESH_DEBUG_PRINTLN("%s Dispatcher::checkSend(): TX stuck (%d failures), resetting radio", getLogDateTime(), tx_fail_count);
onTxStuck();
tx_fail_count = 0;
next_tx_time = futureMillis(2000);
}
}
return;
}
tx_fail_count = 0; // clear counter on successful TX start
outbound_expiry = futureMillis(max_airtime);
#if MESH_PACKET_LOGGING
@@ -312,8 +349,8 @@ void Dispatcher::releasePacket(Packet* packet) {
}
void Dispatcher::sendPacket(Packet* packet, uint8_t priority, uint32_t delay_millis) {
if (packet->path_len > MAX_PATH_SIZE || packet->payload_len > MAX_PACKET_PAYLOAD) {
MESH_DEBUG_PRINTLN("%s Dispatcher::sendPacket(): ERROR: invalid packet... path_len=%d, payload_len=%d", getLogDateTime(), (uint32_t) packet->path_len, (uint32_t) packet->payload_len);
if (packet->getPathByteLen() > MAX_PATH_SIZE || packet->payload_len > MAX_PACKET_PAYLOAD) {
MESH_DEBUG_PRINTLN("%s Dispatcher::sendPacket(): ERROR: invalid packet... path_len=%d (byte_len=%d), payload_len=%d", getLogDateTime(), (uint32_t) packet->path_len, (uint32_t) packet->getPathByteLen(), (uint32_t) packet->payload_len);
_mgr->free(packet);
} else {
_mgr->queueOutbound(packet, priority, futureMillis(delay_millis));
+10 -1
View File
@@ -122,6 +122,8 @@ class Dispatcher {
bool prev_isrecv_mode;
uint32_t n_sent_flood, n_sent_direct;
uint32_t n_recv_flood, n_recv_direct;
uint8_t tx_fail_count;
uint8_t rx_stuck_count;
void processRecvPacket(Packet* pkt);
@@ -142,6 +144,8 @@ protected:
_err_flags = 0;
radio_nonrx_start = 0;
prev_isrecv_mode = true;
tx_fail_count = 0;
rx_stuck_count = 0;
}
virtual DispatcherAction onRecvPacket(Packet* pkt) = 0;
@@ -159,6 +163,11 @@ protected:
virtual uint32_t getCADFailMaxDuration() const;
virtual int getInterferenceThreshold() const { return 0; } // disabled by default
virtual int getAGCResetInterval() const { return 0; } // disabled by default
virtual uint8_t getTxFailResetThreshold() const { return 3; } // reset radio after N consecutive TX failures; 0=disabled
virtual void onTxStuck() { _radio->resetAGC(); } // override to use doFullRadioReset() when available
virtual uint8_t getRxFailRebootThreshold() const { return 3; } // reboot after N failed RX recovery attempts; 0=disabled
virtual void onRxStuck() { _radio->resetAGC(); } // called each time RX stuck for 8s; override for deeper reset
virtual void onRxUnrecoverable() { } // called when reboot threshold exceeded; override to call _board->reboot()
public:
void begin();
@@ -188,4 +197,4 @@ private:
void checkSend();
};
}
}
+5 -2
View File
@@ -20,6 +20,10 @@ public:
memcpy(dest, pub_key, PATH_HASH_SIZE); // hash is just prefix of pub_key
return PATH_HASH_SIZE;
}
int copyHashTo(uint8_t* dest, uint8_t len) const {
memcpy(dest, pub_key, len);
return len;
}
bool isHashMatch(const uint8_t* hash) const {
return memcmp(hash, pub_key, PATH_HASH_SIZE) == 0;
}
@@ -90,5 +94,4 @@ public:
void readFrom(const uint8_t* src, size_t len);
};
}
}
+42 -32
View File
@@ -15,7 +15,7 @@ bool Mesh::allowPacketForward(const mesh::Packet* packet) {
return false; // by default, Transport NOT enabled
}
uint32_t Mesh::getRetransmitDelay(const mesh::Packet* packet) {
uint32_t t = (_radio->getEstAirtimeFor(packet->getRawLength()) * 52 / 50) / 2;
uint32_t t = (uint32_t)(_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * 0.5f);
return _rng->nextInt(0, 5)*t;
}
@@ -77,7 +77,9 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
return ACTION_RELEASE;
}
if (pkt->isRouteDirect() && pkt->path_len >= PATH_HASH_SIZE) {
if (pkt->isRouteDirect() && (pkt->path_len & 63) > 0) {
uint8_t dir_bph = (pkt->path_len >> 6) + 1; // bytes per hop for this packet
// check for 'early received' ACK
if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) {
int i = 0;
@@ -88,7 +90,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
}
}
if (self_id.isHashMatch(pkt->path) && allowPacketForward(pkt)) {
if (self_id.isHashMatch(pkt->path, dir_bph) && allowPacketForward(pkt)) {
if (pkt->getPayloadType() == PAYLOAD_TYPE_MULTIPART) {
return forwardMultipartDirect(pkt);
} else if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) {
@@ -158,7 +160,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH) {
int k = 0;
uint8_t path_len = data[k++];
uint8_t* path = &data[k]; k += path_len;
uint8_t* path = &data[k]; k += Packet::getPathByteLenFor(path_len);
uint8_t extra_type = data[k++] & 0x0F; // upper 4 bits reserved for future use
uint8_t* extra = &data[k];
uint8_t extra_len = len - k; // remainder of packet (may be padded with zeroes!)
@@ -293,8 +295,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
if (type == PAYLOAD_TYPE_ACK && pkt->payload_len >= 5) { // a multipart ACK
Packet tmp;
tmp.header = pkt->header;
tmp.path_len = pkt->path_len;
memcpy(tmp.path, pkt->path, pkt->path_len);
tmp.path_len = Packet::copyPath(tmp.path, pkt->path, pkt->path_len);
tmp.payload_len = pkt->payload_len - 1;
memcpy(tmp.payload, &pkt->payload[1], tmp.payload_len);
@@ -320,28 +321,34 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
}
void Mesh::removeSelfFromPath(Packet* pkt) {
// remove our hash from 'path'
pkt->path_len -= PATH_HASH_SIZE;
#if 0
memcpy(pkt->path, &pkt->path[PATH_HASH_SIZE], pkt->path_len);
#elif PATH_HASH_SIZE == 1
for (int k = 0; k < pkt->path_len; k++) { // shuffle bytes by 1
pkt->path[k] = pkt->path[k + 1];
}
#else
#error "need path remove impl"
#endif
uint8_t bph = (pkt->path_len >> 6) + 1; // bytes per hop
uint8_t hops = pkt->path_len & 63;
if (hops == 0) return;
uint16_t new_byte_len = (hops - 1) * bph;
// remove first bph bytes (our hash) from path, shift remainder
memmove(pkt->path, &pkt->path[bph], new_byte_len);
// decrement hop count, preserve mode bits
pkt->path_len = (pkt->path_len & 0xC0) | ((hops - 1) & 63);
}
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
&& packet->path_len + PATH_HASH_SIZE <= MAX_PATH_SIZE && allowPacketForward(packet)) {
// append this node's hash to 'path'
packet->path_len += self_id.copyHashTo(&packet->path[packet->path_len]);
&& allowPacketForward(packet)) {
uint8_t bph = (packet->path_len >> 6) + 1; // bytes per hop
uint8_t hops = packet->path_len & 63;
uint16_t byte_len = hops * bph;
uint32_t d = getRetransmitDelay(packet);
// as this propagates outwards, give it lower and lower priority
return ACTION_RETRANSMIT_DELAYED(packet->path_len, d); // give priority to closer sources, than ones further away
if (byte_len + bph <= MAX_PATH_SIZE) {
// append this node's hash (bph bytes of pub_key) to path
memcpy(&packet->path[byte_len], self_id.pub_key, bph);
// increment hop count, preserve mode bits
packet->path_len = (packet->path_len & 0xC0) | ((hops + 1) & 63);
uint32_t d = getRetransmitDelay(packet);
// as this propagates outwards, give it lower and lower priority
return ACTION_RETRANSMIT_DELAYED(hops + 1, d); // give priority to closer sources, than ones further away
}
}
return ACTION_RELEASE;
}
@@ -353,8 +360,7 @@ DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) {
if (type == PAYLOAD_TYPE_ACK && pkt->payload_len >= 5) { // a multipart ACK
Packet tmp;
tmp.header = pkt->header;
tmp.path_len = pkt->path_len;
memcpy(tmp.path, pkt->path, pkt->path_len);
tmp.path_len = Packet::copyPath(tmp.path, pkt->path, pkt->path_len);
tmp.payload_len = pkt->payload_len - 1;
memcpy(tmp.payload, &pkt->payload[1], tmp.payload_len);
@@ -376,7 +382,7 @@ void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
delay_millis += getDirectRetransmitDelay(packet) + 300;
auto a1 = createMultiAck(crc, extra);
if (a1) {
memcpy(a1->path, packet->path, a1->path_len = packet->path_len);
a1->path_len = Packet::copyPath(a1->path, packet->path, packet->path_len);
a1->header &= ~PH_ROUTE_MASK;
a1->header |= ROUTE_TYPE_DIRECT;
sendPacket(a1, 0, delay_millis);
@@ -386,7 +392,7 @@ void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
auto a2 = createAck(crc);
if (a2) {
memcpy(a2->path, packet->path, a2->path_len = packet->path_len);
a2->path_len = Packet::copyPath(a2->path, packet->path, packet->path_len);
a2->header &= ~PH_ROUTE_MASK;
a2->header |= ROUTE_TYPE_DIRECT;
sendPacket(a2, 0, delay_millis);
@@ -624,7 +630,7 @@ Packet* Mesh::createControlData(const uint8_t* data, size_t len) {
return packet;
}
void Mesh::sendFlood(Packet* packet, uint32_t delay_millis) {
void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_bytes_per_hop) {
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) {
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
return;
@@ -632,7 +638,9 @@ void Mesh::sendFlood(Packet* packet, uint32_t delay_millis) {
packet->header &= ~PH_ROUTE_MASK;
packet->header |= ROUTE_TYPE_FLOOD;
packet->path_len = 0;
// encode bytes-per-hop mode in upper 2 bits of path_len, 0 hops initially
uint8_t mode = (path_bytes_per_hop > 1) ? (path_bytes_per_hop - 1) : 0;
packet->path_len = (mode << 6);
_tables->hasSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
@@ -647,7 +655,7 @@ void Mesh::sendFlood(Packet* packet, uint32_t delay_millis) {
sendPacket(packet, pri, delay_millis);
}
void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis) {
void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis, uint8_t path_bytes_per_hop) {
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) {
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
return;
@@ -657,7 +665,9 @@ void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_m
packet->header |= ROUTE_TYPE_TRANSPORT_FLOOD;
packet->transport_codes[0] = transport_codes[0];
packet->transport_codes[1] = transport_codes[1];
packet->path_len = 0;
// encode bytes-per-hop mode in upper 2 bits of path_len, 0 hops initially
uint8_t mode = (path_bytes_per_hop > 1) ? (path_bytes_per_hop - 1) : 0;
packet->path_len = (mode << 6);
_tables->hasSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
@@ -685,7 +695,7 @@ void Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uin
packet->path_len = 0;
pri = 5; // maybe make this configurable
} else {
memcpy(packet->path, path, packet->path_len = path_len);
packet->path_len = Packet::copyPath(packet->path, path, path_len);
if (packet->getPayloadType() == PAYLOAD_TYPE_PATH) {
pri = 1; // slightly less priority
} else {
+5 -3
View File
@@ -195,14 +195,16 @@ public:
/**
* \brief send a locally-generated Packet with flood routing
* \param path_bytes_per_hop number of bytes per path hop (1=legacy, 2, or 3)
*/
void sendFlood(Packet* packet, uint32_t delay_millis=0);
void sendFlood(Packet* packet, uint32_t delay_millis=0, uint8_t path_bytes_per_hop=1);
/**
* \brief send a locally-generated Packet with flood routing
* \param transport_codes array of 2 codes to attach to packet
* \param path_bytes_per_hop number of bytes per path hop (1=legacy, 2, or 3)
*/
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0);
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0, uint8_t path_bytes_per_hop=1);
/**
* \brief send a locally-generated Packet with Direct routing
@@ -222,4 +224,4 @@ public:
};
}
}
+6 -4
View File
@@ -11,7 +11,7 @@ Packet::Packet() {
}
int Packet::getRawLength() const {
return 2 + path_len + payload_len + (hasTransportCodes() ? 4 : 0);
return 2 + getPathByteLen() + payload_len + (hasTransportCodes() ? 4 : 0);
}
void Packet::calculatePacketHash(uint8_t* hash) const {
@@ -33,7 +33,8 @@ uint8_t Packet::writeTo(uint8_t dest[]) const {
memcpy(&dest[i], &transport_codes[1], 2); i += 2;
}
dest[i++] = path_len;
memcpy(&dest[i], path, path_len); i += path_len;
uint16_t pbl = getPathByteLen();
memcpy(&dest[i], path, pbl); i += pbl;
memcpy(&dest[i], payload, payload_len); i += payload_len;
return i;
}
@@ -48,8 +49,9 @@ bool Packet::readFrom(const uint8_t src[], uint8_t len) {
transport_codes[0] = transport_codes[1] = 0;
}
path_len = src[i++];
if (path_len > sizeof(path)) return false; // bad encoding
memcpy(path, &src[i], path_len); i += path_len;
uint16_t pbl = getPathByteLen();
if (pbl > sizeof(path)) return false; // bad encoding
memcpy(path, &src[i], pbl); i += pbl;
if (i >= len) return false; // bad encoding
payload_len = len - i;
if (payload_len > sizeof(payload)) return false; // bad encoding
+39 -1
View File
@@ -1,6 +1,7 @@
#pragma once
#include <MeshCore.h>
#include <string.h>
namespace mesh {
@@ -81,6 +82,43 @@ public:
float getSNR() const { return ((float)_snr) / 4.0f; }
/**
* \returns the actual byte length of path data.
* path_len encodes: lower 6 bits = hop count, upper 2 bits = bytes-per-hop mode
* mode 0 = 1 byte/hop (legacy), mode 1 = 2 bytes/hop, mode 2 = 3 bytes/hop
*/
uint16_t getPathByteLen() const {
uint8_t hops = path_len & 63;
uint8_t bph = (path_len >> 6) + 1;
return hops * bph;
}
/** Static variant for computing byte length from any path_len value */
static uint16_t getPathByteLenFor(uint8_t path_len) {
return (path_len & 63) * ((path_len >> 6) + 1);
}
/** Validate that encoded path_len won't exceed buffer */
static bool isValidPathLen(uint8_t path_len) {
return getPathByteLenFor(path_len) <= MAX_PATH_SIZE;
}
/** Copy path bytes using encoded path_len; returns path_len unchanged */
static uint8_t copyPath(uint8_t* dest, const uint8_t* src, uint8_t path_len) {
uint16_t bl = getPathByteLenFor(path_len);
if (bl > MAX_PATH_SIZE) bl = MAX_PATH_SIZE;
memcpy(dest, src, bl);
return path_len;
}
/** Write path bytes to buffer; returns number of bytes written */
static uint8_t writePath(uint8_t* dest, const uint8_t* src, uint8_t path_len) {
uint16_t bl = getPathByteLenFor(path_len);
if (bl > MAX_PATH_SIZE) bl = MAX_PATH_SIZE;
memcpy(dest, src, bl);
return (uint8_t)bl;
}
/**
* \returns the encoded/wire format length of this packet
*/
@@ -101,4 +139,4 @@ public:
bool readFrom(const uint8_t src[], uint8_t len);
};
}
}
+26 -17
View File
@@ -10,10 +10,10 @@
#endif
void BaseChatMesh::sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis) {
sendFlood(pkt, delay_millis);
sendFlood(pkt, delay_millis, getPathHashSize());
}
void BaseChatMesh::sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis) {
sendFlood(pkt, delay_millis);
sendFlood(pkt, delay_millis, getPathHashSize());
}
mesh::Packet* BaseChatMesh::createSelfAdvert(const char* name) {
@@ -39,7 +39,7 @@ mesh::Packet* BaseChatMesh::createSelfAdvert(const char* name, double lat, doubl
}
void BaseChatMesh::sendAckTo(const ContactInfo& dest, uint32_t ack_hash) {
if (dest.out_path_len < 0) {
if (dest.out_path_len == OUT_PATH_UNKNOWN) {
mesh::Packet* ack = createAck(ack_hash);
if (ack) sendFloodScoped(dest, ack, TXT_ACK_DELAY);
} else {
@@ -56,6 +56,14 @@ void BaseChatMesh::sendAckTo(const ContactInfo& dest, uint32_t ack_hash) {
}
void BaseChatMesh::bootstrapRTCfromContacts() {
// If the RTC already has a sane time (e.g. hardware RTC like PCF8563, or
// GPS-synced), don't overwrite it with a potentially stale contact lastmod.
// This bootstrap is only useful for boards with no hardware RTC at all.
uint32_t current = getRTCClock()->getCurrentTime();
if (current > 1704067200UL) { // Jan 1 2024 — matches EPOCH_MIN_SANE
return;
}
uint32_t latest = 0;
for (int i = 0; i < num_contacts; i++) {
if (contacts[i].lastmod > latest) {
@@ -92,7 +100,7 @@ ContactInfo* BaseChatMesh::allocateContactSlot() {
void BaseChatMesh::populateContactFromAdvert(ContactInfo& ci, const mesh::Identity& id, const AdvertDataParser& parser, uint32_t timestamp) {
memset(&ci, 0, sizeof(ci));
ci.id = id;
ci.out_path_len = -1; // initially out_path is unknown
ci.out_path_len = OUT_PATH_UNKNOWN; // initially out_path is unknown
StrHelper::strncpy(ci.name, parser.getName(), sizeof(ci.name));
ci.type = parser.getType();
if (parser.hasLatLon()) {
@@ -263,7 +271,7 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
} else {
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from.id, secret, temp_buf, reply_len);
if (reply) {
if (from.out_path_len >= 0) { // we have an out_path, so send DIRECT
if (from.out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
sendDirect(reply, from.out_path, from.out_path_len, SERVER_RESPONSE_DELAY);
} else {
sendFloodScoped(from, reply, SERVER_RESPONSE_DELAY);
@@ -273,7 +281,7 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
}
} else if (type == PAYLOAD_TYPE_RESPONSE && len > 0) {
onContactResponse(from, data, len);
if (packet->isRouteFlood() && from.out_path_len >= 0) {
if (packet->isRouteFlood() && from.out_path_len != OUT_PATH_UNKNOWN) {
// we have direct path, but other node is still sending flood response, so maybe they didn't receive reciprocal path properly(?)
handleReturnPathRetry(from, packet->path, packet->path_len);
}
@@ -295,7 +303,8 @@ bool BaseChatMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const ui
bool BaseChatMesh::onContactPathRecv(ContactInfo& from, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) {
// NOTE: default impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path.
// FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?)
memcpy(from.out_path, out_path, from.out_path_len = out_path_len); // store a copy of path, for sendDirect()
from.out_path_len = out_path_len;
mesh::Packet::copyPath(from.out_path, out_path, out_path_len); // store a copy of path, for sendDirect()
from.lastmod = getRTCClock()->getCurrentTime();
onContactPathUpdated(from);
@@ -317,7 +326,7 @@ void BaseChatMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) {
txt_send_timeout = 0; // matched one we're waiting for, cancel timeout timer
packet->markDoNotRetransmit(); // ACK was for this node, so don't retransmit
if (packet->isRouteFlood() && from->out_path_len >= 0) {
if (packet->isRouteFlood() && from->out_path_len != OUT_PATH_UNKNOWN) {
// we have direct path, but other node is still sending flood, so maybe they didn't receive reciprocal path properly(?)
handleReturnPathRetry(*from, packet->path, packet->path_len);
}
@@ -386,7 +395,7 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint32_t timestamp,
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
int rc;
if (recipient.out_path_len < 0) {
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
sendFloodScoped(recipient, pkt);
txt_send_timeout = futureMillis(est_timeout = calcFloodTimeoutMillisFor(t));
rc = MSG_SEND_SENT_FLOOD;
@@ -412,7 +421,7 @@ int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timest
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
int rc;
if (recipient.out_path_len < 0) {
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
sendFloodScoped(recipient, pkt);
txt_send_timeout = futureMillis(est_timeout = calcFloodTimeoutMillisFor(t));
rc = MSG_SEND_SENT_FLOOD;
@@ -500,7 +509,7 @@ int BaseChatMesh::sendLogin(const ContactInfo& recipient, const char* password,
}
if (pkt) {
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
if (recipient.out_path_len < 0) {
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -525,7 +534,7 @@ int BaseChatMesh::sendAnonReq(const ContactInfo& recipient, const uint8_t* data,
}
if (pkt) {
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
if (recipient.out_path_len < 0) {
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -552,7 +561,7 @@ int BaseChatMesh::sendRequest(const ContactInfo& recipient, const uint8_t* req_
}
if (pkt) {
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
if (recipient.out_path_len < 0) {
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -579,7 +588,7 @@ int BaseChatMesh::sendRequest(const ContactInfo& recipient, uint8_t req_type, u
}
if (pkt) {
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
if (recipient.out_path_len < 0) {
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -683,7 +692,7 @@ void BaseChatMesh::checkConnections() {
MESH_DEBUG_PRINTLN("checkConnections(): Keep_alive contact not found!");
continue;
}
if (contact->out_path_len < 0) {
if (contact->out_path_len == OUT_PATH_UNKNOWN) {
MESH_DEBUG_PRINTLN("checkConnections(): Keep_alive contact, no out_path!");
continue;
}
@@ -710,7 +719,7 @@ void BaseChatMesh::checkConnections() {
}
void BaseChatMesh::resetPathTo(ContactInfo& recipient) {
recipient.out_path_len = -1;
recipient.out_path_len = OUT_PATH_UNKNOWN;
}
static ContactInfo* table; // pass via global :-(
@@ -875,4 +884,4 @@ void BaseChatMesh::loop() {
releasePacket(_pendingLoopback); // undo the obtainNewPacket()
_pendingLoopback = NULL;
}
}
}
+20 -3
View File
@@ -58,9 +58,9 @@ class BaseChatMesh : public mesh::Mesh {
friend class ContactsIterator;
ContactInfo contacts[MAX_CONTACTS];
ContactInfo* contacts;
int num_contacts;
int sort_array[MAX_CONTACTS];
int* sort_array;
int matching_peer_indexes[MAX_SEARCH_RESULTS];
unsigned long txt_send_timeout;
#ifdef MAX_GROUP_CHANNELS
@@ -78,6 +78,8 @@ protected:
BaseChatMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::PacketManager& mgr, mesh::MeshTables& tables)
: mesh::Mesh(radio, ms, rng, rtc, mgr, tables)
{
contacts = NULL;
sort_array = NULL;
num_contacts = 0;
#ifdef MAX_GROUP_CHANNELS
memset(channels, 0, sizeof(channels));
@@ -90,6 +92,19 @@ protected:
void bootstrapRTCfromContacts();
void resetContacts() { num_contacts = 0; }
// Must be called from begin() before loadContacts/bootstrapRTCfromContacts.
// Deferred from constructor because PSRAM is not available during global init.
void initContacts() {
if (contacts != NULL) return; // already initialized
#if defined(ESP32) && defined(BOARD_HAS_PSRAM)
contacts = (ContactInfo*)ps_calloc(MAX_CONTACTS, sizeof(ContactInfo));
sort_array = (int*)ps_calloc(MAX_CONTACTS, sizeof(int));
#else
contacts = new ContactInfo[MAX_CONTACTS]();
sort_array = new int[MAX_CONTACTS]();
#endif
}
void populateContactFromAdvert(ContactInfo& ci, const mesh::Identity& id, const AdvertDataParser& parser, uint32_t timestamp);
ContactInfo* allocateContactSlot(); // helper to find slot for new contact
@@ -98,6 +113,7 @@ protected:
virtual bool shouldAutoAddContactType(uint8_t type) const { return true; }
virtual void onContactsFull() {};
virtual bool shouldOverwriteWhenFull() const { return false; }
virtual uint8_t getAutoAddMaxHops() const { return 0; } // 0 = no limit
virtual void onContactOverwrite(const uint8_t* pub_key) {};
virtual void onDiscoveredContact(ContactInfo& contact, bool is_new, uint8_t path_len, const uint8_t* path) = 0;
virtual ContactInfo* processAck(const uint8_t *data) = 0;
@@ -114,6 +130,7 @@ protected:
virtual void onContactResponse(const ContactInfo& contact, const uint8_t* data, uint8_t len) = 0;
virtual void handleReturnPathRetry(const ContactInfo& contact, const uint8_t* path, uint8_t path_len);
virtual uint8_t getPathHashSize() const = 0;
virtual void sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis=0);
virtual void sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis=0);
@@ -169,4 +186,4 @@ public:
int findChannelIdx(const mesh::GroupChannel& ch);
void loop();
};
};
+2 -2
View File
@@ -114,7 +114,7 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
memset(c, 0, sizeof(*c));
c->permissions = init_perms;
c->id = id;
c->out_path_len = -1; // initially out_path is unknown
c->out_path_len = OUT_PATH_UNKNOWN; // initially out_path is unknown
return c;
}
@@ -140,4 +140,4 @@ bool ClientACL::applyPermissions(const mesh::LocalIdentity& self_id, const uint8
self_id.calcSharedSecret(c->shared_secret, pubkey);
}
return true;
}
}
+6 -2
View File
@@ -4,6 +4,10 @@
#include <Mesh.h>
#include <helpers/IdentityStore.h>
#ifndef OUT_PATH_UNKNOWN
#define OUT_PATH_UNKNOWN 0xFF
#endif
#define PERM_ACL_ROLE_MASK 3 // lower 2 bits
#define PERM_ACL_GUEST 0
#define PERM_ACL_READ_ONLY 1
@@ -13,7 +17,7 @@
struct ClientInfo {
mesh::Identity id;
uint8_t permissions;
int8_t out_path_len;
uint8_t out_path_len; // OUT_PATH_UNKNOWN = no known path
uint8_t out_path[MAX_PATH_SIZE];
uint8_t shared_secret[PUB_KEY_SIZE];
uint32_t last_timestamp; // by THEIR clock (transient)
@@ -55,4 +59,4 @@ public:
int getNumClients() const { return num_clients; }
ClientInfo* getClientByIdx(int idx) { return &clients[idx]; }
};
};

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