From d3831821c7a9d020b1fea6c2ba56281b6f1d12cd Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 22:59:07 +1000 Subject: [PATCH 01/11] * XiaoC3 custom, .ini fixes --- variants/xiao_c3/platformio.ini | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/variants/xiao_c3/platformio.ini b/variants/xiao_c3/platformio.ini index b5bf1e1..3e4bfdb 100644 --- a/variants/xiao_c3/platformio.ini +++ b/variants/xiao_c3/platformio.ini @@ -109,10 +109,10 @@ lib_deps = [env:Xiao_C3_Repeater_sx1262_custom] extends = Xiao_esp32_C3_custom -build_src_filter = ${Xiao_esp32_C3.build_src_filter} +build_src_filter = ${Xiao_esp32_C3_custom.build_src_filter} +<../examples/simple_repeater/main.cpp> build_flags = - ${Xiao_esp32_C3.build_flags} + ${Xiao_esp32_C3_custom.build_flags} -D RADIO_CLASS=CustomSX1262 -D WRAPPER_CLASS=CustomSX1262Wrapper -D SX126X_RX_BOOSTED_GAIN=1 @@ -125,15 +125,15 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 lib_deps = - ${Xiao_esp32_C3.lib_deps} + ${Xiao_esp32_C3_custom.lib_deps} ${esp32_ota.lib_deps} [env:Xiao_C3_Repeater_sx1268_custom] extends = Xiao_esp32_C3_custom -build_src_filter = ${Xiao_esp32_C3.build_src_filter} +build_src_filter = ${Xiao_esp32_C3_custom.build_src_filter} +<../examples/simple_repeater/main.cpp> build_flags = - ${Xiao_esp32_C3.build_flags} + ${Xiao_esp32_C3_custom.build_flags} -D RADIO_CLASS=CustomSX1268 -D WRAPPER_CLASS=CustomSX1268Wrapper -D LORA_TX_POWER=22 @@ -145,5 +145,5 @@ build_flags = ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 lib_deps = - ${Xiao_esp32_C3.lib_deps} + ${Xiao_esp32_C3_custom.lib_deps} ${esp32_ota.lib_deps} \ No newline at end of file From 7fb7b69bbc4130ad5b787a2b7997d7132df15504 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 7 Jul 2025 14:21:19 +1000 Subject: [PATCH 02/11] * first cut of new simple_sensor sketch --- examples/simple_sensor/SensorMesh.cpp | 590 ++++++++++++++++++++++++++ examples/simple_sensor/SensorMesh.h | 134 ++++++ examples/simple_sensor/UITask.cpp | 114 +++++ examples/simple_sensor/UITask.h | 19 + examples/simple_sensor/main.cpp | 128 ++++++ src/helpers/AdvertDataHelpers.h | 3 +- variants/heltec_v3/platformio.ini | 17 + 7 files changed, 1004 insertions(+), 1 deletion(-) create mode 100644 examples/simple_sensor/SensorMesh.cpp create mode 100644 examples/simple_sensor/SensorMesh.h create mode 100644 examples/simple_sensor/UITask.cpp create mode 100644 examples/simple_sensor/UITask.h create mode 100644 examples/simple_sensor/main.cpp diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp new file mode 100644 index 0000000..3b5b04c --- /dev/null +++ b/examples/simple_sensor/SensorMesh.cpp @@ -0,0 +1,590 @@ +#include "SensorMesh.h" + +/* ------------------------------ Config -------------------------------- */ + +#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 ADVERT_NAME + #define ADVERT_NAME "sensor" +#endif +#ifndef ADVERT_LAT + #define ADVERT_LAT 0.0 +#endif +#ifndef ADVERT_LON + #define ADVERT_LON 0.0 +#endif + +#ifndef ADMIN_PASSWORD + #define ADMIN_PASSWORD "password" +#endif + +#ifndef SERVER_RESPONSE_DELAY + #define SERVER_RESPONSE_DELAY 300 +#endif + +#ifndef TXT_ACK_DELAY + #define TXT_ACK_DELAY 200 +#endif + +#ifndef SENSOR_READ_INTERVAL_SECS + #define SENSOR_READ_INTERVAL_SECS 60 +#endif + +/* ------------------------------ Code -------------------------------- */ + +#define REQ_TYPE_GET_STATUS 0x01 +#define REQ_TYPE_KEEP_ALIVE 0x02 +#define REQ_TYPE_GET_TELEMETRY_DATA 0x03 + +#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ + +#define CLI_REPLY_DELAY_MILLIS 1000 + +#define LAZY_CONTACTS_WRITE_DELAY 5000 + +static File openAppend(FILESYSTEM* _fs, const char* fname) { + #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + return _fs->open(fname, FILE_O_WRITE); + #elif defined(RP2040_PLATFORM) + return _fs->open(fname, "a"); + #else + return _fs->open(fname, "a", true); + #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 +} + +void SensorMesh::loadContacts() { + num_contacts = 0; + if (_fs->exists("/s_contacts")) { + #if defined(RP2040_PLATFORM) + File file = _fs->open("/s_contacts", "r"); + #else + File file = _fs->open("/s_contacts"); + #endif + 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(&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.out_path_len, 1) == 1); + success = success && (file.read(c.out_path, 64) == 64); + success = success && (file.read(c.shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE); + c.last_timestamp = 0; // transient + c.last_activity = 0; + + if (!success) break; // EOF + + c.id = mesh::Identity(pub_key); + if (num_contacts < MAX_CONTACTS) { + contacts[num_contacts++] = c; + } else { + full = true; + } + } + file.close(); + } + } +} + +void SensorMesh::saveContacts() { + File file = openWrite(_fs, "/s_contacts"); + if (file) { + uint8_t unused = 0; + + for (int i = 0; i < num_contacts; i++) { + auto c = &contacts[i]; + if (c->type == 0) continue; // don't persist guest contacts + + bool success = (file.write(c->id.pub_key, 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->out_path_len, 1) == 1); + success = success && (file.write(c->out_path, 64) == 64); + success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE); + + if (!success) break; // write failed + } + file.close(); + } +} + +int SensorMesh::handleRequest(ContactInfo& sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len) { + // uint32_t now = getRTCClock()->getCurrentTimeUnique(); + // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp + memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') + + switch (payload[0]) { + case REQ_TYPE_GET_TELEMETRY_DATA: { + telemetry.reset(); + telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + // query other sensors -- target specific + sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions for admin or guest + + uint8_t tlen = telemetry.getSize(); + memcpy(&reply_data[4], telemetry.getBuffer(), tlen); + return 4 + tlen; // reply_len + } + } + return 0; // unknown command +} + +mesh::Packet* SensorMesh::createSelfAdvert() { + uint8_t app_data[MAX_ADVERT_DATA_SIZE]; + uint8_t app_data_len; + { + AdvertDataBuilder builder(ADV_TYPE_SENSOR, _prefs.node_name, _prefs.node_lat, _prefs.node_lon); + app_data_len = builder.encodeTo(app_data); + } + + return createAdvert(self_id, app_data, app_data_len); +} + +ContactInfo* SensorMesh::putContact(const mesh::Identity& id) { + uint32_t min_time = 0xFFFFFFFF; + ContactInfo* oldest = &contacts[MAX_CONTACTS - 1]; + for (int i = 0; i < num_contacts; i++) { + if (id.matches(contacts[i].id)) return &contacts[i]; // already known + if (!contacts[i].isAdmin() && contacts[i].last_activity < min_time) { + oldest = &contacts[i]; + min_time = oldest->last_activity; + } + } + + ContactInfo* c; + if (num_contacts < MAX_CONTACTS) { + c = &contacts[num_contacts++]; + } else { + c = oldest; // evict least active contact + } + memset(c, 0, sizeof(*c)); + c->id = id; + c->out_path_len = -1; // initially out_path is unknown + return c; +} + +void SensorMesh::alertIfLow(Trigger& t, float value, float threshold, const char* text) { + if (value < threshold) { + if (!t.triggered) { + t.triggered = true; + t.time = getRTCClock()->getCurrentTime(); + sendAlert(text); + } + } else { + if (t.triggered) { + t.triggered = false; + // TODO: apply debounce logic + } + } +} + +void SensorMesh::alertIfHigh(Trigger& t, float value, float threshold, const char* text) { + if (value > threshold) { + if (!t.triggered) { + t.triggered = true; + t.time = getRTCClock()->getCurrentTime(); + sendAlert(text); + } + } else { + if (t.triggered) { + t.triggered = false; + // TODO: apply debounce logic + } + } +} + +float SensorMesh::getAirtimeBudgetFactor() const { + return _prefs.airtime_factor; +} + +bool SensorMesh::allowPacketForward(const mesh::Packet* packet) { + if (_prefs.disable_fwd) return false; + if (packet->isRouteFlood() && packet->path_len >= _prefs.flood_max) return false; + return true; +} + +int SensorMesh::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 SensorMesh::getRetransmitDelay(const mesh::Packet* packet) { + uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.tx_delay_factor); + return getRNG()->nextInt(0, 6)*t; +} +uint32_t SensorMesh::getDirectRetransmitDelay(const mesh::Packet* packet) { + uint32_t t = (_radio->getEstAirtimeFor(packet->path_len + packet->payload_len + 2) * _prefs.direct_tx_delay_factor); + return getRNG()->nextInt(0, 6)*t; +} +int SensorMesh::getInterferenceThreshold() const { + return _prefs.interference_threshold; +} +int SensorMesh::getAGCResetInterval() const { + return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds +} + +void SensorMesh::onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) { + if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) + uint32_t timestamp; + memcpy(×tamp, data, 4); + + bool is_admin; + data[len] = 0; // ensure null terminator + if (strcmp((char *) &data[4], _prefs.password) == 0) { // check for valid password + is_admin = true; + } else if (strcmp((char *) &data[4], _prefs.guest_password) == 0) { // check guest password + is_admin = false; + } else { + #if MESH_DEBUG + MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); + #endif + return; + } + + auto client = putContact(sender); // add to contacts (if not already known) + if (timestamp <= client->last_timestamp) { + MESH_DEBUG_PRINTLN("Possible login replay attack!"); + return; // FATAL: client table is full -OR- replay attack + } + + MESH_DEBUG_PRINTLN("Login success!"); + client->last_timestamp = timestamp; + client->last_activity = getRTCClock()->getCurrentTime(); + client->type = is_admin ? 1 : 0; + self_id.calcSharedSecret(client->shared_secret, client->id); // calc ECDH shared secret + + if (is_admin) { + // only need to saveContacts() if this is an admin + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + } + + uint32_t now = getRTCClock()->getCurrentTimeUnique(); + memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp + reply_data[4] = RESP_SERVER_LOGIN_OK; + reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16) + reply_data[6] = client->type; + reply_data[7] = 0; // FUTURE: reserved + getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness + + if (packet->isRouteFlood()) { + // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response + mesh::Packet* path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len, + PAYLOAD_TYPE_RESPONSE, reply_data, 12); + if (path) sendFlood(path, SERVER_RESPONSE_DELAY); + } else { + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 12); + if (reply) { + if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT + sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); + } else { + sendFlood(reply, SERVER_RESPONSE_DELAY); + } + } + } + } +} + +int SensorMesh::searchPeersByHash(const uint8_t* hash) { + int n = 0; + for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) { + if (contacts[i].id.isHashMatch(hash)) { + matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods) + } + } + return n; +} + +void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) { + int i = matching_peer_indexes[peer_idx]; + if (i >= 0 && i < num_contacts) { + // lookup pre-calculated shared_secret + memcpy(dest_secret, contacts[i].shared_secret, PUB_KEY_SIZE); + } else { + MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i); + } +} + +void SensorMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) { + mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl +#if 0 + // if this a zero hop advert, add it to neighbours + if (packet->path_len == 0) { + AdvertDataParser parser(app_data, app_data_len); + if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters + putNeighbour(id, timestamp, packet->getSNR()); + } + } +#endif +} + +void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) { + int i = matching_peer_indexes[sender_idx]; + if (i < 0 || i >= num_contacts) { + MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i); + return; + } + + ContactInfo& from = contacts[i]; + + if (type == PAYLOAD_TYPE_REQ) { // request (from a known contact) + uint32_t timestamp; + memcpy(×tamp, data, 4); + + if (timestamp > from.last_timestamp) { // prevent replay attacks + int reply_len = handleRequest(from, timestamp, &data[4], len - 4); + if (reply_len == 0) return; // invalid command + + from.last_timestamp = timestamp; + from.last_activity = getRTCClock()->getCurrentTime(); + + if (packet->isRouteFlood()) { + // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response + mesh::Packet* path = createPathReturn(from.id, secret, packet->path, packet->path_len, + PAYLOAD_TYPE_RESPONSE, reply_data, reply_len); + if (path) sendFlood(path, SERVER_RESPONSE_DELAY); + } else { + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from.id, secret, reply_data, reply_len); + if (reply) { + if (from.out_path_len >= 0) { // we have an out_path, so send DIRECT + sendDirect(reply, from.out_path, from.out_path_len, SERVER_RESPONSE_DELAY); + } else { + sendFlood(reply, SERVER_RESPONSE_DELAY); + } + } + } + } else { + MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected"); + } + } else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && from.isAdmin()) { // a CLI command + uint32_t sender_timestamp; + memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong) + uint flags = (data[4] >> 2); // message attempt number, and other flags + + if (!(flags == TXT_TYPE_CLI_DATA)) { + MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags); + } else if (sender_timestamp > from.last_timestamp) { // prevent replay attacks + from.last_timestamp = sender_timestamp; + from.last_activity = getRTCClock()->getCurrentTime(); + + // len can be > original length, but 'text' will be padded with zeroes + data[len] = 0; // need to make a C string again, with null terminator + + uint8_t temp[166]; + const char *command = (const char *) &data[5]; + char *reply = (char *) &temp[5]; + _cli.handleCommand(sender_timestamp, command, reply); + + int text_len = strlen(reply); + if (text_len > 0) { + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); + if (timestamp == sender_timestamp) { + // WORKAROUND: the two timestamps need to be different, in the CLI view + timestamp++; + } + memcpy(temp, ×tamp, 4); // mostly an extra blob to help make packet_hash unique + temp[4] = (TXT_TYPE_CLI_DATA << 2); + + auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len); + if (reply) { + if (from.out_path_len < 0) { + sendFlood(reply, CLI_REPLY_DELAY_MILLIS); + } else { + sendDirect(reply, from.out_path, from.out_path_len, CLI_REPLY_DELAY_MILLIS); + } + } + } + } else { + MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected"); + } + } +} + +bool SensorMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) { + int i = matching_peer_indexes[sender_idx]; + if (i < 0 || i >= num_contacts) { + MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i); + return false; + } + + ContactInfo& from = contacts[i]; + + MESH_DEBUG_PRINTLN("PATH to contact, path_len=%d", (uint32_t) path_len); + // NOTE: for this impl, we just replace the current 'out_path' regardless, whenever sender sends us a new out_path. + // FUTURE: could store multiple out_paths per contact, and try to find which is the 'best'(?) + memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect() + from.last_activity = getRTCClock()->getCurrentTime(); + + if (from.isAdmin()) { + // only need to saveContacts() if this is an admin + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + } + + // NOTE: no reciprocal path send!! + return false; +} + +SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables) + : mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables), + _cli(board, rtc, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4) +{ + num_contacts = 0; + next_local_advert = next_flood_advert = 0; + dirty_contacts_expiry = 0; + last_read_time = 0; + + // defaults + memset(&_prefs, 0, sizeof(_prefs)); + _prefs.airtime_factor = 1.0; // one half + _prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0; + _prefs.tx_delay_factor = 0.5f; // was 0.25f + StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name)); + _prefs.node_lat = ADVERT_LAT; + _prefs.node_lon = ADVERT_LON; + StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password)); + _prefs.freq = LORA_FREQ; + _prefs.sf = LORA_SF; + _prefs.bw = LORA_BW; + _prefs.cr = LORA_CR; + _prefs.tx_power_dbm = LORA_TX_POWER; + _prefs.advert_interval = 1; // default to 2 minutes for NEW installs + _prefs.flood_advert_interval = 3; // 3 hours + _prefs.disable_fwd = true; + _prefs.flood_max = 64; + _prefs.interference_threshold = 0; // disabled +} + +void SensorMesh::begin(FILESYSTEM* fs) { + mesh::Mesh::begin(); + _fs = fs; + // load persisted prefs + _cli.loadPrefs(_fs); + + loadContacts(); + + radio_set_params(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr); + radio_set_tx_power(_prefs.tx_power_dbm); + + updateAdvertTimer(); + updateFloodAdvertTimer(); +} + +bool SensorMesh::formatFileSystem() { +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + return InternalFS.format(); +#elif defined(RP2040_PLATFORM) + return LittleFS.format(); +#elif defined(ESP32) + return SPIFFS.format(); +#else + #error "need to implement file system erase" + return false; +#endif +} + +void SensorMesh::sendSelfAdvertisement(int delay_millis) { + mesh::Packet* pkt = createSelfAdvert(); + if (pkt) { + sendFlood(pkt, delay_millis); + } else { + MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!"); + } +} + +void SensorMesh::updateAdvertTimer() { + if (_prefs.advert_interval > 0) { // schedule local advert timer + next_local_advert = futureMillis( ((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000); + } else { + next_local_advert = 0; // stop the timer + } +} +void SensorMesh::updateFloodAdvertTimer() { + if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer + next_flood_advert = futureMillis( ((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000); + } else { + next_flood_advert = 0; // stop the timer + } +} + +void SensorMesh::setTxPower(uint8_t power_dbm) { + radio_set_tx_power(power_dbm); +} + +void SensorMesh::loop() { + mesh::Mesh::loop(); + + if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { + mesh::Packet* pkt = createSelfAdvert(); + if (pkt) sendFlood(pkt); + + updateFloodAdvertTimer(); // schedule next flood advert + updateAdvertTimer(); // also schedule local advert (so they don't overlap) + } else if (next_local_advert && millisHasNowPassed(next_local_advert)) { + mesh::Packet* pkt = createSelfAdvert(); + if (pkt) sendZeroHop(pkt); + + updateAdvertTimer(); // schedule next local advert + } + + uint32_t curr = getRTCClock()->getCurrentTime(); + if (curr >= last_read_time + SENSOR_READ_INTERVAL_SECS) { + telemetry.reset(); + telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + // query other sensors -- target specific + sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions + + checkForAlerts(); + + // save telemetry to time-series datastore + File file = openAppend(_fs, "/s_data"); + if (file) { + file.write((uint8_t *)&curr, 4); // start record with RTC timestamp + uint8_t tlen = telemetry.getSize(); + file.write(&tlen, 1); + file.write(telemetry.getBuffer(), tlen); + uint8_t zero = 0; + while (tlen < MAX_PACKET_PAYLOAD - 4) { // pad with zeroes, for fixed record length + file.write(&zero, 1); + tlen++; + } + file.close(); + } + + last_read_time = curr; + } + + // is there are pending dirty contacts write needed? + if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) { + saveContacts(); + dirty_contacts_expiry = 0; + } +} diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h new file mode 100644 index 0000000..051d664 --- /dev/null +++ b/examples/simple_sensor/SensorMesh.h @@ -0,0 +1,134 @@ +#pragma once + +#include // needed for PlatformIO +#include + +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) +#include +#elif defined(RP2040_PLATFORM) +#include +#elif defined(ESP32) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct ContactInfo { + mesh::Identity id; + uint8_t type; // 1 = admin, 0 = guest + uint8_t flags; + int8_t out_path_len; + uint8_t out_path[MAX_PATH_SIZE]; + uint8_t shared_secret[PUB_KEY_SIZE]; + uint32_t last_timestamp; // by THEIR clock (transient) + uint32_t last_activity; // by OUR clock (transient) + + bool isAdmin() const { return type != 0; } +}; + +#ifndef FIRMWARE_BUILD_DATE + #define FIRMWARE_BUILD_DATE "2 Jul 2025" +#endif + +#ifndef FIRMWARE_VERSION + #define FIRMWARE_VERSION "v1.7.2" +#endif + +#define FIRMWARE_ROLE "sensor" + +#ifndef MAX_CONTACTS + #define MAX_CONTACTS 32 +#endif + +#define MAX_SEARCH_RESULTS 8 + +class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { +public: + SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables); + void begin(FILESYSTEM* fs); + CommonCLI* getCLI() { return &_cli; } + void loop(); + + // CommonCLI callbacks + const char* getFirmwareVer() override { return FIRMWARE_VERSION; } + const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; } + const char* getRole() override { return FIRMWARE_ROLE; } + const char* getNodeName() { return _prefs.node_name; } + NodePrefs* getNodePrefs() { return &_prefs; } + void savePrefs() override { _cli.savePrefs(_fs); } + bool formatFileSystem() override; + void sendSelfAdvertisement(int delay_millis) override; + void updateAdvertTimer() override; + void updateFloodAdvertTimer() override; + void setLoggingOn(bool enable) override { } + void eraseLogFile() override { } + void dumpLogFile() override { } + void setTxPower(uint8_t power_dbm) override; + void formatNeighborsReply(char *reply) override { + strcpy(reply, "not supported"); + } + const uint8_t* getSelfIdPubKey() override { return self_id.pub_key; } + void clearStats() override { } + +protected: + // telemetry data queries + float getVoltage(uint8_t channel) { return 0.0f; } // TODO: extract from curr telemetry buffer + + // alerts + struct Trigger { + bool triggered; + uint32_t time; + + Trigger() { triggered = false; time = 0; } + }; + + void alertIfLow(Trigger& t, float value, float threshold, const char* text); + void alertIfHigh(Trigger& t, float value, float threshold, const char* text); + + virtual void checkForAlerts() = 0; // for app to implement + + // Mesh overrides + float getAirtimeBudgetFactor() const override; + bool allowPacketForward(const mesh::Packet* packet) 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; + int getInterferenceThreshold() const override; + int getAGCResetInterval() const override; + void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override; + int searchPeersByHash(const uint8_t* hash) override; + void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override; + void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len); + void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override; + bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; + +private: + FILESYSTEM* _fs; + unsigned long next_local_advert, next_flood_advert; + NodePrefs _prefs; + CommonCLI _cli; + uint8_t reply_data[MAX_PACKET_PAYLOAD]; + ContactInfo contacts[MAX_CONTACTS]; + int num_contacts; + unsigned long dirty_contacts_expiry; + CayenneLPP telemetry; + uint32_t last_read_time; + int matching_peer_indexes[MAX_SEARCH_RESULTS]; + + void loadContacts(); + void saveContacts(); + int handleRequest(ContactInfo& sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len); + mesh::Packet* createSelfAdvert(); + ContactInfo* putContact(const mesh::Identity& id); + + void sendAlert(const char* text) { } // TODO + +}; diff --git a/examples/simple_sensor/UITask.cpp b/examples/simple_sensor/UITask.cpp new file mode 100644 index 0000000..0694bc3 --- /dev/null +++ b/examples/simple_sensor/UITask.cpp @@ -0,0 +1,114 @@ +#include "UITask.h" +#include +#include + +#define AUTO_OFF_MILLIS 20000 // 20 seconds +#define BOOT_SCREEN_MILLIS 4000 // 4 seconds + +// '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(NodePrefs* node_prefs, const char* build_date, const char* firmware_version) { + _prevBtnState = HIGH; + _auto_off = millis() + AUTO_OFF_MILLIS; + _node_prefs = node_prefs; + _display->turnOn(); + + // strip off dash and commit hash by changing dash to null terminator + // e.g: v1.2.3-abcdef -> v1.2.3 + char *version = strdup(firmware_version); + char *dash = strchr(version, '-'); + if(dash){ + *dash = 0; + } + + // v1.2.3 (1 Jan 2025) + sprintf(_version_info, "%s (%s)", version, build_date); +} + +void UITask::renderCurrScreen() { + char tmp[80]; + if (millis() < 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 versionWidth = _display->getTextWidth(_version_info); + _display->setCursor((_display->width() - versionWidth) / 2, 22); + _display->print(_version_info); + + // node type + const char* node_type = "< Sensor >"; + uint16_t typeWidth = _display->getTextWidth(node_type); + _display->setCursor((_display->width() - typeWidth) / 2, 35); + _display->print(node_type); + } else { // home screen + // node name + _display->setCursor(0, 0); + _display->setTextSize(1); + _display->setColor(DisplayDriver::GREEN); + _display->print(_node_prefs->node_name); + + // freq / sf + _display->setCursor(0, 20); + _display->setColor(DisplayDriver::YELLOW); + sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); + _display->print(tmp); + + // bw / cr + _display->setCursor(0, 30); + sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); + _display->print(tmp); + } +} + +void UITask::loop() { +#ifdef PIN_USER_BTN + if (millis() >= _next_read) { + int btnState = digitalRead(PIN_USER_BTN); + if (btnState != _prevBtnState) { + if (btnState == LOW) { // pressed? + if (_display->isOn()) { + // TODO: any action ? + } else { + _display->turnOn(); + } + _auto_off = millis() + AUTO_OFF_MILLIS; // extend auto-off timer + } + _prevBtnState = btnState; + } + _next_read = millis() + 200; // 5 reads per second + } +#endif + + if (_display->isOn()) { + if (millis() >= _next_refresh) { + _display->startFrame(); + renderCurrScreen(); + _display->endFrame(); + + _next_refresh = millis() + 1000; // refresh every second + } + if (millis() > _auto_off) { + _display->turnOff(); + } + } +} diff --git a/examples/simple_sensor/UITask.h b/examples/simple_sensor/UITask.h new file mode 100644 index 0000000..a27259f --- /dev/null +++ b/examples/simple_sensor/UITask.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +class UITask { + DisplayDriver* _display; + unsigned long _next_read, _next_refresh, _auto_off; + int _prevBtnState; + NodePrefs* _node_prefs; + char _version_info[32]; + + void renderCurrScreen(); +public: + UITask(DisplayDriver& display) : _display(&display) { _next_read = _next_refresh = 0; } + void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version); + + void loop(); +}; \ No newline at end of file diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp new file mode 100644 index 0000000..63122e9 --- /dev/null +++ b/examples/simple_sensor/main.cpp @@ -0,0 +1,128 @@ +#include "SensorMesh.h" + +#ifdef DISPLAY_CLASS + #include "UITask.h" + static UITask ui_task(display); +#endif + +class MyMesh : public SensorMesh { +public: + MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables) + : SensorMesh(board, radio, ms, rng, rtc, tables) { } + +protected: + /* ========================== custom alert logic here ========================== */ + Trigger low_batt; + + void checkForAlerts() override { + alertIfLow(low_batt, getVoltage(TELEM_CHANNEL_SELF), 3.4f, "Battery low!"); + // alertIf ... + // alertIf ... + } + /* ============================================================================= */ +}; + +StdRNG fast_rng; +SimpleMeshTables tables; + +MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock, tables); + +void halt() { + while (1) ; +} + +static char command[80]; + +void setup() { + Serial.begin(115200); + delay(1000); + + board.begin(); + +#ifdef DISPLAY_CLASS + if (display.begin()) { + display.startFrame(); + display.print("Please wait..."); + display.endFrame(); + } +#endif + + if (!radio_init()) { halt(); } + + fast_rng.begin(radio_get_rng_seed()); + + FILESYSTEM* fs; +#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) + InternalFS.begin(); + fs = &InternalFS; + IdentityStore store(InternalFS, ""); +#elif defined(ESP32) + SPIFFS.begin(true); + fs = &SPIFFS; + IdentityStore store(SPIFFS, "/identity"); +#elif defined(RP2040_PLATFORM) + LittleFS.begin(); + fs = &LittleFS; + IdentityStore store(LittleFS, "/identity"); + store.begin(); +#else + #error "need to define filesystem" +#endif + if (!store.load("_main", the_mesh.self_id)) { + MESH_DEBUG_PRINTLN("Generating new keypair"); + the_mesh.self_id = radio_new_identity(); // create new random identity + int count = 0; + while (count < 10 && (the_mesh.self_id.pub_key[0] == 0x00 || the_mesh.self_id.pub_key[0] == 0xFF)) { // reserved id hashes + the_mesh.self_id = radio_new_identity(); count++; + } + store.save("_main", the_mesh.self_id); + } + + Serial.print("Sensor ID: "); + mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println(); + + command[0] = 0; + + sensors.begin(); + + the_mesh.begin(fs); + +#ifdef DISPLAY_CLASS + ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION); +#endif + + // send out initial Advertisement to the mesh + the_mesh.sendSelfAdvertisement(16000); +} + +void loop() { + int len = strlen(command); + while (Serial.available() && len < sizeof(command)-1) { + char c = Serial.read(); + if (c != '\n') { + command[len++] = c; + command[len] = 0; + } + Serial.print(c); + } + if (len == sizeof(command)-1) { // command buffer full + command[sizeof(command)-1] = '\r'; + } + + if (len > 0 && command[len - 1] == '\r') { // received complete line + command[len - 1] = 0; // replace newline with C string null terminator + char reply[160]; + the_mesh.getCLI()->handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + if (reply[0]) { + Serial.print(" -> "); Serial.println(reply); + } + + command[0] = 0; // reset command buffer + } + + the_mesh.loop(); + sensors.loop(); +#ifdef DISPLAY_CLASS + ui_task.loop(); +#endif +} diff --git a/src/helpers/AdvertDataHelpers.h b/src/helpers/AdvertDataHelpers.h index 6da1880..abe14cb 100644 --- a/src/helpers/AdvertDataHelpers.h +++ b/src/helpers/AdvertDataHelpers.h @@ -8,7 +8,8 @@ #define ADV_TYPE_CHAT 1 #define ADV_TYPE_REPEATER 2 #define ADV_TYPE_ROOM 3 -//FUTURE: 4..15 +#define ADV_TYPE_SENSOR 4 +//FUTURE: 5..15 #define ADV_LATLON_MASK 0x10 #define ADV_FEAT1_MASK 0x20 // FUTURE diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index a4b6bf6..edc683d 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -198,3 +198,20 @@ build_src_filter = ${Heltec_lora32_v3.build_src_filter} lib_deps = ${Heltec_lora32_v3.lib_deps} densaugeo/base64 @ ~1.4.0 + +[env:Heltec_WSL3_sensor] +extends = Heltec_lora32_v3 +build_flags = + ${Heltec_lora32_v3.build_flags} + -D ADVERT_NAME='"Heltec Sensor"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' +; -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Heltec_lora32_v3.build_src_filter} + +<../examples/simple_sensor> +lib_deps = + ${Heltec_lora32_v3.lib_deps} + ${esp32_ota.lib_deps} + From 810b1f8fe7a9d0d90a63fc8b775a38897f7f0d96 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 7 Jul 2025 20:41:28 +1000 Subject: [PATCH 03/11] * Mesh::onAnonDataRecv() slight optimisation, so that shared-secret calc doesn't need to be repeated * SensporMesh: req_type now optionally encoded in anon_req payload (so can send various requests without a prior login) --- examples/simple_repeater/main.cpp | 6 +- examples/simple_room_server/main.cpp | 6 +- examples/simple_sensor/SensorMesh.cpp | 111 +++++++++++++++----------- examples/simple_sensor/SensorMesh.h | 7 +- src/Mesh.cpp | 2 +- src/Mesh.h | 4 +- 6 files changed, 76 insertions(+), 60 deletions(-) diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index 71c9f24..d8f1cde 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -149,7 +149,6 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { oldest->id = id; oldest->out_path_len = -1; // initially out_path is unknown oldest->last_timestamp = 0; - self_id.calcSharedSecret(oldest->secret, id); // calc ECDH shared secret return oldest; } @@ -341,8 +340,8 @@ protected: return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } - void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override { - if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) + void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override { + if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) uint32_t timestamp; memcpy(×tamp, data, 4); @@ -369,6 +368,7 @@ protected: client->last_timestamp = timestamp; client->last_activity = getRTCClock()->getCurrentTime(); client->is_admin = is_admin; + memcpy(client->secret, secret, PUB_KEY_SIZE); uint32_t now = getRTCClock()->getCurrentTimeUnique(); memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index c394f3e..b0ee472 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -188,7 +188,6 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { newClient->id = id; newClient->out_path_len = -1; // initially out_path is unknown newClient->last_timestamp = 0; - self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret return newClient; } @@ -432,8 +431,8 @@ protected: return true; } - void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override { - if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) + void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override { + if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) uint32_t sender_timestamp, sender_sync_since; memcpy(&sender_timestamp, data, 4); memcpy(&sender_sync_since, &data[4], 4); // sender's "sync messags SINCE x" timestamp @@ -465,6 +464,7 @@ protected: client->sync_since = sender_sync_since; client->pending_ack = 0; client->push_failures = 0; + memcpy(client->secret, secret, PUB_KEY_SIZE); uint32_t now = getRTCClock()->getCurrentTime(); client->last_activity = now; diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 3b5b04c..92a57f8 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -46,6 +46,7 @@ /* ------------------------------ Code -------------------------------- */ +#define REQ_TYPE_LOGIN 0x00 #define REQ_TYPE_GET_STATUS 0x01 #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 @@ -139,12 +140,10 @@ void SensorMesh::saveContacts() { } } -int SensorMesh::handleRequest(ContactInfo& sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len) { - // uint32_t now = getRTCClock()->getCurrentTimeUnique(); - // memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp +uint8_t SensorMesh::handleRequest(bool is_admin, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') - switch (payload[0]) { + switch (req_type) { case REQ_TYPE_GET_TELEMETRY_DATA: { telemetry.reset(); telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); @@ -253,63 +252,79 @@ int SensorMesh::getAGCResetInterval() const { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } -void SensorMesh::onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) { - if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) +uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data) { + bool is_admin; + if (strcmp((char *) data, _prefs.password) == 0) { // check for valid password + is_admin = true; + } else if (strcmp((char *) data, _prefs.guest_password) == 0) { // check guest password + is_admin = false; + } else { + #if MESH_DEBUG + MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); + #endif + return 0; + } + + auto client = putContact(sender); // add to contacts (if not already known) + if (sender_timestamp <= client->last_timestamp) { + MESH_DEBUG_PRINTLN("Possible login replay attack!"); + return 0; // FATAL: client table is full -OR- replay attack + } + + MESH_DEBUG_PRINTLN("Login success!"); + client->last_timestamp = sender_timestamp; + client->last_activity = getRTCClock()->getCurrentTime(); + client->type = is_admin ? 1 : 0; + memcpy(client->shared_secret, secret, PUB_KEY_SIZE); + + if (is_admin) { + // only need to saveContacts() if this is an admin + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); + } + + uint32_t now = getRTCClock()->getCurrentTimeUnique(); + memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp + reply_data[4] = RESP_SERVER_LOGIN_OK; + reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16) + reply_data[6] = client->type; + reply_data[7] = 0; // FUTURE: reserved + getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness + + return 12; // reply length +} + +void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) { + if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) uint32_t timestamp; memcpy(×tamp, data, 4); - bool is_admin; data[len] = 0; // ensure null terminator - if (strcmp((char *) &data[4], _prefs.password) == 0) { // check for valid password - is_admin = true; - } else if (strcmp((char *) &data[4], _prefs.guest_password) == 0) { // check guest password - is_admin = false; + + uint8_t req_code; + uint8_t i = 4; + if (data[4] < 32) { // non-print char, is a request code + req_code = data[i++]; } else { - #if MESH_DEBUG - MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); - #endif - return; + req_code = REQ_TYPE_LOGIN; } - auto client = putContact(sender); // add to contacts (if not already known) - if (timestamp <= client->last_timestamp) { - MESH_DEBUG_PRINTLN("Possible login replay attack!"); - return; // FATAL: client table is full -OR- replay attack + uint8_t reply_len; + if (req_code == REQ_TYPE_LOGIN) { + reply_len = handleLoginReq(sender, secret, timestamp, &data[i]); + } else { + reply_len = handleRequest(false, timestamp, req_code, &data[i], len - i); } - MESH_DEBUG_PRINTLN("Login success!"); - client->last_timestamp = timestamp; - client->last_activity = getRTCClock()->getCurrentTime(); - client->type = is_admin ? 1 : 0; - self_id.calcSharedSecret(client->shared_secret, client->id); // calc ECDH shared secret - - if (is_admin) { - // only need to saveContacts() if this is an admin - dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); - } - - uint32_t now = getRTCClock()->getCurrentTimeUnique(); - memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp - reply_data[4] = RESP_SERVER_LOGIN_OK; - reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16) - reply_data[6] = client->type; - reply_data[7] = 0; // FUTURE: reserved - getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness + if (reply_len == 0) return; // invalid request if (packet->isRouteFlood()) { // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response - mesh::Packet* path = createPathReturn(sender, client->shared_secret, packet->path, packet->path_len, - PAYLOAD_TYPE_RESPONSE, reply_data, 12); + mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len, + PAYLOAD_TYPE_RESPONSE, reply_data, reply_len); if (path) sendFlood(path, SERVER_RESPONSE_DELAY); } else { - mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->shared_secret, reply_data, 12); - if (reply) { - if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT - sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY); - } else { - sendFlood(reply, SERVER_RESPONSE_DELAY); - } - } + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); + if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY); } } } @@ -361,7 +376,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i memcpy(×tamp, data, 4); if (timestamp > from.last_timestamp) { // prevent replay attacks - int reply_len = handleRequest(from, timestamp, &data[4], len - 4); + uint8_t reply_len = handleRequest(from.isAdmin(), timestamp, data[4], &data[5], len - 5); if (reply_len == 0) return; // invalid command from.last_timestamp = timestamp; diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 051d664..6293b21 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -103,10 +103,10 @@ protected: uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override; int getInterferenceThreshold() const override; int getAGCResetInterval() const override; - void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override; + void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override; int searchPeersByHash(const uint8_t* hash) override; void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override; - void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len); + void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override; void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override; bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; @@ -125,7 +125,8 @@ private: void loadContacts(); void saveContacts(); - int handleRequest(ContactInfo& sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len); + uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data); + uint8_t handleRequest(bool is_admin, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); ContactInfo* putContact(const mesh::Identity& id); diff --git a/src/Mesh.cpp b/src/Mesh.cpp index 87f9987..f34f6f7 100644 --- a/src/Mesh.cpp +++ b/src/Mesh.cpp @@ -181,7 +181,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) { uint8_t data[MAX_PACKET_PAYLOAD]; int len = Utils::MACThenDecrypt(secret, data, macAndData, pkt->payload_len - i); if (len > 0) { // success! - onAnonDataRecv(pkt, pkt->getPayloadType(), sender, data, len); + onAnonDataRecv(pkt, secret, sender, data, len); pkt->markDoNotRetransmit(); } } diff --git a/src/Mesh.h b/src/Mesh.h index 9649187..b2047ac 100644 --- a/src/Mesh.h +++ b/src/Mesh.h @@ -107,10 +107,10 @@ protected: /** * \brief A (now decrypted) data packet has been received. * NOTE: these can be received multiple times (per sender/contents), via different routes - * \param type one of: PAYLOAD_TYPE_ANON_REQ + * \param secret ECDH shared secret * \param sender public key provided by sender */ - virtual void onAnonDataRecv(Packet* packet, uint8_t type, const Identity& sender, uint8_t* data, size_t len) { } + virtual void onAnonDataRecv(Packet* packet, const uint8_t* secret, const Identity& sender, uint8_t* data, size_t len) { } /** * \brief A path TO 'sender' has been received. (also with optional 'extra' data encoded) From de3e4bc27c3e0c3ec9bc088f5b43a439ceb1773b Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 7 Jul 2025 22:59:01 +1000 Subject: [PATCH 04/11] * added REQ_TYPE_GET_AVG_MIN_MAX * TimeSeriesData * very basic SensorMesh::sendAlert() --- examples/simple_sensor/SensorMesh.cpp | 91 ++++++++++++++++++++++++++- examples/simple_sensor/SensorMesh.h | 30 ++++++++- examples/simple_sensor/main.cpp | 24 ++++--- 3 files changed, 135 insertions(+), 10 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 92a57f8..df568dd 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -50,6 +50,7 @@ #define REQ_TYPE_GET_STATUS 0x01 #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 +#define REQ_TYPE_GET_AVG_MIN_MAX 0x04 #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ @@ -154,6 +155,22 @@ uint8_t SensorMesh::handleRequest(bool is_admin, uint32_t sender_timestamp, uint memcpy(&reply_data[4], telemetry.getBuffer(), tlen); return 4 + tlen; // reply_len } + case REQ_TYPE_GET_AVG_MIN_MAX: { + uint32_t start_secs_ago, end_secs_ago; + memcpy(&start_secs_ago, &payload[0], 4); + memcpy(&end_secs_ago, &payload[4], 4); + uint8_t res1 = payload[8]; // reserved for future (extra query params) + uint8_t res2 = payload[8]; + + MinMaxAvg data[8]; + int n; + if (res1 == 0 && res2 == 0) { + n = querySeriesData(start_secs_ago, end_secs_ago, data, 8); + } else { + n = 0; + } + return 0; // TODO: encode data[0..n) + } } return 0; // unknown command } @@ -192,6 +209,34 @@ ContactInfo* SensorMesh::putContact(const mesh::Identity& id) { return c; } +void SensorMesh::sendAlert(const char* text) { + int text_len = strlen(text); + + // send text message to all admins + for (int i = 0; i < num_contacts; i++) { + auto c = &contacts[i]; + if (!c->isAdmin()) continue; + + uint8_t data[MAX_PACKET_PAYLOAD]; + uint32_t now = getRTCClock()->getCurrentTimeUnique(); // need different timestamp per packet + memcpy(data, &now, 4); + data[4] = (TXT_TYPE_PLAIN << 2); // attempt and flags + memcpy(&data[5], text, text_len); + // calc expected ACK reply + // uint32_t expected_ack; + // mesh::Utils::sha256((uint8_t *)&expected_ack, 4, data, 5 + text_len, self_id.pub_key, PUB_KEY_SIZE); + + auto pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, c->id, c->shared_secret, data, 5 + text_len); + if (pkt) { + if (c->out_path_len >= 0) { // we have an out_path, so send DIRECT + sendDirect(pkt, c->out_path, c->out_path_len); + } else { + sendFlood(pkt); + } + } + } +} + void SensorMesh::alertIfLow(Trigger& t, float value, float threshold, const char* text) { if (value < threshold) { if (!t.triggered) { @@ -222,6 +267,50 @@ void SensorMesh::alertIfHigh(Trigger& t, float value, float threshold, const cha } } +void SensorMesh::recordData(TimeSeriesData& data, float value) { + uint32_t now = getRTCClock()->getCurrentTime(); + if (now >= data.last_timestamp + data.interval_secs) { + data.last_timestamp = now; + + data.data[data.next] = value; // append to cycle table + data.next = (data.next + 1) % data.num_slots; + } +} + +void SensorMesh::calcDataMinMaxAvg(const TimeSeriesData& data, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) { + int i = data.next, n = data.num_slots; + uint32_t ago = data.interval_secs * data.num_slots; + int num_values = 0; + float total = 0.0f; + + dest->_channel = channel; + dest->_lpp_type = lpp_type; + + // start at earliest recording, through to most recent + while (n > 0) { + n--; + i = (i + 1) % data.num_slots; + if (ago >= end_secs_ago && ago < start_secs_ago) { + float v = data.data[i]; + num_values++; + total += v; + if (num_values == 1) { + dest->_max = dest->_min = v; + } else { + if (v < dest->_min) dest->_min = v; + if (v > dest->_max) dest->_max = v; + } + } + ago -= data.interval_secs; + } + // calc average + if (num_values > 0) { + dest->_avg = total / num_values; + } else { + dest->_avg = NAN; + } +} + float SensorMesh::getAirtimeBudgetFactor() const { return _prefs.airtime_factor; } @@ -577,7 +666,7 @@ void SensorMesh::loop() { // query other sensors -- target specific sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions - checkForAlerts(); + onSensorDataRead(); // save telemetry to time-series datastore File file = openAppend(_fs, "/s_data"); diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 6293b21..0f94b12 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -93,7 +93,33 @@ protected: void alertIfLow(Trigger& t, float value, float threshold, const char* text); void alertIfHigh(Trigger& t, float value, float threshold, const char* text); - virtual void checkForAlerts() = 0; // for app to implement + class TimeSeriesData { + public: + float* data; + int num_slots, next; + uint32_t last_timestamp; + uint32_t interval_secs; + + TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { + memset(data, 0, sizeof(float)*num); + } + TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { + data = new float[num]; + memset(data, 0, sizeof(float)*num); + } + }; + + void recordData(TimeSeriesData& data, float value); + + struct MinMaxAvg { + float _min, _max, _avg; + uint8_t _lpp_type, _channel; + }; + + void calcDataMinMaxAvg(const TimeSeriesData& data, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type); + + virtual void onSensorDataRead() = 0; // for app to implement + virtual int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) = 0; // for app to implement // Mesh overrides float getAirtimeBudgetFactor() const override; @@ -130,6 +156,6 @@ private: mesh::Packet* createSelfAdvert(); ContactInfo* putContact(const mesh::Identity& id); - void sendAlert(const char* text) { } // TODO + void sendAlert(const char* text); }; diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 63122e9..500efef 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -8,18 +8,28 @@ class MyMesh : public SensorMesh { public: MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables) - : SensorMesh(board, radio, ms, rng, rtc, tables) { } + : SensorMesh(board, radio, ms, rng, rtc, tables), + battery_data(12*24, 5*60) // 24 hours worth of battery data, every 5 minutes + { + } protected: - /* ========================== custom alert logic here ========================== */ + /* ========================== custom logic here ========================== */ Trigger low_batt; + TimeSeriesData battery_data; - void checkForAlerts() override { - alertIfLow(low_batt, getVoltage(TELEM_CHANNEL_SELF), 3.4f, "Battery low!"); - // alertIf ... - // alertIf ... + void onSensorDataRead() override { + float batt_voltage = getVoltage(TELEM_CHANNEL_SELF); + + recordData(battery_data, batt_voltage); // record battery + alertIfLow(low_batt, batt_voltage, 3.4f, "Battery low!"); } - /* ============================================================================= */ + + int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override { + calcDataMinMaxAvg(battery_data, start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); + return 1; + } + /* ======================================================================= */ }; StdRNG fast_rng; From ac834922dee1782b8aaa6c674a45be635c76b19d Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 16:35:11 +1000 Subject: [PATCH 05/11] * simplified alertIf() * refactored TimeSeriesData to top-level class --- examples/simple_sensor/SensorMesh.cpp | 63 +---------------------- examples/simple_sensor/SensorMesh.h | 30 ++--------- examples/simple_sensor/TimeSeriesData.cpp | 45 ++++++++++++++++ examples/simple_sensor/TimeSeriesData.h | 29 +++++++++++ examples/simple_sensor/main.cpp | 6 +-- 5 files changed, 82 insertions(+), 91 deletions(-) create mode 100644 examples/simple_sensor/TimeSeriesData.cpp create mode 100644 examples/simple_sensor/TimeSeriesData.h diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index df568dd..fa08b15 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -237,8 +237,8 @@ void SensorMesh::sendAlert(const char* text) { } } -void SensorMesh::alertIfLow(Trigger& t, float value, float threshold, const char* text) { - if (value < threshold) { +void SensorMesh::alertIf(bool condition, Trigger& t, const char* text) { + if (condition) { if (!t.triggered) { t.triggered = true; t.time = getRTCClock()->getCurrentTime(); @@ -252,65 +252,6 @@ void SensorMesh::alertIfLow(Trigger& t, float value, float threshold, const char } } -void SensorMesh::alertIfHigh(Trigger& t, float value, float threshold, const char* text) { - if (value > threshold) { - if (!t.triggered) { - t.triggered = true; - t.time = getRTCClock()->getCurrentTime(); - sendAlert(text); - } - } else { - if (t.triggered) { - t.triggered = false; - // TODO: apply debounce logic - } - } -} - -void SensorMesh::recordData(TimeSeriesData& data, float value) { - uint32_t now = getRTCClock()->getCurrentTime(); - if (now >= data.last_timestamp + data.interval_secs) { - data.last_timestamp = now; - - data.data[data.next] = value; // append to cycle table - data.next = (data.next + 1) % data.num_slots; - } -} - -void SensorMesh::calcDataMinMaxAvg(const TimeSeriesData& data, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) { - int i = data.next, n = data.num_slots; - uint32_t ago = data.interval_secs * data.num_slots; - int num_values = 0; - float total = 0.0f; - - dest->_channel = channel; - dest->_lpp_type = lpp_type; - - // start at earliest recording, through to most recent - while (n > 0) { - n--; - i = (i + 1) % data.num_slots; - if (ago >= end_secs_ago && ago < start_secs_ago) { - float v = data.data[i]; - num_values++; - total += v; - if (num_values == 1) { - dest->_max = dest->_min = v; - } else { - if (v < dest->_min) dest->_min = v; - if (v > dest->_max) dest->_max = v; - } - } - ago -= data.interval_secs; - } - // calc average - if (num_values > 0) { - dest->_avg = total / num_values; - } else { - dest->_avg = NAN; - } -} - float SensorMesh::getAirtimeBudgetFactor() const { return _prefs.airtime_factor; } diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 0f94b12..e8b4d88 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -3,6 +3,8 @@ #include // needed for PlatformIO #include +#include "TimeSeriesData.h" + #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include #elif defined(RP2040_PLATFORM) @@ -90,33 +92,7 @@ protected: Trigger() { triggered = false; time = 0; } }; - void alertIfLow(Trigger& t, float value, float threshold, const char* text); - void alertIfHigh(Trigger& t, float value, float threshold, const char* text); - - class TimeSeriesData { - public: - float* data; - int num_slots, next; - uint32_t last_timestamp; - uint32_t interval_secs; - - TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { - memset(data, 0, sizeof(float)*num); - } - TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { - data = new float[num]; - memset(data, 0, sizeof(float)*num); - } - }; - - void recordData(TimeSeriesData& data, float value); - - struct MinMaxAvg { - float _min, _max, _avg; - uint8_t _lpp_type, _channel; - }; - - void calcDataMinMaxAvg(const TimeSeriesData& data, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type); + void alertIf(bool condition, Trigger& t, const char* text); virtual void onSensorDataRead() = 0; // for app to implement virtual int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) = 0; // for app to implement diff --git a/examples/simple_sensor/TimeSeriesData.cpp b/examples/simple_sensor/TimeSeriesData.cpp new file mode 100644 index 0000000..ff7daa2 --- /dev/null +++ b/examples/simple_sensor/TimeSeriesData.cpp @@ -0,0 +1,45 @@ +#include "TimeSeriesData.h" + +void TimeSeriesData::recordData(mesh::RTCClock* clock, float value) { + uint32_t now = clock->getCurrentTime(); + if (now >= last_timestamp + interval_secs) { + last_timestamp = now; + + data[next] = value; // append to cycle table + next = (next + 1) % num_slots; + } +} + +void TimeSeriesData::calcDataMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const { + int i = next, n = num_slots; + uint32_t ago = clock->getCurrentTime() - last_timestamp; + int num_values = 0; + float total = 0.0f; + + dest->_channel = channel; + dest->_lpp_type = lpp_type; + + // start at most recet recording, back-track through to oldest + while (n > 0) { + n--; + i = (i + num_slots - 1) % num_slots; // go back by one + if (ago >= end_secs_ago && ago < start_secs_ago) { // filter by the desired time range + float v = data[i]; + num_values++; + total += v; + if (num_values == 1) { + dest->_max = dest->_min = v; + } else { + if (v < dest->_min) dest->_min = v; + if (v > dest->_max) dest->_max = v; + } + } + ago += interval_secs; + } + // calc average + if (num_values > 0) { + dest->_avg = total / num_values; + } else { + dest->_avg = NAN; + } +} diff --git a/examples/simple_sensor/TimeSeriesData.h b/examples/simple_sensor/TimeSeriesData.h new file mode 100644 index 0000000..ea9e823 --- /dev/null +++ b/examples/simple_sensor/TimeSeriesData.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +struct MinMaxAvg { + float _min, _max, _avg; + uint8_t _lpp_type, _channel; +}; + +class TimeSeriesData { + float* data; + int num_slots, next; + uint32_t last_timestamp; + uint32_t interval_secs; + +public: + TimeSeriesData(float* array, int num, uint32_t secs) : num_slots(num), data(array), last_timestamp(0), next(0), interval_secs(secs) { + memset(data, 0, sizeof(float)*num); + } + TimeSeriesData(int num, uint32_t secs) : num_slots(num), last_timestamp(0), next(0), interval_secs(secs) { + data = new float[num]; + memset(data, 0, sizeof(float)*num); + } + + void recordData(mesh::RTCClock* clock, float value); + void calcDataMinMaxAvg(mesh::RTCClock* clock, uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg* dest, uint8_t channel, uint8_t lpp_type) const; +}; + diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 500efef..03d5cb5 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -21,12 +21,12 @@ protected: void onSensorDataRead() override { float batt_voltage = getVoltage(TELEM_CHANNEL_SELF); - recordData(battery_data, batt_voltage); // record battery - alertIfLow(low_batt, batt_voltage, 3.4f, "Battery low!"); + battery_data.recordData(getRTCClock(), batt_voltage); // record battery + alertIf(batt_voltage < 3.4f, low_batt, "Battery low!"); } int querySeriesData(uint32_t start_secs_ago, uint32_t end_secs_ago, MinMaxAvg dest[], int max_num) override { - calcDataMinMaxAvg(battery_data, start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); + battery_data.calcDataMinMaxAvg(getRTCClock(), start_secs_ago, end_secs_ago, &dest[0], TELEM_CHANNEL_SELF, LPP_VOLTAGE); return 1; } /* ======================================================================= */ From 9cecbad2a7d4c8847b487e9247ee738d134e1d72 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 17:50:06 +1000 Subject: [PATCH 06/11] * refactor: CommonCLI, processing of optional command prefix moved to handleCommand() call sites * Sensor, anon_req now just for admin login (guest password now unused) * special CLI command, "setperm {pubkey-hex} {permissions-int16}" for admin(s) to manage user access (permissions 0 = remove) --- examples/simple_repeater/main.cpp | 20 +++- examples/simple_room_server/main.cpp | 20 +++- examples/simple_sensor/SensorMesh.cpp | 150 +++++++++++++++----------- examples/simple_sensor/SensorMesh.h | 14 ++- examples/simple_sensor/main.cpp | 2 +- src/helpers/CommonCLI.cpp | 8 -- 6 files changed, 125 insertions(+), 89 deletions(-) diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index d8f1cde..cd9ee12 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -500,12 +500,12 @@ protected: } uint8_t temp[166]; - const char *command = (const char *) &data[5]; + char *command = (char *) &data[5]; char *reply = (char *) &temp[5]; if (is_retry) { *reply = 0; } else { - _cli.handleCommand(sender_timestamp, command, reply); + handleCommand(sender_timestamp, command, reply); } int text_len = strlen(reply); if (text_len > 0) { @@ -581,8 +581,6 @@ public: _prefs.interference_threshold = 0; // disabled } - CommonCLI* getCLI() { return &_cli; } - void begin(FILESYSTEM* fs) { mesh::Mesh::begin(); _fs = fs; @@ -706,6 +704,18 @@ public: ((SimpleMeshTables *)getTables())->resetStats(); } + void handleCommand(uint32_t sender_timestamp, char* command, char* reply) { + while (*command == ' ') command++; // skip leading spaces + + if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) + memcpy(reply, command, 3); // reflect the prefix back + reply += 3; + command += 3; + } + + _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands + } + void loop() { mesh::Mesh::loop(); @@ -817,7 +827,7 @@ void loop() { if (len > 0 && command[len - 1] == '\r') { // received complete line command[len - 1] = 0; // replace newline with C string null terminator char reply[160]; - the_mesh.getCLI()->handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! if (reply[0]) { Serial.print(" -> "); Serial.println(reply); } diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index b0ee472..a1400cb 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -333,7 +333,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { } return 0; // unknown command } - + protected: float getAirtimeBudgetFactor() const override { return _prefs.airtime_factor; @@ -555,7 +555,7 @@ protected: if (is_retry) { temp[5] = 0; // no reply } else { - _cli.handleCommand(sender_timestamp, (const char *) &data[5], (char *) &temp[5]); + handleCommand(sender_timestamp, (char *) &data[5], (char *) &temp[5]); temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN) } send_ack = false; @@ -743,8 +743,6 @@ public: _num_posted = _num_post_pushes = 0; } - CommonCLI* getCLI() { return &_cli; } - void begin(FILESYSTEM* fs) { mesh::Mesh::begin(); _fs = fs; @@ -845,6 +843,18 @@ public: ((SimpleMeshTables *)getTables())->resetStats(); } + void handleCommand(uint32_t sender_timestamp, char* command, char* reply) { + while (*command == ' ') command++; // skip leading spaces + + if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) + memcpy(reply, command, 3); // reflect the prefix back + reply += 3; + command += 3; + } + + _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands + } + void loop() { mesh::Mesh::loop(); @@ -998,7 +1008,7 @@ void loop() { if (len > 0 && command[len - 1] == '\r') { // received complete line command[len - 1] = 0; // replace newline with C string null terminator char reply[160]; - the_mesh.getCLI()->handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! if (reply[0]) { Serial.print(" -> "); Serial.println(reply); } diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index fa08b15..8b1b6f2 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -92,12 +92,11 @@ void SensorMesh::loadContacts() { while (!full) { ContactInfo c; uint8_t pub_key[32]; - uint8_t unused; + uint8_t unused[5]; bool success = (file.read(pub_key, 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.permissions, 2) == 2); + success = success && (file.read(unused, 5) == 5); success = success && (file.read((uint8_t *)&c.out_path_len, 1) == 1); success = success && (file.read(c.out_path, 64) == 64); success = success && (file.read(c.shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE); @@ -121,16 +120,16 @@ void SensorMesh::loadContacts() { void SensorMesh::saveContacts() { File file = openWrite(_fs, "/s_contacts"); if (file) { - uint8_t unused = 0; + uint8_t unused[5]; + memset(unused, 0, sizeof(unused)); for (int i = 0; i < num_contacts; i++) { auto c = &contacts[i]; - if (c->type == 0) continue; // don't persist guest contacts + if (c->permissions == 0) continue; // skip deleted entries bool success = (file.write(c->id.pub_key, 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->permissions, 2) == 2); + success = success && (file.write(unused, 5) == 5); success = success && (file.write((uint8_t *)&c->out_path_len, 1) == 1); success = success && (file.write(c->out_path, 64) == 64); success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE); @@ -141,36 +140,34 @@ void SensorMesh::saveContacts() { } } -uint8_t SensorMesh::handleRequest(bool is_admin, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { +uint8_t SensorMesh::handleRequest(uint16_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') - switch (req_type) { - case REQ_TYPE_GET_TELEMETRY_DATA: { - telemetry.reset(); - telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); - // query other sensors -- target specific - sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions for admin or guest + if (req_type == REQ_TYPE_GET_TELEMETRY_DATA && (perms & PERM_GET_TELEMETRY) != 0) { + telemetry.reset(); + telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + // query other sensors -- target specific + sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions for admin or guest - uint8_t tlen = telemetry.getSize(); - memcpy(&reply_data[4], telemetry.getBuffer(), tlen); - return 4 + tlen; // reply_len - } - case REQ_TYPE_GET_AVG_MIN_MAX: { - uint32_t start_secs_ago, end_secs_ago; - memcpy(&start_secs_ago, &payload[0], 4); - memcpy(&end_secs_ago, &payload[4], 4); - uint8_t res1 = payload[8]; // reserved for future (extra query params) - uint8_t res2 = payload[8]; + uint8_t tlen = telemetry.getSize(); + memcpy(&reply_data[4], telemetry.getBuffer(), tlen); + return 4 + tlen; // reply_len + } + if (req_type == REQ_TYPE_GET_AVG_MIN_MAX && (perms & PERM_GET_MIN_MAX_AVG) != 0) { + uint32_t start_secs_ago, end_secs_ago; + memcpy(&start_secs_ago, &payload[0], 4); + memcpy(&end_secs_ago, &payload[4], 4); + uint8_t res1 = payload[8]; // reserved for future (extra query params) + uint8_t res2 = payload[8]; - MinMaxAvg data[8]; - int n; - if (res1 == 0 && res2 == 0) { - n = querySeriesData(start_secs_ago, end_secs_ago, data, 8); - } else { - n = 0; - } - return 0; // TODO: encode data[0..n) + MinMaxAvg data[8]; + int n; + if (res1 == 0 && res2 == 0) { + n = querySeriesData(start_secs_ago, end_secs_ago, data, 8); + } else { + n = 0; } + return 0; // TODO: encode data[0..n) } return 0; // unknown command } @@ -209,6 +206,18 @@ ContactInfo* SensorMesh::putContact(const mesh::Identity& id) { return c; } +void SensorMesh::applyContactPermissions(const uint8_t* pubkey, uint16_t perms) { + mesh::Identity id(pubkey); + auto c = putContact(id); + + if (perms == 0) { // no permissions, remove from contacts + memset(c, 0, sizeof(*c)); + } else { + c->permissions = perms; // update their permissions + } + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger saveContacts() +} + void SensorMesh::sendAlert(const char* text) { int text_len = strlen(text); @@ -283,12 +292,7 @@ int SensorMesh::getAGCResetInterval() const { } uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data) { - bool is_admin; - if (strcmp((char *) data, _prefs.password) == 0) { // check for valid password - is_admin = true; - } else if (strcmp((char *) data, _prefs.guest_password) == 0) { // check guest password - is_admin = false; - } else { + if (strcmp((char *) data, _prefs.password) != 0) { // check for valid password #if MESH_DEBUG MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); #endif @@ -304,46 +308,61 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* MESH_DEBUG_PRINTLN("Login success!"); client->last_timestamp = sender_timestamp; client->last_activity = getRTCClock()->getCurrentTime(); - client->type = is_admin ? 1 : 0; + client->permissions = PERM_IS_ADMIN; memcpy(client->shared_secret, secret, PUB_KEY_SIZE); - if (is_admin) { - // only need to saveContacts() if this is an admin - dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); - } + dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); uint32_t now = getRTCClock()->getCurrentTimeUnique(); memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp reply_data[4] = RESP_SERVER_LOGIN_OK; reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16) - reply_data[6] = client->type; + reply_data[6] = 1; // 1 = is admin reply_data[7] = 0; // FUTURE: reserved getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness return 12; // reply length } +void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* reply) { + while (*command == ' ') command++; // skip leading spaces + + if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) + memcpy(reply, command, 3); // reflect the prefix back + reply += 3; + command += 3; + } + + // handle sensor-specific CLI commands + if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int16} + char* hex = &command[8]; + char* sp = strchr(hex, ' '); // look for separator char + if (sp == NULL || sp - hex != PUB_KEY_SIZE*2) { + strcpy(reply, "Err - bad pubkey len"); + } else { + *sp++ = 0; // replace space with null terminator + + uint8_t pubkey[PUB_KEY_SIZE]; + if (mesh::Utils::fromHex(pubkey, PUB_KEY_SIZE, hex)) { + uint16_t perms = atoi(sp); + applyContactPermissions(pubkey, perms); + strcpy(reply, "OK"); + } else { + strcpy(reply, "Err - bad pubkey"); + } + } + } else { + _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands + } +} + void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) { if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage) uint32_t timestamp; memcpy(×tamp, data, 4); data[len] = 0; // ensure null terminator - - uint8_t req_code; - uint8_t i = 4; - if (data[4] < 32) { // non-print char, is a request code - req_code = data[i++]; - } else { - req_code = REQ_TYPE_LOGIN; - } - - uint8_t reply_len; - if (req_code == REQ_TYPE_LOGIN) { - reply_len = handleLoginReq(sender, secret, timestamp, &data[i]); - } else { - reply_len = handleRequest(false, timestamp, req_code, &data[i], len - i); - } + uint8_t reply_len = handleLoginReq(sender, secret, timestamp, &data[4]); if (reply_len == 0) return; // invalid request @@ -406,7 +425,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i memcpy(×tamp, data, 4); if (timestamp > from.last_timestamp) { // prevent replay attacks - uint8_t reply_len = handleRequest(from.isAdmin(), timestamp, data[4], &data[5], len - 5); + uint8_t reply_len = handleRequest(from.isAdmin() ? 0xFFFF : from.permissions, timestamp, data[4], &data[5], len - 5); if (reply_len == 0) return; // invalid command from.last_timestamp = timestamp; @@ -445,9 +464,9 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i data[len] = 0; // need to make a C string again, with null terminator uint8_t temp[166]; - const char *command = (const char *) &data[5]; + char *command = (char *) &data[5]; char *reply = (char *) &temp[5]; - _cli.handleCommand(sender_timestamp, command, reply); + handleCommand(sender_timestamp, command, reply); int text_len = strlen(reply); if (text_len > 0) { @@ -489,8 +508,9 @@ bool SensorMesh::onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect() from.last_activity = getRTCClock()->getCurrentTime(); + // REVISIT: maybe make ALL out_paths non-persisted to minimise flash writes?? if (from.isAdmin()) { - // only need to saveContacts() if this is an admin + // only do saveContacts() (of this out_path change) if this is an admin dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); } diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index e8b4d88..196acb8 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -23,17 +23,20 @@ #include #include +#define PERM_IS_ADMIN 0x8000 +#define PERM_GET_TELEMETRY 0x0001 +#define PERM_GET_MIN_MAX_AVG 0x0002 + struct ContactInfo { mesh::Identity id; - uint8_t type; // 1 = admin, 0 = guest - uint8_t flags; + uint16_t permissions; int8_t out_path_len; uint8_t out_path[MAX_PATH_SIZE]; uint8_t shared_secret[PUB_KEY_SIZE]; uint32_t last_timestamp; // by THEIR clock (transient) uint32_t last_activity; // by OUR clock (transient) - bool isAdmin() const { return type != 0; } + bool isAdmin() const { return (permissions & PERM_IS_ADMIN) != 0; } }; #ifndef FIRMWARE_BUILD_DATE @@ -56,8 +59,8 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { public: SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables); void begin(FILESYSTEM* fs); - CommonCLI* getCLI() { return &_cli; } void loop(); + void handleCommand(uint32_t sender_timestamp, char* command, char* reply); // CommonCLI callbacks const char* getFirmwareVer() override { return FIRMWARE_VERSION; } @@ -128,9 +131,10 @@ private: void loadContacts(); void saveContacts(); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data); - uint8_t handleRequest(bool is_admin, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); + uint8_t handleRequest(uint16_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); ContactInfo* putContact(const mesh::Identity& id); + void applyContactPermissions(const uint8_t* pubkey, uint16_t perms); void sendAlert(const char* text); diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 03d5cb5..25610a6 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -122,7 +122,7 @@ void loop() { if (len > 0 && command[len - 1] == '\r') { // received complete line command[len - 1] = 0; // replace newline with C string null terminator char reply[160]; - the_mesh.getCLI()->handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! if (reply[0]) { Serial.print(" -> "); Serial.println(reply); } diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 323f363..97b4ffe 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -127,14 +127,6 @@ void CommonCLI::checkAdvertInterval() { } void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, char* reply) { - while (*command == ' ') command++; // skip leading spaces - - if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) - memcpy(reply, command, 3); // reflect the prefix back - reply += 3; - command += 3; - } - if (memcmp(command, "reboot", 6) == 0) { _board->reboot(); // doesn't return } else if (memcmp(command, "advert", 6) == 0) { From 29435342b0eedede0841d06bce983057ab10933e Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 20:41:26 +1000 Subject: [PATCH 07/11] * implemented getter methods for telemetry value types --- examples/simple_sensor/SensorMesh.cpp | 119 ++++++++++++++++++++++---- examples/simple_sensor/SensorMesh.h | 14 ++- src/helpers/CommonCLI.cpp | 7 +- src/helpers/CommonCLI.h | 5 +- 4 files changed, 115 insertions(+), 30 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 8b1b6f2..293a503 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -221,10 +221,10 @@ void SensorMesh::applyContactPermissions(const uint8_t* pubkey, uint16_t perms) void SensorMesh::sendAlert(const char* text) { int text_len = strlen(text); - // send text message to all admins + // send text message to all contacts with RECV_ALERT permission for (int i = 0; i < num_contacts; i++) { auto c = &contacts[i]; - if (!c->isAdmin()) continue; + if ((c->permissions & PERM_RECV_ALERTS) == 0) continue; // contact does NOT want alerts uint8_t data[MAX_PACKET_PAYLOAD]; uint32_t now = getRTCClock()->getCurrentTimeUnique(); // need different timestamp per packet @@ -308,7 +308,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* MESH_DEBUG_PRINTLN("Login success!"); client->last_timestamp = sender_timestamp; client->last_activity = getRTCClock()->getCurrentTime(); - client->permissions = PERM_IS_ADMIN; + client->permissions = PERM_IS_ADMIN | PERM_RECV_ALERTS; memcpy(client->shared_secret, secret, PUB_KEY_SIZE); dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); @@ -542,7 +542,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise _prefs.cr = LORA_CR; _prefs.tx_power_dbm = LORA_TX_POWER; _prefs.advert_interval = 1; // default to 2 minutes for NEW installs - _prefs.flood_advert_interval = 3; // 3 hours + _prefs.flood_advert_interval = 0; // disabled _prefs.disable_fwd = true; _prefs.flood_max = 64; _prefs.interference_threshold = 0; // disabled @@ -604,6 +604,102 @@ void SensorMesh::setTxPower(uint8_t power_dbm) { radio_set_tx_power(power_dbm); } +static uint8_t getDataSize(uint8_t type) { + switch (type) { + case LPP_GPS: + return 9; + case LPP_POLYLINE: + return 8; // TODO: this is MINIMIUM + case LPP_GYROMETER: + case LPP_ACCELEROMETER: + return 6; + case LPP_GENERIC_SENSOR: + case LPP_FREQUENCY: + case LPP_DISTANCE: + case LPP_ENERGY: + case LPP_UNIXTIME: + return 4; + case LPP_COLOUR: + return 3; + case LPP_ANALOG_INPUT: + case LPP_ANALOG_OUTPUT: + case LPP_LUMINOSITY: + case LPP_TEMPERATURE: + case LPP_CONCENTRATION: + case LPP_BAROMETRIC_PRESSURE: + case LPP_ALTITUDE: + case LPP_VOLTAGE: + case LPP_CURRENT: + case LPP_DIRECTION: + case LPP_POWER: + return 2; + } + return 1; +} + +static uint32_t getMultiplier(uint8_t type) { + switch (type) { + case LPP_CURRENT: + case LPP_DISTANCE: + case LPP_ENERGY: + return 1000; + case LPP_VOLTAGE: + case LPP_ANALOG_INPUT: + case LPP_ANALOG_OUTPUT: + return 100; + case LPP_TEMPERATURE: + case LPP_BAROMETRIC_PRESSURE: + return 10; + } + return 1; +} + +static bool isSigned(uint8_t type) { + return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER || + type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER; +} + +static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { + uint32_t value = 0; + for (uint8_t i = 0; i < size; i++) { + value = (value << 8) + buffer[i]; + } + + int sign = 1; + if (is_signed) { + uint32_t bit = 1ul << ((size * 8) - 1); + if ((value & bit) == bit) { + value = (bit << 1) - value; + sign = -1; + } + } + return sign * ((float) value / multiplier); +} + +float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) { + auto buf = telemetry.getBuffer(); + uint8_t size = telemetry.getSize(); + uint8_t i = 0; + + while (i + 2 < size) { + // Get channel # + uint8_t ch = buf[i++]; + // Get data type + uint8_t t = buf[i++]; + uint8_t sz = getDataSize(t); + + if (ch == channel && t == type) { + return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); + } + i += sz; // skip + } + return 0.0f; // not found +} + +bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { + return false; // TODO +} + void SensorMesh::loop() { mesh::Mesh::loop(); @@ -629,21 +725,6 @@ void SensorMesh::loop() { onSensorDataRead(); - // save telemetry to time-series datastore - File file = openAppend(_fs, "/s_data"); - if (file) { - file.write((uint8_t *)&curr, 4); // start record with RTC timestamp - uint8_t tlen = telemetry.getSize(); - file.write(&tlen, 1); - file.write(telemetry.getBuffer(), tlen); - uint8_t zero = 0; - while (tlen < MAX_PACKET_PAYLOAD - 4) { // pad with zeroes, for fixed record length - file.write(&zero, 1); - tlen++; - } - file.close(); - } - last_read_time = curr; } diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 196acb8..05104c9 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -26,6 +26,7 @@ #define PERM_IS_ADMIN 0x8000 #define PERM_GET_TELEMETRY 0x0001 #define PERM_GET_MIN_MAX_AVG 0x0002 +#define PERM_RECV_ALERTS 0x0100 struct ContactInfo { mesh::Identity id; @@ -83,9 +84,18 @@ public: const uint8_t* getSelfIdPubKey() override { return self_id.pub_key; } void clearStats() override { } + float getTelemValue(uint8_t channel, uint8_t type); + protected: - // telemetry data queries - float getVoltage(uint8_t channel) { return 0.0f; } // TODO: extract from curr telemetry buffer + // current telemetry data queries + float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } + float getCurrent(uint8_t channel) { return getTelemValue(channel, LPP_CURRENT); } + float getPower(uint8_t channel) { return getTelemValue(channel, LPP_POWER); } + float getTemperature(uint8_t channel) { return getTelemValue(channel, LPP_TEMPERATURE); } + float getRelativeHumidity(uint8_t channel) { return getTelemValue(channel, LPP_RELATIVE_HUMIDITY); } + float getBarometricPressure(uint8_t channel) { return getTelemValue(channel, LPP_BAROMETRIC_PRESSURE); } + float getAltitude(uint8_t channel) { return getTelemValue(channel, LPP_ALTITUDE); } + bool getGPS(uint8_t channel, float& lat, float& lon, float& alt); // alerts struct Trigger { diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index 97b4ffe..df510c2 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -120,10 +120,11 @@ void CommonCLI::savePrefs(FILESYSTEM* fs) { #define MIN_LOCAL_ADVERT_INTERVAL 60 -void CommonCLI::checkAdvertInterval() { +void CommonCLI::savePrefs() { if (_prefs->advert_interval * 2 < MIN_LOCAL_ADVERT_INTERVAL) { _prefs->advert_interval = 0; // turn it off, now that device has been manually configured } + _callbacks->savePrefs(); } void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, char* reply) { @@ -166,7 +167,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch } else if (memcmp(command, "password ", 9) == 0) { // change admin password StrHelper::strncpy(_prefs->password, &command[9], sizeof(_prefs->password)); - checkAdvertInterval(); savePrefs(); sprintf(reply, "password now: %s", _prefs->password); // echo back just to let admin know for sure!! } else if (memcmp(command, "clear stats", 11) == 0) { @@ -265,7 +265,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch strcpy(reply, "OK"); } else if (memcmp(config, "name ", 5) == 0) { StrHelper::strncpy(_prefs->node_name, &config[5], sizeof(_prefs->node_name)); - checkAdvertInterval(); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "repeat ", 7) == 0) { @@ -292,12 +291,10 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch } } else if (memcmp(config, "lat ", 4) == 0) { _prefs->node_lat = atof(&config[4]); - checkAdvertInterval(); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "lon ", 4) == 0) { _prefs->node_lon = atof(&config[4]); - checkAdvertInterval(); savePrefs(); strcpy(reply, "OK"); } else if (memcmp(config, "rxdelay ", 8) == 0) { diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index 1778c71..b50bf7f 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -55,10 +55,7 @@ class CommonCLI { char tmp[80]; mesh::RTCClock* getRTCClock() { return _rtc; } - void savePrefs() { _callbacks->savePrefs(); } - - void checkAdvertInterval(); - + void savePrefs(); void loadPrefsInt(FILESYSTEM* _fs, const char* filename); public: From 112b360ef45d92b8f08ef5774d40e267f836dbfd Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 21:07:27 +1000 Subject: [PATCH 08/11] * implemented encoding responses to REQ_TYPE_GET_AVG_MIN_MAX --- examples/simple_sensor/SensorMesh.cpp | 187 ++++++++++++++++---------- 1 file changed, 114 insertions(+), 73 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 293a503..d457cd1 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -140,6 +140,101 @@ void SensorMesh::saveContacts() { } } +static uint8_t getDataSize(uint8_t type) { + switch (type) { + case LPP_GPS: + return 9; + case LPP_POLYLINE: + return 8; // TODO: this is MINIMIUM + case LPP_GYROMETER: + case LPP_ACCELEROMETER: + return 6; + case LPP_GENERIC_SENSOR: + case LPP_FREQUENCY: + case LPP_DISTANCE: + case LPP_ENERGY: + case LPP_UNIXTIME: + return 4; + case LPP_COLOUR: + return 3; + case LPP_ANALOG_INPUT: + case LPP_ANALOG_OUTPUT: + case LPP_LUMINOSITY: + case LPP_TEMPERATURE: + case LPP_CONCENTRATION: + case LPP_BAROMETRIC_PRESSURE: + case LPP_ALTITUDE: + case LPP_VOLTAGE: + case LPP_CURRENT: + case LPP_DIRECTION: + case LPP_POWER: + return 2; + } + return 1; +} + +static uint32_t getMultiplier(uint8_t type) { + switch (type) { + case LPP_CURRENT: + case LPP_DISTANCE: + case LPP_ENERGY: + return 1000; + case LPP_VOLTAGE: + case LPP_ANALOG_INPUT: + case LPP_ANALOG_OUTPUT: + return 100; + case LPP_TEMPERATURE: + case LPP_BAROMETRIC_PRESSURE: + return 10; + } + return 1; +} + +static bool isSigned(uint8_t type) { + return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER || + type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER; +} + +static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { + uint32_t value = 0; + for (uint8_t i = 0; i < size; i++) { + value = (value << 8) + buffer[i]; + } + + int sign = 1; + if (is_signed) { + uint32_t bit = 1ul << ((size * 8) - 1); + if ((value & bit) == bit) { + value = (bit << 1) - value; + sign = -1; + } + } + return sign * ((float) value / multiplier); +} + +static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t multiplier, bool is_signed) { + // check sign + bool sign = value < 0; + if (sign) value = -value; + + // get value to store + uint32_t v = value * multiplier; + + // format an uint32_t as if it was an int32_t + if (is_signed & sign) { + uint32_t mask = (1 << (size * 8)) - 1; + v = v & mask; + if (sign) v = mask - v + 1; + } + + // add bytes (MSB first) + for (uint8_t i=1; i<=size; i++) { + dest[size - i] = (v & 0xFF); + v >>= 8; + } + return size; +} + uint8_t SensorMesh::handleRequest(uint16_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') @@ -167,7 +262,25 @@ uint8_t SensorMesh::handleRequest(uint16_t perms, uint32_t sender_timestamp, uin } else { n = 0; } - return 0; // TODO: encode data[0..n) + + uint8_t ofs = 4; + { + uint32_t now = getRTCClock()->getCurrentTime(); + memcpy(&reply_data[ofs], &now, 4); ofs += 4; + } + + for (int i = 0; i < n; i++) { + auto d = &data[i]; + reply_data[ofs++] = d->_channel; + reply_data[ofs++] = d->_lpp_type; + uint8_t sz = getDataSize(d->_lpp_type); + uint32_t mult = getMultiplier(d->_lpp_type); + bool is_signed = isSigned(d->_lpp_type); + ofs += putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); + ofs += putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); + ofs += putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); + } + return ofs; } return 0; // unknown command } @@ -604,78 +717,6 @@ void SensorMesh::setTxPower(uint8_t power_dbm) { radio_set_tx_power(power_dbm); } -static uint8_t getDataSize(uint8_t type) { - switch (type) { - case LPP_GPS: - return 9; - case LPP_POLYLINE: - return 8; // TODO: this is MINIMIUM - case LPP_GYROMETER: - case LPP_ACCELEROMETER: - return 6; - case LPP_GENERIC_SENSOR: - case LPP_FREQUENCY: - case LPP_DISTANCE: - case LPP_ENERGY: - case LPP_UNIXTIME: - return 4; - case LPP_COLOUR: - return 3; - case LPP_ANALOG_INPUT: - case LPP_ANALOG_OUTPUT: - case LPP_LUMINOSITY: - case LPP_TEMPERATURE: - case LPP_CONCENTRATION: - case LPP_BAROMETRIC_PRESSURE: - case LPP_ALTITUDE: - case LPP_VOLTAGE: - case LPP_CURRENT: - case LPP_DIRECTION: - case LPP_POWER: - return 2; - } - return 1; -} - -static uint32_t getMultiplier(uint8_t type) { - switch (type) { - case LPP_CURRENT: - case LPP_DISTANCE: - case LPP_ENERGY: - return 1000; - case LPP_VOLTAGE: - case LPP_ANALOG_INPUT: - case LPP_ANALOG_OUTPUT: - return 100; - case LPP_TEMPERATURE: - case LPP_BAROMETRIC_PRESSURE: - return 10; - } - return 1; -} - -static bool isSigned(uint8_t type) { - return type == LPP_ALTITUDE || type == LPP_TEMPERATURE || type == LPP_GYROMETER || - type == LPP_ANALOG_INPUT || type == LPP_ANALOG_OUTPUT || type == LPP_GPS || type == LPP_ACCELEROMETER; -} - -static float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { - uint32_t value = 0; - for (uint8_t i = 0; i < size; i++) { - value = (value << 8) + buffer[i]; - } - - int sign = 1; - if (is_signed) { - uint32_t bit = 1ul << ((size * 8) - 1); - if ((value & bit) == bit) { - value = (bit << 1) - value; - sign = -1; - } - } - return sign * ((float) value / multiplier); -} - float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) { auto buf = telemetry.getBuffer(); uint8_t size = telemetry.getSize(); From 2715058eb2fa116094bec183cf6cb6d83101a3a2 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 21:56:26 +1000 Subject: [PATCH 09/11] * misc fixes --- examples/simple_sensor/SensorMesh.cpp | 10 ++++++++++ examples/simple_sensor/main.cpp | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index d457cd1..1ed9007 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -327,6 +327,7 @@ void SensorMesh::applyContactPermissions(const uint8_t* pubkey, uint16_t perms) memset(c, 0, sizeof(*c)); } else { c->permissions = perms; // update their permissions + self_id.calcSharedSecret(c->shared_secret, pubkey); } dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger saveContacts() } @@ -464,6 +465,15 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r strcpy(reply, "Err - bad pubkey"); } } + } else if (sender_timestamp == 0 && strcmp(command, "getperm") == 0) { + Serial.println("Permissions:"); + for (int i = 0; i < num_contacts; i++) { + auto c = &contacts[i]; + + mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE); + Serial.printf(" %04X\n", c->permissions); + } + reply[0] = 0; } else { _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands } diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 25610a6..16e14d5 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -41,7 +41,7 @@ void halt() { while (1) ; } -static char command[80]; +static char command[120]; void setup() { Serial.begin(115200); From 541cd8cfd960618e393f8b6a51c24ba004efe773 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Jul 2025 23:18:41 +1000 Subject: [PATCH 10/11] * misc --- examples/simple_sensor/SensorMesh.cpp | 13 ------------- examples/simple_sensor/SensorMesh.h | 1 - 2 files changed, 14 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 1ed9007..48fd10f 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -521,19 +521,6 @@ void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) { } } -void SensorMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) { - mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl -#if 0 - // if this a zero hop advert, add it to neighbours - if (packet->path_len == 0) { - AdvertDataParser parser(app_data, app_data_len); - if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters - putNeighbour(id, timestamp, packet->getSNR()); - } - } -#endif -} - void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) { int i = matching_peer_indexes[sender_idx]; if (i < 0 || i >= num_contacts) { diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 05104c9..0023435 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -121,7 +121,6 @@ protected: void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override; int searchPeersByHash(const uint8_t* hash) override; void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override; - void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override; void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override; bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; From 7d4760898515f9815adbdae5b7e93d66a3432d8e Mon Sep 17 00:00:00 2001 From: jasper Date: Tue, 8 Jul 2025 21:16:03 +0200 Subject: [PATCH 11/11] Changed the Barometric Pressure value since it was a factor 100 to high --- src/helpers/sensors/EnvironmentSensorManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/helpers/sensors/EnvironmentSensorManager.cpp b/src/helpers/sensors/EnvironmentSensorManager.cpp index a424c46..ab5b459 100644 --- a/src/helpers/sensors/EnvironmentSensorManager.cpp +++ b/src/helpers/sensors/EnvironmentSensorManager.cpp @@ -154,7 +154,7 @@ bool EnvironmentSensorManager::querySensors(uint8_t requester_permissions, Cayen if (BME280_initialized) { telemetry.addTemperature(TELEM_CHANNEL_SELF, BME280.readTemperature()); telemetry.addRelativeHumidity(TELEM_CHANNEL_SELF, BME280.readHumidity()); - telemetry.addBarometricPressure(TELEM_CHANNEL_SELF, BME280.readPressure()); + telemetry.addBarometricPressure(TELEM_CHANNEL_SELF, BME280.readPressure()/100); telemetry.addAltitude(TELEM_CHANNEL_SELF, BME280.readAltitude(TELEM_BME280_SEALEVELPRESSURE_HPA)); } #endif