From 40c96332386db7feb1e1c24f87af5b958bd4825a Mon Sep 17 00:00:00 2001 From: UA1ZBE Date: Fri, 5 Jun 2026 09:35:09 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BF=D1=80=D0=BE=D1=88=D0=B8=D0=B2=D0=BA=D0=B0?= =?UTF-8?q?=20Beacon=20Sensor=20=D0=B4=D0=BB=D1=8F=20Heltec=20T114?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Новый пример examples/beacon_sensor/ на основе companion_radio - Автоматическая отправка flood-объявления каждые 15 минут - ADV_TYPE_CHAT, ретрансляция через mesh-сеть - Поддержка BMP280 по I2C (Wire1, SDA=7, SCL=8) - Новые build-варианты в variants/heltec_t114/platformio.ini: - Heltec_t114_without_display_beacon_sensor_ble - Heltec_t114_without_display_beacon_sensor_usb - Heltec_t114_beacon_sensor_ble (с дисплеем) - Heltec_t114_beacon_sensor_usb (с дисплеем) - Радиопараметры: 868.731 MHz, SF7, BW62.5, CR7, path hash 1 байт Инструкция по прошивке: 1. pio run -e Heltec_t114_without_display_beacon_sensor_ble -t create_uf2 2. Зажми BOOT на T114, подключи USB, появится диск T114 3. Перетащи firmware.uf2 на диск --- .gitignore | 21 +- README.md | 70 +- examples/beacon_sensor/AbstractUITask.h | 46 + examples/beacon_sensor/DataStore.cpp | 622 ++++++ examples/beacon_sensor/DataStore.h | 55 + examples/beacon_sensor/MyMesh.cpp | 2218 +++++++++++++++++++++ examples/beacon_sensor/MyMesh.h | 259 +++ examples/beacon_sensor/NodePrefs.h | 37 + examples/beacon_sensor/main.cpp | 232 +++ examples/beacon_sensor/ui-new/UITask.cpp | 923 +++++++++ examples/beacon_sensor/ui-new/UITask.h | 101 + examples/beacon_sensor/ui-new/icons.h | 122 ++ examples/beacon_sensor/ui-orig/Button.cpp | 131 ++ examples/beacon_sensor/ui-orig/Button.h | 80 + examples/beacon_sensor/ui-orig/UITask.cpp | 446 +++++ examples/beacon_sensor/ui-orig/UITask.h | 73 + variants/heltec_t114/platformio.ini | 96 + 17 files changed, 5511 insertions(+), 21 deletions(-) create mode 100644 examples/beacon_sensor/AbstractUITask.h create mode 100644 examples/beacon_sensor/DataStore.cpp create mode 100644 examples/beacon_sensor/DataStore.h create mode 100644 examples/beacon_sensor/MyMesh.cpp create mode 100644 examples/beacon_sensor/MyMesh.h create mode 100644 examples/beacon_sensor/NodePrefs.h create mode 100644 examples/beacon_sensor/main.cpp create mode 100644 examples/beacon_sensor/ui-new/UITask.cpp create mode 100644 examples/beacon_sensor/ui-new/UITask.h create mode 100644 examples/beacon_sensor/ui-new/icons.h create mode 100644 examples/beacon_sensor/ui-orig/Button.cpp create mode 100644 examples/beacon_sensor/ui-orig/Button.h create mode 100644 examples/beacon_sensor/ui-orig/UITask.cpp create mode 100644 examples/beacon_sensor/ui-orig/UITask.h diff --git a/.gitignore b/.gitignore index a0ad5f6..ab30420 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,2 @@ -.direnv -.pio -.vscode/.browse.c_cpp.db* -.vscode/c_cpp_properties.json -.vscode/launch.json -.vscode/ipch -out/ -.direnv/ -.DS_Store -.vscode/settings.json -.vscode/extensions.json -.idea -cmake-* -.cache -.ccls -compile_commands.json -.venv/ -venv/ -platformio.local.ini +*.uf2 +.pio/ diff --git a/README.md b/README.md index 8013b3d..f9ffe22 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ -## MeshCore Simple Sensor — Heltec T114 + BME280 +## MeshCore Firmware for Heltec T114 -Прошивка **Simple Sensor** на базе [MeshCore](https://github.com/meshcore-dev/MeshCore) для платы **Heltec T114** (без экрана) с датчиком **BME280** (температура, влажность, атмосферное давление). +Прошивки на базе [MeshCore](https://github.com/meshcore-dev/MeshCore) для платы **Heltec T114**. + +--- + +## 1. Simple Sensor — Heltec T114 + BME280 + +Прошивка **Simple Sensor** для платы **Heltec T114** (без экрана) с датчиком **BME280** (температура, влажность, атмосферное давление). ### 🎯 Назначение @@ -64,6 +70,66 @@ pio run -e Heltec_t114_without_display_simple_sensor -t create_uf2 Другие устройства mesh-сети могут подключаться к сенсору и запрашивать телеметрию по протоколу MeshCore. +--- + +## 2. Beacon Sensor (Auto-Announce) — Heltec T114 + BMP280 + +Прошивка **Beacon Sensor** — устройство автоматически отправляет flood-объявление (advert) в mesh-сеть **каждые 15 минут**. Подключён **BMP280** по I2C, телеметрия доступна по запросу. Подключается к Companion-клиентам через **BLE**. + +### 📻 Параметры радиоканала + +| Параметр | Значение | +|---|---| +| Частота | 868.731018 МГц | +| Полоса (BW) | 62.5 кГц | +| Spreading Factor | 7 | +| Coding Rate | 7 | +| Хэш пути | 1 байт | +| Мощность | 22 dBm | + +### 🧩 Поддерживаемые датчики (I2C на Wire1, SDA=7, SCL=8) + +- **BMP280** — температура, давление +- Все датчики из списка Simple Sensor + +### 🔧 Сборка + +```bash +# Без дисплея, через BLE (рекомендуемый вариант) +pio run -e Heltec_t114_without_display_beacon_sensor_ble -t create_uf2 + +# С дисплеем, через BLE +pio run -e Heltec_t114_beacon_sensor_ble -t create_uf2 + +# Без дисплея, через USB (Serial) +pio run -e Heltec_t114_without_display_beacon_sensor_usb -t create_uf2 + +# С дисплеем, через USB (Serial) +pio run -e Heltec_t114_beacon_sensor_usb -t create_uf2 +``` + +Файл прошивки: `.pio/build//firmware.uf2` + +### 🚀 Прошивка (UF2) + +1. Зажми кнопку **BOOT/PRG** на T114 +2. Подключи USB к компьютеру +3. Отпусти кнопку — появится диск `T114` +4. Перетащи `firmware.uf2` на этот диск +5. Устройство перезагрузится и начнёт работу + +Или через nrfutil: +```bash +nrfutil dfu usb-serial -pkg .pio/build//firmware.zip -p /dev/ttyACM0 +``` + +### 📡 Использование + +- Устройство автоматически отправляет объявление (advert) в mesh-сеть каждые 15 минут +- Объявление распространяется flood'ом (ретранслируется другими узлами) +- Подключись через **BLE** (пин: `123456`) к мобильному приложению MeshCore +- BMP280 телеметрия доступна по запросу через протокол MeshCore + ### 🔗 Совместимость - Работает с Companion Radio (BLE/USB/WiFi) diff --git a/examples/beacon_sensor/AbstractUITask.h b/examples/beacon_sensor/AbstractUITask.h new file mode 100644 index 0000000..0eee45a --- /dev/null +++ b/examples/beacon_sensor/AbstractUITask.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#ifdef PIN_BUZZER + #include +#endif + +#include "NodePrefs.h" + +enum class UIEventType { + none, + contactMessage, + channelMessage, + roomMessage, + newContactMessage, + ack +}; + +class AbstractUITask { +protected: + mesh::MainBoard* _board; + BaseSerialInterface* _serial; + bool _connected; + + AbstractUITask(mesh::MainBoard* board, BaseSerialInterface* serial) : _board(board), _serial(serial) { + _connected = false; + } + +public: + void setHasConnection(bool connected) { _connected = connected; } + bool hasConnection() const { return _connected; } + uint16_t getBattMilliVolts() const { return _board->getBattMilliVolts(); } + bool isSerialEnabled() const { return _serial->isEnabled(); } + void enableSerial() { _serial->enable(); } + void disableSerial() { _serial->disable(); } + virtual void msgRead(int msgcount) = 0; + virtual void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) = 0; + virtual void notify(UIEventType t = UIEventType::none) = 0; + virtual void loop() = 0; +}; diff --git a/examples/beacon_sensor/DataStore.cpp b/examples/beacon_sensor/DataStore.cpp new file mode 100644 index 0000000..c7988bb --- /dev/null +++ b/examples/beacon_sensor/DataStore.cpp @@ -0,0 +1,622 @@ +#include +#include "DataStore.h" + +#if defined(EXTRAFS) || defined(QSPIFLASH) + #define MAX_BLOBRECS 100 +#else + #define MAX_BLOBRECS 20 +#endif + +DataStore::DataStore(FILESYSTEM& fs, mesh::RTCClock& clock) : _fs(&fs), _fsExtra(nullptr), _clock(&clock), +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + identity_store(fs, "") +#elif defined(RP2040_PLATFORM) + identity_store(fs, "/identity") +#else + identity_store(fs, "/identity") +#endif +{ +} + +#if defined(EXTRAFS) || defined(QSPIFLASH) +DataStore::DataStore(FILESYSTEM& fs, FILESYSTEM& fsExtra, mesh::RTCClock& clock) : _fs(&fs), _fsExtra(&fsExtra), _clock(&clock), +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + identity_store(fs, "") +#elif defined(RP2040_PLATFORM) + identity_store(fs, "/identity") +#else + identity_store(fs, "/identity") +#endif +{ +} +#endif + +static File openWrite(FILESYSTEM* fs, const char* filename) { +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + fs->remove(filename); + return fs->open(filename, FILE_O_WRITE); +#elif defined(RP2040_PLATFORM) + return fs->open(filename, "w"); +#else + return fs->open(filename, "w", true); +#endif +} + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + static uint32_t _ContactsChannelsTotalBlocks = 0; +#endif + +void DataStore::begin() { +#if defined(RP2040_PLATFORM) + identity_store.begin(); +#endif + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + _ContactsChannelsTotalBlocks = _getContactsChannelsFS()->_getFS()->cfg->block_count; + checkAdvBlobFile(); + #if defined(EXTRAFS) || defined(QSPIFLASH) + migrateToSecondaryFS(); + #endif +#else + // init 'blob store' support + _fs->mkdir("/bl"); +#endif +} + +#if defined(ESP32) + #include + #include +#elif defined(RP2040_PLATFORM) + #include +#elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + #if defined(QSPIFLASH) + #include + #elif defined(EXTRAFS) + #include + #else + #include + #endif +#endif + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) +int _countLfsBlock(void *p, lfs_block_t block){ + if (block > _ContactsChannelsTotalBlocks) { + MESH_DEBUG_PRINTLN("ERROR: Block %d exceeds filesystem bounds - CORRUPTION DETECTED!", block); + return LFS_ERR_CORRUPT; // return error to abort lfs_traverse() gracefully + } + lfs_size_t *size = (lfs_size_t*) p; + *size += 1; + return 0; +} + +lfs_ssize_t _getLfsUsedBlockCount(FILESYSTEM* fs) { + lfs_size_t size = 0; + int err = lfs_traverse(fs->_getFS(), _countLfsBlock, &size); + if (err) { + MESH_DEBUG_PRINTLN("ERROR: lfs_traverse() error: %d", err); + return 0; + } + return size; +} +#endif + +uint32_t DataStore::getStorageUsedKb() const { +#if defined(ESP32) + return SPIFFS.usedBytes() / 1024; +#elif defined(RP2040_PLATFORM) + FSInfo info; + info.usedBytes = 0; + _fs->info(info); + return info.usedBytes / 1024; +#elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + const lfs_config* config = _getContactsChannelsFS()->_getFS()->cfg; + int usedBlockCount = _getLfsUsedBlockCount(_getContactsChannelsFS()); + int usedBytes = config->block_size * usedBlockCount; + return usedBytes / 1024; +#else + return 0; +#endif +} + +uint32_t DataStore::getStorageTotalKb() const { +#if defined(ESP32) + return SPIFFS.totalBytes() / 1024; +#elif defined(RP2040_PLATFORM) + FSInfo info; + info.totalBytes = 0; + _fs->info(info); + return info.totalBytes / 1024; +#elif defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + const lfs_config* config = _getContactsChannelsFS()->_getFS()->cfg; + int totalBytes = config->block_size * config->block_count; + return totalBytes / 1024; +#else + return 0; +#endif +} + +File DataStore::openRead(const char* filename) { +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + return _fs->open(filename, FILE_O_READ); +#elif defined(RP2040_PLATFORM) + return _fs->open(filename, "r"); +#else + return _fs->open(filename, "r", false); +#endif +} + +File DataStore::openRead(FILESYSTEM* fs, const char* filename) { +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + return fs->open(filename, FILE_O_READ); +#elif defined(RP2040_PLATFORM) + return fs->open(filename, "r"); +#else + return fs->open(filename, "r", false); +#endif +} + +bool DataStore::removeFile(const char* filename) { + return _fs->remove(filename); +} + +bool DataStore::removeFile(FILESYSTEM* fs, const char* filename) { + return fs->remove(filename); +} + +bool DataStore::formatFileSystem() { +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + if (_fsExtra == nullptr) { + return _fs->format(); + } else { + return _fs->format() && _fsExtra->format(); + } +#elif defined(RP2040_PLATFORM) + return LittleFS.format(); +#elif defined(ESP32) + bool fs_success = ((fs::SPIFFSFS *)_fs)->format(); + esp_err_t nvs_err = nvs_flash_erase(); // no need to reinit, will be done by reboot + return fs_success && (nvs_err == ESP_OK); +#else + #error "need to implement format()" +#endif +} + +bool DataStore::loadMainIdentity(mesh::LocalIdentity &identity) { + return identity_store.load("_main", identity); +} + +bool DataStore::saveMainIdentity(const mesh::LocalIdentity &identity) { + return identity_store.save("_main", identity); +} + +void DataStore::loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon) { + if (_fs->exists("/new_prefs")) { + loadPrefsInt("/new_prefs", prefs, node_lat, node_lon); // new filename + } else if (_fs->exists("/node_prefs")) { + loadPrefsInt("/node_prefs", prefs, node_lat, node_lon); + savePrefs(prefs, node_lat, node_lon); // save to new filename + _fs->remove("/node_prefs"); // remove old + } +} + +void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& node_lat, double& node_lon) { + File file = openRead(_fs, filename); + 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.close(); + } +} + +void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_lon) { + File file = openWrite(_fs, "/new_prefs"); + if (file) { + uint8_t pad[8]; + memset(pad, 0, sizeof(pad)); + + file.write((uint8_t *)&_prefs.airtime_factor, sizeof(float)); // 0 + file.write((uint8_t *)_prefs.node_name, sizeof(_prefs.node_name)); // 4 + file.write(pad, 4); // 36 + file.write((uint8_t *)&node_lat, sizeof(node_lat)); // 40 + file.write((uint8_t *)&node_lon, sizeof(node_lon)); // 48 + file.write((uint8_t *)&_prefs.freq, sizeof(_prefs.freq)); // 56 + file.write((uint8_t *)&_prefs.sf, sizeof(_prefs.sf)); // 60 + file.write((uint8_t *)&_prefs.cr, sizeof(_prefs.cr)); // 61 + file.write((uint8_t *)&_prefs.client_repeat, sizeof(_prefs.client_repeat)); // 62 + file.write((uint8_t *)&_prefs.manual_add_contacts, sizeof(_prefs.manual_add_contacts)); // 63 + file.write((uint8_t *)&_prefs.bw, sizeof(_prefs.bw)); // 64 + file.write((uint8_t *)&_prefs.tx_power_dbm, sizeof(_prefs.tx_power_dbm)); // 68 + file.write((uint8_t *)&_prefs.telemetry_mode_base, sizeof(_prefs.telemetry_mode_base)); // 69 + file.write((uint8_t *)&_prefs.telemetry_mode_loc, sizeof(_prefs.telemetry_mode_loc)); // 70 + file.write((uint8_t *)&_prefs.telemetry_mode_env, sizeof(_prefs.telemetry_mode_env)); // 71 + file.write((uint8_t *)&_prefs.rx_delay_base, sizeof(_prefs.rx_delay_base)); // 72 + file.write((uint8_t *)&_prefs.advert_loc_policy, sizeof(_prefs.advert_loc_policy)); // 76 + file.write((uint8_t *)&_prefs.multi_acks, sizeof(_prefs.multi_acks)); // 77 + file.write((uint8_t *)&_prefs.path_hash_mode, sizeof(_prefs.path_hash_mode)); // 78 + file.write(pad, 1); // 79 + file.write((uint8_t *)&_prefs.ble_pin, sizeof(_prefs.ble_pin)); // 80 + file.write((uint8_t *)&_prefs.buzzer_quiet, sizeof(_prefs.buzzer_quiet)); // 84 + file.write((uint8_t *)&_prefs.gps_enabled, sizeof(_prefs.gps_enabled)); // 85 + file.write((uint8_t *)&_prefs.gps_interval, sizeof(_prefs.gps_interval)); // 86 + file.write((uint8_t *)&_prefs.autoadd_config, sizeof(_prefs.autoadd_config)); // 87 + file.write((uint8_t *)&_prefs.autoadd_max_hops, sizeof(_prefs.autoadd_max_hops)); // 88 + file.write((uint8_t *)&_prefs.rx_boosted_gain, sizeof(_prefs.rx_boosted_gain)); // 89 + file.write((uint8_t *)_prefs.default_scope_name, sizeof(_prefs.default_scope_name)); // 90 + file.write((uint8_t *)_prefs.default_scope_key, sizeof(_prefs.default_scope_key)); // 121 + + file.close(); + } +} + +void DataStore::loadContacts(DataStoreHost* host) { +File file = openRead(_getContactsChannelsFS(), "/contacts3"); + if (file) { + bool full = false; + while (!full) { + ContactInfo c; + uint8_t pub_key[32]; + uint8_t unused; + + bool success = (file.read(pub_key, 32) == 32); + success = success && (file.read((uint8_t *)&c.name, 32) == 32); + success = success && (file.read(&c.type, 1) == 1); + success = success && (file.read(&c.flags, 1) == 1); + success = success && (file.read(&unused, 1) == 1); + success = success && (file.read((uint8_t *)&c.sync_since, 4) == 4); // was 'reserved' + success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1); + success = success && (file.read((uint8_t *)&c.last_advert_timestamp, 4) == 4); + success = success && (file.read(c.out_path, 64) == 64); + success = success && (file.read((uint8_t *)&c.lastmod, 4) == 4); + success = success && (file.read((uint8_t *)&c.gps_lat, 4) == 4); + success = success && (file.read((uint8_t *)&c.gps_lon, 4) == 4); + + if (!success) break; // EOF + + c.id = mesh::Identity(pub_key); + if (!host->onContactLoaded(c)) full = true; + } + file.close(); + } +} + +void DataStore::saveContacts(DataStoreHost* host) { + File file = openWrite(_getContactsChannelsFS(), "/contacts3"); + if (file) { + uint32_t idx = 0; + ContactInfo c; + uint8_t unused = 0; + + while (host->getContactForSave(idx, c)) { + bool success = (file.write(c.id.pub_key, 32) == 32); + success = success && (file.write((uint8_t *)&c.name, 32) == 32); + success = success && (file.write(&c.type, 1) == 1); + success = success && (file.write(&c.flags, 1) == 1); + success = success && (file.write(&unused, 1) == 1); + success = success && (file.write((uint8_t *)&c.sync_since, 4) == 4); + success = success && (file.write((uint8_t *)&c.out_path_len, 1) == 1); + success = success && (file.write((uint8_t *)&c.last_advert_timestamp, 4) == 4); + success = success && (file.write(c.out_path, 64) == 64); + success = success && (file.write((uint8_t *)&c.lastmod, 4) == 4); + success = success && (file.write((uint8_t *)&c.gps_lat, 4) == 4); + success = success && (file.write((uint8_t *)&c.gps_lon, 4) == 4); + + if (!success) break; // write failed + + idx++; // advance to next contact + } + file.close(); + } +} + +void DataStore::loadChannels(DataStoreHost* host) { + File file = openRead(_getContactsChannelsFS(), "/channels2"); + if (file) { + bool full = false; + uint8_t channel_idx = 0; + while (!full) { + ChannelDetails ch; + uint8_t unused[4]; + + bool success = (file.read(unused, 4) == 4); + success = success && (file.read((uint8_t *)ch.name, 32) == 32); + success = success && (file.read((uint8_t *)ch.channel.secret, 32) == 32); + + if (!success) break; // EOF + + if (host->onChannelLoaded(channel_idx, ch)) { + channel_idx++; + } else { + full = true; + } + } + file.close(); + } +} + +void DataStore::saveChannels(DataStoreHost* host) { + File file = openWrite(_getContactsChannelsFS(), "/channels2"); + if (file) { + uint8_t channel_idx = 0; + ChannelDetails ch; + uint8_t unused[4]; + memset(unused, 0, 4); + + while (host->getChannelForSave(channel_idx, ch)) { + bool success = (file.write(unused, 4) == 4); + success = success && (file.write((uint8_t *)ch.name, 32) == 32); + success = success && (file.write((uint8_t *)ch.channel.secret, 32) == 32); + + if (!success) break; // write failed + channel_idx++; + } + file.close(); + } +} + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + +#define MAX_ADVERT_PKT_LEN (2 + 32 + PUB_KEY_SIZE + 4 + SIGNATURE_SIZE + MAX_ADVERT_DATA_SIZE) + +struct BlobRec { + uint32_t timestamp; + uint8_t key[7]; + uint8_t len; + uint8_t data[MAX_ADVERT_PKT_LEN]; +}; + +void DataStore::checkAdvBlobFile() { + if (!_getContactsChannelsFS()->exists("/adv_blobs")) { + File file = openWrite(_getContactsChannelsFS(), "/adv_blobs"); + if (file) { + BlobRec zeroes; + memset(&zeroes, 0, sizeof(zeroes)); + for (int i = 0; i < MAX_BLOBRECS; i++) { // pre-allocate to fixed size + file.write((uint8_t *) &zeroes, sizeof(zeroes)); + } + file.close(); + } + } +} + +void DataStore::migrateToSecondaryFS() { + // migrate old adv_blobs, contacts3 and channels2 files to secondary FS if they don't already exist + if (!_fsExtra->exists("/adv_blobs")) { + if (_fs->exists("/adv_blobs")) { + File oldAdvBlobs = openRead(_fs, "/adv_blobs"); + File newAdvBlobs = openWrite(_fsExtra, "/adv_blobs"); + + if (oldAdvBlobs && newAdvBlobs) { + BlobRec rec; + size_t count = 0; + + // Copy 20 BlobRecs from old to new + while (count < 20 && oldAdvBlobs.read((uint8_t *)&rec, sizeof(rec)) == sizeof(rec)) { + newAdvBlobs.seek(count * sizeof(BlobRec)); + newAdvBlobs.write((uint8_t *)&rec, sizeof(rec)); + count++; + } + } + if (oldAdvBlobs) oldAdvBlobs.close(); + if (newAdvBlobs) newAdvBlobs.close(); + _fs->remove("/adv_blobs"); + } + } + if (!_fsExtra->exists("/contacts3")) { + if (_fs->exists("/contacts3")) { + File oldFile = openRead(_fs, "/contacts3"); + File newFile = openWrite(_fsExtra, "/contacts3"); + + if (oldFile && newFile) { + uint8_t buf[64]; + int n; + while ((n = oldFile.read(buf, sizeof(buf))) > 0) { + newFile.write(buf, n); + } + } + if (oldFile) oldFile.close(); + if (newFile) newFile.close(); + _fs->remove("/contacts3"); + } + } + if (!_fsExtra->exists("/channels2")) { + if (_fs->exists("/channels2")) { + File oldFile = openRead(_fs, "/channels2"); + File newFile = openWrite(_fsExtra, "/channels2"); + + if (oldFile && newFile) { + uint8_t buf[64]; + int n; + while ((n = oldFile.read(buf, sizeof(buf))) > 0) { + newFile.write(buf, n); + } + } + if (oldFile) oldFile.close(); + if (newFile) newFile.close(); + _fs->remove("/channels2"); + } + } + // cleanup nodes which have been testing the extra fs, copy _main.id and new_prefs back to primary + if (_fsExtra->exists("/_main.id")) { + if (_fs->exists("/_main.id")) {_fs->remove("/_main.id");} + File oldFile = openRead(_fsExtra, "/_main.id"); + File newFile = openWrite(_fs, "/_main.id"); + + if (oldFile && newFile) { + uint8_t buf[64]; + int n; + while ((n = oldFile.read(buf, sizeof(buf))) > 0) { + newFile.write(buf, n); + } + } + if (oldFile) oldFile.close(); + if (newFile) newFile.close(); + _fsExtra->remove("/_main.id"); + } + if (_fsExtra->exists("/new_prefs")) { + if (_fs->exists("/new_prefs")) {_fs->remove("/new_prefs");} + File oldFile = openRead(_fsExtra, "/new_prefs"); + File newFile = openWrite(_fs, "/new_prefs"); + + if (oldFile && newFile) { + uint8_t buf[64]; + int n; + while ((n = oldFile.read(buf, sizeof(buf))) > 0) { + newFile.write(buf, n); + } + } + if (oldFile) oldFile.close(); + if (newFile) newFile.close(); + _fsExtra->remove("/new_prefs"); + } + // remove files from where they should not be anymore + if (_fs->exists("/adv_blobs")) { + _fs->remove("/adv_blobs"); + } + if (_fs->exists("/contacts3")) { + _fs->remove("/contacts3"); + } + if (_fs->exists("/channels2")) { + _fs->remove("/channels2"); + } + if (_fsExtra->exists("/_main.id")) { + _fsExtra->remove("/_main.id"); + } + if (_fsExtra->exists("/new_prefs")) { + _fsExtra->remove("/new_prefs"); + } +} + +uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) { + File file = openRead(_getContactsChannelsFS(), "/adv_blobs"); + uint8_t len = 0; // 0 = not found + if (file) { + BlobRec tmp; + while (file.read((uint8_t *) &tmp, sizeof(tmp)) == sizeof(tmp)) { + if (memcmp(key, tmp.key, sizeof(tmp.key)) == 0) { // only match by 7 byte prefix + len = tmp.len; + memcpy(dest_buf, tmp.data, len); + break; + } + } + file.close(); + } + return len; +} + +bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len) { + if (len < PUB_KEY_SIZE+4+SIGNATURE_SIZE || len > MAX_ADVERT_PKT_LEN) return false; + checkAdvBlobFile(); + File file = _getContactsChannelsFS()->open("/adv_blobs", FILE_O_WRITE); + if (file) { + uint32_t pos = 0, found_pos = 0; + uint32_t min_timestamp = 0xFFFFFFFF; + + // search for matching key OR evict by oldest timestmap + BlobRec tmp; + file.seek(0); + while (file.read((uint8_t *) &tmp, sizeof(tmp)) == sizeof(tmp)) { + if (memcmp(key, tmp.key, sizeof(tmp.key)) == 0) { // only match by 7 byte prefix + found_pos = pos; + break; + } + if (tmp.timestamp < min_timestamp) { + min_timestamp = tmp.timestamp; + found_pos = pos; + } + + pos += sizeof(tmp); + } + + memcpy(tmp.key, key, sizeof(tmp.key)); // just record 7 byte prefix of key + memcpy(tmp.data, src_buf, len); + tmp.len = len; + tmp.timestamp = _clock->getCurrentTime(); + + file.seek(found_pos); + file.write((uint8_t *) &tmp, sizeof(tmp)); + + file.close(); + return true; + } + return false; // error +} +bool DataStore::deleteBlobByKey(const uint8_t key[], int key_len) { + return true; // this is just a stub on NRF52/STM32 platforms +} +#else +inline void makeBlobPath(const uint8_t key[], int key_len, char* path, size_t path_size) { + char fname[18]; + if (key_len > 8) key_len = 8; // just use first 8 bytes (prefix) + mesh::Utils::toHex(fname, key, key_len); + sprintf(path, "/bl/%s", fname); +} + +uint8_t DataStore::getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) { + char path[64]; + makeBlobPath(key, key_len, path, sizeof(path)); + + if (_fs->exists(path)) { + File f = openRead(_fs, path); + if (f) { + int len = f.read(dest_buf, 255); // currently MAX 255 byte blob len supported!! + f.close(); + return len; + } + } + return 0; // not found +} + +bool DataStore::putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len) { + char path[64]; + makeBlobPath(key, key_len, path, sizeof(path)); + + File f = openWrite(_fs, path); + if (f) { + int n = f.write(src_buf, len); + f.close(); + if (n == len) return true; // success! + + _fs->remove(path); // blob was only partially written! + } + return false; // error +} + +bool DataStore::deleteBlobByKey(const uint8_t key[], int key_len) { + char path[64]; + makeBlobPath(key, key_len, path, sizeof(path)); + + _fs->remove(path); + + return true; // return true even if file did not exist +} +#endif diff --git a/examples/beacon_sensor/DataStore.h b/examples/beacon_sensor/DataStore.h new file mode 100644 index 0000000..58b4d5d --- /dev/null +++ b/examples/beacon_sensor/DataStore.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +#include "NodePrefs.h" + +class DataStoreHost { +public: + virtual bool onContactLoaded(const ContactInfo& contact) =0; + virtual bool getContactForSave(uint32_t idx, ContactInfo& contact) =0; + virtual bool onChannelLoaded(uint8_t channel_idx, const ChannelDetails& ch) =0; + virtual bool getChannelForSave(uint8_t channel_idx, ChannelDetails& ch) =0; +}; + +class DataStore { + FILESYSTEM* _fs; + FILESYSTEM* _fsExtra; + mesh::RTCClock* _clock; + IdentityStore identity_store; + + void loadPrefsInt(const char *filename, NodePrefs& prefs, double& node_lat, double& node_lon); +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + void checkAdvBlobFile(); +#endif + +public: + DataStore(FILESYSTEM& fs, mesh::RTCClock& clock); + DataStore(FILESYSTEM& fs, FILESYSTEM& fsExtra, mesh::RTCClock& clock); + void begin(); + bool formatFileSystem(); + FILESYSTEM* getPrimaryFS() const { return _fs; } + FILESYSTEM* getSecondaryFS() const { return _fsExtra; } + bool loadMainIdentity(mesh::LocalIdentity &identity); + bool saveMainIdentity(const mesh::LocalIdentity &identity); + void loadPrefs(NodePrefs& prefs, double& node_lat, double& node_lon); + void savePrefs(const NodePrefs& prefs, double node_lat, double node_lon); + void loadContacts(DataStoreHost* host); + void saveContacts(DataStoreHost* host); + void loadChannels(DataStoreHost* host); + void saveChannels(DataStoreHost* host); + void migrateToSecondaryFS(); + uint8_t getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]); + bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], uint8_t len); + bool deleteBlobByKey(const uint8_t key[], int key_len); + File openRead(const char* filename); + File openRead(FILESYSTEM* fs, const char* filename); + bool removeFile(const char* filename); + bool removeFile(FILESYSTEM* fs, const char* filename); + uint32_t getStorageUsedKb() const; + uint32_t getStorageTotalKb() const; + +private: + FILESYSTEM* _getContactsChannelsFS() const { if (_fsExtra) return _fsExtra; return _fs;}; +}; diff --git a/examples/beacon_sensor/MyMesh.cpp b/examples/beacon_sensor/MyMesh.cpp new file mode 100644 index 0000000..9227dc4 --- /dev/null +++ b/examples/beacon_sensor/MyMesh.cpp @@ -0,0 +1,2218 @@ +#include "MyMesh.h" + +#include // needed for PlatformIO +#include + +#define CMD_APP_START 1 +#define CMD_SEND_TXT_MSG 2 +#define CMD_SEND_CHANNEL_TXT_MSG 3 +#define CMD_GET_CONTACTS 4 // with optional 'since' (for efficient sync) +#define CMD_GET_DEVICE_TIME 5 +#define CMD_SET_DEVICE_TIME 6 +#define CMD_SEND_SELF_ADVERT 7 +#define CMD_SET_ADVERT_NAME 8 +#define CMD_ADD_UPDATE_CONTACT 9 +#define CMD_SYNC_NEXT_MESSAGE 10 +#define CMD_SET_RADIO_PARAMS 11 +#define CMD_SET_RADIO_TX_POWER 12 +#define CMD_RESET_PATH 13 +#define CMD_SET_ADVERT_LATLON 14 +#define CMD_REMOVE_CONTACT 15 +#define CMD_SHARE_CONTACT 16 +#define CMD_EXPORT_CONTACT 17 +#define CMD_IMPORT_CONTACT 18 +#define CMD_REBOOT 19 +#define CMD_GET_BATT_AND_STORAGE 20 // was CMD_GET_BATTERY_VOLTAGE +#define CMD_SET_TUNING_PARAMS 21 +#define CMD_DEVICE_QEURY 22 +#define CMD_EXPORT_PRIVATE_KEY 23 +#define CMD_IMPORT_PRIVATE_KEY 24 +#define CMD_SEND_RAW_DATA 25 +#define CMD_SEND_LOGIN 26 +#define CMD_SEND_STATUS_REQ 27 +#define CMD_HAS_CONNECTION 28 +#define CMD_LOGOUT 29 // 'Disconnect' +#define CMD_GET_CONTACT_BY_KEY 30 +#define CMD_GET_CHANNEL 31 +#define CMD_SET_CHANNEL 32 +#define CMD_SIGN_START 33 +#define CMD_SIGN_DATA 34 +#define CMD_SIGN_FINISH 35 +#define CMD_SEND_TRACE_PATH 36 +#define CMD_SET_DEVICE_PIN 37 +#define CMD_SET_OTHER_PARAMS 38 +#define CMD_SEND_TELEMETRY_REQ 39 // can deprecate this +#define CMD_GET_CUSTOM_VARS 40 +#define CMD_SET_CUSTOM_VAR 41 +#define CMD_GET_ADVERT_PATH 42 +#define CMD_GET_TUNING_PARAMS 43 +// NOTE: CMD range 44..49 parked, potentially for WiFi operations +#define CMD_SEND_BINARY_REQ 50 +#define CMD_FACTORY_RESET 51 +#define CMD_SEND_PATH_DISCOVERY_REQ 52 +#define CMD_SET_FLOOD_SCOPE_KEY 54 // v8+ +#define CMD_SEND_CONTROL_DATA 55 // v8+ +#define CMD_GET_STATS 56 // v8+, second byte is stats type +#define CMD_SEND_ANON_REQ 57 +#define CMD_SET_AUTOADD_CONFIG 58 +#define CMD_GET_AUTOADD_CONFIG 59 +#define CMD_GET_ALLOWED_REPEAT_FREQ 60 +#define CMD_SET_PATH_HASH_MODE 61 +#define CMD_SEND_CHANNEL_DATA 62 +#define CMD_SET_DEFAULT_FLOOD_SCOPE 63 +#define CMD_GET_DEFAULT_FLOOD_SCOPE 64 + +// Stats sub-types for CMD_GET_STATS +#define STATS_TYPE_CORE 0 +#define STATS_TYPE_RADIO 1 +#define STATS_TYPE_PACKETS 2 + +#define RESP_CODE_OK 0 +#define RESP_CODE_ERR 1 +#define RESP_CODE_CONTACTS_START 2 // first reply to CMD_GET_CONTACTS +#define RESP_CODE_CONTACT 3 // multiple of these (after CMD_GET_CONTACTS) +#define RESP_CODE_END_OF_CONTACTS 4 // last reply to CMD_GET_CONTACTS +#define RESP_CODE_SELF_INFO 5 // reply to CMD_APP_START +#define RESP_CODE_SENT 6 // reply to CMD_SEND_TXT_MSG +#define RESP_CODE_CONTACT_MSG_RECV 7 // a reply to CMD_SYNC_NEXT_MESSAGE (ver < 3) +#define RESP_CODE_CHANNEL_MSG_RECV 8 // a reply to CMD_SYNC_NEXT_MESSAGE (ver < 3) +#define RESP_CODE_CURR_TIME 9 // a reply to CMD_GET_DEVICE_TIME +#define RESP_CODE_NO_MORE_MESSAGES 10 // a reply to CMD_SYNC_NEXT_MESSAGE +#define RESP_CODE_EXPORT_CONTACT 11 +#define RESP_CODE_BATT_AND_STORAGE 12 // a reply to a CMD_GET_BATT_AND_STORAGE +#define RESP_CODE_DEVICE_INFO 13 // a reply to CMD_DEVICE_QEURY +#define RESP_CODE_PRIVATE_KEY 14 // a reply to CMD_EXPORT_PRIVATE_KEY +#define RESP_CODE_DISABLED 15 +#define RESP_CODE_CONTACT_MSG_RECV_V3 16 // a reply to CMD_SYNC_NEXT_MESSAGE (ver >= 3) +#define RESP_CODE_CHANNEL_MSG_RECV_V3 17 // a reply to CMD_SYNC_NEXT_MESSAGE (ver >= 3) +#define RESP_CODE_CHANNEL_INFO 18 // a reply to CMD_GET_CHANNEL +#define RESP_CODE_SIGN_START 19 +#define RESP_CODE_SIGNATURE 20 +#define RESP_CODE_CUSTOM_VARS 21 +#define RESP_CODE_ADVERT_PATH 22 +#define RESP_CODE_TUNING_PARAMS 23 +#define RESP_CODE_STATS 24 // v8+, second byte is stats type +#define RESP_CODE_AUTOADD_CONFIG 25 +#define RESP_ALLOWED_REPEAT_FREQ 26 +#define RESP_CODE_CHANNEL_DATA_RECV 27 +#define RESP_CODE_DEFAULT_FLOOD_SCOPE 28 + +#define MAX_CHANNEL_DATA_LENGTH (MAX_FRAME_SIZE - 9) + +#define SEND_TIMEOUT_BASE_MILLIS 500 +#define FLOOD_SEND_TIMEOUT_FACTOR 16.0f +#define DIRECT_SEND_PERHOP_FACTOR 6.0f +#define DIRECT_SEND_PERHOP_EXTRA_MILLIS 250 +#define LAZY_CONTACTS_WRITE_DELAY 5000 + +#define PUBLIC_GROUP_PSK "izOH6cXN6mrJ5e26oRXNcg==" + +// these are _pushed_ to client app at any time +#define PUSH_CODE_ADVERT 0x80 +#define PUSH_CODE_PATH_UPDATED 0x81 +#define PUSH_CODE_SEND_CONFIRMED 0x82 +#define PUSH_CODE_MSG_WAITING 0x83 +#define PUSH_CODE_RAW_DATA 0x84 +#define PUSH_CODE_LOGIN_SUCCESS 0x85 +#define PUSH_CODE_LOGIN_FAIL 0x86 +#define PUSH_CODE_STATUS_RESPONSE 0x87 +#define PUSH_CODE_LOG_RX_DATA 0x88 +#define PUSH_CODE_TRACE_DATA 0x89 +#define PUSH_CODE_NEW_ADVERT 0x8A +#define PUSH_CODE_TELEMETRY_RESPONSE 0x8B +#define PUSH_CODE_BINARY_RESPONSE 0x8C +#define PUSH_CODE_PATH_DISCOVERY_RESPONSE 0x8D +#define PUSH_CODE_CONTROL_DATA 0x8E // v8+ +#define PUSH_CODE_CONTACT_DELETED 0x8F // used to notify client app of deleted contact when overwriting oldest +#define PUSH_CODE_CONTACTS_FULL 0x90 // used to notify client app that contacts storage is full + +#define ERR_CODE_UNSUPPORTED_CMD 1 +#define ERR_CODE_NOT_FOUND 2 +#define ERR_CODE_TABLE_FULL 3 +#define ERR_CODE_BAD_STATE 4 +#define ERR_CODE_FILE_IO_ERROR 5 +#define ERR_CODE_ILLEGAL_ARG 6 + +#define MAX_SIGN_DATA_LEN (8 * 1024) // 8K + +// Auto-add config bitmask +// Bit 0: If set, overwrite oldest non-favourite contact when contacts file is full +// Bits 1-4: these indicate which contact types to auto-add when manual_contact_mode = 0x01 +#define AUTO_ADD_OVERWRITE_OLDEST (1 << 0) // 0x01 - overwrite oldest non-favourite when full +#define AUTO_ADD_CHAT (1 << 1) // 0x02 - auto-add Chat (Companion) (ADV_TYPE_CHAT) +#define AUTO_ADD_REPEATER (1 << 2) // 0x04 - auto-add Repeater (ADV_TYPE_REPEATER) +#define AUTO_ADD_ROOM_SERVER (1 << 3) // 0x08 - auto-add Room Server (ADV_TYPE_ROOM) +#define AUTO_ADD_SENSOR (1 << 4) // 0x10 - auto-add Sensor (ADV_TYPE_SENSOR) + +void MyMesh::writeOKFrame() { + uint8_t buf[1]; + buf[0] = RESP_CODE_OK; + _serial->writeFrame(buf, 1); +} +void MyMesh::writeErrFrame(uint8_t err_code) { + uint8_t buf[2]; + buf[0] = RESP_CODE_ERR; + buf[1] = err_code; + _serial->writeFrame(buf, 2); +} + +void MyMesh::writeDisabledFrame() { + uint8_t buf[1]; + buf[0] = RESP_CODE_DISABLED; + _serial->writeFrame(buf, 1); +} + +void MyMesh::writeContactRespFrame(uint8_t code, const ContactInfo &contact) { + int i = 0; + out_frame[i++] = code; + memcpy(&out_frame[i], contact.id.pub_key, PUB_KEY_SIZE); + i += PUB_KEY_SIZE; + out_frame[i++] = contact.type; + out_frame[i++] = contact.flags; + out_frame[i++] = contact.out_path_len; + memcpy(&out_frame[i], contact.out_path, MAX_PATH_SIZE); + i += MAX_PATH_SIZE; + StrHelper::strzcpy((char *)&out_frame[i], contact.name, 32); + i += 32; + memcpy(&out_frame[i], &contact.last_advert_timestamp, 4); + i += 4; + memcpy(&out_frame[i], &contact.gps_lat, 4); + i += 4; + memcpy(&out_frame[i], &contact.gps_lon, 4); + i += 4; + memcpy(&out_frame[i], &contact.lastmod, 4); + i += 4; + _serial->writeFrame(out_frame, i); +} + +void MyMesh::updateContactFromFrame(ContactInfo &contact, uint32_t& last_mod, const uint8_t *frame, int len) { + int i = 0; + uint8_t code = frame[i++]; // eg. CMD_ADD_UPDATE_CONTACT + memcpy(contact.id.pub_key, &frame[i], PUB_KEY_SIZE); + i += PUB_KEY_SIZE; + contact.type = frame[i++]; + contact.flags = frame[i++]; + contact.out_path_len = frame[i++]; + memcpy(contact.out_path, &frame[i], MAX_PATH_SIZE); + i += MAX_PATH_SIZE; + memcpy(contact.name, &frame[i], 32); + i += 32; + memcpy(&contact.last_advert_timestamp, &frame[i], 4); + i += 4; + if (len >= i + 8) { // optional fields + memcpy(&contact.gps_lat, &frame[i], 4); + i += 4; + memcpy(&contact.gps_lon, &frame[i], 4); + i += 4; + if (len >= i + 4) { + memcpy(&last_mod, &frame[i], 4); + } + } +} + +bool MyMesh::Frame::isChannelMsg() const { + return buf[0] == RESP_CODE_CHANNEL_MSG_RECV || buf[0] == RESP_CODE_CHANNEL_MSG_RECV_V3 || + buf[0] == RESP_CODE_CHANNEL_DATA_RECV; +} + +void MyMesh::addToOfflineQueue(const uint8_t frame[], int len) { + if (offline_queue_len >= OFFLINE_QUEUE_SIZE) { + MESH_DEBUG_PRINTLN("WARN: offline_queue is full!"); + int pos = 0; + while (pos < offline_queue_len) { + if (offline_queue[pos].isChannelMsg()) { + for (int i = pos; i < offline_queue_len - 1; i++) { // delete oldest channel msg from queue + offline_queue[i] = offline_queue[i + 1]; + } + MESH_DEBUG_PRINTLN("INFO: removed oldest channel message from queue."); + offline_queue[offline_queue_len - 1].len = len; + memcpy(offline_queue[offline_queue_len - 1].buf, frame, len); + return; + } + pos++; + } + MESH_DEBUG_PRINTLN("INFO: no channel messages to remove from queue."); + } else { + offline_queue[offline_queue_len].len = len; + memcpy(offline_queue[offline_queue_len].buf, frame, len); + offline_queue_len++; + } +} + +int MyMesh::getFromOfflineQueue(uint8_t frame[]) { + if (offline_queue_len > 0) { // check offline queue + size_t len = offline_queue[0].len; // take from top of queue + memcpy(frame, offline_queue[0].buf, len); + + offline_queue_len--; + for (int i = 0; i < offline_queue_len; i++) { // delete top item from queue + offline_queue[i] = offline_queue[i + 1]; + } + return len; + } + return 0; // queue is empty +} + +float MyMesh::getAirtimeBudgetFactor() const { + return _prefs.airtime_factor; +} + +int MyMesh::getInterferenceThreshold() const { + return 0; // disabled for now, until currentRSSI() problem is resolved +} + +int MyMesh::calcRxDelay(float score, uint32_t air_time) const { + if (_prefs.rx_delay_base <= 0.0f) return 0; + return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time); +} + +uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) { + uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * 0.5f); + return getRNG()->nextInt(0, 5*t + 1); +} +uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) { + uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * 0.2f); + return getRNG()->nextInt(0, 5*t + 1); +} + +uint8_t MyMesh::getExtraAckTransmitCount() const { + return _prefs.multi_acks; +} + +void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) { + if (_serial->isConnected() && len + 3 <= MAX_FRAME_SIZE) { + int i = 0; + out_frame[i++] = PUSH_CODE_LOG_RX_DATA; + out_frame[i++] = (int8_t)(snr * 4); + out_frame[i++] = (int8_t)(rssi); + memcpy(&out_frame[i], raw, len); + i += len; + + _serial->writeFrame(out_frame, i); + } +} + +bool MyMesh::isAutoAddEnabled() const { + return (_prefs.manual_add_contacts & 1) == 0; +} + +bool MyMesh::shouldAutoAddContactType(uint8_t contact_type) const { + if ((_prefs.manual_add_contacts & 1) == 0) { + return true; + } + + uint8_t type_bit = 0; + switch (contact_type) { + case ADV_TYPE_CHAT: + type_bit = AUTO_ADD_CHAT; + break; + case ADV_TYPE_REPEATER: + type_bit = AUTO_ADD_REPEATER; + break; + case ADV_TYPE_ROOM: + type_bit = AUTO_ADD_ROOM_SERVER; + break; + case ADV_TYPE_SENSOR: + type_bit = AUTO_ADD_SENSOR; + break; + default: + return false; // Unknown type, don't auto-add + } + + return (_prefs.autoadd_config & type_bit) != 0; +} + +bool MyMesh::shouldOverwriteWhenFull() const { + return (_prefs.autoadd_config & AUTO_ADD_OVERWRITE_OLDEST) != 0; +} + +uint8_t MyMesh::getAutoAddMaxHops() const { + return _prefs.autoadd_max_hops; +} + +void MyMesh::onContactOverwrite(const uint8_t* pub_key) { + _store->deleteBlobByKey(pub_key, PUB_KEY_SIZE); // delete from storage + if (_serial->isConnected()) { + out_frame[0] = PUSH_CODE_CONTACT_DELETED; + memcpy(&out_frame[1], pub_key, PUB_KEY_SIZE); + _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); + } +} + +void MyMesh::onContactsFull() { + if (_serial->isConnected()) { + out_frame[0] = PUSH_CODE_CONTACTS_FULL; + _serial->writeFrame(out_frame, 1); + } +} + +void MyMesh::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { + if (_serial->isConnected()) { + if (is_new) { + writeContactRespFrame(PUSH_CODE_NEW_ADVERT, contact); + } else { + out_frame[0] = PUSH_CODE_ADVERT; + memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE); + _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); + } + } else { +#ifdef DISPLAY_CLASS + if (_ui) _ui->notify(UIEventType::newContactMessage); +#endif + } + + // add inbound-path to mem cache + if (path && mesh::Packet::isValidPathLen(path_len)) { // check path is valid + AdvertPath* p = advert_paths; + uint32_t oldest = 0xFFFFFFFF; + for (int i = 0; i < ADVERT_PATH_TABLE_SIZE; i++) { // check if already in table, otherwise evict oldest + if (memcmp(advert_paths[i].pubkey_prefix, contact.id.pub_key, sizeof(AdvertPath::pubkey_prefix)) == 0) { + p = &advert_paths[i]; // found + break; + } + if (advert_paths[i].recv_timestamp < oldest) { + oldest = advert_paths[i].recv_timestamp; + p = &advert_paths[i]; + } + } + + memcpy(p->pubkey_prefix, contact.id.pub_key, sizeof(p->pubkey_prefix)); + strcpy(p->name, contact.name); + p->recv_timestamp = getRTCClock()->getCurrentTime(); + p->path_len = mesh::Packet::copyPath(p->path, path, path_len); + } + + if (!is_new) dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // only schedule lazy write for contacts that are in contacts[] +} + +static int sort_by_recent(const void *a, const void *b) { + return ((AdvertPath *) b)->recv_timestamp - ((AdvertPath *) a)->recv_timestamp; +} + +int MyMesh::getRecentlyHeard(AdvertPath dest[], int max_num) { + if (max_num > ADVERT_PATH_TABLE_SIZE) max_num = ADVERT_PATH_TABLE_SIZE; + qsort(advert_paths, ADVERT_PATH_TABLE_SIZE, sizeof(advert_paths[0]), sort_by_recent); + + for (int i = 0; i < max_num; i++) { + dest[i] = advert_paths[i]; + } + return max_num; +} + +void MyMesh::onContactPathUpdated(const ContactInfo &contact) { + out_frame[0] = PUSH_CODE_PATH_UPDATED; + memcpy(&out_frame[1], contact.id.pub_key, PUB_KEY_SIZE); + _serial->writeFrame(out_frame, 1 + PUB_KEY_SIZE); // NOTE: app may not be connected + + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); +} + +ContactInfo* MyMesh::processAck(const uint8_t *data) { + // see if matches any in a table + for (int i = 0; i < EXPECTED_ACK_TABLE_SIZE; i++) { + if (memcmp(data, &expected_ack_table[i].ack, 4) == 0) { // got an ACK from recipient + out_frame[0] = PUSH_CODE_SEND_CONFIRMED; + memcpy(&out_frame[1], data, 4); + uint32_t trip_time = _ms->getMillis() - expected_ack_table[i].msg_sent; + memcpy(&out_frame[5], &trip_time, 4); + _serial->writeFrame(out_frame, 9); + + // NOTE: the same ACK can be received multiple times! + expected_ack_table[i].ack = 0; // clear expected hash, now that we have received ACK + return expected_ack_table[i].contact; + } + } + return checkConnectionsAck(data); +} + +void MyMesh::queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packet *pkt, + uint32_t sender_timestamp, const uint8_t *extra, int extra_len, const char *text) { + int i = 0; + if (app_target_ver >= 3) { + out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV_V3; + out_frame[i++] = (int8_t)(pkt->getSNR() * 4); + out_frame[i++] = 0; // reserved1 + out_frame[i++] = 0; // reserved2 + } else { + out_frame[i++] = RESP_CODE_CONTACT_MSG_RECV; + } + memcpy(&out_frame[i], from.id.pub_key, 6); + i += 6; // just 6-byte prefix + uint8_t path_len = out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; + out_frame[i++] = txt_type; + memcpy(&out_frame[i], &sender_timestamp, 4); + i += 4; + if (extra_len > 0) { + memcpy(&out_frame[i], extra, extra_len); + i += extra_len; + } + int tlen = strlen(text); // TODO: UTF-8 ?? + if (i + tlen > MAX_FRAME_SIZE) { + tlen = MAX_FRAME_SIZE - i; + } + memcpy(&out_frame[i], text, tlen); + i += tlen; + addToOfflineQueue(out_frame, i); + + if (_serial->isConnected()) { + uint8_t frame[1]; + frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle' + _serial->writeFrame(frame, 1); + } + +#ifdef DISPLAY_CLASS + // 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); + } + } +#endif +} + +bool MyMesh::filterRecvFloodPacket(mesh::Packet* packet) { + // REVISIT: try to determine which Region (from transport_codes[1]) that Sender is indicating for replies/responses + // if unknown, fallback to finding Region from transport_codes[0], the 'scope' used by Sender + return false; +} + +bool MyMesh::allowPacketForward(const mesh::Packet* packet) { + return _prefs.client_repeat != 0; +} + +void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis) { + if (scope.isNull()) { + sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + } else { + uint16_t codes[2]; + codes[0] = scope.calcTransportCode(pkt); + codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region? + sendFlood(pkt, codes, delay_millis, _prefs.path_hash_mode + 1); + } +} + +void MyMesh::sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis) { + // TODO: dynamic send_scope, depending on recipient and current 'home' Region + TransportKey default_scope; + memcpy(&default_scope.key, _prefs.default_scope_key, sizeof(default_scope.key)); + + auto scope = send_scope.isNull() ? &default_scope : &send_scope; + sendFloodScoped(*scope, pkt, delay_millis); +} +void MyMesh::sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis) { + // TODO: have per-channel send_scope + TransportKey default_scope; + memcpy(&default_scope.key, _prefs.default_scope_key, sizeof(default_scope.key)); + + auto scope = send_scope.isNull() ? &default_scope : &send_scope; + 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); +} + +void MyMesh::onCommandDataRecv(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_CLI_DATA, pkt, sender_timestamp, NULL, 0, text); +} + +void MyMesh::onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, + const uint8_t *sender_prefix, const char *text) { + markConnectionActive(from); + // from.sync_since change needs to be persisted + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + queueMessage(from, TXT_TYPE_SIGNED_PLAIN, pkt, sender_timestamp, sender_prefix, 4, text); +} + +void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, + const char *text) { + int i = 0; + if (app_target_ver >= 3) { + out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV_V3; + out_frame[i++] = (int8_t)(pkt->getSNR() * 4); + out_frame[i++] = 0; // reserved1 + out_frame[i++] = 0; // reserved2 + } else { + out_frame[i++] = RESP_CODE_CHANNEL_MSG_RECV; + } + + uint8_t channel_idx = findChannelIdx(channel); + out_frame[i++] = channel_idx; + uint8_t path_len = out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; + + out_frame[i++] = TXT_TYPE_PLAIN; + memcpy(&out_frame[i], ×tamp, 4); + i += 4; + int tlen = strlen(text); // TODO: UTF-8 ?? + if (i + tlen > MAX_FRAME_SIZE) { + tlen = MAX_FRAME_SIZE - i; + } + memcpy(&out_frame[i], text, tlen); + i += tlen; + addToOfflineQueue(out_frame, i); + + if (_serial->isConnected()) { + 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 + 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); +#endif +} + +void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, + const uint8_t *data, size_t data_len) { + if (data_len > MAX_CHANNEL_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("onChannelDataRecv: dropping payload_len=%d exceeds frame limit=%d", + (uint32_t)data_len, (uint32_t)MAX_CHANNEL_DATA_LENGTH); + return; + } + + int i = 0; + out_frame[i++] = RESP_CODE_CHANNEL_DATA_RECV; + out_frame[i++] = (int8_t)(pkt->getSNR() * 4); + out_frame[i++] = 0; // reserved1 + out_frame[i++] = 0; // reserved2 + + uint8_t channel_idx = findChannelIdx(channel); + out_frame[i++] = channel_idx; + out_frame[i++] = pkt->isRouteFlood() ? pkt->path_len : 0xFF; + out_frame[i++] = (uint8_t)(data_type & 0xFF); + out_frame[i++] = (uint8_t)(data_type >> 8); + out_frame[i++] = (uint8_t)data_len; + + int copy_len = (int)data_len; + if (copy_len > 0) { + memcpy(&out_frame[i], data, copy_len); + i += copy_len; + } + addToOfflineQueue(out_frame, i); + + if (_serial->isConnected()) { + uint8_t frame[1]; + frame[0] = PUSH_CODE_MSG_WAITING; // send push 'tickle' + _serial->writeFrame(frame, 1); + } +} + +uint8_t MyMesh::onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, + uint8_t len, uint8_t *reply) { + if (data[0] == REQ_TYPE_GET_TELEMETRY_DATA) { + uint8_t permissions = 0; + uint8_t cp = contact.flags >> 1; // LSB used as 'favourite' bit (so only use upper bits) + + if (_prefs.telemetry_mode_base == TELEM_MODE_ALLOW_ALL) { + permissions = TELEM_PERM_BASE; + } else if (_prefs.telemetry_mode_base == TELEM_MODE_ALLOW_FLAGS) { + permissions = cp & TELEM_PERM_BASE; + } + + if (_prefs.telemetry_mode_loc == TELEM_MODE_ALLOW_ALL) { + permissions |= TELEM_PERM_LOCATION; + } else if (_prefs.telemetry_mode_loc == TELEM_MODE_ALLOW_FLAGS) { + permissions |= cp & TELEM_PERM_LOCATION; + } + + if (_prefs.telemetry_mode_env == TELEM_MODE_ALLOW_ALL) { + permissions |= TELEM_PERM_ENVIRONMENT; + } else if (_prefs.telemetry_mode_env == TELEM_MODE_ALLOW_FLAGS) { + permissions |= cp & TELEM_PERM_ENVIRONMENT; + } + + uint8_t perm_mask = ~(data[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions + permissions &= perm_mask; + + if (permissions & TELEM_PERM_BASE) { // only respond if base permission bit is set + telemetry.reset(); + telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + // query other sensors -- target specific + sensors.querySensors(permissions, telemetry); + + memcpy(reply, &sender_timestamp, + 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') + + uint8_t tlen = telemetry.getSize(); + memcpy(&reply[4], telemetry.getBuffer(), tlen); + return 4 + tlen; + } + } + return 0; // unknown +} + +void MyMesh::onContactResponse(const ContactInfo &contact, const uint8_t *data, uint8_t len) { + uint32_t tag; + memcpy(&tag, data, 4); + + if (pending_login && memcmp(&pending_login, contact.id.pub_key, 4) == 0) { // check for login response + // yes, is response to pending sendLogin() + pending_login = 0; + + int i = 0; + if (memcmp(&data[4], "OK", 2) == 0) { // legacy Repeater login OK response + out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS; + out_frame[i++] = 0; // legacy: is_admin = false + memcpy(&out_frame[i], contact.id.pub_key, 6); + i += 6; // pub_key_prefix + } else if (data[4] == RESP_SERVER_LOGIN_OK) { // new login response + uint16_t keep_alive_secs = ((uint16_t)data[5]) * 16; + if (keep_alive_secs > 0) { + startConnection(contact, keep_alive_secs); + } + out_frame[i++] = PUSH_CODE_LOGIN_SUCCESS; + out_frame[i++] = data[6]; // permissions (eg. is_admin) + memcpy(&out_frame[i], contact.id.pub_key, 6); + i += 6; // pub_key_prefix + memcpy(&out_frame[i], &tag, 4); + i += 4; // NEW: include server timestamp + out_frame[i++] = data[7]; // NEW (v7): ACL permissions + out_frame[i++] = data[12]; // FIRMWARE_VER_LEVEL + } else { + out_frame[i++] = PUSH_CODE_LOGIN_FAIL; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], contact.id.pub_key, 6); + i += 6; // pub_key_prefix + } + _serial->writeFrame(out_frame, i); + } else if (len > 4 && // check for status response + pending_status && + memcmp(&pending_status, contact.id.pub_key, 4) == 0 // legacy matching scheme + // FUTURE: tag == pending_status + ) { + pending_status = 0; + + int i = 0; + out_frame[i++] = PUSH_CODE_STATUS_RESPONSE; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], contact.id.pub_key, 6); + i += 6; // pub_key_prefix + memcpy(&out_frame[i], &data[4], len - 4); + i += (len - 4); + _serial->writeFrame(out_frame, i); + } else if (len > 4 && tag == pending_telemetry) { // check for matching response tag + pending_telemetry = 0; + + int i = 0; + out_frame[i++] = PUSH_CODE_TELEMETRY_RESPONSE; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], contact.id.pub_key, 6); + i += 6; // pub_key_prefix + memcpy(&out_frame[i], &data[4], len - 4); + i += (len - 4); + _serial->writeFrame(out_frame, i); + } else if (len > 4 && tag == pending_req) { // check for matching response tag + pending_req = 0; + + int i = 0; + out_frame[i++] = PUSH_CODE_BINARY_RESPONSE; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], &tag, 4); // app needs to match this to RESP_CODE_SENT.tag + i += 4; + memcpy(&out_frame[i], &data[4], len - 4); + i += (len - 4); + _serial->writeFrame(out_frame, i); + } +} + +bool MyMesh::onContactPathRecv(ContactInfo& contact, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) { + if (extra_type == PAYLOAD_TYPE_RESPONSE && extra_len > 4) { + uint32_t tag; + memcpy(&tag, extra, 4); + + if (tag == pending_discovery) { // check for matching response tag) + pending_discovery = 0; + + if (!mesh::Packet::isValidPathLen(in_path_len) || !mesh::Packet::isValidPathLen(out_path_len)) { + MESH_DEBUG_PRINTLN("onContactPathRecv, invalid path sizes: %d, %d", in_path_len, out_path_len); + } else { + int i = 0; + out_frame[i++] = PUSH_CODE_PATH_DISCOVERY_RESPONSE; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], contact.id.pub_key, 6); + i += 6; // pub_key_prefix + out_frame[i++] = out_path_len; + i += mesh::Packet::writePath(&out_frame[i], out_path, out_path_len); + out_frame[i++] = in_path_len; + i += mesh::Packet::writePath(&out_frame[i], in_path, in_path_len); + // NOTE: telemetry data in 'extra' is discarded at present + + _serial->writeFrame(out_frame, i); + } + return false; // DON'T send reciprocal path! + } + } + // let base class handle received path and data + return BaseChatMesh::onContactPathRecv(contact, in_path, in_path_len, out_path, out_path_len, extra_type, extra, extra_len); +} + +void MyMesh::onControlDataRecv(mesh::Packet *packet) { + if (packet->payload_len + 4 > sizeof(out_frame)) { + MESH_DEBUG_PRINTLN("onControlDataRecv(), payload_len too long: %d", packet->payload_len); + return; + } + int i = 0; + out_frame[i++] = PUSH_CODE_CONTROL_DATA; + out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4); + out_frame[i++] = (int8_t)(_radio->getLastRSSI()); + out_frame[i++] = packet->path_len; + memcpy(&out_frame[i], packet->payload, packet->payload_len); + i += packet->payload_len; + + if (_serial->isConnected()) { + _serial->writeFrame(out_frame, i); + } else { + MESH_DEBUG_PRINTLN("onControlDataRecv(), data received while app offline"); + } +} + +void MyMesh::onRawDataRecv(mesh::Packet *packet) { + if (packet->payload_len + 4 > sizeof(out_frame)) { + MESH_DEBUG_PRINTLN("onRawDataRecv(), payload_len too long: %d", packet->payload_len); + return; + } + int i = 0; + out_frame[i++] = PUSH_CODE_RAW_DATA; + out_frame[i++] = (int8_t)(_radio->getLastSNR() * 4); + out_frame[i++] = (int8_t)(_radio->getLastRSSI()); + out_frame[i++] = 0xFF; // reserved (possibly path_len in future) + memcpy(&out_frame[i], packet->payload, packet->payload_len); + i += packet->payload_len; + + if (_serial->isConnected()) { + _serial->writeFrame(out_frame, i); + } else { + MESH_DEBUG_PRINTLN("onRawDataRecv(), data received while app offline"); + } +} + +void MyMesh::onTraceRecv(mesh::Packet *packet, uint32_t tag, uint32_t auth_code, uint8_t flags, + const uint8_t *path_snrs, const uint8_t *path_hashes, uint8_t path_len) { + uint8_t path_sz = flags & 0x03; // NEW v1.11+ + if (12 + path_len + (path_len >> path_sz) + 1 > sizeof(out_frame)) { + MESH_DEBUG_PRINTLN("onTraceRecv(), path_len is too long: %d", (uint32_t)path_len); + return; + } + int i = 0; + out_frame[i++] = PUSH_CODE_TRACE_DATA; + out_frame[i++] = 0; // reserved + out_frame[i++] = path_len; + out_frame[i++] = flags; + memcpy(&out_frame[i], &tag, 4); + i += 4; + memcpy(&out_frame[i], &auth_code, 4); + i += 4; + memcpy(&out_frame[i], path_hashes, path_len); + i += path_len; + + memcpy(&out_frame[i], path_snrs, path_len >> path_sz); + i += path_len >> path_sz; + out_frame[i++] = (int8_t)(packet->getSNR() * 4); // extra/final SNR (to this node) + + if (_serial->isConnected()) { + _serial->writeFrame(out_frame, i); + } else { + MESH_DEBUG_PRINTLN("onTraceRecv(), data received while app offline"); + } +} + +uint32_t MyMesh::calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const { + return SEND_TIMEOUT_BASE_MILLIS + (FLOOD_SEND_TIMEOUT_FACTOR * pkt_airtime_millis); +} +uint32_t MyMesh::calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const { + uint8_t path_hash_count = path_len & 63; + return SEND_TIMEOUT_BASE_MILLIS + + ((pkt_airtime_millis * DIRECT_SEND_PERHOP_FACTOR + DIRECT_SEND_PERHOP_EXTRA_MILLIS) * + (path_hash_count + 1)); +} + +void MyMesh::onSendTimeout() {} + +MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui) + : BaseChatMesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16), tables), + _serial(NULL), telemetry(MAX_PACKET_PAYLOAD - 4), _store(&store), _ui(ui) { + _iter_started = false; + _cli_rescue = false; + offline_queue_len = 0; + app_target_ver = 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)); + + // _last_beacon_ms = 0; + + // defaults + memset(&_prefs, 0, sizeof(_prefs)); + _prefs.airtime_factor = 1.0; + strcpy(_prefs.node_name, "NONAME"); + _prefs.freq = LORA_FREQ; + _prefs.sf = LORA_SF; + _prefs.bw = LORA_BW; + _prefs.cr = LORA_CR; + _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.rx_delay_base = 10.0f; enable once new algo fixed +#if defined(USE_SX1262) || defined(USE_SX1268) +#ifdef SX126X_RX_BOOSTED_GAIN + _prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN; +#else + _prefs.rx_boosted_gain = 1; // enabled by default +#endif +#endif +} + +void MyMesh::begin(bool has_display) { + BaseChatMesh::begin(); + + if (!_store->loadMainIdentity(self_id)) { + self_id = radio_new_identity(); // create new random identity + int count = 0; + while (count < 10 && (self_id.pub_key[0] == 0x00 || self_id.pub_key[0] == 0xFF)) { // reserved id hashes + self_id = radio_new_identity(); + count++; + } + _store->saveMainIdentity(self_id); + } + +// if name is provided as a build flag, use that as default node name instead +#ifdef ADVERT_NAME + strcpy(_prefs.node_name, ADVERT_NAME); +#else + // use hex of first 4 bytes of identity public key as default node name + char pub_key_hex[10]; + mesh::Utils::toHex(pub_key_hex, self_id.pub_key, 4); + strcpy(_prefs.node_name, pub_key_hex); +#endif + + // if build provides default-scope, init with that +#ifdef DEFAULT_FLOOD_SCOPE_NAME + strcpy(_prefs.default_scope_name, DEFAULT_FLOOD_SCOPE_NAME); + { + TransportKeyStore temp; + TransportKey key; + temp.getAutoKeyFor(0, "#" DEFAULT_FLOOD_SCOPE_NAME, key); + memcpy(_prefs.default_scope_key, key.key, sizeof(key.key)); + } +#endif + + // load persisted prefs + _store->loadPrefs(_prefs, sensors.node_lat, sensors.node_lon); + + // sanitise bad pref values + _prefs.rx_delay_base = constrain(_prefs.rx_delay_base, 0, 20.0f); + _prefs.airtime_factor = constrain(_prefs.airtime_factor, 0, 9.0f); + _prefs.freq = constrain(_prefs.freq, 150.0f, 2500.0f); + _prefs.bw = constrain(_prefs.bw, 7.8f, 500.0f); + _prefs.sf = constrain(_prefs.sf, 5, 12); + _prefs.cr = constrain(_prefs.cr, 5, 8); + _prefs.tx_power_dbm = constrain(_prefs.tx_power_dbm, -9, MAX_LORA_TX_POWER); + _prefs.gps_enabled = constrain(_prefs.gps_enabled, 0, 1); // Ensure boolean 0 or 1 + _prefs.gps_interval = constrain(_prefs.gps_interval, 0, 86400); // Max 24 hours + +#ifdef BLE_PIN_CODE // 123456 by default + if (_prefs.ble_pin == 0) { +#ifdef DISPLAY_CLASS + if (has_display && BLE_PIN_CODE == 123456) { + StdRNG rng; + _active_ble_pin = rng.nextInt(100000, 999999); // random pin each session + } else { + _active_ble_pin = BLE_PIN_CODE; // otherwise static pin + } +#else + _active_ble_pin = BLE_PIN_CODE; // otherwise static pin +#endif + } else { + _active_ble_pin = _prefs.ble_pin; + } +#else + _active_ble_pin = 0; +#endif + + resetContacts(); + _store->loadContacts(this); + bootstrapRTCfromContacts(); + addChannel("Public", PUBLIC_GROUP_PSK); // pre-configure Andy's public channel + _store->loadChannels(this); + + radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); + radio_set_tx_power(_prefs.tx_power_dbm); + radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain); + MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s", + radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled"); +} + +const char *MyMesh::getNodeName() { + return _prefs.node_name; +} +NodePrefs *MyMesh::getNodePrefs() { + return &_prefs; +} +uint32_t MyMesh::getBLEPin() { + return _active_ble_pin; +} + +struct FreqRange { + uint32_t lower_freq, upper_freq; +}; + +static FreqRange repeat_freq_ranges[] = { + { 433000, 433000 }, + { 869000, 869000 }, + { 918000, 918000 } +}; + +bool MyMesh::isValidClientRepeatFreq(uint32_t f) const { + for (int i = 0; i < sizeof(repeat_freq_ranges)/sizeof(repeat_freq_ranges[0]); i++) { + auto r = &repeat_freq_ranges[i]; + if (f >= r->lower_freq && f <= r->upper_freq) return true; + } + return false; +} + +void MyMesh::startInterface(BaseSerialInterface &serial) { + _serial = &serial; + serial.enable(); +} + +void MyMesh::handleCmdFrame(size_t len) { + if (cmd_frame[0] == CMD_DEVICE_QEURY && len >= 2) { // sent when app establishes connection + app_target_ver = cmd_frame[1]; // which version of protocol does app understand + + int i = 0; + out_frame[i++] = RESP_CODE_DEVICE_INFO; + out_frame[i++] = FIRMWARE_VER_CODE; + out_frame[i++] = MAX_CONTACTS / 2; // v3+ + out_frame[i++] = MAX_GROUP_CHANNELS; // v3+ + memcpy(&out_frame[i], &_prefs.ble_pin, 4); + i += 4; + memset(&out_frame[i], 0, 12); + strcpy((char *)&out_frame[i], FIRMWARE_BUILD_DATE); + i += 12; + StrHelper::strzcpy((char *)&out_frame[i], board.getManufacturerName(), 40); + i += 40; + StrHelper::strzcpy((char *)&out_frame[i], FIRMWARE_VERSION, 20); + i += 20; + out_frame[i++] = _prefs.client_repeat; // v9+ + out_frame[i++] = _prefs.path_hash_mode; // v10+ + _serial->writeFrame(out_frame, i); + } else if (cmd_frame[0] == CMD_APP_START && + len >= 8) { // sent when app establishes connection, respond with node ID + // cmd_frame[1..7] reserved future + char *app_name = (char *)&cmd_frame[8]; + cmd_frame[len] = 0; // make app_name null terminated + MESH_DEBUG_PRINTLN("App %s connected", app_name); + + _iter_started = false; // stop any left-over ContactsIterator + int i = 0; + out_frame[i++] = RESP_CODE_SELF_INFO; + out_frame[i++] = ADV_TYPE_CHAT; // what this node Advert identifies as (maybe node's pronouns too?? :-) + out_frame[i++] = _prefs.tx_power_dbm; + out_frame[i++] = MAX_LORA_TX_POWER; + memcpy(&out_frame[i], self_id.pub_key, PUB_KEY_SIZE); + i += PUB_KEY_SIZE; + + int32_t lat, lon; + lat = (sensors.node_lat * 1000000.0); + lon = (sensors.node_lon * 1000000.0); + memcpy(&out_frame[i], &lat, 4); + i += 4; + memcpy(&out_frame[i], &lon, 4); + i += 4; + out_frame[i++] = _prefs.multi_acks; // new v7+ + out_frame[i++] = _prefs.advert_loc_policy; + out_frame[i++] = (_prefs.telemetry_mode_env << 4) | (_prefs.telemetry_mode_loc << 2) | + (_prefs.telemetry_mode_base); // v5+ + out_frame[i++] = _prefs.manual_add_contacts; + + uint32_t freq = _prefs.freq * 1000; + memcpy(&out_frame[i], &freq, 4); + i += 4; + uint32_t bw = _prefs.bw * 1000; + memcpy(&out_frame[i], &bw, 4); + i += 4; + out_frame[i++] = _prefs.sf; + out_frame[i++] = _prefs.cr; + + int tlen = strlen(_prefs.node_name); // revisit: UTF_8 ?? + memcpy(&out_frame[i], _prefs.node_name, tlen); + i += tlen; + _serial->writeFrame(out_frame, i); + } else if (cmd_frame[0] == CMD_SEND_TXT_MSG && len >= 14) { + int i = 1; + uint8_t txt_type = cmd_frame[i++]; + uint8_t attempt = cmd_frame[i++]; + uint32_t msg_timestamp; + memcpy(&msg_timestamp, &cmd_frame[i], 4); + i += 4; + uint8_t *pub_key_prefix = &cmd_frame[i]; + i += 6; + ContactInfo *recipient = lookupContactByPubKey(pub_key_prefix, 6); + if (recipient && (txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_CLI_DATA)) { + char *text = (char *)&cmd_frame[i]; + int tlen = len - i; + uint32_t est_timeout; + text[tlen] = 0; // ensure null + int result; + uint32_t expected_ack; + if (txt_type == TXT_TYPE_CLI_DATA) { + msg_timestamp = getRTCClock()->getCurrentTimeUnique(); // Use node's RTC instead of app timestamp to avoid tripping replay protection + result = sendCommandData(*recipient, msg_timestamp, attempt, text, est_timeout); + expected_ack = 0; // no Ack expected + } else { + result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack, est_timeout); + } + // TODO: add expected ACK to table + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + if (expected_ack) { + expected_ack_table[next_ack_idx].msg_sent = _ms->getMillis(); // add to circular table + expected_ack_table[next_ack_idx].ack = expected_ack; + expected_ack_table[next_ack_idx].contact = recipient; + next_ack_idx = (next_ack_idx + 1) % EXPECTED_ACK_TABLE_SIZE; + } + + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &expected_ack, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(recipient == NULL + ? ERR_CODE_NOT_FOUND + : ERR_CODE_UNSUPPORTED_CMD); // unknown recipient, or unsuported TXT_TYPE_* + } + } else if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG) { // send GroupChannel text msg + int i = 1; + uint8_t txt_type = cmd_frame[i++]; // should be TXT_TYPE_PLAIN + uint8_t channel_idx = cmd_frame[i++]; + uint32_t msg_timestamp; + memcpy(&msg_timestamp, &cmd_frame[i], 4); + i += 4; + const char *text = (char *)&cmd_frame[i]; + + if (txt_type != TXT_TYPE_PLAIN) { + writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); + } else { + ChannelDetails channel; + bool success = getChannel(channel_idx, channel); + if (success && sendGroupMessage(msg_timestamp, channel.channel, _prefs.node_name, text, len - i)) { + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx + } + } + } else if (cmd_frame[0] == CMD_SEND_CHANNEL_DATA) { // send GroupChannel datagram + if (len < 4) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + return; + } + int i = 1; + uint8_t channel_idx = cmd_frame[i++]; + uint8_t path_len = cmd_frame[i++]; + + // validate path len, allowing 0xFF for flood + if (!mesh::Packet::isValidPathLen(path_len) && path_len != OUT_PATH_UNKNOWN) { + MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA invalid path size: %d", path_len); + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + return; + } + + // parse provided path if not flood + uint8_t path[MAX_PATH_SIZE]; + if (path_len != OUT_PATH_UNKNOWN) { + i += mesh::Packet::writePath(path, &cmd_frame[i], path_len); + } + + uint16_t data_type = ((uint16_t)cmd_frame[i]) | (((uint16_t)cmd_frame[i + 1]) << 8); + i += 2; + const uint8_t *payload = &cmd_frame[i]; + int payload_len = (len > (size_t)i) ? (int)(len - i) : 0; + + ChannelDetails channel; + if (!getChannel(channel_idx, channel)) { + writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx + } else if (data_type == DATA_TYPE_RESERVED) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else if (payload_len > MAX_CHANNEL_DATA_LENGTH) { + MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_CHANNEL_DATA_LENGTH); + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else if (sendGroupData(channel.channel, path, path_len, data_type, payload, payload_len)) { + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } + } else if (cmd_frame[0] == CMD_GET_CONTACTS) { // get Contact list + if (_iter_started) { + writeErrFrame(ERR_CODE_BAD_STATE); // iterator is currently busy + } else { + if (len >= 5) { // has optional 'since' param + memcpy(&_iter_filter_since, &cmd_frame[1], 4); + } else { + _iter_filter_since = 0; + } + + uint8_t reply[5]; + reply[0] = RESP_CODE_CONTACTS_START; + uint32_t count = getNumContacts(); // total, NOT filtered count + memcpy(&reply[1], &count, 4); + _serial->writeFrame(reply, 5); + + // start iterator + _iter = startContactsIterator(); + _iter_started = true; + _most_recent_lastmod = 0; + } + } else if (cmd_frame[0] == CMD_SET_ADVERT_NAME && len >= 2) { + int nlen = len - 1; + if (nlen > sizeof(_prefs.node_name) - 1) nlen = sizeof(_prefs.node_name) - 1; // max len + memcpy(_prefs.node_name, &cmd_frame[1], nlen); + _prefs.node_name[nlen] = 0; // null terminator + savePrefs(); + writeOKFrame(); + } else if (cmd_frame[0] == CMD_SET_ADVERT_LATLON && len >= 9) { + int32_t lat, lon, alt = 0; + memcpy(&lat, &cmd_frame[1], 4); + memcpy(&lon, &cmd_frame[5], 4); + if (len >= 13) { + memcpy(&alt, &cmd_frame[9], 4); // for FUTURE support + } + if (lat <= 90 * 1E6 && lat >= -90 * 1E6 && lon <= 180 * 1E6 && lon >= -180 * 1E6) { + sensors.node_lat = ((double)lat) / 1000000.0; + sensors.node_lon = ((double)lon) / 1000000.0; + savePrefs(); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); // invalid geo coordinate + } + } else if (cmd_frame[0] == CMD_GET_DEVICE_TIME) { + uint8_t reply[5]; + reply[0] = RESP_CODE_CURR_TIME; + uint32_t now = getRTCClock()->getCurrentTime(); + memcpy(&reply[1], &now, 4); + _serial->writeFrame(reply, 5); + } else if (cmd_frame[0] == CMD_SET_DEVICE_TIME && len >= 5) { + uint32_t secs; + memcpy(&secs, &cmd_frame[1], 4); + uint32_t curr = getRTCClock()->getCurrentTime(); + if (secs >= curr) { + getRTCClock()->setCurrentTime(secs); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else if (cmd_frame[0] == CMD_SEND_SELF_ADVERT) { + mesh::Packet* pkt; + if (_prefs.advert_loc_policy == ADVERT_LOC_NONE) { + pkt = createSelfAdvert(_prefs.node_name); + } else { + pkt = createSelfAdvert(_prefs.node_name, sensors.node_lat, sensors.node_lon); + } + if (pkt) { + if (len >= 2 && cmd_frame[1] == 1) { // optional param (1 = flood, 0 = zero hop) + unsigned long delay_millis = 0; + TransportKey default_scope; + memcpy(&default_scope.key, _prefs.default_scope_key, sizeof(default_scope.key)); + sendFloodScoped(default_scope, pkt, delay_millis); + } else { + sendZeroHop(pkt); + } + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } + } else if (cmd_frame[0] == CMD_RESET_PATH && len >= 1 + 32) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient) { + recipient->out_path_len = OUT_PATH_UNKNOWN; + // recipient->lastmod = ?? shouldn't be needed, app already has this version of contact + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // unknown contact + } + } else if (cmd_frame[0] == CMD_ADD_UPDATE_CONTACT && len >= 1 + 32 + 2 + 1) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + uint32_t last_mod = getRTCClock()->getCurrentTime(); // fallback value if not present in cmd_frame + if (recipient) { + updateContactFromFrame(*recipient, last_mod, cmd_frame, len); + recipient->lastmod = last_mod; + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + writeOKFrame(); + } else { + ContactInfo contact; + updateContactFromFrame(contact, last_mod, cmd_frame, len); + contact.lastmod = last_mod; + contact.sync_since = 0; + if (addContact(contact)) { + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } + } + } else if (cmd_frame[0] == CMD_REMOVE_CONTACT) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient && removeContact(*recipient)) { + _store->deleteBlobByKey(pub_key, PUB_KEY_SIZE); + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // not found, or unable to remove + } + } else if (cmd_frame[0] == CMD_SHARE_CONTACT) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient) { + if (shareContactZeroHop(*recipient)) { + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); // unable to send + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); + } + } else if (cmd_frame[0] == CMD_GET_CONTACT_BY_KEY) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *contact = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (contact) { + writeContactRespFrame(RESP_CODE_CONTACT, *contact); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // not found + } + } else if (cmd_frame[0] == CMD_EXPORT_CONTACT) { + if (len < 1 + PUB_KEY_SIZE) { + // export SELF + mesh::Packet* pkt; + if (_prefs.advert_loc_policy == ADVERT_LOC_NONE) { + pkt = createSelfAdvert(_prefs.node_name); + } else { + pkt = createSelfAdvert(_prefs.node_name, sensors.node_lat, sensors.node_lon); + } + if (pkt) { + pkt->header |= ROUTE_TYPE_FLOOD; // would normally be sent in this mode + + out_frame[0] = RESP_CODE_EXPORT_CONTACT; + uint8_t out_len = pkt->writeTo(&out_frame[1]); + releasePacket(pkt); // undo the obtainNewPacket() + _serial->writeFrame(out_frame, out_len + 1); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); // Error + } + } else { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + uint8_t out_len; + if (recipient && (out_len = exportContact(*recipient, &out_frame[1])) > 0) { + out_frame[0] = RESP_CODE_EXPORT_CONTACT; + _serial->writeFrame(out_frame, out_len + 1); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // not found + } + } + } else if (cmd_frame[0] == CMD_IMPORT_CONTACT && len > 2 + 32 + 64) { + if (importContact(&cmd_frame[1], len - 1)) { + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else if (cmd_frame[0] == CMD_SYNC_NEXT_MESSAGE) { + int out_len; + if ((out_len = getFromOfflineQueue(out_frame)) > 0) { + _serial->writeFrame(out_frame, out_len); +#ifdef DISPLAY_CLASS + if (_ui) _ui->msgRead(offline_queue_len); +#endif + } else { + out_frame[0] = RESP_CODE_NO_MORE_MESSAGES; + _serial->writeFrame(out_frame, 1); + } + } else if (cmd_frame[0] == CMD_SET_RADIO_PARAMS) { + int i = 1; + uint32_t freq; + memcpy(&freq, &cmd_frame[i], 4); + i += 4; + uint32_t bw; + memcpy(&bw, &cmd_frame[i], 4); + i += 4; + uint8_t sf = cmd_frame[i++]; + uint8_t cr = cmd_frame[i++]; + uint8_t repeat = 0; // default - false + if (len > i) { + repeat = cmd_frame[i++]; // FIRMWARE_VER_CODE 9+ + } + + if (repeat && !isValidClientRepeatFreq(freq)) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else if (freq >= 150000 && freq <= 2500000 && sf >= 5 && sf <= 12 && cr >= 5 && cr <= 8 && bw >= 7000 && + bw <= 500000) { + _prefs.sf = sf; + _prefs.cr = cr; + _prefs.freq = (float)freq / 1000.0; + _prefs.bw = (float)bw / 1000.0; + _prefs.client_repeat = repeat; + savePrefs(); + + radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); + MESH_DEBUG_PRINTLN("OK: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, + (uint32_t)cr); + + writeOKFrame(); + } else { + MESH_DEBUG_PRINTLN("Error: CMD_SET_RADIO_PARAMS: f=%d, bw=%d, sf=%d, cr=%d", freq, bw, (uint32_t)sf, + (uint32_t)cr); + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else if (cmd_frame[0] == CMD_SET_RADIO_TX_POWER) { + int8_t power = (int8_t)cmd_frame[1]; + if (power < -9 || power > MAX_LORA_TX_POWER) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else { + _prefs.tx_power_dbm = power; + savePrefs(); + radio_set_tx_power(_prefs.tx_power_dbm); + writeOKFrame(); + } + } else if (cmd_frame[0] == CMD_SET_TUNING_PARAMS) { + int i = 1; + uint32_t rx, af; + memcpy(&rx, &cmd_frame[i], 4); + i += 4; + memcpy(&af, &cmd_frame[i], 4); + i += 4; + _prefs.rx_delay_base = ((float)rx) / 1000.0f; + _prefs.airtime_factor = ((float)af) / 1000.0f; + savePrefs(); + writeOKFrame(); + } else if (cmd_frame[0] == CMD_GET_TUNING_PARAMS) { + uint32_t rx = _prefs.rx_delay_base * 1000, af = _prefs.airtime_factor * 1000; + int i = 0; + out_frame[i++] = RESP_CODE_TUNING_PARAMS; + memcpy(&out_frame[i], &rx, 4); i += 4; + memcpy(&out_frame[i], &af, 4); i += 4; + _serial->writeFrame(out_frame, i); + } else if (cmd_frame[0] == CMD_SET_OTHER_PARAMS) { + _prefs.manual_add_contacts = cmd_frame[1]; + if (len >= 3) { + _prefs.telemetry_mode_base = cmd_frame[2] & 0x03; // v5+ + _prefs.telemetry_mode_loc = (cmd_frame[2] >> 2) & 0x03; + _prefs.telemetry_mode_env = (cmd_frame[2] >> 4) & 0x03; + + if (len >= 4) { + _prefs.advert_loc_policy = cmd_frame[3]; + if (len >= 5) { + _prefs.multi_acks = cmd_frame[4]; + } + } + } + savePrefs(); + writeOKFrame(); + } else if (cmd_frame[0] == CMD_SET_PATH_HASH_MODE && cmd_frame[1] == 0 && len >= 3) { + if (cmd_frame[2] >= 3) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else { + _prefs.path_hash_mode = cmd_frame[2]; + savePrefs(); + writeOKFrame(); + } + } else if (cmd_frame[0] == CMD_REBOOT && memcmp(&cmd_frame[1], "reboot", 6) == 0) { + if (dirty_contacts_expiry) { // is there are pending dirty contacts write needed? + saveContacts(); + } + board.reboot(); + } else if (cmd_frame[0] == CMD_GET_BATT_AND_STORAGE) { + uint8_t reply[11]; + int i = 0; + reply[i++] = RESP_CODE_BATT_AND_STORAGE; + uint16_t battery_millivolts = board.getBattMilliVolts(); + uint32_t used = _store->getStorageUsedKb(); + uint32_t total = _store->getStorageTotalKb(); + memcpy(&reply[i], &battery_millivolts, 2); i += 2; + memcpy(&reply[i], &used, 4); i += 4; + memcpy(&reply[i], &total, 4); i += 4; + _serial->writeFrame(reply, i); + } else if (cmd_frame[0] == CMD_EXPORT_PRIVATE_KEY) { +#if ENABLE_PRIVATE_KEY_EXPORT + uint8_t reply[65]; + reply[0] = RESP_CODE_PRIVATE_KEY; + self_id.writeTo(&reply[1], 64); + _serial->writeFrame(reply, 65); +#else + writeDisabledFrame(); +#endif + } else if (cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY && len >= 65) { +#if ENABLE_PRIVATE_KEY_IMPORT + if (!mesh::LocalIdentity::validatePrivateKey(&cmd_frame[1])) { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); // invalid key + } else { + mesh::LocalIdentity identity; + identity.readFrom(&cmd_frame[1], 64); + if (_store->saveMainIdentity(identity)) { + self_id = identity; + writeOKFrame(); + // re-load contacts, to invalidate ecdh shared_secrets + resetContacts(); + _store->loadContacts(this); + } else { + writeErrFrame(ERR_CODE_FILE_IO_ERROR); + } + } +#else + writeDisabledFrame(); +#endif + } else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) { + int i = 1; + int8_t path_len = cmd_frame[i++]; + if (path_len >= 0 && i + path_len + 4 <= len) { // minimum 4 byte payload + uint8_t *path = &cmd_frame[i]; + i += path_len; + auto pkt = createRawData(&cmd_frame[i], len - i); + if (pkt) { + sendDirect(pkt, path, path_len); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } + } else { + writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); // flood, not supported (yet) + } + } else if (cmd_frame[0] == CMD_SEND_LOGIN && len >= 1 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + char *password = (char *)&cmd_frame[1 + PUB_KEY_SIZE]; + cmd_frame[len] = 0; // ensure null terminator in password + if (recipient) { + uint32_t est_timeout; + int result = sendLogin(*recipient, password, est_timeout); + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + clearPendingReqs(); + memcpy(&pending_login, recipient->id.pub_key, 4); // match this to onContactResponse() + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &pending_login, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found + } + } else if (cmd_frame[0] == CMD_SEND_ANON_REQ && len > 1 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + uint8_t *data = &cmd_frame[1 + PUB_KEY_SIZE]; + if (recipient) { + uint32_t tag, est_timeout; + int result = sendAnonReq(*recipient, data, len - (1 + PUB_KEY_SIZE), tag, est_timeout); + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + clearPendingReqs(); + pending_req = tag; // match this to onContactResponse() + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &tag, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found + } + } else if (cmd_frame[0] == CMD_SEND_STATUS_REQ && len >= 1 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient) { + uint32_t tag, est_timeout; + int result = sendRequest(*recipient, REQ_TYPE_GET_STATUS, tag, est_timeout); + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + clearPendingReqs(); + // FUTURE: pending_status = tag; // match this in onContactResponse() + memcpy(&pending_status, recipient->id.pub_key, 4); // legacy matching scheme + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &tag, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found + } + } else if (cmd_frame[0] == CMD_SEND_PATH_DISCOVERY_REQ && cmd_frame[1] == 0 && len >= 2 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[2]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient) { + uint32_t tag, est_timeout; + // 'Path Discovery' is just a special case of flood + Telemetry req + uint8_t req_data[9]; + req_data[0] = REQ_TYPE_GET_TELEMETRY_DATA; + req_data[1] = ~(TELEM_PERM_BASE); // NEW: inverse permissions mask (ie. we only want BASE telemetry) + memset(&req_data[2], 0, 3); // reserved + getRNG()->random(&req_data[5], 4); // random blob to help make packet-hash unique + auto save = recipient->out_path_len; // temporarily force sendRequest() to flood + recipient->out_path_len = OUT_PATH_UNKNOWN; + int result = sendRequest(*recipient, req_data, sizeof(req_data), tag, est_timeout); + recipient->out_path_len = save; + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + clearPendingReqs(); + pending_discovery = tag; // match this in onContactResponse() + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &tag, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found + } + } else if (cmd_frame[0] == CMD_SEND_TELEMETRY_REQ && len >= 4 + PUB_KEY_SIZE) { // can deprecate, in favour of CMD_SEND_BINARY_REQ + uint8_t *pub_key = &cmd_frame[4]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient) { + uint32_t tag, est_timeout; + int result = sendRequest(*recipient, REQ_TYPE_GET_TELEMETRY_DATA, tag, est_timeout); + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + clearPendingReqs(); + pending_telemetry = tag; // match this in onContactResponse() + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &tag, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found + } + } else if (cmd_frame[0] == CMD_SEND_TELEMETRY_REQ && len == 4) { // 'self' telemetry request + telemetry.reset(); + telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + // query other sensors -- target specific + sensors.querySensors(0xFF, telemetry); + + int i = 0; + out_frame[i++] = PUSH_CODE_TELEMETRY_RESPONSE; + out_frame[i++] = 0; // reserved + memcpy(&out_frame[i], self_id.pub_key, 6); + i += 6; // pub_key_prefix + uint8_t tlen = telemetry.getSize(); + memcpy(&out_frame[i], telemetry.getBuffer(), tlen); + i += tlen; + _serial->writeFrame(out_frame, i); + } else if (cmd_frame[0] == CMD_SEND_BINARY_REQ && len >= 2 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[1]; + ContactInfo *recipient = lookupContactByPubKey(pub_key, PUB_KEY_SIZE); + if (recipient) { + uint8_t *req_data = &cmd_frame[1 + PUB_KEY_SIZE]; + uint32_t tag, est_timeout; + int result = sendRequest(*recipient, req_data, len - (1 + PUB_KEY_SIZE), tag, est_timeout); + if (result == MSG_SEND_FAILED) { + writeErrFrame(ERR_CODE_TABLE_FULL); + } else { + clearPendingReqs(); + pending_req = tag; // match this in onContactResponse() + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = (result == MSG_SEND_SENT_FLOOD) ? 1 : 0; + memcpy(&out_frame[2], &tag, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // contact not found + } + } else if (cmd_frame[0] == CMD_HAS_CONNECTION && len >= 1 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[1]; + if (hasConnectionTo(pub_key)) { + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); + } + } else if (cmd_frame[0] == CMD_LOGOUT && len >= 1 + PUB_KEY_SIZE) { + uint8_t *pub_key = &cmd_frame[1]; + stopConnection(pub_key); + writeOKFrame(); + } else if (cmd_frame[0] == CMD_GET_CHANNEL && len >= 2) { + uint8_t channel_idx = cmd_frame[1]; + ChannelDetails channel; + if (getChannel(channel_idx, channel)) { + int i = 0; + out_frame[i++] = RESP_CODE_CHANNEL_INFO; + out_frame[i++] = channel_idx; + strcpy((char *)&out_frame[i], channel.name); + i += 32; + memcpy(&out_frame[i], channel.channel.secret, 16); + i += 16; // NOTE: only 128-bit supported + _serial->writeFrame(out_frame, i); + } else { + 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) + } 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 + if (setChannel(channel_idx, channel)) { + saveChannels(); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx + } + } else if (cmd_frame[0] == CMD_SIGN_START) { + out_frame[0] = RESP_CODE_SIGN_START; + out_frame[1] = 0; // reserved + uint32_t len = MAX_SIGN_DATA_LEN; + memcpy(&out_frame[2], &len, 4); + _serial->writeFrame(out_frame, 6); + + if (sign_data) { + free(sign_data); + } + sign_data = (uint8_t *)malloc(MAX_SIGN_DATA_LEN); + sign_data_len = 0; + } else if (cmd_frame[0] == CMD_SIGN_DATA && len > 1) { + if (sign_data == NULL || sign_data_len + (len - 1) > MAX_SIGN_DATA_LEN) { + writeErrFrame(sign_data == NULL ? ERR_CODE_BAD_STATE : ERR_CODE_TABLE_FULL); // error: too long + } else { + memcpy(&sign_data[sign_data_len], &cmd_frame[1], len - 1); + sign_data_len += (len - 1); + writeOKFrame(); + } + } else if (cmd_frame[0] == CMD_SIGN_FINISH) { + if (sign_data) { + self_id.sign(&out_frame[1], sign_data, sign_data_len); + + free(sign_data); // don't need sign_data now + sign_data = NULL; + + out_frame[0] = RESP_CODE_SIGNATURE; + _serial->writeFrame(out_frame, 1 + SIGNATURE_SIZE); + } else { + writeErrFrame(ERR_CODE_BAD_STATE); + } + } else if (cmd_frame[0] == CMD_SEND_TRACE_PATH && len > 10 && len - 10 < MAX_PACKET_PAYLOAD-5) { + uint8_t path_len = len - 10; + uint8_t flags = cmd_frame[9]; + uint8_t path_sz = flags & 0x03; // NEW v1.11+ + if ((path_len >> path_sz) > MAX_PATH_SIZE || (path_len % (1 << path_sz)) != 0) { // make sure is multiple of path_sz + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } else { + uint32_t tag, auth; + memcpy(&tag, &cmd_frame[1], 4); + memcpy(&auth, &cmd_frame[5], 4); + auto pkt = createTrace(tag, auth, flags); + if (pkt) { + sendDirect(pkt, &cmd_frame[10], path_len); + + uint32_t t = _radio->getEstAirtimeFor(pkt->payload_len + pkt->path_len + 2); + uint32_t est_timeout = calcDirectTimeoutMillisFor(t, path_len >> path_sz); + + out_frame[0] = RESP_CODE_SENT; + out_frame[1] = 0; + memcpy(&out_frame[2], &tag, 4); + memcpy(&out_frame[6], &est_timeout, 4); + _serial->writeFrame(out_frame, 10); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } + } + } else if (cmd_frame[0] == CMD_SET_DEVICE_PIN && len >= 5) { + + // get pin from command frame + uint32_t pin; + memcpy(&pin, &cmd_frame[1], 4); + + // ensure pin is zero, or a valid 6 digit pin + if (pin == 0 || (pin >= 100000 && pin <= 999999)) { + _prefs.ble_pin = pin; + savePrefs(); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else if (cmd_frame[0] == CMD_GET_CUSTOM_VARS) { + out_frame[0] = RESP_CODE_CUSTOM_VARS; + char *dp = (char *)&out_frame[1]; + for (int i = 0; i < sensors.getNumSettings() && dp - (char *)&out_frame[1] < 140; i++) { + if (i > 0) { + *dp++ = ','; + } + strcpy(dp, sensors.getSettingName(i)); + dp = strchr(dp, 0); + *dp++ = ':'; + strcpy(dp, sensors.getSettingValue(i)); + dp = strchr(dp, 0); + } + _serial->writeFrame(out_frame, dp - (char *)out_frame); + } else if (cmd_frame[0] == CMD_SET_CUSTOM_VAR && len >= 4) { + cmd_frame[len] = 0; + char *sp = (char *)&cmd_frame[1]; + char *np = strchr(sp, ':'); // look for separator char + if (np) { + *np++ = 0; // modify 'cmd_frame', replace ':' with null + bool success = sensors.setSettingValue(sp, np); + if (success) { + #if ENV_INCLUDE_GPS == 1 + // Update node preferences for GPS settings + if (strcmp(sp, "gps") == 0) { + _prefs.gps_enabled = (np[0] == '1') ? 1 : 0; + savePrefs(); + } else if (strcmp(sp, "gps_interval") == 0) { + uint32_t interval_seconds = atoi(np); + _prefs.gps_interval = constrain(interval_seconds, 0, 86400); + savePrefs(); + } + #endif + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else if (cmd_frame[0] == CMD_GET_ADVERT_PATH && len >= PUB_KEY_SIZE+2) { + // FUTURE use: uint8_t reserved = cmd_frame[1]; + uint8_t *pub_key = &cmd_frame[2]; + AdvertPath* found = NULL; + for (int i = 0; i < ADVERT_PATH_TABLE_SIZE; i++) { + auto p = &advert_paths[i]; + if (memcmp(p->pubkey_prefix, pub_key, sizeof(p->pubkey_prefix)) == 0) { + found = p; + break; + } + } + if (found) { + int i = 0; + out_frame[i++] = RESP_CODE_ADVERT_PATH; + memcpy(&out_frame[i], &found->recv_timestamp, 4); i += 4; + out_frame[i++] = found->path_len; + i += mesh::Packet::writePath(&out_frame[i], found->path, found->path_len); + _serial->writeFrame(out_frame, i); + } else { + writeErrFrame(ERR_CODE_NOT_FOUND); + } + } else if (cmd_frame[0] == CMD_GET_STATS && len >= 2) { + uint8_t stats_type = cmd_frame[1]; + if (stats_type == STATS_TYPE_CORE) { + int i = 0; + out_frame[i++] = RESP_CODE_STATS; + out_frame[i++] = STATS_TYPE_CORE; + uint16_t battery_mv = board.getBattMilliVolts(); + uint32_t uptime_secs = _ms->getMillis() / 1000; + uint8_t queue_len = (uint8_t)_mgr->getOutboundTotal(); + memcpy(&out_frame[i], &battery_mv, 2); i += 2; + memcpy(&out_frame[i], &uptime_secs, 4); i += 4; + memcpy(&out_frame[i], &_err_flags, 2); i += 2; + out_frame[i++] = queue_len; + _serial->writeFrame(out_frame, i); + } else if (stats_type == STATS_TYPE_RADIO) { + int i = 0; + out_frame[i++] = RESP_CODE_STATS; + out_frame[i++] = STATS_TYPE_RADIO; + int16_t noise_floor = (int16_t)_radio->getNoiseFloor(); + int8_t last_rssi = (int8_t)radio_driver.getLastRSSI(); + int8_t last_snr = (int8_t)(radio_driver.getLastSNR() * 4); // scaled by 4 for 0.25 dB precision + uint32_t tx_air_secs = getTotalAirTime() / 1000; + uint32_t rx_air_secs = getReceiveAirTime() / 1000; + memcpy(&out_frame[i], &noise_floor, 2); i += 2; + out_frame[i++] = last_rssi; + out_frame[i++] = last_snr; + memcpy(&out_frame[i], &tx_air_secs, 4); i += 4; + memcpy(&out_frame[i], &rx_air_secs, 4); i += 4; + _serial->writeFrame(out_frame, i); + } else if (stats_type == STATS_TYPE_PACKETS) { + int i = 0; + out_frame[i++] = RESP_CODE_STATS; + out_frame[i++] = STATS_TYPE_PACKETS; + uint32_t recv = radio_driver.getPacketsRecv(); + uint32_t sent = radio_driver.getPacketsSent(); + uint32_t n_sent_flood = getNumSentFlood(); + uint32_t n_sent_direct = getNumSentDirect(); + uint32_t n_recv_flood = getNumRecvFlood(); + uint32_t n_recv_direct = getNumRecvDirect(); + uint32_t n_recv_errors = radio_driver.getPacketsRecvErrors(); + memcpy(&out_frame[i], &recv, 4); i += 4; + memcpy(&out_frame[i], &sent, 4); i += 4; + memcpy(&out_frame[i], &n_sent_flood, 4); i += 4; + memcpy(&out_frame[i], &n_sent_direct, 4); i += 4; + memcpy(&out_frame[i], &n_recv_flood, 4); i += 4; + memcpy(&out_frame[i], &n_recv_direct, 4); i += 4; + memcpy(&out_frame[i], &n_recv_errors, 4); i += 4; + _serial->writeFrame(out_frame, i); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); // invalid stats sub-type + } + } else if (cmd_frame[0] == CMD_FACTORY_RESET && memcmp(&cmd_frame[1], "reset", 5) == 0) { + if (_serial) { + MESH_DEBUG_PRINTLN("Factory reset: disabling serial interface to prevent reconnects (BLE/WiFi)"); + _serial->disable(); // Phone app disconnects before we can send OK frame so it's safe here + } + bool success = _store->formatFileSystem(); + if (success) { + writeOKFrame(); + delay(1000); + board.reboot(); // doesn't return + } else { + writeErrFrame(ERR_CODE_FILE_IO_ERROR); + } + } else if (cmd_frame[0] == CMD_SET_FLOOD_SCOPE_KEY && len >= 2 && cmd_frame[1] == 0) { + if (len >= 2 + 16) { + memcpy(send_scope.key, &cmd_frame[2], sizeof(send_scope.key)); // set curr scope TransportKey + } else { + memset(send_scope.key, 0, sizeof(send_scope.key)); // set scope to null + } + writeOKFrame(); + } else if (cmd_frame[0] == CMD_SET_DEFAULT_FLOOD_SCOPE && len >= 1) { + if (len >= 1+31+16) { + int n = strlen((char *) &cmd_frame[1]); + if (n > 0 && n < 31) { + strcpy(_prefs.default_scope_name, (char *) &cmd_frame[1]); + memcpy(_prefs.default_scope_key, &cmd_frame[1+31], 16); + savePrefs(); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_ILLEGAL_ARG); + } + } else { + memset(_prefs.default_scope_name, 0, sizeof(_prefs.default_scope_name)); // set default scope to null + memset(_prefs.default_scope_key, 0, sizeof(_prefs.default_scope_key)); + savePrefs(); + writeOKFrame(); + } + } else if (cmd_frame[0] == CMD_GET_DEFAULT_FLOOD_SCOPE) { + out_frame[0] = RESP_CODE_DEFAULT_FLOOD_SCOPE; + if (strlen(_prefs.default_scope_name) > 0) { + memcpy(&out_frame[1], _prefs.default_scope_name, 31); + memcpy(&out_frame[1+31], _prefs.default_scope_key, 16); + _serial->writeFrame(out_frame, 1+31+16); + } else { + _serial->writeFrame(out_frame, 1); // no name or key means null + } + } else if (cmd_frame[0] == CMD_SEND_CONTROL_DATA && len >= 2 && (cmd_frame[1] & 0x80) != 0) { + auto resp = createControlData(&cmd_frame[1], len - 1); + if (resp) { + sendZeroHop(resp); + writeOKFrame(); + } else { + writeErrFrame(ERR_CODE_TABLE_FULL); + } + } else if (cmd_frame[0] == CMD_SET_AUTOADD_CONFIG) { + _prefs.autoadd_config = cmd_frame[1]; + if (len >= 3) { + _prefs.autoadd_max_hops = min(cmd_frame[2], (uint8_t)64); + } + savePrefs(); + writeOKFrame(); + } else if (cmd_frame[0] == CMD_GET_AUTOADD_CONFIG) { + int i = 0; + out_frame[i++] = RESP_CODE_AUTOADD_CONFIG; + out_frame[i++] = _prefs.autoadd_config; + out_frame[i++] = _prefs.autoadd_max_hops; + _serial->writeFrame(out_frame, i); + } else if (cmd_frame[0] == CMD_GET_ALLOWED_REPEAT_FREQ) { + int i = 0; + out_frame[i++] = RESP_ALLOWED_REPEAT_FREQ; + for (int k = 0; k < sizeof(repeat_freq_ranges)/sizeof(repeat_freq_ranges[0]) && i + 8 < sizeof(out_frame); k++) { + auto r = &repeat_freq_ranges[k]; + memcpy(&out_frame[i], &r->lower_freq, 4); i += 4; + memcpy(&out_frame[i], &r->upper_freq, 4); i += 4; + } + _serial->writeFrame(out_frame, i); + } else { + writeErrFrame(ERR_CODE_UNSUPPORTED_CMD); + MESH_DEBUG_PRINTLN("ERROR: unknown command: %02X", cmd_frame[0]); + } +} + +void MyMesh::enterCLIRescue() { + _cli_rescue = true; + cli_command[0] = 0; + Serial.println("========= CLI Rescue ========="); +} + +void MyMesh::checkCLIRescueCmd() { + int len = strlen(cli_command); + while (Serial.available() && len < sizeof(cli_command)-1) { + char c = Serial.read(); + if (c != '\n') { + cli_command[len++] = c; + cli_command[len] = 0; + } + Serial.print(c); // echo + } + if (len == sizeof(cli_command)-1) { // command buffer full + cli_command[sizeof(cli_command)-1] = '\r'; + } + + if (len > 0 && cli_command[len - 1] == '\r') { // received complete line + cli_command[len - 1] = 0; // replace newline with C string null terminator + + if (memcmp(cli_command, "set ", 4) == 0) { + const char* config = &cli_command[4]; + if (memcmp(config, "pin ", 4) == 0) { + _prefs.ble_pin = atoi(&config[4]); + savePrefs(); + Serial.printf(" > pin is now %06d\n", _prefs.ble_pin); + } else { + Serial.printf(" Error: unknown config: %s\n", config); + } + } else if (strcmp(cli_command, "rebuild") == 0) { + bool success = _store->formatFileSystem(); + if (success) { + _store->saveMainIdentity(self_id); + savePrefs(); + saveContacts(); + saveChannels(); + Serial.println(" > erase and rebuild done"); + } else { + Serial.println(" Error: erase failed"); + } + } else if (strcmp(cli_command, "erase") == 0) { + bool success = _store->formatFileSystem(); + if (success) { + Serial.println(" > erase done"); + } else { + Serial.println(" Error: erase failed"); + } + } else if (memcmp(cli_command, "ls", 2) == 0) { + + // get path from command e.g: "ls /adafruit" + const char *path = &cli_command[3]; + + bool is_fs2 = false; + if (memcmp(path, "UserData/", 9) == 0) { + path += 8; // skip "UserData" + } else if (memcmp(path, "ExtraFS/", 8) == 0) { + path += 7; // skip "ExtraFS" + is_fs2 = true; + } + Serial.printf("Listing files in %s\n", path); + + // log each file and directory + File root = _store->openRead(path); + if (is_fs2 == false) { + if (root) { + File file = root.openNextFile(); + while (file) { + if (file.isDirectory()) { + Serial.printf("[dir] UserData%s/%s\n", path, file.name()); + } else { + Serial.printf("[file] UserData%s/%s (%d bytes)\n", path, file.name(), file.size()); + } + // move to next file + file = root.openNextFile(); + } + root.close(); + } + } + + if (is_fs2 == true || strlen(path) == 0 || strcmp(path, "/") == 0) { + if (_store->getSecondaryFS() != nullptr) { + File root2 = _store->openRead(_store->getSecondaryFS(), path); + File file = root2.openNextFile(); + while (file) { + if (file.isDirectory()) { + Serial.printf("[dir] ExtraFS%s/%s\n", path, file.name()); + } else { + Serial.printf("[file] ExtraFS%s/%s (%d bytes)\n", path, file.name(), file.size()); + } + // move to next file + file = root2.openNextFile(); + } + root2.close(); + } + } + } else if (memcmp(cli_command, "cat", 3) == 0) { + + // get path from command e.g: "cat /contacts3" + const char *path = &cli_command[4]; + + bool is_fs2 = false; + if (memcmp(path, "UserData/", 9) == 0) { + path += 8; // skip "UserData" + } else if (memcmp(path, "ExtraFS/", 8) == 0) { + path += 7; // skip "ExtraFS" + is_fs2 = true; + } else { + Serial.println("Invalid path provided, must start with UserData/ or ExtraFS/"); + cli_command[0] = 0; + return; + } + + // log file content as hex + File file = _store->openRead(path); + if (is_fs2 == true) { + file = _store->openRead(_store->getSecondaryFS(), path); + } + if(file){ + + // get file content + int file_size = file.available(); + uint8_t buffer[file_size]; + file.read(buffer, file_size); + + // print hex + mesh::Utils::printHex(Serial, buffer, file_size); + Serial.print("\n"); + + file.close(); + + } + + } else if (memcmp(cli_command, "rm ", 3) == 0) { + // get path from command e.g: "rm /adv_blobs" + const char *path = &cli_command[3]; + MESH_DEBUG_PRINTLN("Removing file: %s", path); + // ensure path is not empty, or root dir + if(!path || strlen(path) == 0 || strcmp(path, "/") == 0){ + Serial.println("Invalid path provided"); + } else { + bool is_fs2 = false; + if (memcmp(path, "UserData/", 9) == 0) { + path += 8; // skip "UserData" + } else if (memcmp(path, "ExtraFS/", 8) == 0) { + path += 7; // skip "ExtraFS" + is_fs2 = true; + } + + // remove file + bool removed; + if (is_fs2) { + MESH_DEBUG_PRINTLN("Removing file from ExtraFS: %s", path); + removed = _store->removeFile(_store->getSecondaryFS(), path); + } else { + MESH_DEBUG_PRINTLN("Removing file from UserData: %s", path); + removed = _store->removeFile(path); + } + if(removed){ + Serial.println("File removed"); + } else { + Serial.println("Failed to remove file"); + } + + } + + } else if (strcmp(cli_command, "reboot") == 0) { + board.reboot(); // doesn't return + } else { + Serial.println(" Error: unknown command"); + } + + cli_command[0] = 0; // reset command buffer + } +} + +void MyMesh::checkSerialInterface() { + size_t len = _serial->checkRecvFrame(cmd_frame); + if (len > 0) { + handleCmdFrame(len); + } else if (_iter_started // check if our ContactsIterator is 'running' + && !_serial->isWriteBusy() // don't spam the Serial Interface too quickly! + ) { + ContactInfo contact; + if (_iter.hasNext(this, contact)) { + if (contact.lastmod > _iter_filter_since) { // apply the 'since' filter + writeContactRespFrame(RESP_CODE_CONTACT, contact); + if (contact.lastmod > _most_recent_lastmod) { + _most_recent_lastmod = contact.lastmod; // save for the RESP_CODE_END_OF_CONTACTS frame + } + } + } else { // EOF + out_frame[0] = RESP_CODE_END_OF_CONTACTS; + memcpy(&out_frame[1], &_most_recent_lastmod, + 4); // include the most recent lastmod, so app can update their 'since' + _serial->writeFrame(out_frame, 5); + _iter_started = false; + } + //} else if (!_serial->isWriteBusy()) { + // checkConnections(); // TODO - deprecate the 'Connections' stuff + } +} + +void MyMesh::loop() { + BaseChatMesh::loop(); + + unsigned long now = millis(); + if (now - _last_beacon_ms >= BEACON_INTERVAL_MS || _last_beacon_ms == 0) { + sendBeacon(); + _last_beacon_ms = now; + } + + if (_cli_rescue) { + checkCLIRescueCmd(); + } else { + checkSerialInterface(); + } + + // is there are pending dirty contacts write needed? + if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) { + saveContacts(); + dirty_contacts_expiry = 0; + } + +#ifdef DISPLAY_CLASS + if (_ui) _ui->setHasConnection(_serial->isConnected()); +#endif +} + +bool MyMesh::advert() { + mesh::Packet* pkt; + if (_prefs.advert_loc_policy == ADVERT_LOC_NONE) { + pkt = createSelfAdvert(_prefs.node_name); + } else { + pkt = createSelfAdvert(_prefs.node_name, sensors.node_lat, sensors.node_lon); + } + if (pkt) { + sendZeroHop(pkt); + return true; + } else { + return false; + } +} + +void MyMesh::sendBeacon() { + uint8_t app_data[MAX_ADVERT_DATA_SIZE]; + uint8_t app_data_len; + { + AdvertDataBuilder builder(ADV_TYPE_CHAT, _prefs.node_name, sensors.node_lat, sensors.node_lon); + app_data_len = builder.encodeTo(app_data); + } + + mesh::Packet* pkt = createAdvert(self_id, app_data, app_data_len); + if (pkt) { + sendFlood(pkt, (uint32_t)0, _prefs.path_hash_mode + 1); + MESH_DEBUG_PRINTLN("Beacon sent (flood)"); + } else { + MESH_DEBUG_PRINTLN("Beacon: failed to create packet"); + } +} diff --git a/examples/beacon_sensor/MyMesh.h b/examples/beacon_sensor/MyMesh.h new file mode 100644 index 0000000..c09c382 --- /dev/null +++ b/examples/beacon_sensor/MyMesh.h @@ -0,0 +1,259 @@ +#pragma once + +#include +#include +#include "AbstractUITask.h" + +/*------------ Frame Protocol --------------*/ +#define FIRMWARE_VER_CODE 12 + +#ifndef FIRMWARE_BUILD_DATE +#define FIRMWARE_BUILD_DATE "05 Jun 2026" +#endif + +#ifndef FIRMWARE_VERSION +#define FIRMWARE_VERSION "v1.0.0-beacon" +#endif + +#ifndef BEACON_INTERVAL_MS +#define BEACON_INTERVAL_MS 900000 +#endif + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) +#include +#elif defined(RP2040_PLATFORM) +#include +#elif defined(ESP32) +#include +#endif + +#include "DataStore.h" +#include "NodePrefs.h" + +#include +#include +#include +#include +#include +#include +#include + +/* ---------------------------------- CONFIGURATION ------------------------------------- */ + +#ifndef LORA_FREQ +#define LORA_FREQ 915.0 +#endif +#ifndef LORA_BW +#define LORA_BW 250 +#endif +#ifndef LORA_SF +#define LORA_SF 10 +#endif +#ifndef LORA_CR +#define LORA_CR 5 +#endif +#ifndef LORA_TX_POWER +#define LORA_TX_POWER 20 +#endif +#ifndef MAX_LORA_TX_POWER +#define MAX_LORA_TX_POWER LORA_TX_POWER +#endif + +#ifndef MAX_CONTACTS +#define MAX_CONTACTS 100 +#endif + +#ifndef OFFLINE_QUEUE_SIZE +#define OFFLINE_QUEUE_SIZE 16 +#endif + +#ifndef BLE_NAME_PREFIX +#define BLE_NAME_PREFIX "MeshCore-" +#endif + +#include +#include + +/* -------------------------------------------------------------------------------------- */ + +#define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS +#define REQ_TYPE_KEEP_ALIVE 0x02 +#define REQ_TYPE_GET_TELEMETRY_DATA 0x03 + +struct AdvertPath { + uint8_t pubkey_prefix[7]; + uint8_t path_len; + char name[32]; + uint32_t recv_timestamp; + uint8_t path[MAX_PATH_SIZE]; +}; + +class MyMesh : public BaseChatMesh, public DataStoreHost { +public: + MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMeshTables &tables, DataStore& store, AbstractUITask* ui=NULL); + + void begin(bool has_display); + void startInterface(BaseSerialInterface &serial); + + const char *getNodeName(); + NodePrefs *getNodePrefs(); + uint32_t getBLEPin(); + + void loop(); + void handleCmdFrame(size_t len); + bool advert(); + void sendBeacon(); + void enterCLIRescue(); + + int getRecentlyHeard(AdvertPath dest[], int max_num); + +protected: + float getAirtimeBudgetFactor() const override; + int getInterferenceThreshold() const override; + int calcRxDelay(float score, uint32_t air_time) const override; + uint32_t getRetransmitDelay(const mesh::Packet *packet) override; + uint32_t getDirectRetransmitDelay(const mesh::Packet *packet) override; + uint8_t getExtraAckTransmitCount() const override; + bool filterRecvFloodPacket(mesh::Packet* packet) override; + bool allowPacketForward(const mesh::Packet* packet) override; + + void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis); + void sendFloodScoped(const ContactInfo& recipient, mesh::Packet* pkt, uint32_t delay_millis=0) override; + void sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis=0) override; + + void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override; + bool isAutoAddEnabled() const override; + bool shouldAutoAddContactType(uint8_t type) const override; + bool shouldOverwriteWhenFull() const override; + uint8_t getAutoAddMaxHops() const override; + void onContactsFull() override; + void onContactOverwrite(const uint8_t* pub_key) override; + bool onContactPathRecv(ContactInfo& from, uint8_t* in_path, uint8_t in_path_len, uint8_t* out_path, uint8_t out_path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; + void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; + void onContactPathUpdated(const ContactInfo &contact) override; + ContactInfo* processAck(const uint8_t *data) override; + void queueMessage(const ContactInfo &from, uint8_t txt_type, mesh::Packet *pkt, uint32_t sender_timestamp, + const uint8_t *extra, int extra_len, const char *text); + + void onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, + const char *text) override; + void onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, + const char *text) override; + void onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp, + const uint8_t *sender_prefix, const char *text) override; + void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp, + const char *text) override; + void onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type, + const uint8_t *data, size_t data_len) override; + + uint8_t onContactRequest(const ContactInfo &contact, uint32_t sender_timestamp, const uint8_t *data, + uint8_t len, uint8_t *reply) override; + void onContactResponse(const ContactInfo &contact, const uint8_t *data, uint8_t len) override; + void onControlDataRecv(mesh::Packet *packet) override; + void onRawDataRecv(mesh::Packet *packet) override; + void onTraceRecv(mesh::Packet *packet, uint32_t tag, uint32_t auth_code, uint8_t flags, + const uint8_t *path_snrs, const uint8_t *path_hashes, uint8_t path_len) override; + + uint32_t calcFloodTimeoutMillisFor(uint32_t pkt_airtime_millis) const override; + uint32_t calcDirectTimeoutMillisFor(uint32_t pkt_airtime_millis, uint8_t path_len) const override; + void onSendTimeout() override; + + // DataStoreHost methods + bool onContactLoaded(const ContactInfo& contact) override { return addContact(contact); } + bool getContactForSave(uint32_t idx, ContactInfo& contact) override { return getContactByIdx(idx, contact); } + bool onChannelLoaded(uint8_t channel_idx, const ChannelDetails& ch) override { return setChannel(channel_idx, ch); } + bool getChannelForSave(uint8_t channel_idx, ChannelDetails& ch) override { return getChannel(channel_idx, ch); } + + void clearPendingReqs() { + pending_login = pending_status = pending_telemetry = pending_discovery = pending_req = 0; + } + +public: + void savePrefs() { _store->savePrefs(_prefs, sensors.node_lat, sensors.node_lon); } + +#if ENV_INCLUDE_GPS == 1 + void applyGpsPrefs() { + sensors.setSettingValue("gps", _prefs.gps_enabled ? "1" : "0"); + if (_prefs.gps_interval > 0) { + char interval_str[12]; // Max: 24 hours = 86400 seconds (5 digits + null) + sprintf(interval_str, "%u", _prefs.gps_interval); + sensors.setSettingValue("gps_interval", interval_str); + } + } +#endif + +private: + void writeOKFrame(); + void writeErrFrame(uint8_t err_code); + void writeDisabledFrame(); + void writeContactRespFrame(uint8_t code, const ContactInfo &contact); + void updateContactFromFrame(ContactInfo &contact, uint32_t& last_mod, const uint8_t *frame, int len); + void addToOfflineQueue(const uint8_t frame[], int len); + int getFromOfflineQueue(uint8_t frame[]); + int getBlobByKey(const uint8_t key[], int key_len, uint8_t dest_buf[]) override { + return _store->getBlobByKey(key, key_len, dest_buf); + } + bool putBlobByKey(const uint8_t key[], int key_len, const uint8_t src_buf[], int len) override { + return _store->putBlobByKey(key, key_len, src_buf, len); + } + + void checkCLIRescueCmd(); + void checkSerialInterface(); + bool isValidClientRepeatFreq(uint32_t f) const; + + // helpers, short-cuts + void saveChannels() { _store->saveChannels(this); } + void saveContacts() { _store->saveContacts(this); } + + DataStore* _store; + NodePrefs _prefs; + uint32_t pending_login; + uint32_t pending_status; + uint32_t pending_telemetry, pending_discovery; // pending _TELEMETRY_REQ + uint32_t pending_req; // pending _BINARY_REQ + BaseSerialInterface *_serial; + AbstractUITask* _ui; + + ContactsIterator _iter; + uint32_t _iter_filter_since; + uint32_t _most_recent_lastmod; + uint32_t _active_ble_pin; + bool _iter_started; + bool _cli_rescue; + char cli_command[80]; + uint8_t app_target_ver; + uint8_t *sign_data; + uint32_t sign_data_len; + unsigned long dirty_contacts_expiry; + + TransportKey send_scope; + + unsigned long _last_beacon_ms; + + uint8_t cmd_frame[MAX_FRAME_SIZE + 1]; + uint8_t out_frame[MAX_FRAME_SIZE + 1]; + CayenneLPP telemetry; + + struct Frame { + uint8_t len; + uint8_t buf[MAX_FRAME_SIZE]; + + bool isChannelMsg() const; + }; + int offline_queue_len; + Frame offline_queue[OFFLINE_QUEUE_SIZE]; + + struct AckTableEntry { + unsigned long msg_sent; + 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 +}; + +extern MyMesh the_mesh; diff --git a/examples/beacon_sensor/NodePrefs.h b/examples/beacon_sensor/NodePrefs.h new file mode 100644 index 0000000..48c381c --- /dev/null +++ b/examples/beacon_sensor/NodePrefs.h @@ -0,0 +1,37 @@ +#pragma once +#include // For uint8_t, uint32_t + +#define TELEM_MODE_DENY 0 +#define TELEM_MODE_ALLOW_FLAGS 1 // use contact.flags +#define TELEM_MODE_ALLOW_ALL 2 + +#define ADVERT_LOC_NONE 0 +#define ADVERT_LOC_SHARE 1 + +struct NodePrefs { // persisted to file + float airtime_factor; + char node_name[32]; + float freq; + uint8_t sf; + uint8_t cr; + uint8_t multi_acks; + uint8_t manual_add_contacts; + float bw; + int8_t tx_power_dbm; + uint8_t telemetry_mode_base; + uint8_t telemetry_mode_loc; + uint8_t telemetry_mode_env; + float rx_delay_base; + uint32_t ble_pin; + uint8_t advert_loc_policy; + uint8_t buzzer_quiet; + uint8_t gps_enabled; // GPS enabled flag (0=disabled, 1=enabled) + uint32_t gps_interval; // GPS read interval in seconds + uint8_t autoadd_config; // bitmask for auto-add contacts config + uint8_t rx_boosted_gain; // SX126x RX boosted gain mode (0=power saving, 1=boosted) + uint8_t client_repeat; + uint8_t path_hash_mode; // which path mode to use when sending + uint8_t autoadd_max_hops; // 0 = no limit, 1 = direct (0 hops), N = up to N-1 hops (max 64) + char default_scope_name[31]; + uint8_t default_scope_key[16]; +}; \ No newline at end of file diff --git a/examples/beacon_sensor/main.cpp b/examples/beacon_sensor/main.cpp new file mode 100644 index 0000000..876dc9c --- /dev/null +++ b/examples/beacon_sensor/main.cpp @@ -0,0 +1,232 @@ +#include // needed for PlatformIO +#include +#include "MyMesh.h" + +// Believe it or not, this std C function is busted on some platforms! +static uint32_t _atoi(const char* sp) { + uint32_t n = 0; + while (*sp && *sp >= '0' && *sp <= '9') { + n *= 10; + n += (*sp++ - '0'); + } + return n; +} + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + #include + #if defined(QSPIFLASH) + #include + DataStore store(InternalFS, QSPIFlash, rtc_clock); + #else + #if defined(EXTRAFS) + #include + CustomLFS ExtraFS(0xD4000, 0x19000, 128); + DataStore store(InternalFS, ExtraFS, rtc_clock); + #else + DataStore store(InternalFS, rtc_clock); + #endif + #endif +#elif defined(RP2040_PLATFORM) + #include + DataStore store(LittleFS, rtc_clock); +#elif defined(ESP32) + #include + DataStore store(SPIFFS, rtc_clock); +#endif + +#ifdef ESP32 + #ifdef WIFI_SSID + #include + SerialWifiInterface serial_interface; + #ifndef TCP_PORT + #define TCP_PORT 5000 + #endif + #elif defined(BLE_PIN_CODE) + #include + SerialBLEInterface serial_interface; + #elif defined(SERIAL_RX) + #include + ArduinoSerialInterface serial_interface; + HardwareSerial companion_serial(1); + #else + #include + ArduinoSerialInterface serial_interface; + #endif +#elif defined(RP2040_PLATFORM) + //#ifdef WIFI_SSID + // #include + // SerialWifiInterface serial_interface; + // #ifndef TCP_PORT + // #define TCP_PORT 5000 + // #endif + // #elif defined(BLE_PIN_CODE) + // #include + // SerialBLEInterface serial_interface; + #if defined(SERIAL_RX) + #include + ArduinoSerialInterface serial_interface; + HardwareSerial companion_serial(1); + #else + #include + ArduinoSerialInterface serial_interface; + #endif +#elif defined(NRF52_PLATFORM) + #ifdef BLE_PIN_CODE + #include + SerialBLEInterface serial_interface; + #else + #include + ArduinoSerialInterface serial_interface; + #endif +#elif defined(STM32_PLATFORM) + #include + ArduinoSerialInterface serial_interface; +#else + #error "need to define a serial interface" +#endif + +/* GLOBAL OBJECTS */ +#ifdef DISPLAY_CLASS + #include "UITask.h" + UITask ui_task(&board, &serial_interface); +#endif + +StdRNG fast_rng; +SimpleMeshTables tables; +MyMesh the_mesh(radio_driver, fast_rng, rtc_clock, tables, store + #ifdef DISPLAY_CLASS + , &ui_task + #endif +); + +/* END GLOBAL OBJECTS */ + +void halt() { + while (1) ; +} + +void setup() { + Serial.begin(115200); + + board.begin(); + +#ifdef DISPLAY_CLASS + DisplayDriver* disp = NULL; + if (display.begin()) { + disp = &display; + disp->startFrame(); + #ifdef ST7789 + disp->setTextSize(2); + #endif + disp->drawTextCentered(disp->width() / 2, 28, "Loading..."); + disp->endFrame(); + } +#endif + + if (!radio_init()) { halt(); } + + fast_rng.begin(radio_get_rng_seed()); + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + InternalFS.begin(); + #if defined(QSPIFLASH) + if (!QSPIFlash.begin()) { + // debug output might not be available at this point, might be too early. maybe should fall back to InternalFS here? + MESH_DEBUG_PRINTLN("CustomLFS_QSPIFlash: failed to initialize"); + } else { + MESH_DEBUG_PRINTLN("CustomLFS_QSPIFlash: initialized successfully"); + } + #else + #if defined(EXTRAFS) + ExtraFS.begin(); + #endif + #endif + store.begin(); + the_mesh.begin( + #ifdef DISPLAY_CLASS + disp != NULL + #else + false + #endif + ); + +#ifdef BLE_PIN_CODE + serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); +#else + serial_interface.begin(Serial); +#endif + the_mesh.startInterface(serial_interface); +#elif defined(RP2040_PLATFORM) + LittleFS.begin(); + store.begin(); + the_mesh.begin( + #ifdef DISPLAY_CLASS + disp != NULL + #else + false + #endif + ); + + //#ifdef WIFI_SSID + // WiFi.begin(WIFI_SSID, WIFI_PWD); + // serial_interface.begin(TCP_PORT); + // #elif defined(BLE_PIN_CODE) + // char dev_name[32+16]; + // sprintf(dev_name, "%s%s", BLE_NAME_PREFIX, the_mesh.getNodeName()); + // serial_interface.begin(dev_name, the_mesh.getBLEPin()); + #if defined(SERIAL_RX) + companion_serial.setPins(SERIAL_RX, SERIAL_TX); + companion_serial.begin(115200); + serial_interface.begin(companion_serial); + #else + serial_interface.begin(Serial); + #endif + the_mesh.startInterface(serial_interface); +#elif defined(ESP32) + SPIFFS.begin(true); + store.begin(); + the_mesh.begin( + #ifdef DISPLAY_CLASS + disp != NULL + #else + false + #endif + ); + +#ifdef WIFI_SSID + board.setInhibitSleep(true); // prevent sleep when WiFi is active + WiFi.begin(WIFI_SSID, WIFI_PWD); + serial_interface.begin(TCP_PORT); +#elif defined(BLE_PIN_CODE) + serial_interface.begin(BLE_NAME_PREFIX, the_mesh.getNodePrefs()->node_name, the_mesh.getBLEPin()); +#elif defined(SERIAL_RX) + companion_serial.setPins(SERIAL_RX, SERIAL_TX); + companion_serial.begin(115200); + serial_interface.begin(companion_serial); +#else + serial_interface.begin(Serial); +#endif + the_mesh.startInterface(serial_interface); +#else + #error "need to define filesystem" +#endif + + sensors.begin(); + +#if ENV_INCLUDE_GPS == 1 + the_mesh.applyGpsPrefs(); +#endif + +#ifdef DISPLAY_CLASS + ui_task.begin(disp, &sensors, the_mesh.getNodePrefs()); // still want to pass this in as dependency, as prefs might be moved +#endif +} + +void loop() { + the_mesh.loop(); + sensors.loop(); +#ifdef DISPLAY_CLASS + ui_task.loop(); +#endif + rtc_clock.tick(); +} diff --git a/examples/beacon_sensor/ui-new/UITask.cpp b/examples/beacon_sensor/ui-new/UITask.cpp new file mode 100644 index 0000000..94a8ee3 --- /dev/null +++ b/examples/beacon_sensor/ui-new/UITask.cpp @@ -0,0 +1,923 @@ +#include "UITask.h" +#include +#include "../MyMesh.h" +#include "target.h" +#ifdef WIFI_SSID + #include +#endif + +#ifndef AUTO_OFF_MILLIS + #define AUTO_OFF_MILLIS 15000 // 15 seconds +#endif +#define BOOT_SCREEN_MILLIS 3000 // 3 seconds + +#ifdef PIN_STATUS_LED +#define LED_ON_MILLIS 20 +#define LED_ON_MSG_MILLIS 200 +#define LED_CYCLE_MILLIS 4000 +#endif + +#define LONG_PRESS_MILLIS 1200 + +#ifndef UI_RECENT_LIST_SIZE + #define UI_RECENT_LIST_SIZE 4 +#endif + +#if UI_HAS_JOYSTICK + #define PRESS_LABEL "press Enter" +#else + #define PRESS_LABEL "long press" +#endif + +#include "icons.h" + +class SplashScreen : public UIScreen { + UITask* _task; + unsigned long dismiss_after; + char _version_info[12]; + +public: + SplashScreen(UITask* task) : _task(task) { + // strip off dash and commit hash by changing dash to null terminator + // e.g: v1.2.3-abcdef -> v1.2.3 + const char *ver = FIRMWARE_VERSION; + const char *dash = strchr(ver, '-'); + + int len = dash ? dash - ver : strlen(ver); + if (len >= sizeof(_version_info)) len = sizeof(_version_info) - 1; + memcpy(_version_info, ver, len); + _version_info[len] = 0; + + dismiss_after = millis() + BOOT_SCREEN_MILLIS; + } + + int render(DisplayDriver& display) override { + // meshcore logo + display.setColor(DisplayDriver::BLUE); + int logoWidth = 128; + display.drawXbm((display.width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); + + // version info + display.setColor(DisplayDriver::LIGHT); + display.setTextSize(2); + display.drawTextCentered(display.width()/2, 22, _version_info); + + display.setTextSize(1); + display.drawTextCentered(display.width()/2, 42, FIRMWARE_BUILD_DATE); + + return 1000; + } + + void poll() override { + if (millis() >= dismiss_after) { + _task->gotoHomeScreen(); + } + } +}; + +class HomeScreen : public UIScreen { + enum HomePage { + FIRST, + RECENT, + RADIO, + BLUETOOTH, + ADVERT, +#if ENV_INCLUDE_GPS == 1 + GPS, +#endif +#if UI_SENSORS_PAGE == 1 + SENSORS, +#endif + SHUTDOWN, + Count // keep as last + }; + + UITask* _task; + mesh::RTCClock* _rtc; + SensorManager* _sensors; + NodePrefs* _node_prefs; + uint8_t _page; + bool _shutdown_init; + AdvertPath recent[UI_RECENT_LIST_SIZE]; + + + void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { + // Convert millivolts to percentage +#ifndef BATT_MIN_MILLIVOLTS + #define BATT_MIN_MILLIVOLTS 3000 +#endif +#ifndef BATT_MAX_MILLIVOLTS + #define BATT_MAX_MILLIVOLTS 4200 +#endif + const int minMilliVolts = BATT_MIN_MILLIVOLTS; + const int maxMilliVolts = BATT_MAX_MILLIVOLTS; + int batteryPercentage = ((batteryMilliVolts - minMilliVolts) * 100) / (maxMilliVolts - minMilliVolts); + if (batteryPercentage < 0) batteryPercentage = 0; // Clamp to 0% + if (batteryPercentage > 100) batteryPercentage = 100; // Clamp to 100% + + // battery icon + int iconWidth = 24; + int iconHeight = 10; + int iconX = display.width() - iconWidth - 5; // Position the icon near the top-right corner + int iconY = 0; + display.setColor(DisplayDriver::GREEN); + + // battery outline + display.drawRect(iconX, iconY, iconWidth, iconHeight); + + // battery "cap" + display.fillRect(iconX + iconWidth, iconY + (iconHeight / 4), 3, iconHeight / 2); + + // fill the battery based on the percentage + int fillWidth = (batteryPercentage * (iconWidth - 4)) / 100; + display.fillRect(iconX + 2, iconY + 2, fillWidth, iconHeight - 4); + + // show muted icon if buzzer is muted +#ifdef PIN_BUZZER + if (_task->isBuzzerQuiet()) { + display.setColor(DisplayDriver::RED); + display.drawXbm(iconX - 9, iconY + 1, muted_icon, 8, 8); + } +#endif + } + + CayenneLPP sensors_lpp; + int sensors_nb = 0; + bool sensors_scroll = false; + int sensors_scroll_offset = 0; + int next_sensors_refresh = 0; + + void refresh_sensors() { + if (millis() > next_sensors_refresh) { + sensors_lpp.reset(); + sensors_nb = 0; + sensors_lpp.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + sensors.querySensors(0xFF, sensors_lpp); + LPPReader reader (sensors_lpp.getBuffer(), sensors_lpp.getSize()); + uint8_t channel, type; + while(reader.readHeader(channel, type)) { + reader.skipData(type); + sensors_nb ++; + } + sensors_scroll = sensors_nb > UI_RECENT_LIST_SIZE; +#if AUTO_OFF_MILLIS > 0 + next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec +#else + next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min +#endif + } + } + +public: + HomeScreen(UITask* task, mesh::RTCClock* rtc, SensorManager* sensors, NodePrefs* node_prefs) + : _task(task), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _page(0), + _shutdown_init(false), sensors_lpp(200) { } + + void poll() override { + if (_shutdown_init && !_task->isButtonPressed()) { // must wait for USR button to be released + _task->shutdown(); + } + } + + int render(DisplayDriver& display) override { + char tmp[80]; + // node name + display.setTextSize(1); + display.setColor(DisplayDriver::GREEN); + char filtered_name[sizeof(_node_prefs->node_name)]; + display.translateUTF8ToBlocks(filtered_name, _node_prefs->node_name, sizeof(filtered_name)); + display.setCursor(0, 0); + display.print(filtered_name); + + // battery voltage + renderBatteryIndicator(display, _task->getBattMilliVolts()); + + // curr page indicator + int y = 14; + int x = display.width() / 2 - 5 * (HomePage::Count-1); + for (uint8_t i = 0; i < HomePage::Count; i++, x += 10) { + if (i == _page) { + display.fillRect(x-1, y-1, 3, 3); + } else { + display.fillRect(x, y, 1, 1); + } + } + + if (_page == HomePage::FIRST) { + display.setColor(DisplayDriver::YELLOW); + display.setTextSize(2); + sprintf(tmp, "MSG: %d", _task->getMsgCount()); + display.drawTextCentered(display.width() / 2, 20, tmp); + + #ifdef WIFI_SSID + IPAddress ip = WiFi.localIP(); + snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 54, tmp); + #endif + if (_task->hasConnection()) { + display.setColor(DisplayDriver::GREEN); + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 43, "< Connected >"); + + } else if (the_mesh.getBLEPin() != 0) { // BT pin + display.setColor(DisplayDriver::RED); + display.setTextSize(2); + sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); + display.drawTextCentered(display.width() / 2, 43, tmp); + } + } else if (_page == HomePage::RECENT) { + the_mesh.getRecentlyHeard(recent, UI_RECENT_LIST_SIZE); + display.setColor(DisplayDriver::GREEN); + int y = 20; + for (int i = 0; i < UI_RECENT_LIST_SIZE; i++, y += 11) { + auto a = &recent[i]; + if (a->name[0] == 0) continue; // empty slot + int secs = _rtc->getCurrentTime() - a->recv_timestamp; + if (secs < 60) { + sprintf(tmp, "%ds", secs); + } else if (secs < 60*60) { + sprintf(tmp, "%dm", secs / 60); + } else { + sprintf(tmp, "%dh", secs / (60*60)); + } + + int timestamp_width = display.getTextWidth(tmp); + int max_name_width = display.width() - timestamp_width - 1; + + char filtered_recent_name[sizeof(a->name)]; + display.translateUTF8ToBlocks(filtered_recent_name, a->name, sizeof(filtered_recent_name)); + display.drawTextEllipsized(0, y, max_name_width, filtered_recent_name); + display.setCursor(display.width() - timestamp_width - 1, y); + display.print(tmp); + } + } else if (_page == HomePage::RADIO) { + display.setColor(DisplayDriver::YELLOW); + display.setTextSize(1); + // freq / sf + display.setCursor(0, 20); + sprintf(tmp, "FQ: %06.3f SF: %d", _node_prefs->freq, _node_prefs->sf); + display.print(tmp); + + display.setCursor(0, 31); + sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); + display.print(tmp); + + // tx power, noise floor + display.setCursor(0, 42); + sprintf(tmp, "TX: %ddBm", _node_prefs->tx_power_dbm); + display.print(tmp); + display.setCursor(0, 53); + sprintf(tmp, "Noise floor: %d", radio_driver.getNoiseFloor()); + display.print(tmp); + } else if (_page == HomePage::BLUETOOTH) { + display.setColor(DisplayDriver::GREEN); + display.drawXbm((display.width() - 32) / 2, 18, + _task->isSerialEnabled() ? bluetooth_on : bluetooth_off, + 32, 32); + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL); + } else if (_page == HomePage::ADVERT) { + display.setColor(DisplayDriver::GREEN); + display.drawXbm((display.width() - 32) / 2, 18, advert_icon, 32, 32); + display.drawTextCentered(display.width() / 2, 64 - 11, "advert: " PRESS_LABEL); +#if ENV_INCLUDE_GPS == 1 + } else if (_page == HomePage::GPS) { + LocationProvider* nmea = sensors.getLocationProvider(); + char buf[50]; + int y = 18; + bool gps_state = _task->getGPSState(); +#ifdef PIN_GPS_SWITCH + bool hw_gps_state = digitalRead(PIN_GPS_SWITCH); + if (gps_state != hw_gps_state) { + strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); + } else { + strcpy(buf, gps_state ? "gps on" : "gps off"); + } +#else + strcpy(buf, gps_state ? "gps on" : "gps off"); +#endif + display.drawTextLeftAlign(0, y, buf); + if (nmea == NULL) { + y = y + 12; + display.drawTextLeftAlign(0, y, "Can't access GPS"); + } else { + strcpy(buf, nmea->isValid()?"fix":"no fix"); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + display.drawTextLeftAlign(0, y, "sat"); + sprintf(buf, "%d", nmea->satellitesCount()); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + display.drawTextLeftAlign(0, y, "pos"); + sprintf(buf, "%.4f %.4f", + nmea->getLatitude()/1000000., nmea->getLongitude()/1000000.); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + display.drawTextLeftAlign(0, y, "alt"); + sprintf(buf, "%.2f", nmea->getAltitude()/1000.); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + } +#endif +#if UI_SENSORS_PAGE == 1 + } else if (_page == HomePage::SENSORS) { + int y = 18; + refresh_sensors(); + char buf[30]; + char name[30]; + LPPReader r(sensors_lpp.getBuffer(), sensors_lpp.getSize()); + + for (int i = 0; i < sensors_scroll_offset; i++) { + uint8_t channel, type; + r.readHeader(channel, type); + r.skipData(type); + } + + for (int i = 0; i < (sensors_scroll?UI_RECENT_LIST_SIZE:sensors_nb); i++) { + uint8_t channel, type; + if (!r.readHeader(channel, type)) { // reached end, reset + r.reset(); + r.readHeader(channel, type); + } + + display.setCursor(0, y); + float v; + switch (type) { + case LPP_GPS: // GPS + float lat, lon, alt; + r.readGPS(lat, lon, alt); + strcpy(name, "gps"); sprintf(buf, "%.4f %.4f", lat, lon); + break; + case LPP_VOLTAGE: + r.readVoltage(v); + strcpy(name, "voltage"); sprintf(buf, "%6.2f", v); + break; + case LPP_CURRENT: + r.readCurrent(v); + strcpy(name, "current"); sprintf(buf, "%.3f", v); + break; + case LPP_TEMPERATURE: + r.readTemperature(v); + strcpy(name, "temperature"); sprintf(buf, "%.2f", v); + break; + case LPP_RELATIVE_HUMIDITY: + r.readRelativeHumidity(v); + strcpy(name, "humidity"); sprintf(buf, "%.2f", v); + break; + case LPP_BAROMETRIC_PRESSURE: + r.readPressure(v); + strcpy(name, "pressure"); sprintf(buf, "%.2f", v); + break; + case LPP_ALTITUDE: + r.readAltitude(v); + strcpy(name, "altitude"); sprintf(buf, "%.0f", v); + break; + case LPP_POWER: + r.readPower(v); + strcpy(name, "power"); sprintf(buf, "%6.2f", v); + break; + default: + r.skipData(type); + strcpy(name, "unk"); sprintf(buf, ""); + } + display.setCursor(0, y); + display.print(name); + display.setCursor( + display.width()-display.getTextWidth(buf)-1, y + ); + display.print(buf); + y = y + 12; + } + if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; + else sensors_scroll_offset = 0; +#endif + } else if (_page == HomePage::SHUTDOWN) { + display.setColor(DisplayDriver::GREEN); + display.setTextSize(1); + if (_shutdown_init) { + display.drawTextCentered(display.width() / 2, 34, "hibernating..."); + } else { + display.drawXbm((display.width() - 32) / 2, 18, power_icon, 32, 32); + display.drawTextCentered(display.width() / 2, 64 - 11, "hibernate:" PRESS_LABEL); + } + } + return 5000; // next render after 5000 ms + } + + bool handleInput(char c) override { + if (c == KEY_LEFT || c == KEY_PREV) { + _page = (_page + HomePage::Count - 1) % HomePage::Count; + return true; + } + if (c == KEY_NEXT || c == KEY_RIGHT) { + _page = (_page + 1) % HomePage::Count; + if (_page == HomePage::RECENT) { + _task->showAlert("Recent adverts", 800); + } + return true; + } + if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { + if (_task->isSerialEnabled()) { // toggle Bluetooth on/off + _task->disableSerial(); + } else { + _task->enableSerial(); + } + return true; + } + if (c == KEY_ENTER && _page == HomePage::ADVERT) { + _task->notify(UIEventType::ack); + if (the_mesh.advert()) { + _task->showAlert("Advert sent!", 1000); + } else { + _task->showAlert("Advert failed..", 1000); + } + return true; + } +#if ENV_INCLUDE_GPS == 1 + if (c == KEY_ENTER && _page == HomePage::GPS) { + _task->toggleGPS(); + return true; + } +#endif +#if UI_SENSORS_PAGE == 1 + if (c == KEY_ENTER && _page == HomePage::SENSORS) { + _task->toggleGPS(); + next_sensors_refresh=0; + return true; + } +#endif + if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) { + _shutdown_init = true; // need to wait for button to be released + return true; + } + return false; + } +}; + +class MsgPreviewScreen : public UIScreen { + UITask* _task; + mesh::RTCClock* _rtc; + + struct MsgEntry { + uint32_t timestamp; + char origin[62]; + char msg[78]; + }; + #define MAX_UNREAD_MSGS 32 + int num_unread; + int head = MAX_UNREAD_MSGS - 1; // index of latest unread message + MsgEntry unread[MAX_UNREAD_MSGS]; + +public: + MsgPreviewScreen(UITask* task, mesh::RTCClock* rtc) : _task(task), _rtc(rtc) { num_unread = 0; } + + void addPreview(uint8_t path_len, const char* from_name, const char* msg) { + head = (head + 1) % MAX_UNREAD_MSGS; + if (num_unread < MAX_UNREAD_MSGS) num_unread++; + + auto p = &unread[head]; + p->timestamp = _rtc->getCurrentTime(); + if (path_len == 0xFF) { + sprintf(p->origin, "(D) %s:", from_name); + } else { + sprintf(p->origin, "(%d) %s:", (uint32_t) path_len, from_name); + } + StrHelper::strncpy(p->msg, msg, sizeof(p->msg)); + } + + int render(DisplayDriver& display) override { + char tmp[16]; + display.setCursor(0, 0); + display.setTextSize(1); + display.setColor(DisplayDriver::GREEN); + sprintf(tmp, "Unread: %d", num_unread); + display.print(tmp); + + auto p = &unread[head]; + + int secs = _rtc->getCurrentTime() - p->timestamp; + if (secs < 60) { + sprintf(tmp, "%ds", secs); + } else if (secs < 60*60) { + sprintf(tmp, "%dm", secs / 60); + } else { + sprintf(tmp, "%dh", secs / (60*60)); + } + display.setCursor(display.width() - display.getTextWidth(tmp) - 2, 0); + display.print(tmp); + + display.drawRect(0, 11, display.width(), 1); // horiz line + + display.setCursor(0, 14); + display.setColor(DisplayDriver::YELLOW); + char filtered_origin[sizeof(p->origin)]; + display.translateUTF8ToBlocks(filtered_origin, p->origin, sizeof(filtered_origin)); + display.print(filtered_origin); + + display.setCursor(0, 25); + display.setColor(DisplayDriver::LIGHT); + char filtered_msg[sizeof(p->msg)]; + display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg)); + display.printWordWrap(filtered_msg, display.width()); + +#if AUTO_OFF_MILLIS==0 // probably e-ink + return 10000; // 10 s +#else + return 1000; // next render after 1000 ms +#endif + } + + bool handleInput(char c) override { + if (c == KEY_NEXT || c == KEY_RIGHT) { + head = (head + MAX_UNREAD_MSGS - 1) % MAX_UNREAD_MSGS; + num_unread--; + if (num_unread == 0) { + _task->gotoHomeScreen(); + } + return true; + } + if (c == KEY_ENTER) { + num_unread = 0; // clear unread queue + _task->gotoHomeScreen(); + return true; + } + return false; + } +}; + +void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs) { + _display = display; + _sensors = sensors; + _auto_off = millis() + AUTO_OFF_MILLIS; + +#if defined(PIN_USER_BTN) + user_btn.begin(); +#endif +#if defined(PIN_USER_BTN_ANA) + analog_btn.begin(); +#endif + + _node_prefs = node_prefs; + + if (_display != NULL) { + _display->turnOn(); + } + +#ifdef PIN_BUZZER + buzzer.begin(); + buzzer.quiet(_node_prefs->buzzer_quiet); +#endif + +#ifdef PIN_VIBRATION + vibration.begin(); +#endif + + ui_started_at = millis(); + _alert_expiry = 0; + + splash = new SplashScreen(this); + home = new HomeScreen(this, &rtc_clock, sensors, node_prefs); + msg_preview = new MsgPreviewScreen(this, &rtc_clock); + setCurrScreen(splash); +} + +void UITask::showAlert(const char* text, int duration_millis) { + strcpy(_alert, text); + _alert_expiry = millis() + duration_millis; +} + +void UITask::notify(UIEventType t) { +#if defined(PIN_BUZZER) +switch(t){ + case UIEventType::contactMessage: + // gemini's pick + buzzer.play("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); + break; + case UIEventType::channelMessage: + buzzer.play("kerplop:d=16,o=6,b=120:32g#,32c#"); + break; + case UIEventType::ack: + buzzer.play("ack:d=32,o=8,b=120:c"); + break; + case UIEventType::roomMessage: + case UIEventType::newContactMessage: + case UIEventType::none: + default: + break; +} +#endif + +#ifdef PIN_VIBRATION + // Trigger vibration for all UI events except none + if (t != UIEventType::none) { + vibration.trigger(); + } +#endif +} + + +void UITask::msgRead(int msgcount) { + _msgcount = msgcount; + if (msgcount == 0) { + gotoHomeScreen(); + } +} + +void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) { + _msgcount = msgcount; + + ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, from_name, text); + setCurrScreen(msg_preview); + + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(); + } + if (_display->isOn()) { + _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + } + } +} + +void UITask::userLedHandler() { +#ifdef PIN_STATUS_LED + int cur_time = millis(); + if (cur_time > next_led_change) { + if (led_state == 0) { + led_state = 1; + if (_msgcount > 0) { + last_led_increment = LED_ON_MSG_MILLIS; + } else { + last_led_increment = LED_ON_MILLIS; + } + next_led_change = cur_time + last_led_increment; + } else { + led_state = 0; + next_led_change = cur_time + LED_CYCLE_MILLIS - last_led_increment; + } + digitalWrite(PIN_STATUS_LED, led_state == LED_STATE_ON); + } +#endif +} + +void UITask::setCurrScreen(UIScreen* c) { + curr = c; + _next_refresh = 100; +} + +/* + hardware-agnostic pre-shutdown activity should be done here +*/ +void UITask::shutdown(bool restart){ + + #ifdef PIN_BUZZER + /* note: we have a choice here - + we can do a blocking buzzer.loop() with non-deterministic consequences + or we can set a flag and delay the shutdown for a couple of seconds + while a non-blocking buzzer.loop() plays out in UITask::loop() + */ + buzzer.shutdown(); + uint32_t buzzer_timer = millis(); // fail-safe shutdown + while (buzzer.isPlaying() && (millis() - 2500) < buzzer_timer) + buzzer.loop(); + + #endif // PIN_BUZZER + + if (restart) { + _board->reboot(); + } else { + _display->turnOff(); + radio_driver.powerOff(); + _board->powerOff(); + } +} + +bool UITask::isButtonPressed() const { +#ifdef PIN_USER_BTN + return user_btn.isPressed(); +#else + return false; +#endif +} + +void UITask::loop() { + char c = 0; +#if UI_HAS_JOYSTICK + int ev = user_btn.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_ENTER); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_ENTER); // REVISIT: could be mapped to different key code + } + ev = joystick_left.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_LEFT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_LEFT); + } + ev = joystick_right.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_RIGHT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_RIGHT); + } + ev = back_btn.check(); + if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } +#elif defined(PIN_USER_BTN) + int ev = user_btn.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_NEXT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_ENTER); + } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { + c = handleDoubleClick(KEY_PREV); + } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } +#endif +#if defined(PIN_USER_BTN_ANA) + if (abs(millis() - _analogue_pin_read_millis) > 10) { + ev = analog_btn.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_NEXT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_ENTER); + } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { + c = handleDoubleClick(KEY_PREV); + } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } + _analogue_pin_read_millis = millis(); + } +#endif +#if defined(BACKLIGHT_BTN) + if (millis() > next_backlight_btn_check) { + bool touch_state = digitalRead(PIN_BUTTON2); +#if defined(DISP_BACKLIGHT) + digitalWrite(DISP_BACKLIGHT, !touch_state); +#elif defined(EXP_PIN_BACKLIGHT) + expander.digitalWrite(EXP_PIN_BACKLIGHT, !touch_state); +#endif + next_backlight_btn_check = millis() + 300; + } +#endif + + if (c != 0 && curr) { + curr->handleInput(c); + _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + _next_refresh = 100; // trigger refresh + } + + userLedHandler(); + +#ifdef PIN_BUZZER + if (buzzer.isPlaying()) buzzer.loop(); +#endif + + if (curr) curr->poll(); + + if (_display != NULL && _display->isOn()) { + if (millis() >= _next_refresh && curr) { + _display->startFrame(); + int delay_millis = curr->render(*_display); + if (millis() < _alert_expiry) { // render alert popup + _display->setTextSize(1); + int y = _display->height() / 3; + int p = _display->height() / 32; + _display->setColor(DisplayDriver::DARK); + _display->fillRect(p, y, _display->width() - p*2, y); + _display->setColor(DisplayDriver::LIGHT); // draw box border + _display->drawRect(p, y, _display->width() - p*2, y); + _display->drawTextCentered(_display->width() / 2, y + p*3, _alert); + _next_refresh = _alert_expiry; // will need refresh when alert is dismissed + } else { + _next_refresh = millis() + delay_millis; + } + _display->endFrame(); + } +#if AUTO_OFF_MILLIS > 0 + if (millis() > _auto_off) { + _display->turnOff(); + } +#endif + } + +#ifdef PIN_VIBRATION + vibration.loop(); +#endif + +#ifdef AUTO_SHUTDOWN_MILLIVOLTS + if (millis() > next_batt_chck) { + uint16_t milliVolts = getBattMilliVolts(); + if (milliVolts > 0 && milliVolts < AUTO_SHUTDOWN_MILLIVOLTS) { + + // show low battery shutdown alert + // we should only do this for eink displays, which will persist after power loss + #if defined(THINKNODE_M1) || defined(LILYGO_TECHO) + if (_display != NULL) { + _display->startFrame(); + _display->setTextSize(2); + _display->setColor(DisplayDriver::RED); + _display->drawTextCentered(_display->width() / 2, 20, "Low Battery."); + _display->drawTextCentered(_display->width() / 2, 40, "Shutting Down!"); + _display->endFrame(); + } + #endif + + shutdown(); + + } + next_batt_chck = millis() + 8000; + } +#endif +} + +char UITask::checkDisplayOn(char c) { + if (_display != NULL) { + if (!_display->isOn()) { + _display->turnOn(); // turn display on and consume event + c = 0; + } + _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + _next_refresh = 0; // trigger refresh + } + return c; +} + +char UITask::handleLongPress(char c) { + if (millis() - ui_started_at < 8000) { // long press in first 8 seconds since startup -> CLI/rescue + the_mesh.enterCLIRescue(); + c = 0; // consume event + } + return c; +} + +char UITask::handleDoubleClick(char c) { + MESH_DEBUG_PRINTLN("UITask: double click triggered"); + checkDisplayOn(c); + return c; +} + +char UITask::handleTripleClick(char c) { + MESH_DEBUG_PRINTLN("UITask: triple click triggered"); + checkDisplayOn(c); + toggleBuzzer(); + c = 0; + return c; +} + +bool UITask::getGPSState() { + if (_sensors != NULL) { + int num = _sensors->getNumSettings(); + for (int i = 0; i < num; i++) { + if (strcmp(_sensors->getSettingName(i), "gps") == 0) { + return !strcmp(_sensors->getSettingValue(i), "1"); + } + } + } + return false; +} + +void UITask::toggleGPS() { + if (_sensors != NULL) { + // toggle GPS on/off + int num = _sensors->getNumSettings(); + for (int i = 0; i < num; i++) { + if (strcmp(_sensors->getSettingName(i), "gps") == 0) { + if (strcmp(_sensors->getSettingValue(i), "1") == 0) { + _sensors->setSettingValue("gps", "0"); + _node_prefs->gps_enabled = 0; + notify(UIEventType::ack); + } else { + _sensors->setSettingValue("gps", "1"); + _node_prefs->gps_enabled = 1; + notify(UIEventType::ack); + } + the_mesh.savePrefs(); + showAlert(_node_prefs->gps_enabled ? "GPS: Enabled" : "GPS: Disabled", 800); + _next_refresh = 0; + break; + } + } + } +} + +void UITask::toggleBuzzer() { + // Toggle buzzer quiet mode + #ifdef PIN_BUZZER + if (buzzer.isQuiet()) { + buzzer.quiet(false); + notify(UIEventType::ack); + } else { + buzzer.quiet(true); + } + _node_prefs->buzzer_quiet = buzzer.isQuiet(); + the_mesh.savePrefs(); + showAlert(buzzer.isQuiet() ? "Buzzer: OFF" : "Buzzer: ON", 800); + _next_refresh = 0; // trigger refresh + #endif +} diff --git a/examples/beacon_sensor/ui-new/UITask.h b/examples/beacon_sensor/ui-new/UITask.h new file mode 100644 index 0000000..a77ad6e --- /dev/null +++ b/examples/beacon_sensor/ui-new/UITask.h @@ -0,0 +1,101 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#ifndef LED_STATE_ON + #define LED_STATE_ON 1 +#endif + +#ifdef PIN_BUZZER + #include +#endif +#ifdef PIN_VIBRATION + #include +#endif + +#include "../AbstractUITask.h" +#include "../NodePrefs.h" + +class UITask : public AbstractUITask { + DisplayDriver* _display; + SensorManager* _sensors; +#ifdef PIN_BUZZER + genericBuzzer buzzer; +#endif +#ifdef PIN_VIBRATION + GenericVibration vibration; +#endif + unsigned long _next_refresh, _auto_off; + NodePrefs* _node_prefs; + char _alert[80]; + unsigned long _alert_expiry; + int _msgcount; + unsigned long ui_started_at, next_batt_chck; + int next_backlight_btn_check = 0; +#ifdef PIN_STATUS_LED + int led_state = 0; + int next_led_change = 0; + int last_led_increment = 0; +#endif + +#ifdef PIN_USER_BTN_ANA + unsigned long _analogue_pin_read_millis = millis(); +#endif + + UIScreen* splash; + UIScreen* home; + UIScreen* msg_preview; + UIScreen* curr; + + void userLedHandler(); + + // Button action handlers + char checkDisplayOn(char c); + char handleLongPress(char c); + char handleDoubleClick(char c); + char handleTripleClick(char c); + + void setCurrScreen(UIScreen* c); + +public: + + UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { + next_batt_chck = _next_refresh = 0; + ui_started_at = 0; + curr = NULL; + } + void begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs); + + void gotoHomeScreen() { setCurrScreen(home); } + void showAlert(const char* text, int duration_millis); + int getMsgCount() const { return _msgcount; } + bool hasDisplay() const { return _display != NULL; } + bool isButtonPressed() const; + + bool isBuzzerQuiet() { +#ifdef PIN_BUZZER + return buzzer.isQuiet(); +#else + return true; +#endif + } + + void toggleBuzzer(); + bool getGPSState(); + void toggleGPS(); + + + // from AbstractUITask + void msgRead(int msgcount) override; + void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override; + void notify(UIEventType t = UIEventType::none) override; + void loop() override; + + void shutdown(bool restart = false); +}; diff --git a/examples/beacon_sensor/ui-new/icons.h b/examples/beacon_sensor/ui-new/icons.h new file mode 100644 index 0000000..cbe2379 --- /dev/null +++ b/examples/beacon_sensor/ui-new/icons.h @@ -0,0 +1,122 @@ +#pragma once + +#include + +// 'meshcore', 128x13px +static const uint8_t meshcore_logo [] = { + 0x3c, 0x01, 0xe3, 0xff, 0xc7, 0xff, 0x8f, 0x03, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, + 0x3c, 0x03, 0xe3, 0xff, 0xc7, 0xff, 0x8e, 0x03, 0x8f, 0xfe, 0x3f, 0xfe, 0x1f, 0xff, 0x1f, 0xfe, + 0x3e, 0x03, 0xc3, 0xff, 0x8f, 0xff, 0x0e, 0x07, 0x8f, 0xfe, 0x7f, 0xfe, 0x1f, 0xff, 0x1f, 0xfc, + 0x3e, 0x07, 0xc7, 0x80, 0x0e, 0x00, 0x0e, 0x07, 0x9e, 0x00, 0x78, 0x0e, 0x3c, 0x0f, 0x1c, 0x00, + 0x3e, 0x0f, 0xc7, 0x80, 0x1e, 0x00, 0x0e, 0x07, 0x1e, 0x00, 0x70, 0x0e, 0x38, 0x0f, 0x3c, 0x00, + 0x7f, 0x0f, 0xc7, 0xfe, 0x1f, 0xfc, 0x1f, 0xff, 0x1c, 0x00, 0x70, 0x0e, 0x38, 0x0e, 0x3f, 0xf8, + 0x7f, 0x1f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x0e, 0x38, 0x0e, 0x3f, 0xf8, + 0x7f, 0x3f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x1e, 0x3f, 0xfe, 0x3f, 0xf0, + 0x77, 0x3b, 0x87, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xfc, 0x38, 0x00, + 0x77, 0xfb, 0x8f, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xf8, 0x38, 0x00, + 0x73, 0xf3, 0x8f, 0xff, 0x0f, 0xff, 0x1c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x78, 0x7f, 0xf8, + 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfe, 0x3c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x3c, 0x7f, 0xf8, + 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfc, 0x3c, 0x0e, 0x1f, 0xf8, 0xff, 0xf8, 0x70, 0x3c, 0x7f, 0xf8, +}; + +static const uint8_t bluetooth_on[] = { + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x30, 0x00, 0x00, + 0x00, 0x3C, 0x00, 0x00, + 0x00, 0x3E, 0x00, 0x00, + 0x00, 0x3F, 0x80, 0x00, + 0x00, 0x3F, 0xC0, 0x00, + 0x00, 0x3B, 0xE0, 0x00, + 0x30, 0x38, 0xF8, 0x00, + 0x3C, 0x38, 0x7C, 0x00, + 0x3E, 0x38, 0x7C, 0x00, + 0x1F, 0xB8, 0xF8, 0x70, + 0x07, 0xF9, 0xF0, 0x78, + 0x03, 0xFF, 0xC0, 0x78, + 0x00, 0xFF, 0x80, 0x3C, + 0x00, 0x7F, 0x07, 0x1C, + 0x00, 0x7E, 0x07, 0x1C, + 0x03, 0xFF, 0x82, 0x1C, + 0x03, 0xFF, 0xC0, 0x78, + 0x07, 0xFB, 0xE0, 0x78, + 0x0F, 0xB8, 0xF8, 0x70, + 0x3E, 0x38, 0x7C, 0x00, + 0x3C, 0x38, 0x7C, 0x00, + 0x38, 0x38, 0xF8, 0x00, + 0x00, 0x39, 0xF0, 0x00, + 0x00, 0x3F, 0xC0, 0x00, + 0x00, 0x3F, 0x80, 0x00, + 0x00, 0x3E, 0x00, 0x00, + 0x00, 0x3C, 0x00, 0x00, + 0x00, 0x38, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, +}; + +static const uint8_t bluetooth_off[] = { + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x03, 0x80, 0x00, + 0x00, 0x03, 0xC0, 0x00, + 0x00, 0x03, 0xE0, 0x00, + 0x38, 0x03, 0xF8, 0x00, + 0x3C, 0x03, 0xFC, 0x00, + 0x3E, 0x03, 0xBF, 0x00, + 0x0F, 0x83, 0x8F, 0x80, + 0x07, 0xC3, 0x87, 0xC0, + 0x03, 0xF0, 0x03, 0xC0, + 0x00, 0xF8, 0x0F, 0x80, + 0x00, 0x7C, 0x0F, 0x00, + 0x00, 0x1F, 0x0E, 0x00, + 0x00, 0x0F, 0x80, 0x00, + 0x00, 0x07, 0xE0, 0x00, + 0x00, 0x07, 0xF0, 0x00, + 0x00, 0x0F, 0xF8, 0x00, + 0x00, 0x3F, 0xBE, 0x00, + 0x00, 0x7F, 0x9F, 0x00, + 0x00, 0xFB, 0x8F, 0xC0, + 0x03, 0xE3, 0x83, 0xE0, + 0x03, 0xC3, 0x87, 0xF0, + 0x03, 0x83, 0x8F, 0xFC, + 0x00, 0x03, 0xBF, 0x3C, + 0x00, 0x03, 0xFC, 0x1C, + 0x00, 0x03, 0xF8, 0x00, + 0x00, 0x03, 0xE0, 0x00, + 0x00, 0x03, 0xC0, 0x00, + 0x00, 0x03, 0x80, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, +}; + +static const uint8_t power_icon[] = { + 0x00, 0x01, 0x80, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x03, 0xC0, 0x00, + 0x00, 0x33, 0xCC, 0x00, 0x00, 0xF3, 0xCF, 0x00, 0x01, 0xF3, 0xCF, 0x80, + 0x03, 0xF3, 0xCF, 0xC0, 0x07, 0xF3, 0xCF, 0xE0, 0x0F, 0xE3, 0xC7, 0xF0, + 0x1F, 0xC3, 0xC3, 0xF8, 0x1F, 0x83, 0xC1, 0xF8, 0x3F, 0x03, 0xC0, 0xFC, + 0x3E, 0x03, 0xC0, 0x7C, 0x3E, 0x03, 0xC0, 0x7C, 0x7E, 0x01, 0x80, 0x7E, + 0x7C, 0x00, 0x00, 0x3E, 0x7C, 0x00, 0x00, 0x3E, 0x7C, 0x00, 0x00, 0x3E, + 0x7C, 0x00, 0x00, 0x3E, 0x7C, 0x00, 0x00, 0x3E, 0x3E, 0x00, 0x00, 0x7C, + 0x3E, 0x00, 0x00, 0x7C, 0x3F, 0x00, 0x00, 0xFC, 0x1F, 0x80, 0x01, 0xF8, + 0x1F, 0xC0, 0x03, 0xF8, 0x0F, 0xE0, 0x07, 0xF0, 0x0F, 0xF8, 0x1F, 0xF0, + 0x07, 0xFF, 0xFF, 0xE0, 0x03, 0xFF, 0xFF, 0xC0, 0x00, 0xFF, 0xFF, 0x00, + 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x0F, 0xF0, 0x00, +}; + +static const uint8_t advert_icon[] = { +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x30, +0x1C, 0x00, 0x00, 0x38, 0x18, 0x00, 0x00, 0x18, 0x30, 0x00, 0x00, 0x0C, +0x30, 0x60, 0x06, 0x0C, 0x60, 0xE0, 0x07, 0x06, 0x61, 0xC0, 0x03, 0x86, +0xE1, 0x81, 0x81, 0x87, 0xC3, 0x07, 0xE0, 0xC3, 0xC3, 0x0F, 0xF0, 0xC3, +0xC3, 0x0F, 0xF0, 0xC3, 0xC3, 0x0F, 0xF0, 0xC3, 0xC3, 0x0F, 0xF0, 0xC3, +0xC3, 0x07, 0xE0, 0xC3, 0xC1, 0x83, 0xC1, 0x83, 0x61, 0x80, 0x01, 0x86, +0x60, 0xC0, 0x03, 0x06, 0x70, 0xE0, 0x07, 0x0E, 0x30, 0x40, 0x02, 0x0C, +0x38, 0x00, 0x00, 0x1C, 0x18, 0x00, 0x00, 0x18, 0x0C, 0x00, 0x00, 0x30, +0x04, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + +static const uint8_t muted_icon[] = { + 0x20, 0x6a, 0xea, 0xe4, 0xe4, 0xea, 0x6a, 0x20 +}; \ No newline at end of file diff --git a/examples/beacon_sensor/ui-orig/Button.cpp b/examples/beacon_sensor/ui-orig/Button.cpp new file mode 100644 index 0000000..f9e83db --- /dev/null +++ b/examples/beacon_sensor/ui-orig/Button.cpp @@ -0,0 +1,131 @@ +#include "Button.h" + +Button::Button(uint8_t pin, bool activeState) + : _pin(pin), _activeState(activeState), _isAnalog(false), _analogThreshold(20) { + _currentState = false; // Initialize as not pressed + _lastState = _currentState; +} + +Button::Button(uint8_t pin, bool activeState, bool isAnalog, uint16_t analogThreshold) + : _pin(pin), _activeState(activeState), _isAnalog(isAnalog), _analogThreshold(analogThreshold) { + _currentState = false; // Initialize as not pressed + _lastState = _currentState; +} + +void Button::begin() { + _currentState = readButton(); + _lastState = _currentState; +} + +void Button::update() { + uint32_t now = millis(); + + // Read button at specified interval + if (now - _lastReadTime < BUTTON_READ_INTERVAL_MS) { + return; + } + _lastReadTime = now; + + bool newState = readButton(); + + // Check if state has changed + if (newState != _lastState) { + _stateChangeTime = now; + } + + // Debounce check + if ((now - _stateChangeTime) > BUTTON_DEBOUNCE_TIME_MS) { + if (newState != _currentState) { + _currentState = newState; + handleStateChange(); + } + } + + _lastState = newState; + + // Handle multi-click timeout + if (_state == WAITING_FOR_MULTI_CLICK && (now - _releaseTime) > BUTTON_CLICK_TIMEOUT_MS) { + // Timeout reached, process the clicks + if (_clickCount == 1) { + triggerEvent(SHORT_PRESS); + } else if (_clickCount == 2) { + triggerEvent(DOUBLE_PRESS); + } else if (_clickCount == 3) { + triggerEvent(TRIPLE_PRESS); + } else if (_clickCount >= 4) { + triggerEvent(QUADRUPLE_PRESS); + } + + _clickCount = 0; + _state = IDLE; + } + + // Handle long press while button is held + if (_state == PRESSED && (now - _pressTime) > BUTTON_LONG_PRESS_TIME_MS) { + triggerEvent(LONG_PRESS); + _state = IDLE; // Prevent multiple press events + _clickCount = 0; + } +} + +bool Button::readButton() { + if (_isAnalog) { + return (analogRead(_pin) < _analogThreshold); + } else { + return (digitalRead(_pin) == _activeState); + } +} + +void Button::handleStateChange() { + uint32_t now = millis(); + + if (_currentState) { + // Button pressed + _pressTime = now; + _state = PRESSED; + triggerEvent(ANY_PRESS); + } else { + // Button released + if (_state == PRESSED) { + uint32_t pressDuration = now - _pressTime; + + if (pressDuration < BUTTON_LONG_PRESS_TIME_MS) { + // Short press detected + _clickCount++; + _releaseTime = now; + _state = WAITING_FOR_MULTI_CLICK; + } else { + // Long press already handled in update() + _state = IDLE; + _clickCount = 0; + } + } + } +} + +void Button::triggerEvent(EventType event) { + _lastEvent = event; + + switch (event) { + case ANY_PRESS: + if (_onAnyPress) _onAnyPress(); + break; + case SHORT_PRESS: + if (_onShortPress) _onShortPress(); + break; + case DOUBLE_PRESS: + if (_onDoublePress) _onDoublePress(); + break; + case TRIPLE_PRESS: + if (_onTriplePress) _onTriplePress(); + break; + case QUADRUPLE_PRESS: + if (_onQuadruplePress) _onQuadruplePress(); + break; + case LONG_PRESS: + if (_onLongPress) _onLongPress(); + break; + default: + break; + } +} \ No newline at end of file diff --git a/examples/beacon_sensor/ui-orig/Button.h b/examples/beacon_sensor/ui-orig/Button.h new file mode 100644 index 0000000..9df809b --- /dev/null +++ b/examples/beacon_sensor/ui-orig/Button.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include + +// Button timing configuration +#define BUTTON_DEBOUNCE_TIME_MS 50 // Debounce time in ms +#define BUTTON_CLICK_TIMEOUT_MS 500 // Max time between clicks for multi-click +#define BUTTON_LONG_PRESS_TIME_MS 3000 // Time to trigger long press (3 seconds) +#define BUTTON_READ_INTERVAL_MS 10 // How often to read the button + +class Button { +public: + enum EventType { + NONE, + SHORT_PRESS, + DOUBLE_PRESS, + TRIPLE_PRESS, + QUADRUPLE_PRESS, + LONG_PRESS, + ANY_PRESS + }; + + using EventCallback = std::function; + + Button(uint8_t pin, bool activeState = LOW); + Button(uint8_t pin, bool activeState, bool isAnalog, uint16_t analogThreshold = 20); + + void begin(); + void update(); + + // Set callbacks for different events + void onShortPress(EventCallback callback) { _onShortPress = callback; } + void onDoublePress(EventCallback callback) { _onDoublePress = callback; } + void onTriplePress(EventCallback callback) { _onTriplePress = callback; } + void onQuadruplePress(EventCallback callback) { _onQuadruplePress = callback; } + void onLongPress(EventCallback callback) { _onLongPress = callback; } + void onAnyPress(EventCallback callback) { _onAnyPress = callback; } + + // State getters + bool isPressed() const { return _currentState; } + EventType getLastEvent() const { return _lastEvent; } + +private: + enum State { + IDLE, + PRESSED, + RELEASED, + WAITING_FOR_MULTI_CLICK + }; + + uint8_t _pin; + bool _activeState; + bool _isAnalog; + uint16_t _analogThreshold; + + State _state = IDLE; + bool _currentState; + bool _lastState; + + uint32_t _stateChangeTime = 0; + uint32_t _pressTime = 0; + uint32_t _releaseTime = 0; + uint32_t _lastReadTime = 0; + + uint8_t _clickCount = 0; + EventType _lastEvent = NONE; + + // Callbacks + EventCallback _onShortPress = nullptr; + EventCallback _onDoublePress = nullptr; + EventCallback _onTriplePress = nullptr; + EventCallback _onQuadruplePress = nullptr; + EventCallback _onLongPress = nullptr; + EventCallback _onAnyPress = nullptr; + + bool readButton(); + void handleStateChange(); + void triggerEvent(EventType event); +}; \ No newline at end of file diff --git a/examples/beacon_sensor/ui-orig/UITask.cpp b/examples/beacon_sensor/ui-orig/UITask.cpp new file mode 100644 index 0000000..3ad36fb --- /dev/null +++ b/examples/beacon_sensor/ui-orig/UITask.cpp @@ -0,0 +1,446 @@ +#include "UITask.h" +#include +#include +#include "../MyMesh.h" + +#define AUTO_OFF_MILLIS 15000 // 15 seconds +#define BOOT_SCREEN_MILLIS 3000 // 3 seconds + +#ifdef PIN_STATUS_LED +#define LED_ON_MILLIS 20 +#define LED_ON_MSG_MILLIS 200 +#define LED_CYCLE_MILLIS 4000 +#endif + +#ifndef USER_BTN_PRESSED +#define USER_BTN_PRESSED LOW +#endif + +// 'meshcore', 128x13px +static const uint8_t meshcore_logo [] PROGMEM = { + 0x3c, 0x01, 0xe3, 0xff, 0xc7, 0xff, 0x8f, 0x03, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, + 0x3c, 0x03, 0xe3, 0xff, 0xc7, 0xff, 0x8e, 0x03, 0x8f, 0xfe, 0x3f, 0xfe, 0x1f, 0xff, 0x1f, 0xfe, + 0x3e, 0x03, 0xc3, 0xff, 0x8f, 0xff, 0x0e, 0x07, 0x8f, 0xfe, 0x7f, 0xfe, 0x1f, 0xff, 0x1f, 0xfc, + 0x3e, 0x07, 0xc7, 0x80, 0x0e, 0x00, 0x0e, 0x07, 0x9e, 0x00, 0x78, 0x0e, 0x3c, 0x0f, 0x1c, 0x00, + 0x3e, 0x0f, 0xc7, 0x80, 0x1e, 0x00, 0x0e, 0x07, 0x1e, 0x00, 0x70, 0x0e, 0x38, 0x0f, 0x3c, 0x00, + 0x7f, 0x0f, 0xc7, 0xfe, 0x1f, 0xfc, 0x1f, 0xff, 0x1c, 0x00, 0x70, 0x0e, 0x38, 0x0e, 0x3f, 0xf8, + 0x7f, 0x1f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x0e, 0x38, 0x0e, 0x3f, 0xf8, + 0x7f, 0x3f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x1e, 0x3f, 0xfe, 0x3f, 0xf0, + 0x77, 0x3b, 0x87, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xfc, 0x38, 0x00, + 0x77, 0xfb, 0x8f, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xf8, 0x38, 0x00, + 0x73, 0xf3, 0x8f, 0xff, 0x0f, 0xff, 0x1c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x78, 0x7f, 0xf8, + 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfe, 0x3c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x3c, 0x7f, 0xf8, + 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfc, 0x3c, 0x0e, 0x1f, 0xf8, 0xff, 0xf8, 0x70, 0x3c, 0x7f, 0xf8, +}; + +void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs) { + _display = display; + _sensors = sensors; + _auto_off = millis() + AUTO_OFF_MILLIS; + clearMsgPreview(); + _node_prefs = node_prefs; + if (_display != NULL) { + _display->turnOn(); + } + + // strip off dash and commit hash by changing dash to null terminator + // e.g: v1.2.3-abcdef -> v1.2.3 + char *version = strdup(FIRMWARE_VERSION); + char *dash = strchr(version, '-'); + if (dash) { + *dash = 0; + } + + // v1.2.3 (1 Jan 2025) + sprintf(_version_info, "%s (%s)", version, FIRMWARE_BUILD_DATE); + +#ifdef PIN_BUZZER + buzzer.begin(); + buzzer.quiet(_node_prefs->buzzer_quiet); +#endif + + // Initialize digital button if available +#ifdef PIN_USER_BTN + _userButton = new Button(PIN_USER_BTN, USER_BTN_PRESSED); + _userButton->begin(); + + // Set up digital button callbacks + _userButton->onShortPress([this]() { handleButtonShortPress(); }); + _userButton->onDoublePress([this]() { handleButtonDoublePress(); }); + _userButton->onTriplePress([this]() { handleButtonTriplePress(); }); + _userButton->onQuadruplePress([this]() { handleButtonQuadruplePress(); }); + _userButton->onLongPress([this]() { handleButtonLongPress(); }); + _userButton->onAnyPress([this]() { handleButtonAnyPress(); }); +#endif + + // Initialize analog button if available +#ifdef PIN_USER_BTN_ANA + _userButtonAnalog = new Button(PIN_USER_BTN_ANA, USER_BTN_PRESSED, true, 20); + _userButtonAnalog->begin(); + + // Set up analog button callbacks + _userButtonAnalog->onShortPress([this]() { handleButtonShortPress(); }); + _userButtonAnalog->onDoublePress([this]() { handleButtonDoublePress(); }); + _userButtonAnalog->onTriplePress([this]() { handleButtonTriplePress(); }); + _userButtonAnalog->onQuadruplePress([this]() { handleButtonQuadruplePress(); }); + _userButtonAnalog->onLongPress([this]() { handleButtonLongPress(); }); + _userButtonAnalog->onAnyPress([this]() { handleButtonAnyPress(); }); +#endif + ui_started_at = millis(); +} + +void UITask::notify(UIEventType t) { +#if defined(PIN_BUZZER) +switch(t){ + case UIEventType::contactMessage: + // gemini's pick + buzzer.play("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); + break; + case UIEventType::channelMessage: + buzzer.play("kerplop:d=16,o=6,b=120:32g#,32c#"); + break; + case UIEventType::ack: + buzzer.play("ack:d=32,o=8,b=120:c"); + break; + case UIEventType::roomMessage: + case UIEventType::newContactMessage: + case UIEventType::none: + default: + break; +} +#endif +// Serial.print("DBG: Alert user -> "); +// Serial.println((int) t); +} + +void UITask::msgRead(int msgcount) { + _msgcount = msgcount; + if (msgcount == 0) { + clearMsgPreview(); + } +} + +void UITask::clearMsgPreview() { + _origin[0] = 0; + _msg[0] = 0; + _need_refresh = true; +} + +void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) { + _msgcount = msgcount; + + if (path_len == 0xFF) { + sprintf(_origin, "(F) %s", from_name); + } else { + sprintf(_origin, "(%d) %s", (uint32_t) path_len, from_name); + } + StrHelper::strncpy(_msg, text, sizeof(_msg)); + + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(); + } + if (_display->isOn()) { + _auto_off = millis() + AUTO_OFF_MILLIS; // extend the auto-off timer + _need_refresh = true; + } + } +} + +void UITask::renderBatteryIndicator(uint16_t batteryMilliVolts) { + // Convert millivolts to percentage +#ifndef BATT_MIN_MILLIVOLTS + #define BATT_MIN_MILLIVOLTS 3000 +#endif +#ifndef BATT_MAX_MILLIVOLTS + #define BATT_MAX_MILLIVOLTS 4200 +#endif + const int minMilliVolts = BATT_MIN_MILLIVOLTS; + const int maxMilliVolts = BATT_MAX_MILLIVOLTS; + int batteryPercentage = ((batteryMilliVolts - minMilliVolts) * 100) / (maxMilliVolts - minMilliVolts); + if (batteryPercentage < 0) batteryPercentage = 0; // Clamp to 0% + if (batteryPercentage > 100) batteryPercentage = 100; // Clamp to 100% + + // battery icon + int iconWidth = 24; + int iconHeight = 12; + int iconX = _display->width() - iconWidth - 5; // Position the icon near the top-right corner + int iconY = 0; + _display->setColor(DisplayDriver::GREEN); + + // battery outline + _display->drawRect(iconX, iconY, iconWidth, iconHeight); + + // battery "cap" + _display->fillRect(iconX + iconWidth, iconY + (iconHeight / 4), 3, iconHeight / 2); + + // fill the battery based on the percentage + int fillWidth = (batteryPercentage * (iconWidth - 4)) / 100; + _display->fillRect(iconX + 2, iconY + 2, fillWidth, iconHeight - 4); +} + +void UITask::renderCurrScreen() { + if (_display == NULL) return; // assert() ?? + + char tmp[80]; + if (_alert[0]) { + _display->setTextSize(1.4); + uint16_t textWidth = _display->getTextWidth(_alert); + _display->setCursor((_display->width() - textWidth) / 2, 22); + _display->setColor(DisplayDriver::GREEN); + _display->print(_alert); + _alert[0] = 0; + _need_refresh = true; + return; + } else if (_origin[0] && _msg[0]) { // message preview + // render message preview + _display->setCursor(0, 0); + _display->setTextSize(1); + _display->setColor(DisplayDriver::GREEN); + _display->print(_node_prefs->node_name); + + _display->setCursor(0, 12); + _display->setColor(DisplayDriver::YELLOW); + _display->print(_origin); + _display->setCursor(0, 24); + _display->setColor(DisplayDriver::LIGHT); + _display->print(_msg); + + _display->setCursor(_display->width() - 28, 9); + _display->setTextSize(2); + _display->setColor(DisplayDriver::ORANGE); + sprintf(tmp, "%d", _msgcount); + _display->print(tmp); + _display->setColor(DisplayDriver::YELLOW); // last color will be kept on T114 + } else if ((millis() - ui_started_at) < BOOT_SCREEN_MILLIS) { // boot screen + // meshcore logo + _display->setColor(DisplayDriver::BLUE); + int logoWidth = 128; + _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); + + // version info + _display->setColor(DisplayDriver::LIGHT); + _display->setTextSize(1); + uint16_t textWidth = _display->getTextWidth(_version_info); + _display->setCursor((_display->width() - textWidth) / 2, 22); + _display->print(_version_info); + } else { // home screen + // node name + _display->setCursor(0, 0); + _display->setTextSize(1); + _display->setColor(DisplayDriver::GREEN); + _display->print(_node_prefs->node_name); + + // battery voltage + renderBatteryIndicator(_board->getBattMilliVolts()); + + // freq / sf + _display->setCursor(0, 20); + _display->setColor(DisplayDriver::YELLOW); + sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); + _display->print(tmp); + + // bw / cr + _display->setCursor(0, 30); + sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); + _display->print(tmp); + + // BT pin + if (!_connected && the_mesh.getBLEPin() != 0) { + _display->setColor(DisplayDriver::RED); + _display->setTextSize(2); + _display->setCursor(0, 43); + sprintf(tmp, "Pin:%d", the_mesh.getBLEPin()); + _display->print(tmp); + _display->setColor(DisplayDriver::GREEN); + } else { + _display->setColor(DisplayDriver::LIGHT); + } + } + _need_refresh = false; +} + +void UITask::userLedHandler() { +#ifdef PIN_STATUS_LED + static int state = 0; + static int next_change = 0; + static int last_increment = 0; + + int cur_time = millis(); + if (cur_time > next_change) { + if (state == 0) { + state = 1; + if (_msgcount > 0) { + last_increment = LED_ON_MSG_MILLIS; + } else { + last_increment = LED_ON_MILLIS; + } + next_change = cur_time + last_increment; + } else { + state = 0; + next_change = cur_time + LED_CYCLE_MILLIS - last_increment; + } + digitalWrite(PIN_STATUS_LED, state == LED_STATE_ON); + } +#endif +} + +/* + hardware-agnostic pre-shutdown activity should be done here +*/ +void UITask::shutdown(bool restart){ + + #ifdef PIN_BUZZER + /* note: we have a choice here - + we can do a blocking buzzer.loop() with non-deterministic consequences + or we can set a flag and delay the shutdown for a couple of seconds + while a non-blocking buzzer.loop() plays out in UITask::loop() + */ + buzzer.shutdown(); + uint32_t buzzer_timer = millis(); // fail-safe shutdown + while (buzzer.isPlaying() && (millis() - 2500) < buzzer_timer) + buzzer.loop(); + + #endif // PIN_BUZZER + + if (restart) { + _board->reboot(); + } else { + radio_driver.powerOff(); + _board->powerOff(); + } +} + +void UITask::loop() { + #ifdef PIN_USER_BTN + if (_userButton) { + _userButton->update(); + } + #endif + #ifdef PIN_USER_BTN_ANA + if (_userButtonAnalog) { + _userButtonAnalog->update(); + } + #endif + userLedHandler(); + +#ifdef PIN_BUZZER + if (buzzer.isPlaying()) buzzer.loop(); +#endif + + if (_display != NULL && _display->isOn()) { + static bool _firstBoot = true; + if(_firstBoot && (millis() - ui_started_at) >= BOOT_SCREEN_MILLIS) { + _need_refresh = true; + _firstBoot = false; + } + if (millis() >= _next_refresh && _need_refresh) { + _display->startFrame(); + renderCurrScreen(); + _display->endFrame(); + + _next_refresh = millis() + 1000; // refresh every second + } + if (millis() > _auto_off) { + _display->turnOff(); + } + } +} + +void UITask::handleButtonAnyPress() { + MESH_DEBUG_PRINTLN("UITask: any press triggered"); + // called on any button press before other events, to wake up the display quickly + // do not refresh the display here, as it may block the button handler + if (_display != NULL) { + _displayWasOn = _display->isOn(); // Track display state before any action + if (!_displayWasOn) { + _display->turnOn(); + } + _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + } +} + +void UITask::handleButtonShortPress() { + MESH_DEBUG_PRINTLN("UITask: short press triggered"); + if (_display != NULL) { + // Only clear message preview if display was already on before button press + if (_displayWasOn) { + // If display was on and showing message preview, clear it + if (_origin[0] && _msg[0]) { + clearMsgPreview(); + } else { + // Otherwise, refresh the display + _need_refresh = true; + } + } else { + _need_refresh = true; // display just turned on, so we need to refresh + } + // Note: Display turn-on and auto-off timer extension are handled by handleButtonAnyPress + } +} + +void UITask::handleButtonDoublePress() { + MESH_DEBUG_PRINTLN("UITask: double press triggered, sending advert"); + // ADVERT + #ifdef PIN_BUZZER + notify(UIEventType::ack); + #endif + if (the_mesh.advert()) { + MESH_DEBUG_PRINTLN("Advert sent!"); + sprintf(_alert, "Advert sent!"); + } else { + MESH_DEBUG_PRINTLN("Advert failed!"); + sprintf(_alert, "Advert failed.."); + } + _need_refresh = true; +} + +void UITask::handleButtonTriplePress() { + MESH_DEBUG_PRINTLN("UITask: triple press triggered"); + // Toggle buzzer quiet mode + #ifdef PIN_BUZZER + if (buzzer.isQuiet()) { + buzzer.quiet(false); + notify(UIEventType::ack); + sprintf(_alert, "Buzzer: ON"); + } else { + buzzer.quiet(true); + sprintf(_alert, "Buzzer: OFF"); + } + _node_prefs->buzzer_quiet = buzzer.isQuiet(); + the_mesh.savePrefs(); + _need_refresh = true; + #endif +} + +void UITask::handleButtonQuadruplePress() { + MESH_DEBUG_PRINTLN("UITask: quad press triggered"); + if (_sensors != NULL) { + // toggle GPS onn/off + int num = _sensors->getNumSettings(); + for (int i = 0; i < num; i++) { + if (strcmp(_sensors->getSettingName(i), "gps") == 0) { + if (strcmp(_sensors->getSettingValue(i), "1") == 0) { + _sensors->setSettingValue("gps", "0"); + notify(UIEventType::ack); + sprintf(_alert, "GPS: Disabled"); + } else { + _sensors->setSettingValue("gps", "1"); + notify(UIEventType::ack); + sprintf(_alert, "GPS: Enabled"); + } + break; + } + } + } + _need_refresh = true; +} + +void UITask::handleButtonLongPress() { + MESH_DEBUG_PRINTLN("UITask: long press triggered"); + if (millis() - ui_started_at < 8000) { // long press in first 8 seconds since startup -> CLI/rescue + the_mesh.enterCLIRescue(); + } else { + shutdown(); + } +} \ No newline at end of file diff --git a/examples/beacon_sensor/ui-orig/UITask.h b/examples/beacon_sensor/ui-orig/UITask.h new file mode 100644 index 0000000..60cd0d0 --- /dev/null +++ b/examples/beacon_sensor/ui-orig/UITask.h @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include +#include + +#ifdef PIN_BUZZER + #include +#endif + +#include "../AbstractUITask.h" +#include "../NodePrefs.h" + +#include "Button.h" + +class UITask : public AbstractUITask { + DisplayDriver* _display; + SensorManager* _sensors; +#ifdef PIN_BUZZER + genericBuzzer buzzer; +#endif + unsigned long _next_refresh, _auto_off; + NodePrefs* _node_prefs; + char _version_info[32]; + char _origin[62]; + char _msg[80]; + char _alert[80]; + int _msgcount; + bool _need_refresh = true; + bool _displayWasOn = false; // Track display state before button press + unsigned long ui_started_at; + + // Button handlers +#ifdef PIN_USER_BTN + Button* _userButton = nullptr; +#endif +#ifdef PIN_USER_BTN_ANA + Button* _userButtonAnalog = nullptr; +#endif + + void renderCurrScreen(); + void userLedHandler(); + void renderBatteryIndicator(uint16_t batteryMilliVolts); + + // Button action handlers + void handleButtonAnyPress(); + void handleButtonShortPress(); + void handleButtonDoublePress(); + void handleButtonTriplePress(); + void handleButtonQuadruplePress(); + void handleButtonLongPress(); + + +public: + + UITask(mesh::MainBoard* board, BaseSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { + _next_refresh = 0; + ui_started_at = 0; + } + void begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs); + + bool hasDisplay() const { return _display != NULL; } + void clearMsgPreview(); + + // from AbstractUITask + void msgRead(int msgcount) override; + void newMsg(uint8_t path_len, const char* from_name, const char* text, int msgcount) override; + void notify(UIEventType t = UIEventType::none) override; + void loop() override; + + void shutdown(bool restart = false); +}; diff --git a/variants/heltec_t114/platformio.ini b/variants/heltec_t114/platformio.ini index b985030..f482497 100644 --- a/variants/heltec_t114/platformio.ini +++ b/variants/heltec_t114/platformio.ini @@ -117,6 +117,33 @@ lib_deps = ${Heltec_t114.lib_deps} densaugeo/base64 @ ~1.4.0 +[env:Heltec_t114_without_display_beacon_sensor_ble] +extends = Heltec_t114 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${Heltec_t114.build_flags} + -I examples/beacon_sensor/ui-new + -D DISPLAY_CLASS=NullDisplayDriver + -D MAX_CONTACTS=50 + -D MAX_GROUP_CHANNELS=10 + -D BLE_PIN_CODE=123456 + -D ADVERT_NAME='"Beacon-T114"' + -D LORA_FREQ=868.731 + -D LORA_BW=62.5 + -D LORA_SF=7 + -D LORA_CR=7 + -D OFFLINE_QUEUE_SIZE=16 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Heltec_t114.build_src_filter} + + + +<../examples/beacon_sensor/*.cpp> + +<../examples/beacon_sensor/ui-new/*.cpp> +lib_deps = + ${Heltec_t114.lib_deps} + densaugeo/base64 @ ~1.4.0 + [env:Heltec_t114_without_display_companion_radio_usb] extends = Heltec_t114 board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld @@ -139,6 +166,28 @@ lib_deps = ${Heltec_t114.lib_deps} densaugeo/base64 @ ~1.4.0 +[env:Heltec_t114_without_display_beacon_sensor_usb] +extends = Heltec_t114 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${Heltec_t114.build_flags} + -I examples/beacon_sensor/ui-new + -D DISPLAY_CLASS=NullDisplayDriver + -D MAX_CONTACTS=50 + -D MAX_GROUP_CHANNELS=10 + -D ADVERT_NAME='"BMP280-Beacon"' + -D OFFLINE_QUEUE_SIZE=16 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Heltec_t114.build_src_filter} + + + +<../examples/beacon_sensor/*.cpp> + +<../examples/beacon_sensor/ui-new/*.cpp> +lib_deps = + ${Heltec_t114.lib_deps} + densaugeo/base64 @ ~1.4.0 + ; ; Heltec T114 with ST7789 display ; @@ -232,6 +281,32 @@ lib_deps = ${Heltec_t114_with_display.lib_deps} densaugeo/base64 @ ~1.4.0 +[env:Heltec_t114_beacon_sensor_ble] +extends = Heltec_t114_with_display +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${Heltec_t114_with_display.build_flags} + -I examples/beacon_sensor/ui-new + -D MAX_CONTACTS=50 + -D MAX_GROUP_CHANNELS=10 + -D BLE_PIN_CODE=123456 + -D ADVERT_NAME='"Beacon-T114"' + -D LORA_FREQ=868.731 + -D LORA_BW=62.5 + -D LORA_SF=7 + -D LORA_CR=7 + -D OFFLINE_QUEUE_SIZE=16 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Heltec_t114_with_display.build_src_filter} + + + +<../examples/beacon_sensor/*.cpp> + +<../examples/beacon_sensor/ui-new/*.cpp> +lib_deps = + ${Heltec_t114_with_display.lib_deps} + densaugeo/base64 @ ~1.4.0 + [env:Heltec_t114_companion_radio_usb] extends = Heltec_t114_with_display board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld @@ -249,6 +324,27 @@ build_src_filter = ${Heltec_t114_with_display.build_src_filter} + +<../examples/companion_radio/*.cpp> +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = + ${Heltec_t114_with_display.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:Heltec_t114_beacon_sensor_usb] +extends = Heltec_t114_with_display +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = + ${Heltec_t114_with_display.build_flags} + -I examples/beacon_sensor/ui-new + -D MAX_CONTACTS=50 + -D MAX_GROUP_CHANNELS=10 + -D ADVERT_NAME='"BMP280-Beacon"' + -D OFFLINE_QUEUE_SIZE=16 +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Heltec_t114_with_display.build_src_filter} + + + +<../examples/beacon_sensor/*.cpp> + +<../examples/beacon_sensor/ui-new/*.cpp> lib_deps = ${Heltec_t114_with_display.lib_deps} densaugeo/base64 @ ~1.4.0 \ No newline at end of file