merge: bring eink-ui into wio-eink-unified

This commit is contained in:
Jakub
2026-05-23 10:21:23 +02:00
58 changed files with 8374 additions and 662 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
README.md merge=ours

View File

@@ -22,8 +22,10 @@ runs:
pip install --upgrade platformio
# a git tag of "room-server-v1.2.3" should set "v1.2.3" as GIT_TAG_VERSION
# a git tag of "wio-tracker-v1.15-plus.1.3" should set "v1.15-plus.1.3" as GIT_TAG_VERSION
# Strip the shortest prefix ending with "-v" so hyphens in the version are preserved.
- name: Extract Version from Git Tag
shell: bash
run: |
GIT_TAG_NAME="${GITHUB_REF#refs/tags/}"
echo "GIT_TAG_VERSION=${GIT_TAG_NAME##*-}" >> $GITHUB_ENV
echo "GIT_TAG_VERSION=v${GIT_TAG_NAME#*-v}" >> $GITHUB_ENV

View File

@@ -9,6 +9,9 @@ on:
tags:
- 'companion-*'
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
jobs:
build:

View File

@@ -9,6 +9,9 @@ on:
tags:
- 'repeater-*'
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
jobs:
build:

View File

@@ -9,6 +9,9 @@ on:
tags:
- 'room-server-*'
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
jobs:
build:

View File

@@ -0,0 +1,90 @@
name: Build Wio Tracker L1 Firmwares
permissions:
contents: write
on:
workflow_dispatch:
push:
tags:
- 'wio-tracker-v*'
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
jobs:
build-oled:
runs-on: ubuntu-latest
steps:
- name: Clone Repo
uses: actions/checkout@v4
with:
ref: wio-tracker-l1-improvements
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Build Dual OLED Firmware
env:
FIRMWARE_VERSION: ${{ env.GIT_TAG_VERSION }}
run: /usr/bin/env bash build.sh build-wio-tracker-l1-firmwares
- name: Upload OLED Firmware
uses: actions/upload-artifact@v4
with:
name: wio-tracker-l1-oled-firmware
path: out
build-eink:
runs-on: ubuntu-latest
steps:
- name: Clone Repo
uses: actions/checkout@v4
with:
ref: eink-ui
- name: Setup Build Environment
uses: ./.github/actions/setup-build-environment
- name: Build Dual E-ink Firmware
env:
FIRMWARE_VERSION: ${{ env.GIT_TAG_VERSION }}
run: /usr/bin/env bash build.sh build-firmware WioTrackerL1Eink_companion_radio_dual
- name: Upload E-ink Firmware
uses: actions/upload-artifact@v4
with:
name: wio-tracker-l1-eink-firmware
path: out
release:
needs: [build-oled, build-eink]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
steps:
- name: Extract Version from Git Tag
run: echo "GIT_TAG_VERSION=v${GITHUB_REF_NAME#*-v}" >> $GITHUB_ENV
- name: Download OLED Firmware
uses: actions/download-artifact@v4
with:
name: wio-tracker-l1-oled-firmware
path: out
- name: Download E-ink Firmware
uses: actions/download-artifact@v4
with:
name: wio-tracker-l1-eink-firmware
path: out
- name: Create Release
uses: softprops/action-gh-release@v2
with:
name: Wio Tracker L1 Firmware ${{ env.GIT_TAG_VERSION }}
body: ""
draft: true
files: out/*.uf2

View File

@@ -9,6 +9,9 @@ on:
permissions:
contents: write
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
jobs:
github-pages:
runs-on: ubuntu-latest

View File

@@ -18,6 +18,9 @@ on:
- 'platformio.ini'
- '.github/workflows/pr-build-check.yml'
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
jobs:
build:
runs-on: ubuntu-latest

255
README.md
View File

@@ -1,120 +1,205 @@
## About MeshCore
# Wio Tracker L1 — Extended Companion Radio Firmware
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.
This branch extends the official MeshCore companion radio firmware for the **Seeed Wio Tracker L1**.
## 🔍 What is MeshCore?
Join the discussion on offical MeshCore discord: https://discord.gg/sdhYArU2jr
MeshCore now supports a range of LoRa devices, allowing for easy flashing without the need to compile firmware manually. Users can flash a pre-built binary using tools like Adafruit ESPTool and interact with the network through a serial console.
MeshCore provides the ability to create wireless mesh networks, similar to Meshtastic and Reticulum but with a focus on lightweight multi-hop packet routing for embedded projects. Unlike Meshtastic, which is tailored for casual LoRa communication, or Reticulum, which offers advanced networking, MeshCore balances simplicity with scalability, making it ideal for custom embedded solutions., where devices (nodes) can communicate over long distances by relaying messages through intermediate nodes. This is especially useful in off-grid, emergency, or tactical situations where traditional communication infrastructure is unavailable.
## New Features
## ⚡ Key Features
### Messages Screen
* Multi-Hop Packet Routing
* Devices can forward messages across multiple nodes, extending range beyond a single radio's reach.
* Supports up to a configurable number of hops to balance network efficiency and prevent excessive traffic.
* Nodes use fixed roles where "Companion" nodes are not repeating messages at all to prevent adverse routing paths from being used.
* Supports LoRa Radios Works with Heltec, RAK Wireless, and other LoRa-based hardware.
* Decentralized & Resilient No central server or internet required; the network is self-healing.
* Low Power Consumption Ideal for battery-powered or solar-powered devices.
* Simple to Deploy Pre-built example applications make it easy to get started.
View and send messages using the on-screen keyboard or predefined quick replies. The keyboard supports placeholders that insert live sensor data — `{time}` and `{loc}` are always available; additional placeholders (`{temp}`, `{hum}`, `{pres}`, `{batt}`, `{alt}`, `{lux}`, `{co2}`) appear automatically for sensors that are connected and returning data.
## 🎯 What Can You Use MeshCore For?
Each message in the history list shows the sender name and a compact age indicator (`3m`, `2h`, `>1d`) in the top-right corner of the entry.
* Off-Grid Communication: Stay connected even in remote areas.
* Emergency Response & Disaster Recovery: Set up instant networks where infrastructure is down.
* Outdoor Activities: Hiking, camping, and adventure racing communication.
* Tactical & Security Applications: Military, law enforcement, and private security use cases.
* IoT & Sensor Networks: Collect data from remote sensors and relay it back to a central location.
```
╔══════════════════════════════╗
║ #general ║
╠══════════════════════════════╣
║▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ║ ← selected
║ Alice 3m ║
║ Hey, let's meet tomorrow ║
║┌───────────────────────────┐ ║
║│▓▓▓▓▓▓▓▓▓ Bob 1h ▓▓▓▓ │ ║
║│ Sure, what time works? │ ║
║└───────────────────────────┘ ║
║[+ send] ║
╚══════════════════════════════╝
```
## 🚀 How to Get Started
Press Enter on a message to open it in fullscreen. Navigate between messages with left (newer) and right (older). If the message is a reply addressed to someone (`@[nick]`), a **To: nick** bar is shown below the sender name and the body is displayed without the address prefix.
- Watch the [MeshCore Intro Video](https://www.youtube.com/watch?v=t1qne8uJBAc) by Andy Kirby.
- Watch the [MeshCore Technical Presentation](https://www.youtube.com/watch?v=OwmkVkZQTf4) by Liam Cottle.
- Read through our [Frequently Asked Questions](./docs/faq.md) and [Documentation](https://docs.meshcore.io).
- Flash the MeshCore firmware on a supported device.
- Connect with a supported client.
```
╔══════════════════════════════╗
║▓▓ Alice ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ║ ← sender
║▓▓ To: Bob ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ║ ← recipient
╠══════════════════════════════╣
║ Hey Bob, let's meet up ║
║ tomorrow at 6pm downtown. ║
║ Will you make it? ║
║ ║
║< newer older >║
╚══════════════════════════════╝
```
For developers;
Hold Enter on a message to open a context menu. From the list or fullscreen view, select **Reply** to pre-fill the keyboard or a quick message with `@[nick]` so the recipient is clearly addressed. The reply picker title shows the recipient's name.
- Install [PlatformIO](https://docs.platformio.org) in [Visual Studio Code](https://code.visualstudio.com).
- Clone and open the MeshCore repository in Visual Studio Code.
- See the example applications you can modify and run:
- [Companion Radio](./examples/companion_radio) - For use with an external chat app, over BLE, USB or WiFi.
- [KISS Modem](./examples/kiss_modem) - Serial KISS protocol bridge for host applications. ([protocol docs](./docs/kiss_modem_protocol.md))
- [Simple Repeater](./examples/simple_repeater) - Extends network coverage by relaying messages.
- [Simple Room Server](./examples/simple_room_server) - A simple BBS server for shared Posts.
- [Simple Secure Chat](./examples/simple_secure_chat) - Secure terminal based text communication between devices.
- [Simple Sensor](./examples/simple_sensor) - Remote sensor node with telemetry and alerting.
```
╔══════════════════════════════╗
║ RE:Alice ║
╠══════════════════════════════╣
║> Custom message... ║
OK, I understand ║
On my way ║
Be right there ║
╚══════════════════════════════╝
```
The Simple Secure Chat example can be interacted with through the Serial Monitor in Visual Studio Code, or with a Serial USB Terminal on Android.
On channel or contact list entries, the context menu also lets you change per-channel notification settings (mute, follow global, or force-on), per-channel melody override (follow global, Melody 1, or Melody 2), or mark messages as read.
## ⚡️ MeshCore Flasher
### Settings Screen
We have prebuilt firmware ready to flash on supported devices.
All settings are saved to flash and restored on next boot.
- Launch https://meshcore.io/flasher
- Select a supported device
- Flash one of the firmware types:
- Companion, Repeater or Room Server
- Once flashing is complete, you can connect with one of the MeshCore clients below.
- **Display**
- Brightness
- Auto-off timeout
- Battery display mode (icon, %, V)
- Clock seconds (show/hide — hiding reduces display refresh from 1 s to 60 s)
- Font — **Default** (5×7 Adafruit, ASCII + transliteration) or **Lemon** (native Unicode, available in the `font-switcher` build only)
- **Sound**
- Buzzer: On / Off / **Auto** — Auto mode silences the device while connected via Bluetooth, and re-enables sound when the connection drops
- Volume (15; preview tone plays on each change)
- DM Melody — notification sound for incoming private messages: built-in, Melody 1, or Melody 2
- Channel Melody — notification sound for incoming channel messages: built-in, Melody 1, or Melody 2
- **Home Pages** — toggle visibility of individual home screen pages
- **Radio**
- TX power
- **System**
- Timezone (UTC offset in hours)
- Low battery shutdown threshold
- Auto-lock — automatically locks the device when the display turns off
- **GPS**
- Position broadcast interval
- **Contacts**
- Show all DMs or favourites only
- Show all room servers or favourites only
- **Messages**
- Edit up to 10 quick reply templates (Q1Q10)
## 📱 MeshCore Clients
### Clock Screen
**Companion Firmware**
A dedicated clock page on the home screen shows the current time and date, synchronized from GPS or via Bluetooth. Timezone offset is applied from Settings.
The companion firmware can be connected to via BLE, USB or WiFi depending on the firmware type you flashed.
Up to three configurable data fields are displayed below the clock. Available fields: battery voltage, temperature, humidity, pressure, GPS coordinates, altitude, luminosity, CO₂, contact count, and total unread message count.
- Web: https://app.meshcore.nz
- Android: https://play.google.com/store/apps/details?id=com.liamcottle.meshcore.android
- iOS: https://apps.apple.com/us/app/meshcore/id6742354151?platform=iphone
- NodeJS: https://github.com/liamcottle/meshcore.js
- Python: https://github.com/fdlamotte/meshcore-cli
### Screen Lock
**Repeater and Room Server Firmware**
Hold **Back** and press **Enter** three times to lock or unlock the device. While locked:
The repeater and room server firmwares can be setup via USB in the web config tool.
- The display turns off and ignores incoming keypresses
- A brief button press shows the lock screen: current time, date, and up to two sensor values (reuses the Dashboard Config fields)
- A hint popup guides through the unlock sequence
- **Auto-lock** (configurable in Settings → System) locks automatically when the display turns off
- https://config.meshcore.io
### Nearby Nodes
They can also be managed via LoRa in the mobile app by using the Remote Management feature.
Browse nodes that have recently advertised on the mesh. Filter by category (Favourites, All, Companion, Repeater, Room, Sensor). Select a node to see its coordinates, distance, bearing with cardinal direction, type, and last-heard time.
## 🛠 Hardware Compatibility
```
╔══════════════════════════════╗
║▓▓▓▓▓ WioTracker-Alice ▓▓▓▓▓▓ ║ ← node name
╠══════════════════════════════╣
║ Lat: 50.06190 ║
║ Lon: 19.94090 ║
║ Dist: 2.3km ║
║ Az: 145d (SE) ║
║ Type: Companion ║
║ Seen: 5m ago ║
╚══════════════════════════════╝
```
MeshCore is designed for devices listed in the [MeshCore Flasher](https://meshcore.io/flasher)
Use **Send my advert** (hold Enter → context menu) to broadcast your position and prompt nearby nodes to respond with theirs.
## 📜 License
#### Active Discovery
MeshCore is open-source software released under the MIT License. You are free to use, modify, and distribute it for personal and commercial projects.
Press **Enter** from the Nearby screen to send a live `NODE_DISCOVER_REQ` ping. All reachable repeaters, sensors and room servers within zero-hop range respond immediately with their name, type and signal data. Results appear as 2-line boxed cards with RSSI, SNR and the remote SNR (signal quality at the responder's end).
## Contributing
```
╔═══════════════════════════════╗
║▓▓▓▓▓▓▓ DISCOVER (2 found) ▓▓ ║
╠═══════════════════════════════╣
║▓▓▓▓▓▓▓▓▓▓▓▓▓ Rptr-A Rpt ▓▓▓▓║ ← selected
║▓▓▓▓▓▓▓▓ RSSI:-79 SNR:9 ▓▓▓▓▓▓▓║
║┌────────────────────────────┐ ║
║│▓▓▓▓▓▓▓▓▓▓▓▓ Sensor-B Snsr │ ║
║│ RSSI:-94 SNR:3 │ ║
║└────────────────────────────┘ ║
╚═══════════════════════════════╝
```
Please submit PR's using 'dev' as the base branch!
For minor changes just submit your PR and we'll try to review it, but for anything more 'impactful' please open an Issue first and start a discussion. Is better to sound out what it is you want to achieve first, and try to come to a consensus on what the best approach is, especially when it impacts the structure or architecture of this codebase.
Navigate with **UP/DOWN**. Press **Enter** on a node to open a full-screen detail view showing the public key, RSSI, SNR, remote SNR and whether the node is already in your contacts.
Here are some general principals you should try to adhere to:
* Keep it simple. Please, don't think like a high-level lang programmer. Think embedded, and keep code concise, without any unnecessary layers.
* No dynamic memory allocation, except during setup/begin functions.
* Use the same brace and indenting style that's in the core source modules. (A .clang-format is prob going to be added soon, but please do NOT retroactively re-format existing code. This just creates unnecessary diffs that make finding problems harder)
```
╔══════════════════════════════╗
║▓▓▓▓▓▓▓▓▓▓▓▓▓ Rptr-A ▓▓▓▓▓▓▓ ║
╠══════════════════════════════╣
║ Key: ABCdef12XYZ... ║
║ RSSI: -79 dBm ║
║ SNR: 9 dB ║
║ Rem: 6 dB ║
║ Status: known ║
╚══════════════════════════════╝
```
Help us prioritize! Please react with thumbs-up to issues/PRs you care about most. We look at reaction counts when planning work.
Hold **Enter** from the discovery list to rescan. Press **Cancel** or **Back** to return.
## Road-Map / To-Do
### Tools Screen
There are a number of fairly major features in the pipeline, with no particular time-frames attached yet. In very rough chronological order:
- [X] Companion radio: UI redesign
- [X] Repeater + Room Server: add ACL's (like Sensor Node has)
- [X] Standardise Bridge mode for repeaters
- [ ] Repeater/Bridge: Standardise the Transport Codes for zoning/filtering
- [X] Core + Repeater: enhanced zero-hop neighbour discovery
- [ ] Core: round-trip manual path support
- [ ] Companion + Apps: support for multiple sub-meshes (and 'off-grid' client repeat mode)
- [ ] Core + Apps: support for LZW message compression
- [ ] Core: dynamic CR (Coding Rate) for weak vs strong hops
- [ ] Core: new framework for hosting multiple virtual nodes on one physical device
- [ ] V2 protocol spec: discussion and consensus around V2 packet protocol, including path hashes, new encryption specs, etc
#### Auto-Advert
## 📞 Get Support
Periodically broadcasts a 0-hop advert with your GPS position so nearby nodes can track your location automatically. Configurable interval: off / 1 min / 2 min / 5 min / 10 min / 30 min / 1 h.
- Report bugs and request features on the [GitHub Issues](https://github.com/ripplebiz/MeshCore/issues) page.
- Find additional guides and components on [my site](https://buymeacoffee.com/ripplebiz).
- Join [MeshCore Discord](https://meshcore.gg) to chat with the developers and get help from the community.
A blinking **A** indicator appears in the status bar while Auto-Advert is active.
#### Ringtone Editor
A step sequencer for composing custom notification melodies stored on the device. Two independent melody slots are available — **Melody 1** and **Melody 2** — switchable from within the editor. Each melody supports up to 32 notes with adjustable pitch (CB + pause), octave (47), duration (whole / half / quarter / eighth), and BPM (60 / 90 / 120 / 150 / 180). Playback preview is available directly from the editor.
Melodies can be assigned as notification sounds per message type (DM / channel) in Settings, and individually overridden per channel or per contact from the message screen context menu.
#### Auto-Reply Bot
Automatically replies to incoming messages that contain a configured trigger word (case-insensitive).
- **DM mode** — when enabled, the bot listens to all incoming private messages and replies with the DM reply text.
- **Channel mode** — optionally, select a channel for the bot to monitor. When a trigger is matched, it replies with a separate channel reply text.
- Both modes can be active simultaneously and share the same trigger word but use independent reply texts.
- Replies support placeholders (`{time}`, `{loc}`).
- A 10-second cooldown prevents repeated replies in quick succession.
---
## Font Switcher Build
An alternative firmware build is available (`font-switcher` in the filename). It includes both the default 5×7 Adafruit font and the [Lemon bitmap font](https://github.com/cmvnd/fonts), switchable at runtime in **Settings → Display → Font** without reflashing. The selected font is saved to flash and takes effect immediately.
The Lemon font offers:
- **Native Unicode rendering** — Latin Extended, Greek, and Cyrillic characters (U+0020U+04FF) are displayed directly without transliteration, covering Polish, Czech, Slovak, German, French, Scandinavian, Hungarian, Romanian, Croatian, Turkish, Baltic, Russian, and Greek scripts.
- **Pixel-accurate word wrap** — text wraps based on actual glyph widths rather than a fixed character count.
- **Slightly taller glyphs** — the font uses a 10 px line height compared to 8 px for the default font.
Prebuilt `.uf2` files for the font-switcher variant are included in each release alongside the standard builds and are identified by `font-switcher` in the filename.
---
Feel free to explore, share feedback and feature requests!
## Development
This fork tracks the upstream [MeshCore](https://github.com/ripplebiz/MeshCore) repository. To prevent upstream changes from overwriting this README during merges, `README.md` is protected via `.gitattributes`. After cloning, run once:
```sh
git config merge.ours.driver true
```

71
WIOTRACKER_L1.md Normal file
View File

@@ -0,0 +1,71 @@
# Wio Tracker L1 — Extended Companion Radio Firmware
This branch extends the official MeshCore companion radio firmware for the **Seeed Wio Tracker L1** (NRF52840 + SX1262 + SH1106 OLED 128×64 + GPS + buzzer + 5-way joystick).
## New Build Variants
In addition to the standard `_companion_radio_usb` and `_companion_radio_ble` builds, two new variants are available with a full **settings screen**:
| Environment | Interface |
|---|---|
| `WioTrackerL1_companion_radio_usb_settings` | USB serial |
| `WioTrackerL1_companion_radio_ble_settings` | Bluetooth LE |
The settings screen is accessed by navigating to the last page of the home screen and pressing Enter.
## New Features
### Settings Screen
All settings are saved to flash and restored on next boot.
| Setting | Options | Default |
|---|---|---|
| Display brightness | 5 levels (very dim → max) | Medium |
| Buzzer | ON / OFF | ON |
| TX Power | 2 22 dBm | Board default |
| Auto-off delay | 5 s / 15 s / 30 s / 60 s / never | 15 s |
| GPS update interval | off / 30 s / 1 min / 5 min / 15 min / 30 min | off |
| Timezone | UTC12 .. UTC+14 | UTC |
| Low battery shutdown | off / 3.0 V 3.5 V | 3.4 V |
| Battery display | icon / % / voltage | icon |
### Clock Screen
A dedicated clock page on the home screen shows the current time and date, synchronized from GPS. Timezone is applied from the settings above.
### Battery Display Modes
The top-right battery indicator can be switched between:
- **Icon** — classic fill bar
- **%** — percentage, where 0% = low battery shutdown threshold (if set), otherwise 3.2 V
- **V** — live voltage (e.g. `3.84V`)
Battery voltage is filtered with an exponential moving average (α = 0.2) to smooth out ADC noise from uneven load.
### Low Battery Auto-Shutdown
When the filtered battery voltage drops below the configured threshold, the device displays a warning on screen for 2 seconds and then shuts down gracefully. The threshold is configurable from the settings screen (3.0 V 3.5 V) or can be disabled.
## Bug Fixes
- **Buzzer mute at startup** — the saved mute preference is now respected during the startup sound; previously the buzzer was always unmuted on boot regardless of the saved setting.
- **Brightness change delay** — brightness changes are now applied instantly without triggering a flash write on every keypress; flash is written only when exiting the settings screen.
## Build & Release
Firmware is built automatically via GitHub Actions on every `wio-tracker-*` tag push.
Pre-built `.uf2` files are published in the [Releases](../../releases) section.
To flash: copy the `.uf2` file to the device while it is in bootloader mode (double-press reset).
## Syncing with Upstream
This branch tracks [meshcore-dev/MeshCore](https://github.com/meshcore-dev/MeshCore).
To pull upstream updates:
```bash
git fetch upstream
git rebase upstream/main
git push origin wio-tracker-l1-improvements --force-with-lease
```

View File

@@ -225,9 +225,15 @@ build_companion_firmwares() {
# build all companion firmwares
build_all_firmwares_by_suffix "_companion_radio_usb"
build_all_firmwares_by_suffix "_companion_radio_ble"
build_all_firmwares_by_suffix "_companion_radio_usb_settings"
build_all_firmwares_by_suffix "_companion_radio_ble_settings"
}
build_wio_tracker_l1_firmwares() {
build_firmware "WioTrackerL1_companion_radio_dual_settings"
}
build_room_server_firmwares() {
# # build specific room server firmwares
@@ -273,6 +279,8 @@ elif [[ $1 == "build-companion-firmwares" ]]; then
build_companion_firmwares
elif [[ $1 == "build-repeater-firmwares" ]]; then
build_repeater_firmwares
elif [[ $1 == "build-wio-tracker-l1-firmwares" ]]; then
build_wio_tracker_l1_firmwares
elif [[ $1 == "build-room-server-firmwares" ]]; then
build_room_server_firmwares
fi

View File

@@ -21,6 +21,8 @@ def create_uf2_action(source, target, env):
)
env.Execute(uf2_cmd)
env.AddPostAction(firmware_hex, create_uf2_action)
env.AddCustomTarget(
name="create_uf2",
dependencies=firmware_hex,

View File

@@ -40,7 +40,9 @@ public:
void enableSerial() { _serial->enable(); }
void disableSerial() { _serial->disable(); }
virtual void msgRead(int msgcount) = 0;
virtual void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) = 0;
virtual void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount, uint8_t contact_type = 0, const uint8_t* pub_key = nullptr) = 0;
virtual void notify(UIEventType t = UIEventType::none) = 0;
virtual void addChannelMsg(uint8_t channel_idx, const char* text) {}
virtual void addDMMsg(const uint8_t* pub_key, bool outgoing, const char* text) {}
virtual void loop() = 0;
};

View File

@@ -204,35 +204,122 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no
if (file) {
uint8_t pad[8];
file.read((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
file.read((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
file.read(pad, 4); // 36
file.read((uint8_t *)&node_lat, sizeof(node_lat)); // 40
file.read((uint8_t *)&node_lon, sizeof(node_lon)); // 48
file.read((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
file.read((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
file.read((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
file.read((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62
file.read((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
file.read((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
file.read((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
file.read((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
file.read((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
file.read((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
file.read((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
file.read((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
file.read((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
file.read((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78
file.read(pad, 1); // 79
file.read((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
file.read((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84
file.read((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85
file.read((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86
file.read((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87
file.read((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88
file.read((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89
file.read((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90
file.read((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121
file.read((uint8_t *)&_prefs.airtime_factor, sizeof(float));
file.read((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name));
file.read(pad, 4);
file.read((uint8_t *)&node_lat, sizeof(node_lat));
file.read((uint8_t *)&node_lon, sizeof(node_lon));
file.read((uint8_t *)&_prefs.freq, sizeof(_prefs.freq));
file.read((uint8_t *)&_prefs.sf, sizeof(_prefs.sf));
file.read((uint8_t *)&_prefs.cr, sizeof(_prefs.cr));
file.read((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat));
file.read((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts));
file.read((uint8_t *)&_prefs.bw, sizeof(_prefs.bw));
file.read((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm));
file.read((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base));
file.read((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc));
file.read((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env));
file.read((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base));
file.read((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy));
file.read((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks));
file.read((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode));
file.read(pad, 1);
file.read((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin));
file.read((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet));
file.read((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled));
file.read((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval));
file.read((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config));
file.read((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops));
file.read((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain));
file.read((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name));
file.read((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key));
file.read((uint8_t *)&_prefs.display_brightness, sizeof(_prefs.display_brightness));
file.read((uint8_t *)&_prefs.auto_off_secs, sizeof(_prefs.auto_off_secs));
file.read((uint8_t *)&_prefs.tz_offset_hours, sizeof(_prefs.tz_offset_hours));
file.read((uint8_t *)&_prefs.low_batt_mv, sizeof(_prefs.low_batt_mv));
file.read((uint8_t *)&_prefs.batt_display_mode, sizeof(_prefs.batt_display_mode));
if (file.available()) {
file.read((uint8_t *)_prefs.custom_msgs, sizeof(_prefs.custom_msgs));
file.read((uint8_t *)&_prefs.ch_notif_override, sizeof(_prefs.ch_notif_override));
file.read((uint8_t *)&_prefs.ch_notif_muted, sizeof(_prefs.ch_notif_muted));
file.read((uint8_t *)&_prefs.dm_show_all, sizeof(_prefs.dm_show_all));
file.read((uint8_t *)&_prefs.room_fav_only, sizeof(_prefs.room_fav_only));
if (file.available()) {
file.read((uint8_t *)&_prefs.buzzer_volume, sizeof(_prefs.buzzer_volume));
if (file.available()) {
file.read((uint8_t *)&_prefs.ringtone_bpm_idx, sizeof(_prefs.ringtone_bpm_idx));
file.read((uint8_t *)&_prefs.ringtone_len, sizeof(_prefs.ringtone_len));
if (_prefs.ringtone_len > 32) _prefs.ringtone_len = 0;
file.read((uint8_t *)_prefs.ringtone_notes, sizeof(_prefs.ringtone_notes));
if (file.available()) {
file.read((uint8_t *)&_prefs.home_pages_mask, sizeof(_prefs.home_pages_mask));
if (file.available()) {
file.read((uint8_t *)&_prefs.bot_enabled, sizeof(_prefs.bot_enabled));
file.read((uint8_t *)&_prefs.bot_channel_enabled, sizeof(_prefs.bot_channel_enabled));
file.read((uint8_t *)&_prefs.bot_channel_idx, sizeof(_prefs.bot_channel_idx));
file.read((uint8_t *)_prefs.bot_trigger, sizeof(_prefs.bot_trigger));
file.read((uint8_t *)_prefs.bot_reply_dm, sizeof(_prefs.bot_reply_dm));
file.read((uint8_t *)_prefs.bot_reply_ch, sizeof(_prefs.bot_reply_ch));
if (file.available()) {
file.read((uint8_t *)&_prefs.clock_hide_seconds, sizeof(_prefs.clock_hide_seconds));
if (file.available()) {
file.read((uint8_t *)&_prefs.buzzer_auto, sizeof(_prefs.buzzer_auto));
if (file.available()) {
file.read((uint8_t *)_prefs.dm_notif, sizeof(_prefs.dm_notif));
if (file.available()) {
file.read((uint8_t *)_prefs.dashboard_fields, sizeof(_prefs.dashboard_fields));
if (file.available()) {
file.read((uint8_t *)&_prefs.advert_auto_interval_sec, sizeof(_prefs.advert_auto_interval_sec));
if (file.available()) {
file.read((uint8_t *)&_prefs.ringtone2_bpm_idx, sizeof(_prefs.ringtone2_bpm_idx));
file.read((uint8_t *)&_prefs.ringtone2_len, sizeof(_prefs.ringtone2_len));
if (_prefs.ringtone2_len > 32) _prefs.ringtone2_len = 0;
file.read((uint8_t *)_prefs.ringtone2_notes, sizeof(_prefs.ringtone2_notes));
if (file.available()) {
file.read((uint8_t *)&_prefs.notif_melody_dm, sizeof(_prefs.notif_melody_dm));
file.read((uint8_t *)&_prefs.notif_melody_ch, sizeof(_prefs.notif_melody_ch));
if (file.available()) {
file.read((uint8_t *)&_prefs.ch_notif_melody_set, sizeof(_prefs.ch_notif_melody_set));
file.read((uint8_t *)&_prefs.ch_notif_melody_2, sizeof(_prefs.ch_notif_melody_2));
if (file.available()) {
file.read((uint8_t *)_prefs.dm_melody, sizeof(_prefs.dm_melody));
if (file.available()) {
file.read((uint8_t *)&_prefs.auto_lock, sizeof(_prefs.auto_lock));
if (file.available()) {
file.read((uint8_t *)&_prefs.clock_12h, sizeof(_prefs.clock_12h));
if (file.available()) {
file.read((uint8_t *)&_prefs.use_lemon_font, sizeof(_prefs.use_lemon_font));
if (file.available()) {
file.read((uint8_t *)&_prefs.display_rotation, sizeof(_prefs.display_rotation));
if (file.available()) {
file.read((uint8_t *)_prefs.page_order, sizeof(_prefs.page_order));
}
} else {
#ifdef DISPLAY_ROTATION
_prefs.display_rotation = DISPLAY_ROTATION;
#endif
}
}
} else {
#ifdef DISPLAY_ROTATION
_prefs.display_rotation = DISPLAY_ROTATION;
#endif
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
file.close();
}
@@ -244,40 +331,99 @@ void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_
uint8_t pad[8];
memset(pad, 0, sizeof(pad));
file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0
file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4
file.write(pad, 4); // 36
file.write((uint8_t *)&node_lat, sizeof(node_lat)); // 40
file.write((uint8_t *)&node_lon, sizeof(node_lon)); // 48
file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56
file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60
file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61
file.write((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62
file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63
file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64
file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68
file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69
file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70
file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71
file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72
file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76
file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77
file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78
file.write(pad, 1); // 79
file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80
file.write((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84
file.write((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85
file.write((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86
file.write((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87
file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88
file.write((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89
file.write((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90
file.write((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121
file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float));
file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name));
file.write(pad, 4);
file.write((uint8_t *)&node_lat, sizeof(node_lat));
file.write((uint8_t *)&node_lon, sizeof(node_lon));
file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq));
file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf));
file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr));
file.write((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat));
file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts));
file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw));
file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm));
file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base));
file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc));
file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env));
file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base));
file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy));
file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks));
file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode));
file.write(pad, 1);
file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin));
file.write((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet));
file.write((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled));
file.write((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval));
file.write((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config));
file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops));
file.write((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain));
file.write((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name));
file.write((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key));
file.write((uint8_t *)&_prefs.display_brightness, sizeof(_prefs.display_brightness));
file.write((uint8_t *)&_prefs.auto_off_secs, sizeof(_prefs.auto_off_secs));
file.write((uint8_t *)&_prefs.tz_offset_hours, sizeof(_prefs.tz_offset_hours));
file.write((uint8_t *)&_prefs.low_batt_mv, sizeof(_prefs.low_batt_mv));
file.write((uint8_t *)&_prefs.batt_display_mode, sizeof(_prefs.batt_display_mode));
file.write((uint8_t *)_prefs.custom_msgs, sizeof(_prefs.custom_msgs));
file.write((uint8_t *)&_prefs.ch_notif_override, sizeof(_prefs.ch_notif_override));
file.write((uint8_t *)&_prefs.ch_notif_muted, sizeof(_prefs.ch_notif_muted));
file.write((uint8_t *)&_prefs.dm_show_all, sizeof(_prefs.dm_show_all));
file.write((uint8_t *)&_prefs.room_fav_only, sizeof(_prefs.room_fav_only));
file.write((uint8_t *)&_prefs.buzzer_volume, sizeof(_prefs.buzzer_volume));
file.write((uint8_t *)&_prefs.ringtone_bpm_idx, sizeof(_prefs.ringtone_bpm_idx));
file.write((uint8_t *)&_prefs.ringtone_len, sizeof(_prefs.ringtone_len));
file.write((uint8_t *)_prefs.ringtone_notes, sizeof(_prefs.ringtone_notes));
file.write((uint8_t *)&_prefs.home_pages_mask, sizeof(_prefs.home_pages_mask));
file.write((uint8_t *)&_prefs.bot_enabled, sizeof(_prefs.bot_enabled));
file.write((uint8_t *)&_prefs.bot_channel_enabled, sizeof(_prefs.bot_channel_enabled));
file.write((uint8_t *)&_prefs.bot_channel_idx, sizeof(_prefs.bot_channel_idx));
file.write((uint8_t *)_prefs.bot_trigger, sizeof(_prefs.bot_trigger));
file.write((uint8_t *)_prefs.bot_reply_dm, sizeof(_prefs.bot_reply_dm));
file.write((uint8_t *)_prefs.bot_reply_ch, sizeof(_prefs.bot_reply_ch));
file.write((uint8_t *)&_prefs.clock_hide_seconds, sizeof(_prefs.clock_hide_seconds));
file.write((uint8_t *)&_prefs.buzzer_auto, sizeof(_prefs.buzzer_auto));
file.write((uint8_t *)_prefs.dm_notif, sizeof(_prefs.dm_notif));
file.write((uint8_t *)_prefs.dashboard_fields, sizeof(_prefs.dashboard_fields));
file.write((uint8_t *)&_prefs.advert_auto_interval_sec, sizeof(_prefs.advert_auto_interval_sec));
file.write((uint8_t *)&_prefs.ringtone2_bpm_idx, sizeof(_prefs.ringtone2_bpm_idx));
file.write((uint8_t *)&_prefs.ringtone2_len, sizeof(_prefs.ringtone2_len));
file.write((uint8_t *)_prefs.ringtone2_notes, sizeof(_prefs.ringtone2_notes));
file.write((uint8_t *)&_prefs.notif_melody_dm, sizeof(_prefs.notif_melody_dm));
file.write((uint8_t *)&_prefs.notif_melody_ch, sizeof(_prefs.notif_melody_ch));
file.write((uint8_t *)&_prefs.ch_notif_melody_set, sizeof(_prefs.ch_notif_melody_set));
file.write((uint8_t *)&_prefs.ch_notif_melody_2, sizeof(_prefs.ch_notif_melody_2));
file.write((uint8_t *)_prefs.dm_melody, sizeof(_prefs.dm_melody));
file.write((uint8_t *)&_prefs.auto_lock, sizeof(_prefs.auto_lock));
file.write((uint8_t *)&_prefs.clock_12h, sizeof(_prefs.clock_12h));
file.write((uint8_t *)&_prefs.use_lemon_font, sizeof(_prefs.use_lemon_font));
file.write((uint8_t *)&_prefs.display_rotation, sizeof(_prefs.display_rotation));
file.write((uint8_t *)_prefs.page_order, sizeof(_prefs.page_order));
file.close();
}
}
void DataStore::saveRTCTime() {
uint32_t t = _clock->getCurrentTime();
if (t < 1000000000UL) return; // don't save if time not yet synced
File file = openWrite(_fs, "/rtc_save");
if (file) {
file.write((uint8_t *)&t, sizeof(t));
file.close();
}
}
void DataStore::restoreRTCTime() {
File file = openRead(_fs, "/rtc_save");
if (file) {
uint32_t t = 0;
file.read((uint8_t *)&t, sizeof(t));
file.close();
if (t > 1000000000UL) _clock->setCurrentTime(t);
}
}
void DataStore::loadContacts(DataStoreHost* host) {
File file = openRead(_getContactsChannelsFS(), "/contacts3");
if (file) {

View File

@@ -49,6 +49,8 @@ public:
bool removeFile(FILESYSTEM* fs, const char* filename);
uint32_t getStorageUsedKb() const;
uint32_t getStorageTotalKb() const;
void saveRTCTime();
void restoreRTCTime();
private:
FILESYSTEM* _getContactsChannelsFS() const { if (_fsExtra) return _fsExtra; return _fs;};

View File

@@ -0,0 +1,132 @@
#pragma once
#include <cstring>
#include <cstdio>
#include <ctime>
#include <cstdint>
#include <helpers/SensorManager.h>
#include <helpers/sensors/LPPDataHelpers.h>
// Expands placeholders in tmpl into out (out_len bytes).
// {loc} — GPS coordinates (lat/lon) or "no GPS"
// {time} — local time HH:MM from RTC
// {temp} — temperature in °C (requires sm)
// {hum} — relative humidity % (requires sm)
// {pres} — barometric pressure hPa (requires sm)
// {batt} — battery voltage V (batt_volts >= 0 or LPP_VOLTAGE from sm)
// {alt} — altitude m (requires sm)
// {lux} — luminosity lux (requires sm)
// {dist} — distance m (requires sm)
// {co2} — CO2 concentration ppm (requires sm)
inline void expandMsg(const char* tmpl, char* out, int out_len,
double lat, double lon, bool gps_valid,
uint32_t utc_ts, int8_t tz_hours,
SensorManager* sm = nullptr,
float batt_volts = -1.0f) {
// sv indices: 0=temp 1=hum 2=pres 3=batt 4=alt 5=lux 6=dist 7=co2
float sv[8] = {};
bool sv_ok[8] = {};
if (sm) {
CayenneLPP lpp(100);
sm->querySensors(0xFF, lpp);
LPPReader r(lpp.getBuffer(), lpp.getSize());
uint8_t ch, type;
while (r.readHeader(ch, type)) {
float tmp;
switch (type) {
case LPP_TEMPERATURE:
r.readTemperature(tmp);
if (!sv_ok[0]) { sv[0] = tmp; sv_ok[0] = true; } break;
case LPP_RELATIVE_HUMIDITY:
r.readRelativeHumidity(tmp);
if (!sv_ok[1]) { sv[1] = tmp; sv_ok[1] = true; } break;
case LPP_BAROMETRIC_PRESSURE:
r.readPressure(tmp);
if (!sv_ok[2]) { sv[2] = tmp; sv_ok[2] = true; } break;
case LPP_VOLTAGE:
r.readVoltage(tmp);
if (!sv_ok[3]) { sv[3] = tmp; sv_ok[3] = true; } break;
case LPP_ALTITUDE:
r.readAltitude(tmp);
if (!sv_ok[4]) { sv[4] = tmp; sv_ok[4] = true; } break;
case LPP_LUMINOSITY:
r.readLuminosity(tmp);
if (!sv_ok[5]) { sv[5] = tmp; sv_ok[5] = true; } break;
case LPP_DISTANCE:
r.readDistance(tmp);
if (!sv_ok[6]) { sv[6] = tmp; sv_ok[6] = true; } break;
case LPP_CONCENTRATION:
r.readConcentration(tmp);
if (!sv_ok[7]) { sv[7] = tmp; sv_ok[7] = true; } break;
default:
r.skipData(type); break;
}
}
}
// board battery takes precedence over INA sensor voltage
if (batt_volts >= 0.0f) { sv[3] = batt_volts; sv_ok[3] = true; }
int oi = 0;
const char* p = tmpl;
while (*p && oi < out_len - 1) {
// helper macro: append a buffer whose length is already known
#define APPEND(s, slen) do { \
int _l = (slen); \
if (oi + _l < out_len) { memcpy(out + oi, (s), _l); oi += _l; } \
} while(0)
if (strncmp(p, "{loc}", 5) == 0) {
char lb[32];
if (gps_valid) snprintf(lb, sizeof(lb), "%.5f,%.5f", lat, lon);
else strcpy(lb, "no GPS");
APPEND(lb, strlen(lb)); p += 5;
} else if (strncmp(p, "{time}", 6) == 0) {
if (utc_ts > 1000000000UL) {
uint32_t local_ts = utc_ts + (int32_t)tz_hours * 3600;
time_t t = (time_t)local_ts;
struct tm* ti = gmtime(&t);
char tb[8];
snprintf(tb, sizeof(tb), "%02d:%02d", ti->tm_hour, ti->tm_min);
APPEND(tb, strlen(tb));
}
p += 6;
} else if (strncmp(p, "{temp}", 6) == 0) {
if (sv_ok[0]) { char b[10]; snprintf(b,sizeof(b),"%.1fC",sv[0]); APPEND(b,strlen(b)); }
else { APPEND("{temp}", 6); }
p += 6;
} else if (strncmp(p, "{hum}", 5) == 0) {
if (sv_ok[1]) { char b[8]; snprintf(b,sizeof(b),"%.0f%%",sv[1]); APPEND(b,strlen(b)); }
else { APPEND("{hum}", 5); }
p += 5;
} else if (strncmp(p, "{pres}", 6) == 0) {
if (sv_ok[2]) { char b[12]; snprintf(b,sizeof(b),"%.0fhPa",sv[2]); APPEND(b,strlen(b)); }
else { APPEND("{pres}", 6); }
p += 6;
} else if (strncmp(p, "{batt}", 6) == 0) {
if (sv_ok[3]) { char b[8]; snprintf(b,sizeof(b),"%.2fV",sv[3]); APPEND(b,strlen(b)); }
else { APPEND("{batt}", 6); }
p += 6;
} else if (strncmp(p, "{alt}", 5) == 0) {
if (sv_ok[4]) { char b[10]; snprintf(b,sizeof(b),"%.0fm",sv[4]); APPEND(b,strlen(b)); }
else { APPEND("{alt}", 5); }
p += 5;
} else if (strncmp(p, "{lux}", 5) == 0) {
if (sv_ok[5]) { char b[10]; snprintf(b,sizeof(b),"%.0flux",sv[5]); APPEND(b,strlen(b)); }
else { APPEND("{lux}", 5); }
p += 5;
} else if (strncmp(p, "{dist}", 6) == 0) {
if (sv_ok[6]) { char b[12]; snprintf(b,sizeof(b),"%.2fm",sv[6]); APPEND(b,strlen(b)); }
else { APPEND("{dist}", 6); }
p += 6;
} else if (strncmp(p, "{co2}", 5) == 0) {
if (sv_ok[7]) { char b[12]; snprintf(b,sizeof(b),"%.0fppm",sv[7]); APPEND(b,strlen(b)); }
else { APPEND("{co2}", 5); }
p += 5;
} else {
out[oi++] = *p++;
}
#undef APPEND
}
out[oi] = '\0';
}

View File

@@ -1,4 +1,5 @@
#include "MyMesh.h"
#include "MsgExpand.h"
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
@@ -464,10 +465,10 @@ void MyMesh::queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packe
// we only want to show text messages on display, not cli data
bool should_display = txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN;
if (should_display && _ui) {
_ui->newMsg(path_len, from.name, text, offline_queue_len);
if (!_serial->isConnected()) {
_ui->notify(UIEventType::contactMessage);
}
_ui->newMsg(path_len, from.name, text, offline_queue_len, from.type, from.id.pub_key);
_ui->notify(UIEventType::contactMessage);
if (from.type == ADV_TYPE_CHAT)
_ui->addDMMsg(from.id.pub_key, false, text);
}
#endif
}
@@ -510,10 +511,13 @@ void MyMesh::sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pk
sendFloodScoped(*scope, pkt, delay_millis);
}
void MyMesh::onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
const char *text) {
markConnectionActive(from); // in case this is from a server, and we have a connection
queueMessage(from, TXT_TYPE_PLAIN, pkt, sender_timestamp, NULL, 0, text);
tryBotReplyDM(from, text);
}
void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
@@ -561,20 +565,19 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe
uint8_t frame[1];
frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle'
_serial->writeFrame(frame, 1);
} else {
#ifdef DISPLAY_CLASS
if (_ui) _ui->notify(UIEventType::channelMessage);
#endif
}
#ifdef DISPLAY_CLASS
// Get the channel name from the channel index
if (_ui) _ui->addChannelMsg(channel_idx, text);
if (_ui) _ui->notify(UIEventType::channelMessage);
const char *channel_name = "Unknown";
ChannelDetails channel_details;
if (getChannel(channel_idx, channel_details)) {
channel_name = channel_details.name;
}
if (_ui) _ui->newMsg(path_len, channel_name, text, offline_queue_len);
if (_ui) _ui->newMsg(path_len, channel_name, text, offline_queue_len, 0);
#endif
tryBotReplyChannel(channel_idx, text);
}
void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type,
@@ -761,7 +764,67 @@ bool MyMesh::onContactPathRecv(ContactInfo& contact, uint8_t* in_path, uint8_t i
return BaseChatMesh::onContactPathRecv(contact, in_path, in_path_len, out_path, out_path_len, extra_type, extra, extra_len);
}
#define CTL_TYPE_NODE_DISCOVER_REQ 0x80
#define CTL_TYPE_NODE_DISCOVER_RESP 0x90
void MyMesh::sendNodeDiscoverReq() {
uint8_t data[10];
data[0] = CTL_TYPE_NODE_DISCOVER_REQ;
data[1] = (1 << ADV_TYPE_REPEATER) | (1 << ADV_TYPE_SENSOR) | (1 << ADV_TYPE_ROOM);
getRNG()->random(&data[2], 4);
memcpy(&_pending_node_discover_tag, &data[2], 4);
_pending_node_discover_until = futureMillis(8000);
_discover_count = 0;
uint32_t since = 0;
memcpy(&data[6], &since, 4);
auto pkt = createControlData(data, sizeof(data));
if (pkt) sendZeroHop(pkt);
}
int MyMesh::getDiscoverResults(DiscoverResult dest[], int max_count) {
int n = min(_discover_count, max_count);
memcpy(dest, _discover_results, n * sizeof(DiscoverResult));
return n;
}
void MyMesh::onControlDataRecv(mesh::Packet *packet) {
// If we have an active standalone discover, check if this is a matching response.
// Tag matching provides isolation — no isBLEConnected check needed.
if ((packet->payload[0] & 0xF0) == CTL_TYPE_NODE_DISCOVER_RESP &&
packet->payload_len >= 6 + PUB_KEY_SIZE &&
_pending_node_discover_tag != 0 &&
!millisHasNowPassed(_pending_node_discover_until)) {
uint32_t tag;
memcpy(&tag, &packet->payload[2], 4);
if (tag == _pending_node_discover_tag) {
uint8_t node_type = packet->payload[0] & 0x0F;
const uint8_t* pub_key = &packet->payload[6];
ContactInfo* known = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
if (known) {
known->lastmod = getRTCClock()->getCurrentTime();
}
if (_discover_count < DISCOVER_RESULTS_MAX) {
DiscoverResult& r = _discover_results[_discover_count++];
if (known) {
strncpy(r.name, known->name, sizeof(r.name) - 1);
r.name[sizeof(r.name) - 1] = '\0';
r.is_known = true;
} else {
r.name[0] = '\0';
r.is_known = false;
}
r.type = node_type;
r.rssi = (int8_t)_radio->getLastRSSI();
r.snr_x4 = (int8_t)(_radio->getLastSNR() * 4);
r.remote_snr_x4 = (int8_t)packet->payload[1];
memcpy(r.pub_key, pub_key, PUB_KEY_SIZE);
r.timestamp = getRTCClock()->getCurrentTime();
}
if (_ui) _ui->notify(UIEventType::newContactMessage);
return; // our discover — don't forward to BLE app
}
}
if (packet->payload_len + 4 > sizeof(out_frame)) {
MESH_DEBUG_PRINTLN("onControlDataRecv(), payload_len too long: %d", packet->payload_len);
return;
@@ -850,12 +913,18 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
_cli_rescue = false;
offline_queue_len = 0;
app_target_ver = 0;
_bot_last_dm_reply_ms = 0;
_bot_last_ch_reply_ms = 0;
_next_auto_advert_ms = 0;
clearPendingReqs();
next_ack_idx = 0;
sign_data = NULL;
dirty_contacts_expiry = 0;
memset(advert_paths, 0, sizeof(advert_paths));
memset(send_scope.key, 0, sizeof(send_scope.key));
_discover_count = 0;
_pending_node_discover_tag = 0;
_pending_node_discover_until = 0;
// defaults
memset(&_prefs, 0, sizeof(_prefs));
@@ -868,6 +937,27 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
_prefs.tx_power_dbm = LORA_TX_POWER;
_prefs.gps_enabled = 0; // GPS disabled by default
_prefs.gps_interval = 0; // No automatic GPS updates by default
_prefs.display_brightness = 2; // medium brightness by default
_prefs.buzzer_volume = 4; // max volume by default
_prefs.ringtone_bpm_idx = 2; // 120 bpm default
_prefs.ringtone_len = 0; // no custom ringtone by default
_prefs.ringtone2_bpm_idx = 2; // 120 bpm default
_prefs.home_pages_mask = 0x01FF; // all pages visible
_prefs.bot_enabled = 0;
_prefs.bot_channel_enabled = 0;
_prefs.bot_channel_idx = 0;
_prefs.bot_trigger[0] = '\0';
_prefs.bot_reply_dm[0] = '\0';
_prefs.bot_reply_ch[0] = '\0';
_prefs.dm_show_all = 1; // show all contacts by default
memset(_prefs.dm_notif, 0, sizeof(_prefs.dm_notif));
_prefs.auto_off_secs = 15; // 15 seconds auto-off by default
#ifdef EINK_DISPLAY_MODEL
_prefs.clock_hide_seconds = 1; // e-ink: seconds cause a panel refresh every second
#endif
_prefs.tz_offset_hours = 0; // UTC by default
_prefs.low_batt_mv = 3400; // auto-shutdown at 3.4V by default
_prefs.batt_display_mode = 0; // icon by default
//_prefs.rx_delay_base = 10.0f; enable once new algo fixed
#if defined(USE_SX1262) || defined(USE_SX1268)
#ifdef SX126X_RX_BOOSTED_GAIN
@@ -1255,7 +1345,9 @@ void MyMesh::handleCmdFrame(size_t len) {
ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE);
uint32_t last_mod = getRTCClock()->getCurrentTime(); // fallback value if not present in cmd_frame
if (recipient) {
uint8_t saved_type = recipient->type; // type is authoritative from advert, not app
updateContactFromFrame(*recipient, last_mod, cmd_frame, len);
if (saved_type != ADV_TYPE_NONE) recipient->type = saved_type;
recipient->lastmod = last_mod;
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
writeOKFrame();
@@ -1673,13 +1765,22 @@ void MyMesh::handleCmdFrame(size_t len) {
writeErrFrame(ERR_CODE_NOT_FOUND);
}
} else if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 32) {
writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); // not supported (yet)
uint8_t channel_idx = cmd_frame[1];
ChannelDetails channel;
StrHelper::strncpy(channel.name, (char *)&cmd_frame[2], 32);
memcpy(channel.channel.secret, &cmd_frame[2 + 32], 32); // 256-bit key
if (setChannel(channel_idx, channel)) {
saveChannels();
writeOKFrame();
} else {
writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx
}
} else if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 16) {
uint8_t channel_idx = cmd_frame[1];
ChannelDetails channel;
StrHelper::strncpy(channel.name, (char *)&cmd_frame[2], 32);
memset(channel.channel.secret, 0, sizeof(channel.channel.secret));
memcpy(channel.channel.secret, &cmd_frame[2 + 32], 16); // NOTE: only 128-bit supported
memcpy(channel.channel.secret, &cmd_frame[2 + 32], 16); // 128-bit key
if (setChannel(channel_idx, channel)) {
saveChannels();
writeOKFrame();
@@ -2172,8 +2273,16 @@ void MyMesh::loop() {
dirty_contacts_expiry = 0;
}
if (_prefs.advert_auto_interval_sec > 0 && millisHasNowPassed(_next_auto_advert_ms)) {
mesh::Packet* pkt = (sensors.node_lat != 0 || sensors.node_lon != 0)
? createSelfAdvert(_prefs.node_name, sensors.node_lat, sensors.node_lon)
: createSelfAdvert(_prefs.node_name);
if (pkt) sendZeroHop(pkt);
_next_auto_advert_ms = futureMillis(_prefs.advert_auto_interval_sec * 1000UL);
}
#ifdef DISPLAY_CLASS
if (_ui) _ui->setHasConnection(_serial->isConnected());
if (_ui) _ui->setHasConnection(_serial->isBLEConnected());
#endif
}
@@ -2191,3 +2300,5 @@ bool MyMesh::advert() {
return false;
}
}
#include "MyMeshBot.h"

View File

@@ -8,11 +8,12 @@
#define FIRMWARE_VER_CODE 11
#ifndef FIRMWARE_BUILD_DATE
#define FIRMWARE_BUILD_DATE "19 Apr 2026"
#define FIRMWARE_BUILD_DATE "12 May 2026"
#endif
// Versioning: vX.Y = upstream base, plus.N = fork revision
#ifndef FIRMWARE_VERSION
#define FIRMWARE_VERSION "v1.15.0"
#define FIRMWARE_VERSION "v1.15-plus.1"
#endif
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
@@ -84,6 +85,19 @@ struct AdvertPath {
uint8_t path[MAX_PATH_SIZE];
};
struct DiscoverResult {
char name[32]; // contact name if known, "" if unknown (use type label)
uint8_t type; // ADV_TYPE_REPEATER / ADV_TYPE_SENSOR / ADV_TYPE_ROOM
bool is_known; // true = in contacts[], false = new unknown node
int8_t rssi; // RSSI of the response as received by us (dBm)
int8_t snr_x4; // SNR of the response as received by us (dB × 4)
int8_t remote_snr_x4; // SNR at which responder heard our request (dB × 4)
uint8_t pub_key[PUB_KEY_SIZE];
uint32_t timestamp;
};
#define EXPECTED_ACK_TABLE_SIZE 8
class MyMesh : public BaseChatMesh, public DataStoreHost {
public:
MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui=NULL);
@@ -98,9 +112,11 @@ public:
void loop();
void handleCmdFrame(size_t len);
bool advert();
void sendNodeDiscoverReq();
void enterCLIRescue();
int getRecentlyHeard(AdvertPath dest[], int max_num);
int getDiscoverResults(DiscoverResult dest[], int max_count);
protected:
float getAirtimeBudgetFactor() const override;
@@ -165,6 +181,14 @@ protected:
public:
void savePrefs() { _store->savePrefs(_prefs, sensors.node_lat, sensors.node_lon); }
void saveRTCTime() { _store->saveRTCTime(); }
bool isAckPending(uint32_t expected_ack) const {
for (int i = 0; i < EXPECTED_ACK_TABLE_SIZE; i++)
if (expected_ack_table[i].ack == expected_ack) return true;
return false;
}
#if ENV_INCLUDE_GPS == 1
void applyGpsPrefs() {
@@ -178,6 +202,9 @@ public:
#endif
private:
void tryBotReplyDM(const ContactInfo& from, const char* text);
void tryBotReplyChannel(uint8_t channel_idx, const char* text);
void writeOKFrame();
void writeErrFrame(uint8_t err_code);
void writeDisabledFrame();
@@ -220,6 +247,9 @@ private:
uint8_t *sign_data;
uint32_t sign_data_len;
unsigned long dirty_contacts_expiry;
unsigned long _bot_last_dm_reply_ms;
unsigned long _bot_last_ch_reply_ms;
unsigned long _next_auto_advert_ms;
TransportKey send_scope;
@@ -241,12 +271,17 @@ private:
uint32_t ack;
ContactInfo* contact;
};
#define EXPECTED_ACK_TABLE_SIZE 8
AckTableEntry expected_ack_table[EXPECTED_ACK_TABLE_SIZE]; // circular table
int next_ack_idx;
#define ADVERT_PATH_TABLE_SIZE 16
AdvertPath advert_paths[ADVERT_PATH_TABLE_SIZE]; // circular table
#define DISCOVER_RESULTS_MAX 16
DiscoverResult _discover_results[DISCOVER_RESULTS_MAX];
int _discover_count;
uint32_t _pending_node_discover_tag;
unsigned long _pending_node_discover_until;
};
extern MyMesh the_mesh;

View File

@@ -0,0 +1,79 @@
#pragma once
// Bot logic — not part of upstream MyMesh.cpp.
// Included at the bottom of MyMesh.cpp after all class definitions.
void MyMesh::tryBotReplyDM(const ContactInfo& from, const char* text) {
if (from.type != ADV_TYPE_CHAT) return;
if (!(_prefs.bot_enabled && _prefs.bot_trigger[0] && _prefs.bot_reply_dm[0] &&
millis() - _bot_last_dm_reply_ms > 10000UL))
return;
const char* tr = _prefs.bot_trigger;
int tlen = strlen(tr);
bool matched = false;
for (const char* t = text; *t && !matched; t++) {
int i = 0;
while (i < tlen && tolower((uint8_t)t[i]) == tolower((uint8_t)tr[i])) i++;
if (i == tlen) matched = true;
}
if (!matched) return;
uint32_t ts = getRTCClock()->getCurrentTime();
char expanded[200];
expandMsg(_prefs.bot_reply_dm, expanded, sizeof(expanded),
sensors.node_lat, sensors.node_lon,
sensors.node_lat != 0.0 || sensors.node_lon != 0.0,
ts, _prefs.tz_offset_hours,
&sensors, (float)board.getBattMilliVolts() / 1000.0f);
uint32_t expected_ack, est_timeout;
if (sendMessage(from, ts, 0, expanded, expected_ack, est_timeout) != MSG_SEND_FAILED) {
_bot_last_dm_reply_ms = millis();
#ifdef DISPLAY_CLASS
if (_ui) _ui->addDMMsg(from.id.pub_key, true, expanded);
#endif
}
}
void MyMesh::tryBotReplyChannel(uint8_t channel_idx, const char* text) {
if (!(_prefs.bot_enabled && _prefs.bot_channel_enabled && _prefs.bot_trigger[0] && _prefs.bot_reply_ch[0] &&
channel_idx == _prefs.bot_channel_idx &&
millis() - _bot_last_ch_reply_ms > 10000UL))
return;
// Skip "sender_name: " prefix so the trigger is only matched against the message body.
const char* msg = text;
const char* sep = strstr(text, ": ");
if (sep) msg = sep + 2;
const char* tr = _prefs.bot_trigger;
int tlen = strlen(tr);
bool matched = false;
for (const char* t = msg; *t && !matched; t++) {
int i = 0;
while (i < tlen && tolower((uint8_t)t[i]) == tolower((uint8_t)tr[i])) i++;
if (i == tlen) matched = true;
}
if (!matched) return;
ChannelDetails ch;
if (!getChannel(channel_idx, ch)) return;
uint32_t ts = getRTCClock()->getCurrentTime();
char expanded[200];
expandMsg(_prefs.bot_reply_ch, expanded, sizeof(expanded),
sensors.node_lat, sensors.node_lon,
sensors.node_lat != 0.0 || sensors.node_lon != 0.0,
ts, _prefs.tz_offset_hours,
&sensors, (float)board.getBattMilliVolts() / 1000.0f);
int rlen = strlen(expanded);
if (sendGroupMessage(ts, ch.channel, _prefs.node_name, expanded, rlen)) {
_bot_last_ch_reply_ms = millis();
#ifdef DISPLAY_CLASS
if (_ui) {
char with_sender[240]; // node_name(32) + ": "(2) + expanded(200) + margin
snprintf(with_sender, sizeof(with_sender), "%s: %s", _prefs.node_name, expanded);
_ui->addChannelMsg(channel_idx, with_sender);
}
#endif
}
}

View File

@@ -25,6 +25,7 @@ struct NodePrefs { // persisted to file
uint32_t ble_pin;
uint8_t advert_loc_policy;
uint8_t buzzer_quiet;
uint8_t buzzer_volume; // 0=min..4=max, default 4
uint8_t gps_enabled; // GPS enabled flag (0=disabled, 1=enabled)
uint32_t gps_interval; // GPS read interval in seconds
uint8_t autoadd_config; // bitmask for auto-add contacts config
@@ -34,4 +35,52 @@ struct NodePrefs { // persisted to file
uint8_t autoadd_max_hops; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64)
char default_scope_name[31];
uint8_t default_scope_key[16];
uint8_t display_brightness; // 0=min..4=max, default 2 (medium)
uint16_t auto_off_secs; // display auto-off: 0=never, else seconds (default 15)
uint8_t auto_lock; // 0=disabled, 1=lock screen when display turns off
int8_t tz_offset_hours; // timezone offset from UTC, -12..+14 (default 0)
uint16_t low_batt_mv; // auto-shutdown threshold: 0=disabled, 3000-3500 mV
uint8_t batt_display_mode; // 0=icon, 1=percent, 2=voltage
char custom_msgs[10][140]; // user-defined quick messages (supports {loc}, {time})
uint64_t ch_notif_override; // bitmask: bit i = channel i has explicit notification setting
uint64_t ch_notif_muted; // bitmask: bit i = channel i muted (only if override bit set)
uint8_t dm_show_all; // 0=favourites only (default), 1=all chat contacts
uint8_t room_fav_only; // 0=all room servers (default), 1=favourites only
uint8_t ringtone_bpm_idx; // index into {60,90,120,150,180}
uint8_t ringtone_len; // number of notes in custom ringtone (0 = use default)
uint8_t ringtone_notes[32]; // packed: bits0-2=pitch, bits3-4=octave-4, bits5-6=dur_idx
uint16_t home_pages_mask; // bitmask of visible home pages (bit0=Clock..bit8=Shutdown); 0=all visible
uint8_t bot_enabled; // 0=disabled, 1=DM bot active (responds to all DMs)
uint8_t bot_channel_enabled; // 0=disabled, 1=channel bot active for bot_channel_idx
uint8_t bot_channel_idx; // channel index for channel bot
char bot_trigger[64]; // trigger phrase (case-insensitive contains match)
char bot_reply_dm[140]; // auto-reply text for DM
char bot_reply_ch[140]; // auto-reply text for channel
uint8_t clock_hide_seconds; // 0=show HH:MM:SS/refresh 1s (default), 1=hide/refresh 60s
uint8_t clock_12h; // 0=24h (default), 1=12h with AM/PM
uint8_t buzzer_auto; // 0=manual (default), 1=auto-mute when BT connected
struct DmNotifEntry { uint8_t prefix[4]; uint8_t state; }; // state: 0=default,1=muted,2=force-on
static const int DM_NOTIF_TABLE_MAX = 16;
DmNotifEntry dm_notif[DM_NOTIF_TABLE_MAX]; // 16*5 = 80 bytes
uint8_t dashboard_fields[3]; // 0=None,1=Batt,2=Temp,3=Hum,4=Pres,5=GPS,6=Alt,7=Lux,8=CO2,9=Nodes
uint32_t advert_auto_interval_sec; // periodic 0-hop advert with GPS: 0=off, else seconds
// Second melody slot (same packing as ringtone_*)
uint8_t ringtone2_bpm_idx;
uint8_t ringtone2_len;
uint8_t ringtone2_notes[32];
// Global melody for notifications: 0=built-in, 1=melody1, 2=melody2
uint8_t notif_melody_dm;
uint8_t notif_melody_ch;
// Per-channel melody override (2 bitmasks, 1 bit per channel)
uint64_t ch_notif_melody_set; // bit i = channel i has explicit melody
uint64_t ch_notif_melody_2; // bit i = use melody 2 (else melody 1, when set bit is set)
// Per-DM melody table
struct DmMelodyEntry { uint8_t prefix[4]; uint8_t slot; }; // slot: 0=global,1=melody1,2=melody2
static const int DM_MELODY_TABLE_MAX = 16;
DmMelodyEntry dm_melody[DM_MELODY_TABLE_MAX];
uint8_t use_lemon_font; // 0=default Adafruit font, 1=Lemon font (Unicode, pixel-accurate wrap)
uint8_t display_rotation; // 0-3; only used on e-ink displays
// Home screen page order: each byte = bit-index+1 (see HP_* bit positions + 9=Settings, 10=Messages).
// 0 = end of list (also uninitialized legacy). hasCustomOrder iff page_order[0] in 1..11.
uint8_t page_order[11];
};

View File

@@ -71,7 +71,10 @@ static uint32_t _atoi(const char* sp) {
ArduinoSerialInterface serial_interface;
#endif
#elif defined(NRF52_PLATFORM)
#ifdef BLE_PIN_CODE
#ifdef DUAL_SERIAL
#include <helpers/nrf52/DualSerialInterface.h>
DualSerialInterface serial_interface;
#elif defined(BLE_PIN_CODE)
#include <helpers/nrf52/SerialBLEInterface.h>
SerialBLEInterface serial_interface;
#else
@@ -150,7 +153,9 @@ void setup() {
#endif
);
#ifdef BLE_PIN_CODE
#ifdef DUAL_SERIAL
serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin(), Serial);
#elif defined(BLE_PIN_CODE)
serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin());
#else
serial_interface.begin(Serial);
@@ -211,6 +216,7 @@ void setup() {
#error "need to define filesystem"
#endif
store.restoreRTCTime();
sensors.begin();
#if ENV_INCLUDE_GPS == 1
@@ -218,15 +224,30 @@ void setup() {
#endif
#ifdef DISPLAY_CLASS
// Apply saved brightness as soon as prefs are available so the tail of
// the loading screen is not stuck at full brightness.
if (disp && the_mesh.getNodePrefs())
disp->setBrightness(the_mesh.getNodePrefs()->display_brightness);
ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved
#endif
#ifdef NRF52_PLATFORM
NRF_WDT->CONFIG = 0x01; // run during sleep; pause during debug halt
NRF_WDT->CRV = 32768*30-1; // 30 second timeout
NRF_WDT->RREN = 0x01; // enable reload register 0
NRF_WDT->TASKS_START = 1;
#endif
}
void loop() {
#ifdef NRF52_PLATFORM
NRF_WDT->RR[0] = 0x6E524635UL; // pet watchdog
#endif
the_mesh.loop();
sensors.loop();
#ifdef DISPLAY_CLASS
ui_task.loop();
#endif
rtc_clock.tick();
board.sleep(0); // CPU sleeps until next interrupt (radio, timer, BLE); nRF52 ignores the seconds param
}

View File

@@ -0,0 +1,73 @@
#pragma once
// Configures periodic automatic 0-hop advert with GPS position.
// Included by UITask.cpp after DashboardConfigScreen.h.
class AutoAdvertScreen : public UIScreen {
UITask* _task;
NodePrefs* _prefs;
bool _dirty;
static const int OPT_COUNT = 8;
static const uint32_t OPTS[OPT_COUNT];
static const char* OPT_LABELS[OPT_COUNT];
int currentIdx() const {
for (int i = 0; i < OPT_COUNT; i++)
if (OPTS[i] == _prefs->advert_auto_interval_sec) return i;
return 0;
}
public:
AutoAdvertScreen(UITask* task, NodePrefs* prefs) : _task(task), _prefs(prefs) {}
void enter() { _dirty = false; }
int render(DisplayDriver& display) override {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
int label_y = display.listStart();
int bar_y = label_y + display.lineStep();
int bar_h = display.lineStep();
int tip_y = bar_y + bar_h + 4;
display.drawTextCentered(display.width() / 2, 0, "AUTO-ADVERT");
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
display.setCursor(2, label_y);
display.print("Interval:");
int idx = currentIdx();
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, bar_y, display.width(), bar_h);
display.setColor(DisplayDriver::DARK);
display.drawTextCentered(display.width() / 2, bar_y + 1, OPT_LABELS[idx]);
display.setColor(DisplayDriver::LIGHT);
display.setCursor(2, tip_y);
display.print("< > to change");
display.setCursor(2, tip_y + display.lineStep());
display.print("[Esc] to save");
return 500;
}
bool handleInput(char c) override {
if (c == KEY_CANCEL || c == KEY_CONTEXT_MENU) {
if (_dirty) the_mesh.savePrefs();
_task->gotoToolsScreen();
return true;
}
bool right = (c == KEY_RIGHT || c == KEY_NEXT || c == KEY_ENTER);
bool left = (c == KEY_LEFT || c == KEY_PREV);
if (right || left) {
int idx = currentIdx();
idx = right ? (idx + 1) % OPT_COUNT : (idx + OPT_COUNT - 1) % OPT_COUNT;
_prefs->advert_auto_interval_sec = OPTS[idx];
_dirty = true;
return true;
}
return false;
}
};
const uint32_t AutoAdvertScreen::OPTS[AutoAdvertScreen::OPT_COUNT] = { 0, 30, 60, 120, 300, 600, 1800, 3600 };
const char* AutoAdvertScreen::OPT_LABELS[AutoAdvertScreen::OPT_COUNT] = { "off", "30s", "1min", "2min", "5min", "10min", "30min", "1h" };

View File

@@ -0,0 +1,195 @@
#pragma once
// Custom screen — not part of upstream UITask.cpp
// Included by UITask.cpp after KeyboardWidget.h is defined.
class BotScreen : public UIScreen {
UITask* _task;
NodePrefs* _prefs;
// Items: 0=Enable(DM), 1=Channel, 2=Trigger, 3=Reply DM, 4=Reply Ch
static const int ITEM_COUNT = 5;
int _sel;
bool _dirty;
// keyboard state (reused for trigger and reply fields)
int _kb_field; // -1=off, 2=trigger, 3=reply DM, 4=reply Ch
KeyboardWidget _kb;
// channel cache (refreshed on enter)
int _num_channels;
uint8_t _channel_indices[MAX_GROUP_CHANNELS];
void refreshChannels() {
_num_channels = 0;
ChannelDetails ch;
for (int i = 0; i < MAX_GROUP_CHANNELS; i++) {
if (the_mesh.getChannel(i, ch) && ch.name[0] != '\0')
_channel_indices[_num_channels++] = (uint8_t)i;
}
}
// Returns index into _channel_indices[] for current bot_channel_idx, or -1 if not found/disabled.
int currentChannelListIdx() const {
if (!_prefs->bot_channel_enabled) return -1;
for (int i = 0; i < _num_channels; i++)
if (_channel_indices[i] == _prefs->bot_channel_idx) return i;
return -1;
}
public:
BotScreen(UITask* task, NodePrefs* prefs) : _task(task), _prefs(prefs) {}
void enter() {
_sel = 0;
_kb_field = -1;
_dirty = false;
refreshChannels();
}
int render(DisplayDriver& display) override {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
if (_kb_field >= 0) {
return _kb.render(display);
}
int avail_h = display.height() - display.listStart();
int item_h = display.lineStep();
if (item_h * ITEM_COUNT > avail_h) item_h = avail_h / ITEM_COUNT;
int start_y = display.listStart();
int val_x = display.valCol();
display.drawTextCentered(display.width() / 2, 0, "AUTO-REPLY BOT");
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
static const char* labels[] = { "Enable", "Channel", "Trigger", "Reply DM", "Reply Ch" };
for (int i = 0; i < ITEM_COUNT; i++) {
int y = start_y + i * item_h;
bool sel = (i == _sel);
if (sel) {
display.fillRect(0, y - 1, display.width(), item_h);
display.setColor(DisplayDriver::DARK);
}
display.setCursor(2, y);
display.print(labels[i]);
display.setCursor(val_x, y);
if (i == 0) {
display.print(_prefs->bot_enabled ? "ON" : "OFF");
} else if (i == 1) {
if (!_prefs->bot_channel_enabled || _num_channels == 0) {
display.print("OFF");
} else {
ChannelDetails ch;
if (the_mesh.getChannel(_prefs->bot_channel_idx, ch) && ch.name[0])
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, ch.name);
else
display.print("?");
}
} else if (i == 2) {
const char* tr = _prefs->bot_trigger;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, tr[0] ? tr : "(none)");
} else if (i == 3) {
const char* rp = _prefs->bot_reply_dm;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, rp[0] ? rp : "(none)");
} else {
const char* rp = _prefs->bot_reply_ch;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, rp[0] ? rp : "(none)");
}
display.setColor(DisplayDriver::LIGHT);
}
return 2000;
}
bool handleInput(char c) override {
bool up = (c == KEY_UP);
bool down = (c == KEY_DOWN);
bool left = (c == KEY_LEFT || c == KEY_PREV);
bool right = (c == KEY_RIGHT || c == KEY_NEXT);
bool enter = (c == KEY_ENTER);
bool cancel = (c == KEY_CANCEL || c == KEY_CONTEXT_MENU);
if (_kb_field >= 0) {
auto res = _kb.handleInput(c);
if (res == KeyboardWidget::DONE) {
if (_kb_field == 2) {
strncpy(_prefs->bot_trigger, _kb.buf, sizeof(_prefs->bot_trigger) - 1);
_prefs->bot_trigger[sizeof(_prefs->bot_trigger) - 1] = '\0';
} else if (_kb_field == 3) {
strncpy(_prefs->bot_reply_dm, _kb.buf, sizeof(_prefs->bot_reply_dm) - 1);
_prefs->bot_reply_dm[sizeof(_prefs->bot_reply_dm) - 1] = '\0';
} else {
strncpy(_prefs->bot_reply_ch, _kb.buf, sizeof(_prefs->bot_reply_ch) - 1);
_prefs->bot_reply_ch[sizeof(_prefs->bot_reply_ch) - 1] = '\0';
}
_dirty = true;
_kb_field = -1;
} else if (res == KeyboardWidget::CANCELLED) {
_kb_field = -1;
}
return true;
}
if (cancel) {
if (_dirty) the_mesh.savePrefs();
_task->gotoToolsScreen();
return true;
}
if (up && _sel > 0) { _sel--; return true; }
if (down && _sel < ITEM_COUNT - 1) { _sel++; return true; }
if (_sel == 0 && (enter || left || right)) {
_prefs->bot_enabled ^= 1;
_dirty = true;
return true;
}
if (_sel == 1) {
if (_num_channels == 0) return false;
// Cycle: OFF → ch[0] → ch[1] → ... → OFF
int idx = currentChannelListIdx(); // -1 = OFF
if (right || enter) {
idx++;
if (idx >= _num_channels) idx = -1; // wrap to OFF
}
if (left) {
idx--;
if (idx < -1) idx = _num_channels - 1;
}
if (left || right || enter) {
if (idx < 0) {
_prefs->bot_channel_enabled = 0;
} else {
_prefs->bot_channel_enabled = 1;
_prefs->bot_channel_idx = _channel_indices[idx];
}
_dirty = true;
return true;
}
}
if ((_sel == 2 || _sel == 3 || _sel == 4) && enter) {
_kb_field = _sel;
const char* initial;
int max;
if (_sel == 2) {
initial = _prefs->bot_trigger;
max = sizeof(_prefs->bot_trigger) - 1;
} else if (_sel == 3) {
initial = _prefs->bot_reply_dm;
max = sizeof(_prefs->bot_reply_dm) - 1;
} else {
initial = _prefs->bot_reply_ch;
max = sizeof(_prefs->bot_reply_ch) - 1;
}
_kb.begin(initial, max);
if (_sel == 2) {
_kb._ph_count = 0; // trigger is literal text — placeholders never match incoming msgs
} else {
kbAddSensorPlaceholders(_kb, &sensors);
}
return true;
}
return false;
}
};

View File

@@ -0,0 +1,90 @@
#pragma once
// Configures which data fields appear on the clock home page.
// Included by UITask.cpp after BotScreen.h.
// Field type constants — used here and in UITask.cpp HP_CLOCK render.
static const uint8_t DASH_NONE = 0;
static const uint8_t DASH_BATT = 1;
static const uint8_t DASH_TEMP = 2;
static const uint8_t DASH_HUM = 3;
static const uint8_t DASH_PRES = 4;
static const uint8_t DASH_GPS = 5;
static const uint8_t DASH_ALT = 6;
static const uint8_t DASH_LUX = 7;
static const uint8_t DASH_CO2 = 8;
static const uint8_t DASH_NODES = 9;
static const uint8_t DASH_MSGS = 10;
static const uint8_t DASH_COUNT = 11;
class DashboardConfigScreen : public UIScreen {
UITask* _task;
NodePrefs* _prefs;
static const int FIELD_SLOTS = 3;
static const char* OPTION_NAMES[DASH_COUNT];
int _sel;
bool _dirty;
void cycle(int slot, int dir) {
uint8_t& f = _prefs->dashboard_fields[slot];
f = (uint8_t)((f + DASH_COUNT + dir) % DASH_COUNT);
_dirty = true;
}
public:
DashboardConfigScreen(UITask* task, NodePrefs* prefs) : _task(task), _prefs(prefs) {}
void enter() { _sel = 0; _dirty = false; }
int render(DisplayDriver& display) override {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
int item_h = display.lineStep();
int start_y = display.listStart();
int val_x = display.valCol();
display.drawTextCentered(display.width() / 2, 0, "CLOCK FIELDS");
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
static const char* labels[] = { "Field 1", "Field 2", "Field 3" };
for (int i = 0; i < FIELD_SLOTS; i++) {
int y = start_y + i * item_h;
bool sel = (i == _sel);
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y - 1, display.width(), item_h);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(2, y);
display.print(labels[i]);
display.setCursor(val_x, y);
uint8_t f = _prefs->dashboard_fields[i];
display.print(OPTION_NAMES[f < DASH_COUNT ? f : DASH_NONE]);
display.setColor(DisplayDriver::LIGHT);
}
return 500;
}
bool handleInput(char c) override {
if (c == KEY_CANCEL || c == KEY_CONTEXT_MENU) {
if (_dirty) the_mesh.savePrefs();
_task->gotoHomeScreen();
return true;
}
if (c == KEY_UP && _sel > 0) { _sel--; return true; }
if (c == KEY_DOWN && _sel < FIELD_SLOTS - 1){ _sel++; return true; }
if (c == KEY_LEFT || c == KEY_PREV) { cycle(_sel, -1); return true; }
if (c == KEY_RIGHT || c == KEY_NEXT) { cycle(_sel, 1); return true; }
if (c == KEY_ENTER) { cycle(_sel, 1); return true; }
return false;
}
};
const char* DashboardConfigScreen::OPTION_NAMES[DASH_COUNT] = {
"None", "Battery", "Temp", "Humidity", "Pressure",
"GPS", "Altitude", "Lux", "CO2", "Contacts", "Messages"
};

View File

@@ -0,0 +1,148 @@
#pragma once
#include <helpers/ui/DisplayDriver.h>
#include <Arduino.h>
static const int FS_CHARS_MAX = 80; // max bytes per wrapped line
struct FullscreenMsgView {
int scroll;
bool active;
FullscreenMsgView() : scroll(0), active(false) {}
enum Result { NONE, PREV, NEXT, CLOSE, REPLY };
void begin() { scroll = 0; active = true; }
// Pixel-accurate word-wrap: breaks at last space that fits within max_px,
// hard-breaks long words. Works for both fixed- and variable-width fonts.
static int wrapLines(DisplayDriver& display, const char* text, int max_px,
char out[][FS_CHARS_MAX], int max_lines) {
int count = 0;
const char* seg = text;
while (*seg && count < max_lines) {
const char* p = seg;
const char* last_sp = nullptr;
const char* last_fit = seg;
while (*p && (p - seg) < FS_CHARS_MAX - 1) {
uint8_t b0 = (uint8_t)*p;
int cb = (b0 < 0x80) ? 1 : (b0 < 0xE0) ? 2 : (b0 < 0xF0) ? 3 : 4;
if ((p - seg) + cb >= FS_CHARS_MAX) break;
char buf[FS_CHARS_MAX];
int n = (int)(p - seg) + cb;
memcpy(buf, seg, n); buf[n] = '\0';
if (display.getTextWidth(buf) > max_px && p > seg) break;
if (*p == ' ') last_sp = p;
p += cb;
last_fit = p;
}
const char* end;
const char* next_seg;
if (!*p) {
end = p; next_seg = p;
} else if (last_sp && last_sp > seg) {
end = last_sp; next_seg = last_sp + 1;
} else {
end = last_fit; next_seg = last_fit;
}
int len = (int)(end - seg);
if (len <= 0) { seg = *seg ? seg + 1 : seg; continue; }
if (len > FS_CHARS_MAX - 1) len = FS_CHARS_MAX - 1;
memcpy(out[count], seg, len);
out[count][len] = '\0';
count++;
seg = next_seg;
}
return count;
}
int render(DisplayDriver& display, const char* sender, const char* text,
bool has_prev, bool has_next) {
display.setTextSize(1);
const int lineH = display.getLineHeight();
const int max_px = display.width() - 6;
// detect @recipient at start of message
char to_nick[32] = "";
const char* body = text;
if (text[0] == '@' && text[1] == '[') {
const char* close = strchr(text + 2, ']');
if (close && close[1] == ' ' && close[2]) {
int len = (int)(close - text) - 2;
if (len >= (int)sizeof(to_nick)) len = sizeof(to_nick) - 1;
memcpy(to_nick, text + 2, len);
to_nick[len] = '\0';
body = close + 2;
}
}
const int cw = display.getCharWidth();
const int header_h = to_nick[0] ? (lineH * 2 + 4) : (lineH + 2);
const int startY = header_h + 2;
const int visible = (display.height() - startY - lineH) / lineH;
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, 0, display.width(), header_h);
display.setColor(DisplayDriver::DARK);
display.drawTextEllipsized(2, 1, display.width() - 4, sender);
if (to_nick[0]) {
char trans_nick[32], to_label[36];
display.translateUTF8ToBlocks(trans_nick, to_nick, sizeof(trans_nick));
snprintf(to_label, sizeof(to_label), "To: %s", trans_nick);
display.drawTextEllipsized(2, lineH + 3, display.width() - 4, to_label);
}
display.setColor(DisplayDriver::LIGHT);
char trans_text[512];
display.translateUTF8ToBlocks(trans_text, body, sizeof(trans_text));
char lines[12][FS_CHARS_MAX];
int lcount = wrapLines(display, trans_text, max_px, lines, 12);
int max_scroll = lcount > visible ? lcount - visible : 0;
if (scroll > max_scroll) scroll = max_scroll;
for (int i = 0; i < visible && (scroll + i) < lcount; i++) {
display.setCursor(0, startY + i * lineH);
display.print(lines[scroll + i]);
}
if (scroll > 0) {
display.setColor(DisplayDriver::DARK);
display.fillRect(display.width() - cw, startY, cw, lineH);
display.setColor(DisplayDriver::LIGHT);
display.setCursor(display.width() - cw, startY);
display.print("^");
}
if (scroll < max_scroll) {
display.setColor(DisplayDriver::DARK);
display.fillRect(display.width() - cw, startY + (visible - 1) * lineH, cw, lineH);
display.setColor(DisplayDriver::LIGHT);
display.setCursor(display.width() - cw, startY + (visible - 1) * lineH);
display.print("v");
}
const int nav_y = display.height() - lineH;
if (has_next) {
display.setCursor(0, nav_y);
display.print("<");
}
if (has_prev) {
display.setCursor(display.width() - cw, nav_y);
display.print(">");
}
return 2000;
}
Result handleInput(char c) {
if (c == KEY_UP) { if (scroll > 0) scroll--; return NONE; }
if (c == KEY_DOWN) { scroll++; return NONE; }
if (c == KEY_LEFT) return NEXT;
if (c == KEY_RIGHT) return PREV;
if (c == KEY_CONTEXT_MENU) return REPLY;
if (c == KEY_ENTER || c == KEY_CANCEL) return CLOSE;
return NONE;
}
};

View File

@@ -0,0 +1,217 @@
#pragma once
#include <helpers/ui/DisplayDriver.h>
#include <Arduino.h>
#include "PopupMenu.h"
// Layout constants shared by all keyboard users
static const char KB_CHARS[4][10] = {
{'a','b','c','d','e','f','g','h','i','j'},
{'k','l','m','n','o','p','q','r','s','t'},
{'u','v','w','x','y','z','.',' ','!','?'},
{'1','2','3','4','5','6','7','8','9','0'},
};
static const int KB_ROWS_CHAR = 4;
static const int KB_COLS_CHAR = 10;
static const int KB_SPECIAL = 5; // [^] [Sp] [De] [{}] [OK]
static const int KB_MAX_LEN = 139;
static const int KB_PH_MAX = 12; // max placeholders in list
static const int KB_PH_LEN = 9; // max placeholder string length incl. null
static const int KB_PH_VISIBLE = 3; // items shown at once in overlay
struct KeyboardWidget {
char buf[KB_MAX_LEN + 1];
int len;
int max_len;
int row, col;
bool caps;
char _ph_buf[KB_PH_MAX][KB_PH_LEN];
int _ph_count;
PopupMenu _ph_menu;
enum Result { NONE, DONE, CANCELLED };
void begin(const char* initial = "", int max = KB_MAX_LEN) {
max_len = (max > KB_MAX_LEN) ? KB_MAX_LEN : max;
strncpy(buf, initial, max_len);
buf[max_len] = '\0';
len = strlen(buf);
row = col = 0;
caps = false;
_ph_menu.active = false;
// default placeholders — always available
_ph_count = 0;
addPlaceholder("{loc}");
addPlaceholder("{time}");
}
void addPlaceholder(const char* ph) {
if (_ph_count < KB_PH_MAX) {
strncpy(_ph_buf[_ph_count], ph, KB_PH_LEN - 1);
_ph_buf[_ph_count][KB_PH_LEN - 1] = '\0';
_ph_count++;
}
}
int render(DisplayDriver& display) {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
const int lh = display.getLineHeight();
const int cw = display.getCharWidth();
const int cell_w = display.width() / KB_COLS_CHAR;
// compact: don't stretch cells beyond lh; freed vertical space goes to preview lines
const int kb_h = (KB_ROWS_CHAR + 1) * lh;
const int preview_h = display.height() - kb_h - 1;
const int prev_lines = (preview_h / lh) > 1 ? (preview_h / lh) : 1;
const int sep_y = prev_lines * lh;
const int chars_y = sep_y + 1;
const int cell_h = (display.height() - chars_y) / (KB_ROWS_CHAR + 1);
const int spec_y = chars_y + KB_ROWS_CHAR * cell_h;
const int spec_w = display.width() / KB_SPECIAL;
// multi-line text preview: cursor always on last preview line
int cpl = display.width() / cw; // chars per preview line
if (cpl < 1) cpl = 1;
int cursor_line = len / cpl;
int first_line = (cursor_line >= prev_lines) ? (cursor_line - prev_lines + 1) : 0;
int start = first_line * cpl;
for (int pl = 0; pl < prev_lines; pl++) {
int ps = start + pl * cpl;
int pe = ps + cpl;
bool cursor_here = (ps <= len && (len < pe || pl == prev_lines - 1));
char linebuf[32];
if (cursor_here) {
int nc = len - ps; if (nc < 0) nc = 0; if (nc > cpl - 1) nc = cpl - 1;
snprintf(linebuf, sizeof(linebuf), "%.*s_", nc, buf + ps);
} else if (len > ps) {
int nc = (len < pe) ? (len - ps) : cpl;
snprintf(linebuf, sizeof(linebuf), "%.*s", nc, buf + ps);
} else {
linebuf[0] = '\0';
}
display.setCursor(0, pl * lh);
display.print(linebuf);
}
display.fillRect(0, sep_y, display.width(), 1);
// character grid
for (int r = 0; r < KB_ROWS_CHAR; r++) {
int y = chars_y + r * cell_h;
for (int c = 0; c < KB_COLS_CHAR; c++) {
bool sel = (row == r && col == c);
char ch = KB_CHARS[r][c];
if (caps && ch >= 'a' && ch <= 'z') ch = ch - 'a' + 'A';
char ch_buf[2] = { ch == ' ' ? '_' : ch, '\0' };
int cx = c * cell_w;
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(cx, y - 1, cell_w - 1, cell_h);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(cx + (cell_w - cw) / 2, y);
display.print(ch_buf);
}
}
// special row: [^] [Sp] [Dl] [{}] [OK]
const char* spec[] = { "[^]", "[Sp]", "[Dl]", "[{}]", "[OK]" };
for (int i = 0; i < KB_SPECIAL; i++) {
bool sel = (row == KB_ROWS_CHAR && col == i);
bool active = (i == 0 && caps);
int sx = i * spec_w;
if (sel || active) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(sx, spec_y - 1, spec_w - 1, cell_h);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
int tw = display.getTextWidth(spec[i]);
display.setCursor(sx + (spec_w - tw) / 2, spec_y);
display.print(spec[i]);
display.setColor(DisplayDriver::LIGHT);
}
// placeholder picker overlay (drawn on top of keyboard)
if (_ph_menu.active) _ph_menu.render(display);
return 50;
}
Result handleInput(char c) {
// placeholder overlay consumes all input
if (_ph_menu.active) {
auto res = _ph_menu.handleInput(c);
if (res == PopupMenu::SELECTED) {
int idx = _ph_menu.selectedIndex();
const char* ph = _ph_buf[idx];
int ph_len = strlen(ph);
if (len + ph_len <= max_len) {
memcpy(buf + len, ph, ph_len);
len += ph_len;
buf[len] = '\0';
}
}
return NONE;
}
if (c == KEY_CANCEL || c == KEY_CONTEXT_MENU) return CANCELLED;
if (c == KEY_UP) {
if (row > 0) {
row--;
if (row == KB_ROWS_CHAR - 1) // leaving special row upward
col = col * KB_COLS_CHAR / KB_SPECIAL;
}
return NONE;
}
if (c == KEY_DOWN) {
if (row < KB_ROWS_CHAR) {
row++;
if (row == KB_ROWS_CHAR) // entering special row
col = col * KB_SPECIAL / KB_COLS_CHAR;
}
return NONE;
}
if (c == KEY_LEFT) {
if (col > 0) col--;
return NONE;
}
if (c == KEY_RIGHT) {
int max_col = (row == KB_ROWS_CHAR) ? KB_SPECIAL - 1 : KB_COLS_CHAR - 1;
if (col < max_col) col++;
return NONE;
}
if (c == KEY_ENTER) {
if (row < KB_ROWS_CHAR) {
if (len < max_len) {
char ch = KB_CHARS[row][col];
if (caps && ch >= 'a' && ch <= 'z') ch = ch - 'a' + 'A';
buf[len++] = ch;
buf[len] = '\0';
}
} else {
switch (col) {
case 0: caps = !caps; break;
case 1:
if (len < max_len) { buf[len++] = ' '; buf[len] = '\0'; }
break;
case 2:
if (len > 0) buf[--len] = '\0';
break;
case 3:
_ph_menu.begin("Placeholder:", KB_PH_VISIBLE);
for (int i = 0; i < _ph_count; i++) _ph_menu.addItem(_ph_buf[i]);
break;
case 4:
return DONE;
}
}
}
return NONE;
}
};

View File

@@ -0,0 +1,573 @@
#pragma once
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
class NearbyScreen : public UIScreen {
UITask* _task;
int _visible = 4; // updated each render; used by handleInput for scroll clamping
static const int FILTER_COUNT = 6;
static const char* FILTER_LABELS[FILTER_COUNT];
static const uint8_t FILTER_TYPES[FILTER_COUNT];
// ── nearby list state ────────────────────────────────────────────────────────
struct Entry {
char name[32];
int32_t lat_e6, lon_e6;
float dist_km;
uint8_t type;
int contact_idx;
uint32_t lastmod;
};
static const int MAX_NEARBY = 32;
Entry _entries[MAX_NEARBY];
int _count;
int _sel;
int _scroll;
bool _detail;
int32_t _own_lat, _own_lon;
bool _own_gps;
uint8_t _filter;
unsigned long _detail_refresh_ms;
static const unsigned long DETAIL_REFRESH_MS = 10000UL;
PopupMenu _ctx_menu;
// ── discover sub-screen state ────────────────────────────────────────────────
bool _discover_mode;
bool _discovering;
unsigned long _discover_started_ms;
static const unsigned long DISCOVER_DURATION_MS = 8000UL;
DiscoverResult _dresults[DISCOVER_RESULTS_MAX];
int _dresult_count;
int _dscroll;
int _dsel;
bool _ddetail;
int _d_visible = 2; // updated each render; used by handleInputDiscover
// ── helpers ──────────────────────────────────────────────────────────────────
static void pubKeyToBase64(const uint8_t* key, char* out, int out_len) {
static const char T[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int j = 0;
for (int i = 0; i < PUB_KEY_SIZE && j + 5 < out_len; i += 3) {
uint32_t b = ((uint32_t)key[i] << 16)
| (i+1 < PUB_KEY_SIZE ? (uint32_t)key[i+1] << 8 : 0)
| (i+2 < PUB_KEY_SIZE ? (uint32_t)key[i+2] : 0);
out[j++] = T[(b >> 18) & 63];
out[j++] = T[(b >> 12) & 63];
if (i+1 < PUB_KEY_SIZE) out[j++] = T[(b >> 6) & 63];
if (i+2 < PUB_KEY_SIZE) out[j++] = T[b & 63];
}
out[j] = '\0';
}
static float haversineKm(int32_t lat1, int32_t lon1, int32_t lat2, int32_t lon2) {
static const float DEG2RAD = (float)M_PI / 180.0f;
float la1 = lat1 * (1e-6f * DEG2RAD);
float la2 = lat2 * (1e-6f * DEG2RAD);
float dla = (lat2 - lat1) * (1e-6f * DEG2RAD);
float dlo = (lon2 - lon1) * (1e-6f * DEG2RAD);
float a = sinf(dla/2)*sinf(dla/2) + cosf(la1)*cosf(la2)*sinf(dlo/2)*sinf(dlo/2);
return 6371.0f * 2.0f * asinf(sqrtf(a));
}
static int bearingDeg(int32_t lat1, int32_t lon1, int32_t lat2, int32_t lon2) {
static const float DEG2RAD = (float)M_PI / 180.0f;
float la1 = lat1 * (1e-6f * DEG2RAD);
float la2 = lat2 * (1e-6f * DEG2RAD);
float dlo = (lon2 - lon1) * (1e-6f * DEG2RAD);
float b = atan2f(sinf(dlo)*cosf(la2),
cosf(la1)*sinf(la2) - sinf(la1)*cosf(la2)*cosf(dlo)) * (180.0f / (float)M_PI);
if (b < 0.0f) b += 360.0f;
return (int)(b + 0.5f) % 360;
}
static const char* bearingCardinal(int deg) {
static const char* dirs[] = { "N","NE","E","SE","S","SW","W","NW" };
return dirs[((deg + 22) % 360) / 45];
}
static void fmtAge(char* buf, int n, uint32_t lastmod) {
uint32_t now = rtc_clock.getCurrentTime();
if (now < lastmod || lastmod == 0) { snprintf(buf, n, "unknown"); return; }
uint32_t age = now - lastmod;
if (age < 60) snprintf(buf, n, "%us ago", age);
else if (age < 3600) snprintf(buf, n, "%um ago", age / 60);
else if (age < 86400) snprintf(buf, n, "%uh ago", age / 3600);
else snprintf(buf, n, ">1d ago");
}
static void fmtDist(char* buf, int n, float km) {
if (km < 1.0f) snprintf(buf, n, "%dm", (int)(km * 1000 + 0.5f));
else if (km < 100.0f) snprintf(buf, n, "%.1fkm", km);
else snprintf(buf, n, "%dkm", (int)(km + 0.5f));
}
static const char* typeName(uint8_t t) {
switch (t) {
case ADV_TYPE_CHAT: return "Companion";
case ADV_TYPE_REPEATER: return "Repeater";
case ADV_TYPE_ROOM: return "Room";
case ADV_TYPE_SENSOR: return "Sensor";
default: return "Unknown";
}
}
void refresh() {
_count = 0;
_own_gps = false;
_own_lat = _own_lon = 0;
#if ENV_INCLUDE_GPS == 1
LocationProvider* loc = sensors.getLocationProvider();
if (loc && loc->isValid()) {
_own_lat = loc->getLatitude();
_own_lon = loc->getLongitude();
_own_gps = true;
}
#endif
int nc = the_mesh.getNumContacts();
for (int i = 0; i < nc && _count < MAX_NEARBY; i++) {
ContactInfo ci;
if (!the_mesh.getContactByIdx(i, ci)) continue;
if (_filter == 0 && !(ci.flags & 1)) continue;
if (_filter >= 2 && ci.type != FILTER_TYPES[_filter]) continue;
Entry& e = _entries[_count++];
strncpy(e.name, ci.name, sizeof(e.name) - 1);
e.name[sizeof(e.name) - 1] = '\0';
e.lat_e6 = ci.gps_lat;
e.lon_e6 = ci.gps_lon;
bool remote_gps = (ci.gps_lat != 0 || ci.gps_lon != 0);
e.dist_km = (_own_gps && remote_gps)
? haversineKm(_own_lat, _own_lon, ci.gps_lat, ci.gps_lon)
: -1.0f;
e.type = ci.type;
e.contact_idx = i;
e.lastmod = ci.lastmod;
}
// sort by distance ascending; nodes without GPS go to the end
for (int i = 0; i < _count - 1; i++) {
int best = i;
for (int j = i + 1; j < _count; j++) {
float dj = _entries[j].dist_km, db = _entries[best].dist_km;
if (dj >= 0.0f && (db < 0.0f || dj < db)) best = j;
}
if (best != i) { Entry tmp = _entries[i]; _entries[i] = _entries[best]; _entries[best] = tmp; }
}
if (_count == 0) {
_sel = _scroll = 0;
} else if (_sel >= _count) {
_sel = _count - 1;
if (_scroll > _sel) _scroll = _sel;
}
}
// ── discover sub-screen ──────────────────────────────────────────────────────
void enterDiscoverMode() {
_discover_mode = true;
_discovering = true;
_ddetail = false;
_discover_started_ms = millis();
_dresult_count = 0;
_dscroll = 0;
_dsel = 0;
the_mesh.sendNodeDiscoverReq();
}
int renderDiscover(DisplayDriver& display) {
int lh = display.getLineHeight();
int hdr = display.headerH();
int d_box_h = 2 * lh + 3; // two text rows + padding
int d_item_h = d_box_h + 2;
int d_start_y = hdr;
_d_visible = display.listVisible(d_item_h);
if (_d_visible < 1) _d_visible = 1;
if (_ddetail) {
// ── full-screen detail for selected node ──────────────────────────────
const DiscoverResult& r = _dresults[_dsel];
const char* fullType = (r.type == ADV_TYPE_REPEATER) ? "Repeater" :
(r.type == ADV_TYPE_SENSOR) ? "Sensor" :
(r.type == ADV_TYPE_ROOM) ? "Room" : "Node";
// title bar: node name inverted
char label[32];
if (r.name[0]) { strncpy(label, r.name, 31); label[31] = '\0'; }
else { snprintf(label, sizeof(label), "[%s]", fullType); }
char filtered[32];
display.translateUTF8ToBlocks(filtered, label, sizeof(filtered));
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, 0, display.width(), hdr - 1);
display.setColor(DisplayDriver::DARK);
display.drawTextEllipsized(2, 1, display.width() - 4, filtered);
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, hdr - 1, display.width(), 1);
// public key as base64 — truncate to one line via charWidth
char b64[48];
pubKeyToBase64(r.pub_key, b64, sizeof(b64));
{
int max_chars = (display.width() - 4) / display.getCharWidth();
int b64_len = strlen(b64);
char b64_line[48];
if (b64_len > max_chars) {
strncpy(b64_line, b64, max_chars - 3);
b64_line[max_chars - 3] = '\0';
strcat(b64_line, "...");
} else {
strncpy(b64_line, b64, sizeof(b64_line) - 1);
b64_line[sizeof(b64_line) - 1] = '\0';
}
display.setCursor(2, hdr);
display.print(b64_line);
}
// distribute 4 remaining lines below b64 — compact step, shrink only if needed
int step = display.lineStep();
if (step * 5 > display.height() - hdr) step = (display.height() - hdr) / 5;
char buf[32];
snprintf(buf, sizeof(buf), "RSSI: %d dBm", (int)r.rssi);
display.setCursor(2, hdr + step); display.print(buf);
snprintf(buf, sizeof(buf), "SNR: %d dB", (int)(r.snr_x4 / 4));
display.setCursor(2, hdr + step * 2); display.print(buf);
snprintf(buf, sizeof(buf), "Rem: %d dB", (int)(r.remote_snr_x4 / 4));
display.setCursor(2, hdr + step * 3); display.print(buf);
display.setCursor(2, hdr + step * 4);
display.print(r.is_known ? "Status: known" : "Status: new");
return 5000;
}
// ── list view ─────────────────────────────────────────────────────────────
_dresult_count = the_mesh.getDiscoverResults(_dresults, DISCOVER_RESULTS_MAX);
if (_discovering && millis() - _discover_started_ms >= DISCOVER_DURATION_MS)
_discovering = false;
display.setColor(DisplayDriver::LIGHT);
char title[28];
if (_discovering)
snprintf(title, sizeof(title), "SCANNING... (%d)", _dresult_count);
else if (_dresult_count == 0)
snprintf(title, sizeof(title), "DISCOVER: none");
else
snprintf(title, sizeof(title), "DISCOVER (%d found)", _dresult_count);
display.drawTextCentered(display.width() / 2, 0, title);
display.fillRect(0, hdr - 1, display.width(), 1);
if (_dresult_count == 0) {
display.drawTextCentered(display.width() / 2, display.height() / 2,
_discovering ? "Waiting for replies..." : "No nodes found");
} else {
if (_dsel >= _dresult_count) _dsel = _dresult_count - 1;
if (_dscroll > _dresult_count - _d_visible)
_dscroll = _dresult_count > _d_visible ? _dresult_count - _d_visible : 0;
if (_dscroll < 0) _dscroll = 0;
for (int i = 0; i < _d_visible && (_dscroll + i) < _dresult_count; i++) {
int idx = _dscroll + i;
bool sel = (idx == _dsel);
const DiscoverResult& r = _dresults[idx];
int y = d_start_y + i * d_item_h;
const char* typeStr = (r.type == ADV_TYPE_REPEATER) ? "Rpt" :
(r.type == ADV_TYPE_SENSOR) ? "Snsr" :
(r.type == ADV_TYPE_ROOM) ? "Room" : "?";
display.setColor(DisplayDriver::LIGHT);
if (sel) {
display.fillRect(0, y, display.width(), d_box_h);
display.setColor(DisplayDriver::DARK);
} else {
display.drawRect(0, y, display.width(), d_box_h);
display.fillRect(1, y + 1, display.width() - 2, lh);
display.setColor(DisplayDriver::DARK);
}
// header: name left, type right
char label[32];
if (r.name[0]) { strncpy(label, r.name, 31); label[31] = '\0'; }
else {
const char* ft = (r.type == ADV_TYPE_REPEATER) ? "Repeater" :
(r.type == ADV_TYPE_SENSOR) ? "Sensor" :
(r.type == ADV_TYPE_ROOM) ? "Room" : "Node";
snprintf(label, sizeof(label), "[%s]", ft);
}
char filtered[32];
display.translateUTF8ToBlocks(filtered, label, sizeof(filtered));
int tw = display.getTextWidth(typeStr);
display.drawTextEllipsized(3, y + 1, display.width() - 6 - tw, filtered);
display.setCursor(display.width() - 3 - tw, y + 1);
display.print(typeStr);
// body: RSSI + SNR
display.setColor(sel ? DisplayDriver::DARK : DisplayDriver::LIGHT);
char sig[24];
snprintf(sig, sizeof(sig), "RSSI:%d SNR:%d", (int)r.rssi, (int)(r.snr_x4 / 4));
display.drawTextEllipsized(3, y + lh + 2, display.width() - 6, sig);
}
display.setColor(DisplayDriver::LIGHT);
int cw = display.getCharWidth();
if (_dscroll > 0)
{ display.setCursor(display.width() - cw, d_start_y); display.print("^"); }
if (_dscroll + _d_visible < _dresult_count)
{ display.setCursor(display.width() - cw, d_start_y + (_d_visible - 1) * d_item_h); display.print("v"); }
}
return _discovering ? 200 : 2000;
}
bool handleInputDiscover(char c) {
if (_ddetail) {
if (c == KEY_CANCEL) { _ddetail = false; return true; }
if (c == KEY_CONTEXT_MENU || c == KEY_ENTER) {
enterDiscoverMode(); // re-scan; clears _ddetail
return true;
}
return true;
}
if (c == KEY_CANCEL) {
_discover_mode = false;
refresh();
return true;
}
if (c == KEY_ENTER && _dresult_count > 0) {
_ddetail = true;
return true;
}
if (c == KEY_CONTEXT_MENU) {
enterDiscoverMode(); // re-scan
return true;
}
if (c == KEY_UP && _dsel > 0) {
_dsel--;
if (_dsel < _dscroll) _dscroll = _dsel;
return true;
}
if (c == KEY_DOWN && _dsel < _dresult_count - 1) {
_dsel++;
if (_dsel >= _dscroll + _d_visible) _dscroll = _dsel - _d_visible + 1;
return true;
}
return true;
}
public:
NearbyScreen(UITask* task)
: _task(task), _count(0), _sel(0), _scroll(0), _detail(false),
_own_lat(0), _own_lon(0), _own_gps(false), _filter(0),
_detail_refresh_ms(0),
_discover_mode(false), _discovering(false), _discover_started_ms(0),
_dresult_count(0), _dscroll(0), _dsel(0), _ddetail(false) {}
void enter() {
_sel = _scroll = 0;
_detail = false;
_filter = 0;
_discover_mode = false;
_ddetail = false;
_dsel = 0;
_ctx_menu.active = false;
refresh();
}
int render(DisplayDriver& display) override {
display.setTextSize(1);
// ── discover sub-screen ──────────────────────────────────────────────────
if (_discover_mode) return renderDiscover(display);
// periodic refresh in detail view — preserve selected contact by idx
if (_detail && millis() - _detail_refresh_ms >= DETAIL_REFRESH_MS) {
int saved_contact_idx = (_sel < _count) ? _entries[_sel].contact_idx : -1;
refresh();
bool found = false;
if (saved_contact_idx >= 0) {
for (int i = 0; i < _count; i++) {
if (_entries[i].contact_idx == saved_contact_idx) { _sel = i; found = true; break; }
}
}
if (!found) _detail = false;
_detail_refresh_ms = millis();
}
// ── detail view ──────────────────────────────────────────────────────────
if (_detail && _sel < _count) {
const Entry& e = _entries[_sel];
int hdr = display.headerH();
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, 0, display.width(), hdr - 1);
display.setColor(DisplayDriver::DARK);
char filtered[32];
display.translateUTF8ToBlocks(filtered, e.name, sizeof(filtered));
display.drawTextEllipsized(2, 1, display.width() - 4, filtered);
display.setColor(DisplayDriver::LIGHT);
// 5 lines: lat, lon, dist+bearing, type, seen — compact step, shrink only if needed
int step = display.lineStep();
if (step * 5 > display.height() - hdr) step = (display.height() - hdr) / 5;
char buf[32];
snprintf(buf, sizeof(buf), "Lat: %.5f", e.lat_e6 / 1e6);
display.setCursor(2, hdr); display.print(buf);
snprintf(buf, sizeof(buf), "Lon: %.5f", e.lon_e6 / 1e6);
display.setCursor(2, hdr + step); display.print(buf);
if (e.dist_km >= 0.0f) {
char dist[12];
fmtDist(dist, sizeof(dist), e.dist_km);
int az = bearingDeg(_own_lat, _own_lon, e.lat_e6, e.lon_e6);
snprintf(buf, sizeof(buf), "Dist: %s %s", dist, bearingCardinal(az));
} else {
snprintf(buf, sizeof(buf), "Dist: no GPS");
}
display.setCursor(2, hdr + step * 2); display.print(buf);
snprintf(buf, sizeof(buf), "Type: %s", typeName(e.type));
display.setCursor(2, hdr + step * 3); display.print(buf);
char age[16];
fmtAge(age, sizeof(age), e.lastmod);
snprintf(buf, sizeof(buf), "Seen: %s", age);
display.setCursor(2, hdr + step * 4); display.print(buf);
return 2000;
}
// ── list view ────────────────────────────────────────────────────────────
int item_h = display.lineStep();
int start_y = display.listStart();
int dist_col = display.width() - display.getCharWidth() * 7;
_visible = display.listVisible(item_h);
display.setColor(DisplayDriver::LIGHT);
char title[22];
snprintf(title, sizeof(title), "NEARBY[%s]", FILTER_LABELS[_filter]);
display.drawTextCentered(display.width() / 2, 0, title);
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
if (_count == 0) {
display.drawTextCentered(display.width() / 2, display.height() / 2 - display.lineStep() / 2, "No contacts found");
display.drawTextCentered(display.width() / 2, display.height() / 2 + display.lineStep() / 2, "[Enter]=Discover");
} else {
for (int i = 0; i < _visible && (_scroll + i) < _count; i++) {
int idx = _scroll + i;
bool sel = (idx == _sel);
int y = start_y + i * item_h;
const Entry& e = _entries[idx];
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y - 1, display.width(), item_h - 1);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
char filt[32];
display.translateUTF8ToBlocks(filt, e.name, sizeof(filt));
display.drawTextEllipsized(2, y, dist_col - 4, filt);
display.setColor(sel ? DisplayDriver::DARK : DisplayDriver::LIGHT);
char dist[10];
if (e.dist_km >= 0.0f) fmtDist(dist, sizeof(dist), e.dist_km);
else strncpy(dist, "?GPS", sizeof(dist));
display.setCursor(dist_col, y);
display.print(dist);
}
display.setColor(DisplayDriver::LIGHT);
int cw = display.getCharWidth();
if (_scroll > 0)
{ display.setCursor(display.width() - cw, start_y); display.print("^"); }
if (_scroll + _visible < _count)
{ display.setCursor(display.width() - cw, start_y + (_visible - 1) * item_h); display.print("v"); }
}
if (_ctx_menu.active) {
_ctx_menu.render(display);
return 50;
}
return _count == 0 ? 3000 : 2000;
}
bool handleInput(char c) override {
// ── discover sub-screen ──────────────────────────────────────────────────
if (_discover_mode) return handleInputDiscover(c);
// ── detail view ─────────────────────────────────────────────────────────
if (_detail) {
if (c == KEY_CANCEL || c == KEY_CONTEXT_MENU) { _detail = false; return true; }
return true;
}
// ── context menu ─────────────────────────────────────────────────────────
if (_ctx_menu.active) {
auto res = _ctx_menu.handleInput(c);
if (res == PopupMenu::SELECTED) {
if (_ctx_menu.selectedIndex() == 0)
enterDiscoverMode();
else
_task->gotoToolsScreen();
}
return true;
}
// ── list view ────────────────────────────────────────────────────────────
if (c == KEY_CANCEL) { _task->gotoToolsScreen(); return true; }
if (c == KEY_CONTEXT_MENU) {
_ctx_menu.begin("Options", 2);
_ctx_menu.addItem("Discover nearby");
_ctx_menu.addItem("Back");
return true;
}
if (c == KEY_UP && _sel > 0) {
_sel--;
if (_sel < _scroll) _scroll = _sel;
return true;
}
if (c == KEY_DOWN && _sel < _count - 1) {
_sel++;
if (_sel >= _scroll + _visible) _scroll = _sel - _visible + 1;
return true;
}
if (c == KEY_ENTER && _count == 0) { enterDiscoverMode(); return true; }
if (c == KEY_ENTER && _count > 0) {
_detail = true;
_detail_refresh_ms = millis();
return true;
}
if (c == KEY_LEFT) {
_filter = (_filter + FILTER_COUNT - 1) % FILTER_COUNT;
refresh();
return true;
}
if (c == KEY_RIGHT) {
_filter = (_filter + 1) % FILTER_COUNT;
refresh();
return true;
}
return false;
}
};
const char* NearbyScreen::FILTER_LABELS[6] = { "Fav", "ALL", "Comp", "Rpt", "Room", "Snsr" };
const uint8_t NearbyScreen::FILTER_TYPES[6] = { 0, 0, ADV_TYPE_CHAT, ADV_TYPE_REPEATER, ADV_TYPE_ROOM, ADV_TYPE_SENSOR };

View File

@@ -0,0 +1,90 @@
#pragma once
#include <helpers/ui/DisplayDriver.h>
#include <Arduino.h>
// Generic scrollable popup menu overlay.
// Caller owns item string lifetimes — addItem() stores const char* pointers.
// Navigation wraps around: up from first item goes to last, and vice versa.
struct PopupMenu {
static const int PM_MAX_ITEMS = 16;
static const int PM_BX = 12;
static const int PM_BY = 10;
static const int PM_BW = 104;
static const int PM_ITEM_H = 10;
const char* _items[PM_MAX_ITEMS];
int _count;
int _sel;
int _scroll;
int _visible;
bool active;
const char* _title;
enum Result { NONE, SELECTED, CANCELLED };
PopupMenu() : _count(0), _sel(0), _scroll(0), _visible(3), active(false), _title(nullptr) {}
void begin(const char* title, int visible = 3) {
_count = 0; _sel = 0; _scroll = 0;
_visible = visible; active = true; _title = title;
}
void addItem(const char* item) {
if (_count < PM_MAX_ITEMS) _items[_count++] = item;
}
int render(DisplayDriver& display) {
int vis = (_count < _visible) ? _count : _visible;
int bh = 12 + vis * PM_ITEM_H;
display.setColor(DisplayDriver::DARK);
display.fillRect(PM_BX, PM_BY, PM_BW, bh);
display.setColor(DisplayDriver::LIGHT);
display.drawRect(PM_BX, PM_BY, PM_BW, bh);
display.setCursor(PM_BX + 4, PM_BY + 1);
display.print(_title);
display.fillRect(PM_BX, PM_BY + 10, PM_BW, 1);
if (_scroll > 0)
{ display.setCursor(PM_BX + PM_BW - 7, PM_BY + 1); display.print("^"); }
if (_scroll + vis < _count)
{ display.setCursor(PM_BX + PM_BW - 7, PM_BY + 2 + vis * PM_ITEM_H); display.print("v"); }
for (int i = 0; i < vis && (_scroll + i) < _count; i++) {
int idx = _scroll + i;
int py = PM_BY + 12 + i * PM_ITEM_H;
if (idx == _sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(PM_BX + 1, py - 1, PM_BW - 2, PM_ITEM_H);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(PM_BX + 4, py);
display.print(_items[idx]);
}
display.setColor(DisplayDriver::LIGHT);
return 50;
}
Result handleInput(char c) {
if (_count == 0) { active = false; return CANCELLED; }
if (c == KEY_UP) {
_sel = (_sel > 0) ? _sel - 1 : _count - 1;
if (_sel < _scroll) _scroll = _sel;
else if (_sel == _count - 1 && _count > _visible) _scroll = _count - _visible;
return NONE;
}
if (c == KEY_DOWN) {
_sel = (_sel < _count - 1) ? _sel + 1 : 0;
if (_sel >= _scroll + _visible) _scroll = _sel - _visible + 1;
else if (_sel == 0) _scroll = 0;
return NONE;
}
if (c == KEY_ENTER) { active = false; return SELECTED; }
if (c == KEY_CANCEL || c == KEY_CONTEXT_MENU) { active = false; return CANCELLED; }
return NONE;
}
int selectedIndex() const { return _sel; }
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,342 @@
#pragma once
// Custom screen — not part of upstream UITask.cpp
// Included by UITask.cpp after the global KB_* constants are defined.
class RingtoneEditorScreen : public UIScreen {
UITask* _task;
NodePrefs* _prefs;
static const int MAX_NOTES = 32;
static const int MENU_VISIBLE = 5;
int _visible_notes = 7; // updated in render(); used by clampScroll()
static const uint16_t BPM_OPTS[5];
static const uint8_t DUR_VALS[4];
static const char* DUR_LABELS[4];
static const char PITCH_NAMES[8]; // lowercase rtttl names
uint8_t _notes[MAX_NOTES];
uint8_t _len;
uint8_t _bpm_idx;
int _slot; // 0=melody1, 1=melody2
int _cursor;
int _scroll;
bool _menu_open;
int _menu_sel;
int _menu_scroll;
char _play_buf[220]; // persistent RTTTL buffer — library holds a pointer into it
enum MenuOpt {
M_PLAY_STOP, M_SWITCH, M_DURATION, M_BPM_UP, M_BPM_DOWN,
M_INSERT, M_DELETE, M_SAVE, M_DISCARD, M_COUNT
};
static const char* MENU_LABELS[M_COUNT];
static uint8_t notePitch(uint8_t b) { return b & 0x07; }
static uint8_t noteOctave(uint8_t b) { return ((b >> 3) & 0x03) + 4; }
static uint8_t noteDurIdx(uint8_t b) { return (b >> 5) & 0x03; }
static uint8_t packNote(uint8_t pitch, uint8_t octave, uint8_t dur_idx) {
return (pitch & 0x07) | (((octave - 4) & 0x03) << 3) | ((dur_idx & 0x03) << 5);
}
void clampScroll() {
if (_cursor < _scroll) _scroll = _cursor;
if (_cursor >= _scroll + _visible_notes) _scroll = _cursor - _visible_notes + 1;
if (_scroll < 0) _scroll = 0;
}
void buildRTTTL() {
uint16_t bpm = BPM_OPTS[_bpm_idx < 5 ? _bpm_idx : 2];
int pos = snprintf(_play_buf, sizeof(_play_buf), "Ring:d=8,o=5,b=%u:", bpm);
for (int i = 0; i < _len && pos < (int)sizeof(_play_buf) - 8; i++) {
if (i > 0 && pos < (int)sizeof(_play_buf) - 1) _play_buf[pos++] = ',';
uint8_t pitch = notePitch(_notes[i]);
uint8_t octave = noteOctave(_notes[i]);
uint8_t dur_val = DUR_VALS[noteDurIdx(_notes[i])];
if (pitch == 0)
pos += snprintf(_play_buf + pos, sizeof(_play_buf) - pos, "%dp", dur_val);
else
pos += snprintf(_play_buf + pos, sizeof(_play_buf) - pos, "%d%c%d", dur_val, PITCH_NAMES[pitch], octave);
}
if (pos < (int)sizeof(_play_buf)) _play_buf[pos] = '\0';
}
void previewNote(uint8_t note_byte) {
uint8_t pitch = notePitch(note_byte);
if (pitch == 0) { _task->stopMelody(); return; }
snprintf(_play_buf, sizeof(_play_buf), "P:d=16,o=5,b=240:%c%d", PITCH_NAMES[pitch], noteOctave(note_byte));
_task->playMelody(_play_buf);
}
public:
RingtoneEditorScreen(UITask* task, NodePrefs* prefs) : _task(task), _prefs(prefs), _slot(0) {}
void enter(int slot = 0) {
_slot = (slot == 1) ? 1 : 0;
bool s2 = (_slot == 1);
_bpm_idx = (_prefs && (s2 ? _prefs->ringtone2_bpm_idx : _prefs->ringtone_bpm_idx) < 5)
? (s2 ? _prefs->ringtone2_bpm_idx : _prefs->ringtone_bpm_idx) : 2;
uint8_t rlen = _prefs ? (s2 ? _prefs->ringtone2_len : _prefs->ringtone_len) : 0;
_len = (rlen <= (uint8_t)MAX_NOTES) ? rlen : 0;
if (_prefs) memcpy(_notes, s2 ? _prefs->ringtone2_notes : _prefs->ringtone_notes, sizeof(_notes));
_cursor = 0;
_scroll = 0;
_menu_open = false;
_menu_sel = 0;
_menu_scroll = 0;
}
int render(DisplayDriver& display) override {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
const int lh = display.getLineHeight();
const int cw = display.getCharWidth();
const int cell_w = cw * 2 + 6; // fits 2-char label with margin
const int notes_y = display.listStart();
const int cell_h = lh + 6;
_visible_notes = display.width() / cell_w;
char hdr[32];
snprintf(hdr, sizeof(hdr), "M%d BPM:%u %d/%d", _slot + 1, BPM_OPTS[_bpm_idx], _len, MAX_NOTES);
display.setCursor(0, 0);
display.print(hdr);
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
for (int i = 0; i < _visible_notes; i++) {
int ni = _scroll + i;
int cx = i * cell_w;
bool sel = (ni == _cursor);
if (ni < _len) {
uint8_t pitch = notePitch(_notes[ni]);
uint8_t octave = noteOctave(_notes[ni]);
char label[3];
if (pitch == 0) {
label[0] = '-'; label[1] = '-'; label[2] = '\0';
} else {
label[0] = PITCH_NAMES[pitch] - 32; // uppercase
label[1] = '0' + octave;
label[2] = '\0';
}
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(cx, notes_y, cell_w - 1, cell_h);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
display.drawRect(cx, notes_y, cell_w - 1, cell_h);
}
display.setCursor(cx + (cell_w - cw * 2) / 2, notes_y + 3);
display.print(label);
display.setColor(DisplayDriver::LIGHT);
} else if (ni == _len && _len < MAX_NOTES) {
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(cx, notes_y, cell_w - 1, cell_h);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(cx + (cell_w - cw) / 2, notes_y + 3);
display.print("+");
display.setColor(DisplayDriver::LIGHT);
}
}
const int info_y = notes_y + cell_h + 2;
const int bottom_y = display.height() - display.lineStep();
if (_scroll > 0) { display.setCursor(0, info_y); display.print("<"); }
if (_scroll + _visible_notes <= _len) { display.setCursor(display.width() - display.getCharWidth(), info_y); display.print(">"); }
if (_cursor < _len) {
char info[24];
snprintf(info, sizeof(info), "oct:%d dur:%s",
noteOctave(_notes[_cursor]), DUR_LABELS[noteDurIdx(_notes[_cursor])]);
display.setCursor(display.getCharWidth() + 2, info_y);
display.print(info);
} else if (_cursor == _len) {
display.setCursor(display.getCharWidth() + 2, info_y);
display.print("U/D to add note");
}
display.setCursor(0, bottom_y);
display.print("ENT:oct MENU:opts");
if (_menu_open) {
const int menu_ih = display.lineStep();
const int mw = 100, mh = MENU_VISIBLE * menu_ih + 4;
int mx = (display.width() - mw) / 2;
int my = (display.height() - mh) / 2;
display.setColor(DisplayDriver::DARK);
display.fillRect(mx, my, mw, mh);
display.setColor(DisplayDriver::LIGHT);
display.drawRect(mx, my, mw, mh);
for (int i = 0; i < MENU_VISIBLE; i++) {
int item = _menu_scroll + i;
if (item >= M_COUNT) break;
int iy = my + 2 + i * menu_ih;
bool sel = (item == _menu_sel);
if (sel) {
display.fillRect(mx + 1, iy - 1, mw - 2, menu_ih);
display.setColor(DisplayDriver::DARK);
}
display.setCursor(mx + 4, iy);
if (item == M_PLAY_STOP)
display.print(_task->isMelodyPlaying() ? "Stop" : "Play");
else if (item == M_SWITCH)
display.print(_slot == 0 ? "Edit Melody 2" : "Edit Melody 1");
else
display.print(MENU_LABELS[item]);
display.setColor(DisplayDriver::LIGHT);
}
int cw = display.getCharWidth();
if (_menu_scroll > 0) { display.setCursor(mx + mw - cw - 1, my + 2); display.print("^"); }
if (_menu_scroll + MENU_VISIBLE < M_COUNT) { display.setCursor(mx + mw - cw - 1, my + mh - menu_ih); display.print("v"); }
}
return 200;
}
bool handleInput(char c) override {
bool up = (c == KEY_UP);
bool down = (c == KEY_DOWN);
bool left = (c == KEY_LEFT || c == KEY_PREV);
bool right = (c == KEY_RIGHT || c == KEY_NEXT);
bool enter = (c == KEY_ENTER);
bool menu_key = (c == KEY_CONTEXT_MENU);
bool cancel = (c == KEY_CANCEL);
if (_menu_open) {
if (cancel) { _menu_open = false; return true; }
if (up && _menu_sel > 0) {
_menu_sel--;
if (_menu_sel < _menu_scroll) _menu_scroll = _menu_sel;
return true;
}
if (down && _menu_sel < M_COUNT - 1) {
_menu_sel++;
if (_menu_sel >= _menu_scroll + MENU_VISIBLE) _menu_scroll = _menu_sel - MENU_VISIBLE + 1;
return true;
}
if (!enter) return true;
_menu_open = false;
switch ((MenuOpt)_menu_sel) {
case M_PLAY_STOP:
if (_task->isMelodyPlaying()) {
_task->stopMelody();
} else if (_len > 0) {
buildRTTTL();
_task->playMelody(_play_buf);
}
break;
case M_SWITCH:
_task->stopMelody();
this->enter(1 - _slot);
break;
case M_DURATION:
if (_cursor < _len) {
uint8_t p = notePitch(_notes[_cursor]);
uint8_t o = noteOctave(_notes[_cursor]);
uint8_t di = (noteDurIdx(_notes[_cursor]) + 1) & 0x03;
_notes[_cursor] = packNote(p, o, di);
}
break;
case M_BPM_UP: if (_bpm_idx < 4) _bpm_idx++; break;
case M_BPM_DOWN: if (_bpm_idx > 0) _bpm_idx--; break;
case M_INSERT:
if (_len < MAX_NOTES) {
int ins = (_cursor < _len) ? _cursor + 1 : _cursor;
for (int i = _len; i > ins; i--) _notes[i] = _notes[i - 1];
_notes[ins] = packNote(1, 5, 1);
_len++;
_cursor = ins;
clampScroll();
}
break;
case M_DELETE:
if (_len > 0 && _cursor < _len) {
for (int i = _cursor; i < _len - 1; i++) _notes[i] = _notes[i + 1];
_len--;
if (_cursor >= _len && _len > 0) _cursor = _len - 1;
else if (_len == 0) _cursor = 0;
clampScroll();
}
break;
case M_SAVE:
if (_prefs) {
if (_slot == 1) {
_prefs->ringtone2_bpm_idx = _bpm_idx;
_prefs->ringtone2_len = _len;
memcpy(_prefs->ringtone2_notes, _notes, sizeof(_notes));
} else {
_prefs->ringtone_bpm_idx = _bpm_idx;
_prefs->ringtone_len = _len;
memcpy(_prefs->ringtone_notes, _notes, sizeof(_notes));
}
the_mesh.savePrefs();
}
_task->stopMelody();
_task->gotoToolsScreen();
break;
case M_DISCARD:
_task->stopMelody();
_task->gotoToolsScreen();
break;
default: break;
}
return true;
}
if (cancel) { _task->stopMelody(); _task->gotoToolsScreen(); return true; }
if (menu_key) { _menu_open = true; _menu_sel = 0; _menu_scroll = 0; return true; }
if (left && _cursor > 0) { _cursor--; clampScroll(); return true; }
if (right) {
int max_cur = (_len < MAX_NOTES) ? _len : _len - 1;
if (_cursor < max_cur) { _cursor++; clampScroll(); return true; }
}
if ((up || down) && _cursor == _len && _len < MAX_NOTES) {
_notes[_len] = packNote(1, 5, 1);
_len++;
clampScroll();
}
if ((up || down) && _cursor < _len) {
uint8_t p = notePitch(_notes[_cursor]);
uint8_t o = noteOctave(_notes[_cursor]);
uint8_t di = noteDurIdx(_notes[_cursor]);
if (up) p = (p + 1) & 0x07;
if (down) p = (p + 7) & 0x07;
_notes[_cursor] = packNote(p, o, di);
previewNote(_notes[_cursor]);
return true;
}
if (enter && _cursor < _len) {
uint8_t p = notePitch(_notes[_cursor]);
uint8_t o = noteOctave(_notes[_cursor]);
uint8_t di = noteDurIdx(_notes[_cursor]);
if (p != 0) o = (o < 6) ? o + 1 : 4;
_notes[_cursor] = packNote(p, o, di);
previewNote(_notes[_cursor]);
return true;
}
if (enter && _cursor == _len && _len < MAX_NOTES) {
_notes[_len] = packNote(1, 5, 1);
_len++;
clampScroll();
previewNote(_notes[_cursor]);
return true;
}
return false;
}
};
const uint16_t RingtoneEditorScreen::BPM_OPTS[5] = { 60, 90, 120, 150, 180 };
const uint8_t RingtoneEditorScreen::DUR_VALS[4] = { 4, 8, 16, 32 };
const char* RingtoneEditorScreen::DUR_LABELS[4] = { "1/4", "1/8", "1/16", "1/32" };
const char RingtoneEditorScreen::PITCH_NAMES[8] = { 'p', 'c', 'd', 'e', 'f', 'g', 'a', 'b' };
const char* RingtoneEditorScreen::MENU_LABELS[RingtoneEditorScreen::M_COUNT] = {
"Play/Stop", "Switch Melody", "Duration", "BPM+", "BPM-", "Insert", "Delete", "Save & Exit", "Discard"
};

View File

@@ -0,0 +1,46 @@
#pragma once
// Populates a KeyboardWidget's placeholder list based on live sensor data.
// Only adds placeholders for types that actually returned a value right now.
// Always adds {loc} and {time} via begin(); this helper appends the rest.
#include "KeyboardWidget.h"
#include <helpers/SensorManager.h>
#include <helpers/sensors/LPPDataHelpers.h>
inline void kbAddSensorPlaceholders(KeyboardWidget& kb, SensorManager* sm) {
if (!sm) return;
CayenneLPP lpp(100);
sm->querySensors(0xFF, lpp);
// collect unique LPP types that have actual data
uint8_t present[16];
int pc = 0;
{
LPPReader r(lpp.getBuffer(), lpp.getSize());
uint8_t ch, type;
while (r.readHeader(ch, type)) {
bool already = false;
for (int i = 0; i < pc; i++) if (present[i] == type) { already = true; break; }
if (!already && pc < 16) present[pc++] = type;
r.skipData(type);
}
}
static const struct { uint8_t t; const char* ph; } MAP[] = {
{ LPP_TEMPERATURE, "{temp}" },
{ LPP_RELATIVE_HUMIDITY, "{hum}" },
{ LPP_BAROMETRIC_PRESSURE, "{pres}" },
{ LPP_VOLTAGE, "{batt}" },
{ LPP_ALTITUDE, "{alt}" },
{ LPP_LUMINOSITY, "{lux}" },
{ LPP_DISTANCE, "{dist}" },
{ LPP_CONCENTRATION, "{co2}" },
};
for (const auto& m : MAP) {
for (int i = 0; i < pc; i++) {
if (present[i] == m.t) { kb.addPlaceholder(m.ph); break; }
}
}
}

View File

@@ -0,0 +1,701 @@
#pragma once
// Custom screen — not part of upstream UITask.cpp
// Included by UITask.cpp after SensorPlaceholders.h is defined.
class SettingsScreen : public UIScreen {
UITask* _task;
enum SettingItem {
// Display section
SECTION_DISPLAY,
#if !defined(EINK_DISPLAY_MODEL)
BRIGHTNESS,
#endif
#if AUTO_OFF_MILLIS > 0
AUTO_OFF,
#endif
AUTO_LOCK,
BATT_DISPLAY,
#if !defined(EINK_DISPLAY_MODEL)
CLOCK_SECONDS,
#endif
CLOCK_FORMAT,
FONT,
#if defined(EINK_DISPLAY_MODEL)
ROTATION,
#endif
// Sound section
SECTION_SOUND,
BUZZER,
BUZZER_VOLUME,
DM_MELODY,
CH_MELODY,
// Home pages section
SECTION_HOME_PAGES,
HOME_CLOCK, HOME_RECENT, HOME_RADIO, HOME_BT, HOME_ADVERT,
#if ENV_INCLUDE_GPS == 1
HOME_GPS,
#endif
#if UI_SENSORS_PAGE == 1
HOME_SENSORS,
#endif
HOME_SETTINGS, HOME_QUICK_MSG,
HOME_TOOLS, HOME_SHUTDOWN,
// Radio section
SECTION_RADIO,
TX_POWER,
// System section
SECTION_SYSTEM,
TIMEZONE,
LOW_BAT,
#if ENV_INCLUDE_GPS == 1
// GPS section
SECTION_GPS,
GPS_INTERVAL,
#endif
// Contacts section
SECTION_CONTACTS, DM_FILTER, ROOM_FILTER,
// Messages section
SECTION_MESSAGES,
MSG_SLOT_0, MSG_SLOT_1, MSG_SLOT_2, MSG_SLOT_3, MSG_SLOT_4,
MSG_SLOT_5, MSG_SLOT_6, MSG_SLOT_7, MSG_SLOT_8, MSG_SLOT_9,
Count
};
int _selected;
int _scroll;
int _visible; // items fitting on screen; updated each render, used by handleInput
bool _dirty;
#if AUTO_OFF_MILLIS > 0
static const uint16_t AUTO_OFF_OPTS[5];
static const char* AUTO_OFF_LABELS[5];
static const int AUTO_OFF_COUNT = 5;
#endif
#if ENV_INCLUDE_GPS == 1
static const uint32_t GPS_INTERVAL_OPTS[6];
static const char* GPS_INTERVAL_LABELS[6];
static const int GPS_INTERVAL_COUNT = 6;
#endif
static const uint16_t LOW_BAT_OPTS[7];
static const char* LOW_BAT_LABELS[7];
static const int LOW_BAT_COUNT = 7;
static const char* BATT_DISPLAY_LABELS[3];
static const int BATT_DISPLAY_COUNT = 3;
int lowBatIndex() {
NodePrefs* p = _task->getNodePrefs();
if (!p) return 0;
for (int i = 0; i < LOW_BAT_COUNT; i++)
if (LOW_BAT_OPTS[i] == p->low_batt_mv) return i;
return 0;
}
void renderBar(DisplayDriver& display, int x, int y, int value, int max_val) {
const int gap = 2;
const int avail = display.width() - x;
const int raw = (avail - (max_val - 1) * gap) / max_val;
const int cap = display.getLineHeight() - 2;
const int box_h = raw < cap ? (raw < 2 ? 2 : raw) : cap;
const int box_w = box_h;
for (int i = 0; i < max_val; i++) {
int bx = x + i * (box_w + gap);
display.drawRect(bx, y, box_w, box_h);
if (i < value)
display.fillRect(bx + 1, y + 1, box_w - 2, box_h - 2);
}
}
#if AUTO_OFF_MILLIS > 0
int autoOffIndex() {
NodePrefs* p = _task->getNodePrefs();
if (!p) return 1;
for (int i = 0; i < AUTO_OFF_COUNT; i++)
if (AUTO_OFF_OPTS[i] == p->auto_off_secs) return i;
return 1;
}
#endif
#if ENV_INCLUDE_GPS == 1
int gpsIntervalIndex() {
NodePrefs* p = _task->getNodePrefs();
if (!p) return 0;
for (int i = 0; i < GPS_INTERVAL_COUNT; i++)
if (GPS_INTERVAL_OPTS[i] == p->gps_interval) return i;
return 0;
}
#endif
bool isSection(int item) const {
return item == SECTION_DISPLAY || item == SECTION_SOUND ||
item == SECTION_HOME_PAGES ||
item == SECTION_RADIO || item == SECTION_SYSTEM ||
item == SECTION_CONTACTS || item == SECTION_MESSAGES
#if ENV_INCLUDE_GPS == 1
|| item == SECTION_GPS
#endif
;
}
const char* sectionName(int item) const {
if (item == SECTION_DISPLAY) return "Display";
if (item == SECTION_SOUND) return "Sound";
if (item == SECTION_HOME_PAGES) return "Home Pages";
if (item == SECTION_RADIO) return "Radio";
if (item == SECTION_SYSTEM) return "System";
if (item == SECTION_CONTACTS) return "Contacts";
if (item == SECTION_MESSAGES) return "Messages";
#if ENV_INCLUDE_GPS == 1
if (item == SECTION_GPS) return "GPS";
#endif
return "";
}
bool isHomePage(int item) const {
return item == HOME_CLOCK || item == HOME_RECENT || item == HOME_RADIO ||
item == HOME_BT || item == HOME_ADVERT || item == HOME_TOOLS ||
item == HOME_SHUTDOWN || item == HOME_SETTINGS || item == HOME_QUICK_MSG
#if ENV_INCLUDE_GPS == 1
|| item == HOME_GPS
#endif
#if UI_SENSORS_PAGE == 1
|| item == HOME_SENSORS
#endif
;
}
uint16_t homePageBit(int item) const {
if (item == HOME_CLOCK) return HP_CLOCK;
if (item == HOME_RECENT) return HP_RECENT;
if (item == HOME_RADIO) return HP_RADIO;
if (item == HOME_BT) return HP_BLUETOOTH;
if (item == HOME_ADVERT) return HP_ADVERT;
if (item == HOME_TOOLS) return HP_TOOLS;
if (item == HOME_SHUTDOWN) return HP_SHUTDOWN;
// HOME_SETTINGS and HOME_QUICK_MSG have no mask bit — always visible
#if ENV_INCLUDE_GPS == 1
if (item == HOME_GPS) return HP_GPS;
#endif
#if UI_SENSORS_PAGE == 1
if (item == HOME_SENSORS) return HP_SENSORS;
#endif
return 0;
}
const char* homePageLabel(int item) const {
if (item == HOME_CLOCK) return "Clock";
if (item == HOME_RECENT) return "Recent";
if (item == HOME_RADIO) return "Radio";
if (item == HOME_BT) return "Bluetooth";
if (item == HOME_ADVERT) return "Advert";
if (item == HOME_TOOLS) return "Tools";
if (item == HOME_SHUTDOWN) return "Shutdown";
if (item == HOME_SETTINGS) return "Settings";
if (item == HOME_QUICK_MSG) return "Messages";
#if ENV_INCLUDE_GPS == 1
if (item == HOME_GPS) return "GPS";
#endif
#if UI_SENSORS_PAGE == 1
if (item == HOME_SENSORS) return "Sensors";
#endif
return "";
}
bool homePageVisible(int item, const NodePrefs* p) const {
if (item == HOME_SETTINGS || item == HOME_QUICK_MSG) return true;
uint16_t bit = homePageBit(item);
if (!bit) return false;
uint16_t mask = (p && p->home_pages_mask) ? p->home_pages_mask : HP_ALL;
return (mask & bit) != 0;
}
bool homePageToggleable(int item) const {
return item != HOME_SETTINGS && item != HOME_QUICK_MSG;
}
// Returns the bit-index (0-10) used in page_order for this SettingItem, or -1.
int homePageBitIndex(int item) const {
if (item == HOME_CLOCK) return 0;
if (item == HOME_RECENT) return 1;
if (item == HOME_RADIO) return 2;
if (item == HOME_BT) return 3;
if (item == HOME_ADVERT) return 4;
#if ENV_INCLUDE_GPS == 1
if (item == HOME_GPS) return 5;
#endif
#if UI_SENSORS_PAGE == 1
if (item == HOME_SENSORS) return 6;
#endif
if (item == HOME_TOOLS) return 7;
if (item == HOME_SHUTDOWN) return 8;
if (item == HOME_SETTINGS) return 9;
if (item == HOME_QUICK_MSG) return 10;
return -1;
}
// Returns 1-based position of item in page_order, or 0 if no custom order / not found.
int homePagePosition(int item, const NodePrefs* p) const {
if (!p || p->page_order[0] < 1 || p->page_order[0] > 11) return 0;
int bit = homePageBitIndex(item);
if (bit < 0) return 0;
for (int i = 0; i < 11; i++) {
uint8_t v = p->page_order[i];
if (v < 1 || v > 11) break;
if ((int)(v - 1) == bit) return i + 1;
}
return 0;
}
// Initialises page_order to the default display sequence if not already set.
void ensurePageOrderInit(NodePrefs* p) const {
if (!p) return;
if (p->page_order[0] >= 1 && p->page_order[0] <= 11) return;
// Default: CLOCK RECENT RADIO BT ADVERT [GPS] [SENSORS] SETTINGS TOOLS MESSAGES SHUTDOWN
int j = 0;
p->page_order[j++] = 0 + 1; // CLOCK
p->page_order[j++] = 1 + 1; // RECENT
p->page_order[j++] = 2 + 1; // RADIO
p->page_order[j++] = 3 + 1; // BLUETOOTH
p->page_order[j++] = 4 + 1; // ADVERT
#if ENV_INCLUDE_GPS == 1
p->page_order[j++] = 5 + 1; // GPS
#endif
#if UI_SENSORS_PAGE == 1
p->page_order[j++] = 6 + 1; // SENSORS
#endif
p->page_order[j++] = 9 + 1; // SETTINGS
p->page_order[j++] = 7 + 1; // TOOLS
p->page_order[j++] = 10 + 1; // MESSAGES (QUICK_MSG)
p->page_order[j++] = 8 + 1; // SHUTDOWN
while (j < 11) p->page_order[j++] = 0;
}
// Swaps item's page_order slot with its neighbour in the given direction (-1=earlier, +1=later).
void movePageInOrder(int item, int delta, NodePrefs* p) {
ensurePageOrderInit(p);
int bit = homePageBitIndex(item);
if (bit < 0) return;
int cur = -1, total = 0;
for (int i = 0; i < 11; i++) {
uint8_t v = p->page_order[i];
if (v < 1 || v > 11) break;
if ((int)(v - 1) == bit) cur = i;
total++;
}
if (cur < 0) return;
int next = cur + delta;
if (next < 0 || next >= total) return;
uint8_t tmp = p->page_order[cur];
p->page_order[cur] = p->page_order[next];
p->page_order[next] = tmp;
}
bool isMsgSlot(int item) const {
return item >= MSG_SLOT_0 && item <= MSG_SLOT_9;
}
int msgSlotIndex(int item) const {
return item - MSG_SLOT_0;
}
int nextSelectable(int from) const {
for (int i = from + 1; i < (int)Count; i++)
if (!isSection(i)) return i;
return from;
}
int prevSelectable(int from) const {
for (int i = from - 1; i >= 0; i--)
if (!isSection(i)) return i;
return from;
}
void renderItem(DisplayDriver& display, int item, int y) {
NodePrefs* p = _task->getNodePrefs();
if (isSection(item)) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y, display.width(), 1);
display.setCursor(2, y + 2);
display.print(sectionName(item));
return;
}
bool sel = (item == _selected);
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y - 1, display.width(), display.lineStep());
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(0, y);
display.print(sel ? ">" : " ");
display.setCursor(display.getCharWidth() + 2, y);
#if !defined(EINK_DISPLAY_MODEL)
if (item == BRIGHTNESS) {
display.print("Bright");
renderBar(display, display.valCol(), y, (p ? p->display_brightness : 2) + 1, 5);
} else
#endif
if (item == BUZZER) {
display.print("Buzzer");
display.setCursor(display.valCol(), y);
#ifdef PIN_BUZZER
{ static const char* labels[] = { "ON", "OFF", "Auto" };
int m = _task->getBuzzerMode();
display.print(labels[m < 3 ? m : 0]); }
#else
display.print("N/A");
#endif
} else if (item == BUZZER_VOLUME) {
display.print("BzrVol");
#ifdef PIN_BUZZER
renderBar(display, display.valCol(), y, _task->getBuzzerVolume() + 1, 5);
#else
display.setCursor(display.valCol(), y);
display.print("N/A");
#endif
} else if (item == DM_MELODY) {
display.print("DM sound");
display.setCursor(display.valCol(), y);
{ static const char* L[] = { "built-in", "M1", "M2" };
uint8_t v = p ? p->notif_melody_dm : 0;
display.print(L[v < 3 ? v : 0]); }
} else if (item == CH_MELODY) {
display.print("Ch sound");
display.setCursor(display.valCol(), y);
{ static const char* L[] = { "built-in", "M1", "M2" };
uint8_t v = p ? p->notif_melody_ch : 0;
display.print(L[v < 3 ? v : 0]); }
} else if (isHomePage(item)) {
int pos = homePagePosition(item, p);
if (pos > 0) {
char pb[5]; snprintf(pb, sizeof(pb), "%2d ", pos);
display.print(pb);
}
display.print(homePageLabel(item));
display.setCursor(display.width() - 6 * display.getCharWidth(), y);
if (!homePageToggleable(item))
display.print("always");
else
display.print(homePageVisible(item, p) ? "ON" : "OFF");
} else if (item == TX_POWER) {
display.print("TX Pwr");
char buf[8];
sprintf(buf, "%ddBm", p ? p->tx_power_dbm : 0);
display.setCursor(display.valCol(), y);
display.print(buf);
#if AUTO_OFF_MILLIS > 0
} else if (item == AUTO_OFF) {
display.print("AutoOff");
display.setCursor(display.valCol(), y);
display.print(AUTO_OFF_LABELS[autoOffIndex()]);
#endif
} else if (item == AUTO_LOCK) {
display.print("AutoLock");
display.setCursor(display.valCol(), y);
display.print((p && p->auto_lock) ? "ON" : "OFF");
#if ENV_INCLUDE_GPS == 1
} else if (item == GPS_INTERVAL) {
display.print("GPS upd");
display.setCursor(display.valCol(), y);
display.print(GPS_INTERVAL_LABELS[gpsIntervalIndex()]);
#endif
} else if (item == TIMEZONE) {
display.print("TimeZone");
char buf[8];
int8_t tz = p ? p->tz_offset_hours : 0;
if (tz >= 0) sprintf(buf, "UTC+%d", (int)tz);
else sprintf(buf, "UTC%d", (int)tz);
display.setCursor(display.valCol(), y);
display.print(buf);
} else if (item == LOW_BAT) {
display.print("LowBat");
display.setCursor(display.valCol(), y);
display.print(LOW_BAT_LABELS[lowBatIndex()]);
} else if (item == BATT_DISPLAY) {
display.print("BattDisp");
display.setCursor(display.valCol(), y);
uint8_t mode = p ? p->batt_display_mode : 0;
display.print(BATT_DISPLAY_LABELS[mode < BATT_DISPLAY_COUNT ? mode : 0]);
#if !defined(EINK_DISPLAY_MODEL)
} else if (item == CLOCK_SECONDS) {
display.print("Seconds");
display.setCursor(display.valCol(), y);
display.print((p && p->clock_hide_seconds) ? "OFF" : "ON");
#endif
} else if (item == CLOCK_FORMAT) {
display.print("Format");
display.setCursor(display.valCol(), y);
display.print((p && p->clock_12h) ? "12h" : "24h");
} else if (item == FONT) {
display.print("Font");
display.setCursor(display.valCol(), y);
display.print((p && p->use_lemon_font) ? "Lemon" : "Default");
#if defined(EINK_DISPLAY_MODEL)
} else if (item == ROTATION) {
display.print("Rotation");
display.setCursor(display.valCol(), y);
{ static const char* ROT_LABELS[] = { "0 deg", "90 deg", "180 deg", "270 deg" };
uint8_t r = p ? (p->display_rotation & 3) : 0;
display.print(ROT_LABELS[r]); }
#endif
} else if (item == DM_FILTER) {
display.print("DM");
display.setCursor(display.valCol(), y);
display.print((p && p->dm_show_all) ? "all" : "fav");
} else if (item == ROOM_FILTER) {
display.print("Rooms");
display.setCursor(display.valCol(), y);
display.print((p && p->room_fav_only) ? "fav" : "all");
} else if (isMsgSlot(item)) {
int slot = msgSlotIndex(item);
char label[5];
snprintf(label, sizeof(label), "Q%d:", slot + 1);
display.print(label);
const char* tmpl = (p && p->custom_msgs[slot][0]) ? p->custom_msgs[slot] : "(empty)";
int xm = 8 + display.getCharWidth() * 4;
display.drawTextEllipsized(xm, y, display.width() - xm, tmpl);
}
}
// Keyboard state for editing message slots
int _edit_slot; // -1 = not editing, 0..9 = slot being edited
KeyboardWidget _kb;
public:
SettingsScreen(UITask* task)
: _task(task), _selected(AUTO_LOCK), _scroll(0), _visible(4), _dirty(false), _edit_slot(-1) {}
void markClean() { _dirty = false; }
int render(DisplayDriver& display) override {
display.setTextSize(1);
if (_edit_slot >= 0) {
return _kb.render(display);
}
int item_h = display.lineStep();
int start_y = display.listStart();
_visible = display.listVisible(item_h);
display.setColor(DisplayDriver::LIGHT);
display.drawTextCentered(display.width() / 2, 0, "SETTINGS");
display.fillRect(0, display.headerH() - display.sepH(), display.width(), display.sepH());
for (int i = 0; i < _visible && (_scroll + i) < SettingItem::Count; i++) {
renderItem(display, _scroll + i, start_y + i * item_h);
}
// scroll indicators
if (_scroll > 0) {
display.setColor(DisplayDriver::LIGHT);
display.setCursor(display.width() - display.getCharWidth(), start_y);
display.print("^");
}
if (_scroll + _visible < SettingItem::Count) {
display.setColor(DisplayDriver::LIGHT);
display.setCursor(display.width() - display.getCharWidth(), start_y + (_visible - 1) * item_h);
display.print("v");
}
return 2000;
}
bool handleInput(char c) override {
NodePrefs* p = _task->getNodePrefs();
// Keyboard editing mode for message slots
if (_edit_slot >= 0) {
auto res = _kb.handleInput(c);
if (res == KeyboardWidget::DONE) {
if (p) {
strncpy(p->custom_msgs[_edit_slot], _kb.buf, sizeof(p->custom_msgs[0]) - 1);
p->custom_msgs[_edit_slot][sizeof(p->custom_msgs[0]) - 1] = '\0';
_dirty = true;
}
_edit_slot = -1;
} else if (res == KeyboardWidget::CANCELLED) {
_edit_slot = -1;
}
return true;
}
if (c == KEY_UP) {
int prev = prevSelectable(_selected);
if (prev != _selected) {
_selected = prev;
if (_selected < _scroll) _scroll = _selected;
}
return true;
}
if (c == KEY_DOWN) {
int next = nextSelectable(_selected);
if (next != _selected) {
_selected = next;
if (_selected >= _scroll + _visible) _scroll = _selected - _visible + 1;
}
return true;
}
if (c == KEY_CANCEL) {
if (_dirty) the_mesh.savePrefs();
_task->gotoHomeScreen();
return true;
}
bool right = (c == KEY_RIGHT || c == KEY_NEXT);
bool left = (c == KEY_LEFT || c == KEY_PREV);
bool enter = (c == KEY_ENTER);
#if !defined(EINK_DISPLAY_MODEL)
if (_selected == BRIGHTNESS) {
uint8_t lvl = _task->getBrightnessLevel();
if (right && lvl < 4) { _task->setBrightnessLevel(lvl + 1); _dirty = true; return true; }
if (left && lvl > 0) { _task->setBrightnessLevel(lvl - 1); _dirty = true; return true; }
return right || left;
}
#endif
if (_selected == BUZZER && (left || right || enter)) {
_task->cycleBuzzerMode();
_dirty = true;
return true;
}
if (_selected == BUZZER_VOLUME) {
#ifdef PIN_BUZZER
uint8_t lvl = _task->getBuzzerVolume();
if (right && lvl < 4) { _task->setBuzzerVolumeLevel(lvl + 1); _dirty = true; return true; }
if (left && lvl > 0) { _task->setBuzzerVolumeLevel(lvl - 1); _dirty = true; return true; }
#endif
return right || left;
}
if (_selected == DM_MELODY && p && (left || right || enter)) {
p->notif_melody_dm = (p->notif_melody_dm + (left ? 2 : 1)) % 3;
_dirty = true; return true;
}
if (_selected == CH_MELODY && p && (left || right || enter)) {
p->notif_melody_ch = (p->notif_melody_ch + (left ? 2 : 1)) % 3;
_dirty = true; return true;
}
if (isHomePage(_selected) && p) {
if (left || right) {
movePageInOrder(_selected, left ? -1 : 1, p);
_dirty = true;
return true;
}
if (enter && homePageToggleable(_selected)) {
p->home_pages_mask ^= homePageBit(_selected);
_dirty = true;
return true;
}
return enter;
}
if (_selected == TX_POWER && p) {
if (right && p->tx_power_dbm < 22) { p->tx_power_dbm++; _task->applyTxPower(); _dirty = true; return true; }
if (left && p->tx_power_dbm > 2) { p->tx_power_dbm--; _task->applyTxPower(); _dirty = true; return true; }
}
#if AUTO_OFF_MILLIS > 0
if (_selected == AUTO_OFF && p) {
int idx = autoOffIndex();
if (right) idx = (idx + 1) % AUTO_OFF_COUNT;
if (left) idx = (idx + AUTO_OFF_COUNT - 1) % AUTO_OFF_COUNT;
if (left || right) { p->auto_off_secs = AUTO_OFF_OPTS[idx]; _dirty = true; return true; }
}
#endif
if (_selected == AUTO_LOCK && p && (left || right || enter)) {
p->auto_lock ^= 1;
_dirty = true;
return true;
}
#if ENV_INCLUDE_GPS == 1
if (_selected == GPS_INTERVAL && p) {
int idx = gpsIntervalIndex();
if (right) idx = (idx + 1) % GPS_INTERVAL_COUNT;
if (left) idx = (idx + GPS_INTERVAL_COUNT - 1) % GPS_INTERVAL_COUNT;
if (left || right) {
p->gps_interval = GPS_INTERVAL_OPTS[idx];
_task->applyGPSInterval();
_dirty = true;
return true;
}
}
#endif
if (_selected == TIMEZONE && p) {
if (right && p->tz_offset_hours < 14) { p->tz_offset_hours++; _dirty = true; return true; }
if (left && p->tz_offset_hours > -12) { p->tz_offset_hours--; _dirty = true; return true; }
}
if (_selected == LOW_BAT && p) {
int idx = lowBatIndex();
if (right) idx = (idx + 1) % LOW_BAT_COUNT;
if (left) idx = (idx + LOW_BAT_COUNT - 1) % LOW_BAT_COUNT;
if (left || right) { p->low_batt_mv = LOW_BAT_OPTS[idx]; _dirty = true; return true; }
}
if (_selected == BATT_DISPLAY && p) {
int idx = p->batt_display_mode < BATT_DISPLAY_COUNT ? p->batt_display_mode : 0;
if (right) idx = (idx + 1) % BATT_DISPLAY_COUNT;
if (left) idx = (idx + BATT_DISPLAY_COUNT - 1) % BATT_DISPLAY_COUNT;
if (left || right) { p->batt_display_mode = idx; _dirty = true; return true; }
}
#if !defined(EINK_DISPLAY_MODEL)
if (_selected == CLOCK_SECONDS && p && (left || right || enter)) {
p->clock_hide_seconds ^= 1;
_dirty = true;
return true;
}
#endif
if (_selected == CLOCK_FORMAT && p && (left || right || enter)) {
p->clock_12h ^= 1;
_dirty = true;
return true;
}
if (_selected == FONT && p && (left || right || enter)) {
p->use_lemon_font ^= 1;
_task->applyFont();
_dirty = true;
return true;
}
#if defined(EINK_DISPLAY_MODEL)
if (_selected == ROTATION && p && (left || right || enter)) {
p->display_rotation = (p->display_rotation + (left ? 3 : 1)) & 3;
_task->applyRotation();
_dirty = true;
return true;
}
#endif
if (_selected == DM_FILTER && p && (left || right || enter)) {
p->dm_show_all = p->dm_show_all ? 0 : 1;
_dirty = true;
return true;
}
if (_selected == ROOM_FILTER && p && (left || right || enter)) {
p->room_fav_only = p->room_fav_only ? 0 : 1;
_dirty = true;
return true;
}
if (isMsgSlot(_selected) && enter) {
int slot = msgSlotIndex(_selected);
_edit_slot = slot;
_kb.begin(p ? p->custom_msgs[slot] : "");
kbAddSensorPlaceholders(_kb, &sensors);
return true;
}
return false;
}
};
#if AUTO_OFF_MILLIS > 0
const uint16_t SettingsScreen::AUTO_OFF_OPTS[5] = { 5, 15, 30, 60, 0 };
const char* SettingsScreen::AUTO_OFF_LABELS[5] = { "5s", "15s", "30s", "60s", "never" };
#endif
#if ENV_INCLUDE_GPS == 1
const uint32_t SettingsScreen::GPS_INTERVAL_OPTS[6] = { 0, 30, 60, 300, 900, 1800 };
const char* SettingsScreen::GPS_INTERVAL_LABELS[6] = { "off", "30s", "1min", "5min", "15min", "30min" };
#endif
const uint16_t SettingsScreen::LOW_BAT_OPTS[7] = { 0, 3000, 3100, 3200, 3300, 3400, 3500 };
const char* SettingsScreen::LOW_BAT_LABELS[7] = { "off", "3.0V", "3.1V", "3.2V", "3.3V", "3.4V", "3.5V" };
const char* SettingsScreen::BATT_DISPLAY_LABELS[3] = { "icon", "%", "V" };

View File

@@ -0,0 +1,57 @@
#pragma once
// Custom screen — not part of upstream UITask.cpp
// Included by UITask.cpp just before HomeScreen.
class ToolsScreen : public UIScreen {
UITask* _task;
int _sel;
static const int ITEM_COUNT = 4;
static const char* ITEMS[ITEM_COUNT];
public:
ToolsScreen(UITask* task) : _task(task), _sel(0) {}
int render(DisplayDriver& display) override {
display.setTextSize(1);
display.setColor(DisplayDriver::LIGHT);
display.drawTextCentered(display.width() / 2, 0, "TOOLS");
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
int item_h = display.lineStep();
int start_y = display.listStart();
int cw = display.getCharWidth();
for (int i = 0; i < ITEM_COUNT; i++) {
int y = start_y + i * item_h;
bool sel = (i == _sel);
if (sel) {
display.setColor(DisplayDriver::LIGHT);
display.fillRect(0, y - 1, display.width(), item_h);
display.setColor(DisplayDriver::DARK);
} else {
display.setColor(DisplayDriver::LIGHT);
}
display.setCursor(0, y);
display.print(sel ? ">" : " ");
display.setCursor(cw + 2, y);
display.print(ITEMS[i]);
}
display.setColor(DisplayDriver::LIGHT);
return 500;
}
bool handleInput(char c) override {
if (c == KEY_UP && _sel > 0) { _sel--; return true; }
if (c == KEY_DOWN && _sel < ITEM_COUNT - 1) { _sel++; return true; }
if (c == KEY_CANCEL || c == KEY_CONTEXT_MENU) { _task->gotoHomeScreen(); return true; }
if (c == KEY_ENTER) {
if (_sel == 0) { _task->gotoRingtoneEditor(); return true; }
if (_sel == 1) { _task->gotoBotScreen(); return true; }
if (_sel == 2) { _task->gotoNearbyScreen(); return true; }
if (_sel == 3) { _task->gotoAutoAdvertScreen(); return true; }
}
return false;
}
};
const char* ToolsScreen::ITEMS[4] = { "Ringtone Editor", "Auto-Reply Bot", "Nearby Nodes", "Auto-Advert" };

File diff suppressed because it is too large Load Diff

View File

@@ -33,10 +33,24 @@ class UITask : public AbstractUITask {
#endif
unsigned long _next_refresh, _auto_off;
NodePrefs* _node_prefs;
bool _locked;
unsigned long _lock_wake_until; // when to blank screen again after locked wake (5s)
int _lock_seq_count; // Enter presses while Back held (lock/unlock sequence)
unsigned long _lock_seq_ms; // millis() of last lock-sequence press (for timeout)
bool _lock_seq_used; // true = suppress next back_btn CLICK (post-sequence release)
char _alert[80];
char _notif_mel_buf[220]; // persistent RTTTL buffer for custom notification melodies
unsigned long _alert_expiry;
int _msgcount;
int _room_unread;
int _last_notif_ch_idx;
uint8_t _last_notif_dm_prefix[4];
bool _last_notif_dm_valid;
struct DMUnreadEntry { uint8_t prefix[4]; uint8_t count; };
static const int DM_UNREAD_TABLE_SIZE = 16;
DMUnreadEntry _dm_unread_table[DM_UNREAD_TABLE_SIZE];
unsigned long ui_started_at, next_batt_chck;
uint16_t _batt_mv; // EMA-filtered battery voltage
int next_backlight_btn_check = 0;
#ifdef PIN_STATUS_LED
int led_state = 0;
@@ -50,7 +64,14 @@ class UITask : public AbstractUITask {
UIScreen* splash;
UIScreen* home;
UIScreen* msg_preview;
UIScreen* settings;
UIScreen* quick_msg;
UIScreen* tools_screen;
UIScreen* ringtone_edit;
UIScreen* bot_screen;
UIScreen* nearby_screen;
UIScreen* dashboard_config;
UIScreen* auto_advert_screen;
UIScreen* curr;
void userLedHandler();
@@ -65,16 +86,55 @@ class UITask : public AbstractUITask {
public:
UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) {
UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL), _node_prefs(NULL) {
next_batt_chck = _next_refresh = 0;
ui_started_at = 0;
_batt_mv = 0;
_msgcount = _room_unread = 0;
_locked = false;
_lock_wake_until = 0;
_lock_seq_count = 0; _lock_seq_ms = 0; _lock_seq_used = false;
_last_notif_ch_idx = -1;
_last_notif_dm_valid = false;
memset(_last_notif_dm_prefix, 0, sizeof(_last_notif_dm_prefix));
memset(_dm_unread_table, 0, sizeof(_dm_unread_table));
curr = NULL;
}
void begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs);
NodePrefs* getNodePrefs() const { return _node_prefs; }
uint16_t getBattMilliVolts() const { return _batt_mv > 0 ? _batt_mv : AbstractUITask::getBattMilliVolts(); }
void gotoHomeScreen() { setCurrScreen(home); }
void gotoSettingsScreen();
void gotoQuickMsgScreen();
void gotoToolsScreen();
void gotoRingtoneEditor(int slot = 0);
void gotoBotScreen();
void gotoNearbyScreen();
void gotoDashboardConfig();
void gotoAutoAdvertScreen();
void playMelody(const char* melody);
void stopMelody();
bool isMelodyPlaying();
void showAlert(const char* text, int duration_millis);
void addChannelMsg(uint8_t channel_idx, const char* text) override;
void addDMMsg(const uint8_t* pub_key, bool outgoing, const char* text) override;
int getDMUnreadTotal() const;
int getMsgCount() const { return _msgcount; }
int getChannelUnreadCount() const;
int getRoomUnreadCount() const { return _room_unread; }
void clearRoomUnread() { _room_unread = 0; }
uint8_t getDMUnread(const uint8_t* pub_key) const {
for (int i = 0; i < DM_UNREAD_TABLE_SIZE; i++)
if (_dm_unread_table[i].count > 0 && memcmp(_dm_unread_table[i].prefix, pub_key, 4) == 0)
return _dm_unread_table[i].count;
return 0;
}
void clearDMUnread(const uint8_t* pub_key) {
for (int i = 0; i < DM_UNREAD_TABLE_SIZE; i++)
if (_dm_unread_table[i].count > 0 && memcmp(_dm_unread_table[i].prefix, pub_key, 4) == 0)
{ _dm_unread_table[i].count = 0; return; }
}
bool hasDisplay() const { return _display != NULL; }
bool isButtonPressed() const;
@@ -87,13 +147,28 @@ public:
}
void toggleBuzzer();
void cycleBuzzerMode(); // ON → OFF → Auto → ON
int getBuzzerMode(); // 0=ON, 1=OFF, 2=Auto
bool getGPSState();
void toggleGPS();
void applyBrightness();
void setBrightnessLevel(uint8_t level);
uint8_t getBrightnessLevel() const { return _node_prefs ? _node_prefs->display_brightness : 2; }
void setBuzzerVolumeLevel(uint8_t level);
uint8_t getBuzzerVolume() const { return _node_prefs ? _node_prefs->buzzer_volume : 4; }
void applyTxPower();
void applyGPSInterval();
void applyFont();
void applyRotation();
uint32_t autoOffMillis() const {
if (!_node_prefs || _node_prefs->auto_off_secs == 0) return 0;
return (uint32_t)_node_prefs->auto_off_secs * 1000UL;
}
// from AbstractUITask
void msgRead(int msgcount) override;
void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override;
void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount, uint8_t contact_type = 0, const uint8_t* pub_key = nullptr) override;
void notify(UIEventType t = UIEventType::none) override;
void loop() override;

View File

@@ -50,7 +50,9 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
uint8_t path_sz = flags & 0x03; // NEW v1.11+: lower 2 bits is path hash size
uint8_t len = pkt->payload_len - i;
uint8_t offset = pkt->path_len << path_sz;
// path_len*entry_size can exceed 255 (path_len up to 63, entry_size up to 8);
// a uint8_t offset would wrap and steer the isHashMatch() read to the wrong place.
uint16_t offset = (uint16_t)pkt->path_len << path_sz;
if (offset >= len) { // TRACE has reached end of given path
onTraceRecv(pkt, trace_tag, auth_code, flags, pkt->path, &pkt->payload[i], len);
} else if (self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->hasSeen(pkt)) {

View File

@@ -14,6 +14,10 @@ public:
virtual bool isEnabled() const = 0;
virtual bool isConnected() const = 0;
// Returns true when a BLE companion app is connected. Default delegates to
// isConnected(); override in dual-interface wrappers that always report
// isConnected()=true but still need to distinguish BLE from USB state.
virtual bool isBLEConnected() const { return isConnected(); }
virtual bool isWriteBusy() const = 0;
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;

View File

@@ -23,6 +23,7 @@ public:
virtual const char* getSettingValue(int i) const { return NULL; }
virtual bool setSettingValue(const char* name, const char* value) { return false; }
virtual LocationProvider* getLocationProvider() { return NULL; }
virtual int getAvailableLPPTypes(uint8_t* types, int max_count) const { return 0; }
// Helper functions to manage setting by keys (useful in many places ...)
const char* getSettingByKey(const char* key) {

View File

@@ -0,0 +1,68 @@
#pragma once
#include "../BaseSerialInterface.h"
#include "../ArduinoSerialInterface.h"
#include "SerialBLEInterface.h"
// Wraps BLE + USB serial interfaces: BLE takes priority when connected,
// USB is always ready as a fallback.
// enable()/disable() control BLE only — USB is always on.
// BLE state machine is only pumped when BLE is enabled; USB is not read while BLE is connected.
class DualSerialInterface : public BaseSerialInterface {
SerialBLEInterface _ble;
ArduinoSerialInterface _usb;
uint8_t _ble_buf[MAX_FRAME_SIZE];
uint8_t _usb_buf[MAX_FRAME_SIZE];
bool _ble_enabled;
bool _ble_was_connected;
public:
DualSerialInterface() : _ble_enabled(false), _ble_was_connected(false) {}
void begin(const char* ble_prefix, char* node_name, uint32_t pin_code, Stream& usb_stream) {
_ble.begin(ble_prefix, node_name, pin_code);
_usb.begin(usb_stream);
_usb.enable(); // USB is always on
}
void enable() override { _ble.enable(); _ble_enabled = true; }
void disable() override { _ble.disable(); _ble_enabled = false; }
bool isEnabled() const override { return _ble_enabled; }
// Always true — USB is always available as fallback, so the mesh can send.
bool isConnected() const override { return true; }
// True only when a BLE companion app is paired and connected.
bool isBLEConnected() const override { return _ble_enabled && _ble.isConnected(); }
bool isWriteBusy() const override {
return (_ble_enabled && _ble.isConnected()) ? _ble.isWriteBusy() : _usb.isWriteBusy();
}
size_t writeFrame(const uint8_t src[], size_t len) override {
return (_ble_enabled && _ble.isConnected()) ? _ble.writeFrame(src, len) : _usb.writeFrame(src, len);
}
size_t checkRecvFrame(uint8_t dest[]) override {
if (_ble_enabled) {
size_t ble_len = _ble.checkRecvFrame(_ble_buf);
bool ble_now = _ble.isConnected();
if (ble_now) {
_ble_was_connected = true;
if (ble_len > 0) { memcpy(dest, _ble_buf, ble_len); return ble_len; }
return 0; // BLE active — don't read USB to keep its state machine clean
}
if (_ble_was_connected) {
// BLE just disconnected — reset USB state machine so stale partial frames don't block it
_ble_was_connected = false;
_usb.enable();
return 0;
}
}
size_t usb_len = _usb.checkRecvFrame(_usb_buf);
if (usb_len > 0) { memcpy(dest, _usb_buf, usb_len); return usb_len; }
return 0;
}
};

View File

@@ -540,6 +540,46 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen
}
int EnvironmentSensorManager::getAvailableLPPTypes(uint8_t* types, int max_count) const {
int n = 0;
auto add = [&](uint8_t t) { if (n < max_count) types[n++] = t; };
add(LPP_VOLTAGE); // battery voltage — always present
#if ENV_INCLUDE_GPS
add(LPP_GPS);
#endif
bool has_temp = AHTX0_initialized || BME680_initialized || BME280_initialized ||
BMP280_initialized || SHTC3_initialized || SHT4X_initialized ||
LPS22HB_initialized || MLX90614_initialized || BMP085_initialized ||
RAK12035_initialized;
if (has_temp) add(LPP_TEMPERATURE);
bool has_hum = AHTX0_initialized || BME680_initialized || BME280_initialized ||
SHTC3_initialized || SHT4X_initialized || RAK12035_initialized;
if (has_hum) add(LPP_RELATIVE_HUMIDITY);
bool has_press = BME680_initialized || LPS22HB_initialized;
if (has_press) add(LPP_BAROMETRIC_PRESSURE);
bool has_alt = BME680_initialized || BME280_initialized || BMP280_initialized || BMP085_initialized;
if (has_alt) add(LPP_ALTITUDE);
bool has_power = INA3221_initialized || INA219_initialized || INA260_initialized || INA226_initialized;
if (has_power) { add(LPP_CURRENT); add(LPP_POWER); }
#if ENV_INCLUDE_VL53L0X
if (VL53L0X_initialized) add(LPP_DISTANCE);
#endif
#if ENV_INCLUDE_RAK12035
if (RAK12035_initialized) add(LPP_PERCENTAGE);
#endif
return n;
}
int EnvironmentSensorManager::getNumSettings() const {
int settings = 0;
#if ENV_INCLUDE_GPS

View File

@@ -49,6 +49,7 @@ public:
#endif
bool begin() override;
bool querySensors(uint8_t requester_permissions, CayenneLPP& telemetry) override;
int getAvailableLPPTypes(uint8_t* types, int max_count) const override;
#if ENV_INCLUDE_GPS
void loop() override;
#endif

View File

@@ -136,6 +136,22 @@ public:
m = getFloat(&_buf[_pos], 2, 1, true); _pos += 2;
return _pos <= _len;
}
bool readLuminosity(float& lux) {
lux = getFloat(&_buf[_pos], 2, 1, false); _pos += 2;
return _pos <= _len;
}
bool readPercentage(float& pct) {
pct = getFloat(&_buf[_pos], 1, 1, false); _pos += 1;
return _pos <= _len;
}
bool readConcentration(float& ppm) {
ppm = getFloat(&_buf[_pos], 2, 1, false); _pos += 2;
return _pos <= _len;
}
bool readDistance(float& m) {
m = getFloat(&_buf[_pos], 4, 1000, false); _pos += 4;
return _pos <= _len;
}
void skipData(uint8_t type) {
switch (type) {

View File

@@ -7,6 +7,7 @@ class DisplayDriver {
int _w, _h;
protected:
DisplayDriver(int w, int h) { _w = w; _h = h; }
void setDimensions(int w, int h) { _w = w; _h = h; }
public:
enum Color { DARK=0, LIGHT, RED, GREEN, BLUE, YELLOW, ORANGE }; // on b/w screen, colors will be !=0 synonym of light
@@ -27,6 +28,21 @@ public:
virtual void drawRect(int x, int y, int w, int h) = 0;
virtual void drawXbm(int x, int y, const uint8_t* bits, int w, int h) = 0;
virtual uint16_t getTextWidth(const char* str) = 0;
virtual int getCharWidth() const { return 6; } // typical character advance width (px)
virtual int getLineHeight() const { return 8; } // pixel rows per text line
virtual void setLemonFont(bool) { } // no-op; overridden by displays that support Lemon
// Layout helpers — derived from font metrics and screen size.
// Use these instead of hardcoded pixel values so layouts adapt to any display.
int lineStep() const { return getLineHeight() + 2; } // row pitch: text + gap
int headerH() const { return getLineHeight() + 3; } // title bar height
int listStart() const { return headerH(); } // y where list items begin
int listVisible(int itemH) const { return (height() - listStart()) / itemH; }
int listVisible() const { return listVisible(lineStep()); }
// x where a right-side value column starts (leaves ~8 chars for the value)
int valCol() const { return width() - getCharWidth() * 8; }
// separator line thickness: 2px on landscape e-ink, 1px on OLED
int sepH() const { return (width() >= height()) ? 2 : 1; }
virtual void drawTextCentered(int mid_x, int y, const char* str) { // helper method (override to optimise)
int w = getTextWidth(str);
setCursor(mid_x - w/2, y);
@@ -42,17 +58,112 @@ public:
print(str);
}
// convert UTF-8 characters to displayable block characters for compatibility
static char transliterateCodepoint(uint32_t cp) {
switch (cp) {
// Polish
case 0x0105: return 'a'; case 0x0104: return 'A'; // ą Ą
case 0x0107: return 'c'; case 0x0106: return 'C'; // ć Ć
case 0x0119: return 'e'; case 0x0118: return 'E'; // ę Ę
case 0x0142: return 'l'; case 0x0141: return 'L'; // ł Ł
case 0x0144: return 'n'; case 0x0143: return 'N'; // ń Ń
case 0x00F3: return 'o'; case 0x00D3: return 'O'; // ó Ó
case 0x015B: return 's'; case 0x015A: return 'S'; // ś Ś
case 0x017A: return 'z'; case 0x0179: return 'Z'; // ź Ź
case 0x017C: return 'z'; case 0x017B: return 'Z'; // ż Ż
// Czech/Slovak
case 0x010D: return 'c'; case 0x010C: return 'C'; // č Č
case 0x0161: return 's'; case 0x0160: return 'S'; // š Š
case 0x017E: return 'z'; case 0x017D: return 'Z'; // ž Ž
case 0x0159: return 'r'; case 0x0158: return 'R'; // ř Ř
case 0x011B: return 'e'; case 0x011A: return 'E'; // ě Ě
case 0x016F: return 'u'; case 0x016E: return 'U'; // ů Ů
case 0x010F: return 'd'; case 0x010E: return 'D'; // ď Ď
case 0x0165: return 't'; case 0x0164: return 'T'; // ť Ť
case 0x0148: return 'n'; case 0x0147: return 'N'; // ň Ň
case 0x013E: return 'l'; case 0x013D: return 'L'; // ľ Ľ
case 0x013A: return 'l'; case 0x0139: return 'L'; // ĺ Ĺ
case 0x0155: return 'r'; case 0x0154: return 'R'; // ŕ Ŕ
// German
case 0x00E4: return 'a'; case 0x00C4: return 'A'; // ä Ä
case 0x00F6: return 'o'; case 0x00D6: return 'O'; // ö Ö
case 0x00FC: return 'u'; case 0x00DC: return 'U'; // ü Ü
case 0x00DF: return 's'; // ß
// Scandinavian
case 0x00E5: return 'a'; case 0x00C5: return 'A'; // å Å
case 0x00F8: return 'o'; case 0x00D8: return 'O'; // ø Ø
case 0x00E6: return 'a'; case 0x00C6: return 'A'; // æ Æ
// Hungarian
case 0x0151: return 'o'; case 0x0150: return 'O'; // ő Ő
case 0x0171: return 'u'; case 0x0170: return 'U'; // ű Ű
// Romanian
case 0x0103: return 'a'; case 0x0102: return 'A'; // ă Ă
case 0x0219: return 's'; case 0x0218: return 'S'; // ș Ș
case 0x021B: return 't'; case 0x021A: return 'T'; // ț Ț
// Croatian
case 0x0111: return 'd'; case 0x0110: return 'D'; // đ Đ
// Icelandic
case 0x00F0: return 'd'; case 0x00D0: return 'D'; // ð Ð (eth)
case 0x00FE: return 't'; case 0x00DE: return 'T'; // þ Þ (thorn)
// Romanian cedilla variants (legacy encoding)
case 0x0163: return 't'; case 0x0162: return 'T'; // ţ Ţ
// Turkish
case 0x011F: return 'g'; case 0x011E: return 'G'; // ğ Ğ
case 0x015F: return 's'; case 0x015E: return 'S'; // ş Ş
case 0x0131: return 'i'; // ı
// Baltic (Lithuanian/Latvian)
case 0x0101: return 'a'; case 0x0100: return 'A'; // ā Ā
case 0x0113: return 'e'; case 0x0112: return 'E'; // ē Ē
case 0x012B: return 'i'; case 0x012A: return 'I'; // ī Ī
case 0x016B: return 'u'; case 0x016A: return 'U'; // ū Ū
case 0x0123: return 'g'; case 0x0122: return 'G'; // ģ Ģ
case 0x0137: return 'k'; case 0x0136: return 'K'; // ķ Ķ
case 0x013C: return 'l'; case 0x013B: return 'L'; // ļ Ļ
case 0x0146: return 'n'; case 0x0145: return 'N'; // ņ Ņ
case 0x0157: return 'r'; case 0x0156: return 'R'; // ŗ Ŗ
case 0x0173: return 'u'; case 0x0172: return 'U'; // ų Ų
case 0x0117: return 'e'; case 0x0116: return 'E'; // ė Ė
case 0x012F: return 'i'; case 0x012E: return 'I'; // į Į
// French/Spanish/Portuguese common accents
case 0x00E0: case 0x00E1: case 0x00E2: case 0x00E3: return 'a';
case 0x00C0: case 0x00C1: case 0x00C2: case 0x00C3: return 'A';
case 0x00E8: case 0x00E9: case 0x00EA: case 0x00EB: return 'e';
case 0x00C8: case 0x00C9: case 0x00CA: case 0x00CB: return 'E';
case 0x00EC: case 0x00ED: case 0x00EE: case 0x00EF: return 'i';
case 0x00CC: case 0x00CD: case 0x00CE: case 0x00CF: return 'I';
case 0x00F2: case 0x00F4: case 0x00F5: return 'o';
case 0x00D2: case 0x00D4: case 0x00D5: return 'O';
case 0x00F9: case 0x00FA: case 0x00FB: return 'u';
case 0x00D9: case 0x00DA: case 0x00DB: return 'U';
case 0x00E7: return 'c'; case 0x00C7: return 'C'; // ç Ç
case 0x00F1: return 'n'; case 0x00D1: return 'N'; // ñ Ñ
case 0x00FD: return 'y'; case 0x00DD: return 'Y'; // ý Ý
default: return '?';
}
}
// convert UTF-8 to ASCII, transliterating accented/diacritic characters
virtual void translateUTF8ToBlocks(char* dest, const char* src, size_t dest_size) {
size_t j = 0;
for (size_t i = 0; src[i] != 0 && j < dest_size - 1; i++) {
unsigned char c = (unsigned char)src[i];
if (c >= 32 && c <= 126) {
dest[j++] = c; // ASCII printable
} else if (c >= 0x80) {
dest[j++] = '\xDB'; // CP437 full block █
while (src[i+1] && (src[i+1] & 0xC0) == 0x80)
i++; // skip UTF-8 continuation bytes
const uint8_t* p = (const uint8_t*)src;
while (*p && j < dest_size - 1) {
uint8_t c = *p++;
if (c < 0x80) {
if (c >= 32) dest[j++] = c;
} else {
uint32_t cp = c;
if ((c & 0xE0) == 0xC0) {
cp = c & 0x1F;
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
} else if ((c & 0xF0) == 0xE0) {
cp = c & 0x0F;
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
} else {
while (*p && (*p & 0xC0) == 0x80) p++;
dest[j++] = '\xDB';
continue;
}
dest[j++] = transliterateCodepoint(cp);
}
}
dest[j] = 0;
@@ -61,10 +172,7 @@ public:
// draw text with ellipsis if it exceeds max_width
virtual void drawTextEllipsized(int x, int y, int max_width, const char* str) {
char temp_str[256]; // reasonable buffer size
size_t len = strlen(str);
if (len >= sizeof(temp_str)) len = sizeof(temp_str) - 1;
memcpy(temp_str, str, len);
temp_str[len] = 0;
translateUTF8ToBlocks(temp_str, str, sizeof(temp_str));
if (getTextWidth(temp_str) <= max_width) {
setCursor(x, y);
@@ -90,11 +198,17 @@ public:
while (str_len > 0 && getTextWidth(temp_str) > max_width - ellipsis_width) {
temp_str[--str_len] = 0;
}
// Strip orphaned UTF-8 leading byte left by byte-at-a-time trimming above.
while (str_len > 0 && ((uint8_t)temp_str[str_len - 1] & 0xC0) == 0xC0) {
temp_str[--str_len] = 0;
}
strcat(temp_str, ellipsis);
setCursor(x, y);
print(temp_str);
}
virtual void setBrightness(uint8_t level) { } // level 0-4 (min to max), no-op default
virtual void setDisplayRotation(uint8_t rot) { } // 0-3, no-op for fixed-orientation displays
virtual void endFrame() = 0;
};

View File

@@ -1,4 +1,3 @@
#include "GxEPDDisplay.h"
#ifdef EXP_PIN_BACKLIGHT
@@ -7,13 +6,22 @@
#endif
#ifndef DISPLAY_ROTATION
#define DISPLAY_ROTATION 3
#define DISPLAY_ROTATION 0
#endif
#ifdef ESP32
SPIClass SPI1 = SPIClass(FSPI);
#endif
// GFX fonts use the baseline as the cursor origin. UI code assumes top-of-cell
// coordinates (same convention as the OLED driver). Add the font ascender so
// the two conventions match.
static int fontAscender(int sz, bool use_lemon, int scale) {
if (sz == 3) return 26; // FreeSans18pt7b: proportional, baseline origin
if (sz == 1 && use_lemon) return 8 * scale; // Lemon GFX font: baseline origin, ascender 8px×scale
return 0; // GFX built-in font: cursor is top-left of cell
}
bool GxEPDDisplay::begin() {
display.epd2.selectSPI(SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0));
#ifdef ESP32
@@ -23,15 +31,14 @@ bool GxEPDDisplay::begin() {
#endif
display.init(115200, true, 2, false);
display.setRotation(DISPLAY_ROTATION);
setTextSize(1); // Default to size 1
setTextSize(1);
display.setPartialWindow(0, 0, display.width(), display.height());
display.fillScreen(GxEPD_WHITE);
display.display(true);
#if DISP_BACKLIGHT
#if DISP_BACKLIGHT
digitalWrite(DISP_BACKLIGHT, LOW);
pinMode(DISP_BACKLIGHT, OUTPUT);
#endif
#endif
_init = true;
return true;
}
@@ -64,30 +71,39 @@ void GxEPDDisplay::clear() {
void GxEPDDisplay::startFrame(Color bkg) {
display.fillScreen(GxEPD_WHITE);
display.setTextColor(_curr_color = GxEPD_BLACK);
_text_sz = 1;
int sc = (width() >= height()) ? 2 : 1;
display.setFont(_use_lemon ? &Lemon : NULL);
display.setTextSize(sc);
display_crc.reset();
}
void GxEPDDisplay::setTextSize(int sz) {
_text_sz = sz;
display_crc.update<int>(sz);
switch(sz) {
case 1: // Small
display.setFont(&FreeSans9pt7b);
break;
case 2: // Medium Bold
display.setFont(&FreeSansBold12pt7b);
break;
case 3: // Large
// Size 1 scales with orientation: 1× in portrait (≈OLED width), 2× in landscape.
// Size 2 always uses 2× built-in (12×16) — fixed because layout Y-positions are hardcoded.
// Size 3 always uses FreeSans18pt for large headings.
int sc = (width() >= height()) ? 2 : 1;
switch (sz) {
case 3:
display.setFont(&FreeSans18pt7b);
display.setTextSize(1);
break;
case 2:
display.setFont(NULL);
display.setTextSize((width() >= height()) ? 4 : 2);
break;
default:
display.setFont(&FreeSans9pt7b);
display.setFont(_use_lemon ? &Lemon : NULL);
display.setTextSize(sc);
break;
}
}
void GxEPDDisplay::setColor(Color c) {
display_crc.update<Color> (c);
// colours need to be inverted for epaper displays
display_crc.update<Color>(c);
// e-ink: DARK background = white paper, LIGHT foreground = black ink
if (c == DARK) {
display.setTextColor(_curr_color = GxEPD_WHITE);
} else {
@@ -98,7 +114,10 @@ void GxEPDDisplay::setColor(Color c) {
void GxEPDDisplay::setCursor(int x, int y) {
display_crc.update<int>(x);
display_crc.update<int>(y);
display.setCursor((x+offset_x)*scale_x, (y+offset_y)*scale_y);
// Offset y by the font ascender: callers pass top-of-cell y, GFX fonts
// expect baseline y. Without this, text would be clipped at the top.
int sc = (width() >= height()) ? 2 : 1;
display.setCursor(x, y + fontAscender(_text_sz, _use_lemon, sc));
}
void GxEPDDisplay::print(const char* str) {
@@ -111,7 +130,7 @@ void GxEPDDisplay::fillRect(int x, int y, int w, int h) {
display_crc.update<int>(y);
display_crc.update<int>(w);
display_crc.update<int>(h);
display.fillRect(x*scale_x, y*scale_y, w*scale_x, h*scale_y, _curr_color);
display.fillRect(x, y, w, h, _curr_color);
}
void GxEPDDisplay::drawRect(int x, int y, int w, int h) {
@@ -119,7 +138,9 @@ void GxEPDDisplay::drawRect(int x, int y, int w, int h) {
display_crc.update<int>(y);
display_crc.update<int>(w);
display_crc.update<int>(h);
display.drawRect(x*scale_x, y*scale_y, w*scale_x, h*scale_y, _curr_color);
display.drawRect(x, y, w, h, _curr_color);
if (width() >= height() && w > 2 && h > 2)
display.drawRect(x + 1, y + 1, w - 2, h - 2, _curr_color);
}
void GxEPDDisplay::drawXbm(int x, int y, const uint8_t* bits, int w, int h) {
@@ -128,36 +149,13 @@ void GxEPDDisplay::drawXbm(int x, int y, const uint8_t* bits, int w, int h) {
display_crc.update<int>(w);
display_crc.update<int>(h);
display_crc.update<uint8_t>(bits, w * h / 8);
// Calculate the base position in display coordinates
uint16_t startX = x * scale_x;
uint16_t startY = y * scale_y;
// Width in bytes for bitmap processing
uint16_t widthInBytes = (w + 7) / 8;
// Process the bitmap row by row
for (uint16_t by = 0; by < h; by++) {
// Calculate the target y-coordinates for this logical row
int y1 = startY + (int)(by * scale_y);
int y2 = startY + (int)((by + 1) * scale_y);
int block_h = y2 - y1;
// Scan across the row bit by bit
for (uint16_t bx = 0; bx < w; bx++) {
// Calculate the target x-coordinates for this logical column
int x1 = startX + (int)(bx * scale_x);
int x2 = startX + (int)((bx + 1) * scale_x);
int block_w = x2 - x1;
// Get the current bit
uint16_t byteOffset = (by * widthInBytes) + (bx / 8);
uint8_t bitMask = 0x80 >> (bx & 7);
bool bitSet = pgm_read_byte(bits + byteOffset) & bitMask;
// If the bit is set, draw a block of pixels
if (bitSet) {
// Draw the block as a filled rectangle
display.fillRect(x1, y1, block_w, block_h, _curr_color);
if (pgm_read_byte(bits + byteOffset) & bitMask) {
display.drawPixel(x + bx, y + by, _curr_color);
}
}
}
@@ -167,7 +165,13 @@ uint16_t GxEPDDisplay::getTextWidth(const char* str) {
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(str, 0, 0, &x1, &y1, &w, &h);
return ceil((w + 1) / scale_x);
return w;
}
void GxEPDDisplay::setDisplayRotation(uint8_t rot) {
display.setRotation(rot & 3);
setDimensions(display.width(), display.height());
last_display_crc_value = -1; // force redraw on next endFrame
}
void GxEPDDisplay::endFrame() {

View File

@@ -15,38 +15,78 @@
#include <CRC32.h>
#include "DisplayDriver.h"
#include "LemonFont.h"
#ifndef DISPLAY_ROTATION
#define DISPLAY_ROTATION 0
#endif
// Panel native dimensions before rotation. Derived from the model class when
// EINK_DISPLAY_MODEL is set; override with EINK_PANEL_W/H for other panels.
#if defined(EINK_DISPLAY_MODEL)
#ifndef EINK_PANEL_W
#define EINK_PANEL_W EINK_DISPLAY_MODEL::WIDTH
#endif
#ifndef EINK_PANEL_H
#define EINK_PANEL_H EINK_DISPLAY_MODEL::HEIGHT
#endif
#else
#ifndef EINK_PANEL_W
#define EINK_PANEL_W 200
#define EINK_PANEL_H 200
#endif
#endif
// Odd rotations (1, 3) swap width and height.
#define EINK_DISP_W ((DISPLAY_ROTATION & 1) ? EINK_PANEL_H : EINK_PANEL_W)
#define EINK_DISP_H ((DISPLAY_ROTATION & 1) ? EINK_PANEL_W : EINK_PANEL_H)
class GxEPDDisplay : public DisplayDriver {
#if defined(EINK_DISPLAY_MODEL)
GxEPD2_BW<EINK_DISPLAY_MODEL, EINK_DISPLAY_MODEL::HEIGHT> display;
const float scale_x = EINK_SCALE_X;
const float scale_y = EINK_SCALE_Y;
const float offset_x = EINK_X_OFFSET;
const float offset_y = EINK_Y_OFFSET;
#else
GxEPD2_BW<GxEPD2_150_BN, 200> display;
const float scale_x = 1.5625f;
const float scale_y = 1.5625f;
const float offset_x = 0;
const float offset_y = 10;
#endif
bool _init = false;
bool _isOn = false;
bool _use_lemon = false;
uint16_t _curr_color;
CRC32 display_crc;
int last_display_crc_value = 0;
int _text_sz = 1;
public:
#if defined(EINK_DISPLAY_MODEL)
GxEPDDisplay() : DisplayDriver(128, 128), display(EINK_DISPLAY_MODEL(PIN_DISPLAY_CS, PIN_DISPLAY_DC, PIN_DISPLAY_RST, PIN_DISPLAY_BUSY)) {}
GxEPDDisplay() : DisplayDriver(EINK_DISP_W, EINK_DISP_H),
display(EINK_DISPLAY_MODEL(PIN_DISPLAY_CS, PIN_DISPLAY_DC, PIN_DISPLAY_RST, PIN_DISPLAY_BUSY)) {}
#else
GxEPDDisplay() : DisplayDriver(128, 128), display(GxEPD2_150_BN(DISP_CS, DISP_DC, DISP_RST, DISP_BUSY)) {}
GxEPDDisplay() : DisplayDriver(EINK_DISP_W, EINK_DISP_H),
display(GxEPD2_150_BN(DISP_CS, DISP_DC, DISP_RST, DISP_BUSY)) {}
#endif
// Line height and approx. char width for each font size:
// 1 = FreeSans9pt (lineH=16, charW≈9)
// 2 = FreeSansBold12pt (lineH=20, charW≈12)
// 3 = FreeSans18pt (lineH=28, charW≈17)
// Size 1 scales with orientation (portrait 1×, landscape 2×); size 2 is always 12×16;
// size 3 is FreeSans18pt (~17×28). Landscape = width >= height.
int getCharWidth() const override {
int sc = (width() >= height()) ? 2 : 1;
if (_text_sz == 3) return 17;
if (_text_sz == 2) return 12 * sc;
return (_use_lemon ? 5 : 6) * sc;
}
int getLineHeight() const override {
int sc = (width() >= height()) ? 2 : 1;
if (_text_sz == 3) return 28;
if (_text_sz == 2) return 16 * sc;
return (_use_lemon ? 10 : 8) * sc;
}
void setLemonFont(bool enabled) override { _use_lemon = enabled; }
bool begin();
bool isOn() override {return _isOn;};
bool isOn() override { return _isOn; }
void turnOn() override;
void turnOff() override;
void clear() override;
@@ -59,5 +99,6 @@ public:
void drawRect(int x, int y, int w, int h) override;
void drawXbm(int x, int y, const uint8_t* bits, int w, int h) override;
uint16_t getTextWidth(const char* str) override;
void setDisplayRotation(uint8_t rot) override;
void endFrame() override;
};

1523
src/helpers/ui/LemonFont.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
// Lemon font icon glyphs (Private Use Area), converted manually from lemon.bdf
// Add new icons by appending to the bitmap array, lemonIconCPs, and lemonIconGlyphs.
#pragma once
#include <Adafruit_GFX.h>
static const uint8_t lemonIconBitmaps[] PROGMEM = {
0xEE, 0xBA, 0x2B, 0xA3, 0xB0, // U+E03B mute: 6×6, yoff=0
};
static const uint32_t lemonIconCPs[] PROGMEM = {
0xE03B, // mute
};
static const GFXglyph lemonIconGlyphs[] PROGMEM = {
// off w h adv xo yo
{ 0, 6, 6, 5, 0, -6 }, // U+E03B mute
};
static const uint8_t lemonIconCount = sizeof(lemonIconCPs) / sizeof(lemonIconCPs[0]);

View File

@@ -1,6 +1,8 @@
#include "SH1106Display.h"
#include <Adafruit_GrayOLED.h>
#include "Adafruit_SH110X.h"
#include "LemonFont.h"
#include "LemonIcons.h"
bool SH1106Display::i2c_probe(TwoWire &wire, uint8_t addr)
{
@@ -17,6 +19,9 @@ bool SH1106Display::begin()
void SH1106Display::turnOn()
{
display.oled_command(SH110X_DISPLAYON);
uint8_t pre[] = { 0xD9, _precharge };
display.oled_commandList(pre, 2);
display.setContrast(_contrast);
_isOn = true;
}
@@ -38,11 +43,13 @@ void SH1106Display::startFrame(Color bkg)
_color = SH110X_WHITE;
display.setTextColor(_color);
display.setTextSize(1);
_text_sz = 1;
display.cp437(true); // Use full 256 char 'Code Page 437' font
}
void SH1106Display::setTextSize(int sz)
{
_text_sz = sz;
display.setTextSize(sz);
}
@@ -57,9 +64,107 @@ void SH1106Display::setCursor(int x, int y)
display.setCursor(x, y);
}
uint32_t SH1106Display::decodeUtf8(const uint8_t*& p) {
uint8_t c = *p++;
if (c < 0x80) return c;
if ((c & 0xE0) == 0xC0) {
uint32_t cp = c & 0x1F;
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
return cp;
}
if ((c & 0xF0) == 0xE0) {
uint32_t cp = c & 0x0F;
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
return cp;
}
if ((c & 0xF8) == 0xF0) {
uint32_t cp = c & 0x07;
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
if (*p) cp = (cp << 6) | (*p++ & 0x3F);
return cp;
}
while (*p && (*p & 0xC0) == 0x80) p++;
return 0xFFFD;
}
int16_t SH1106Display::drawLemonChar(int16_t x, int16_t y, uint32_t cp) {
int sz = _text_sz;
for (uint8_t i = 0; i < lemonIconCount; i++) {
if (pgm_read_dword(&lemonIconCPs[i]) == cp) {
const GFXglyph* g = &lemonIconGlyphs[i];
uint8_t w = pgm_read_byte(&g->width), h = pgm_read_byte(&g->height);
int8_t xo = (int8_t)pgm_read_byte(&g->xOffset), yo = (int8_t)pgm_read_byte(&g->yOffset);
uint8_t xa = pgm_read_byte(&g->xAdvance);
uint16_t bo = pgm_read_word(&g->bitmapOffset);
uint8_t bits = 0, bit = 0;
for (uint8_t row = 0; row < h; row++)
for (uint8_t col = 0; col < w; col++) {
if (!bit) { bits = pgm_read_byte(&lemonIconBitmaps[bo++]); bit = 0x80; }
if (bits & bit) {
if (sz == 1) display.drawPixel(x + xo + col, y + 6 + yo + row, _color);
else display.fillRect(x + xo*sz + col*sz, y + 6*sz + yo*sz + row*sz, sz, sz, _color);
}
bit >>= 1;
}
return x + xa * sz;
}
}
if (cp < Lemon.first || cp > Lemon.last) {
if (cp >= 0x20) display.fillRect(x + sz, y - sz, 4*sz, 6*sz, _color);
return x + 6 * sz;
}
const GFXglyph* g = &lemonGlyphs[cp - Lemon.first];
uint8_t w = pgm_read_byte(&g->width), h = pgm_read_byte(&g->height);
int8_t xo = (int8_t)pgm_read_byte(&g->xOffset), yo = (int8_t)pgm_read_byte(&g->yOffset);
uint8_t xa = pgm_read_byte(&g->xAdvance);
uint16_t bo = pgm_read_word(&g->bitmapOffset);
uint8_t bits = 0, bit = 0;
for (uint8_t row = 0; row < h; row++)
for (uint8_t col = 0; col < w; col++) {
if (!bit) { bits = pgm_read_byte(&lemonBitmaps[bo++]); bit = 0x80; }
if (bits & bit) {
if (sz == 1) display.drawPixel(x + xo + col, y + 6 + yo + row, _color);
else display.fillRect(x + xo*sz + col*sz, y + 6*sz + yo*sz + row*sz, sz, sz, _color);
}
bit >>= 1;
}
return x + xa * sz;
}
uint8_t SH1106Display::lemonXAdvance(uint32_t cp) {
uint8_t xa;
if (cp < Lemon.first || cp > Lemon.last) xa = 6;
else xa = pgm_read_byte(&lemonGlyphs[cp - Lemon.first].xAdvance);
return xa * _text_sz;
}
void SH1106Display::translateUTF8ToBlocks(char* dest, const char* src, size_t dest_size) {
if (_use_lemon) {
size_t n = strlen(src);
if (n >= dest_size) n = dest_size - 1;
memcpy(dest, src, n);
dest[n] = '\0';
} else {
DisplayDriver::translateUTF8ToBlocks(dest, src, dest_size);
}
}
void SH1106Display::print(const char *str)
{
display.print(str);
if (!_use_lemon) { display.print(str); return; }
int16_t cx = display.getCursorX();
int16_t cy = display.getCursorY();
const uint8_t* p = (const uint8_t*)str;
while (*p) {
uint32_t cp = decodeUtf8(p);
if (cp == '\n') { cy += Lemon.yAdvance; cx = 0; }
else { cx = drawLemonChar(cx, cy, cp); }
}
display.setCursor(cx, cy);
}
void SH1106Display::fillRect(int x, int y, int w, int h)
@@ -79,12 +184,33 @@ void SH1106Display::drawXbm(int x, int y, const uint8_t *bits, int w, int h)
uint16_t SH1106Display::getTextWidth(const char *str)
{
if (_use_lemon) {
uint16_t width = 0;
const uint8_t* p = (const uint8_t*)str;
while (*p) width += lemonXAdvance(decodeUtf8(p));
return width;
}
int16_t x1, y1;
uint16_t w, h;
display.getTextBounds(str, 0, 0, &x1, &y1, &w, &h);
return w;
}
void SH1106Display::setBrightness(uint8_t level)
{
// Contrast alone has limited effect on some OLED panels; combining with
// pre-charge period (0xD9) gives a wider perceptible dimming range.
// Pre-charge 0x11 = phase1=1,phase2=1 (minimum drive); 0x1F = default.
static const uint8_t contrast_values[] = { 0, 25, 60, 150, 255 };
static const uint8_t precharge_values[] = { 0x11, 0x15, 0x1F, 0x1F, 0x1F };
uint8_t idx = level < 5 ? level : 4;
_contrast = contrast_values[idx];
_precharge = precharge_values[idx];
uint8_t pre[] = { 0xD9, _precharge };
display.oled_commandList(pre, 2);
display.setContrast(_contrast);
}
void SH1106Display::endFrame()
{
display.display();

View File

@@ -19,11 +19,20 @@ class SH1106Display : public DisplayDriver
Adafruit_SH1106G display;
bool _isOn;
uint8_t _color;
uint8_t _contrast;
uint8_t _precharge;
bool _use_lemon;
int _text_sz;
bool i2c_probe(TwoWire &wire, uint8_t addr);
static uint32_t decodeUtf8(const uint8_t*& p);
int16_t drawLemonChar(int16_t x, int16_t y, uint32_t cp);
uint8_t lemonXAdvance(uint32_t cp);
public:
SH1106Display() : DisplayDriver(128, 64), display(128, 64, &Wire, PIN_OLED_RESET) { _isOn = false; }
SH1106Display() : DisplayDriver(128, 64), display(128, 64, &Wire, PIN_OLED_RESET) {
_isOn = false; _contrast = 255; _precharge = 0x1F; _use_lemon = false; _text_sz = 1;
}
bool begin();
bool isOn() override { return _isOn; }
@@ -39,5 +48,10 @@ public:
void drawRect(int x, int y, int w, int h) override;
void drawXbm(int x, int y, const uint8_t *bits, int w, int h) override;
uint16_t getTextWidth(const char *str) override;
int getCharWidth() const override { return (_use_lemon ? 5 : 6) * _text_sz; }
int getLineHeight() const override { return (_use_lemon ? 9 : 8) * _text_sz; }
void setLemonFont(bool enabled) override { _use_lemon = enabled; }
void translateUTF8ToBlocks(char* dest, const char* src, size_t dest_size) override;
void setBrightness(uint8_t level) override;
void endFrame() override;
};

View File

@@ -2,61 +2,243 @@
#include "buzzer.h"
void genericBuzzer::begin() {
// Serial.print("DBG: Setting up buzzer on pin ");
// Serial.println(PIN_BUZZER);
#ifdef PIN_BUZZER_EN
pinMode(PIN_BUZZER_EN, OUTPUT);
digitalWrite(PIN_BUZZER_EN, HIGH);
#endif
quiet(false);
pinMode(PIN_BUZZER, OUTPUT);
digitalWrite(PIN_BUZZER, LOW); // need to pull low by default to avoid extreme power draw
digitalWrite(PIN_BUZZER, LOW);
startup();
}
void genericBuzzer::play(const char *melody) {
if (isPlaying()) // interrupt existing
{
rtttl::stop();
}
if (_is_quiet) return;
rtttl::begin(PIN_BUZZER,melody);
// Serial.print("DBG: Playing melody - isQuiet: ");
// Serial.println(isQuiet());
}
bool genericBuzzer::isPlaying() {
return rtttl::isPlaying();
}
void genericBuzzer::loop() {
if (!rtttl::done()) rtttl::play();
}
void genericBuzzer::startup() {
play(startup_song);
}
void genericBuzzer::shutdown() {
play(shutdown_song);
}
void genericBuzzer::quiet(bool buzzer_state) {
_is_quiet = buzzer_state;
#ifdef PIN_BUZZER_EN
if (_is_quiet) {
digitalWrite(PIN_BUZZER_EN, LOW);
} else {
digitalWrite(PIN_BUZZER_EN, HIGH);
}
digitalWrite(PIN_BUZZER_EN, _is_quiet ? LOW : HIGH);
#endif
}
bool genericBuzzer::isQuiet() {
return _is_quiet;
bool genericBuzzer::isQuiet() { return _is_quiet; }
void genericBuzzer::startup() { play(startup_song); }
void genericBuzzer::shutdown() { play(shutdown_song); }
// ---------------------------------------------------------------------------
// nRF52 path — direct NRF_PWM2 control, bypasses tone()
// ---------------------------------------------------------------------------
#if defined(NRF52_PLATFORM)
// Chromatic frequencies for octave 4 (Hz): C C# D D# E F F# G G# A A# B
static const uint16_t CHROM4[12] = { 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494 };
// Map 'a'-'g' → chromatic index within octave
static const uint8_t NOTE_IDX[7] = { 9, 11, 0, 2, 4, 5, 7 }; // a b c d e f g
uint16_t genericBuzzer::_noteFreq(char letter, bool sharp, uint8_t octave) {
if (letter == 'p') return 0;
if (letter < 'a' || letter > 'g') return 0;
uint8_t idx = NOTE_IDX[letter - 'a'];
if (sharp) { if (++idx >= 12) { idx = 0; octave++; } }
if (octave < 4) octave = 4;
if (octave > 7) octave = 7;
uint32_t f = (uint32_t)CHROM4[idx] << (octave - 4);
return (uint16_t)(f > 25000 ? 25000 : f);
}
#endif // ifdef PIN_BUZZER
void genericBuzzer::_parseHeader(const char* melody, uint8_t& def_dur, uint8_t& def_oct,
uint16_t& bpm, const char*& notes) {
def_dur = 4; def_oct = 5; bpm = 120;
const char* p = melody;
while (*p && *p != ':') p++;
if (*p == ':') p++;
while (*p && *p != ':') {
while (*p == ' ' || *p == ',') p++;
if (p[0]=='d' && p[1]=='=') { p+=2; def_dur=(uint8_t)atoi(p); while(*p&&*p!=','&&*p!=':')p++; }
else if (p[0]=='o' && p[1]=='=') { p+=2; def_oct=(uint8_t)atoi(p); while(*p&&*p!=','&&*p!=':')p++; }
else if (p[0]=='b' && p[1]=='=') { p+=2; bpm=(uint16_t)atoi(p); while(*p&&*p!=','&&*p!=':')p++; }
else { while(*p&&*p!=','&&*p!=':')p++; }
}
if (*p == ':') p++;
notes = p;
}
bool genericBuzzer::_parseNext(const char*& p, uint8_t def_dur, uint8_t def_oct, uint16_t bpm,
uint16_t& freq, uint32_t& dur_ms) {
while (*p == ' ' || *p == ',') p++;
if (*p == '\0') return false;
uint8_t dur = def_dur;
if (*p >= '0' && *p <= '9') { dur=(uint8_t)atoi(p); while(*p>='0'&&*p<='9')p++; }
if (dur == 0) dur = 4;
if (*p == '\0') return false;
char note = *p++;
bool sharp = (*p == '#') ? (p++, true) : false;
uint8_t oct = def_oct;
if (*p >= '4' && *p <= '8') oct = (uint8_t)(*p++ - '0');
bool dot = (*p == '.') ? (p++, true) : false;
dur_ms = (60000UL * 4UL) / ((uint32_t)bpm * dur);
if (dot) dur_ms = dur_ms * 3 / 2;
freq = _noteFreq(note, sharp, oct);
return true;
}
uint8_t genericBuzzer::_dutyPct() const {
// Inverted polarity (0x8000 bit): duty_HIGH = 100% - PCT.
// Values chosen for ~6-8 dB perceptual steps: -24/-16/-9/-3/0 dB.
static const uint8_t PCT[5] = { 2, 5, 12, 25, 50 };
return PCT[_volume_level < 5 ? _volume_level : 4];
}
void genericBuzzer::_nrfStartPwm(uint16_t freq) {
if (freq < 20 || freq > 25000) { _nrfStopPwm(); return; }
uint32_t nrf_pin = g_ADigitalPinMap[PIN_BUZZER];
uint16_t top = 125000 / freq;
uint16_t cmp = (uint16_t)(((uint32_t)top * _dutyPct()) / 100);
if (cmp == 0) cmp = 1; // inverted polarity: cmp=0 → 100% HIGH → no AC → silence
// Write duty BEFORE SEQSTART so DMA reads our value on the very first period
_duty_buf = 0x8000U | cmp;
__DMB();
NRF_PWM2->TASKS_STOP = 1;
// Wait for STOPPED (short busy-wait, typically < 1 PWM period)
uint32_t t = millis();
while (!(NRF_PWM2->EVENTS_STOPPED) && (millis() - t) < 2) {}
NRF_PWM2->EVENTS_STOPPED = 0;
NRF_PWM2->PSEL.OUT[0] = nrf_pin;
NRF_PWM2->PSEL.OUT[1] = 0xFFFFFFFFUL;
NRF_PWM2->PSEL.OUT[2] = 0xFFFFFFFFUL;
NRF_PWM2->PSEL.OUT[3] = 0xFFFFFFFFUL;
NRF_PWM2->ENABLE = PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos;
NRF_PWM2->MODE = PWM_MODE_UPDOWN_Up << PWM_MODE_UPDOWN_Pos;
// DIV_128 on 16 MHz = 125 kHz — same clock as tone(), so same frequency math
NRF_PWM2->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_128 << PWM_PRESCALER_PRESCALER_Pos;
NRF_PWM2->COUNTERTOP = top;
NRF_PWM2->DECODER = (PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) |
(PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos);
NRF_PWM2->SHORTS = PWM_SHORTS_LOOPSDONE_SEQSTART0_Msk;
NRF_PWM2->LOOP = 0xFFFFUL << PWM_LOOP_CNT_Pos;
// Both SEQ0 and SEQ1 point to the same buffer; REFRESH=0 means DMA re-reads every period
NRF_PWM2->SEQ[0].PTR = (uint32_t)&_duty_buf;
NRF_PWM2->SEQ[0].CNT = 1;
NRF_PWM2->SEQ[0].REFRESH = 0;
NRF_PWM2->SEQ[0].ENDDELAY = 0;
NRF_PWM2->SEQ[1].PTR = (uint32_t)&_duty_buf;
NRF_PWM2->SEQ[1].CNT = 1;
NRF_PWM2->SEQ[1].REFRESH = 0;
NRF_PWM2->SEQ[1].ENDDELAY = 0;
NRF_PWM2->TASKS_SEQSTART[0] = 1;
_pwm_on = true;
}
void genericBuzzer::_nrfStopPwm() {
NRF_PWM2->TASKS_STOP = 1;
NRF_PWM2->PSEL.OUT[0] = 0xFFFFFFFFUL;
NRF_PWM2->ENABLE = 0;
digitalWrite(PIN_BUZZER, LOW);
_pwm_on = false;
}
void genericBuzzer::_nrfBegin(const char* melody) {
_nrfStopPwm();
if (!melody || !*melody) { _rtttl_done = true; return; }
const char* notes;
_parseHeader(melody, _def_dur, _def_oct, _def_bpm, notes);
_rtttl_pos = notes;
_rtttl_done = false;
_nrfAdvance();
}
void genericBuzzer::_nrfAdvance() {
uint16_t freq; uint32_t dur_ms;
if (_parseNext(_rtttl_pos, _def_dur, _def_oct, _def_bpm, freq, dur_ms)) {
_note_end_ms = millis() + dur_ms;
if (freq > 0) _nrfStartPwm(freq); else _nrfStopPwm();
} else {
_nrfStopPwm();
_rtttl_done = true;
}
}
void genericBuzzer::applyVolume() {
if (!_pwm_on) return;
uint16_t top = (uint16_t)NRF_PWM2->COUNTERTOP;
uint16_t cmp = (uint16_t)(((uint32_t)top * _dutyPct()) / 100);
if (cmp == 0) cmp = 1;
_duty_buf = 0x8000U | cmp; // DMA picks this up within one period (< 2.3 ms at A4)
}
void genericBuzzer::play(const char* melody) {
if (_is_quiet) return;
_nrfBegin(melody);
}
void genericBuzzer::playForced(const char* melody) {
_nrfBegin(melody);
}
bool genericBuzzer::isPlaying() { return !_rtttl_done; }
void genericBuzzer::stop() {
_nrfStopPwm();
_rtttl_done = true;
}
void genericBuzzer::loop() {
if (!_rtttl_done && (millis() >= _note_end_ms)) _nrfAdvance();
}
void genericBuzzer::setVolume(uint8_t level) {
_volume_level = level < 5 ? level : 4;
applyVolume();
}
// ---------------------------------------------------------------------------
// Non-nRF52 path — NonBlockingRtttl + analogWrite for volume
// ---------------------------------------------------------------------------
#else
void genericBuzzer::applyVolume() {
// After tone() sets 50% duty, analogWrite overrides duty on the same PWM channel.
static const uint8_t duty[5] = { 6, 20, 50, 90, 128 };
uint8_t d = duty[_volume_level < 5 ? _volume_level : 4];
if (d < 128) analogWrite(PIN_BUZZER, d);
}
void genericBuzzer::play(const char* melody) {
if (isPlaying()) rtttl::stop();
if (_is_quiet) return;
rtttl::begin(PIN_BUZZER, melody);
}
void genericBuzzer::playForced(const char* melody) {
if (isPlaying()) rtttl::stop();
rtttl::begin(PIN_BUZZER, melody);
}
bool genericBuzzer::isPlaying() { return rtttl::isPlaying(); }
void genericBuzzer::stop() { rtttl::stop(); }
void genericBuzzer::loop() {
if (!rtttl::done()) {
rtttl::play();
if (_volume_level < 4) applyVolume();
}
}
void genericBuzzer::setVolume(uint8_t level) {
_volume_level = level < 5 ? level : 4;
if (isPlaying()) applyVolume();
}
#endif // NRF52_PLATFORM
#endif // PIN_BUZZER

View File

@@ -1,37 +1,58 @@
#pragma once
#include <Arduino.h>
#include <NonBlockingRtttl.h>
/* class abstracts underlying RTTTL library
Just a simple imlementation to start. At the moment use same
melody for message and discovery
Suggest enum type for different sounds
- on message
- on discovery
TODO
- make message ring tone configurable
*/
#if !defined(NRF52_PLATFORM)
#include <NonBlockingRtttl.h>
#endif
class genericBuzzer
{
public:
void begin(); // set up buzzer port
void play(const char *melody); // Generic play function
void loop(); // loop driven-nonblocking
void startup(); // play startup sound
void shutdown(); // play shutdown sound
bool isPlaying(); // returns true if a sound is still playing else false
void quiet(bool buzzer_state); // enables or disables the buzzer
bool isQuiet(); // get buzzer state on/off
void begin();
void play(const char *melody);
void playForced(const char *melody);
void loop();
void startup();
void shutdown();
bool isPlaying();
void quiet(bool buzzer_state);
bool isQuiet();
void setVolume(uint8_t level);
uint8_t getVolume() const { return _volume_level; }
void stop();
private:
// gemini's picks:
const char *startup_song = "Startup:d=4,o=5,b=160:16c6,16e6,8g6";
uint8_t _volume_level = 4;
void applyVolume();
const char *startup_song = "Startup:d=4,o=5,b=160:16c6,16e6,8g6";
const char *shutdown_song = "Shutdown:d=4,o=5,b=100:8g5,16e5,16c5";
bool _is_quiet = true;
#if defined(NRF52_PLATFORM)
// Own RTTTL player — bypasses tone() to allow volume control from note start.
// tone() pre-computes seq_refresh so the DMA repeats 50% duty for ~30ms before
// re-reading its buffer; we cannot beat that timing. By owning NRF_PWM2 directly
// and setting REFRESH=0, DMA re-reads _duty_buf every period so duty takes effect
// immediately at SEQSTART.
volatile uint16_t _duty_buf = 0; // DMA source — must stay in RAM
const char* _rtttl_pos = nullptr;
bool _rtttl_done = true;
bool _pwm_on = false;
unsigned long _note_end_ms = 0;
uint8_t _def_dur = 4;
uint8_t _def_oct = 5;
uint16_t _def_bpm = 120;
void _nrfBegin(const char* melody);
void _nrfAdvance();
void _nrfStartPwm(uint16_t freq);
void _nrfStopPwm();
uint8_t _dutyPct() const;
static uint16_t _noteFreq(char letter, bool sharp, uint8_t octave);
static bool _parseNext(const char*& pos, uint8_t def_dur, uint8_t def_oct,
uint16_t bpm, uint16_t& freq_hz, uint32_t& dur_ms);
static void _parseHeader(const char* melody, uint8_t& def_dur, uint8_t& def_oct,
uint16_t& bpm, const char*& notes_start);
#endif
};

View File

@@ -1,12 +1,14 @@
[WioTrackerL1Eink]
extends = nrf52_base
board = seeed-wio-tracker-l1
board_build.ldscript = boards/nrf52840_s140_v7.ld
board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld
board_upload.maximum_size = 708608
build_flags = ${nrf52_base.build_flags}
${sensor_base.build_flags}
-I lib/nrf52/s140_nrf52_7.3.0_API/include
-I lib/nrf52/s140_nrf52_7.3.0_API/include/nrf52
-I variants/wio-tracker-l1
-I examples/companion_radio/ui-new
-D WIO_TRACKER_L1
-D WIO_TRACKER_L1_EINK
-D USE_SX1262
@@ -15,56 +17,51 @@ build_flags = ${nrf52_base.build_flags}
-D LORA_TX_POWER=22
-D SX126X_CURRENT_LIMIT=140
-D SX126X_RX_BOOSTED_GAIN=1
-D PIN_OLED_RESET=-1
-D EINK_DISPLAY_MODEL=GxEPD2_213_B74
-D EINK_SCALE_X=1.953125f
-D EINK_SCALE_Y=1.28f
-D EINK_X_OFFSET=0
-D EINK_Y_OFFSET=10
-D DISPLAY_ROTATION=1
-D DISABLE_DIAGNOSTIC_OUTPUT
-D AUTO_OFF_MILLIS=0
-D GPS_BAUD_RATE=9600
-D ENV_PIN_SDA=PIN_WIRE1_SDA
-D ENV_PIN_SCL=PIN_WIRE1_SCL
-D DISABLE_DIAGNOSTIC_OUTPUT
-D AUTO_OFF_MILLIS=0
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D OFFLINE_QUEUE_SIZE=256
-D DISPLAY_CLASS=GxEPDDisplay
-D UI_HAS_JOYSTICK=1
-D UI_HAS_JOYSTICK_UPDOWN=1
-D PIN_BUZZER=12
-D QSPIFLASH=1
-D FIRMWARE_PLUS_BUILD=1
-D UI_SENSORS_PAGE=1
-D BLE_PIN_CODE=123456
build_src_filter = ${nrf52_base.build_src_filter}
+<WioTrackerL1Board.cpp>
+<../variants/wio-tracker-l1>
+<helpers/ui/GxEPDDisplay.cpp>
+<helpers/sensors>
lib_deps= ${nrf52_base.lib_deps}
${sensor_base.lib_deps}
adafruit/Adafruit GFX Library @ ^1.12.1
zinggjm/GxEPD2 @ 1.6.2
bakercp/CRC32 @ ^2.0.0
[env:WioTrackerL1Eink_companion_radio_ble]
extends = WioTrackerL1Eink
board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld
board_upload.maximum_size = 708608
build_flags = ${WioTrackerL1Eink.build_flags}
-I examples/companion_radio/ui-new
-D MAX_CONTACTS=350
-D MAX_GROUP_CHANNELS=40
-D BLE_PIN_CODE=123456
-D BLE_DEBUG_LOGGING=1
-D OFFLINE_QUEUE_SIZE=256
-D DISPLAY_CLASS=GxEPDDisplay
-D UI_HAS_JOYSTICK=1
-D PIN_BUZZER=12
-D QSPIFLASH=1
; -D MESH_PACKET_LOGGING=1
; -D MESH_DEBUG=1
-D UI_RECENT_LIST_SIZE=6
-D UI_SENSORS_PAGE=1
build_src_filter = ${WioTrackerL1Eink.build_src_filter}
+<helpers/nrf52/SerialBLEInterface.cpp>
+<helpers/ui/MomentaryButton.cpp>
+<helpers/ui/buzzer.cpp>
+<helpers/nrf52/SerialBLEInterface.cpp>
+<helpers/sensors>
+<../examples/companion_radio/*.cpp>
+<../examples/companion_radio/ui-new/*.cpp>
lib_deps = ${WioTrackerL1Eink.lib_deps}
lib_deps = ${nrf52_base.lib_deps}
${sensor_base.lib_deps}
adafruit/Adafruit GFX Library @ ^1.12.1
adafruit/RTClib @ ^2.1.3
zinggjm/GxEPD2 @ 1.6.2
bakercp/CRC32 @ ^2.0.0
densaugeo/base64 @ ~1.4.0
end2endzone/NonBlockingRTTTL@^1.3.0
debug_tool=stlink
; BLE only
[env:WioTrackerL1Eink_companion_radio_ble]
extends = WioTrackerL1Eink
extra_scripts = post:create-uf2.py
; Dual BLE+USB
[env:WioTrackerL1Eink_companion_radio_dual]
extends = WioTrackerL1Eink
build_flags = ${WioTrackerL1Eink.build_flags}
-D DUAL_SERIAL=1
extra_scripts = post:create-uf2.py

View File

@@ -8,6 +8,8 @@ void WioTrackerL1Board::begin() {
btn_prev_state = HIGH;
pinMode(PIN_VBAT_READ, INPUT); // VBAT ADC input
pinMode(VBAT_ENABLE, OUTPUT);
digitalWrite(VBAT_ENABLE, LOW); // keep voltage divider off; enabled only during ADC read
// Set all button pins to INPUT_PULLUP
pinMode(PIN_BUTTON1, INPUT_PULLUP);
pinMode(PIN_BUTTON2, INPUT_PULLUP);

View File

@@ -22,11 +22,12 @@ public:
#endif
uint16_t getBattMilliVolts() override {
int adcvalue = 0;
digitalWrite(VBAT_ENABLE, HIGH);
analogReadResolution(12);
analogReference(AR_INTERNAL);
delay(10);
adcvalue = analogRead(PIN_VBAT_READ);
delay(10); // allow voltage divider to stabilize
int adcvalue = analogRead(PIN_VBAT_READ);
digitalWrite(VBAT_ENABLE, LOW);
return (adcvalue * ADC_MULTIPLIER * AREF_VOLTAGE) / 4.096;
}

View File

@@ -55,7 +55,7 @@ build_flags = ${WioTrackerL1.build_flags}
lib_deps = ${WioTrackerL1.lib_deps}
adafruit/RTClib @ ^2.1.3
[env:WioTrackerL1_companion_radio_usb]
[WioTrackerL1CompanionUSB]
extends = WioTrackerL1
board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld
board_upload.maximum_size = 708608
@@ -65,9 +65,12 @@ build_flags = ${WioTrackerL1.build_flags}
-D MAX_GROUP_CHANNELS=40
-D DISPLAY_CLASS=SH1106Display
-D UI_HAS_JOYSTICK=1
-D UI_HAS_JOYSTICK_UPDOWN=1
-D OFFLINE_QUEUE_SIZE=256
-D PIN_BUZZER=12
-D QSPIFLASH=1
-D FIRMWARE_PLUS_BUILD=1
-D UI_SENSORS_PAGE=1
; NOTE: DO NOT ENABLE --> -D MESH_PACKET_LOGGING=1
; NOTE: DO NOT ENABLE --> -D MESH_DEBUG=1
build_src_filter = ${WioTrackerL1.build_src_filter}
@@ -81,7 +84,16 @@ lib_deps = ${WioTrackerL1.lib_deps}
densaugeo/base64 @ ~1.4.0
end2endzone/NonBlockingRTTTL@^1.3.0
[env:WioTrackerL1_companion_radio_ble]
[env:WioTrackerL1_companion_radio_usb]
extends = WioTrackerL1CompanionUSB
[env:WioTrackerL1_companion_radio_usb_settings]
extends = WioTrackerL1CompanionUSB
build_flags = ${WioTrackerL1CompanionUSB.build_flags}
-D UI_HAS_JOYSTICK_UPDOWN=1
extra_scripts = post:create-uf2.py
[WioTrackerL1CompanionBLE]
extends = WioTrackerL1
board_build.ldscript = boards/nrf52840_s140_v7_extrafs.ld
board_upload.maximum_size = 708608
@@ -94,9 +106,12 @@ build_flags = ${WioTrackerL1.build_flags}
-D OFFLINE_QUEUE_SIZE=256
-D DISPLAY_CLASS=SH1106Display
-D UI_HAS_JOYSTICK=1
-D UI_HAS_JOYSTICK_UPDOWN=1
-D PIN_BUZZER=12
-D QSPIFLASH=1
-D ADVERT_NAME='"@@MAC"'
-D FIRMWARE_PLUS_BUILD=1
-D UI_SENSORS_PAGE=1
-D ENV_PIN_SDA=PIN_WIRE1_SDA
-D ENV_PIN_SCL=PIN_WIRE1_SCL
; -D MESH_PACKET_LOGGING=1
@@ -111,3 +126,27 @@ lib_deps = ${WioTrackerL1.lib_deps}
adafruit/RTClib @ ^2.1.3
densaugeo/base64 @ ~1.4.0
end2endzone/NonBlockingRTTTL@^1.3.0
[env:WioTrackerL1_companion_radio_ble]
extends = WioTrackerL1CompanionBLE
[env:WioTrackerL1_companion_radio_ble_settings]
extends = WioTrackerL1CompanionBLE
build_flags = ${WioTrackerL1CompanionBLE.build_flags}
-D UI_HAS_JOYSTICK_UPDOWN=1
extra_scripts = post:create-uf2.py
[WioTrackerL1CompanionDual]
extends = WioTrackerL1CompanionBLE
build_flags = ${WioTrackerL1CompanionBLE.build_flags}
-D DUAL_SERIAL=1
-UBLE_DEBUG_LOGGING
[env:WioTrackerL1_companion_radio_dual]
extends = WioTrackerL1CompanionDual
[env:WioTrackerL1_companion_radio_dual_settings]
extends = WioTrackerL1CompanionDual
build_flags = ${WioTrackerL1CompanionDual.build_flags}
-D UI_HAS_JOYSTICK_UPDOWN=1
extra_scripts = post:create-uf2.py

View File

@@ -25,6 +25,10 @@ EnvironmentSensorManager sensors = EnvironmentSensorManager();
MomentaryButton joystick_left(JOYSTICK_LEFT, 1000, true, false, false);
MomentaryButton joystick_right(JOYSTICK_RIGHT, 1000, true, false, false);
MomentaryButton back_btn(PIN_BACK_BTN, 1000, true, false, true);
#ifdef UI_HAS_JOYSTICK_UPDOWN
MomentaryButton joystick_up(JOYSTICK_UP, 1000, true, false, false);
MomentaryButton joystick_down(JOYSTICK_DOWN, 1000, true, false, false);
#endif
#endif
bool radio_init() {

View File

@@ -28,6 +28,10 @@ extern EnvironmentSensorManager sensors;
extern MomentaryButton joystick_left;
extern MomentaryButton joystick_right;
extern MomentaryButton back_btn;
#ifdef UI_HAS_JOYSTICK_UPDOWN
extern MomentaryButton joystick_up;
extern MomentaryButton joystick_down;
#endif
#endif
bool radio_init();

View File

@@ -67,9 +67,9 @@ void initVariant() {
pinMode(PIN_QSPI_CS, OUTPUT);
digitalWrite(PIN_QSPI_CS, HIGH);
// VBAT_ENABLE
// VBAT_ENABLE: keep LOW by default, WioTrackerL1Board::getBattMilliVolts() toggles it
pinMode(VBAT_ENABLE, OUTPUT);
digitalWrite(VBAT_ENABLE, HIGH);
digitalWrite(VBAT_ENABLE, LOW);
// set LED pin as output and set it low
pinMode(PIN_LED, OUTPUT);
@@ -78,5 +78,4 @@ void initVariant() {
// set buzzer pin as output and set it low
pinMode(12, OUTPUT);
digitalWrite(12, LOW);
pinMode(12, OUTPUT);
}