Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5002c7b0f9 | ||
| 2e157adbe7 | |||
| f7f821a475 | |||
| f48ef775c4 |
125
AGENTS.md
Normal file
125
AGENTS.md
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
# Project: MeshCore Relay Radio (for opencode)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Modify MeshCore `companion_radio` firmware for Heltec T114 to control a relay and read DS18B20 temperature sensor via LoRa mesh private messages.
|
||||||
|
|
||||||
|
## Hardware
|
||||||
|
|
||||||
|
- **Board:** Heltec T114 (nRF52840 + SX1262)
|
||||||
|
- **Relay:** GPIO 4 (RELAY_PIN)
|
||||||
|
- **DS18B20:** GPIO 5 (ONE_WIRE_BUS) with 4.7k pull-up
|
||||||
|
- **BLE PIN (for BLE variant):** 123456
|
||||||
|
|
||||||
|
## Radio Parameters
|
||||||
|
|
||||||
|
- Frequency: 868.731018 MHz
|
||||||
|
- Bandwidth: 62.5 kHz
|
||||||
|
- Spreading Factor: 7
|
||||||
|
- Coding Rate: 7
|
||||||
|
- Path Hash: 1 byte (mode 0)
|
||||||
|
|
||||||
|
## Commands (via private mesh messages)
|
||||||
|
|
||||||
|
| Command | Response | Action |
|
||||||
|
|----------|---------------------------------|-----------------------|
|
||||||
|
| `on1234` | `relay on` | Relay ON |
|
||||||
|
| `off1234`| `relay off` | Relay OFF |
|
||||||
|
| `temp` | `temp: 23.5 C` | Read DS18B20 temp |
|
||||||
|
| `state` | `temp: 23.5 C, relay: ON` | Temp + relay state |
|
||||||
|
|
||||||
|
Numbers in commands (e.g. `1234`) are a PIN code, not validated by firmware.
|
||||||
|
|
||||||
|
## Source Files
|
||||||
|
|
||||||
|
Modified files (relative to MeshCore root):
|
||||||
|
|
||||||
|
- `examples/relay_radio/MyMesh.h` — class declaration, relay/temp fields
|
||||||
|
- `examples/relay_radio/MyMesh.cpp` — relay on/off logic, temp reading, command parsing
|
||||||
|
- `examples/relay_radio/main.cpp` — entry point, BLE config, pin setup
|
||||||
|
- `platformio.ini` — added OneWire/DallasTemperature libs, 2 new envs for T114
|
||||||
|
|
||||||
|
## Build Environments
|
||||||
|
|
||||||
|
Two envs defined in `platformio.ini`:
|
||||||
|
|
||||||
|
1. `Heltec_t114_relay_radio_usb` — Serial USB interface
|
||||||
|
2. `Heltec_t114_relay_radio_ble` — BLE interface with PIN 123456
|
||||||
|
|
||||||
|
Both based on existing `Heltec_t114` variant.
|
||||||
|
|
||||||
|
## Build & Flash
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build
|
||||||
|
pio run -e Heltec_t114_relay_radio_usb
|
||||||
|
pio run -e Heltec_t114_relay_radio_ble
|
||||||
|
|
||||||
|
# Flash
|
||||||
|
pio run -e Heltec_t114_relay_radio_ble -t upload --upload-port <port>
|
||||||
|
```
|
||||||
|
|
||||||
|
### UF2 Drag-and-Drop
|
||||||
|
|
||||||
|
1. Double-tap reset button on T114 to enter UF2 mode
|
||||||
|
2. Copy `firmware.uf2` from `.pio/build/Heltec_t114_relay_radio_ble/` to mounted disk
|
||||||
|
|
||||||
|
## Key Implementation Details
|
||||||
|
|
||||||
|
- Commands received via `onMessageRecv()` callback
|
||||||
|
- Response sent via `sendMessage()` (reuses encrypted chat channel)
|
||||||
|
- Timer-based advert in `MyMesh::loop()` every 30 min (1800000 ms)
|
||||||
|
- OneWire/DallasTemperature initialized in constructor
|
||||||
|
- Temperature read on demand (not periodically)
|
||||||
|
- All parameters settable via build flags in `platformio.ini`
|
||||||
|
|
||||||
|
## Auto-Advert Timing
|
||||||
|
|
||||||
|
- Interval: 30 minutes (1800000 ms)
|
||||||
|
- Advert name: "Relay" (set via `ADVERT_NAME` define)
|
||||||
|
- Implemented in `MyMesh::loop()` with `_next_advert_ms` field
|
||||||
|
|
||||||
|
## Repository
|
||||||
|
|
||||||
|
- Gitea: https://git2.ua1zbe.ru/ua1zbe/MeshCore-RelayRadio
|
||||||
|
- Release v1.0.0 with UF2 binaries (BLE + USB)
|
||||||
|
- User credentials: ua1zbe / Personal Access Token: `067f4415552ac62ba4ff8e7704c924da17dd3fbf`
|
||||||
|
|
||||||
|
## Updating Gitea
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /tmp/opencode/fresh-repo
|
||||||
|
git add -A
|
||||||
|
git commit -m "message"
|
||||||
|
git push origin main
|
||||||
|
```
|
||||||
|
|
||||||
|
## Creating a New Release
|
||||||
|
|
||||||
|
```bash
|
||||||
|
TOKEN="067f4415552ac62ba4ff8e7704c924da17dd3fbf"
|
||||||
|
VERSION="v1.1.0"
|
||||||
|
|
||||||
|
# Tag and push
|
||||||
|
git tag -a "$VERSION" -m "Release $VERSION"
|
||||||
|
git push origin "$VERSION"
|
||||||
|
|
||||||
|
# Create release
|
||||||
|
curl -s -X POST "https://git2.ua1zbe.ru/api/v1/repos/ua1zbe/MeshCore-RelayRadio/releases" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Authorization: token $TOKEN" \
|
||||||
|
-d "{\"tag_name\":\"$VERSION\",\"name\":\"$VERSION\",\"body\":\"Release description\"}"
|
||||||
|
|
||||||
|
# Upload assets (get RELEASE_ID from response)
|
||||||
|
curl -s -X POST "https://git2.ua1zbe.ru/api/v1/repos/ua1zbe/MeshCore-RelayRadio/releases/$RELEASE_ID/assets" \
|
||||||
|
-H "Authorization: token $TOKEN" \
|
||||||
|
-F "attachment=@path/to/file.uf2" \
|
||||||
|
-F "name=Heltec_T114_BLE_firmware.uf2"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Ongoing Maintenance
|
||||||
|
|
||||||
|
- Firmware is based on upstream MeshCore. To update, re-clone MeshCore, re-apply the `examples/relay_radio/` modifications, and rebuild.
|
||||||
|
- The `relay_radio` example lives in `examples/relay_radio/` — it is a modified copy of `examples/companion_radio/`.
|
||||||
|
- Compiled UF2 files are kept in `/home/ua1zbe/Рабочий стол/relay_radio_firmware/` on the developer machine.
|
||||||
|
- Full build/usage instructions: `README.md`
|
||||||
441
README.md
441
README.md
@@ -1,128 +1,333 @@
|
|||||||
## About MeshCore
|
# MeshCore — Relay + DS18B20 на базе Companion Radio
|
||||||
|
|
||||||
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.
|
## 1. Что это
|
||||||
|
|
||||||
## 🔍 What is MeshCore?
|
Модификация прошивки `companion_radio` из MeshCore. Устройство получает по LoRa-мешу приватные команды и управляет реле, а также отвечает на запросы температуры с DS18B20.
|
||||||
|
|
||||||
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.
|
## 2. Откуда брать проект
|
||||||
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.
|
|
||||||
|
|
||||||
## ⚡ Key Features
|
|
||||||
|
|
||||||
* 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.
|
|
||||||
|
|
||||||
## 🎯 What Can You Use MeshCore For?
|
|
||||||
|
|
||||||
* 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.
|
|
||||||
|
|
||||||
## 🚀 How to Get Started
|
|
||||||
|
|
||||||
- Watch the [MeshCore QuickStart Playlist](https://www.youtube.com/watch?v=iaFltojJrAc&list=PLshzThxhw4O4WU_iZo3NmNZOv6KMrUuF9) by The Comms Channel
|
|
||||||
- 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.
|
|
||||||
|
|
||||||
For developers:
|
|
||||||
|
|
||||||
- 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 Wi-Fi.
|
|
||||||
- [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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## ⚡️ MeshCore Flasher
|
|
||||||
|
|
||||||
We have prebuilt firmware ready to flash on supported devices.
|
|
||||||
|
|
||||||
- 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.
|
|
||||||
|
|
||||||
## 📱 MeshCore Clients
|
|
||||||
|
|
||||||
**Companion Firmware**
|
|
||||||
|
|
||||||
The companion firmware can be connected to via BLE, USB or Wi-Fi depending on the firmware type you flashed.
|
|
||||||
|
|
||||||
- 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
|
|
||||||
|
|
||||||
**Repeater and Room Server Firmware**
|
|
||||||
|
|
||||||
The repeater and room server firmware can be set up via USB in the web config tool.
|
|
||||||
|
|
||||||
- https://config.meshcore.io
|
|
||||||
|
|
||||||
They can also be managed via LoRa in the mobile app by using the Remote Management feature.
|
|
||||||
|
|
||||||
## 🛠 Hardware Compatibility
|
|
||||||
|
|
||||||
MeshCore is designed for devices listed in the [MeshCore Flasher](https://meshcore.io/flasher)
|
|
||||||
|
|
||||||
## 📜 License
|
|
||||||
|
|
||||||
MeshCore is open-source software released under the MIT License. You are free to use, modify, and distribute it for personal and commercial projects.
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
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. It 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.
|
|
||||||
|
|
||||||
Here are some general principles 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 probably going to be added soon, but please do NOT retroactively re-format existing code. This just creates unnecessary diffs that make finding problems harder)
|
|
||||||
|
|
||||||
Help us prioritize! Please react with thumbs-up to issues/PRs you care about most. We look at reaction counts when planning work.
|
|
||||||
|
|
||||||
### Running unit tests
|
|
||||||
|
|
||||||
To run unit tests, run the following command:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pio test --environment native --verbose
|
git clone --depth 1 https://github.com/meshcore-dev/MeshCore.git
|
||||||
|
cd MeshCore
|
||||||
```
|
```
|
||||||
|
|
||||||
## Road-Map / To-Do
|
## 3. Что нужно установить
|
||||||
|
|
||||||
There are a number of fairly major features in the pipeline, with no particular time-frames attached yet. In very rough chronological order:
|
### PlatformIO
|
||||||
- [X] Companion radio: UI redesign
|
- Установить Python 3
|
||||||
- [X] Repeater + Room Server: add ACL's (like Sensor Node has)
|
- Установить PlatformIO: `pip install platformio`
|
||||||
- [X] Standardise Bridge mode for repeaters
|
- Или установить VS Code + расширение PlatformIO
|
||||||
- [ ] 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
|
|
||||||
|
|
||||||
## 📞 Get Support
|
### Зависимости (добавить в platformio.ini)
|
||||||
|
В секцию `[arduino_base]`, в `lib_deps` добавить:
|
||||||
|
```
|
||||||
|
paulstoffregen/OneWire @ ^2.3.7
|
||||||
|
milesburton/DallasTemperature @ ^3.11.0
|
||||||
|
```
|
||||||
|
|
||||||
- Report bugs and request features on the [GitHub Issues](https://github.com/ripplebiz/MeshCore/issues) page.
|
## 4. Какие файлы править
|
||||||
- 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.
|
Базовый проект — `examples/companion_radio/`.
|
||||||
|
|
||||||
|
### Файлы для изменения:
|
||||||
|
|
||||||
|
| Файл | Что делать |
|
||||||
|
|------|------------|
|
||||||
|
| `platformio.ini` | Добавить OneWire и DallasTemperature в lib_deps; для nRF52 добавить env (раздел 7.3) |
|
||||||
|
| `examples/companion_radio/MyMesh.h` | Добавить #include, пины, поле OneWire/DallasTemperature, метод `readTemperature()` |
|
||||||
|
| `examples/companion_radio/MyMesh.cpp` | В конструктор — инициализация OneWire, в begin() — `_tempSensor.begin()`, реализовать `readTemperature()`, изменить `onMessageRecv()` |
|
||||||
|
| `examples/companion_radio/main.cpp` | В `setup()` добавить `pinMode(RELAY_PIN, OUTPUT)` |
|
||||||
|
|
||||||
|
### Подключение железа (ESP32):
|
||||||
|
|
||||||
|
| Пин | Назначение |
|
||||||
|
|-----|------------|
|
||||||
|
| GPIO 4 | Реле (RELAY_PIN) |
|
||||||
|
| GPIO 5 | DS18B20 Data (ONE_WIRE_BUS) |
|
||||||
|
| 3.3V | DS18B20 VCC (через 4.7k подтяжку к Data) |
|
||||||
|
| GND | Общий |
|
||||||
|
|
||||||
|
### Параметры радио (ESP32)
|
||||||
|
|
||||||
|
В `platformio.ini` в вашей env-секции (например `[env:esp32dev_companion_radio_usb]`) переопределить:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
build_flags = ${arduino_base.build_flags}
|
||||||
|
-D LORA_FREQ=868.731018
|
||||||
|
-D LORA_BW=62.5
|
||||||
|
-D LORA_SF=7
|
||||||
|
-D LORA_CR=7
|
||||||
|
```
|
||||||
|
|
||||||
|
Для хэша пути 1 байт в `MyMesh.cpp` в конструкторе указать:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
_prefs.path_hash_mode = 0;
|
||||||
|
```
|
||||||
|
|
||||||
|
Для **nRF52840 (XIAO)** пины по умолчанию: `RELAY_PIN = D6 (P0.08)`, `ONE_WIRE_BUS = D7 (P0.09)` — смотрите раздел 7.2.
|
||||||
|
|
||||||
|
### Автоматическая отправка advertise каждые 30 минут
|
||||||
|
|
||||||
|
В `MyMesh.h` добавить поле:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
float readTemperature();
|
||||||
|
|
||||||
|
private:
|
||||||
|
unsigned long _next_advert_ms;
|
||||||
|
OneWire _oneWire;
|
||||||
|
DallasTemperature _tempSensor;
|
||||||
|
```
|
||||||
|
|
||||||
|
В `MyMesh.cpp` в конструкторе инициализировать:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
MyMesh::MyMesh(...) : BaseChatMesh(...), _oneWire(ONE_WIRE_BUS), _tempSensor(&_oneWire) {
|
||||||
|
_next_advert_ms = 0;
|
||||||
|
// ... остальной код ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
В `MyMesh::loop()` (или в `main.cpp` в `loop()`) добавить проверку таймера:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void MyMesh::loop() {
|
||||||
|
BaseChatMesh::loop(); // существующий вызов
|
||||||
|
|
||||||
|
// advertise каждые 30 минут (1800000 мс)
|
||||||
|
if (millisHasNowPassed(_next_advert_ms)) {
|
||||||
|
advert();
|
||||||
|
_next_advert_ms = futureMillis(1800000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Либо ещё проще — в `main.cpp`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void loop() {
|
||||||
|
static unsigned long next_advert = 0;
|
||||||
|
the_mesh.loop();
|
||||||
|
sensors.loop();
|
||||||
|
// ... остальной код ...
|
||||||
|
|
||||||
|
if (millisHasNowPassed(next_advert)) {
|
||||||
|
the_mesh.advert();
|
||||||
|
next_advert = futureMillis(1800000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Команды (приватные сообщения узлу)
|
||||||
|
|
||||||
|
| Команда | Ответ | Действие |
|
||||||
|
|---------|-------|----------|
|
||||||
|
| `on1234` | `relay on` | Реле включено |
|
||||||
|
| `off1234` | `relay off` | Реле выключено |
|
||||||
|
| `temp` | `temp: 23.5 C` | Температура с DS18B20 |
|
||||||
|
| `state` | `temp: 23.5 C, relay: ON` | Температура + состояние реле |
|
||||||
|
|
||||||
|
Цифра `1234` — код доступа к реле (можно сменить в `RELAY_CODE`).
|
||||||
|
|
||||||
|
## 6. Как залить
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd MeshCore
|
||||||
|
# для конкретной платы, например ESP32:
|
||||||
|
pio run -e <board_name> -t upload
|
||||||
|
# или открыть в VS Code + PlatformIO и собрать через IDE
|
||||||
|
```
|
||||||
|
|
||||||
|
## 7. Версия для nRF52840 + HT-RA62 (SX1262)
|
||||||
|
|
||||||
|
### 7.1 Что за связка
|
||||||
|
|
||||||
|
**nRF52840** — популярный MCU с BLE. **HT-RA62** — LoRa-модуль на чипе SX1262 (аналог E22-900Mxx).
|
||||||
|
|
||||||
|
Можно использовать любую плату на nRF52840 + внешний HT-RA62 по SPI. Самый популярный вариант — **Seeed XIAO nRF52840** + HT-RA62 на макетной плате.
|
||||||
|
|
||||||
|
### 7.2 Распиновка XIAO nRF52840 + HT-RA62
|
||||||
|
|
||||||
|
| Пин XIAO | GPIO nRF52 | HT-RA62 | Назначение |
|
||||||
|
|----------|------------|---------|------------|
|
||||||
|
| D0 | P0.02 | NSS | CS (SPI chip select) |
|
||||||
|
| D1 | P0.03 | DIO1 | IRQ (прерывание) |
|
||||||
|
| D2 | P0.04 | BUSY | Занятость модуля |
|
||||||
|
| D3 | P0.05 | RESET | Сброс |
|
||||||
|
| D4 | P0.06 | RXEN | Включение RX (если есть) |
|
||||||
|
| D5 | P0.07 | TXEN | Включение TX (если есть) |
|
||||||
|
| D6 | P0.08 | (свободен) | **Реле (RELAY_PIN)** |
|
||||||
|
| D7 | P0.09 | (свободен) | **DS18B20 Data (ONE_WIRE_BUS)** |
|
||||||
|
| D8 | P0.10 | SCK | SPI clock |
|
||||||
|
| D9 | P0.28 | MO | SPI MOSI |
|
||||||
|
| D10 | P0.02 | MI | SPI MISO |
|
||||||
|
| 3.3V | — | VCC | 3.3V питание |
|
||||||
|
| GND | — | GND | Общий |
|
||||||
|
|
||||||
|
> **Важно:** У HT-RA62 DIO2 настроен как RF-переключатель, DIO3 — 1.8V для TCXO (задаётся в коде).
|
||||||
|
|
||||||
|
**Свободные пины XIAO nRF52840 после подключения:**
|
||||||
|
|
||||||
|
| Пин | Назначение | Можно |
|
||||||
|
|-----|------------|-------|
|
||||||
|
| D0 (P0.01) | GPIO | цифровой вход/выход |
|
||||||
|
| D5 (P0.06) | RXEN (HT-RA62) | **да** — если RXEN не используется (у HT-RA62 коммутация RF уже через DIO2) |
|
||||||
|
| A0 (P0.31) | ADC/GPIO | аналоговый или цифровой |
|
||||||
|
| A1 (P0.29) | ADC/GPIO | аналоговый или цифровой |
|
||||||
|
| A2 (P0.30) | ADC/GPIO | аналоговый или цифровой |
|
||||||
|
|
||||||
|
**Занято:** D1(IRQ), D2(BUSY), D3(RESET), D4(NSS), D6(реле), D7(DS18B20), D8(SCK), D9(MOSI), D10(MISO) — 9 пинов.
|
||||||
|
**Свободно:** 4–5 пинов (D0, D5, A0, A1, A2) для кнопок, светодиодов или доп. датчиков.
|
||||||
|
|
||||||
|
### 7.3 Что добавить в platformio.ini
|
||||||
|
|
||||||
|
В конец файла `platformio.ini` дописать:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
; ===== nRF52840 + HT-RA62 (SX1262) =====
|
||||||
|
[Xiao_nrf52]
|
||||||
|
extends = nrf52_base
|
||||||
|
board = seeed-xiao-afruitnrf52-nrf52840
|
||||||
|
board_build.ldscript = boards/nrf52840_s140_v7.ld
|
||||||
|
build_flags = ${nrf52_base.build_flags}
|
||||||
|
-D USE_SX1262
|
||||||
|
-D LORA_TX_POWER=22
|
||||||
|
-D ADVERT_NAME="Relay"
|
||||||
|
-D LORA_FREQ=868.731018
|
||||||
|
-D LORA_BW=62.5
|
||||||
|
-D LORA_SF=7
|
||||||
|
-D LORA_CR=7
|
||||||
|
|
||||||
|
[env:Xiao_nrf52_companion_radio_usb]
|
||||||
|
extends = Xiao_nrf52
|
||||||
|
build_src_filter = ${nrf52_base.build_src_filter}
|
||||||
|
+<examples/companion_radio/>
|
||||||
|
|
||||||
|
[env:Xiao_nrf52_companion_radio_ble]
|
||||||
|
extends = Xiao_nrf52
|
||||||
|
build_flags = ${Xiao_nrf52.build_flags}
|
||||||
|
-D BLE_PIN_CODE=123456
|
||||||
|
build_src_filter = ${nrf52_base.build_src_filter}
|
||||||
|
+<examples/companion_radio/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Значения по умолчанию в `[arduino_base]` переопределяются в `Xiao_nrf52`.
|
||||||
|
|
||||||
|
### 7.3.1 Хэш пути 1 байт
|
||||||
|
|
||||||
|
В `MyMesh.h` перед классом `MyMesh` добавить:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define ADVERT_NAME "Relay"
|
||||||
|
// хэш пути — 1 байт (mode 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
В конструкторе `MyMesh` (в `MyMesh.cpp`) явно установить `path_hash_mode`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
_prefs.path_hash_mode = 0; // 0 = 1 байт, 1 = 2 байта, 2 = 3 байта
|
||||||
|
```
|
||||||
|
|
||||||
|
Либо в `main.cpp` можно задать через define и использовать в `platformio.ini`:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
-D PATH_HASH_MODE=0
|
||||||
|
```
|
||||||
|
|
||||||
|
а в `MyMesh.cpp`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#ifndef PATH_HASH_MODE
|
||||||
|
#define PATH_HASH_MODE 0
|
||||||
|
#endif
|
||||||
|
...
|
||||||
|
_prefs.path_hash_mode = PATH_HASH_MODE;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3.2 Итоговые параметры радио
|
||||||
|
|
||||||
|
| Параметр | Значение |
|
||||||
|
|----------|----------|
|
||||||
|
| Частота | 868.731018 МГц |
|
||||||
|
| Полоса (BW) | 62.5 кГц |
|
||||||
|
| Spreading Factor | 7 |
|
||||||
|
| Coding Rate | 7 |
|
||||||
|
| Хэш пути | 1 байт |
|
||||||
|
|
||||||
|
### 7.4 Как собрать и прошить
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export FIRMWARE_VERSION=v1.0.0
|
||||||
|
|
||||||
|
# Собрать прошивку (USB Serial)
|
||||||
|
pio run -e Xiao_nrf52_companion_radio_usb
|
||||||
|
|
||||||
|
# Собрать прошивку (BLE)
|
||||||
|
pio run -e Xiao_nrf52_companion_radio_ble
|
||||||
|
|
||||||
|
# После сборки .uf2 файл будет здесь:
|
||||||
|
# .pio/build/Xiao_nrf52_companion_radio_usb/firmware.uf2
|
||||||
|
```
|
||||||
|
|
||||||
|
**Способы прошивки nRF52840:**
|
||||||
|
|
||||||
|
| Метод | Описание |
|
||||||
|
|-------|----------|
|
||||||
|
| **UF2 (drag-and-drop)** | Подключить плату в режиме UF2 (двойной тап по кнопке reset), скопировать `.uf2` на появившийся диск |
|
||||||
|
| **pio run -t upload** | Через PlatformIO (nrfutil) |
|
||||||
|
| **через J-Link** | `pio run -e Xiao_nrf52_companion_radio_usb -t upload --upload-port jlink` |
|
||||||
|
| **OTA по BLE** | Через приложение Adafruit Bluefruit (если собран `_ble` вариант) |
|
||||||
|
|
||||||
|
### 7.5 Если HT-RA62 подключен к другой плате
|
||||||
|
|
||||||
|
Найдите в `variants/` свою плату или создайте свою. Для HT-RA62 везде одинаковые настройки SX1262:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define SX126X_DIO2_AS_RF_SWITCH 1
|
||||||
|
#define SX126X_DIO3_TCXO_VOLTAGE 1.8
|
||||||
|
#define SX126X_CURRENT_LIMIT 140
|
||||||
|
#define SX126X_RX_BOOSTED_GAIN 1
|
||||||
|
```
|
||||||
|
|
||||||
|
Пины SPI (SCK, MOSI, MISO) общие с остальной периферией. NSS, DIO1, BUSY, RESET — назначаются индивидуально.
|
||||||
|
|
||||||
|
### 7.6 Альтернативные платформы с nRF52840
|
||||||
|
|
||||||
|
Если HT-RA62 уже впаян в готовую плату — проверьте `variants/`, возможно ваша плата уже там:
|
||||||
|
|
||||||
|
| Плата | Вариант | Пример env |
|
||||||
|
|-------|---------|------------|
|
||||||
|
| RAK4631 WisBlock | `rak4631` | `env:RAK_4631_companion_radio_ble` |
|
||||||
|
| Nologo ProMicro nRF52840 | `promicro` | `env:ProMicro_repeater` |
|
||||||
|
| Nano G2 Ultra | `nano_g2_ultra` | `env:Nano_G2_Ultra_companion_radio_ble` |
|
||||||
|
| RAK3401 (1W) | `rak3401` | `env:RAK_3401_repeater` |
|
||||||
|
|
||||||
|
Список всех nRF52-вариантов — в `variants/`.
|
||||||
|
|
||||||
|
## 8. Структура проекта (кратко)
|
||||||
|
|
||||||
|
```
|
||||||
|
MeshCore/
|
||||||
|
├── src/ # ядро библиотеки
|
||||||
|
│ ├── Mesh.h / .cpp # роутинг, диспетчеризация payload-типов
|
||||||
|
│ ├── Packet.h / .cpp # формат пакета
|
||||||
|
│ ├── Dispatcher.h / .cpp # планировщик радио
|
||||||
|
│ └── helpers/
|
||||||
|
│ └── BaseChatMesh.h/.cpp # чат-абстракция (родительский класс)
|
||||||
|
├── examples/
|
||||||
|
│ └── companion_radio/ # ТО, ЧТО МЫ МОДИФИЦИРУЕМ
|
||||||
|
│ ├── MyMesh.h / .cpp # основной класс
|
||||||
|
│ ├── main.cpp # точка входа
|
||||||
|
│ └── ...
|
||||||
|
└── platformio.ini # конфиг сборки
|
||||||
|
```
|
||||||
|
|
||||||
|
## 9. Как это работает (кратко)
|
||||||
|
|
||||||
|
1. Узел-отправитель знает публичный ключ устройства с реле (контакт добавлен через advertise)
|
||||||
|
2. Он отправляет `sendMessage(recipient, timestamp, 0, "on1234", ...)`
|
||||||
|
3. Пакет шифруется AES128+HMAC, летит по mesh (flood routing)
|
||||||
|
4. Устройство-исполнитель получает, расшифровывает, `BaseChatMesh` вызывает `onMessageRecv()`
|
||||||
|
5. Мы проверяем текст, управляем реле/читаем температуру и шлём ответ
|
||||||
|
6. Ответ тоже шифрованный, идёт по обратному пути
|
||||||
|
|||||||
@@ -2297,7 +2297,9 @@ bool MyMesh::advert() {
|
|||||||
|
|
||||||
// To check if there is pending work
|
// To check if there is pending work
|
||||||
bool MyMesh::hasPendingWork() const {
|
bool MyMesh::hasPendingWork() const {
|
||||||
return _mgr->getOutboundTotal() > 0 || dirty_contacts_expiry != 0;
|
return _mgr->getOutboundTotal() > 0
|
||||||
|
|| dirty_contacts_expiry != 0
|
||||||
|
|| millisHasNowPassed(_next_advert_ms);
|
||||||
}
|
}
|
||||||
|
|
||||||
float MyMesh::readTemperature() {
|
float MyMesh::readTemperature() {
|
||||||
|
|||||||
@@ -434,3 +434,39 @@ lib_deps =
|
|||||||
extends = Heltec_lora32_v4
|
extends = Heltec_lora32_v4
|
||||||
build_src_filter = ${Heltec_lora32_v4.build_src_filter}
|
build_src_filter = ${Heltec_lora32_v4.build_src_filter}
|
||||||
+<../examples/kiss_modem/>
|
+<../examples/kiss_modem/>
|
||||||
|
|
||||||
|
; ===== Heltec V4 Relay Radio =====
|
||||||
|
[Heltec_v4_relay]
|
||||||
|
extends = heltec_v4_oled
|
||||||
|
build_flags =
|
||||||
|
${heltec_v4_oled.build_flags}
|
||||||
|
-I examples/relay_radio/ui-new
|
||||||
|
-D MAX_CONTACTS=100
|
||||||
|
-D MAX_GROUP_CHANNELS=10
|
||||||
|
-D DISPLAY_CLASS=SSD1306Display
|
||||||
|
-D RELAY_PIN=6
|
||||||
|
-D ONE_WIRE_BUS=20
|
||||||
|
-D LORA_FREQ=868.731018
|
||||||
|
-D LORA_BW=62.5
|
||||||
|
-D LORA_SF=7
|
||||||
|
-D LORA_CR=7
|
||||||
|
-D ADVERT_NAME='"Relay"'
|
||||||
|
; -D MESH_PACKET_LOGGING=1
|
||||||
|
; -D MESH_DEBUG=1
|
||||||
|
build_src_filter = ${heltec_v4_oled.build_src_filter}
|
||||||
|
+<helpers/ui/SSD1306Display.cpp>
|
||||||
|
+<helpers/ui/MomentaryButton.cpp>
|
||||||
|
+<helpers/esp32/*.cpp>
|
||||||
|
+<../examples/relay_radio/*.cpp>
|
||||||
|
+<../examples/relay_radio/ui-new/*.cpp>
|
||||||
|
lib_deps =
|
||||||
|
${heltec_v4_oled.lib_deps}
|
||||||
|
densaugeo/base64 @ ~1.4.0
|
||||||
|
|
||||||
|
[env:heltec_v4_relay_radio_usb]
|
||||||
|
extends = Heltec_v4_relay
|
||||||
|
|
||||||
|
[env:heltec_v4_relay_radio_ble]
|
||||||
|
extends = Heltec_v4_relay
|
||||||
|
build_flags = ${Heltec_v4_relay.build_flags}
|
||||||
|
-D BLE_PIN_CODE=123456
|
||||||
|
|||||||
Reference in New Issue
Block a user