From b4e37044edf55ce96a7a4e14261ef3ec711faa68 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Thu, 3 Sep 2026 14:09:15 +1000 Subject: [PATCH 01/11] * default and reply scopes now applied --- examples/simple_sensor/SensorMesh.cpp | 76 ++++++++++++++++++++++----- examples/simple_sensor/SensorMesh.h | 6 +++ 2 files changed, 69 insertions(+), 13 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 23d0cdc353..287a3c1bf8 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -1,4 +1,5 @@ #include "SensorMesh.h" +#include /* ------------------------------ Config -------------------------------- */ @@ -262,7 +263,7 @@ void SensorMesh::sendAlert(const ClientInfo* c, Trigger* t) { sendDirect(pkt, c->out_path, c->out_path_len); } else { unsigned long delay_millis = 0; - sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); } } t->send_expiry = futureMillis(ALERT_ACK_EXPIRY_MILLIS); @@ -400,10 +401,11 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r if (sp == NULL) { strcpy(reply, "Err - bad params"); } else { + int hex_len = min(sp - hex, PUB_KEY_SIZE*2); + uint8_t pubkey[PUB_KEY_SIZE]; + *sp++ = 0; // replace space with null terminator - uint8_t pubkey[PUB_KEY_SIZE]; - int hex_len = min(sp - hex, PUB_KEY_SIZE*2); if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) { uint8_t perms = atoi(sp); if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) { @@ -451,6 +453,21 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r } } +mesh::DispatcherAction SensorMesh::onRecvPacket(mesh::Packet* pkt) { + if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) { + recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD); + } else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) { + if (region_map.getWildcard().flags & REGION_DENY_FLOOD) { + recv_pkt_region = NULL; + } else { + recv_pkt_region = ®ion_map.getWildcard(); + } + } else { + recv_pkt_region = NULL; + } + return Mesh::onRecvPacket(pkt); +} + 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; @@ -472,10 +489,10 @@ void SensorMesh::onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, con // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response 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, packet->getPathHashSize()); + if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } else { mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len); - if (reply) sendFlood(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); + if (reply) sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } } } @@ -503,7 +520,7 @@ void SensorMesh::getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) { void SensorMesh::sendAckTo(const ClientInfo& dest, uint32_t ack_hash, uint8_t path_hash_size) { if (dest.out_path_len == OUT_PATH_UNKNOWN) { mesh::Packet* ack = createAck(ack_hash); - if (ack) sendFlood(ack, TXT_ACK_DELAY, path_hash_size); + if (ack) sendFloodScoped(default_scope, ack, TXT_ACK_DELAY, path_hash_size); } else { uint32_t d = TXT_ACK_DELAY; if (getExtraAckTransmitCount() > 0) { @@ -541,14 +558,14 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i // 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, packet->getPathHashSize()); + if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } else { mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, from->id, secret, reply_data, reply_len); if (reply) { if (from->out_path_len != OUT_PATH_UNKNOWN) { // 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, packet->getPathHashSize()); + sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize()); } } } @@ -571,7 +588,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK mesh::Packet* path = createPathReturn(from->id, secret, packet->path, packet->path_len, PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4); - if (path) sendFlood(path, TXT_ACK_DELAY, packet->getPathHashSize()); + if (path) sendFloodReply(path, TXT_ACK_DELAY, packet->getPathHashSize()); } else { sendAckTo(*from, ack_hash, packet->getPathHashSize()); } @@ -601,7 +618,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from->id, secret, temp, 5 + text_len); if (reply) { if (from->out_path_len == OUT_PATH_UNKNOWN) { - sendFlood(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize()); + sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize()); } else { sendDirect(reply, from->out_path, from->out_path_len, CLI_REPLY_DELAY_MILLIS); } @@ -708,6 +725,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise last_read_time = 0; num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; + recv_pkt_region = NULL; // defaults _prefs.airtime_factor = 1.0; @@ -820,11 +838,43 @@ void SensorMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t revert_radio_at = futureMillis(2000 + timeout_mins*60*1000); // schedule when to revert radio params } +void SensorMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) { + if (scope.isNull()) { + sendFlood(pkt, delay_millis, path_hash_size); + } else { + uint16_t codes[2]; + codes[0] = scope.calcTransportCode(pkt); + codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region? + sendFlood(pkt, codes, delay_millis, path_hash_size); + } +} + +void SensorMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) { + TransportKey req_scope; + bool is_wildcard = recv_pkt_region != NULL && recv_pkt_region->isWildcard(); + bool req_scope_known = recv_pkt_region != NULL && !is_wildcard + && region_map.getTransportKeysFor(*recv_pkt_region, &req_scope, 1) > 0; + + switch (mesh::chooseReplyScope(req_scope_known, is_wildcard, !default_scope.isNull())) { + case mesh::REPLY_SCOPE_REQUEST: + sendFloodScoped(req_scope, packet, delay_millis, path_hash_size); // reply with same scope as request + break; + case mesh::REPLY_SCOPE_DEFAULT: + // requester's scope is unknown: DIRECT request (no transport codes), or code matched no Region. + // un-scoped would be dropped at hop 0 by repeaters running flood.max.unscoped=0 + sendFloodScoped(default_scope, packet, delay_millis, path_hash_size); + break; + case mesh::REPLY_SCOPE_NONE: + sendFlood(packet, delay_millis, path_hash_size); // send un-scoped + break; + } +} + void SensorMesh::sendSelfAdvertisement(int delay_millis, bool flood) { mesh::Packet* pkt = createSelfAdvert(); if (pkt) { if (flood) { - sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); } else { sendZeroHop(pkt, delay_millis); } @@ -902,7 +952,7 @@ void SensorMesh::loop() { if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { mesh::Packet* pkt = createSelfAdvert(); unsigned long delay_millis = 0; - if (pkt) sendFlood(pkt, delay_millis, _prefs.path_hash_mode + 1); + if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1); updateFloodAdvertTimer(); // schedule next flood advert updateAdvertTimer(); // also schedule local advert (so they don't overlap) @@ -973,7 +1023,7 @@ void SensorMesh::loop() { } } - // is there are pending dirty contacts write needed? + // pending dirty contacts write needed? if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) { acl.save(_fs); dirty_contacts_expiry = 0; diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index b5e96d5cc7..845402bae3 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -81,6 +81,9 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { float getTelemValue(uint8_t channel, uint8_t type); + void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size); + void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); + protected: // current telemetry data queries float getVoltage(uint8_t channel) { return getTelemValue(channel, LPP_VOLTAGE); } @@ -122,6 +125,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { int getInterferenceThreshold() const override; bool getCADEnabled() const override; int getAGCResetInterval() const override; + mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) 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; @@ -129,6 +133,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { 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; void onControlDataRecv(mesh::Packet* packet) override; void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override; + virtual bool handleIncomingMsg(ClientInfo& from, uint32_t timestamp, uint8_t* data, uint8_t flags, size_t len); void sendAckTo(const ClientInfo& dest, uint32_t ack_hash, uint8_t path_hash_size=1); private: @@ -142,6 +147,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { CayenneLPP telemetry; TransportKeyStore key_store; RegionMap region_map; + RegionEntry* recv_pkt_region; TransportKey default_scope; uint32_t last_read_time; int matching_peer_indexes[MAX_SEARCH_RESULTS]; From 9bc6060831a0ad6064911836518e143d8a7c5ab9 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 4 Sep 2026 15:13:17 +1000 Subject: [PATCH 02/11] * new: REQ_TYPE_SUBSCRIBE and REQ_TYPE_UNSUBSCRIBE --- examples/simple_sensor/SensorMesh.cpp | 124 ++++++++++++++++++++++---- examples/simple_sensor/SensorMesh.h | 9 +- src/helpers/ClientACL.h | 5 ++ 3 files changed, 116 insertions(+), 22 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 287a3c1bf8..0a78f5daf7 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -55,6 +55,8 @@ #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 #define REQ_TYPE_GET_AVG_MIN_MAX 0x04 #define REQ_TYPE_GET_ACCESS_LIST 0x05 +#define REQ_TYPE_SUBSCRIBE 0x10 +#define REQ_TYPE_UNSUBSCRIBE 0x11 #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ @@ -74,6 +76,8 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) { #endif } +/* --------------------- Cayenne LPP helpers ----------------------------*/ + static uint8_t getDataSize(uint8_t type) { switch (type) { case LPP_GPS: @@ -171,7 +175,53 @@ static uint8_t putFloat(uint8_t * dest, float value, uint8_t size, uint32_t mult return size; } -uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { +static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) { + 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 +} + +/* ------------------ end Cayenne LPP helpers ----------------------*/ + +bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { + if (telemetry.getSize() != prev_telem_size) return true; + + 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); + + float v = getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); + float pv = getFloat(&prev_telem[i], sz, getMultiplier(t), isSigned(t)); + float min_delta = findTelemValue(min_deltas, min_deltas_len, ch, t); + if (abs(v - pv) > min_delta) return true; // Yes, has changed + + i += sz; // skip + } + return false; // no changes +} + +uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { + uint8_t perms = from->isAdmin() ? 0xFF : from->permissions; + memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag') if (req_type == REQ_TYPE_GET_TELEMETRY_DATA) { // allow all @@ -235,6 +285,29 @@ uint8_t SensorMesh::handleRequest(uint8_t perms, uint32_t sender_timestamp, uint return ofs; } } + if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 2 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + uint8_t reserved = payload[0]; + RegionEntry* r; + if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope + r = recv_pkt_region; + } else { // use default scope + r = region_map.getDefaultRegion(); + } + from->extra.sensor.scope_region_id = r ? r->id : 0; + from->extra.sensor.min_deltas_len = payload[1]; + // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) + memcpy(from->extra.sensor.min_deltas, &payload[2], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[1])); + + getRNG()->random(&reply_data[4], 2); // just some entropy for better packet-hash uniqueness + strcpy((char *)&reply_data[6], r ? r->name : ""); // reply with name of scope that will be used + return 6 + strlen((char *)&reply_data[6]); + } + if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + from->extra.sensor.scope_region_id = 0; + reply_data[4] = 0; // success + getRNG()->random(&reply_data[5], 3); // just some entropy for better packet-hash uniqueness + return 8; + } return 0; // unknown command } @@ -548,7 +621,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() ? 0xFF : from->permissions, timestamp, data[4], &data[5], len - 5); + uint8_t reply_len = handleRequest(from, timestamp, data[4], &data[5], len - 5); if (reply_len == 0) return; // invalid command from->last_timestamp = timestamp; @@ -726,6 +799,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; + prev_telem_size = 0; // defaults _prefs.airtime_factor = 1.0; @@ -916,23 +990,7 @@ void SensorMesh::formatPacketStatsReply(char *reply) { } 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 + return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type); } bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { @@ -982,6 +1040,34 @@ void SensorMesh::loop() { // query other sensors -- target specific sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions + // compare with previous telemetry, check if any deltas are greater than subscriber minimums + for (int i = 0; i < acl.getNumClients(); i++) { + auto c = acl.getClientByIdx(i); + if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0) continue; // skip deleted entries, or Not subscribed to deltas + RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); + if (r == NULL) continue; // unknown region scope + if (telemHasChanged(c->extra.sensor.min_deltas, c->extra.sensor.min_deltas_len)) { + TransportKey scope; + if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { + uint8_t tlen = telemetry.getSize(); + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); // this will be an unknown 'tag' to the client + memcpy(reply_data, ×tamp, 4); + memcpy(&reply_data[4], telemetry.getBuffer(), tlen); + + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 4 + tlen); + if (reply) { + if (c->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT + sendDirect(reply, c->out_path, c->out_path_len, 0); + } else { + sendFloodScoped(scope, reply, 0, _prefs.path_hash_mode + 1); + } + } + } + } + } + memcpy(prev_telem, telemetry.getBuffer(), telemetry.getSize()); // save snapshot for next compare cycle + prev_telem_size = telemetry.getSize(); + onSensorDataRead(); last_read_time = curr; diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 845402bae3..7ea87f2068 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -96,12 +96,12 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { bool getGPS(uint8_t channel, float& lat, float& lon, float& alt); // alerts - enum AlertPriority { LOW_PRI_ALERT, HIGH_PRI_ALERT }; + enum AlertPriority : uint8_t { LOW_PRI_ALERT, HIGH_PRI_ALERT }; struct Trigger { uint32_t timestamp; - AlertPriority pri; uint32_t expected_acks[4]; + AlertPriority pri; int8_t curr_contact_idx; uint8_t attempt; unsigned long send_expiry; @@ -145,6 +145,8 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { uint8_t reply_data[MAX_PACKET_PAYLOAD]; unsigned long dirty_contacts_expiry; CayenneLPP telemetry; + uint8_t prev_telem_size; + uint8_t prev_telem[MAX_PACKET_PAYLOAD - 4]; TransportKeyStore key_store; RegionMap region_map; RegionEntry* recv_pkt_region; @@ -159,8 +161,9 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { uint8_t pending_sf; uint8_t pending_cr; + bool telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); - uint8_t handleRequest(uint8_t perms, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); + uint8_t handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); void sendAlert(const ClientInfo* c, Trigger* t); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index e065446476..9fde35ecbe 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -28,6 +28,11 @@ struct ClientInfo { unsigned long ack_timeout; uint8_t push_failures; } room; + struct { + uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber + uint8_t min_deltas_len; + uint8_t min_deltas[14]; // LPP encoded + } sensor; } extra; bool isAdmin() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_ADMIN; } From 3a5a6b90ab3d9e65950dd4e8e03026ce73da4103 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Fri, 4 Sep 2026 22:02:49 +1000 Subject: [PATCH 03/11] * sensor: CLI "sub" and "unsub" commands --- examples/simple_sensor/SensorMesh.cpp | 68 ++++++++++++++++++++++++++- examples/simple_sensor/SensorMesh.h | 2 +- examples/simple_sensor/main.cpp | 2 +- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 0a78f5daf7..008cbcfc08 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -193,6 +193,43 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u return 0.0f; // not found } +static uint8_t compileLPPSpec(char* txt, uint8_t* dest, size_t max_len) { + const char* parts[3]; + int n = mesh::Utils::parseTextParts(txt, parts, 3, ','); + uint8_t len = 0; + for (int i = 0; i < n && len + 6 <= max_len; i++) { + const char* cp = strchr(parts[i], ':'); + if (cp) { + uint8_t t; + float factor = 1.0f; + cp++; // skip the ':' + char* ep = strchr(cp, 0) - 1; // find LAST char + if (*ep == 'V') { // Volts + t = LPP_VOLTAGE; + } else if (*ep == 'W') { // Watts + t = LPP_POWER; + } else if (*ep == 'C') { // Celcius + t = LPP_TEMPERATURE; + } else if (*ep == 'P') { // Pascals + t = LPP_BAROMETRIC_PRESSURE; + } else if (*ep == 'A') { // Amps + t = LPP_CURRENT; + } else if (*ep == 'm') { + t = LPP_DISTANCE; factor = 0.001f; + } else { + t = 0; + } + + if (t) { + dest[len++] = atoi(parts[i]); // channel number + dest[len++] = t; // LPP type + len += putFloat(&dest[len], atof(cp) * factor, getDataSize(t), getMultiplier(t), isSigned(t)); + } + } + } + return len; +} + /* ------------------ end Cayenne LPP helpers ----------------------*/ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { @@ -453,7 +490,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* return 13; // reply length } -void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* reply) { +void SensorMesh::handleCommand(ClientInfo* from, 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) @@ -502,6 +539,33 @@ void SensorMesh::handleCommand(uint32_t sender_timestamp, char* command, char* r Serial.printf("\n"); } reply[0] = 0; + } else if (from != NULL && memcmp(command, "sub", 3) == 0 && (command[3] == ' ' || command[3] == 0)) { // subscribe + uint8_t perms = from->isAdmin() ? 0xFF : from->permissions; + if ((perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + RegionEntry* r; + if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope + r = recv_pkt_region; + } else { // use default scope + r = region_map.getDefaultRegion(); + } + if (command[3] == ' ') { + // compile params as LPP data, eg. "sub 1:0.2V" + from->extra.sensor.min_deltas_len = compileLPPSpec(&command[4], from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); + } else { + from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) + } + from->extra.sensor.scope_region_id = r ? r->id : 0; + if (from->extra.sensor.scope_region_id) { + strcpy(reply, "OK - subscribed"); + } else { + strcpy(reply, "Err - region scope needed"); + } + } else { + strcpy(reply, "Err - no permission"); + } + } else if (from != NULL && strcmp(command, "unsub") == 0) { // unsubscribe + from->extra.sensor.scope_region_id = 0; + strcpy(reply, "OK - unsubscribed"); } else if (memcmp(command, "io ", 2) == 0) { // io {value}: write, io: read if (command[2] == ' ') { // it's a write uint32_t val; @@ -676,7 +740,7 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i uint8_t temp[166]; char *command = (char *) &data[5]; char *reply = (char *) &temp[5]; - handleCommand(sender_timestamp, command, reply); + handleCommand(from, sender_timestamp, command, reply); int text_len = strlen(reply); if (text_len > 0) { diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 7ea87f2068..6d5857d053 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -51,7 +51,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables); void begin(FILESYSTEM* fs); void loop(); - void handleCommand(uint32_t sender_timestamp, char* command, char* reply); + void handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply); // CommonCLI callbacks const char* getFirmwareVer() override { return FIRMWARE_VERSION; } diff --git a/examples/simple_sensor/main.cpp b/examples/simple_sensor/main.cpp index 69182f3a7a..9e3b230b68 100644 --- a/examples/simple_sensor/main.cpp +++ b/examples/simple_sensor/main.cpp @@ -137,7 +137,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.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! + the_mesh.handleCommand(NULL, 0, command, reply); // NOTE: there is no sender_timestamp via serial! if (reply[0]) { Serial.print(" -> "); Serial.println(reply); } From 62d0556a7024dd86046cea9d74e176f4737d91a0 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Sat, 5 Sep 2026 15:59:29 +1000 Subject: [PATCH 04/11] * added region load/save support * SUBSCRIBE now with timeout param (default 30 mins, max ~18 hours) --- examples/simple_sensor/SensorMesh.cpp | 102 ++++++++++++++++++++++---- examples/simple_sensor/SensorMesh.h | 7 +- src/helpers/ClientACL.h | 1 + 3 files changed, 93 insertions(+), 17 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 008cbcfc08..c3f2d9b07f 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -322,8 +322,10 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u return ofs; } } - if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 2 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { - uint8_t reserved = payload[0]; + if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 4 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + uint16_t timeout_secs; + memcpy(&timeout_secs, &payload[0], 2); + uint8_t reserved = payload[2]; RegionEntry* r; if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope r = recv_pkt_region; @@ -331,16 +333,19 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u r = region_map.getDefaultRegion(); } from->extra.sensor.scope_region_id = r ? r->id : 0; - from->extra.sensor.min_deltas_len = payload[1]; + from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; + from->extra.sensor.min_deltas_len = payload[3]; // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) - memcpy(from->extra.sensor.min_deltas, &payload[2], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[1])); + memcpy(from->extra.sensor.min_deltas, &payload[4], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[3])); - getRNG()->random(&reply_data[4], 2); // just some entropy for better packet-hash uniqueness - strcpy((char *)&reply_data[6], r ? r->name : ""); // reply with name of scope that will be used - return 6 + strlen((char *)&reply_data[6]); + memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); // reply with actual expiry timestamp (or 0 for error) + strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used + return 6 + strlen((char *)&reply_data[8]); } if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { from->extra.sensor.scope_region_id = 0; + from->extra.sensor.expiry_timestamp = 0; + // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? reply_data[4] = 0; // success getRNG()->random(&reply_data[5], 3); // just some entropy for better packet-hash uniqueness return 8; @@ -441,6 +446,25 @@ int SensorMesh::getAGCResetInterval() const { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } +void SensorMesh::startRegionsLoad() { + temp_map.resetFrom(region_map); // rebuild regions in a temp instance + memset(load_stack, 0, sizeof(load_stack)); + load_stack[0] = &temp_map.getWildcard(); + region_load_active = true; +} + +bool SensorMesh::saveRegions() { + return region_map.save(_fs); +} + +void SensorMesh::onDefaultRegionChanged(const RegionEntry* r) { + if (r) { + region_map.getTransportKeysFor(*r, &default_scope, 1); + } else { + memset(default_scope.key, 0, sizeof(default_scope.key)); + } +} + uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) { ClientInfo* client; if (data[0] == 0) { // blank password, just check if sender is in ACL @@ -454,7 +478,7 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* } else { if (strcmp((char *) data, _prefs.password) != 0) { // check for valid admin password #if MESH_DEBUG - MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); + MESH_DEBUG_PRINTLN("Invalid password: %s", &data[0]); #endif return 0; } @@ -491,6 +515,40 @@ uint8_t SensorMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* } void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char* command, char* reply) { + if (region_load_active) { + if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation + region_map = temp_map; // copy over the temp instance as new current map + region_load_active = false; + + sprintf(reply, "OK - loaded %d regions", region_map.getCount()); + } else { + char *np = command; + while (*np == ' ') np++; // skip indent + int indent = np - command; + + char *ep = np; + while (RegionMap::is_name_char(*ep)) ep++; + if (*ep) { *ep++ = 0; } // set null terminator for end of name + + while (*ep && *ep != 'F') ep++; // look for (optional) flags + + if (indent > 0 && indent < 8 && strlen(np) > 0) { + auto parent = load_stack[indent - 1]; + if (parent) { + auto old = region_map.findByName(np); + auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists) + if (nw) { + nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr + + load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's + } + } + } + reply[0] = 0; + } + return; + } + while (*command == ' ') command++; // skip leading spaces if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI) @@ -548,15 +606,25 @@ void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char } else { // use default scope r = region_map.getDefaultRegion(); } - if (command[3] == ' ') { - // compile params as LPP data, eg. "sub 1:0.2V" - from->extra.sensor.min_deltas_len = compileLPPSpec(&command[4], from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); - } else { - from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) + // defaults: + from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) + uint16_t timeout_secs = 30*60; // expires after 30 mins + if (command[3] == ' ') { // eg. "sub 300 1:0.2V" + char* cp = &command[4]; + while (*cp >= '0' && *cp <= '9') cp++; + if (cp > &command[4]) { + timeout_secs = atoi(&command[4]); + if (*cp == ' ') { + cp++; // skip the space + from->extra.sensor.min_deltas_len = compileLPPSpec(cp, from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); + } + } } from->extra.sensor.scope_region_id = r ? r->id : 0; - if (from->extra.sensor.scope_region_id) { - strcpy(reply, "OK - subscribed"); + from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; + if (from->extra.sensor.expiry_timestamp) { + DateTime dt = DateTime(from->extra.sensor.expiry_timestamp); + sprintf(reply, "OK - sub expires: %02d:%02d (UTC)", dt.hour(), dt.minute()); } else { strcpy(reply, "Err - region scope needed"); } @@ -853,7 +921,7 @@ void SensorMesh::onAckRecv(mesh::Packet* packet, uint32_t ack_crc) { 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), - region_map(key_store), + region_map(key_store), temp_map(key_store), _cli(board, rtc, sensors, region_map, acl, &_prefs, this), telemetry(MAX_PACKET_PAYLOAD - 4) { @@ -864,6 +932,7 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; prev_telem_size = 0; + region_load_active = false; // defaults _prefs.airtime_factor = 1.0; @@ -1110,6 +1179,7 @@ void SensorMesh::loop() { if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0) continue; // skip deleted entries, or Not subscribed to deltas RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); if (r == NULL) continue; // unknown region scope + if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired if (telemHasChanged(c->extra.sensor.min_deltas, c->extra.sensor.min_deltas_len)) { TransportKey scope; if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 6d5857d053..e0e03c81be 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -78,6 +78,9 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { void saveIdentity(const mesh::LocalIdentity& new_id) override; void clearStats() override { } void applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) override; + void startRegionsLoad() override; + bool saveRegions() override; + void onDefaultRegionChanged(const RegionEntry* r) override; float getTelemValue(uint8_t channel, uint8_t type); @@ -148,8 +151,9 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { uint8_t prev_telem_size; uint8_t prev_telem[MAX_PACKET_PAYLOAD - 4]; TransportKeyStore key_store; - RegionMap region_map; + RegionMap region_map, temp_map; RegionEntry* recv_pkt_region; + RegionEntry* load_stack[8]; TransportKey default_scope; uint32_t last_read_time; int matching_peer_indexes[MAX_SEARCH_RESULTS]; @@ -160,6 +164,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { float pending_bw; uint8_t pending_sf; uint8_t pending_cr; + bool region_load_active; bool telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index 9fde35ecbe..1e9f472d57 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -29,6 +29,7 @@ struct ClientInfo { uint8_t push_failures; } room; struct { + uint32_t expiry_timestamp; // epoch seconds uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber uint8_t min_deltas_len; uint8_t min_deltas[14]; // LPP encoded From d71a54cd3dfe8dc5eca7c0e0834c6e6e3ea18837 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 7 Sep 2026 13:56:47 +1000 Subject: [PATCH 05/11] * CLI: removed "sub" and "unsub" (cannot support via command line) * _SUBSCRIBE: binary req/resp payload changes (now keeps supplied 'push_tag') * Sensor: added MCU temperature support in telemetry --- examples/simple_sensor/SensorMesh.cpp | 112 ++++++-------------------- src/helpers/ClientACL.h | 1 + 2 files changed, 27 insertions(+), 86 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index c3f2d9b07f..8c6b06a6db 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -55,8 +55,10 @@ #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 #define REQ_TYPE_GET_AVG_MIN_MAX 0x04 #define REQ_TYPE_GET_ACCESS_LIST 0x05 -#define REQ_TYPE_SUBSCRIBE 0x10 -#define REQ_TYPE_UNSUBSCRIBE 0x11 +#define REQ_TYPE_GET_NEIGHBOURS 0x06 // repeater only (at present) + +#define REQ_TYPE_SUBSCRIBE 0x08 +#define REQ_TYPE_UNSUBSCRIBE 0x09 #define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ @@ -193,43 +195,6 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u return 0.0f; // not found } -static uint8_t compileLPPSpec(char* txt, uint8_t* dest, size_t max_len) { - const char* parts[3]; - int n = mesh::Utils::parseTextParts(txt, parts, 3, ','); - uint8_t len = 0; - for (int i = 0; i < n && len + 6 <= max_len; i++) { - const char* cp = strchr(parts[i], ':'); - if (cp) { - uint8_t t; - float factor = 1.0f; - cp++; // skip the ':' - char* ep = strchr(cp, 0) - 1; // find LAST char - if (*ep == 'V') { // Volts - t = LPP_VOLTAGE; - } else if (*ep == 'W') { // Watts - t = LPP_POWER; - } else if (*ep == 'C') { // Celcius - t = LPP_TEMPERATURE; - } else if (*ep == 'P') { // Pascals - t = LPP_BAROMETRIC_PRESSURE; - } else if (*ep == 'A') { // Amps - t = LPP_CURRENT; - } else if (*ep == 'm') { - t = LPP_DISTANCE; factor = 0.001f; - } else { - t = 0; - } - - if (t) { - dest[len++] = atoi(parts[i]); // channel number - dest[len++] = t; // LPP type - len += putFloat(&dest[len], atof(cp) * factor, getDataSize(t), getMultiplier(t), isSigned(t)); - } - } - } - return len; -} - /* ------------------ end Cayenne LPP helpers ----------------------*/ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { @@ -269,6 +234,10 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u // query other sensors -- target specific sensors.querySensors(0xFF & perm_mask, telemetry); // allow all telemetry permissions for admin or guest // TODO: let requester know permissions they have: telemetry.addPresence(TELEM_CHANNEL_SELF, perms); + float temperature = board.getMCUTemperature(); + if (!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN + telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature + } uint8_t tlen = telemetry.getSize(); memcpy(&reply_data[4], telemetry.getBuffer(), tlen); @@ -322,10 +291,11 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u return ofs; } } - if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 4 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + if (req_type == REQ_TYPE_SUBSCRIBE && payload_len >= 8 && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { + memcpy(&from->extra.sensor.push_tag, &payload[0], 4); uint16_t timeout_secs; - memcpy(&timeout_secs, &payload[0], 2); - uint8_t reserved = payload[2]; + memcpy(&timeout_secs, &payload[4], 2); + uint8_t reserved = payload[6]; RegionEntry* r; if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope r = recv_pkt_region; @@ -334,16 +304,17 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u } from->extra.sensor.scope_region_id = r ? r->id : 0; from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; - from->extra.sensor.min_deltas_len = payload[3]; + from->extra.sensor.min_deltas_len = min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[7]); // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) - memcpy(from->extra.sensor.min_deltas, &payload[4], min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[3])); + memcpy(from->extra.sensor.min_deltas, &payload[8], from->extra.sensor.min_deltas_len); memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); // reply with actual expiry timestamp (or 0 for error) strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used - return 6 + strlen((char *)&reply_data[8]); + return 8 + strlen((char *)&reply_data[8]); } if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { from->extra.sensor.scope_region_id = 0; + from->extra.sensor.push_tag = 0; from->extra.sensor.expiry_timestamp = 0; // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? reply_data[4] = 0; // success @@ -597,43 +568,6 @@ void SensorMesh::handleCommand(ClientInfo* from, uint32_t sender_timestamp, char Serial.printf("\n"); } reply[0] = 0; - } else if (from != NULL && memcmp(command, "sub", 3) == 0 && (command[3] == ' ' || command[3] == 0)) { // subscribe - uint8_t perms = from->isAdmin() ? 0xFF : from->permissions; - if ((perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { - RegionEntry* r; - if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope - r = recv_pkt_region; - } else { // use default scope - r = region_map.getDefaultRegion(); - } - // defaults: - from->extra.sensor.min_deltas_len = 0; // no minimums (telemetry just needs to CHANGE) - uint16_t timeout_secs = 30*60; // expires after 30 mins - if (command[3] == ' ') { // eg. "sub 300 1:0.2V" - char* cp = &command[4]; - while (*cp >= '0' && *cp <= '9') cp++; - if (cp > &command[4]) { - timeout_secs = atoi(&command[4]); - if (*cp == ' ') { - cp++; // skip the space - from->extra.sensor.min_deltas_len = compileLPPSpec(cp, from->extra.sensor.min_deltas, sizeof(from->extra.sensor.min_deltas)); - } - } - } - from->extra.sensor.scope_region_id = r ? r->id : 0; - from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; - if (from->extra.sensor.expiry_timestamp) { - DateTime dt = DateTime(from->extra.sensor.expiry_timestamp); - sprintf(reply, "OK - sub expires: %02d:%02d (UTC)", dt.hour(), dt.minute()); - } else { - strcpy(reply, "Err - region scope needed"); - } - } else { - strcpy(reply, "Err - no permission"); - } - } else if (from != NULL && strcmp(command, "unsub") == 0) { // unsubscribe - from->extra.sensor.scope_region_id = 0; - strcpy(reply, "OK - unsubscribed"); } else if (memcmp(command, "io ", 2) == 0) { // io {value}: write, io: read if (command[2] == ' ') { // it's a write uint32_t val; @@ -1172,6 +1106,11 @@ void SensorMesh::loop() { telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); // query other sensors -- target specific sensors.querySensors(0xFF, telemetry); // allow all telemetry permissions + // This MCU temperature will be overridden by external sensors (if any) + float temperature = board.getMCUTemperature(); + if (!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN + telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature + } // compare with previous telemetry, check if any deltas are greater than subscriber minimums for (int i = 0; i < acl.getNumClients(); i++) { @@ -1184,11 +1123,12 @@ void SensorMesh::loop() { TransportKey scope; if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { uint8_t tlen = telemetry.getSize(); - uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); // this will be an unknown 'tag' to the client - memcpy(reply_data, ×tamp, 4); - memcpy(&reply_data[4], telemetry.getBuffer(), tlen); + memcpy(reply_data, &c->extra.sensor.push_tag, 4); + uint32_t timestamp = getRTCClock()->getCurrentTimeUnique(); + memcpy(&reply_data[4], ×tamp, 4); + memcpy(&reply_data[8], telemetry.getBuffer(), tlen); - mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 4 + tlen); + mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, c->id, c->shared_secret, reply_data, 8 + tlen); if (reply) { if (c->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT sendDirect(reply, c->out_path, c->out_path_len, 0); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index 1e9f472d57..39e71f2c8b 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -30,6 +30,7 @@ struct ClientInfo { } room; struct { uint32_t expiry_timestamp; // epoch seconds + uint32_t push_tag; uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber uint8_t min_deltas_len; uint8_t min_deltas[14]; // LPP encoded From 8660d1c973d1770275fe36cd990623a5a807b204 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 8 Sep 2026 17:55:02 +1000 Subject: [PATCH 06/11] * refactor: LPP helpers moved to LPPData class --- examples/simple_sensor/SensorMesh.cpp | 126 +++----------------- src/helpers/sensors/LPPDataHelpers.h | 159 ++++++++++++++++++-------- 2 files changed, 128 insertions(+), 157 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 8c6b06a6db..de58e2b168 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -1,5 +1,6 @@ #include "SensorMesh.h" #include +#include /* ------------------------------ Config -------------------------------- */ @@ -80,103 +81,6 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) { /* --------------------- Cayenne LPP helpers ----------------------------*/ -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_RELATIVE_HUMIDITY: - 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: - case LPP_RELATIVE_HUMIDITY: - 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; -} - static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) { uint8_t i = 0; @@ -185,10 +89,10 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u uint8_t ch = buf[i++]; // Get data type uint8_t t = buf[i++]; - uint8_t sz = getDataSize(t); + uint8_t sz = LPPData::getDataSize(t); if (ch == channel && t == type) { - return getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); + return LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); } i += sz; // skip } @@ -209,10 +113,10 @@ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_l uint8_t ch = buf[i++]; // Get data type uint8_t t = buf[i++]; - uint8_t sz = getDataSize(t); + uint8_t sz = LPPData::getDataSize(t); - float v = getFloat(&buf[i], sz, getMultiplier(t), isSigned(t)); - float pv = getFloat(&prev_telem[i], sz, getMultiplier(t), isSigned(t)); + float v = LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + float pv = LPPData::getFloat(&prev_telem[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); float min_delta = findTelemValue(min_deltas, min_deltas_len, ch, t); if (abs(v - pv) > min_delta) return true; // Yes, has changed @@ -268,12 +172,12 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u 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); + uint8_t sz = LPPData::getDataSize(d->_lpp_type); + uint32_t mult = LPPData::getMultiplier(d->_lpp_type); + bool is_signed = LPPData::isSigned(d->_lpp_type); + ofs += LPPData::putFloat(&reply_data[ofs], d->_min, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_max, sz, mult, is_signed); + ofs += LPPData::putFloat(&reply_data[ofs], d->_avg, sz, mult, is_signed); } return ofs; } @@ -317,9 +221,9 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u from->extra.sensor.push_tag = 0; from->extra.sensor.expiry_timestamp = 0; // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? - reply_data[4] = 0; // success - getRNG()->random(&reply_data[5], 3); // just some entropy for better packet-hash uniqueness - return 8; + memset(&reply_data[4], 0, 8); // success + getRNG()->random(&reply_data[12], 2); // just some entropy for better packet-hash uniqueness + return 12 + 2; } return 0; // unknown command } diff --git a/src/helpers/sensors/LPPDataHelpers.h b/src/helpers/sensors/LPPDataHelpers.h index 70a036c493..db49cade49 100644 --- a/src/helpers/sensors/LPPDataHelpers.h +++ b/src/helpers/sensors/LPPDataHelpers.h @@ -63,12 +63,66 @@ #define LPP_ERROR_OVERFLOW 1 #define LPP_ERROR_UNKOWN_TYPE 2 -class LPPReader { - const uint8_t* _buf; - uint8_t _len; - uint8_t _pos; +class LPPData { +public: + 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_RELATIVE_HUMIDITY: + 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: + case LPP_RELATIVE_HUMIDITY: + 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; + } - float getFloat(const uint8_t * buffer, uint8_t size, uint32_t multiplier, bool is_signed) { + 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]; @@ -85,6 +139,36 @@ class LPPReader { 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; + } + +}; + +class LPPReader { + const uint8_t* _buf; + uint8_t _len; + uint8_t _pos; + public: LPPReader(const uint8_t buf[], uint8_t len) : _buf(buf), _len(len), _pos(0) { } @@ -103,72 +187,42 @@ class LPPReader { } bool readGPS(float& lat, float& lon, float& alt) { - lat = getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; - lon = getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; - alt = getFloat(&_buf[_pos], 3, 100, true); _pos += 3; + lat = LPPData::getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; + lon = LPPData::getFloat(&_buf[_pos], 3, 10000, true); _pos += 3; + alt = LPPData::getFloat(&_buf[_pos], 3, 100, true); _pos += 3; return _pos <= _len; } bool readVoltage(float& voltage) { - voltage = getFloat(&_buf[_pos], 2, 100, false); _pos += 2; + voltage = LPPData::getFloat(&_buf[_pos], 2, 100, false); _pos += 2; return _pos <= _len; } bool readCurrent(float& amps) { - amps = getFloat(&_buf[_pos], 2, 1000, true); _pos += 2; + amps = LPPData::getFloat(&_buf[_pos], 2, 1000, true); _pos += 2; return _pos <= _len; } bool readPower(float& watts) { - watts = getFloat(&_buf[_pos], 2, 1, false); _pos += 2; + watts = LPPData::getFloat(&_buf[_pos], 2, 1, false); _pos += 2; return _pos <= _len; } bool readTemperature(float& degrees_c) { - degrees_c = getFloat(&_buf[_pos], 2, 10, true); _pos += 2; + degrees_c = LPPData::getFloat(&_buf[_pos], 2, 10, true); _pos += 2; return _pos <= _len; } bool readPressure(float& pa) { - pa = getFloat(&_buf[_pos], 2, 10, false); _pos += 2; + pa = LPPData::getFloat(&_buf[_pos], 2, 10, false); _pos += 2; return _pos <= _len; } bool readRelativeHumidity(float& pct) { - pct = getFloat(&_buf[_pos], 1, 2, false); _pos += 1; + pct = LPPData::getFloat(&_buf[_pos], 1, 2, false); _pos += 1; return _pos <= _len; } bool readAltitude(float& m) { - m = getFloat(&_buf[_pos], 2, 1, true); _pos += 2; + m = LPPData::getFloat(&_buf[_pos], 2, 1, true); _pos += 2; return _pos <= _len; } void skipData(uint8_t type) { - switch (type) { - case LPP_GPS: - _pos += 9; break; - case LPP_POLYLINE: - _pos += 8; break; // TODO: this is MINIMUM - case LPP_GYROMETER: - case LPP_ACCELEROMETER: - _pos += 6; break; - case LPP_GENERIC_SENSOR: - case LPP_FREQUENCY: - case LPP_DISTANCE: - case LPP_ENERGY: - case LPP_UNIXTIME: - _pos += 4; break; - case LPP_COLOUR: - _pos += 3; break; - 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: - _pos += 2; break; - default: - _pos++; - } + _pos += LPPData::getDataSize(type); } }; @@ -185,6 +239,19 @@ class LPPWriter { public: LPPWriter(uint8_t buf[], uint8_t max_len): _buf(buf), _max_len(max_len), _len(0) { } + bool writeData(uint8_t channel, uint8_t type, float v) { + uint8_t sz = LPPData::getDataSize(type); + bool s = LPPData::isSigned(type); + uint32_t mul = LPPData::getMultiplier(type); + if (_len + 2 + sz <= _max_len) { + _buf[_len++] = channel; + _buf[_len++] = type; + _len += LPPData::putFloat(&_buf[_len], v, sz, mul, s); + return true; + } + return false; + } + bool writeVoltage(uint8_t channel, float voltage) { if (_len + 4 <= _max_len) { _buf[_len++] = channel; From d69ae98b5a2db3b7484183d5acaac8b3d550f3ff Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Sat, 12 Sep 2026 16:53:45 +1000 Subject: [PATCH 07/11] * telemHasChanged() mod, so that only _specified_ min_delta values are considered. --- examples/simple_sensor/SensorMesh.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index de58e2b168..4f2ed8bf11 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -81,7 +81,7 @@ static File openAppend(FILESYSTEM* _fs, const char* fname) { /* --------------------- Cayenne LPP helpers ----------------------------*/ -static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type) { +static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, uint8_t type, float def_value) { uint8_t i = 0; while (i + 2 < size) { @@ -96,7 +96,7 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u } i += sz; // skip } - return 0.0f; // not found + return def_value; // not found } /* ------------------ end Cayenne LPP helpers ----------------------*/ @@ -117,12 +117,14 @@ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_l float v = LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); float pv = LPPData::getFloat(&prev_telem[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); - float min_delta = findTelemValue(min_deltas, min_deltas_len, ch, t); + float min_delta = min_deltas_len > 0 + ? findTelemValue(min_deltas, min_deltas_len, ch, t, 1.0e+16f) // default is just something BIG + : 0.0f; // for ANY change if (abs(v - pv) > min_delta) return true; // Yes, has changed i += sz; // skip } - return false; // no changes + return false; // no changes (OR none of the -specified- telemetry values changed by min_delta) } uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { @@ -961,7 +963,7 @@ void SensorMesh::formatPacketStatsReply(char *reply) { } float SensorMesh::getTelemValue(uint8_t channel, uint8_t type) { - return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type); + return findTelemValue(telemetry.getBuffer(), telemetry.getSize(), channel, type, 0.0f); } bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) { From df82dc23390097e72fdef829d48a34b124cf1036 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Sun, 13 Sep 2026 11:05:38 +1000 Subject: [PATCH 08/11] * min_deltas now mandatory --- examples/simple_sensor/SensorMesh.cpp | 49 ++++++++++++++------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 4f2ed8bf11..54bce50ddf 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -102,29 +102,24 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u /* ------------------ end Cayenne LPP helpers ----------------------*/ bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { - if (telemetry.getSize() != prev_telem_size) return true; - 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++]; + while (i + 2 < min_deltas_len) { + uint8_t ch = min_deltas[i++]; // Get channel # + uint8_t t = min_deltas[i++]; // Get data type uint8_t sz = LPPData::getDataSize(t); - float v = LPPData::getFloat(&buf[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); - float pv = LPPData::getFloat(&prev_telem[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); - float min_delta = min_deltas_len > 0 - ? findTelemValue(min_deltas, min_deltas_len, ch, t, 1.0e+16f) // default is just something BIG - : 0.0f; // for ANY change + float min_delta = LPPData::getFloat(&min_deltas[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + + float v = findTelemValue(buf, size, ch, t, 0.0f); + float pv = findTelemValue(prev_telem, prev_telem_size, ch, t, 0.0f); if (abs(v - pv) > min_delta) return true; // Yes, has changed i += sz; // skip } - return false; // no changes (OR none of the -specified- telemetry values changed by min_delta) + return false; // none of the -specified- telemetry values changed by min_delta } uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { @@ -202,26 +197,34 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u uint16_t timeout_secs; memcpy(&timeout_secs, &payload[4], 2); uint8_t reserved = payload[6]; + uint8_t min_deltas_len = payload[7]; RegionEntry* r; if (recv_pkt_region && !recv_pkt_region->isWildcard()) { // use request scope r = recv_pkt_region; } else { // use default scope r = region_map.getDefaultRegion(); } - from->extra.sensor.scope_region_id = r ? r->id : 0; - from->extra.sensor.expiry_timestamp = r ? getRTCClock()->getCurrentTime() + timeout_secs : 0; - from->extra.sensor.min_deltas_len = min(sizeof(from->extra.sensor.min_deltas), (size_t)payload[7]); - // NOTE: curr impl truncates LPP min_diffs spec (re-do if better impl is needed) - memcpy(from->extra.sensor.min_deltas, &payload[8], from->extra.sensor.min_deltas_len); - - memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); // reply with actual expiry timestamp (or 0 for error) - strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used - return 8 + strlen((char *)&reply_data[8]); + uint8_t reply_len; + if (r && min_deltas_len >= 3 && min_deltas_len <= sizeof(from->extra.sensor.min_deltas)) { + from->extra.sensor.scope_region_id = r->id; + from->extra.sensor.expiry_timestamp = getRTCClock()->getCurrentTime() + timeout_secs; + from->extra.sensor.min_deltas_len = min_deltas_len; + memcpy(from->extra.sensor.min_deltas, &payload[8], min_deltas_len); + // reply with actual expiry timestamp + memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); + strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used + reply_len = 8 + strlen((char *)&reply_data[8]); + } else { + memset(&reply_data[4], 0, 4); // expiry timestamp (0 for error) + reply_len = 8; + } + return reply_len; } if (req_type == REQ_TYPE_UNSUBSCRIBE && (perms & PERM_ACL_ROLE_MASK) >= PERM_ACL_READ_ONLY) { from->extra.sensor.scope_region_id = 0; from->extra.sensor.push_tag = 0; from->extra.sensor.expiry_timestamp = 0; + from->extra.sensor.min_deltas_len = 0; // REVISIT: maybe return some stats, eg total number of telemetry pushes since SUBSCRIBE? memset(&reply_data[4], 0, 8); // success getRNG()->random(&reply_data[12], 2); // just some entropy for better packet-hash uniqueness @@ -1021,7 +1024,7 @@ void SensorMesh::loop() { // compare with previous telemetry, check if any deltas are greater than subscriber minimums for (int i = 0; i < acl.getNumClients(); i++) { auto c = acl.getClientByIdx(i); - if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0) continue; // skip deleted entries, or Not subscribed to deltas + if (c->permissions == 0 || c->extra.sensor.scope_region_id == 0 || c->extra.sensor.min_deltas_len == 0) continue; // skip deleted entries, or Not subscribed to deltas RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); if (r == NULL) continue; // unknown region scope if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired From c6b051d063c611f892fba0341919a969e36991a9 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Sun, 13 Sep 2026 11:40:25 +1000 Subject: [PATCH 09/11] * request payload doco --- docs/payloads.md | 52 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/docs/payloads.md b/docs/payloads.md index fb9cbaf996..493f628ce6 100644 --- a/docs/payloads.md +++ b/docs/payloads.md @@ -93,6 +93,7 @@ Returned path messages provide a description of the route a packet took from the | Field | Size (bytes) | Description | |--------------|-----------------|------------------------------------------| | timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | request sub type | | request data | rest of payload | application-defined request payload body | For the common chat/server helpers in `BaseChatMesh`, the current request type values are: @@ -100,7 +101,13 @@ For the common chat/server helpers in `BaseChatMesh`, the current request type v | Value | Name | Description | |--------|-----------|----------------------------------------------------| | `0x01` | get stats | get stats of repeater or room server | -| `0x02` | keepalive | keep-alive request used for maintained connections | +| `0x02` | keepalive | (deprecated) | +| `0x03` | get telemetry | request node telemetry | +| `0x04` | get min/max/avg | get sensor node stats on time series data | +| `0x05` | get acl | node ACL query | +| `0x06` | get neighbors | node neighbors query | +| `0x08` | subscribe | subscribe to telemetry push | +| `0x09` | ubsubscribe | unsubscribe from telemetry push | #### Get stats @@ -125,21 +132,50 @@ Gets information about the node, possibly including the following: * Number posted (?) * Number of post pushes (?) -#### Get telemetry data - -Not defined in `BaseChatMesh`. Sensor- and application-specific request payloads may be implemented by higher-level firmware. - #### Get Telemetry -Not defined in `BaseChatMesh`. +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x03 (request sub type) | +| permission mask | 1 | bitwise inverse mask to AND to permissions (0 = get ALL telem values) | #### Get Min/Max/Ave (Sensor nodes) -Not defined in `BaseChatMesh`. +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x04 (request sub type) | +| start | 4 | starting time, seconds ago | +| end | 4 | ending time, seconds ago | +| reserved | 2 | should be zeroes | + +#### Subscribe to Telemetry push - (Sensor nodes) + +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x08 (request sub type) | +| push tag | 4 | 32-bit tag to be used in telemetry push _REPLY payloads | +| timeout secs | 2 | subscription timeout (seconds) | +| reserved | 1 | should be zero | +| min deltas len | 1 | byte length of LPP encoded min_deltas | +| min deltas | (variable) | LPP encoded min_deltas | + +#### Unsubscribe from Telemetry push - (Sensor nodes) + +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x09 (request sub type) | #### Get Access List -Not defined in `BaseChatMesh`. +| Field | Size (bytes) | Description | +|----------------|--------------|------------------------------| +| timestamp | 4 | sender time (unix timestamp) | +| req type | 1 | 0x05 (request sub type) | +| reserved | 2 | should be zeroes | #### Get Neighbors From bc8ccefafe1423ba50a0932da815a40c063e6121 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Mon, 14 Sep 2026 20:23:10 +1000 Subject: [PATCH 10/11] * fix for telemHasChanged() --- examples/simple_sensor/SensorMesh.cpp | 41 ++++++++++++++++++--------- examples/simple_sensor/SensorMesh.h | 4 +-- src/helpers/ClientACL.h | 1 + 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 54bce50ddf..70a619f7f8 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -101,25 +101,43 @@ static float findTelemValue(const uint8_t* buf, uint8_t size, uint8_t channel, u /* ------------------ end Cayenne LPP helpers ----------------------*/ -bool SensorMesh::telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len) { +bool SensorMesh::telemHasChanged(ClientInfo* c) { auto buf = telemetry.getBuffer(); uint8_t size = telemetry.getSize(); uint8_t i = 0; + bool changed = false; - while (i + 2 < min_deltas_len) { - uint8_t ch = min_deltas[i++]; // Get channel # - uint8_t t = min_deltas[i++]; // Get data type + while (i + 2 < c->extra.sensor.min_deltas_len) { + uint8_t ch = c->extra.sensor.min_deltas[i]; // Get channel # + uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type uint8_t sz = LPPData::getDataSize(t); - float min_delta = LPPData::getFloat(&min_deltas[i], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + float min_delta = LPPData::getFloat(&c->extra.sensor.min_deltas[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + float pv = LPPData::getFloat(&c->extra.sensor.prev_telem[i + 2], sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); float v = findTelemValue(buf, size, ch, t, 0.0f); - float pv = findTelemValue(prev_telem, prev_telem_size, ch, t, 0.0f); - if (abs(v - pv) > min_delta) return true; // Yes, has changed + if (abs(v - pv) > min_delta) changed = true; // Yes, has changed - i += sz; // skip + i += 2 + sz; // skip + } + if (changed) { + // take snapshot of all _monitored_ telem values, for next cycle + i = 0; + while (i + 2 < c->extra.sensor.min_deltas_len) { + uint8_t ch = c->extra.sensor.min_deltas[i]; // Get channel # + uint8_t t = c->extra.sensor.min_deltas[i + 1]; // Get data type + uint8_t sz = LPPData::getDataSize(t); + + c->extra.sensor.prev_telem[i] = ch; + c->extra.sensor.prev_telem[i + 1] = t; + + float v = findTelemValue(buf, size, ch, t, 0.0f); + LPPData::putFloat(&c->extra.sensor.prev_telem[i + 2], v, sz, LPPData::getMultiplier(t), LPPData::isSigned(t)); + + i += 2 + sz; // skip + } } - return false; // none of the -specified- telemetry values changed by min_delta + return changed; } uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len) { @@ -774,7 +792,6 @@ SensorMesh::SensorMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::Millise num_alert_tasks = 0; set_radio_at = revert_radio_at = 0; recv_pkt_region = NULL; - prev_telem_size = 0; region_load_active = false; // defaults @@ -1028,7 +1045,7 @@ void SensorMesh::loop() { RegionEntry* r = region_map.findById(c->extra.sensor.scope_region_id); if (r == NULL) continue; // unknown region scope if (curr > c->extra.sensor.expiry_timestamp) continue; // subscription now expired - if (telemHasChanged(c->extra.sensor.min_deltas, c->extra.sensor.min_deltas_len)) { + if (telemHasChanged(c)) { TransportKey scope; if (region_map.getTransportKeysFor(*r, &scope, 1) > 0) { uint8_t tlen = telemetry.getSize(); @@ -1048,8 +1065,6 @@ void SensorMesh::loop() { } } } - memcpy(prev_telem, telemetry.getBuffer(), telemetry.getSize()); // save snapshot for next compare cycle - prev_telem_size = telemetry.getSize(); onSensorDataRead(); diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index e0e03c81be..6b7a32fef0 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -148,8 +148,6 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { uint8_t reply_data[MAX_PACKET_PAYLOAD]; unsigned long dirty_contacts_expiry; CayenneLPP telemetry; - uint8_t prev_telem_size; - uint8_t prev_telem[MAX_PACKET_PAYLOAD - 4]; TransportKeyStore key_store; RegionMap region_map, temp_map; RegionEntry* recv_pkt_region; @@ -166,7 +164,7 @@ class SensorMesh : public mesh::Mesh, public CommonCLICallbacks { uint8_t pending_cr; bool region_load_active; - bool telemHasChanged(const uint8_t* min_deltas, uint8_t min_deltas_len); + bool telemHasChanged(ClientInfo* c); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); uint8_t handleRequest(ClientInfo* from, uint32_t sender_timestamp, uint8_t req_type, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); diff --git a/src/helpers/ClientACL.h b/src/helpers/ClientACL.h index 39e71f2c8b..9938bc1e1f 100644 --- a/src/helpers/ClientACL.h +++ b/src/helpers/ClientACL.h @@ -34,6 +34,7 @@ struct ClientInfo { uint16_t scope_region_id; // scope to use when sending telemetry to this client/subscriber uint8_t min_deltas_len; uint8_t min_deltas[14]; // LPP encoded + uint8_t prev_telem[14]; // LPP encoded } sensor; } extra; From 3819a0bd897b63e1ec8e11d0bb34d83a107ffb00 Mon Sep 17 00:00:00 2001 From: Scott Powell Date: Tue, 15 Sep 2026 17:17:48 +1000 Subject: [PATCH 11/11] * subscribe response now returns expiry_secs (not timestamp) --- examples/simple_sensor/SensorMesh.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/examples/simple_sensor/SensorMesh.cpp b/examples/simple_sensor/SensorMesh.cpp index 70a619f7f8..b186066810 100644 --- a/examples/simple_sensor/SensorMesh.cpp +++ b/examples/simple_sensor/SensorMesh.cpp @@ -228,12 +228,13 @@ uint8_t SensorMesh::handleRequest(ClientInfo* from, uint32_t sender_timestamp, u from->extra.sensor.expiry_timestamp = getRTCClock()->getCurrentTime() + timeout_secs; from->extra.sensor.min_deltas_len = min_deltas_len; memcpy(from->extra.sensor.min_deltas, &payload[8], min_deltas_len); - // reply with actual expiry timestamp - memcpy(&reply_data[4], &from->extra.sensor.expiry_timestamp, 4); + // reply with actual expiry seconds (we could modify/impose restriction) + memcpy(&reply_data[4], &timeout_secs, 2); + memset(&reply_data[6], 0, 2); // reserved strcpy((char *)&reply_data[8], r ? r->name : ""); // reply with name of scope that will be used reply_len = 8 + strlen((char *)&reply_data[8]); } else { - memset(&reply_data[4], 0, 4); // expiry timestamp (0 for error) + memset(&reply_data[4], 0, 4); // expiry secs (0 for error) reply_len = 8; } return reply_len;