3 Commits

64 changed files with 1392 additions and 10574 deletions

View File

@@ -1,8 +1,6 @@
## Meshcore + Fork = Meck
This fork was created specifically to focus on enabling BLE companion firmware for the LilyGo T-Deck Pro. Created with the assistance of Claude AI using Meshcore v1.11 code.
<img src="https://github.com/user-attachments/assets/b30ce6bd-79af-44d3-93c4-f5e7e21e5621" alt="IMG_1453" width="300" height="650">
### Contents
- [T-Deck Pro Keyboard Controls](#t-deck-pro-keyboard-controls)
- [Navigation (Home Screen)](#navigation-home-screen)
@@ -16,8 +14,6 @@ This fork was created specifically to focus on enabling BLE companion firmware f
- [Compose Mode](#compose-mode)
- [Symbol Entry (Sym Key)](#symbol-entry-sym-key)
- [Emoji Picker](#emoji-picker)
- [SMS & Phone App (4G only)](#sms--phone-app-4g-only)
- [Web Browser & IRC](#web-browser--irc)
- [About MeshCore](#about-meshcore)
- [What is MeshCore?](#what-is-meshcore)
- [Key Features](#key-features)
@@ -46,11 +42,7 @@ The T-Deck Pro BLE companion firmware includes full keyboard support for standal
| M | Open channel messages |
| C | Open contacts list |
| E | Open e-book reader |
| N | Open notes |
| S | Open settings |
| B | Open web browser (BLE and 4G variants only) |
| T | Open SMS & Phone app (4G variant only) |
| P | Open audiobook player (audio variant only) |
| Q | Back to home screen |
### Bluetooth (BLE)
@@ -88,8 +80,6 @@ The GPS page also shows the current time, satellite count, position, altitude, a
| W / S | Scroll messages up/down |
| A / D | Switch between channels |
| Enter | Compose new message |
| R | Reply to a message — enter reply select mode, scroll to a message with W/S, then press Enter to compose a reply with an @mention |
| V | View relay path of the last received message (scrollable, up to 20 hops) |
| Q | Back to home screen |
### Contacts Screen
@@ -99,14 +89,10 @@ Press **C** from the home screen to open the contacts list. All known mesh conta
| Key | Action |
|-----|--------|
| W / S | Scroll up / down through contacts |
| A / D | Cycle filter: All → Chat → Repeater → Room → Sensor → Favourites |
| A / D | Cycle filter: All → Chat → Repeater → Room → Sensor |
| Enter | Open DM compose (Chat contact) or repeater admin (Repeater contact) |
| X | Export contacts to SD card (wait 510 seconds for confirmation popup) |
| R | Import contacts from SD card (wait 510 seconds for confirmation popup) |
| Q | Back to home screen |
**Contact limits:** Standalone variants support up to 1,500 contacts (stored in PSRAM). BLE variants (both Audio-BLE and 4G-BLE) are limited to 500 contacts due to BLE protocol constraints.
### Sending a Direct Message
Select a **Chat** contact in the contacts list and press **Enter** to start composing a direct message. The compose screen will show `DM: ContactName` in the header. Type your message and press **Enter** to send. The DM is sent encrypted directly to that contact (or flooded if no direct path is known). After sending or cancelling, you're returned to the contacts list.
@@ -159,8 +145,6 @@ Press **S** from the home screen to open settings. On first boot (when the devic
| Channels | View existing channels, add hashtag channels, or delete non-primary channels (X) |
| Device Info | Public key and firmware version (read-only) |
The bottom of the settings screen also displays your node ID and firmware version. On the 4G variant, IMEI, carrier name, and APN details are shown here as well.
When adding a hashtag channel, type the channel name and press Enter. The channel secret is automatically derived from the name via SHA-256, matching the standard MeshCore hashtag convention.
If you've changed radio parameters, pressing Q will prompt you to apply changes before exiting.
@@ -210,22 +194,6 @@ While in compose mode, press the **$** key to open the emoji picker. A scrollabl
| Enter | Insert selected emoji |
| $ / Q / Backspace | Cancel and return to compose |
### SMS & Phone App (4G only)
Press **T** from the home screen to open the SMS & Phone app. The app opens to a menu screen where you can choose between the **Phone** dialer (for calling any number) or the **SMS Inbox** (for messaging and calling saved contacts).
For full documentation including key mappings, dialpad usage, contacts management, and troubleshooting, see the [SMS & Phone App Guide](SMS%20%26%20Phone%20App%20Guide.md).
### Web Browser & IRC
Press **B** from the home screen to open the web reader. This is available on the BLE and 4G variants (not the standalone audio variant, which excludes WiFi to preserve lowest-battery-usage design).
The web reader home screen provides access to the **IRC client**, the **URL bar**, and your **bookmarks** and **history**. Select IRC Chat and press Enter to configure and connect to an IRC server. Select the URL bar to enter a web address, or scroll down to open a bookmark or history entry.
The browser is a text-centric reader best suited to text-heavy websites. It also includes basic web search via DuckDuckGo Lite, and can download EPUB files — follow a link to an `.epub` and it will be saved to the books folder on your SD card for reading later in the e-book reader.
For full documentation including key mappings, WiFi setup, bookmarks, IRC configuration, and SD card structure, see the [Web App Guide](Web%20App%20Guide.md).
## About MeshCore
MeshCore is a lightweight, portable C++ library that enables multi-hop packet routing for embedded projects using LoRa and other packet radios. It is designed for developers who want to create resilient, decentralized communication networks that work without the internet.
@@ -317,13 +285,12 @@ There are a number of fairly major features in the pipeline, with no particular
- [X] Standalone repeater admin access for Companion BLE firmware
- [X] GPS time sync with on-device timezone setting
- [X] Settings screen with radio presets, channel management, and first-boot onboarding
- [X] Expand SMS app to enable phone calls
- [X] Basic web reader app for text-centric websites
- [ ] Fix M4B rendering to enable chaptered audiobook playback
- [ ] Expand SMS app to enable phone calls
- [ ] Better JPEG and PNG decoding
- [ ] Improve EPUB rendering and EPUB format handling
- [ ] Map support with GPS
- [ ] WiFi companion environment
- [ ] Basic web reader app for text-centric websites
## 📞 Get Support
@@ -349,4 +316,4 @@ However, this firmware links against libraries with different license terms. Bec
| [base64](https://github.com/Densaugeo/base64_arduino) | MIT | densaugeo |
| [Arduino Crypto](https://github.com/rweather/arduinolibs) | MIT | Rhys Weatherley |
Full license texts for each dependency are available in their respective repositories linked above.
Full license texts for each dependency are available in their respective repositories linked above.

View File

@@ -1,4 +1,4 @@
## SMS & Phone App (4G variant only) - Meck v0.9.5
## SMS & Phone App (4G variant only) - Meck v0.9.3 (Alpha)
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
@@ -8,31 +8,16 @@ 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 |
| Inbox | Q | Back to home screen |
| Conversation | W / S | Scroll messages |
| Conversation | C | Reply to this conversation |
| Conversation | F | Call this number |
@@ -46,10 +31,6 @@ return to the home screen.
| 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 |
@@ -74,20 +55,23 @@ shown in the footer while composing.
### Making a Phone Call
There are three ways to start a call:
Press **F** to call from either the conversation view or the contacts
directory. 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.
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
There are two ways to start a call:
1. **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
2. **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.
> **Note:** There is currently no way to dial an arbitrary phone number without
> first creating a conversation. To call a new number, press **C** from the
> inbox to compose a new SMS, enter the phone number, send a short message,
> then open the resulting conversation and press **F** to call.
During an active call, **W** and **S** adjust the speaker volume (05). The
number keys **09**, **\***, and **#** send DTMF tones for navigating phone
@@ -96,26 +80,6 @@ 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
@@ -170,12 +134,6 @@ 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
```
@@ -200,6 +158,7 @@ SD Card
| 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 |
| Cannot dial a number | You must first have a conversation or saved contact for that number. Send a short SMS to create a conversation, then press F |
> **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

View File

@@ -1,315 +0,0 @@
# 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 gps` | GPS status and interval |
| `get pin` | BLE pairing PIN |
| `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 |
**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
```
#### BLE PIN
```
set pin 123456
```
### 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
```
### 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.

View File

@@ -1,97 +1,15 @@
# Web Reader & IRC - Meck v0.9.5
# Web Reader - Integration Summary
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.
### 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_audio_standalone**: No — excluded 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.
### 4G Modem / PPP Support
The web reader uses `isNetworkAvailable()` which checks both WiFi and (future) PPP connectivity. The `fetchPage()` method uses ESP32's standard `HTTPClient` which routes through whatever network interface is active — WiFi or PPP.
## 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.
When PPP support is added to the 4G modem driver, the web reader will work over cellular automatically without code changes. The `isNetworkAvailable()` method has a `TODO` placeholder for the PPP status check.
---
@@ -105,8 +23,8 @@ discarded as new ones arrive.
### 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 |
| `w` / `s` | Navigate up/down in bookmarks/history |
| `Enter` | Select URL bar or bookmark/history item |
| Type | Enter URL (when URL bar is active) |
| `q` | Exit to firmware home |
@@ -118,7 +36,6 @@ discarded as new ones arrive.
| `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
@@ -129,37 +46,6 @@ discarded as new ones arrive.
| 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
@@ -168,14 +54,4 @@ over cellular data without WiFi.
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
```

View File

@@ -1,101 +0,0 @@
# 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.

Before

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 261 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 KiB

View File

@@ -41,18 +41,14 @@ public:
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,
const uint8_t* path = nullptr, int8_t snr = 0) = 0;
const uint8_t* path = nullptr) = 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) {}
};

View File

@@ -230,28 +230,6 @@ 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;
file.close();
}
}
@@ -287,66 +265,14 @@ 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.close();
}
}
void DataStore::loadContacts(DataStoreHost* host) {
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");
File file = openRead(_getContactsChannelsFS(), "/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;
@@ -376,86 +302,36 @@ void DataStore::loadContacts(DataStoreHost* host) {
}
void DataStore::saveContacts(DataStoreHost* host) {
FILESYSTEM* fs = _getContactsChannelsFS();
const char* finalPath = "/contacts3";
const char* tmpPath = "/contacts3.tmp";
File file = openWrite(_getContactsChannelsFS(), "/contacts3");
if (file) {
uint32_t idx = 0;
ContactInfo c;
uint8_t unused = 0;
// --- 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;
}
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);
uint32_t idx = 0;
ContactInfo c;
uint8_t unused = 0;
uint32_t recordsWritten = 0;
bool writeOk = true;
if (!success) break; // write failed
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;
idx++; // advance to next contact
}
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");
file.close();
}
}
void DataStore::loadChannels(DataStoreHost* host) {
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");
File file = openRead(_getContactsChannelsFS(), "/channels2");
if (file) {
bool full = false;
uint8_t channel_idx = 0;
@@ -480,54 +356,22 @@ void DataStore::loadChannels(DataStoreHost* host) {
}
void DataStore::saveChannels(DataStoreHost* host) {
FILESYSTEM* fs = _getContactsChannelsFS();
const char* finalPath = "/channels2";
const char* tmpPath = "/channels2.tmp";
File file = openWrite(_getContactsChannelsFS(), "/channels2");
if (file) {
uint8_t channel_idx = 0;
ChannelDetails ch;
uint8_t unused[4];
memset(unused, 0, 4);
File file = openWrite(fs, tmpPath);
if (!file) {
Serial.println("DataStore: saveChannels FAILED — cannot open tmp file");
return;
}
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);
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;
if (!success) break; // write failed
channel_idx++;
}
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");
file.close();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -5,14 +5,14 @@
#include "AbstractUITask.h"
/*------------ Frame Protocol --------------*/
#define FIRMWARE_VER_CODE 10
#define FIRMWARE_VER_CODE 8
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "7 March 2026"
#define FIRMWARE_BUILD_DATE "24 Feb 2026"
#endif
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "Meck v0.9.9"
#define FIRMWARE_VERSION "Meck v0.9.3"
#endif
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
@@ -84,16 +84,6 @@ struct AdvertPath {
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);
@@ -111,14 +101,6 @@ 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
// Queue a sent channel message for BLE app sync
void queueSentChannelMessage(uint8_t channel_idx, uint32_t timestamp, const char* sender, const char* text);
@@ -127,9 +109,8 @@ public:
bool uiSendDirectMessage(uint32_t contact_idx, const char* text);
// Repeater admin - UI-initiated operations
bool uiLoginToRepeater(uint32_t contact_idx, const char* password, uint32_t& est_timeout_ms);
bool uiLoginToRepeater(uint32_t contact_idx, const char* password);
bool uiSendCliCommand(uint32_t contact_idx, const char* command);
bool uiSendTelemetryRequest(uint32_t contact_idx);
int getAdminContactIdx() const { return _admin_contact_idx; }
@@ -137,10 +118,7 @@ protected:
float getAirtimeBudgetFactor() const override;
int getInterferenceThreshold() const 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;
void sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis=0) override;
@@ -278,13 +256,6 @@ 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;

View File

@@ -30,7 +30,4 @@ struct NodePrefs { // persisted to file
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)
};

View File

@@ -1,11 +1,10 @@
#include <Arduino.h> // needed for PlatformIO
#ifdef BLE_PIN_CODE
#include <esp_bt.h> // for esp_bt_controller_mem_release (web reader WiFi)
#endif
#include <esp_bt.h> // for esp_bt_controller_mem_release (web reader WiFi)
#include <Mesh.h>
#include "MyMesh.h"
#include "variant.h" // Board-specific defines (HAS_GPS, etc.)
#include "target.h" // For sensors, board, etc.
#include "GPSDutyCycle.h"
#include "CPUPowerManager.h"
// T-Deck Pro Keyboard support
@@ -18,7 +17,6 @@
#include "ChannelScreen.h"
#include "SettingsScreen.h"
#include "RepeaterAdminScreen.h"
#include "DiscoveryScreen.h"
#ifdef MECK_WEB_READER
#include "WebReaderScreen.h"
#endif
@@ -35,11 +33,6 @@
static bool composeNeedsRefresh = false;
#define COMPOSE_REFRESH_INTERVAL 100 // ms before starting e-ink refresh after keypress (refresh itself takes ~644ms)
// Phone dialer debounce — independent from compose/smsSuppressLoop to avoid
// interfering with call view rendering and alert display
static bool dialerNeedsRefresh = false;
static unsigned long lastDialerRefresh = 0;
// DM compose mode (direct message to a specific contact)
static bool composeDM = false;
static int composeDMContactIdx = -1;
@@ -84,12 +77,10 @@
static bool smsMode = false;
#endif
// Touch input (for phone dialer numpad)
#ifdef HAS_TOUCHSCREEN
#include "TouchInput.h"
TouchInput touchInput(&Wire);
// Power management
#if HAS_GPS
GPSDutyCycle gpsDuty;
#endif
CPUPowerManager cpuPower;
void initKeyboard();
@@ -196,151 +187,6 @@
digitalWrite(SDCARD_CS, HIGH);
return restored;
}
// -----------------------------------------------------------------------
// On-demand export: save current contacts to SD card.
// Writes binary backup + human-readable listing.
// Returns number of contacts exported, or -1 on error.
// -----------------------------------------------------------------------
int exportContactsToSD() {
if (!sdCardReady) {
Serial.println("Export: SD card not ready");
return -1;
}
// Ensure in-memory contacts are flushed to SPIFFS first
the_mesh.saveContacts();
if (!SD.exists("/meshcore")) SD.mkdir("/meshcore");
// 1) Binary backup: SPIFFS /contacts3 → SD /meshcore/contacts.bin
// Non-fatal — text export reads from memory and doesn't need this.
if (SPIFFS.exists("/contacts3")) {
if (copyFile(SPIFFS, "/contacts3", SD, "/meshcore/contacts.bin")) {
Serial.println("Export: binary backup OK");
} else {
Serial.println("Export: binary copy to SD failed (continuing with text export)");
}
} else {
Serial.println("Export: /contacts3 not found on SPIFFS (skipping binary backup)");
}
// 2) Human-readable listing for inspection on a computer
// Reads from in-memory contact table — always works if SD is writable.
int count = 0;
File txt = SD.open("/meshcore/contacts_export.txt", "w", true);
if (!txt) {
Serial.println("Export: failed to open contacts_export.txt for writing");
digitalWrite(SDCARD_CS, HIGH);
return -1;
}
txt.printf("Meck Contacts Export (%d total)\n", (int)the_mesh.getNumContacts());
txt.printf("========================================\n");
txt.printf("%-5s %-30s %s\n", "Type", "Name", "PubKey (prefix)");
txt.printf("----------------------------------------\n");
ContactInfo c;
for (uint32_t i = 0; i < (uint32_t)the_mesh.getNumContacts(); i++) {
if (the_mesh.getContactByIdx(i, c)) {
const char* typeStr = "???";
switch (c.type) {
case ADV_TYPE_CHAT: typeStr = "Chat"; break;
case ADV_TYPE_REPEATER: typeStr = "Rptr"; break;
case ADV_TYPE_ROOM: typeStr = "Room"; break;
}
// First 8 bytes of pub key as hex identifier
char hexBuf[20];
mesh::Utils::toHex(hexBuf, c.id.pub_key, 8);
txt.printf("%-5s %-30s %s\n", typeStr, c.name, hexBuf);
count++;
}
}
txt.printf("========================================\n");
txt.printf("Total: %d contacts\n", count);
txt.close();
digitalWrite(SDCARD_CS, HIGH);
Serial.printf("Contacts exported to SD: %d contacts\n", count);
return count;
}
// -----------------------------------------------------------------------
// On-demand import: merge contacts from SD backup into live table.
//
// Reads /meshcore/contacts.bin from SD and for each contact:
// - If already in memory (matching pub_key) → skip (keep current)
// - If NOT in memory → addContact (append to table)
//
// This is a non-destructive merge: you never lose contacts already in
// memory, and you gain any that were only in the backup.
//
// After merging, saves the combined set back to SPIFFS so it persists.
// Returns number of NEW contacts added, or -1 on error.
// -----------------------------------------------------------------------
int importContactsFromSD() {
if (!sdCardReady) return -1;
if (!SD.exists("/meshcore/contacts.bin")) return -1;
File file = SD.open("/meshcore/contacts.bin", "r");
if (!file) return -1;
int added = 0;
int skipped = 0;
while (true) {
ContactInfo c;
uint8_t pub_key[32];
uint8_t unused;
// Parse one contact record (same binary format as DataStore::loadContacts)
bool success = (file.read(pub_key, 32) == 32);
success = success && (file.read((uint8_t *)&c.name, 32) == 32);
success = success && (file.read(&c.type, 1) == 1);
success = success && (file.read(&c.flags, 1) == 1);
success = success && (file.read(&unused, 1) == 1);
success = success && (file.read((uint8_t *)&c.sync_since, 4) == 4);
success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1);
success = success && (file.read((uint8_t *)&c.last_advert_timestamp, 4) == 4);
success = success && (file.read(c.out_path, 64) == 64);
success = success && (file.read((uint8_t *)&c.lastmod, 4) == 4);
success = success && (file.read((uint8_t *)&c.gps_lat, 4) == 4);
success = success && (file.read((uint8_t *)&c.gps_lon, 4) == 4);
if (!success) break; // EOF or read error
c.id = mesh::Identity(pub_key);
c.shared_secret_valid = false;
// Check if this contact already exists in the live table
if (the_mesh.lookupContactByPubKey(pub_key, PUB_KEY_SIZE) != NULL) {
skipped++;
continue; // Already have this contact, skip
}
// New contact — add to the live table
if (the_mesh.addContact(c)) {
added++;
} else {
// Table is full, stop importing
Serial.printf("Import: table full after adding %d contacts\n", added);
break;
}
}
file.close();
digitalWrite(SDCARD_CS, HIGH);
// Persist the merged set to SPIFFS
if (added > 0) {
the_mesh.saveContacts();
}
Serial.printf("Contacts import: %d added, %d already present, %d total\n",
added, skipped, (int)the_mesh.getNumContacts());
return added;
}
#endif
// Believe it or not, this std C function is busted on some platforms!
@@ -382,13 +228,6 @@ static uint32_t _atoi(const char* sp) {
#ifndef TCP_PORT
#define TCP_PORT 5000
#endif
#elif defined(MECK_WIFI_COMPANION)
#include <WiFi.h>
#include <helpers/esp32/SerialWifiInterface.h>
SerialWifiInterface serial_interface;
#ifndef TCP_PORT
#define TCP_PORT 5000
#endif
#elif defined(BLE_PIN_CODE)
#include <helpers/esp32/SerialBLEInterface.h>
SerialBLEInterface serial_interface;
@@ -436,7 +275,6 @@ static uint32_t _atoi(const char* sp) {
/* GLOBAL OBJECTS */
#ifdef DISPLAY_CLASS
#include "UITask.h"
#include "MapScreen.h" // After BLE — PNGdec headers conflict with BLE if included earlier
UITask ui_task(&board, &serial_interface);
#endif
@@ -665,44 +503,9 @@ void setup() {
MESH_DEBUG_PRINTLN("setup() - the_mesh.begin() done");
#ifdef WIFI_SSID
MESH_DEBUG_PRINTLN("setup() - WiFi mode (compile-time credentials)");
MESH_DEBUG_PRINTLN("setup() - WiFi mode");
WiFi.begin(WIFI_SSID, WIFI_PWD);
serial_interface.begin(TCP_PORT);
#elif defined(MECK_WIFI_COMPANION)
{
// WiFi companion: load credentials from SD at runtime.
// TCP server starts regardless — companion connects when WiFi comes up.
MESH_DEBUG_PRINTLN("setup() - WiFi companion mode (runtime credentials)");
WiFi.mode(WIFI_STA);
if (sdCardReady) {
File f = SD.open("/web/wifi.cfg", FILE_READ);
if (f) {
String ssid = f.readStringUntil('\n'); ssid.trim();
String pass = f.readStringUntil('\n'); pass.trim();
f.close();
digitalWrite(SDCARD_CS, HIGH);
if (ssid.length() > 0) {
MESH_DEBUG_PRINTLN("setup() - WiFi: connecting to '%s'", ssid.c_str());
WiFi.begin(ssid.c_str(), pass.c_str());
unsigned long timeout = millis() + 8000;
while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
delay(100);
}
if (WiFi.status() == WL_CONNECTED) {
Serial.printf("WiFi companion: connected to %s, IP: %s\n",
ssid.c_str(), WiFi.localIP().toString().c_str());
} else {
Serial.println("WiFi companion: auto-connect failed (configure in Settings)");
}
}
} else {
digitalWrite(SDCARD_CS, HIGH);
Serial.println("WiFi companion: no /web/wifi.cfg found (configure in Settings)");
}
}
serial_interface.begin(TCP_PORT);
MESH_DEBUG_PRINTLN("setup() - WiFi TCP server started on port %d", TCP_PORT);
}
#elif defined(BLE_PIN_CODE)
MESH_DEBUG_PRINTLN("setup() - about to call serial_interface.begin() with BLE");
serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin());
@@ -745,15 +548,6 @@ void setup() {
initKeyboard();
#endif
// Initialize touch input (CST328)
#ifdef HAS_TOUCHSCREEN
if (touchInput.begin(CST328_PIN_INT)) {
MESH_DEBUG_PRINTLN("setup() - Touch input initialized");
} else {
MESH_DEBUG_PRINTLN("setup() - Touch input FAILED");
}
#endif
// ---------------------------------------------------------------------------
// SD card is already initialized (early init above).
// Now set up SD-dependent features: message history + text reader.
@@ -838,22 +632,18 @@ void setup() {
}
#endif
// GPS power — honour saved pref, default to enabled on first boot
// GPS duty cycle — honour saved pref, default to enabled on first boot
#if HAS_GPS
{
bool gps_wanted = the_mesh.getNodePrefs()->gps_enabled;
gpsDuty.setStreamCounter(&gpsStream);
gpsDuty.begin(gps_wanted);
if (gps_wanted) {
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, GPS_EN_ACTIVE);
#endif
sensors.setSettingValue("gps", "1");
} else {
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, !GPS_EN_ACTIVE);
#endif
sensors.setSettingValue("gps", "0");
}
MESH_DEBUG_PRINTLN("setup() - GPS power %s", gps_wanted ? "on" : "off");
MESH_DEBUG_PRINTLN("setup() - GPS duty cycle started (enabled=%d)", gps_wanted);
}
#endif
@@ -872,35 +662,20 @@ void setup() {
void loop() {
the_mesh.loop();
sensors.loop();
// Map screen: periodically update own GPS position and contact markers
if (ui_task.isOnMapScreen()) {
static unsigned long lastMapUpdate = 0;
if (millis() - lastMapUpdate > 30000) { // Every 30 seconds
lastMapUpdate = millis();
MapScreen* ms = (MapScreen*)ui_task.getMapScreen();
if (ms) {
// Update own GPS position when GPS is enabled
#if HAS_GPS
ms->updateGPSPosition(sensors.node_lat, sensors.node_lon);
#endif
// Always refresh contact markers (new contacts arrive via radio)
ms->clearMarkers();
ContactsIterator it = the_mesh.startContactsIterator();
ContactInfo ci;
while (it.hasNext(&the_mesh, ci)) {
if (ci.gps_lat != 0 || ci.gps_lon != 0) {
double lat = ((double)ci.gps_lat) / 1000000.0;
double lon = ((double)ci.gps_lon) / 1000000.0;
ms->addMarker(lat, lon, ci.name, ci.type);
}
}
// GPS duty cycle — check for fix and manage power state
#if HAS_GPS
{
bool gps_hw_on = gpsDuty.loop();
if (gps_hw_on) {
LocationProvider* lp = sensors.getLocationProvider();
if (lp != NULL && lp->isValid()) {
gpsDuty.notifyFix();
}
}
}
#endif
sensors.loop();
// CPU frequency auto-timeout back to idle
cpuPower.loop();
@@ -968,19 +743,6 @@ void loop() {
} else if (callEvt.type == CallEventType::ENDED) {
Serial.printf("[Call] Ended (%lus) with %s\n",
(unsigned long)callEvt.duration, callEvt.phone);
// Show alert with duration (supplements the immediate alert from Q hangup;
// this catches remote hangups and network drops)
{
char alertBuf[48];
if (callEvt.duration > 0) {
snprintf(alertBuf, sizeof(alertBuf), "Call Ended %lu:%02lu",
(unsigned long)(callEvt.duration / 60),
(unsigned long)(callEvt.duration % 60));
} else {
snprintf(alertBuf, sizeof(alertBuf), "Call Ended");
}
ui_task.showAlert(alertBuf, 2000);
}
ui_task.forceRefresh();
} else if (callEvt.type == CallEventType::MISSED) {
char alertBuf[48];
@@ -1025,7 +787,7 @@ void loop() {
webReaderNeedsRefresh = false;
}
#endif
if (!composeMode && !notesSuppressLoop && !smsSuppressLoop && !dialerNeedsRefresh
if (!composeMode && !notesSuppressLoop && !smsSuppressLoop
#ifdef MECK_WEB_READER
&& !webReaderTextEntry
#endif
@@ -1055,21 +817,6 @@ void loop() {
lastComposeRefresh = millis();
composeNeedsRefresh = false;
}
// Phone dialer debounced render (separate from compose debounce)
#ifdef HAS_4G_MODEM
if (dialerNeedsRefresh && (millis() - lastDialerRefresh) >= COMPOSE_REFRESH_INTERVAL) {
if (smsMode) {
SMSScreen* dialScr = (SMSScreen*)ui_task.getSMSScreen();
if (dialScr && dialScr->getSubView() == SMSScreen::PHONE_DIALER) {
display.startFrame();
dialScr->render(display);
display.endFrame();
}
}
dialerNeedsRefresh = false;
lastDialerRefresh = millis();
}
#endif
#ifdef MECK_WEB_READER
if (webReaderNeedsRefresh && (millis() - lastWebReaderRefresh) >= COMPOSE_REFRESH_INTERVAL) {
WebReaderScreen* wr2 = (WebReaderScreen*)ui_task.getWebReaderScreen();
@@ -1114,44 +861,6 @@ void loop() {
#if defined(LilyGo_TDeck_Pro)
handleKeyboardInput();
#endif
// Poll touch input for phone dialer numpad
// Hybrid debounce: finger-up detection + 150ms minimum between accepted taps.
// The CST328 INT pin is pulse-based (not level), so getPoint() can return
// false intermittently during a hold. Time guard prevents that from
// causing repeat fires.
#if defined(HAS_TOUCHSCREEN) && defined(HAS_4G_MODEM)
{
static bool touchFingerDown = false;
static unsigned long lastTouchAccepted = 0;
if (smsMode) {
SMSScreen* smsScr = (SMSScreen*)ui_task.getSMSScreen();
if (smsScr && smsScr->getSubView() == SMSScreen::PHONE_DIALER) {
int16_t tx, ty;
if (touchInput.getPoint(tx, ty)) {
unsigned long now = millis();
if (!touchFingerDown && (now - lastTouchAccepted >= 150)) {
touchFingerDown = true;
lastTouchAccepted = now;
if (smsScr->handleTouch(tx, ty)) {
dialerNeedsRefresh = true;
lastDialerRefresh = millis();
}
}
} else {
// Only allow finger-up after 100ms from last acceptance
// (prevents INT pulse misses from resetting state mid-hold)
if (touchFingerDown && (millis() - lastTouchAccepted >= 100)) {
touchFingerDown = false;
}
}
} else {
touchFingerDown = false;
}
}
}
#endif
}
// ============================================================================
@@ -1232,7 +941,7 @@ void handleKeyboardInput() {
if (wasDM) {
ui_task.gotoContactsScreen();
} else {
ui_task.gotoChannelScreen();
ui_task.gotoHomeScreen();
}
return;
}
@@ -1252,7 +961,7 @@ void handleKeyboardInput() {
if (wasDM) {
ui_task.gotoContactsScreen();
} else {
ui_task.gotoChannelScreen();
ui_task.gotoHomeScreen();
}
return;
}
@@ -1560,8 +1269,8 @@ void handleKeyboardInput() {
return;
}
// In category menu (top level): Shift+Del exits to contacts, C opens compose
if (astate == RepeaterAdminScreen::STATE_CATEGORY_MENU) {
// In menu state: Shift+Del exits to contacts, C opens compose
if (astate == RepeaterAdminScreen::STATE_MENU) {
if (shiftDel) {
Serial.println("Nav: Back to contacts from admin menu");
ui_task.gotoContactsScreen();
@@ -1583,9 +1292,8 @@ void handleKeyboardInput() {
return;
}
// All other states (command menu, param entry, confirm, waiting,
// response, error): convert Shift+Del to exit signal and let the
// screen handle back-navigation internally
// In waiting/response/error states: convert Shift+Del to exit signal,
// pass all other keys through
if (shiftDel) {
ui_task.injectKey(KEY_ADMIN_EXIT);
} else {
@@ -1599,46 +1307,21 @@ void handleKeyboardInput() {
if (smsMode) {
SMSScreen* smsScr = (SMSScreen*)ui_task.getSMSScreen();
if (smsScr) {
// Keep display alive — SMS routes many keys via handleInput() directly,
// bypassing injectKey() which normally extends the auto-off timer.
ui_task.keepAlive();
// During active call views, route all keys directly to the screen
// and force a refresh after each keypress (no debounce needed)
if (smsScr->isInCallView()) {
smsScr->handleInput(key);
if (!smsScr->isInCallView()) {
// Hangup just happened — show "Call Ended" alert immediately
ui_task.showAlert("Call Ended", 2000);
}
// Force immediate render (call screen updates or return-to-dialer)
ui_task.forceRefresh();
ui_task.loop();
return;
}
// Q from app menu → go home; Q from inner views is handled by SMSScreen
if ((key == 'q' || key == '\b') && smsScr->getSubView() == SMSScreen::APP_MENU) {
// Q from inbox → go home; Q from inner views is handled by SMSScreen
if ((key == 'q' || key == '\b') && smsScr->getSubView() == SMSScreen::INBOX) {
Serial.println("Nav: SMS -> Home");
ui_task.gotoHomeScreen();
return;
}
// Phone dialer: debounced refresh for digit entry, immediate render for
// view transitions (Enter=call, Q=back). This avoids the 686ms e-ink
// block per keypress while ensuring call/back screens render instantly.
if (smsScr->getSubView() == SMSScreen::PHONE_DIALER) {
smsScr->handleInput(key);
if (smsScr->getSubView() == SMSScreen::PHONE_DIALER) {
// Still on dialer (digit/backspace) — debounced refresh
dialerNeedsRefresh = true;
lastDialerRefresh = millis();
} else {
// View changed (startCall or Q back) — render immediately
dialerNeedsRefresh = false;
ui_task.forceRefresh();
ui_task.loop();
}
return;
}
if (smsScr->isComposing()) {
// Composing/text input: route directly to screen, bypass injectKey()
// to avoid UITask scheduling its own competing refresh
@@ -1671,13 +1354,12 @@ void handleKeyboardInput() {
bool urlEdit = wr ? wr->isUrlEditing() : false;
bool passEdit = wr ? wr->isPasswordEntry() : false;
bool formEdit = wr ? wr->isFormFilling() : false;
bool searchEdit = wr ? wr->isSearchEditing() : false;
if (wr && (urlEdit || passEdit || formEdit || searchEdit)) {
if (wr && (urlEdit || passEdit || formEdit)) {
webReaderTextEntry = true; // Suppress ui_task.loop() in main loop
wr->handleInput(key); // Updates buffer instantly, no render
// Check if text entry ended (submitted, cancelled, etc.)
if (!wr->isUrlEditing() && !wr->isPasswordEntry() && !wr->isFormFilling() && !wr->isSearchEditing()) {
if (!wr->isUrlEditing() && !wr->isPasswordEntry() && !wr->isFormFilling()) {
// Text entry ended
webReaderTextEntry = false;
webReaderNeedsRefresh = false;
@@ -1694,7 +1376,7 @@ void handleKeyboardInput() {
webReaderTextEntry = false;
// Q from HOME mode exits the web reader entirely (like text reader)
if ((key == 'q' || key == 'Q') && wr && wr->isHome() && !wr->isUrlEditing() && !wr->isSearchEditing()) {
if ((key == 'q' || key == 'Q') && wr && wr->isHome() && !wr->isUrlEditing()) {
Serial.println("Exiting web reader");
ui_task.gotoHomeScreen();
return;
@@ -1758,12 +1440,7 @@ void handleKeyboardInput() {
Serial.println("Opening web reader");
{
static bool webReaderWifiReady = false;
#ifdef MECK_WIFI_COMPANION
// WiFi companion: WiFi is already up from boot, no BLE to tear down
webReaderWifiReady = true;
#endif
if (!webReaderWifiReady) {
#ifdef BLE_PIN_CODE
// WiFi needs ~40KB contiguous heap. The BLE controller holds ~30KB,
// leaving only ~30KB largest block. We MUST release BLE memory first.
//
@@ -1782,14 +1459,14 @@ void handleKeyboardInput() {
Serial.printf("WebReader: heap AFTER BT release: free=%d, largest=%d\n",
ESP.getFreeHeap(), ESP.getMaxAllocHeap());
#endif
// Init WiFi while we have maximum contiguous heap
// 3) Now init WiFi while we have maximum contiguous heap
if (WiFi.mode(WIFI_STA)) {
Serial.println("WebReader: WiFi STA init OK");
webReaderWifiReady = true;
} else {
Serial.println("WebReader: WiFi STA init FAILED");
Serial.println("WebReader: WiFi STA init FAILED even after BT release");
// Clean up partial WiFi init to avoid memory leak
WiFi.mode(WIFI_OFF);
}
@@ -1801,39 +1478,6 @@ void handleKeyboardInput() {
break;
#endif
case 'g':
// Open map screen, or re-center on GPS if already on map
if (ui_task.isOnMapScreen()) {
ui_task.injectKey('g'); // Re-center on GPS
} 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;
int markerCount = 0;
while (it.hasNext(&the_mesh, ci)) {
if (ci.gps_lat != 0 || ci.gps_lon != 0) {
double lat = ((double)ci.gps_lat) / 1000000.0;
double lon = ((double)ci.gps_lon) / 1000000.0;
ms->addMarker(lat, lon, ci.name, ci.type);
markerCount++;
Serial.printf(" marker: %s @ %.4f,%.4f (type=%d)\n", ci.name, lat, lon, ci.type);
}
}
Serial.printf("MapScreen: %d contacts with GPS position\n", markerCount);
}
}
ui_task.gotoMapScreen();
}
break;
case 'n':
// Open notes
Serial.println("Opening notes");
@@ -1849,13 +1493,11 @@ void handleKeyboardInput() {
break;
case 's':
// Open settings (from home), or navigate down on channel/contacts/admin/web/map/discovery
// Open settings (from home), or navigate down on channel/contacts/admin/web
if (ui_task.isOnChannelScreen() || ui_task.isOnContactsScreen() || ui_task.isOnRepeaterAdmin()
|| ui_task.isOnDiscoveryScreen()
#ifdef MECK_WEB_READER
|| ui_task.isOnWebReader()
#endif
|| ui_task.isOnMapScreen()
) {
ui_task.injectKey('s'); // Pass directly for scrolling
} else {
@@ -1867,11 +1509,9 @@ void handleKeyboardInput() {
case 'w':
// Navigate up/previous (scroll on channel screen)
if (ui_task.isOnChannelScreen() || ui_task.isOnContactsScreen() || ui_task.isOnRepeaterAdmin()
|| ui_task.isOnDiscoveryScreen()
#ifdef MECK_WEB_READER
|| ui_task.isOnWebReader()
#endif
|| ui_task.isOnMapScreen()
) {
ui_task.injectKey('w'); // Pass directly for scrolling
} else {
@@ -1882,7 +1522,7 @@ void handleKeyboardInput() {
case 'a':
// Navigate left or switch channel (on channel screen)
if (ui_task.isOnChannelScreen() || ui_task.isOnContactsScreen() || ui_task.isOnMapScreen()) {
if (ui_task.isOnChannelScreen() || ui_task.isOnContactsScreen()) {
ui_task.injectKey('a'); // Pass directly for channel/contacts switching
} else {
Serial.println("Nav: Previous");
@@ -1892,7 +1532,7 @@ void handleKeyboardInput() {
case 'd':
// Navigate right or switch channel (on channel screen)
if (ui_task.isOnChannelScreen() || ui_task.isOnContactsScreen() || ui_task.isOnMapScreen()) {
if (ui_task.isOnChannelScreen() || ui_task.isOnContactsScreen()) {
ui_task.injectKey('d'); // Pass directly for channel/contacts switching
} else {
Serial.println("Nav: Next");
@@ -1928,143 +1568,31 @@ void handleKeyboardInput() {
Serial.printf("Selected contact type=%d idx=%d\n", ctype, idx);
}
} else if (ui_task.isOnChannelScreen()) {
// If path overlay is showing, Enter copies path text to compose buffer
// Don't enter compose if path overlay is showing
ChannelScreen* chScr2 = (ChannelScreen*)ui_task.getChannelScreen();
if (chScr2 && chScr2->isShowingPathOverlay()) {
char pathText[138];
int pathLen = chScr2->formatPathAsText(pathText, sizeof(pathText));
if (pathLen > 0) {
int copyLen = pathLen < 137 ? pathLen : 137;
memcpy(composeBuffer, pathText, copyLen);
composeBuffer[copyLen] = '\0';
composePos = copyLen;
} else {
composeBuffer[0] = '\0';
composePos = 0;
}
composeDM = false;
composeDMContactIdx = -1;
composeChannelIdx = ui_task.getChannelScreenViewIdx();
composeMode = true;
chScr2->dismissPathOverlay();
Serial.printf("Compose with path, channel %d, prefill %d chars\n", composeChannelIdx, composePos);
drawComposeScreen();
lastComposeRefresh = millis();
break;
}
composeDM = false;
composeDMContactIdx = -1;
composeChannelIdx = ui_task.getChannelScreenViewIdx();
composeMode = true;
// If reply select mode is active, pre-fill @SenderName
char replySender[32];
if (chScr2 && chScr2->isReplySelectMode()
&& chScr2->getReplySelectSender(replySender, sizeof(replySender))) {
int prefixLen = snprintf(composeBuffer, sizeof(composeBuffer),
"@%s ", replySender);
composePos = prefixLen;
chScr2->exitReplySelect();
Serial.printf("Reply compose to @%s, channel %d\n",
replySender, composeChannelIdx);
} else {
composeBuffer[0] = '\0';
composePos = 0;
if (chScr2) chScr2->exitReplySelect(); // Clean up if somehow active
Serial.printf("Entering compose mode, channel %d\n", composeChannelIdx);
}
composeBuffer[0] = '\0';
composePos = 0;
Serial.printf("Entering compose mode, channel %d\n", composeChannelIdx);
drawComposeScreen();
lastComposeRefresh = millis();
} else if (ui_task.isOnDiscoveryScreen()) {
// Discovery screen: Enter adds selected node to contacts
DiscoveryScreen* ds = (DiscoveryScreen*)ui_task.getDiscoveryScreen();
int didx = ds->getSelectedIdx();
if (didx >= 0 && didx < the_mesh.getDiscoveredCount()) {
const DiscoveredNode& node = the_mesh.getDiscovered(didx);
if (node.already_in_contacts) {
ui_task.showAlert("Already in contacts", 800);
} else if (the_mesh.addDiscoveredToContacts(didx)) {
char alertBuf[48];
snprintf(alertBuf, sizeof(alertBuf), "Added: %s", node.contact.name);
ui_task.showAlert(alertBuf, 1500);
ui_task.notify(UIEventType::ack);
} else {
ui_task.showAlert("Add failed", 1000);
}
}
} else {
// Other screens: pass Enter as generic select
ui_task.injectKey(13);
}
break;
case 'z':
// Zoom in on map screen
if (ui_task.isOnMapScreen()) {
ui_task.injectKey('z');
}
break;
case 'x':
// Zoom out on map screen, or export contacts on contacts screen
if (ui_task.isOnMapScreen()) {
ui_task.injectKey('x');
} else if (ui_task.isOnContactsScreen()) {
Serial.println("Contacts: Exporting to SD...");
int exported = exportContactsToSD();
if (exported >= 0) {
char alertBuf[48];
snprintf(alertBuf, sizeof(alertBuf), "Exported %d to SD", exported);
ui_task.showAlert(alertBuf, 2000);
} else {
ui_task.showAlert("Export failed (check serial)", 2000);
}
}
break;
case 'r':
// Reply select mode (channel screen) or import contacts (contacts screen)
if (ui_task.isOnChannelScreen()) {
ui_task.injectKey('r');
} else if (ui_task.isOnContactsScreen()) {
Serial.println("Contacts: Importing from SD...");
int added = importContactsFromSD();
if (added > 0) {
// Invalidate the contacts screen cache so it rebuilds
ContactsScreen* cs2 = (ContactsScreen*)ui_task.getContactsScreen();
if (cs2) cs2->invalidateCache();
char alertBuf[48];
snprintf(alertBuf, sizeof(alertBuf), "+%d imported (%d total)",
added, (int)the_mesh.getNumContacts());
ui_task.showAlert(alertBuf, 2500);
} else if (added == 0) {
ui_task.showAlert("No new contacts to add", 2000);
} else {
ui_task.showAlert("Import failed (no backup?)", 2000);
}
}
break;
case 'f':
// Start discovery scan from contacts screen, or rescan on discovery screen
if (ui_task.isOnContactsScreen()) {
Serial.println("Contacts: Starting discovery scan...");
the_mesh.startDiscovery();
ui_task.gotoDiscoveryScreen();
} else if (ui_task.isOnDiscoveryScreen()) {
ui_task.injectKey('f'); // pass through for rescan
}
break;
case 'q':
case '\b':
// If channel screen reply select or path overlay is showing, dismiss it
// If channel screen path overlay is showing, dismiss it instead of going home
if (ui_task.isOnChannelScreen()) {
ChannelScreen* chScr = (ChannelScreen*)ui_task.getChannelScreen();
if (chScr && chScr->isReplySelectMode()) {
ui_task.injectKey('q');
break;
}
if (chScr && chScr->isShowingPathOverlay()) {
ui_task.injectKey('q');
break;
@@ -2081,13 +1609,6 @@ void handleKeyboardInput() {
}
}
#endif
// Discovery screen: Q goes back to contacts (not home)
if (ui_task.isOnDiscoveryScreen()) {
the_mesh.stopDiscovery();
Serial.println("Nav: Discovery -> Contacts");
ui_task.gotoContactsScreen();
break;
}
// Go back to home screen (admin mode handled above)
Serial.println("Nav: Back to home");
ui_task.gotoHomeScreen();
@@ -2119,11 +1640,6 @@ void handleKeyboardInput() {
break;
}
#endif
// Pass unhandled keys to map screen (+, -, i, o for zoom)
if (ui_task.isOnMapScreen()) {
ui_task.injectKey(key);
break;
}
Serial.printf("Unhandled key in normal mode: '%c' (0x%02X)\n", key, key);
break;
}

View File

@@ -1,372 +0,0 @@
#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

View File

@@ -4,7 +4,6 @@
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ChannelDetails.h>
#include <MeshCore.h>
#include <Packet.h>
#include "EmojiSprites.h"
// SD card message persistence
@@ -25,7 +24,7 @@
// On-disk format for message persistence (SD card)
// ---------------------------------------------------------------------------
#define MSG_FILE_MAGIC 0x4D434853 // "MCHS" - MeshCore History Store
#define MSG_FILE_VERSION 3 // v3: MSG_PATH_MAX=20, reserved→snr field
#define MSG_FILE_VERSION 3
#define MSG_FILE_PATH "/meshcore/messages.bin"
struct __attribute__((packed)) MsgFileHeader {
@@ -42,7 +41,7 @@ struct __attribute__((packed)) MsgFileRecord {
uint8_t path_len;
uint8_t channel_idx;
uint8_t valid;
int8_t snr; // Receive SNR × 4 (was reserved; 0 = unknown)
uint8_t reserved;
uint8_t path[MSG_PATH_MAX]; // Repeater hop hashes (first byte of pub key)
char text[CHANNEL_MSG_TEXT_LEN];
// 188 bytes total
@@ -58,7 +57,6 @@ public:
uint32_t timestamp;
uint8_t path_len;
uint8_t channel_idx; // Which channel this message belongs to
int8_t snr; // Receive SNR × 4 (0 if locally sent or unknown)
uint8_t path[MSG_PATH_MAX]; // Repeater hop hashes
char text[CHANNEL_MSG_TEXT_LEN];
bool valid;
@@ -76,38 +74,24 @@ private:
uint8_t _viewChannelIdx; // Which channel we're currently viewing
bool _sdReady; // SD card is available for persistence
bool _showPathOverlay; // Show path detail overlay for last received msg
int _pathScrollPos; // Scroll offset within path overlay hop list
int _pathHopsVisible; // Hops that fit on screen (set during render)
// Reply select mode — press R to pick a message and reply with @mention
bool _replySelectMode; // True when user is picking a message to reply to
int _replySelectPos; // Index into chronological channelMsgs[] (0=oldest)
int _replyChannelMsgCount; // Cached count from last render (for input bounds)
// Per-channel unread message counts (standalone mode)
// Index 0..MAX_GROUP_CHANNELS-1 for channel messages
// Index MAX_GROUP_CHANNELS for DMs (channel_idx == 0xFF)
int _unread[MAX_GROUP_CHANNELS + 1];
int _pathOverlayScroll; // Scroll offset for hop list in path overlay
public:
ChannelScreen(UITask* task, mesh::RTCClock* rtc)
: _task(task), _rtc(rtc), _msgCount(0), _newestIdx(-1), _scrollPos(0),
_msgsPerPage(6), _viewChannelIdx(0), _sdReady(false), _showPathOverlay(false), _pathScrollPos(0), _pathHopsVisible(20),
_replySelectMode(false), _replySelectPos(-1), _replyChannelMsgCount(0) {
_msgsPerPage(6), _viewChannelIdx(0), _sdReady(false), _showPathOverlay(false), _pathOverlayScroll(0) {
// Initialize all messages as invalid
for (int i = 0; i < CHANNEL_MSG_HISTORY_SIZE; i++) {
_messages[i].valid = false;
memset(_messages[i].path, 0, MSG_PATH_MAX);
}
// Initialize unread counts
memset(_unread, 0, sizeof(_unread));
}
void setSDReady(bool ready) { _sdReady = ready; }
// Add a new message to the history
void addMessage(uint8_t channel_idx, uint8_t path_len, const char* sender, const char* text,
const uint8_t* path_bytes = nullptr, int8_t snr = 0) {
const uint8_t* path_bytes = nullptr) {
// Move to next slot in circular buffer
_newestIdx = (_newestIdx + 1) % CHANNEL_MSG_HISTORY_SIZE;
@@ -115,14 +99,12 @@ public:
msg->timestamp = _rtc->getCurrentTime();
msg->path_len = path_len;
msg->channel_idx = channel_idx;
msg->snr = snr;
msg->valid = true;
// Store path hop hashes
memset(msg->path, 0, MSG_PATH_MAX);
if (path_bytes && path_len > 0 && path_len != 0xFF) {
int n = mesh::Packet::getPathByteLenFor(path_len);
if (n > MSG_PATH_MAX) n = MSG_PATH_MAX;
int n = path_len < MSG_PATH_MAX ? path_len : MSG_PATH_MAX;
memcpy(msg->path, path_bytes, n);
}
@@ -137,18 +119,7 @@ public:
// Reset scroll to show newest message
_scrollPos = 0;
_showPathOverlay = false; // Dismiss overlay on new message
_pathScrollPos = 0;
_replySelectMode = false; // Dismiss reply select on new message
_replySelectPos = -1;
// Track unread count for this channel (only for received messages, not sent)
// path_len == 0 means locally sent
if (path_len != 0) {
int unreadSlot = (channel_idx == 0xFF) ? MAX_GROUP_CHANNELS : channel_idx;
if (unreadSlot >= 0 && unreadSlot <= MAX_GROUP_CHANNELS) {
_unread[unreadSlot]++;
}
}
_pathOverlayScroll = 0;
// Persist to SD card
saveToSD();
@@ -168,107 +139,8 @@ public:
int getMessageCount() const { return _msgCount; }
uint8_t getViewChannelIdx() const { return _viewChannelIdx; }
void setViewChannelIdx(uint8_t idx) {
_viewChannelIdx = idx;
_scrollPos = 0;
_showPathOverlay = false;
_pathScrollPos = 0;
markChannelRead(idx);
}
void setViewChannelIdx(uint8_t idx) { _viewChannelIdx = idx; _scrollPos = 0; _showPathOverlay = false; _pathOverlayScroll = 0; }
bool isShowingPathOverlay() const { return _showPathOverlay; }
void dismissPathOverlay() { _showPathOverlay = false; _pathScrollPos = 0; }
// --- Reply select mode (R key → pick a message → Enter to @mention reply) ---
bool isReplySelectMode() const { return _replySelectMode; }
void exitReplySelect() { _replySelectMode = false; _replySelectPos = -1; }
// Extract sender name from a "Sender: message" formatted text.
// Returns true if a sender was found, fills senderBuf (null-terminated).
static bool extractSenderName(const char* msgText, char* senderBuf, int bufLen) {
const char* colon = strstr(msgText, ": ");
if (!colon || colon == msgText) return false;
int nameLen = colon - msgText;
if (nameLen >= bufLen) nameLen = bufLen - 1;
memcpy(senderBuf, msgText, nameLen);
senderBuf[nameLen] = '\0';
return true;
}
// Get the sender name of the currently selected message in reply select mode.
// Returns true and fills senderBuf if valid selection exists.
bool getReplySelectSender(char* senderBuf, int bufLen) {
if (!_replySelectMode || _replySelectPos < 0) return false;
// Rebuild the channel message list (same logic as render)
static int rsMsgs[CHANNEL_MSG_HISTORY_SIZE];
int count = 0;
for (int i = 0; i < _msgCount && count < CHANNEL_MSG_HISTORY_SIZE; i++) {
int idx = _newestIdx - i;
while (idx < 0) idx += CHANNEL_MSG_HISTORY_SIZE;
idx = idx % CHANNEL_MSG_HISTORY_SIZE;
if (_messages[idx].valid && _messages[idx].channel_idx == _viewChannelIdx) {
rsMsgs[count++] = idx;
}
}
// Reverse to chronological (oldest first)
for (int l = 0, r = count - 1; l < r; l++, r--) {
int t = rsMsgs[l]; rsMsgs[l] = rsMsgs[r]; rsMsgs[r] = t;
}
if (_replySelectPos >= count) return false;
int idx = rsMsgs[_replySelectPos];
return extractSenderName(_messages[idx].text, senderBuf, bufLen);
}
// Get the ChannelMessage pointer for the currently selected reply message.
ChannelMessage* getReplySelectMsg() {
if (!_replySelectMode || _replySelectPos < 0) return nullptr;
static int rsMsgs[CHANNEL_MSG_HISTORY_SIZE];
int count = 0;
for (int i = 0; i < _msgCount && count < CHANNEL_MSG_HISTORY_SIZE; i++) {
int idx = _newestIdx - i;
while (idx < 0) idx += CHANNEL_MSG_HISTORY_SIZE;
idx = idx % CHANNEL_MSG_HISTORY_SIZE;
if (_messages[idx].valid && _messages[idx].channel_idx == _viewChannelIdx) {
rsMsgs[count++] = idx;
}
}
for (int l = 0, r = count - 1; l < r; l++, r--) {
int t = rsMsgs[l]; rsMsgs[l] = rsMsgs[r]; rsMsgs[r] = t;
}
if (_replySelectPos >= count) return nullptr;
return &_messages[rsMsgs[_replySelectPos]];
}
// --- Unread message tracking (standalone mode) ---
// Mark all messages for a channel as read
void markChannelRead(uint8_t channel_idx) {
int slot = (channel_idx == 0xFF) ? MAX_GROUP_CHANNELS : channel_idx;
if (slot >= 0 && slot <= MAX_GROUP_CHANNELS) {
_unread[slot] = 0;
}
}
// Get unread count for a specific channel
int getUnreadForChannel(uint8_t channel_idx) const {
int slot = (channel_idx == 0xFF) ? MAX_GROUP_CHANNELS : channel_idx;
if (slot >= 0 && slot <= MAX_GROUP_CHANNELS) {
return _unread[slot];
}
return 0;
}
// Get total unread across all channels
int getTotalUnread() const {
int total = 0;
for (int i = 0; i <= MAX_GROUP_CHANNELS; i++) {
total += _unread[i];
}
return total;
}
// Find the newest RECEIVED message for the current channel
// (path_len != 0 means received, path_len 0 = locally sent)
@@ -285,34 +157,12 @@ public:
return nullptr;
}
// Format the path of the newest received message as paste-ready text
// Output: comma-separated hex prefixes e.g. "30, 3b, 9b, 05, e8, 36"
// Returns length written (0 if no path available)
int formatPathAsText(char* buf, int bufLen) {
ChannelMessage* msg = getNewestReceivedMsg();
if (!msg || msg->path_len == 0 || msg->path_len == 0xFF) return 0;
int pos = 0;
uint8_t hopCount = msg->path_len & 63;
uint8_t bytesPerHop = (msg->path_len >> 6) + 1;
for (int h = 0; h < hopCount && pos < bufLen - 1; h++) {
if (h > 0) pos += snprintf(buf + pos, bufLen - pos, ", ");
int offset = h * bytesPerHop;
for (int b = 0; b < bytesPerHop && pos < bufLen - 1; b++) {
pos += snprintf(buf + pos, bufLen - pos, "%02x", msg->path[offset + b]);
}
}
return pos;
}
// -----------------------------------------------------------------------
// SD card persistence
// -----------------------------------------------------------------------
// Save the entire message buffer to SD card.
// File: /meshcore/messages.bin (~50 KB for 300 messages)
// File: /meshcore/messages.bin (~56 KB for 300 messages)
void saveToSD() {
#if defined(HAS_SDCARD) && defined(ESP32)
if (!_sdReady) return;
@@ -344,7 +194,7 @@ public:
rec.path_len = _messages[i].path_len;
rec.channel_idx = _messages[i].channel_idx;
rec.valid = _messages[i].valid ? 1 : 0;
rec.snr = _messages[i].snr;
rec.reserved = 0;
memcpy(rec.path, _messages[i].path, MSG_PATH_MAX);
memcpy(rec.text, _messages[i].text, CHANNEL_MSG_TEXT_LEN);
f.write((uint8_t*)&rec, sizeof(rec));
@@ -411,7 +261,6 @@ public:
_messages[i].path_len = rec.path_len;
_messages[i].channel_idx = rec.channel_idx;
_messages[i].valid = (rec.valid != 0);
_messages[i].snr = rec.snr;
memcpy(_messages[i].path, rec.path, MSG_PATH_MAX);
memcpy(_messages[i].text, rec.text, CHANNEL_MSG_TEXT_LEN);
if (_messages[i].valid) loaded++;
@@ -500,8 +349,6 @@ public:
// Route type
display.setCursor(0, y);
uint8_t plen = msg->path_len;
uint8_t hopCount = plen & 63; // extract hop count from encoded path_len
uint8_t bytesPerHop = (plen >> 6) + 1; // 1, 2, or 3 bytes per hop
if (plen == 0xFF) {
display.setColor(DisplayDriver::LIGHT);
display.print("Route: Direct");
@@ -510,82 +357,47 @@ public:
display.print("Route: Local/Sent");
} else {
display.setColor(DisplayDriver::GREEN);
sprintf(tmp, "Route: %d hop%s (%dB)", hopCount, hopCount == 1 ? "" : "s", bytesPerHop);
sprintf(tmp, "Route: %d hop%s", plen, plen == 1 ? "" : "s");
display.print(tmp);
}
y += lineH;
// SNR (if available — value is SNR×4)
if (msg->snr != 0) {
display.setCursor(0, y);
display.setColor(DisplayDriver::YELLOW);
int snr_whole = msg->snr / 4;
int snr_frac = ((abs(msg->snr) % 4) * 10) / 4;
sprintf(tmp, "SNR: %d.%ddB", snr_whole, snr_frac);
display.print(tmp);
y += lineH;
}
y += 2;
y += lineH + 2;
// Show each hop resolved against contacts (scrollable)
if (hopCount > 0 && plen != 0xFF) {
int displayHops = hopCount;
int footerReserve = 26; // footer + divider
if (plen > 0 && plen != 0xFF) {
int displayHops = plen < MSG_PATH_MAX ? plen : MSG_PATH_MAX;
int footerHeight = 14;
int scrollBarW = 4;
int maxY = display.height() - footerReserve;
int hopAreaTop = y;
int maxY = display.height() - footerHeight;
// Calculate how many hops fit in the visible area
int hopsVisible = (maxY - hopAreaTop) / lineH;
if (hopsVisible < 1) hopsVisible = 1;
_pathHopsVisible = hopsVisible; // Cache for input handler
bool needsScroll = displayHops > hopsVisible;
int hopsAreaTop = y;
int visibleHops = (maxY - y) / lineH;
if (visibleHops < 1) visibleHops = 1;
// Clamp scroll position
int maxScroll = displayHops - hopsVisible;
if (maxScroll < 0) maxScroll = 0;
if (_pathScrollPos > maxScroll) _pathScrollPos = maxScroll;
int maxScroll = displayHops > visibleHops ? displayHops - visibleHops : 0;
if (_pathOverlayScroll > maxScroll) _pathOverlayScroll = maxScroll;
// Available text width (narrower if scroll bar present)
int textRight = needsScroll ? display.width() - scrollBarW - 2 : display.width();
(void)textRight; // reserved for future truncation
int startHop = _pathOverlayScroll;
int startHop = _pathScrollPos;
int endHop = startHop + hopsVisible;
if (endHop > displayHops) endHop = displayHops;
for (int h = startHop; h < endHop && y + lineH <= maxY; h++) {
int hopOffset = h * bytesPerHop; // byte offset into path[]
for (int h = startHop; h < displayHops && y + lineH <= maxY; h++) {
uint8_t hopHash = msg->path[h];
display.setCursor(0, y);
display.setColor(DisplayDriver::LIGHT);
sprintf(tmp, " %d: ", h + 1);
display.print(tmp);
// Show hex prefix (1, 2, or 3 bytes)
display.setColor(DisplayDriver::LIGHT);
if (bytesPerHop == 1) {
sprintf(tmp, "%02X ", msg->path[hopOffset]);
} else if (bytesPerHop == 2) {
sprintf(tmp, "%02X%02X ", msg->path[hopOffset], msg->path[hopOffset + 1]);
} else {
sprintf(tmp, "%02X%02X%02X ", msg->path[hopOffset], msg->path[hopOffset + 1], msg->path[hopOffset + 2]);
}
display.print(tmp);
// Try to resolve name: prefer repeaters, then any contact
// Try to resolve: prefer repeaters, then any contact
bool resolved = false;
int numContacts = the_mesh.getNumContacts();
ContactInfo contact;
char filteredName[32];
// First pass: repeaters only
for (uint32_t ci = 0; ci < numContacts && !resolved; ci++) {
if (the_mesh.getContactByIdx(ci, contact)) {
if (memcmp(contact.id.pub_key, &msg->path[hopOffset], bytesPerHop) == 0
&& contact.type == ADV_TYPE_REPEATER) {
if (contact.id.pub_key[0] == hopHash && contact.type == ADV_TYPE_REPEATER) {
display.setColor(DisplayDriver::GREEN);
display.translateUTF8ToBlocks(filteredName, contact.name, sizeof(filteredName));
display.print(filteredName);
display.print(contact.name);
resolved = true;
}
}
@@ -594,39 +406,38 @@ public:
if (!resolved) {
for (uint32_t ci = 0; ci < numContacts; ci++) {
if (the_mesh.getContactByIdx(ci, contact)) {
if (memcmp(contact.id.pub_key, &msg->path[hopOffset], bytesPerHop) == 0) {
if (contact.id.pub_key[0] == hopHash) {
display.setColor(DisplayDriver::YELLOW);
display.translateUTF8ToBlocks(filteredName, contact.name, sizeof(filteredName));
display.print(filteredName);
display.print(contact.name);
resolved = true;
break;
}
}
}
}
// No name resolved - hex prefix already shown, add "?" marker
// Fallback: show hex hash
if (!resolved) {
display.setColor(DisplayDriver::LIGHT);
display.print("?");
sprintf(tmp, "?%02X", hopHash);
display.print(tmp);
}
y += lineH;
}
// Scroll bar (right edge) when hops exceed visible area
if (needsScroll) {
// --- Scroll bar for hop list ---
if (displayHops > visibleHops) {
int sbX = display.width() - scrollBarW;
int sbTop = hopAreaTop;
int sbHeight = maxY - hopAreaTop;
int sbTop = hopsAreaTop;
int sbHeight = maxY - hopsAreaTop;
// Outline
// Draw track outline
display.setColor(DisplayDriver::LIGHT);
display.drawRect(sbX, sbTop, scrollBarW, sbHeight);
// Proportional thumb
int thumbH = (hopsVisible * sbHeight) / displayHops;
// Draw proportional thumb
int thumbH = (visibleHops * sbHeight) / displayHops;
if (thumbH < 4) thumbH = 4;
int thumbY = sbTop + (_pathScrollPos * (sbHeight - thumbH)) / maxScroll;
display.setColor(DisplayDriver::GREEN);
int thumbY = sbTop + (_pathOverlayScroll * (sbHeight - thumbH)) / maxScroll;
for (int ty = thumbY + 1; ty < thumbY + thumbH - 1; ty++)
display.drawRect(sbX + 1, ty, scrollBarW - 2, 1);
}
@@ -639,17 +450,7 @@ public:
display.drawRect(0, footerY - 2, display.width(), 1);
display.setCursor(0, footerY);
display.setColor(DisplayDriver::YELLOW);
display.print("Q:Back");
// Show scroll hint if path is scrollable
if (msg && (msg->path_len & 63) > _pathHopsVisible && msg->path_len != 0xFF) {
const char* scrollHint = "W/S:Scrl";
int scrollW = display.getTextWidth(scrollHint);
display.setCursor((display.width() - scrollW) / 2, footerY);
display.print(scrollHint);
}
const char* copyHint = "Ent:Copy";
display.setCursor(display.width() - display.getTextWidth(copyHint) - 2, footerY);
display.print(copyHint);
display.print("Q:Back W/S:Scroll");
#if AUTO_OFF_MILLIS == 0
return 5000;
@@ -700,9 +501,6 @@ public:
int tmp = channelMsgs[l]; channelMsgs[l] = channelMsgs[r]; channelMsgs[r] = tmp;
}
// Cache for reply select input bounds
_replyChannelMsgCount = numChannelMsgs;
// Clamp scroll position to valid range
int maxScroll = numChannelMsgs > _msgsPerPage ? numChannelMsgs - _msgsPerPage : 0;
if (_scrollPos > maxScroll) _scrollPos = maxScroll;
@@ -715,66 +513,35 @@ public:
// Display messages oldest-to-newest (top to bottom)
int msgsDrawn = 0;
bool screenFull = false;
bool lastMsgTruncated = false; // Did the last message get clipped by footer?
for (int i = startIdx; i < numChannelMsgs && y + lineHeight <= maxY; i++) {
int idx = channelMsgs[i];
ChannelMessage* msg = &_messages[idx];
// Reply select: is this the currently selected message?
bool isSelected = (_replySelectMode && i == _replySelectPos);
// Highlight: single fillRect for the entire message area, then
// draw DARK text on top (same pattern as web reader bookmarks).
// Because message height depends on word-wrap, we fill a generous
// area up-front and erase the excess after rendering.
int yStart = y;
int contentW = display.width();
int maxLinesPerMsg = 8;
if (isSelected) {
int maxFillH = (maxLinesPerMsg + 1) * lineHeight + 2;
int availH = maxY - y;
if (maxFillH > availH) maxFillH = availH;
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y + 5, contentW, maxFillH);
}
// Time indicator with hop count - inline on same line as message start
display.setCursor(0, y);
display.setColor(isSelected ? DisplayDriver::DARK : DisplayDriver::YELLOW);
display.setColor(DisplayDriver::YELLOW);
uint32_t age = _rtc->getCurrentTime() - msg->timestamp;
if (isSelected) {
// Show > marker for selected message, replacing the hop count
if (age < 60) {
sprintf(tmp, ">%ds ", age);
} else if (age < 3600) {
sprintf(tmp, ">%dm ", age / 60);
} else if (age < 86400) {
sprintf(tmp, ">%dh ", age / 3600);
} else {
sprintf(tmp, ">%dd ", age / 86400);
}
if (age < 60) {
sprintf(tmp, "(%d) %ds ", msg->path_len == 0xFF ? 0 : msg->path_len, age);
} else if (age < 3600) {
sprintf(tmp, "(%d) %dm ", msg->path_len == 0xFF ? 0 : msg->path_len, age / 60);
} else if (age < 86400) {
sprintf(tmp, "(%d) %dh ", msg->path_len == 0xFF ? 0 : msg->path_len, age / 3600);
} else {
if (age < 60) {
sprintf(tmp, "(%d) %ds ", msg->path_len == 0xFF ? 0 : (msg->path_len & 63), age);
} else if (age < 3600) {
sprintf(tmp, "(%d) %dm ", msg->path_len == 0xFF ? 0 : (msg->path_len & 63), age / 60);
} else if (age < 86400) {
sprintf(tmp, "(%d) %dh ", msg->path_len == 0xFF ? 0 : (msg->path_len & 63), age / 3600);
} else {
sprintf(tmp, "(%d) %dd ", msg->path_len == 0xFF ? 0 : (msg->path_len & 63), age / 86400);
}
sprintf(tmp, "(%d) %dd ", msg->path_len == 0xFF ? 0 : msg->path_len, age / 86400);
}
display.print(tmp);
// DO NOT advance y - message text continues on the same line
// Message text with character wrapping and inline emoji support
// (continues after timestamp on first line)
display.setColor(isSelected ? DisplayDriver::DARK : DisplayDriver::LIGHT);
display.setColor(DisplayDriver::LIGHT);
int textLen = strlen(msg->text);
int pos = 0;
int linesForThisMsg = 0;
int maxLinesPerMsg = 8;
char charStr[2] = {0, 0};
// Track position in pixels for emoji placement
@@ -868,30 +635,12 @@ public:
}
}
// Check if this message was clipped (not all text rendered)
lastMsgTruncated = (pos < textLen);
// If we didn't end on a full line, still count it
if (px > 0) {
y += lineHeight;
}
y += 2; // Small gap between messages
// Erase excess highlight below the actual message.
// The upfront fillRect covered a max area; restore the unused
// portion back to background so subsequent messages render cleanly.
if (isSelected) {
int usedH = y - yStart;
int maxFillH = (maxLinesPerMsg + 1) * lineHeight + 2;
int availH = maxY - yStart;
if (maxFillH > availH) maxFillH = availH;
if (usedH < maxFillH) {
display.setColor(DisplayDriver::DARK);
display.fillRect(0, y + 5, contentW, maxFillH - usedH);
}
}
msgsDrawn++;
if (y + lineHeight > maxY) screenFull = true;
}
@@ -901,12 +650,7 @@ public:
// prevents a feedback loop where variable-height messages cause
// msgsPerPage to oscillate, shifting startIdx every render (flicker).
if (screenFull && msgsDrawn > 0 && _scrollPos == 0) {
// If the last message was truncated (text clipped by footer), exclude it
// from the page count so next render starts one message later and the
// bottom message fits completely.
int effectiveDrawn = lastMsgTruncated ? msgsDrawn - 1 : msgsDrawn;
if (effectiveDrawn < 1) effectiveDrawn = 1;
_msgsPerPage = effectiveDrawn;
_msgsPerPage = msgsDrawn;
}
// --- Scroll bar (emoji picker style) ---
@@ -944,17 +688,12 @@ public:
display.setColor(DisplayDriver::YELLOW);
// Left side: abbreviated controls
if (_replySelectMode) {
display.print("W/S:Sel V:Pth Q:X");
const char* rightText = "Ent:Reply";
display.setCursor(display.width() - display.getTextWidth(rightText) - 2, footerY);
display.print(rightText);
} else {
display.print("Q:Bck A/D:Ch R:Rply");
const char* rightText = "Ent:New";
display.setCursor(display.width() - display.getTextWidth(rightText) - 2, footerY);
display.print(rightText);
}
display.print("Q:Bck A/D:Ch V:Pth");
// Right side: Ent:New
const char* rightText = "Ent:New";
display.setCursor(display.width() - display.getTextWidth(rightText) - 2, footerY);
display.print(rightText);
#if AUTO_OFF_MILLIS == 0 // e-ink
return 5000;
@@ -964,107 +703,34 @@ public:
}
bool handleInput(char c) override {
// If overlay is showing, handle scroll and dismiss
// If overlay is showing, only handle dismiss
if (_showPathOverlay) {
if (c == 'q' || c == 'Q' || c == '\b' || c == 'v' || c == 'V') {
_showPathOverlay = false;
_pathScrollPos = 0;
return true;
}
if (c == '\r' || c == 13) {
return false; // Let main.cpp handle Enter for copy-to-compose
}
// W - scroll up in hop list
if (c == 'w' || c == 'W' || c == 0xF2) {
if (_pathScrollPos > 0) {
_pathScrollPos--;
if (_pathOverlayScroll > 0) {
_pathOverlayScroll--;
return true;
}
return true;
}
// S - scroll down in hop list
if (c == 's' || c == 'S' || c == 0xF1) {
ChannelMessage* msg = getNewestReceivedMsg();
if (msg && msg->path_len > 0 && msg->path_len != 0xFF) {
int totalHops = msg->path_len & 63;
if (_pathScrollPos < totalHops - _pathHopsVisible) {
_pathScrollPos++;
}
}
_pathOverlayScroll++; // Clamped during render
return true;
}
return true; // Consume all other keys while overlay is up
return true; // Consume all keys while overlay is up
}
// --- Reply select mode ---
if (_replySelectMode) {
// Q - exit reply select
if (c == 'q' || c == 'Q' || c == '\b') {
_replySelectMode = false;
_replySelectPos = -1;
return true;
}
// W - select older message (lower index in chronological order)
if (c == 'w' || c == 'W' || c == 0xF2) {
if (_replySelectPos > 0) {
_replySelectPos--;
// Auto-scroll to keep selection visible
int startIdx = _replyChannelMsgCount - _msgsPerPage - _scrollPos;
if (startIdx < 0) startIdx = 0;
if (_replySelectPos < startIdx) {
_scrollPos++;
}
}
return true;
}
// S - select newer message (higher index in chronological order)
if (c == 's' || c == 'S' || c == 0xF1) {
if (_replySelectPos < _replyChannelMsgCount - 1) {
_replySelectPos++;
// Auto-scroll to keep selection visible
int endIdx = _replyChannelMsgCount - _scrollPos;
if (_replySelectPos >= endIdx) {
if (_scrollPos > 0) _scrollPos--;
}
}
return true;
}
// V - view path for the SELECTED message (not just newest received)
if (c == 'v' || c == 'V') {
// Path overlay will use getNewestReceivedMsg() — for v1 this is fine.
// The user can see the selected message's hop count in the > marker.
ChannelMessage* selMsg = getReplySelectMsg();
if (selMsg && selMsg->path_len != 0) {
_showPathOverlay = true;
_pathScrollPos = 0;
}
return true;
}
// Enter - let main.cpp handle (enters compose with @mention)
if (c == '\r' || c == 13) {
return false;
}
return true; // Consume all other keys in reply select
}
int channelMsgCount = getMessageCountForChannel();
// R - enter reply select mode
if (c == 'r' || c == 'R') {
if (channelMsgCount > 0) {
_replySelectMode = true;
// Start with newest message selected
_replySelectPos = _replyChannelMsgCount > 0
? _replyChannelMsgCount - 1 : channelMsgCount - 1;
return true;
}
return false;
}
// V - show path detail for last received message
if (c == 'v' || c == 'V') {
if (getNewestReceivedMsg() != nullptr) {
_showPathOverlay = true;
_pathScrollPos = 0;
_pathOverlayScroll = 0;
return true;
}
return false; // No received messages to show
@@ -1088,8 +754,6 @@ public:
// A - previous channel
if (c == 'a' || c == 'A') {
_replySelectMode = false;
_replySelectPos = -1;
if (_viewChannelIdx > 0) {
_viewChannelIdx--;
} else {
@@ -1103,14 +767,11 @@ public:
}
}
_scrollPos = 0;
markChannelRead(_viewChannelIdx);
return true;
}
// D - next channel
if (c == 'd' || c == 'D') {
_replySelectMode = false;
_replySelectPos = -1;
ChannelDetails ch;
uint8_t nextIdx = _viewChannelIdx + 1;
if (the_mesh.getChannel(nextIdx, ch) && ch.name[0] != '\0') {
@@ -1119,7 +780,6 @@ public:
_viewChannelIdx = 0;
}
_scrollPos = 0;
markChannelRead(_viewChannelIdx);
return true;
}

View File

@@ -18,7 +18,6 @@ public:
FILTER_REPEATER,
FILTER_ROOM, // Room servers
FILTER_SENSOR,
FILTER_FAVOURITE, // Contacts marked as favourite (any type)
FILTER_COUNT // keep last
};
@@ -31,9 +30,9 @@ private:
// Cached filtered contact indices for efficient scrolling
// We rebuild this on filter change or when entering the screen
// Arrays allocated in PSRAM when available (supports 1000+ contacts)
uint16_t* _filteredIdx; // indices into contact table
uint32_t* _filteredTs; // cached last_advert_timestamp for sorting
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
int _filteredCount; // how many contacts match current filter
bool _cacheValid;
@@ -49,7 +48,6 @@ private:
case FILTER_REPEATER: return "Rptr";
case FILTER_ROOM: return "Room";
case FILTER_SENSOR: return "Sens";
case FILTER_FAVOURITE: return "Fav";
default: return "?";
}
}
@@ -63,7 +61,7 @@ private:
}
}
bool matchesFilter(uint8_t adv_type, uint8_t flags = 0) const {
bool matchesFilter(uint8_t adv_type) const {
switch (_filter) {
case FILTER_ALL: return true;
case FILTER_CHAT: return adv_type == ADV_TYPE_CHAT;
@@ -72,7 +70,6 @@ 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;
}
}
@@ -81,9 +78,9 @@ private:
_filteredCount = 0;
uint32_t numContacts = the_mesh.getNumContacts();
ContactInfo contact;
for (uint32_t i = 0; i < numContacts && _filteredCount < MAX_CONTACTS; i++) {
for (uint32_t i = 0; i < numContacts && _filteredCount < MAX_VISIBLE; i++) {
if (the_mesh.getContactByIdx(i, contact)) {
if (matchesFilter(contact.type, contact.flags)) {
if (matchesFilter(contact.type)) {
_filteredIdx[_filteredCount] = (uint16_t)i;
_filteredTs[_filteredCount] = contact.last_advert_timestamp;
_filteredCount++;
@@ -91,7 +88,7 @@ private:
}
}
// Sort by last_advert_timestamp descending (most recently seen first)
// Insertion sort fine for up to ~1000 entries on ESP32
// Simple insertion sort — fine for up to 400 entries on ESP32
for (int i = 1; i < _filteredCount; i++) {
uint16_t tmpIdx = _filteredIdx[i];
uint32_t tmpTs = _filteredTs[i];
@@ -133,15 +130,7 @@ private:
public:
ContactsScreen(UITask* task, mesh::RTCClock* rtc)
: _task(task), _rtc(rtc), _scrollPos(0), _filter(FILTER_ALL),
_filteredCount(0), _cacheValid(false), _rowsPerPage(5) {
#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));
#else
_filteredIdx = new uint16_t[MAX_CONTACTS]();
_filteredTs = new uint32_t[MAX_CONTACTS]();
#endif
}
_filteredCount(0), _cacheValid(false), _rowsPerPage(5) {}
void invalidateCache() { _cacheValid = false; }
@@ -297,17 +286,17 @@ public:
display.drawRect(0, footerY - 2, display.width(), 1);
display.setColor(DisplayDriver::YELLOW);
// Left: Q:Bk
// Left: Q:Back
display.setCursor(0, footerY);
display.print("Q:Bk");
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: F:Dscvr
const char* right = "F:Dscvr";
// Right: W/S:Scroll
const char* right = "W/S:Scrll";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);

View File

@@ -1,205 +0,0 @@
#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; }
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(0); // tiny font for compact rows
int lineHeight = 9;
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);
display.print("F: Scan again Q: Back");
}
} 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);
display.fillRect(0, y + 5, display.width(), lineHeight);
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);
display.print("Q:Back");
const char* mid = "Ent:Add";
display.setCursor((display.width() - display.getTextWidth(mid)) / 2, footerY);
display.print(mid);
const char* right = "F:Rescan";
display.setCursor(display.width() - display.getTextWidth(right) - 2, footerY);
display.print(right);
// 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
}
};

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
// 65 total emoji: joy/thumbsup/frown first, then 43 original, then 19 new
// 46 total emoji: joy/thumbsup/frown first, then 43 original (telephone removed)
#include <stdint.h>
#ifdef ESP32
@@ -15,11 +15,11 @@
#define EMOJI_SM_W 10
#define EMOJI_SM_H 10
#define EMOJI_COUNT 65
#define EMOJI_COUNT 46
// Escape codes in 0x80+ range - safe from keyboard ASCII (32-126)
#define EMOJI_ESCAPE_START 0x80
#define EMOJI_ESCAPE_END 0xC0 // 0x80 + 64
#define EMOJI_ESCAPE_END 0xAD // 0x80 + 45
#define EMOJI_PAD_BYTE 0x7F // DEL, not typeable (key < 127 guard)
// ======== LARGE 12x12 SPRITES ========
@@ -208,82 +208,6 @@ 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,
};
static const uint8_t* const EMOJI_SPRITES_LG[] PROGMEM = {
emoji_lg_joy, emoji_lg_thumbsup, emoji_lg_frown,
@@ -296,11 +220,6 @@ static const uint8_t* const EMOJI_SPRITES_LG[] PROGMEM = {
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_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,
};
// ======== SMALL 10x10 SPRITES ========
@@ -443,82 +362,6 @@ 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,
};
static const uint8_t* const EMOJI_SPRITES_SM[] PROGMEM = {
emoji_sm_joy, emoji_sm_thumbsup, emoji_sm_frown,
@@ -531,11 +374,6 @@ static const uint8_t* const EMOJI_SPRITES_SM[] PROGMEM = {
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_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,
};
// ---- Codepoint lookup for UTF-8 conversion ----
@@ -588,37 +426,10 @@ static const EmojiCodepoint EMOJI_CODEPOINTS[EMOJI_COUNT] = {
{ 0x1F39B, 0x0000, 0xAB }, // control_knobs
{ 0x1F351, 0x0000, 0xAC }, // peach
{ 0x1F3CE, 0x0000, 0xAD }, // racing_car
{ 0x1F42D, 0x0000, 0xAE }, // mouse
{ 0x1F344, 0x0000, 0xAF }, // mushroom
{ 0x2623, 0x0000, 0xB0 }, // biohazard
{ 0x1F43C, 0x0000, 0xB1 }, // panda
{ 0x1F4A2, 0x0000, 0xB2 }, // anger
{ 0x1F432, 0x0000, 0xB3 }, // dragon_face
{ 0x1F4DF, 0x0000, 0xB4 }, // pager
{ 0x1F41D, 0x0000, 0xB5 }, // bee
{ 0x1F4A1, 0x0000, 0xB6 }, // bulb
{ 0x1F431, 0x0000, 0xB7 }, // cat
{ 0x269C, 0x0000, 0xB8 }, // fleur
{ 0x1F314, 0x0000, 0xB9 }, // moon
{ 0x2615, 0x0000, 0xBA }, // coffee
{ 0x1F9B7, 0x0000, 0xBB }, // tooth
{ 0x1F968, 0x0000, 0xBC }, // pretzel
{ 0x1F9EE, 0x0000, 0xBD }, // abacus
{ 0x1F5FF, 0x0000, 0xBE }, // moai
{ 0x1F481, 0x0000, 0xBF }, // tipping
{ 0x1F994, 0x0000, 0xC0 }, // hedgehog
};
// ---- 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, 0xA5 }, // 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; }
@@ -672,18 +483,6 @@ 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;

View File

@@ -1,886 +0,0 @@
#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),
_tileFound(false)
{
// Allocate marker array in PSRAM at construction (~20KB)
// so addMarker() works before enter() is called
_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");
}
}
~MapScreen() {
if (_pngBuf) { free(_pngBuf); _pngBuf = 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) {
if (!_markers || _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 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");
}
}
// 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;
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)
};
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 || !_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;
// 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) 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;
uint16_t lineBuf[MAP_TILE_SIZE];
if (lineWidth > MAP_TILE_SIZE) lineWidth = MAP_TILE_SIZE;
ctx->png->getLineAsRGB565(pDraw, 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 = 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++;
}
}
}
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);
}
};

View File

@@ -17,10 +17,6 @@ ModemManager modemManager;
#define AT_BUF_SIZE 512
static char _atBuf[AT_BUF_SIZE];
// Config file paths
#define MODEM_CONFIG_FILE "/sms/modem.cfg"
#define APN_CONFIG_FILE "/sms/apn.cfg"
// ---------------------------------------------------------------------------
// Public API - SMS (unchanged)
// ---------------------------------------------------------------------------
@@ -33,15 +29,7 @@ void ModemManager::begin() {
_operator[0] = '\0';
_callPhone[0] = '\0';
_callStartTime = 0;
_ringtoneEnabled = false;
_ringing = false;
_nextRingTone = 0;
_toneActive = false;
_urcPos = 0;
_imei[0] = '\0';
_imsi[0] = '\0';
_apn[0] = '\0';
strcpy(_apnSource, "none");
// Create FreeRTOS primitives
_sendQueue = xQueueCreate(MODEM_SEND_QUEUE_SIZE, sizeof(SMSOutgoing));
@@ -204,6 +192,8 @@ const char* ModemManager::stateToString(ModemState s) {
// Persistent modem enable/disable config
// ---------------------------------------------------------------------------
#define MODEM_CONFIG_FILE "/sms/modem.cfg"
bool ModemManager::loadEnabledConfig() {
File f = SD.open(MODEM_CONFIG_FILE, FILE_READ);
if (!f) {
@@ -227,112 +217,6 @@ void ModemManager::saveEnabledConfig(bool enabled) {
}
}
// ---------------------------------------------------------------------------
// APN Configuration
// ---------------------------------------------------------------------------
void ModemManager::setAPN(const char* apn) {
strncpy(_apn, apn, sizeof(_apn) - 1);
_apn[sizeof(_apn) - 1] = '\0';
strcpy(_apnSource, "user");
saveAPNConfig(apn);
MESH_DEBUG_PRINTLN("[Modem] APN set by user: %s", _apn);
}
bool ModemManager::loadAPNConfig(char* apnOut, int maxLen) {
File f = SD.open(APN_CONFIG_FILE, FILE_READ);
if (!f) { return false; }
String line = f.readStringUntil('\n');
f.close();
line.trim();
if (line.length() == 0) return false;
strncpy(apnOut, line.c_str(), maxLen - 1);
apnOut[maxLen - 1] = '\0';
return true;
}
void ModemManager::saveAPNConfig(const char* apn) {
if (!SD.exists("/sms")) SD.mkdir("/sms");
File f = SD.open(APN_CONFIG_FILE, FILE_WRITE);
if (f) {
f.println(apn);
f.close();
Serial.printf("[Modem] APN config saved: %s\n", apn);
}
}
// ---------------------------------------------------------------------------
// APN Resolution — called during init after network registration
//
// Priority:
// 1. User-configured APN (from /sms/apn.cfg)
// 2. Network-provisioned APN (AT+CGDCONT? — modem already has one)
// 3. Auto-detected from IMSI via embedded ApnDatabase
// 4. Blank (some carriers work with empty APN)
// ---------------------------------------------------------------------------
void ModemManager::resolveAPN() {
// 1. Check for user-configured APN on SD card
char userApn[64];
if (loadAPNConfig(userApn, sizeof(userApn))) {
strncpy(_apn, userApn, sizeof(_apn) - 1);
strcpy(_apnSource, "user");
MESH_DEBUG_PRINTLN("[Modem] APN from user config: %s", _apn);
// Apply to modem
char cmd[80];
snprintf(cmd, sizeof(cmd), "AT+CGDCONT=1,\"IP\",\"%s\"", _apn);
sendAT(cmd, "OK", 3000);
return;
}
// 2. Check if modem already has a network-provisioned APN
if (sendAT("AT+CGDCONT?", "OK", 3000)) {
// Response: +CGDCONT: 1,"IP","telstra.internet",,0,0
char* p = strstr(_atBuf, "+CGDCONT:");
if (p) {
char* q1 = strchr(p, '"'); // first quote (before IP)
if (q1) q1 = strchr(q1 + 1, '"'); // close quote of IP
if (q1) q1 = strchr(q1 + 1, '"'); // open quote of APN
if (q1) {
q1++;
char* q2 = strchr(q1, '"');
if (q2 && q2 > q1) {
int len = q2 - q1;
if (len > 0 && len < (int)sizeof(_apn)) {
memcpy(_apn, q1, len);
_apn[len] = '\0';
strcpy(_apnSource, "network");
MESH_DEBUG_PRINTLN("[Modem] APN from network/modem: %s", _apn);
return;
}
}
}
}
}
// 3. Auto-detect from IMSI using embedded database
if (_imsi[0]) {
const ApnEntry* entry = apnLookupFromIMSI(_imsi);
if (entry) {
strncpy(_apn, entry->apn, sizeof(_apn) - 1);
strcpy(_apnSource, "auto");
MESH_DEBUG_PRINTLN("[Modem] APN auto-detected: %s (%s)", _apn, entry->carrier);
// Apply to modem
char cmd[80];
snprintf(cmd, sizeof(cmd), "AT+CGDCONT=1,\"IP\",\"%s\"", _apn);
sendAT(cmd, "OK", 3000);
return;
}
}
// 4. No APN found — leave blank
_apn[0] = '\0';
strcpy(_apnSource, "none");
MESH_DEBUG_PRINTLN("[Modem] APN: none detected (IMSI=%s)", _imsi[0] ? _imsi : "unknown");
}
// ---------------------------------------------------------------------------
// URC (Unsolicited Result Code) Handling
// ---------------------------------------------------------------------------
@@ -609,46 +493,6 @@ bool ModemManager::doSetVolume(uint8_t level) {
return ok;
}
// ---------------------------------------------------------------------------
// Incoming call ringtone — tone bursts via AT+SIMTONE on modem speaker
// Pattern: 400ms tone → 1200ms silence → repeat
// ---------------------------------------------------------------------------
void ModemManager::handleRingtone() {
bool nowRinging = (_state == ModemState::RINGING_IN);
if (nowRinging && !_ringing) {
// Just started ringing
_ringing = true;
_nextRingTone = 0; // Play first burst immediately
_toneActive = false;
} else if (!nowRinging && _ringing) {
// Ringing stopped (answered, rejected, missed)
_ringing = false;
if (_toneActive) {
sendAT("AT+SIMTONE=0", "OK", 500);
_toneActive = false;
}
return;
}
if (!_ringing || !_ringtoneEnabled) return;
unsigned long now = millis();
if (now < _nextRingTone) return;
if (!_toneActive) {
// Play tone burst: 1000 Hz, level 5000 (of 50-25500), 400ms duration
sendAT("AT+SIMTONE=1,1000,5000,400", "OK", 500);
_toneActive = true;
_nextRingTone = now + 400; // Tone plays for 400ms
} else {
// Tone just finished — gap before next burst
_toneActive = false;
_nextRingTone = now + 1200; // 1.2s silence (classic ring cadence)
}
}
// ---------------------------------------------------------------------------
// FreeRTOS Task
// ---------------------------------------------------------------------------
@@ -693,28 +537,6 @@ restart:
// Disable echo
sendAT("ATE0", "OK");
// --- Query device identity ---
// IMEI (International Mobile Equipment Identity)
if (sendAT("AT+GSN", "OK", 3000)) {
// Response is just the IMEI number on its own line
char* p = _atBuf;
while (*p && !isdigit(*p)) p++; // skip to first digit
int i = 0;
while (isdigit(p[i]) && i < 19) { _imei[i] = p[i]; i++; }
_imei[i] = '\0';
MESH_DEBUG_PRINTLN("[Modem] IMEI: %s", _imei);
}
// IMSI (International Mobile Subscriber Identity) — for APN auto-detection
if (sendAT("AT+CIMI", "OK", 3000)) {
char* p = _atBuf;
while (*p && !isdigit(*p)) p++;
int i = 0;
while (isdigit(p[i]) && i < 19) { _imsi[i] = p[i]; i++; }
_imsi[i] = '\0';
MESH_DEBUG_PRINTLN("[Modem] IMSI: %s", _imsi);
}
// Set SMS text mode
sendAT("AT+CMGF=1", "OK");
@@ -767,10 +589,6 @@ restart:
}
// Query operator name
// AT+COPS=3,0 sets the format to "long alphanumeric" so AT+COPS?
// returns "Optus" instead of "50502"
sendAT("AT+COPS=3,0", "OK", 2000);
if (sendAT("AT+COPS?", "OK", 5000)) {
char* p = strchr(_atBuf, '"');
if (p) {
@@ -786,28 +604,9 @@ restart:
}
}
// If operator is still numeric (all digits), look up friendly name from IMSI
if (_operator[0] && isdigit(_operator[0])) {
bool allDigits = true;
for (int i = 0; _operator[i]; i++) {
if (!isdigit(_operator[i])) { allDigits = false; break; }
}
if (allDigits && _imsi[0]) {
const ApnEntry* entry = apnLookupFromIMSI(_imsi);
if (entry && entry->carrier) {
strncpy(_operator, entry->carrier, sizeof(_operator) - 1);
_operator[sizeof(_operator) - 1] = '\0';
MESH_DEBUG_PRINTLN("[Modem] operator (from IMSI lookup): %s", _operator);
}
}
}
// Initial signal query
pollCSQ();
// Resolve APN (user config → network provisioned → IMSI auto-detect)
resolveAPN();
// Sync ESP32 system clock from modem network time
bool clockSet = false;
for (int attempt = 0; attempt < 5 && !clockSet; attempt++) {
@@ -854,8 +653,7 @@ restart:
sendAT("AT+CMGD=1,4", "OK", 5000);
_state = ModemState::READY;
MESH_DEBUG_PRINTLN("[Modem] READY (CSQ=%d, operator=%s, APN=%s [%s], IMEI=%s)",
_csq, _operator, _apn[0] ? _apn : "(none)", _apnSource, _imei);
MESH_DEBUG_PRINTLN("[Modem] READY (CSQ=%d, operator=%s)", _csq, _operator);
// ---- Phase 4: Main loop ----
unsigned long lastCSQPoll = 0;
@@ -873,11 +671,6 @@ restart:
// ================================================================
drainURCs();
// ================================================================
// Step 1b: Ringtone — play tone bursts while incoming call rings
// ================================================================
handleRingtone();
// ================================================================
// Step 2: Process call commands from main loop
// ================================================================
@@ -922,10 +715,8 @@ restart:
// Primary detection is via "VOICE CALL: BEGIN" URC (handled by
// drainURCs/processURCLine above). CLCC polling is a safety net
// in case the URC is missed or delayed.
// Skip when paused to avoid Core 0 contention with WiFi TLS.
// ================================================================
if (!_paused &&
_state == ModemState::DIALING &&
if (_state == ModemState::DIALING &&
millis() - lastCLCCPoll > CLCC_POLL_INTERVAL) {
if (sendAT("AT+CLCC", "OK", 2000)) {
// +CLCC: 1,0,0,0,0,"number",129 — stat field:
@@ -956,11 +747,8 @@ restart:
// ================================================================
// Step 4: SMS and signal polling (only when not in a call)
// Skip when paused to avoid Core 0 contention with WiFi/TLS.
// The modem task's sendAT() calls (AT+CMGL 5s, AT+CSQ 2s) do
// tight UART poll loops that disrupt WiFi packet timing.
// ================================================================
if (!_paused && !isCallActive()) {
if (!isCallActive()) {
// Check for outgoing SMS in queue
SMSOutgoing outMsg;
if (xQueueReceive(_sendQueue, &outMsg, 0) == pdTRUE) {
@@ -978,7 +766,7 @@ restart:
}
// Periodic signal strength update (always, even during calls)
if (!_paused && millis() - lastCSQPoll > CSQ_POLL_INTERVAL) {
if (millis() - lastCSQPoll > CSQ_POLL_INTERVAL) {
// Only poll CSQ if not actively in a call (avoid interrupting audio)
if (!isCallActive()) {
pollCSQ();

View File

@@ -22,7 +22,6 @@
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include "variant.h"
#include "ApnDatabase.h"
// ---------------------------------------------------------------------------
// Modem pins (from variant.h, always defined for reference)
@@ -142,10 +141,6 @@ public:
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
@@ -163,28 +158,6 @@ public:
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)
@@ -194,25 +167,12 @@ public:
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
@@ -242,9 +202,6 @@ private:
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();
@@ -252,7 +209,6 @@ private:
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);

View File

@@ -1,34 +0,0 @@
#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

File diff suppressed because it is too large Load Diff

View File

@@ -10,39 +10,42 @@
#include "ModemManager.h"
#endif
#ifdef MECK_WIFI_COMPANION
#include <WiFi.h>
#include <SD.h>
#endif
// Forward declarations
class UITask;
class MyMesh;
extern MyMesh the_mesh;
// ---------------------------------------------------------------------------
// Auto-add config bitmask (mirrored from MyMesh.cpp for UI access)
// Radio presets
// ---------------------------------------------------------------------------
#define AUTO_ADD_OVERWRITE_OLDEST (1 << 0) // 0x01 - overwrite oldest non-favourite when full
#define AUTO_ADD_CHAT (1 << 1) // 0x02 - auto-add Chat (Companion) (ADV_TYPE_CHAT)
#define AUTO_ADD_REPEATER (1 << 2) // 0x04 - auto-add Repeater (ADV_TYPE_REPEATER)
#define AUTO_ADD_ROOM_SERVER (1 << 3) // 0x08 - auto-add Room Server (ADV_TYPE_ROOM)
#define AUTO_ADD_SENSOR (1 << 4) // 0x10 - auto-add Sensor (ADV_TYPE_SENSOR)
struct RadioPreset {
const char* name;
float freq;
float bw;
uint8_t sf;
uint8_t cr;
uint8_t tx_power;
};
// All type bits combined (excludes overwrite flag)
#define AUTO_ADD_ALL_TYPES (AUTO_ADD_CHAT | AUTO_ADD_REPEATER | \
AUTO_ADD_ROOM_SERVER | AUTO_ADD_SENSOR)
// Contact mode indices for picker
#define CONTACT_MODE_AUTO_ALL 0 // Add all contacts automatically
#define CONTACT_MODE_CUSTOM 1 // Per-type toggles
#define CONTACT_MODE_MANUAL 2 // No auto-add, companion app only
#define CONTACT_MODE_COUNT 3
// ---------------------------------------------------------------------------
// Radio presets (shared with Serial CLI in MyMesh.cpp)
// ---------------------------------------------------------------------------
#include "RadioPresets.h"
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]))
// ---------------------------------------------------------------------------
// Settings row types
@@ -57,33 +60,15 @@ enum SettingsRowType : uint8_t {
ROW_TX_POWER, // TX power (1-20 dBm)
ROW_UTC_OFFSET, // UTC offset (-12 to +14)
ROW_MSG_NOTIFY, // Keyboard flash on new msg toggle
ROW_PATH_HASH_SIZE, // Path hash size (1, 2, or 3 bytes per hop)
#ifdef MECK_WIFI_COMPANION
ROW_WIFI_SETUP, // WiFi SSID/password configuration
ROW_WIFI_TOGGLE, // WiFi radio on/off toggle
#endif
#ifdef HAS_4G_MODEM
ROW_MODEM_TOGGLE, // 4G modem enable/disable toggle (4G builds only)
// ROW_RINGTONE, // Incoming call ringtone toggle (4G builds only)
#endif
ROW_CONTACT_HEADER, // "--- Contacts ---" separator
ROW_CONTACT_MODE, // Contact auto-add mode picker (Auto All / Custom / Manual)
ROW_AUTOADD_CHAT, // Toggle: auto-add Chat clients
ROW_AUTOADD_REPEATER,// Toggle: auto-add Repeaters
ROW_AUTOADD_ROOM, // Toggle: auto-add Room Servers
ROW_AUTOADD_SENSOR, // Toggle: auto-add Sensors
ROW_AUTOADD_OVERWRITE, // Toggle: overwrite oldest non-favourite when full
ROW_CH_HEADER, // "--- Channels ---" separator
ROW_CHANNEL, // A channel entry (dynamic, index stored separately)
ROW_ADD_CHANNEL, // "+ Add Hashtag Channel"
ROW_INFO_HEADER, // "--- Info ---" separator
ROW_PUB_KEY, // Public key display
ROW_FIRMWARE, // Firmware version
#ifdef HAS_4G_MODEM
ROW_IMEI, // IMEI display (read-only)
ROW_OPERATOR_INFO, // Carrier/operator display (read-only)
ROW_APN, // APN setting (editable)
#endif
};
// ---------------------------------------------------------------------------
@@ -92,24 +77,13 @@ enum SettingsRowType : uint8_t {
enum EditMode : uint8_t {
EDIT_NONE, // Just browsing
EDIT_TEXT, // Typing into a text buffer (name, channel name)
EDIT_PICKER, // A/D cycles options (radio preset, contact mode)
EDIT_PICKER, // A/D cycles options (radio preset)
EDIT_NUMBER, // W/S adjusts value (freq, BW, SF, CR, TX, UTC)
EDIT_CONFIRM, // Confirmation dialog (delete channel, apply radio)
#ifdef MECK_WIFI_COMPANION
EDIT_WIFI, // WiFi scan/select/password flow
#endif
};
// Max rows in the settings list (increased for contact sub-toggles + WiFi)
#if defined(HAS_4G_MODEM) && defined(MECK_WIFI_COMPANION)
#define SETTINGS_MAX_ROWS 56 // Extra rows for IMEI, Carrier, APN, contacts, WiFi
#elif defined(HAS_4G_MODEM)
#define SETTINGS_MAX_ROWS 54 // Extra rows for IMEI, Carrier, APN + contacts
#elif defined(MECK_WIFI_COMPANION)
#define SETTINGS_MAX_ROWS 50 // Extra rows for contacts + WiFi
#else
#define SETTINGS_MAX_ROWS 48 // Contacts section
#endif
// Max rows in the settings list
#define SETTINGS_MAX_ROWS 40
#define SETTINGS_TEXT_BUF 33 // 32 chars + null
class SettingsScreen : public UIScreen {
@@ -134,7 +108,7 @@ private:
EditMode _editMode;
char _editBuf[SETTINGS_TEXT_BUF];
int _editPos;
int _editPickerIdx; // for preset picker / contact mode picker
int _editPickerIdx; // for preset picker
float _editFloat; // for freq/BW editing
int _editInt; // for SF/CR/TX/UTC editing
int _confirmAction; // 0=none, 1=delete channel, 2=apply radio
@@ -150,75 +124,6 @@ private:
bool _modemEnabled;
#endif
#ifdef MECK_WIFI_COMPANION
// WiFi setup sub-screen state
enum WifiSetupPhase : uint8_t {
WIFI_PHASE_IDLE,
WIFI_PHASE_SCANNING,
WIFI_PHASE_SELECT, // W/S to pick SSID, Enter to select
WIFI_PHASE_PASSWORD, // Type password, Enter to connect
WIFI_PHASE_CONNECTING,
};
WifiSetupPhase _wifiPhase;
String _wifiSSIDs[10];
int _wifiSSIDCount;
int _wifiSSIDSelected;
char _wifiPassBuf[64];
int _wifiPassLen;
unsigned long _wifiFormLastChar; // For brief password reveal
#endif
// ---------------------------------------------------------------------------
// Contact mode helpers
// ---------------------------------------------------------------------------
// Determine current contact mode from prefs
int getContactMode() const {
if ((_prefs->manual_add_contacts & 1) == 0) {
return CONTACT_MODE_AUTO_ALL;
}
// manual_add_contacts bit 0 is set — check if any type bits are enabled
if ((_prefs->autoadd_config & AUTO_ADD_ALL_TYPES) != 0) {
return CONTACT_MODE_CUSTOM;
}
return CONTACT_MODE_MANUAL;
}
// Get display label for a contact mode
static const char* contactModeLabel(int mode) {
switch (mode) {
case CONTACT_MODE_AUTO_ALL: return "Auto All";
case CONTACT_MODE_CUSTOM: return "Custom";
case CONTACT_MODE_MANUAL: return "Manual Only";
default: return "?";
}
}
// Apply a contact mode selection from picker
void applyContactMode(int mode) {
switch (mode) {
case CONTACT_MODE_AUTO_ALL:
_prefs->manual_add_contacts &= ~1; // clear bit 0 → auto all
break;
case CONTACT_MODE_CUSTOM:
_prefs->manual_add_contacts |= 1; // set bit 0 → selective
// If no type bits are set, default to all types enabled
if ((_prefs->autoadd_config & AUTO_ADD_ALL_TYPES) == 0) {
_prefs->autoadd_config |= AUTO_ADD_ALL_TYPES;
}
break;
case CONTACT_MODE_MANUAL:
_prefs->manual_add_contacts |= 1; // set bit 0 → selective
_prefs->autoadd_config &= ~AUTO_ADD_ALL_TYPES; // clear all type bits
// Note: keeps AUTO_ADD_OVERWRITE_OLDEST bit unchanged
break;
}
the_mesh.savePrefs();
rebuildRows(); // show/hide sub-toggles
Serial.printf("Settings: Contact mode = %s (manual=%d, autoadd=0x%02X)\n",
contactModeLabel(mode), _prefs->manual_add_contacts, _prefs->autoadd_config);
}
// ---------------------------------------------------------------------------
// Row table management
// ---------------------------------------------------------------------------
@@ -235,30 +140,9 @@ private:
addRow(ROW_TX_POWER);
addRow(ROW_UTC_OFFSET);
addRow(ROW_MSG_NOTIFY);
addRow(ROW_PATH_HASH_SIZE);
#ifdef MECK_WIFI_COMPANION
addRow(ROW_WIFI_SETUP);
addRow(ROW_WIFI_TOGGLE);
#endif
#ifdef HAS_4G_MODEM
addRow(ROW_MODEM_TOGGLE);
// addRow(ROW_RINGTONE);
#endif
// --- Contacts section ---
addRow(ROW_CONTACT_HEADER);
addRow(ROW_CONTACT_MODE);
// Show per-type sub-toggles only in Custom mode
if (getContactMode() == CONTACT_MODE_CUSTOM) {
addRow(ROW_AUTOADD_CHAT);
addRow(ROW_AUTOADD_REPEATER);
addRow(ROW_AUTOADD_ROOM);
addRow(ROW_AUTOADD_SENSOR);
addRow(ROW_AUTOADD_OVERWRITE);
}
// --- Channels section ---
addRow(ROW_CH_HEADER);
// Enumerate current channels
@@ -276,12 +160,6 @@ private:
addRow(ROW_PUB_KEY);
addRow(ROW_FIRMWARE);
#ifdef HAS_4G_MODEM
addRow(ROW_IMEI);
addRow(ROW_OPERATOR_INFO);
addRow(ROW_APN);
#endif
// Clamp cursor
if (_cursor >= _numRows) _cursor = _numRows - 1;
if (_cursor < 0) _cursor = 0;
@@ -299,11 +177,7 @@ private:
bool isSelectable(int idx) const {
if (idx < 0 || idx >= _numRows) return false;
SettingsRowType t = _rows[idx].type;
return t != ROW_CH_HEADER && t != ROW_INFO_HEADER && t != ROW_CONTACT_HEADER
#ifdef HAS_4G_MODEM
&& t != ROW_IMEI && t != ROW_OPERATOR_INFO
#endif
;
return t != ROW_CH_HEADER && t != ROW_INFO_HEADER;
}
void skipNonSelectable(int dir) {
@@ -433,14 +307,6 @@ public:
#ifdef HAS_4G_MODEM
_modemEnabled = ModemManager::loadEnabledConfig();
#endif
#ifdef MECK_WIFI_COMPANION
_wifiPhase = WIFI_PHASE_IDLE;
_wifiSSIDCount = 0;
_wifiSSIDSelected = 0;
_wifiPassLen = 0;
memset(_wifiPassBuf, 0, sizeof(_wifiPassBuf));
_wifiFormLastChar = 0;
#endif
rebuildRows();
}
@@ -456,64 +322,6 @@ public:
bool isEditing() const { return _editMode != EDIT_NONE; }
bool hasRadioChanges() const { return _radioChanged; }
// ---------------------------------------------------------------------------
// WiFi scan helpers
// ---------------------------------------------------------------------------
#ifdef MECK_WIFI_COMPANION
// Perform a blocking WiFi scan. Populates _wifiSSIDs/_wifiSSIDCount and
// advances _wifiPhase to SELECT (even on zero results, so the overlay
// stays visible and the user can rescan with 'r').
void performWifiScan() {
_wifiPhase = WIFI_PHASE_SCANNING;
_wifiSSIDCount = 0;
_wifiSSIDSelected = 0;
// Disconnect any active WiFi connection first — the ESP32 driver
// returns -2 (WIFI_SCAN_FAILED) if the radio is busy with an
// existing connection or the TCP companion server socket.
WiFi.disconnect(false); // false = don't turn off WiFi radio
delay(100); // let the driver settle
WiFi.mode(WIFI_STA);
// 500ms per-channel dwell helps detect phone hotspots that are slow
// to respond to probe requests (default 300ms often misses them).
int n = WiFi.scanNetworks(false, false, false, 500);
Serial.printf("Settings: WiFi scan found %d networks\n", n);
if (n > 0) {
_wifiSSIDCount = min(n, 10);
for (int si = 0; si < _wifiSSIDCount; si++) {
_wifiSSIDs[si] = WiFi.SSID(si);
Serial.printf(" [%d] %s (RSSI %d)\n", si,
_wifiSSIDs[si].c_str(), WiFi.RSSI(si));
}
} else if (n < 0) {
Serial.printf("Settings: WiFi scan error %d\n", n);
}
WiFi.scanDelete();
_wifiPhase = WIFI_PHASE_SELECT; // always show overlay (even if 0)
}
// After WiFi setup exits (connect success or user quit), try to
// reconnect to saved credentials so the companion TCP server works.
void wifiReconnectSaved() {
File f = SD.open("/web/wifi.cfg", FILE_READ);
if (f) {
String ssid = f.readStringUntil('\n'); ssid.trim();
String pass = f.readStringUntil('\n'); pass.trim();
f.close();
digitalWrite(SDCARD_CS, HIGH);
if (ssid.length() > 0) {
Serial.printf("Settings: Reconnecting to saved WiFi '%s'\n", ssid.c_str());
WiFi.begin(ssid.c_str(), pass.c_str());
}
} else {
digitalWrite(SDCARD_CS, HIGH);
}
}
#endif
// ---------------------------------------------------------------------------
// Edit mode starters
// ---------------------------------------------------------------------------
@@ -683,93 +491,14 @@ public:
display.print(tmp);
break;
case ROW_PATH_HASH_SIZE:
if (editing && _editMode == EDIT_NUMBER) {
snprintf(tmp, sizeof(tmp), "Path Hash Size: %d-byte <W/S>", _editInt);
} else {
snprintf(tmp, sizeof(tmp), "Path Hash Size: %d-byte", _prefs->path_hash_mode + 1);
}
display.print(tmp);
break;
#ifdef MECK_WIFI_COMPANION
case ROW_WIFI_SETUP:
if (WiFi.status() == WL_CONNECTED) {
snprintf(tmp, sizeof(tmp), "WiFi: %s", WiFi.SSID().c_str());
} else {
strcpy(tmp, "WiFi: (not connected)");
}
display.print(tmp);
break;
case ROW_WIFI_TOGGLE:
snprintf(tmp, sizeof(tmp), "WiFi Radio: %s",
(WiFi.getMode() != WIFI_OFF) ? "ON" : "OFF");
display.print(tmp);
break;
#endif
#ifdef HAS_4G_MODEM
case ROW_MODEM_TOGGLE:
snprintf(tmp, sizeof(tmp), "4G Modem: %s",
_modemEnabled ? "ON" : "OFF");
display.print(tmp);
break;
//case ROW_RINGTONE:
// snprintf(tmp, sizeof(tmp), "Incoming Call Ring: %s",
// _prefs->ringtone_enabled ? "ON" : "OFF");
// display.print(tmp);
// break;
#endif
// --- Contacts section ---
case ROW_CONTACT_HEADER:
display.setColor(DisplayDriver::YELLOW);
display.print("--- Contacts ---");
break;
case ROW_CONTACT_MODE:
if (editing && _editMode == EDIT_PICKER) {
snprintf(tmp, sizeof(tmp), "< Add Mode: %s >",
contactModeLabel(_editPickerIdx));
} else {
snprintf(tmp, sizeof(tmp), "Add Mode: %s",
contactModeLabel(getContactMode()));
}
display.print(tmp);
break;
case ROW_AUTOADD_CHAT:
snprintf(tmp, sizeof(tmp), " Chat: %s",
(_prefs->autoadd_config & AUTO_ADD_CHAT) ? "ON" : "OFF");
display.print(tmp);
break;
case ROW_AUTOADD_REPEATER:
snprintf(tmp, sizeof(tmp), " Repeater: %s",
(_prefs->autoadd_config & AUTO_ADD_REPEATER) ? "ON" : "OFF");
display.print(tmp);
break;
case ROW_AUTOADD_ROOM:
snprintf(tmp, sizeof(tmp), " Room Server: %s",
(_prefs->autoadd_config & AUTO_ADD_ROOM_SERVER) ? "ON" : "OFF");
display.print(tmp);
break;
case ROW_AUTOADD_SENSOR:
snprintf(tmp, sizeof(tmp), " Sensor: %s",
(_prefs->autoadd_config & AUTO_ADD_SENSOR) ? "ON" : "OFF");
display.print(tmp);
break;
case ROW_AUTOADD_OVERWRITE:
snprintf(tmp, sizeof(tmp), " Overwrite Oldest: %s",
(_prefs->autoadd_config & AUTO_ADD_OVERWRITE_OLDEST) ? "ON" : "OFF");
display.print(tmp);
break;
// --- Channels section ---
case ROW_CH_HEADER:
display.setColor(DisplayDriver::YELLOW);
display.print("--- Channels ---");
@@ -819,7 +548,7 @@ public:
// Show first 8 bytes of pub key as hex (16 chars)
char hexBuf[17];
mesh::Utils::toHex(hexBuf, the_mesh.self_id.pub_key, 8);
snprintf(tmp, sizeof(tmp), "Node ID: %s", hexBuf);
snprintf(tmp, sizeof(tmp), "ID: %s", hexBuf);
display.print(tmp);
break;
}
@@ -828,53 +557,6 @@ public:
snprintf(tmp, sizeof(tmp), "FW: %s", FIRMWARE_VERSION);
display.print(tmp);
break;
#ifdef HAS_4G_MODEM
case ROW_IMEI: {
const char* imei = modemManager.getIMEI();
snprintf(tmp, sizeof(tmp), "IMEI: %s", imei[0] ? imei : "(unavailable)");
display.print(tmp);
break;
}
case ROW_OPERATOR_INFO: {
const char* op = modemManager.getOperator();
int bars = modemManager.getSignalBars();
if (op[0]) {
// Show carrier name with signal bar count
snprintf(tmp, sizeof(tmp), "Carrier: %s (%d/5)", op, bars);
} else {
snprintf(tmp, sizeof(tmp), "Carrier: (searching)");
}
display.print(tmp);
break;
}
case ROW_APN: {
if (editing && _editMode == EDIT_TEXT) {
snprintf(tmp, sizeof(tmp), "APN: %s_", _editBuf);
} else {
const char* apn = modemManager.getAPN();
const char* src = modemManager.getAPNSource();
if (apn[0]) {
// Truncate APN to fit: "APN: " (5) + apn (max 28) + " [x]" (4) = ~37 chars
char apnShort[29];
strncpy(apnShort, apn, 28);
apnShort[28] = '\0';
// Abbreviate source: auto→A, network→N, user→U, none→?
char srcChar = '?';
if (strcmp(src, "auto") == 0) srcChar = 'A';
else if (strcmp(src, "network") == 0) srcChar = 'N';
else if (strcmp(src, "user") == 0) srcChar = 'U';
snprintf(tmp, sizeof(tmp), "APN: %s [%c]", apnShort, srcChar);
} else {
snprintf(tmp, sizeof(tmp), "APN: (none)");
}
}
display.print(tmp);
break;
}
#endif
}
y += lineHeight;
@@ -904,88 +586,6 @@ public:
display.setTextSize(1);
}
#ifdef MECK_WIFI_COMPANION
// === WiFi setup overlay ===
if (_editMode == EDIT_WIFI) {
int bx = 2, by = 14, bw = display.width() - 4;
int bh = display.height() - 28;
display.setColor(DisplayDriver::DARK);
display.fillRect(bx, by, bw, bh);
display.setColor(DisplayDriver::LIGHT);
display.drawRect(bx, by, bw, bh);
display.setTextSize(0);
int wy = by + 4;
if (_wifiPhase == WIFI_PHASE_SCANNING) {
display.drawTextCentered(display.width() / 2, wy, "Scanning for networks...");
} else if (_wifiPhase == WIFI_PHASE_SELECT) {
if (_wifiSSIDCount == 0) {
// No networks found — show message with rescan prompt
display.setCursor(bx + 4, wy);
display.print("No networks found.");
wy += 12;
display.setCursor(bx + 4, wy);
display.print("Check your hotspot is on");
wy += 8;
display.setCursor(bx + 4, wy);
display.print("and set to 2.4GHz.");
wy += 12;
display.setCursor(bx + 4, wy);
display.print("Press R or Enter to rescan.");
} else {
display.setCursor(bx + 4, wy);
display.print("Select network:");
wy += 10;
for (int wi = 0; wi < _wifiSSIDCount && wy < by + bh - 16; wi++) {
bool sel = (wi == _wifiSSIDSelected);
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(bx + 2, wy + 5, bw - 4, 8);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(bx + 4, wy);
char ssidLine[40];
if (sel) {
snprintf(ssidLine, sizeof(ssidLine), "> %.33s", _wifiSSIDs[wi].c_str());
} else {
snprintf(ssidLine, sizeof(ssidLine), " %.33s", _wifiSSIDs[wi].c_str());
}
display.print(ssidLine);
wy += 8;
}
}
} else if (_wifiPhase == WIFI_PHASE_PASSWORD) {
display.setCursor(bx + 4, wy);
snprintf(tmp, sizeof(tmp), "SSID: %s", _wifiSSIDs[_wifiSSIDSelected].c_str());
display.print(tmp);
wy += 12;
display.setCursor(bx + 4, wy);
display.print("Password:");
wy += 10;
display.setCursor(bx + 4, wy);
// Masked password with brief reveal of last char
char passBuf[66];
for (int pi = 0; pi < _wifiPassLen; pi++) passBuf[pi] = '*';
if (_wifiPassLen > 0 && _wifiFormLastChar > 0 &&
(millis() - _wifiFormLastChar) < 800) {
passBuf[_wifiPassLen - 1] = _wifiPassBuf[_wifiPassLen - 1];
}
passBuf[_wifiPassLen] = '_';
passBuf[_wifiPassLen + 1] = '\0';
display.print(passBuf);
} else if (_wifiPhase == WIFI_PHASE_CONNECTING) {
display.drawTextCentered(display.width() / 2, wy + 10, "Connecting...");
}
display.setTextSize(1);
}
#endif
// === Footer ===
int footerY = display.height() - 12;
display.drawRect(0, footerY - 2, display.width(), 1);
@@ -994,20 +594,6 @@ public:
if (_editMode == EDIT_TEXT) {
display.print("Type, Enter:Ok Q:Cancel");
#ifdef MECK_WIFI_COMPANION
} else if (_editMode == EDIT_WIFI) {
if (_wifiPhase == WIFI_PHASE_SELECT) {
if (_wifiSSIDCount == 0) {
display.print("R/Enter:Rescan Q:Back");
} else {
display.print("W/S:Pick Enter:Sel R:Rescan");
}
} else if (_wifiPhase == WIFI_PHASE_PASSWORD) {
display.print("Type, Enter:Connect Q:Bck");
} else {
display.print("Please wait...");
}
#endif
} else if (_editMode == EDIT_PICKER) {
display.print("A/D:Choose Enter:Ok");
} else if (_editMode == EDIT_NUMBER) {
@@ -1053,113 +639,6 @@ public:
return true; // consume all keys in confirm mode
}
#ifdef MECK_WIFI_COMPANION
// --- WiFi setup flow ---
if (_editMode == EDIT_WIFI) {
if (_wifiPhase == WIFI_PHASE_SELECT) {
if (c == 'w' || c == 'W') {
if (_wifiSSIDSelected > 0) _wifiSSIDSelected--;
return true;
}
if (c == 's' || c == 'S') {
if (_wifiSSIDSelected < _wifiSSIDCount - 1) _wifiSSIDSelected++;
return true;
}
if (c == 'r' || c == 'R') {
// Rescan — lets user toggle hotspot on then retry
performWifiScan();
return true;
}
if (c == '\r' || c == 13) {
if (_wifiSSIDCount == 0) {
// No networks — Enter rescans (same as R)
performWifiScan();
return true;
}
// Selected an SSID — move to password entry
_wifiPhase = WIFI_PHASE_PASSWORD;
_wifiPassLen = 0;
memset(_wifiPassBuf, 0, sizeof(_wifiPassBuf));
_wifiFormLastChar = 0;
return true;
}
if (c == 'q' || c == 'Q') {
_editMode = EDIT_NONE;
_wifiPhase = WIFI_PHASE_IDLE;
if (_onboarding) _onboarding = false; // Skip WiFi, finish onboarding
wifiReconnectSaved(); // Restore connection after scan disconnect
return true;
}
return true;
}
if (_wifiPhase == WIFI_PHASE_PASSWORD) {
if (c == '\r' || c == 13) {
// Attempt connection
_wifiPassBuf[_wifiPassLen] = '\0';
_wifiPhase = WIFI_PHASE_CONNECTING;
// Save credentials to SD first (so web reader can reuse them)
if (SD.exists("/web") || SD.mkdir("/web")) {
File f = SD.open("/web/wifi.cfg", FILE_WRITE);
if (f) {
f.println(_wifiSSIDs[_wifiSSIDSelected]);
f.println(_wifiPassBuf);
f.close();
}
digitalWrite(SDCARD_CS, HIGH);
}
WiFi.disconnect(false);
WiFi.begin(_wifiSSIDs[_wifiSSIDSelected].c_str(), _wifiPassBuf);
// Brief blocking wait — fine for e-ink (screen won't update during this anyway)
unsigned long timeout = millis() + 8000;
while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
delay(100);
}
if (WiFi.status() == WL_CONNECTED) {
Serial.printf("Settings: WiFi connected to %s, IP: %s\n",
_wifiSSIDs[_wifiSSIDSelected].c_str(),
WiFi.localIP().toString().c_str());
_editMode = EDIT_NONE;
_wifiPhase = WIFI_PHASE_IDLE;
if (_onboarding) _onboarding = false; // Finish onboarding
} else {
Serial.println("Settings: WiFi connection failed");
// Go back to SSID selection so user can retry
_wifiPhase = WIFI_PHASE_SELECT;
}
return true;
}
if (c == 'q' || c == 'Q') {
// Back to SSID selection
_wifiPhase = WIFI_PHASE_SELECT;
return true;
}
if (c == '\b') {
if (_wifiPassLen > 0) {
_wifiPassLen--;
_wifiPassBuf[_wifiPassLen] = '\0';
}
return true;
}
// Printable character
if (c >= 32 && c < 127 && _wifiPassLen < 63) {
_wifiPassBuf[_wifiPassLen++] = c;
_wifiPassBuf[_wifiPassLen] = '\0';
_wifiFormLastChar = millis();
return true;
}
return true;
}
// Scanning and connecting phases consume all keys
return true;
}
#endif
// --- Text editing mode ---
if (_editMode == EDIT_TEXT) {
if (c == '\r' || c == 13) {
@@ -1194,20 +673,6 @@ public:
}
_editMode = EDIT_NONE;
}
#ifdef HAS_4G_MODEM
else if (type == ROW_APN) {
// Save the edited APN (even if empty — clears user override)
if (_editPos > 0) {
modemManager.setAPN(_editBuf);
Serial.printf("Settings: APN set to '%s'\n", _editBuf);
} else {
// Empty APN: remove user override, revert to auto-detection
ModemManager::saveAPNConfig("");
Serial.println("Settings: APN cleared (will auto-detect on next boot)");
}
_editMode = EDIT_NONE;
}
#endif
return true;
}
if (c == 'q' || c == 'Q' || c == 27) {
@@ -1230,65 +695,34 @@ public:
return true; // consume all keys in text edit
}
// --- Picker mode (radio preset or contact mode) ---
// --- Picker mode (radio preset) ---
if (_editMode == EDIT_PICKER) {
SettingsRowType type = _rows[_cursor].type;
if (c == 'a' || c == 'A') {
if (type == ROW_CONTACT_MODE) {
_editPickerIdx--;
if (_editPickerIdx < 0) _editPickerIdx = CONTACT_MODE_COUNT - 1;
} else {
// Radio preset
_editPickerIdx--;
if (_editPickerIdx < 0) _editPickerIdx = (int)NUM_RADIO_PRESETS - 1;
}
_editPickerIdx--;
if (_editPickerIdx < 0) _editPickerIdx = (int)NUM_RADIO_PRESETS - 1;
return true;
}
if (c == 'd' || c == 'D') {
if (type == ROW_CONTACT_MODE) {
_editPickerIdx++;
if (_editPickerIdx >= CONTACT_MODE_COUNT) _editPickerIdx = 0;
} else {
// Radio preset
_editPickerIdx++;
if (_editPickerIdx >= (int)NUM_RADIO_PRESETS) _editPickerIdx = 0;
}
_editPickerIdx++;
if (_editPickerIdx >= (int)NUM_RADIO_PRESETS) _editPickerIdx = 0;
return true;
}
if (c == '\r' || c == 13) {
if (type == ROW_CONTACT_MODE) {
applyContactMode(_editPickerIdx);
_editMode = EDIT_NONE;
} else {
// Apply radio preset
if (_editPickerIdx >= 0 && _editPickerIdx < (int)NUM_RADIO_PRESETS) {
const RadioPreset& p = RADIO_PRESETS[_editPickerIdx];
_prefs->freq = p.freq;
_prefs->bw = p.bw;
_prefs->sf = p.sf;
_prefs->cr = p.cr;
_prefs->tx_power_dbm = p.tx_power;
_radioChanged = true;
}
_editMode = EDIT_NONE;
if (_onboarding) {
applyRadioParams();
#ifdef MECK_WIFI_COMPANION
// Move to WiFi setup before finishing onboarding
for (int r = 0; r < _numRows; r++) {
if (_rows[r].type == ROW_WIFI_SETUP) {
_cursor = r;
break;
}
}
// Auto-launch the WiFi scan
_editMode = EDIT_WIFI;
performWifiScan();
#else
_onboarding = false;
#endif
}
// Apply preset
if (_editPickerIdx >= 0 && _editPickerIdx < (int)NUM_RADIO_PRESETS) {
const RadioPreset& p = RADIO_PRESETS[_editPickerIdx];
_prefs->freq = p.freq;
_prefs->bw = p.bw;
_prefs->sf = p.sf;
_prefs->cr = p.cr;
_prefs->tx_power_dbm = p.tx_power;
_radioChanged = true;
}
_editMode = EDIT_NONE;
if (_onboarding) {
// Apply and finish onboarding
applyRadioParams();
_onboarding = false;
}
return true;
}
@@ -1317,7 +751,6 @@ public:
case ROW_CR: if (_editInt < 8) _editInt++; break;
case ROW_TX_POWER: if (_editInt < MAX_LORA_TX_POWER) _editInt++; break;
case ROW_UTC_OFFSET: if (_editInt < 14) _editInt++; break;
case ROW_PATH_HASH_SIZE: if (_editInt < 3) _editInt++; break;
default: break;
}
return true;
@@ -1334,7 +767,6 @@ public:
case ROW_CR: if (_editInt > 5) _editInt--; break;
case ROW_TX_POWER: if (_editInt > 1) _editInt--; break;
case ROW_UTC_OFFSET: if (_editInt > -12) _editInt--; break;
case ROW_PATH_HASH_SIZE: if (_editInt > 1) _editInt--; break;
default: break;
}
return true;
@@ -1362,10 +794,6 @@ public:
_prefs->utc_offset_hours = (int8_t)constrain(_editInt, -12, 14);
the_mesh.savePrefs();
break;
case ROW_PATH_HASH_SIZE:
_prefs->path_hash_mode = (uint8_t)constrain(_editInt - 1, 0, 2); // display 1-3, store 0-2
the_mesh.savePrefs();
break;
default: break;
}
_editMode = EDIT_NONE;
@@ -1436,52 +864,6 @@ public:
Serial.printf("Settings: Msg flash notify = %s\n",
_prefs->kb_flash_notify ? "ON" : "OFF");
break;
case ROW_PATH_HASH_SIZE:
startEditInt(_prefs->path_hash_mode + 1); // display as 1-3
break;
#ifdef MECK_WIFI_COMPANION
case ROW_WIFI_SETUP: {
// Launch WiFi scan → select → password → connect flow
_editMode = EDIT_WIFI;
performWifiScan();
break;
}
case ROW_WIFI_TOGGLE:
if (WiFi.getMode() != WIFI_OFF) {
// Turn WiFi OFF
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
Serial.println("Settings: WiFi radio OFF");
} else {
// Turn WiFi ON — reconnect using saved credentials
WiFi.mode(WIFI_STA);
if (SD.exists("/web/wifi.cfg")) {
File f = SD.open("/web/wifi.cfg", FILE_READ);
if (f) {
String ssid = f.readStringUntil('\n'); ssid.trim();
String pass = f.readStringUntil('\n'); pass.trim();
f.close();
digitalWrite(SDCARD_CS, HIGH);
if (ssid.length() > 0) {
WiFi.begin(ssid.c_str(), pass.c_str());
unsigned long timeout = millis() + 8000;
while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
delay(100);
}
if (WiFi.status() == WL_CONNECTED) {
Serial.printf("Settings: WiFi ON, connected to %s\n", ssid.c_str());
} else {
Serial.println("Settings: WiFi ON, but connection failed");
}
}
} else {
digitalWrite(SDCARD_CS, HIGH);
}
}
Serial.println("Settings: WiFi radio ON");
}
break;
#endif
#ifdef HAS_4G_MODEM
case ROW_MODEM_TOGGLE:
_modemEnabled = !_modemEnabled;
@@ -1494,58 +876,7 @@ public:
Serial.println("Settings: 4G modem DISABLED (shutdown)");
}
break;
// case ROW_RINGTONE:
// _prefs->ringtone_enabled = _prefs->ringtone_enabled ? 0 : 1;
// modemManager.setRingtoneEnabled(_prefs->ringtone_enabled);
// the_mesh.savePrefs();
// Serial.printf("Settings: Ringtone = %s\n",
// _prefs->ringtone_enabled ? "ON" : "OFF");
// break;
case ROW_APN: {
// Start text editing with current APN as initial value
const char* currentApn = modemManager.getAPN();
startEditText(currentApn);
break;
}
#endif
// --- Contact mode picker ---
case ROW_CONTACT_MODE:
startEditPicker(getContactMode());
break;
// --- Contact sub-toggles (flip bit and save) ---
case ROW_AUTOADD_CHAT:
_prefs->autoadd_config ^= AUTO_ADD_CHAT;
the_mesh.savePrefs();
Serial.printf("Settings: Auto-add Chat = %s\n",
(_prefs->autoadd_config & AUTO_ADD_CHAT) ? "ON" : "OFF");
break;
case ROW_AUTOADD_REPEATER:
_prefs->autoadd_config ^= AUTO_ADD_REPEATER;
the_mesh.savePrefs();
Serial.printf("Settings: Auto-add Repeater = %s\n",
(_prefs->autoadd_config & AUTO_ADD_REPEATER) ? "ON" : "OFF");
break;
case ROW_AUTOADD_ROOM:
_prefs->autoadd_config ^= AUTO_ADD_ROOM_SERVER;
the_mesh.savePrefs();
Serial.printf("Settings: Auto-add Room = %s\n",
(_prefs->autoadd_config & AUTO_ADD_ROOM_SERVER) ? "ON" : "OFF");
break;
case ROW_AUTOADD_SENSOR:
_prefs->autoadd_config ^= AUTO_ADD_SENSOR;
the_mesh.savePrefs();
Serial.printf("Settings: Auto-add Sensor = %s\n",
(_prefs->autoadd_config & AUTO_ADD_SENSOR) ? "ON" : "OFF");
break;
case ROW_AUTOADD_OVERWRITE:
_prefs->autoadd_config ^= AUTO_ADD_OVERWRITE_OLDEST;
the_mesh.savePrefs();
Serial.printf("Settings: Overwrite oldest = %s\n",
(_prefs->autoadd_config & AUTO_ADD_OVERWRITE_OLDEST) ? "ON" : "OFF");
break;
case ROW_ADD_CHANNEL:
startEditText("");
break;

View File

@@ -1,128 +0,0 @@
#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

View File

@@ -3,10 +3,9 @@
#include "../MyMesh.h"
#include "NotesScreen.h"
#include "RepeaterAdminScreen.h"
#include "DiscoveryScreen.h"
#include "MapScreen.h"
#include "target.h"
#if defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
#include "GPSDutyCycle.h"
#ifdef WIFI_SSID
#include <WiFi.h>
#endif
@@ -98,8 +97,6 @@ class HomeScreen : public UIScreen {
RADIO,
#ifdef BLE_PIN_CODE
BLUETOOTH,
#elif defined(MECK_WIFI_COMPANION)
WIFI_STATUS,
#endif
ADVERT,
#if ENV_INCLUDE_GPS == 1
@@ -300,20 +297,18 @@ public:
int y = 20;
display.setColor(DisplayDriver::YELLOW);
display.setTextSize(2);
sprintf(tmp, "MSG: %d", _task->getUnreadMsgCount());
sprintf(tmp, "MSG: %d", _task->getMsgCount());
display.drawTextCentered(display.width() / 2, y, tmp);
y += 18;
#if defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
#ifdef WIFI_SSID
IPAddress ip = WiFi.localIP();
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;
}
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, y, tmp);
y += 12;
#endif
#if defined(BLE_PIN_CODE) || defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
#if defined(BLE_PIN_CODE) || defined(WIFI_SSID)
if (_task->hasConnection()) {
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
@@ -340,20 +335,16 @@ public:
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 ");
#ifdef HAS_4G_MODEM
display.drawTextCentered(display.width() / 2, y, "[E] Reader [T] Phone ");
#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 ");
display.drawTextCentered(display.width() / 2, y, "[E] Reader [P] Audiobooks");
#else
y -= 10; // reclaim the row for standalone
display.drawTextCentered(display.width() / 2, y, "[E] Reader ");
#endif
#ifdef MECK_WEB_READER
y += 10;
display.drawTextCentered(display.width() / 2, y, "[B] Browser ");
#endif
y += 14;
@@ -424,44 +415,6 @@ public:
display.setColor(DisplayDriver::GREEN);
display.setTextSize(1);
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);
@@ -469,16 +422,34 @@ public:
display.drawTextCentered(display.width() / 2, 64 - 11, "advert: " PRESS_LABEL);
#if ENV_INCLUDE_GPS == 1
} else if (_page == HomePage::GPS) {
extern GPSDutyCycle gpsDuty;
extern GPSStreamCounter gpsStream;
LocationProvider* nmea = sensors.getLocationProvider();
char buf[50];
int y = 18;
// GPS state line
// GPS state line with duty cycle info
if (!_node_prefs->gps_enabled) {
strcpy(buf, "gps off");
} else {
strcpy(buf, "gps on");
switch (gpsDuty.getState()) {
case GPSDutyState::ACQUIRING: {
uint32_t elapsed = gpsDuty.acquireElapsedSecs();
sprintf(buf, "acquiring %us", (unsigned)elapsed);
break;
}
case GPSDutyState::SLEEPING: {
uint32_t remain = gpsDuty.sleepRemainingSecs();
if (remain >= 60) {
sprintf(buf, "sleep %um%02us", (unsigned)(remain / 60), (unsigned)(remain % 60));
} else {
sprintf(buf, "sleep %us", (unsigned)remain);
}
break;
}
default:
strcpy(buf, "gps off");
}
}
display.drawTextLeftAlign(0, y, buf);
@@ -494,9 +465,9 @@ public:
display.drawTextRightAlign(display.width()-1, y, buf);
y = y + 12;
// NMEA sentence counter confirms baud rate and data flow
// NMEA sentence counter — confirms baud rate and data flow
display.drawTextLeftAlign(0, y, "sentences");
if (_node_prefs->gps_enabled) {
if (gpsDuty.isHardwareOn()) {
uint16_t sps = gpsStream.getSentencesPerSec();
uint32_t total = gpsStream.getSentenceCount();
sprintf(buf, "%u/s (%lu)", sps, (unsigned long)total);
@@ -671,11 +642,8 @@ public:
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)
// Remaining capacity
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);
@@ -930,11 +898,6 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no
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;
@@ -947,12 +910,10 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no
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
discovery_screen = new DiscoveryScreen(this, &rtc_clock);
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);
}
@@ -1000,7 +961,7 @@ void UITask::msgRead(int msgcount) {
}
void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount,
const uint8_t* path, int8_t snr) {
const uint8_t* path) {
_msgcount = msgcount;
// Add to preview screen (for notifications on non-keyboard devices)
@@ -1018,15 +979,8 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i
}
}
// Add to channel history screen with channel index, path data, and SNR
((ChannelScreen *) channel_screen)->addMessage(channel_idx, path_len, from_name, text, path, snr);
// 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);
}
// Add to channel history screen with channel index and path data
((ChannelScreen *) channel_screen)->addMessage(channel_idx, path_len, from_name, text, path);
#if defined(LilyGo_TDeck_Pro)
// T-Deck Pro: Don't interrupt user with popup - just show brief notification
@@ -1122,11 +1076,10 @@ void UITask::shutdown(bool restart){
// Disable GPS if active
#if ENV_INCLUDE_GPS == 1
{
extern GPSDutyCycle gpsDuty;
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
gpsDuty.disable();
}
}
#endif
@@ -1221,60 +1174,11 @@ void UITask::loop() {
// 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
@@ -1315,11 +1219,10 @@ 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 on e-ink (persists after power loss)
#if defined(THINKNODE_M1) || defined(LILYGO_TECHO) || defined(LilyGo_TDeck_Pro)
// 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)
if (_display != NULL) {
_display->startFrame();
_display->setTextSize(2);
@@ -1331,9 +1234,7 @@ if (curr) curr->poll();
#endif
shutdown();
}
} else {
_low_batt_count = 0;
}
next_batt_chck = millis() + 8000;
}
@@ -1384,22 +1285,20 @@ bool UITask::getGPSState() {
void UITask::toggleGPS() {
#if ENV_INCLUDE_GPS == 1
extern GPSDutyCycle gpsDuty;
if (_sensors != NULL) {
if (_node_prefs->gps_enabled) {
// Disable GPS cut hardware power
// 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
gpsDuty.disable();
notify(UIEventType::ack);
} else {
// Enable GPS — power on hardware
// Enable GPS — start duty cycle
_sensors->setSettingValue("gps", "1");
_node_prefs->gps_enabled = 1;
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, GPS_EN_ACTIVE);
#endif
gpsDuty.enable();
notify(UIEventType::ack);
}
the_mesh.savePrefs();
@@ -1463,10 +1362,6 @@ 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();
@@ -1564,10 +1459,6 @@ 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];
@@ -1577,12 +1468,6 @@ void UITask::addSentChannelMessage(uint8_t channel_idx, const char* sender, cons
((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) {
@@ -1608,16 +1493,6 @@ void UITask::gotoRepeaterAdmin(int contactIdx) {
_next_refresh = 100;
}
void UITask::gotoDiscoveryScreen() {
((DiscoveryScreen*)discovery_screen)->resetScroll();
setCurrScreen(discovery_screen);
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)
@@ -1631,9 +1506,6 @@ void UITask::gotoWebReader() {
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();
@@ -1643,19 +1515,6 @@ void UITask::gotoWebReader() {
}
#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);
@@ -1670,14 +1529,6 @@ void UITask::onAdminCliResponse(const char* from_name, const char* text) {
}
}
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;

View File

@@ -30,9 +30,6 @@
#include "WebReaderScreen.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;
@@ -44,17 +41,11 @@ class UITask : public AbstractUITask {
#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;
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;
@@ -79,11 +70,9 @@ class UITask : public AbstractUITask {
UIScreen* sms_screen; // SMS messaging screen (4G variant only)
#endif
UIScreen* repeater_admin; // Repeater admin screen
UIScreen* discovery_screen; // Node discovery scan screen
#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;
void userLedHandler();
@@ -101,11 +90,6 @@ 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;
}
@@ -120,8 +104,6 @@ public:
void gotoOnboarding(); // Navigate to settings in onboarding mode
void gotoAudiobookPlayer(); // Navigate to audiobook player
void gotoRepeaterAdmin(int contactIdx); // Navigate to repeater admin
void gotoDiscoveryScreen(); // Navigate to node discovery scan
void gotoMapScreen(); // Navigate to map tile screen
#ifdef MECK_WEB_READER
void gotoWebReader(); // Navigate to web reader (browser)
#endif
@@ -132,14 +114,7 @@ public:
#endif
void showAlert(const char* text, int duration_millis) override;
void forceRefresh() override { _next_refresh = 100; }
// 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)
bool hasDisplay() const { return _display != NULL; }
bool isButtonPressed() const;
bool isOnChannelScreen() const { return curr == channel_screen; }
@@ -149,8 +124,6 @@ public:
bool isOnSettingsScreen() const { return curr == settings_screen; }
bool isOnAudiobookPlayer() const { return curr == audiobook_screen; }
bool isOnRepeaterAdmin() const { return curr == repeater_admin; }
bool isOnDiscoveryScreen() const { return curr == discovery_screen; }
bool isOnMapScreen() const { return curr == map_screen; }
#ifdef MECK_WEB_READER
bool isOnWebReader() const { return curr == web_reader; }
#endif
@@ -175,13 +148,9 @@ public:
// Add a sent message to the channel screen history
void addSentChannelMessage(uint8_t channel_idx, const char* sender, const char* text) override;
// 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; }
@@ -194,8 +163,6 @@ public:
UIScreen* getAudiobookScreen() const { return audiobook_screen; }
void setAudiobookScreen(UIScreen* s) { audiobook_screen = s; }
UIScreen* getRepeaterAdminScreen() const { return repeater_admin; }
UIScreen* getDiscoveryScreen() const { return discovery_screen; }
UIScreen* getMapScreen() const { return map_screen; }
#ifdef MECK_WEB_READER
UIScreen* getWebReaderScreen() const { return web_reader; }
#endif
@@ -203,7 +170,7 @@ public:
// from AbstractUITask
void msgRead(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;
const uint8_t* path = nullptr) override;
void notify(UIEventType t = UIEventType::none) override;
void loop() override;

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
#pragma once
// Emoji Picker with scrolling grid and scroll bar
// 5 columns, 4 visible rows, scrollable through all 65 emoji
// 5 columns, 4 visible rows, scrollable through all 46 emoji
// WASD navigation, Enter to select, $/Q/Backspace to cancel
#include <helpers/ui/DisplayDriver.h>
@@ -58,25 +58,6 @@ static const char* EMOJI_LABELS[EMOJI_COUNT] = {
"Knob", // 43 control_knobs
"Pch", // 44 peach
"Race", // 45 racing_car
"Mous", // 46 mouse
"Shrm", // 47 mushroom
"Bio", // 48 biohazard
"Pnda", // 49 panda
"Bang", // 50 anger
"DrgF", // 51 dragon_face
"Pagr", // 52 pager
"Bee", // 53 bee
"Bulb", // 54 bulb
"Cat", // 55 cat
"Flur", // 56 fleur
"Moon", // 57 moon
"Cafe", // 58 coffee
"Toth", // 59 tooth
"Prtz", // 60 pretzel
"Abac", // 61 abacus
"Moai", // 62 moai
"Hiii", // 63 tipping
"Hedg", // 64 hedgehog
};
struct EmojiPicker {

View File

@@ -1,11 +1,8 @@
#include "UITask.h"
#include <helpers/TxtDataHelpers.h>
#include "../MyMesh.h"
#include "NotesScreen.h"
#include "RepeaterAdminScreen.h"
#include "MapScreen.h"
#include "target.h"
#if defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
#ifdef WIFI_SSID
#include <WiFi.h>
#endif
@@ -37,18 +34,11 @@
#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[24];
char _version_info[12];
public:
SplashScreen(UITask* task) : _task(task) {
@@ -95,20 +85,13 @@ 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
@@ -120,13 +103,12 @@ 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, int* outIconX = nullptr) {
void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) {
// Use voltage-based estimation to match BLE app readings
uint8_t batteryPercentage = 0;
if (batteryMilliVolts > 0) {
@@ -155,8 +137,6 @@ 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);
@@ -176,24 +156,6 @@ 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;
@@ -224,7 +186,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), _shutdown_at(0), _editing_utc(false), _saved_utc_offset(0), sensors_lpp(200) { }
_shutdown_init(false), _editing_utc(false), _saved_utc_offset(0), sensors_lpp(200) { }
bool isEditingUTC() const { return _editing_utc; }
void cancelEditUTC() {
@@ -235,31 +197,23 @@ public:
}
void poll() override {
if (_shutdown_init && millis() >= _shutdown_at && !_task->isButtonPressed()) {
if (_shutdown_init && !_task->isButtonPressed()) { // must wait for USR button to be released
_task->shutdown();
}
}
int render(DisplayDriver& display) override {
char tmp[80];
// node name (tinyfont to avoid overlapping clock)
display.setTextSize(0);
// node name
display.setTextSize(1);
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, -3);
display.setCursor(0, 0);
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
{
@@ -296,70 +250,28 @@ public:
}
if (_page == HomePage::FIRST) {
int y = 20;
display.setColor(DisplayDriver::YELLOW);
display.setTextSize(2);
sprintf(tmp, "MSG: %d", _task->getUnreadMsgCount());
display.drawTextCentered(display.width() / 2, y, tmp);
y += 18;
sprintf(tmp, "MSG: %d", _task->getMsgCount());
display.drawTextCentered(display.width() / 2, 20, tmp);
#if defined(WIFI_SSID) || defined(MECK_WIFI_COMPANION)
#ifdef WIFI_SSID
IPAddress ip = WiFi.localIP();
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;
}
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);
#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, y, "< Connected >");
y += 12;
#ifdef BLE_PIN_CODE
} else if (_task->isSerialEnabled() && the_mesh.getBLEPin() != 0) {
display.drawTextCentered(display.width() / 2, 43, "< Connected >");
} else if (the_mesh.getBLEPin() != 0) { // BT pin
display.setColor(DisplayDriver::RED);
display.setTextSize(2);
sprintf(tmp, "Pin:%d", the_mesh.getBLEPin());
display.drawTextCentered(display.width() / 2, y, tmp);
y += 18;
#endif
display.drawTextCentered(display.width() / 2, 43, tmp);
}
#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);
@@ -404,83 +316,34 @@ 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, 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
display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL);
} 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;
// GPS state line
if (!_node_prefs->gps_enabled) {
strcpy(buf, "gps off");
bool gps_state = _task->getGPSState();
#ifdef PIN_GPS_SWITCH
bool hw_gps_state = digitalRead(PIN_GPS_SWITCH);
if (gps_state != hw_gps_state) {
strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)");
} else {
strcpy(buf, "gps on");
strcpy(buf, gps_state ? "gps on" : "gps off");
}
#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");
@@ -492,19 +355,6 @@ 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.);
@@ -623,68 +473,6 @@ 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);
@@ -745,7 +533,6 @@ public:
}
return true;
}
#ifdef BLE_PIN_CODE
if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) {
if (_task->isSerialEnabled()) { // toggle Bluetooth on/off
_task->disableSerial();
@@ -754,7 +541,6 @@ public:
}
return true;
}
#endif
if (c == KEY_ENTER && _page == HomePage::ADVERT) {
_task->notify(UIEventType::ack);
if (the_mesh.advert()) {
@@ -783,8 +569,7 @@ public:
}
#endif
if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) {
_shutdown_init = true;
_shutdown_at = millis() + 900; // allow e-ink refresh (644ms) before shutdown
_shutdown_init = true; // need to wait for button to be released
return true;
}
return false;
@@ -923,17 +708,6 @@ 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;
@@ -943,14 +717,7 @@ 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);
}
@@ -992,13 +759,12 @@ switch(t){
void UITask::msgRead(int msgcount) {
_msgcount = msgcount;
if (msgcount == 0 && curr == msg_preview) {
if (msgcount == 0) {
gotoHomeScreen();
}
}
void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount,
const uint8_t* path) {
void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) {
_msgcount = msgcount;
// Add to preview screen (for notifications on non-keyboard devices)
@@ -1016,25 +782,15 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, i
}
}
// 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);
}
// Add to channel history screen with channel index
((ChannelScreen *) channel_screen)->addMessage(channel_idx, path_len, from_name, text);
#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
// 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);
}
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);
@@ -1049,14 +805,6 @@ 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() {
@@ -1106,32 +854,8 @@ void UITask::shutdown(bool restart){
if (restart) {
_board->reboot();
} else {
// 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();
radio_driver.powerOff();
_board->powerOff();
}
}
@@ -1216,63 +940,6 @@ 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
@@ -1313,11 +980,10 @@ 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 on e-ink (persists after power loss)
#if defined(THINKNODE_M1) || defined(LILYGO_TECHO) || defined(LilyGo_TDeck_Pro)
// 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)
if (_display != NULL) {
_display->startFrame();
_display->setTextSize(2);
@@ -1329,9 +995,7 @@ if (curr) curr->poll();
#endif
shutdown();
}
} else {
_low_batt_count = 0;
}
next_batt_chck = millis() + 8000;
}
@@ -1373,38 +1037,39 @@ char UITask::handleTripleClick(char c) {
}
bool UITask::getGPSState() {
#if ENV_INCLUDE_GPS == 1
return _node_prefs != NULL && _node_prefs->gps_enabled;
#else
return false;
#endif
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;
}
void UITask::toggleGPS() {
#if ENV_INCLUDE_GPS == 1
if (_sensors != NULL) {
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);
// 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;
}
the_mesh.savePrefs();
showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800);
_next_refresh = 0;
}
#endif
}
}
void UITask::toggleBuzzer() {
@@ -1461,10 +1126,6 @@ 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();
@@ -1496,21 +1157,8 @@ 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();
@@ -1520,7 +1168,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();
@@ -1529,43 +1177,10 @@ 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];
@@ -1573,109 +1188,4 @@ 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
}

View File

@@ -68,7 +68,7 @@ void Dispatcher::loop() {
next_tx_time = futureMillis(t * getAirtimeBudgetFactor());
_radio->onSendFinished();
logTx(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
logTx(outbound, 2 + outbound->path_len + outbound->payload_len);
if (outbound->isRouteFlood()) {
n_sent_flood++;
} else {
@@ -80,7 +80,7 @@ void Dispatcher::loop() {
MESH_DEBUG_PRINTLN("%s Dispatcher::loop(): WARNING: outbound packed send timed out!", getLogDateTime());
_radio->onSendFinished();
logTxFail(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
logTxFail(outbound, 2 + outbound->path_len + outbound->payload_len);
releasePacket(outbound); // return to pool
outbound = NULL;
@@ -141,13 +141,12 @@ void Dispatcher::checkRecv() {
}
pkt->path_len = raw[i++];
uint16_t path_byte_len = pkt->getPathByteLen();
if (path_byte_len > MAX_PATH_SIZE || i + path_byte_len > len) {
if (pkt->path_len > MAX_PATH_SIZE || i + pkt->path_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], path_byte_len); i += path_byte_len;
memcpy(pkt->path, &raw[i], pkt->path_len); i += pkt->path_len;
pkt->payload_len = len - i; // payload is remainder
if (pkt->payload_len > sizeof(pkt->payload)) {
@@ -259,8 +258,7 @@ void Dispatcher::checkSend() {
memcpy(&raw[len], &outbound->transport_codes[1], 2); len += 2;
}
raw[len++] = outbound->path_len;
uint16_t out_pbl = outbound->getPathByteLen();
memcpy(&raw[len], outbound->path, out_pbl); len += out_pbl;
memcpy(&raw[len], outbound->path, outbound->path_len); len += outbound->path_len;
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);
@@ -314,8 +312,8 @@ void Dispatcher::releasePacket(Packet* packet) {
}
void Dispatcher::sendPacket(Packet* packet, uint8_t priority, uint32_t delay_millis) {
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);
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);
_mgr->free(packet);
} else {
_mgr->queueOutbound(packet, priority, futureMillis(delay_millis));

View File

@@ -20,10 +20,6 @@ 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;
}
@@ -94,4 +90,5 @@ public:
void readFrom(const uint8_t* src, size_t len);
};
}
}

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 = (uint32_t)(_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * 0.5f);
uint32_t t = (_radio->getEstAirtimeFor(packet->getRawLength()) * 52 / 50) / 2;
return _rng->nextInt(0, 5)*t;
}
@@ -77,9 +77,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
return ACTION_RELEASE;
}
if (pkt->isRouteDirect() && (pkt->path_len & 63) > 0) {
uint8_t dir_bph = (pkt->path_len >> 6) + 1; // bytes per hop for this packet
if (pkt->isRouteDirect() && pkt->path_len >= PATH_HASH_SIZE) {
// check for 'early received' ACK
if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) {
int i = 0;
@@ -90,7 +88,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
}
}
if (self_id.isHashMatch(pkt->path, dir_bph) && allowPacketForward(pkt)) {
if (self_id.isHashMatch(pkt->path) && allowPacketForward(pkt)) {
if (pkt->getPayloadType() == PAYLOAD_TYPE_MULTIPART) {
return forwardMultipartDirect(pkt);
} else if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) {
@@ -160,7 +158,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 += Packet::getPathByteLenFor(path_len);
uint8_t* path = &data[k]; k += 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!)
@@ -295,7 +293,8 @@ 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 = Packet::copyPath(tmp.path, pkt->path, pkt->path_len);
tmp.path_len = pkt->path_len;
memcpy(tmp.path, pkt->path, pkt->path_len);
tmp.payload_len = pkt->payload_len - 1;
memcpy(tmp.payload, &pkt->payload[1], tmp.payload_len);
@@ -321,34 +320,28 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
}
void Mesh::removeSelfFromPath(Packet* pkt) {
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);
// 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
}
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
&& 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;
&& 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]);
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
}
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
}
return ACTION_RELEASE;
}
@@ -360,7 +353,8 @@ 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 = Packet::copyPath(tmp.path, pkt->path, pkt->path_len);
tmp.path_len = pkt->path_len;
memcpy(tmp.path, pkt->path, pkt->path_len);
tmp.payload_len = pkt->payload_len - 1;
memcpy(tmp.payload, &pkt->payload[1], tmp.payload_len);
@@ -382,7 +376,7 @@ void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
delay_millis += getDirectRetransmitDelay(packet) + 300;
auto a1 = createMultiAck(crc, extra);
if (a1) {
a1->path_len = Packet::copyPath(a1->path, packet->path, packet->path_len);
memcpy(a1->path, packet->path, a1->path_len = packet->path_len);
a1->header &= ~PH_ROUTE_MASK;
a1->header |= ROUTE_TYPE_DIRECT;
sendPacket(a1, 0, delay_millis);
@@ -392,7 +386,7 @@ void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
auto a2 = createAck(crc);
if (a2) {
a2->path_len = Packet::copyPath(a2->path, packet->path, packet->path_len);
memcpy(a2->path, packet->path, a2->path_len = packet->path_len);
a2->header &= ~PH_ROUTE_MASK;
a2->header |= ROUTE_TYPE_DIRECT;
sendPacket(a2, 0, delay_millis);
@@ -630,7 +624,7 @@ Packet* Mesh::createControlData(const uint8_t* data, size_t len) {
return packet;
}
void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_bytes_per_hop) {
void Mesh::sendFlood(Packet* packet, uint32_t delay_millis) {
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) {
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
return;
@@ -638,9 +632,7 @@ void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_bytes_p
packet->header &= ~PH_ROUTE_MASK;
packet->header |= ROUTE_TYPE_FLOOD;
// 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);
packet->path_len = 0;
_tables->hasSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
@@ -655,7 +647,7 @@ void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_bytes_p
sendPacket(packet, pri, delay_millis);
}
void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis, uint8_t path_bytes_per_hop) {
void Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis) {
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) {
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
return;
@@ -665,9 +657,7 @@ 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];
// 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);
packet->path_len = 0;
_tables->hasSeen(packet); // mark this packet as already sent in case it is rebroadcast back to us
@@ -695,7 +685,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 {
packet->path_len = Packet::copyPath(packet->path, path, path_len);
memcpy(packet->path, path, packet->path_len = path_len);
if (packet->getPayloadType() == PAYLOAD_TYPE_PATH) {
pri = 1; // slightly less priority
} else {

View File

@@ -195,16 +195,14 @@ 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, uint8_t path_bytes_per_hop=1);
void sendFlood(Packet* packet, uint32_t delay_millis=0);
/**
* \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, uint8_t path_bytes_per_hop=1);
void sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis=0);
/**
* \brief send a locally-generated Packet with Direct routing
@@ -224,4 +222,4 @@ public:
};
}
}

View File

@@ -11,7 +11,7 @@ Packet::Packet() {
}
int Packet::getRawLength() const {
return 2 + getPathByteLen() + payload_len + (hasTransportCodes() ? 4 : 0);
return 2 + path_len + payload_len + (hasTransportCodes() ? 4 : 0);
}
void Packet::calculatePacketHash(uint8_t* hash) const {
@@ -33,8 +33,7 @@ uint8_t Packet::writeTo(uint8_t dest[]) const {
memcpy(&dest[i], &transport_codes[1], 2); i += 2;
}
dest[i++] = path_len;
uint16_t pbl = getPathByteLen();
memcpy(&dest[i], path, pbl); i += pbl;
memcpy(&dest[i], path, path_len); i += path_len;
memcpy(&dest[i], payload, payload_len); i += payload_len;
return i;
}
@@ -49,9 +48,8 @@ bool Packet::readFrom(const uint8_t src[], uint8_t len) {
transport_codes[0] = transport_codes[1] = 0;
}
path_len = src[i++];
uint16_t pbl = getPathByteLen();
if (pbl > sizeof(path)) return false; // bad encoding
memcpy(path, &src[i], pbl); i += pbl;
if (path_len > sizeof(path)) return false; // bad encoding
memcpy(path, &src[i], path_len); i += path_len;
if (i >= len) return false; // bad encoding
payload_len = len - i;
if (payload_len > sizeof(payload)) return false; // bad encoding

View File

@@ -1,7 +1,6 @@
#pragma once
#include <MeshCore.h>
#include <string.h>
namespace mesh {
@@ -82,43 +81,6 @@ 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
*/
@@ -139,4 +101,4 @@ public:
bool readFrom(const uint8_t src[], uint8_t len);
};
}
}

View File

@@ -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 == OUT_PATH_UNKNOWN) {
if (dest.out_path_len < 0) {
mesh::Packet* ack = createAck(ack_hash);
if (ack) sendFloodScoped(dest, ack, TXT_ACK_DELAY);
} else {
@@ -92,7 +92,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 = OUT_PATH_UNKNOWN; // initially out_path is unknown
ci.out_path_len = -1; // initially out_path is unknown
StrHelper::strncpy(ci.name, parser.getName(), sizeof(ci.name));
ci.type = parser.getType();
if (parser.hasLatLon()) {
@@ -263,7 +263,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 != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
if (from.out_path_len >= 0) { // 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 +273,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 != OUT_PATH_UNKNOWN) {
if (packet->isRouteFlood() && from.out_path_len >= 0) {
// 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,8 +295,7 @@ 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'(?)
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()
memcpy(from.out_path, out_path, from.out_path_len = out_path_len); // store a copy of path, for sendDirect()
from.lastmod = getRTCClock()->getCurrentTime();
onContactPathUpdated(from);
@@ -318,7 +317,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 != OUT_PATH_UNKNOWN) {
if (packet->isRouteFlood() && from->out_path_len >= 0) {
// 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);
}
@@ -387,7 +386,7 @@ int BaseChatMesh::sendMessage(const ContactInfo& recipient, uint32_t timestamp,
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
int rc;
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
if (recipient.out_path_len < 0) {
sendFloodScoped(recipient, pkt);
txt_send_timeout = futureMillis(est_timeout = calcFloodTimeoutMillisFor(t));
rc = MSG_SEND_SENT_FLOOD;
@@ -413,7 +412,7 @@ int BaseChatMesh::sendCommandData(const ContactInfo& recipient, uint32_t timest
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
int rc;
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
if (recipient.out_path_len < 0) {
sendFloodScoped(recipient, pkt);
txt_send_timeout = futureMillis(est_timeout = calcFloodTimeoutMillisFor(t));
rc = MSG_SEND_SENT_FLOOD;
@@ -501,7 +500,7 @@ int BaseChatMesh::sendLogin(const ContactInfo& recipient, const char* password,
}
if (pkt) {
uint32_t t = _radio->getEstAirtimeFor(pkt->getRawLength());
if (recipient.out_path_len == OUT_PATH_UNKNOWN) {
if (recipient.out_path_len < 0) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -526,7 +525,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 == OUT_PATH_UNKNOWN) {
if (recipient.out_path_len < 0) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -553,7 +552,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 == OUT_PATH_UNKNOWN) {
if (recipient.out_path_len < 0) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -580,7 +579,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 == OUT_PATH_UNKNOWN) {
if (recipient.out_path_len < 0) {
sendFloodScoped(recipient, pkt);
est_timeout = calcFloodTimeoutMillisFor(t);
return MSG_SEND_SENT_FLOOD;
@@ -684,7 +683,7 @@ void BaseChatMesh::checkConnections() {
MESH_DEBUG_PRINTLN("checkConnections(): Keep_alive contact not found!");
continue;
}
if (contact->out_path_len == OUT_PATH_UNKNOWN) {
if (contact->out_path_len < 0) {
MESH_DEBUG_PRINTLN("checkConnections(): Keep_alive contact, no out_path!");
continue;
}
@@ -711,7 +710,7 @@ void BaseChatMesh::checkConnections() {
}
void BaseChatMesh::resetPathTo(ContactInfo& recipient) {
recipient.out_path_len = OUT_PATH_UNKNOWN;
recipient.out_path_len = -1;
}
static ContactInfo* table; // pass via global :-(
@@ -876,4 +875,4 @@ void BaseChatMesh::loop() {
releasePacket(_pendingLoopback); // undo the obtainNewPacket()
_pendingLoopback = NULL;
}
}
}

View File

@@ -58,9 +58,9 @@ class BaseChatMesh : public mesh::Mesh {
friend class ContactsIterator;
ContactInfo* contacts;
ContactInfo contacts[MAX_CONTACTS];
int num_contacts;
int* sort_array;
int sort_array[MAX_CONTACTS];
int matching_peer_indexes[MAX_SEARCH_RESULTS];
unsigned long txt_send_timeout;
#ifdef MAX_GROUP_CHANNELS
@@ -78,8 +78,6 @@ 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));
@@ -92,19 +90,6 @@ 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
@@ -113,7 +98,6 @@ 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;
@@ -185,4 +169,4 @@ public:
int findChannelIdx(const mesh::GroupChannel& ch);
void loop();
};
};

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 = OUT_PATH_UNKNOWN; // initially out_path is unknown
c->out_path_len = -1; // 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;
}
}

View File

@@ -4,10 +4,6 @@
#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
@@ -17,7 +13,7 @@
struct ClientInfo {
mesh::Identity id;
uint8_t permissions;
uint8_t out_path_len; // OUT_PATH_UNKNOWN = no known path
int8_t out_path_len;
uint8_t out_path[MAX_PATH_SIZE];
uint8_t shared_secret[PUB_KEY_SIZE];
uint32_t last_timestamp; // by THEIR clock (transient)
@@ -59,4 +55,4 @@ public:
int getNumClients() const { return num_clients; }
ClientInfo* getClientByIdx(int idx) { return &clients[idx]; }
};
};

View File

@@ -3,14 +3,12 @@
#include <Arduino.h>
#include <Mesh.h>
#define OUT_PATH_UNKNOWN 0xFF // no known path — triggers flood routing
struct ContactInfo {
mesh::Identity id;
char name[32];
uint8_t type; // on of ADV_TYPE_*
uint8_t flags;
uint8_t out_path_len; // encoded: bits[7:6]=mode, bits[5:0]=hops. OUT_PATH_UNKNOWN=no path
int8_t out_path_len;
mutable bool shared_secret_valid; // flag to indicate if shared_secret has been calculated
uint8_t out_path[MAX_PATH_SIZE];
uint32_t last_advert_timestamp; // by THEIR clock
@@ -28,4 +26,4 @@ struct ContactInfo {
private:
mutable uint8_t shared_secret[PUB_KEY_SIZE];
};
};

View File

@@ -147,21 +147,15 @@ void SerialBLEInterface::enable() {
}
void SerialBLEInterface::disable() {
bool wasEnabled = _isEnabled;
_isEnabled = false;
BLE_DEBUG_PRINTLN("SerialBLEInterface::disable");
// Only try BLE operations if we were previously enabled
// (avoids accessing dead BLE objects after btStop/mem_release)
if (wasEnabled && pServer) {
pServer->getAdvertising()->stop();
pServer->disconnect(last_conn_id);
pService->stop();
}
pServer->getAdvertising()->stop();
pServer->disconnect(last_conn_id);
pService->stop();
oldDeviceConnected = deviceConnected = false;
adv_restart_time = 0;
clearBuffers();
}
size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
@@ -192,8 +186,6 @@ bool SerialBLEInterface::isWriteBusy() const {
}
size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
if (!_isEnabled) return 0; // BLE disabled — skip all BLE operations
if (send_queue_len > 0 // first, check send queue
&& millis() >= _last_write + BLE_WRITE_MIN_INTERVAL // space the writes apart
) {

View File

@@ -12,31 +12,7 @@
#include <Fonts/FreeSans9pt7b.h>
#include <Fonts/FreeSansBold12pt7b.h>
#include <Fonts/FreeSans18pt7b.h>
// Inline CRC32 for frame change detection (replaces bakercp/CRC32
// to avoid naming collision with PNGdec's bundled CRC32.h)
class FrameCRC32 {
uint32_t _crc = 0xFFFFFFFF;
public:
void reset() { _crc = 0xFFFFFFFF; }
template<typename T> void update(T val) {
const uint8_t* p = (const uint8_t*)&val;
for (size_t i = 0; i < sizeof(T); i++) {
_crc ^= p[i];
for (int b = 0; b < 8; b++)
_crc = (_crc >> 1) ^ (0xEDB88320 & -(int32_t)(_crc & 1));
}
}
template<typename T> void update(const T* data, size_t len) {
const uint8_t* p = (const uint8_t*)data;
for (size_t i = 0; i < len * sizeof(T); i++) {
_crc ^= p[i];
for (int b = 0; b < 8; b++)
_crc = (_crc >> 1) ^ (0xEDB88320 & -(int32_t)(_crc & 1));
}
}
uint32_t finalize() { return _crc ^ 0xFFFFFFFF; }
};
#include <CRC32.h>
#include "DisplayDriver.h"
@@ -58,7 +34,7 @@ class GxEPDDisplay : public DisplayDriver {
bool _init = false;
bool _isOn = false;
uint16_t _curr_color;
FrameCRC32 display_crc;
CRC32 display_crc;
int last_display_crc_value = 0;
public:
@@ -84,24 +60,4 @@ public:
void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override;
uint16_t getTextWidth(const char* str) override;
void endFrame() override;
// --- 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(); }
// Draw text at raw (unscaled) physical coordinates using built-in 5x7 font
void drawTextRaw(int16_t x, int16_t y, const char* text, uint16_t color) {
display.setFont(NULL); // Built-in 5x7 font
display.setTextSize(1);
display.setTextColor(color);
display.setCursor(x, y);
display.print(text);
}
// Force endFrame() to push to display even if CRC unchanged
// (needed because drawPixelRaw bypasses CRC tracking)
void invalidateFrameCRC() { last_display_crc_value = 0; }
};
};

View File

@@ -0,0 +1,185 @@
#pragma once
#include <Arduino.h>
#include "variant.h"
#include "GPSStreamCounter.h"
// GPS Duty Cycle Manager
// Controls the hardware GPS enable pin (PIN_GPS_EN) to save power.
// When enabled, cycles between acquiring a fix and sleeping with power cut.
//
// States:
// OFF User has disabled GPS. Hardware power is cut.
// ACQUIRING GPS module powered on, waiting for a fix or timeout.
// SLEEPING GPS module powered off, timer counting down to next cycle.
#if HAS_GPS
// How long to leave GPS powered on while acquiring a fix (ms)
#ifndef GPS_ACQUIRE_TIMEOUT_MS
#define GPS_ACQUIRE_TIMEOUT_MS 180000 // 3 minutes
#endif
// How long to sleep between acquisition cycles (ms)
#ifndef GPS_SLEEP_DURATION_MS
#define GPS_SLEEP_DURATION_MS 900000 // 15 minutes
#endif
// If we get a fix quickly, power off immediately but still respect
// a minimum on-time so the RTC can sync properly
#ifndef GPS_MIN_ON_TIME_MS
#define GPS_MIN_ON_TIME_MS 5000 // 5 seconds after fix
#endif
enum class GPSDutyState : uint8_t {
OFF = 0, // User-disabled, hardware power off
ACQUIRING, // Hardware on, waiting for fix
SLEEPING // Hardware off, timer running
};
class GPSDutyCycle {
public:
GPSDutyCycle() : _state(GPSDutyState::OFF), _state_entered(0),
_last_fix_time(0), _got_fix(false), _time_synced(false),
_stream(nullptr) {}
// Attach the stream counter so we can reset it on power cycles
void setStreamCounter(GPSStreamCounter* stream) { _stream = stream; }
// Call once in setup() after board.begin() and GPS serial init.
void begin(bool initial_enable) {
if (initial_enable) {
_powerOn();
_setState(GPSDutyState::ACQUIRING);
} else {
_powerOff();
_setState(GPSDutyState::OFF);
}
}
// Call every iteration of loop().
// Returns true if GPS hardware is currently powered on.
bool loop() {
switch (_state) {
case GPSDutyState::OFF:
return false;
case GPSDutyState::ACQUIRING: {
unsigned long elapsed = millis() - _state_entered;
if (_got_fix && elapsed >= GPS_MIN_ON_TIME_MS) {
MESH_DEBUG_PRINTLN("GPS duty: fix acquired, powering off for %u min",
(unsigned)(GPS_SLEEP_DURATION_MS / 60000));
_powerOff();
_setState(GPSDutyState::SLEEPING);
return false;
}
if (elapsed >= GPS_ACQUIRE_TIMEOUT_MS) {
MESH_DEBUG_PRINTLN("GPS duty: acquire timeout (%us), sleeping",
(unsigned)(GPS_ACQUIRE_TIMEOUT_MS / 1000));
_powerOff();
_setState(GPSDutyState::SLEEPING);
return false;
}
return true;
}
case GPSDutyState::SLEEPING: {
if (millis() - _state_entered >= GPS_SLEEP_DURATION_MS) {
MESH_DEBUG_PRINTLN("GPS duty: waking up for next acquisition cycle");
_got_fix = false;
_powerOn();
_setState(GPSDutyState::ACQUIRING);
return true;
}
return false;
}
}
return false;
}
void notifyFix() {
if (_state == GPSDutyState::ACQUIRING && !_got_fix) {
_got_fix = true;
_last_fix_time = millis();
MESH_DEBUG_PRINTLN("GPS duty: fix notification received");
}
}
void notifyTimeSync() {
_time_synced = true;
}
void enable() {
if (_state == GPSDutyState::OFF) {
_got_fix = false;
_powerOn();
_setState(GPSDutyState::ACQUIRING);
MESH_DEBUG_PRINTLN("GPS duty: enabled, starting acquisition");
}
}
void disable() {
_powerOff();
_setState(GPSDutyState::OFF);
_got_fix = false;
MESH_DEBUG_PRINTLN("GPS duty: disabled, power off");
}
void forceWake() {
if (_state == GPSDutyState::SLEEPING) {
_got_fix = false;
_powerOn();
_setState(GPSDutyState::ACQUIRING);
MESH_DEBUG_PRINTLN("GPS duty: forced wake for user request");
}
}
GPSDutyState getState() const { return _state; }
bool isHardwareOn() const { return _state == GPSDutyState::ACQUIRING; }
bool hadFix() const { return _got_fix; }
bool hasTimeSynced() const { return _time_synced; }
uint32_t sleepRemainingSecs() const {
if (_state != GPSDutyState::SLEEPING) return 0;
unsigned long elapsed = millis() - _state_entered;
if (elapsed >= GPS_SLEEP_DURATION_MS) return 0;
return (GPS_SLEEP_DURATION_MS - elapsed) / 1000;
}
uint32_t acquireElapsedSecs() const {
if (_state != GPSDutyState::ACQUIRING) return 0;
return (millis() - _state_entered) / 1000;
}
private:
void _powerOn() {
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, GPS_EN_ACTIVE);
delay(10);
#endif
if (_stream) _stream->resetCounters();
}
void _powerOff() {
#ifdef PIN_GPS_EN
digitalWrite(PIN_GPS_EN, !GPS_EN_ACTIVE);
#endif
}
void _setState(GPSDutyState s) {
_state = s;
_state_entered = millis();
}
GPSDutyState _state;
unsigned long _state_entered;
unsigned long _last_fix_time;
bool _got_fix;
bool _time_synced;
GPSStreamCounter* _stream;
};
#endif // HAS_GPS

View File

@@ -78,25 +78,6 @@ void TDeckBoard::begin() {
MESH_DEBUG_PRINTLN("TDeckBoard::begin() - Battery voltage: %d mV", voltage);
configureFuelGauge();
#endif
// --- Early low-voltage protection ---
// If we boot below the shutdown threshold, go straight to deep sleep
// WITHOUT touching the filesystem. This breaks the brown-out reboot
// loop that corrupts contacts when battery is deeply depleted (~2.5V).
#if HAS_BQ27220 && defined(AUTO_SHUTDOWN_MILLIVOLTS)
{
uint16_t bootMv = getBattMilliVolts();
if (bootMv > 0 && bootMv < AUTO_SHUTDOWN_MILLIVOLTS) {
Serial.printf("CRITICAL: Boot voltage %dmV < %dmV — sleeping immediately\n",
bootMv, AUTO_SHUTDOWN_MILLIVOLTS);
// Don't mount SD, don't load contacts, don't pass Go.
// Only wake on user button press (presumably after plugging in charger).
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL);
esp_sleep_enable_ext1_wakeup(1ULL << PIN_USER_BTN, ESP_EXT1_WAKEUP_ANY_HIGH);
esp_deep_sleep_start(); // CPU halts here
}
}
#endif
MESH_DEBUG_PRINTLN("TDeckBoard::begin() - complete");
}
@@ -180,7 +161,7 @@ static bool bq27220_writeControl(uint16_t subcmd) {
#endif
// ---- BQ27220 Design Capacity configuration ----
// The BQ27220 ships with a 3000 mAh default. The T-Deck Pro uses a 2000 mAh
// The BQ27220 ships with a 3000 mAh default. The T-Deck Pro uses a 1400 mAh
// cell. This function checks on boot and writes the correct value via the
// MAC Data Memory interface if needed. The value persists in battery-backed
// RAM, so this typically only writes once (or after a full battery disconnect).
@@ -196,162 +177,7 @@ bool TDeckBoard::configureFuelGauge(uint16_t designCapacity_mAh) {
Serial.printf("BQ27220: Design Capacity = %d mAh (target %d)\n", currentDC, designCapacity_mAh);
if (currentDC == designCapacity_mAh) {
// Design Capacity correct, but check if Full Charge Capacity is sane.
uint16_t fcc = bq27220_read16(BQ27220_REG_FULL_CAP);
Serial.printf("BQ27220: Design Capacity already correct, FCC=%d mAh\n", fcc);
if (fcc >= designCapacity_mAh * 3 / 2) {
// FCC is >=150% of design — stale from factory defaults (typically 3000 mAh).
uint16_t designEnergy = (uint16_t)((uint32_t)designCapacity_mAh * 37 / 10);
Serial.printf("BQ27220: FCC %d >> DC %d, checking Design Energy (target %d mWh)\n",
fcc, designCapacity_mAh, designEnergy);
// Unseal to read data memory and issue RESET
bq27220_writeControl(0x0414); delay(2);
bq27220_writeControl(0x3672); delay(2);
// Full Access
bq27220_writeControl(0xFFFF); delay(2);
bq27220_writeControl(0xFFFF); delay(2);
// Read current Design Energy from data memory to check if it needs writing
// Enter CFG_UPDATE to access data memory
bq27220_writeControl(0x0090);
bool ready = false;
for (int i = 0; i < 50; i++) {
delay(20);
uint16_t opSt = bq27220_read16(BQ27220_REG_OP_STATUS);
if (opSt & 0x0400) { ready = true; break; }
}
if (ready) {
// Read Design Energy at data memory address 0x92A1
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x3E); Wire.write(0xA1); Wire.write(0x92);
Wire.endTransmission();
delay(10);
uint8_t oldMSB = bq27220_read8(0x40);
uint8_t oldLSB = bq27220_read8(0x41);
uint16_t currentDE = (oldMSB << 8) | oldLSB;
if (currentDE != designEnergy) {
// Design Energy actually needs updating — write it
uint8_t oldChk = bq27220_read8(0x60);
uint8_t dLen = bq27220_read8(0x61);
uint8_t newMSB = (designEnergy >> 8) & 0xFF;
uint8_t newLSB = designEnergy & 0xFF;
uint8_t temp = (255 - oldChk - oldMSB - oldLSB);
uint8_t newChk = 255 - ((temp + newMSB + newLSB) & 0xFF);
Serial.printf("BQ27220: DE old=%d new=%d mWh, writing\n", currentDE, designEnergy);
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x3E); Wire.write(0xA1); Wire.write(0x92);
Wire.write(newMSB); Wire.write(newLSB);
Wire.endTransmission();
delay(5);
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x60); Wire.write(newChk); Wire.write(dLen);
Wire.endTransmission();
delay(10);
// Exit with reinit since we actually changed data
bq27220_writeControl(0x0091); // EXIT_CFG_UPDATE_REINIT
delay(200);
Serial.println("BQ27220: Design Energy written, exited CFG_UPDATE");
} else {
// DC=2000, DE=7400, Update Status=0x00, but FCC is stuck at 3000.
// Diagnostic scan found the culprits:
// 0x9106 = Qmax Cell 0 (IT Cfg class) — the raw capacity the
// gauge uses for FCC calculation. Factory default 3000.
// 0x929D = Stored FCC reference (Gas Gauging class, 2 bytes
// before Design Capacity). Also stuck at 3000.
//
// Fix: overwrite both with designCapacity_mAh (2000).
Serial.printf("BQ27220: DE correct (%d mWh) — fixing Qmax + stored FCC\n", currentDE);
// --- Helper lambda for MAC data memory 2-byte write ---
// Reads old value + checksum, computes differential checksum, writes new value.
auto writeDM16 = [](uint16_t addr, uint16_t newVal) -> bool {
// Select address
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x3E);
Wire.write(addr & 0xFF);
Wire.write((addr >> 8) & 0xFF);
Wire.endTransmission();
delay(10);
uint8_t oldMSB = bq27220_read8(0x40);
uint8_t oldLSB = bq27220_read8(0x41);
uint8_t oldChk = bq27220_read8(0x60);
uint8_t dLen = bq27220_read8(0x61);
uint16_t oldVal = (oldMSB << 8) | oldLSB;
if (oldVal == newVal) {
Serial.printf("BQ27220: [0x%04X] already %d, skip\n", addr, newVal);
return true; // already correct
}
uint8_t newMSB = (newVal >> 8) & 0xFF;
uint8_t newLSB = newVal & 0xFF;
uint8_t temp = (255 - oldChk - oldMSB - oldLSB);
uint8_t newChk = 255 - ((temp + newMSB + newLSB) & 0xFF);
Serial.printf("BQ27220: [0x%04X] %d -> %d\n", addr, oldVal, newVal);
// Write new value
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x3E);
Wire.write(addr & 0xFF);
Wire.write((addr >> 8) & 0xFF);
Wire.write(newMSB);
Wire.write(newLSB);
Wire.endTransmission();
delay(5);
// Write checksum
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x60);
Wire.write(newChk);
Wire.write(dLen);
Wire.endTransmission();
delay(10);
return true;
};
// Overwrite Qmax Cell 0 (IT Cfg) — this is what FCC is derived from
writeDM16(0x9106, designCapacity_mAh);
// Overwrite stored FCC reference (Gas Gauging, 2 bytes before DC)
writeDM16(0x929D, designCapacity_mAh);
// Exit with reinit to apply the new values
bq27220_writeControl(0x0091); // EXIT_CFG_UPDATE_REINIT
delay(200);
Serial.println("BQ27220: Qmax + stored FCC updated, exited CFG_UPDATE");
}
} else {
Serial.println("BQ27220: Failed to enter CFG_UPDATE for DE check");
}
// Seal first, then issue RESET.
// RESET forces the gauge to fully reinitialize its Impedance Track
// algorithm and recalculate FCC from the current DC/DE values.
// This is the actual fix when DC and DE are correct but FCC is stuck.
bq27220_writeControl(0x0030); // SEAL
delay(5);
Serial.println("BQ27220: Issuing RESET to force FCC recalculation...");
bq27220_writeControl(0x0041); // RESET
delay(2000); // Full reset needs generous settle time
fcc = bq27220_read16(BQ27220_REG_FULL_CAP);
Serial.printf("BQ27220: FCC after RESET: %d mAh (target <= %d)\n", fcc, designCapacity_mAh);
if (fcc > designCapacity_mAh * 3 / 2) {
// RESET didn't fix FCC — the gauge IT algorithm is stubbornly
// retaining its learned value. This typically resolves after one
// full charge/discharge cycle. Software clamp in
// getFullChargeCapacity() ensures correct display regardless.
Serial.printf("BQ27220: FCC still stale at %d — software clamp active\n", fcc);
}
}
Serial.println("BQ27220: Design Capacity already correct, skipping");
return true;
}
@@ -455,39 +281,6 @@ bool TDeckBoard::configureFuelGauge(uint16_t designCapacity_mAh) {
Serial.printf("BQ27220: Verify in CFGUPDATE: DC bytes=0x%02X 0x%02X (%d mAh)\n",
verMSB, verLSB, (verMSB << 8) | verLSB);
// Step 4g: Also update Design Energy (address 0x92A1) while in CFG_UPDATE.
// Design Energy = capacity × 3.7V (nominal LiPo voltage).
// The gauge uses both DC and DE to compute Full Charge Capacity.
{
uint16_t designEnergy = (uint16_t)((uint32_t)designCapacity_mAh * 37 / 10);
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x3E); Wire.write(0xA1); Wire.write(0x92);
Wire.endTransmission();
delay(10);
uint8_t deOldMSB = bq27220_read8(0x40);
uint8_t deOldLSB = bq27220_read8(0x41);
uint8_t deOldChk = bq27220_read8(0x60);
uint8_t deLen = bq27220_read8(0x61);
uint8_t deNewMSB = (designEnergy >> 8) & 0xFF;
uint8_t deNewLSB = designEnergy & 0xFF;
uint8_t deTemp = (255 - deOldChk - deOldMSB - deOldLSB);
uint8_t deNewChk = 255 - ((deTemp + deNewMSB + deNewLSB) & 0xFF);
Serial.printf("BQ27220: Design Energy: old=%d new=%d mWh\n",
(deOldMSB << 8) | deOldLSB, designEnergy);
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x3E); Wire.write(0xA1); Wire.write(0x92);
Wire.write(deNewMSB); Wire.write(deNewLSB);
Wire.endTransmission();
delay(5);
Wire.beginTransmission(BQ27220_I2C_ADDR);
Wire.write(0x60); Wire.write(deNewChk); Wire.write(deLen);
Wire.endTransmission();
delay(10);
}
// Step 5: Exit CFG_UPDATE (with reinit to apply changes immediately)
bq27220_writeControl(0x0091); // EXIT_CFG_UPDATE_REINIT
Serial.println("BQ27220: Sent EXIT_CFG_UPDATE_REINIT, waiting...");
@@ -498,30 +291,16 @@ bool TDeckBoard::configureFuelGauge(uint16_t designCapacity_mAh) {
Serial.printf("BQ27220: Design Capacity now reads %d mAh (expected %d)\n",
verifyDC, designCapacity_mAh);
uint16_t newFCC = bq27220_read16(BQ27220_REG_FULL_CAP);
Serial.printf("BQ27220: Full Charge Capacity: %d mAh\n", newFCC);
if (verifyDC == designCapacity_mAh) {
Serial.println("BQ27220: Configuration SUCCESS");
} else {
Serial.println("BQ27220: Configuration FAILED");
}
// Step 6: Seal the device
// Step 7: Seal the device
bq27220_writeControl(0x0030);
delay(5);
// Step 7: Force full gauge RESET to reinitialize FCC from new DC/DE.
// Without this, the Impedance Track algorithm retains the old FCC
// (often 3000 mAh from factory) until a full charge/discharge cycle.
bq27220_writeControl(0x0041); // RESET
delay(1000); // Gauge needs time to fully reinitialize
// Re-verify after hard reset
verifyDC = bq27220_read16(BQ27220_REG_DESIGN_CAP);
newFCC = bq27220_read16(BQ27220_REG_FULL_CAP);
Serial.printf("BQ27220: Post-RESET DC=%d FCC=%d mAh\n", verifyDC, newFCC);
return verifyDC == designCapacity_mAh;
#else
return false;
@@ -562,12 +341,7 @@ uint16_t TDeckBoard::getRemainingCapacity() {
uint16_t TDeckBoard::getFullChargeCapacity() {
#if HAS_BQ27220
uint16_t fcc = bq27220_read16(BQ27220_REG_FULL_CAP);
// Clamp to design capacity — the gauge may report a stale factory FCC
// (e.g. 3000 mAh) until it completes a full learning cycle. Never let
// the reported FCC exceed what the actual cell can hold.
if (fcc > BQ27220_DESIGN_CAPACITY_MAH) fcc = BQ27220_DESIGN_CAPACITY_MAH;
return fcc;
return bq27220_read16(BQ27220_REG_FULL_CAP);
#else
return 0;
#endif

View File

@@ -256,12 +256,14 @@ public:
return KB_KEY_EMOJI;
}
// Handle Mic key - always produces '0' (silk-screened on key)
// Sym+Mic also produces '0' (consumes sym so it doesn't leak)
// Handle Mic key - produces 0 with Sym, otherwise ignore
if (keyCode == 34) {
_symActive = false;
Serial.println("KB: Mic -> '0'");
return '0';
if (_symActive) {
_symActive = false;
Serial.println("KB: Sym+Mic -> '0'");
return '0';
}
return 0; // Ignore mic without Sym
}
// Get the character

View File

@@ -62,8 +62,6 @@ build_flags =
-D EINK_MOSI=33
-D EINK_BL=45
-D EINK_NOT_HIBERNATE=1
-D HAS_BQ27220=1
-D AUTO_SHUTDOWN_MILLIVOLTS=2800
-D EINK_LIMIT_FASTREFRESH=10
-D EINK_LIMIT_GHOSTING_PX=2000
-D DISPLAY_ROTATION=0
@@ -82,6 +80,7 @@ build_flags =
-D PIN_DISPLAY_BL=45
-D PIN_USER_BTN=0
-D CST328_PIN_RST=38
-D FIRMWARE_VERSION='"Meck v0.9.3A"'
-D ARDUINO_LOOP_STACK_SIZE=32768
build_src_filter = ${esp32_base.build_src_filter}
+<../variants/LilyGo_TDeck_Pro>
@@ -91,58 +90,24 @@ lib_deps =
${sensor_base.lib_deps}
zinggjm/GxEPD2@^1.5.9
adafruit/Adafruit GFX Library@^1.11.0
bitbank2/PNGdec@^1.0.1
bakercp/CRC32@^2.0.0
; ---------------------------------------------------------------------------
; Meck unified builds — one codebase, six variants via build flags
; Meck unified builds — one codebase, three variants via build flags
; ---------------------------------------------------------------------------
; Audio + BLE companion (audio-player hardware with BLE phone bridging)
; MAX_CONTACTS=500 is near BLE protocol ceiling (MAX_CONTACTS/2 sent as uint8_t, max 510)
[env:meck_audio_ble]
extends = LilyGo_TDeck_Pro
build_flags =
${LilyGo_TDeck_Pro.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=500
-D MAX_CONTACTS=400
-D MAX_GROUP_CHANNELS=20
-D BLE_PIN_CODE=123456
-D OFFLINE_QUEUE_SIZE=256
-D MECK_AUDIO_VARIANT
-D MECK_WEB_READER=1
build_src_filter = ${LilyGo_TDeck_Pro.build_src_filter}
+<helpers/esp32/*.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
+<helpers/ui/GxEPDDisplay.cpp>
lib_deps =
${LilyGo_TDeck_Pro.lib_deps}
densaugeo/base64 @ ~1.4.0
https://github.com/schreibfaul1/ESP32-audioI2S.git#2.0.6
bitbank2/JPEGDEC
; Audio + WiFi companion (audio-player hardware with WiFi app bridging)
; No BLE — WiFi companion uses SerialWifiInterface (TCP socket on port 5000).
; Connect via MeshCore web app, meshcore.js, or Python CLI over local network.
; No BLE protocol ceiling on contacts; bumped to 1500 (PSRAM-backed).
; WiFi always on from boot — web reader works without teardown, extra free heap.
; WiFi credentials loaded from SD card at runtime (/web/wifi.cfg).
; Configure via Settings > WiFi Setup, or through the web reader.
[env:meck_audio_wifi]
extends = LilyGo_TDeck_Pro
build_flags =
${LilyGo_TDeck_Pro.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=1500
-D MAX_GROUP_CHANNELS=20
-D MECK_WIFI_COMPANION=1
-D TCP_PORT=5000
-D WIFI_DEBUG_LOGGING=1
-D OFFLINE_QUEUE_SIZE=256
-D MECK_AUDIO_VARIANT
-D MECK_WEB_READER=1
-D FIRMWARE_VERSION='"Meck v0.9.9WiFi"'
; -D MECK_WEB_READER=1
build_src_filter = ${LilyGo_TDeck_Pro.build_src_filter}
+<helpers/esp32/*.cpp>
+<helpers/ui/MomentaryButton.cpp>
@@ -157,14 +122,13 @@ lib_deps =
; Audio standalone (audio-player hardware, no BLE/WiFi — maximum battery life)
; No MECK_WEB_READER: WiFi power draw conflicts with zero-radio-power design.
; Contacts and sort arrays allocated in PSRAM — 1500 contacts uses ~290KB of 8MB.
[env:meck_audio_standalone]
extends = LilyGo_TDeck_Pro
build_flags =
${LilyGo_TDeck_Pro.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=1500
-D MAX_GROUP_CHANNELS=20
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D OFFLINE_QUEUE_SIZE=256
-D MECK_AUDIO_VARIANT
build_src_filter = ${LilyGo_TDeck_Pro.build_src_filter}
@@ -180,75 +144,18 @@ lib_deps =
bitbank2/JPEGDEC
; 4G + BLE companion (4G modem hardware, no audio — GPIO conflict with PCM5102A)
; MAX_CONTACTS=500 is near BLE protocol ceiling (MAX_CONTACTS/2 sent as uint8_t, max 510)
[env:meck_4g_ble]
extends = LilyGo_TDeck_Pro
build_flags =
${LilyGo_TDeck_Pro.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=500
-D MAX_CONTACTS=400
-D MAX_GROUP_CHANNELS=20
-D BLE_PIN_CODE=123456
-D OFFLINE_QUEUE_SIZE=256
-D HAS_4G_MODEM=1
-D MECK_WEB_READER=1
-D FIRMWARE_VERSION='"Meck v0.9.94G"'
build_src_filter = ${LilyGo_TDeck_Pro.build_src_filter}
+<helpers/esp32/*.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
+<helpers/ui/GxEPDDisplay.cpp>
lib_deps =
${LilyGo_TDeck_Pro.lib_deps}
densaugeo/base64 @ ~1.4.0
; 4G + WiFi companion (4G modem hardware with WiFi app bridging, no audio)
; No BLE — WiFi companion uses SerialWifiInterface (TCP socket on port 5000).
; Connect via MeshCore web app, meshcore.js, or Python CLI over local network.
; WiFi credentials loaded from SD card at runtime (/web/wifi.cfg).
; Configure via Settings > WiFi Setup, or through the web reader.
; Contacts and sort arrays allocated in PSRAM — 1500 contacts uses ~290KB of 8MB.
[env:meck_4g_wifi]
extends = LilyGo_TDeck_Pro
build_flags =
${LilyGo_TDeck_Pro.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=1500
-D MAX_GROUP_CHANNELS=20
-D MECK_WIFI_COMPANION=1
-D TCP_PORT=5000
-D WIFI_DEBUG_LOGGING=1
-D OFFLINE_QUEUE_SIZE=256
-D HAS_4G_MODEM=1
-D MECK_WEB_READER=1
-D FIRMWARE_VERSION='"Meck v0.9.94G.WiFi"'
build_src_filter = ${LilyGo_TDeck_Pro.build_src_filter}
+<helpers/esp32/*.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
+<helpers/ui/GxEPDDisplay.cpp>
lib_deps =
${LilyGo_TDeck_Pro.lib_deps}
densaugeo/base64 @ ~1.4.0
; 4G standalone (4G modem hardware, no BLE — maximum battery + cellular features)
; No BLE_PIN_CODE: BLE never initializes, saving ~30KB heap + radio power.
; MECK_WEB_READER enabled: works better without BLE (no teardown dance needed,
; more free heap from boot). WiFi-first with cellular PPP fallback (future).
; Contacts and sort arrays allocated in PSRAM — 1500 contacts uses ~290KB of 8MB.
[env:meck_4g_standalone]
extends = LilyGo_TDeck_Pro
build_flags =
${LilyGo_TDeck_Pro.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=1500
-D MAX_GROUP_CHANNELS=20
-D OFFLINE_QUEUE_SIZE=256
-D HAS_4G_MODEM=1
-D MECK_WEB_READER=1
-D FIRMWARE_VERSION='"Meck v0.9.94G.SA"'
; -D MECK_WEB_READER=1
-D FIRMWARE_VERSION='"Meck v0.9.3-4G"'
build_src_filter = ${LilyGo_TDeck_Pro.build_src_filter}
+<helpers/esp32/*.cpp>
+<helpers/ui/MomentaryButton.cpp>