Merge observer firmware and webconfig updates
# Conflicts: # MQTT_INTERNALS.md # build.sh # docs/cli_commands.md # examples/simple_repeater/MyMesh.cpp # examples/simple_repeater/MyMesh.h # examples/simple_repeater/UITask.cpp # examples/simple_room_server/MyMesh.cpp # examples/simple_room_server/MyMesh.h # examples/simple_room_server/UITask.cpp # examples/simple_sensor/SensorMesh.cpp # platformio.ini # scripts/generate_webconfig_html.py # src/MeshCore.h # src/helpers/CommonCLI.cpp # src/helpers/CommonCLI.h # src/helpers/CommonCLI_Observer.cpp # src/helpers/ESP32Board.h # src/helpers/MQTTMessageBuilder.cpp # src/helpers/MQTTPresets.h # src/helpers/NRF52Board.cpp # src/helpers/NRF52Board.h # src/helpers/bridges/MQTTBridge.cpp # src/helpers/bridges/MQTTBridge.h # src/helpers/esp32/WebConfigServer.cpp # src/helpers/esp32/WebConfigServer.h # src/helpers/radiolib/RadioLibWrappers.cpp # src/helpers/radiolib/RadioLibWrappers.h # variants/lilygo_tbeam_SX1262/platformio.ini # variants/lilygo_tbeam_SX1276/platformio.ini # variants/lilygo_tlora_v2_1/platformio.ini # webui/index.html
This commit is contained in:
commit
c1caa5ad81
109 files changed
+14844
-2297
No files matched your search
@@ -87,6 +87,12 @@
|
||||
|
||||
#define CLI_REPLY_DELAY_MILLIS 600
|
||||
|
||||
// Max time to flush the outbound queue (START alert + CLI reply) before the OTA
|
||||
// teardown blocks the loop until reboot. Best-effort: exits early once the queue
|
||||
// drains (immediate on a healthy node), caps the wait on a jammed/duty-limited
|
||||
// channel so an update is never stalled indefinitely.
|
||||
#define OTA_TX_DRAIN_TIMEOUT_MS 5000
|
||||
|
||||
#define LAZY_CONTACTS_WRITE_DELAY 5000
|
||||
|
||||
#define FLOOD_CHANNEL_BLOCK_FILE "/flood_ch_block"
|
||||
@@ -2218,7 +2224,22 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
|
||||
int MyMesh::searchPeersByHash(const uint8_t *hash) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < acl.getNumClients(); i++) {
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// While a neighbor-scope discovery is active, overlay the heard neighbours
|
||||
// that are NOT already ACL clients so their RESPONSE packets can be decoded.
|
||||
// Overlay indices are offset by NEIGHBOR_DISCOVER_PEER_BASE to keep them
|
||||
// distinct from real ACL indices.
|
||||
if (neighbor_discover_active) {
|
||||
for (int i = 0; i < neighbor_discover_count && n < MAX_CLIENTS; i++) {
|
||||
auto& nb = neighbours[neighbor_discover[i].neighbour_idx];
|
||||
if (acl.getClient(nb.id.pub_key, PUB_KEY_SIZE) != nullptr) continue;
|
||||
if (nb.heard_timestamp > 0 && nb.id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = NEIGHBOR_DISCOVER_PEER_BASE + i;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
for (int i = 0; i < acl.getNumClients() && n < MAX_CLIENTS; i++) {
|
||||
if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
|
||||
}
|
||||
@@ -2228,6 +2249,16 @@ int MyMesh::searchPeersByHash(const uint8_t *hash) {
|
||||
|
||||
void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
|
||||
int i = matching_peer_indexes[peer_idx];
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// Overlay entries have no precomputed shared secret; derive it on the fly.
|
||||
if (neighbor_discover_active && i >= NEIGHBOR_DISCOVER_PEER_BASE) {
|
||||
int oi = i - NEIGHBOR_DISCOVER_PEER_BASE;
|
||||
if (oi >= 0 && oi < neighbor_discover_count) {
|
||||
self_id.calcSharedSecret(dest_secret, neighbours[neighbor_discover[oi].neighbour_idx].id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (i >= 0 && i < acl.getNumClients()) {
|
||||
// lookup pre-calculated shared_secret
|
||||
memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
|
||||
@@ -2279,11 +2310,34 @@ void MyMesh::onGroupPacketRecv(mesh::Packet* packet) {
|
||||
void MyMesh::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 defined(WITH_MQTT_NEIGHBORS)
|
||||
// Overlay response: a heard neighbour (not an ACL client) answering our
|
||||
// anon-regions scope query. Consume it and stop -- it is not a client packet.
|
||||
if (neighbor_discover_active && i >= NEIGHBOR_DISCOVER_PEER_BASE) {
|
||||
int oi = i - NEIGHBOR_DISCOVER_PEER_BASE;
|
||||
if (type == PAYLOAD_TYPE_RESPONSE && oi >= 0 && oi < neighbor_discover_count) {
|
||||
handleNeighborDiscoverResponse(oi, data, len);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
|
||||
return;
|
||||
}
|
||||
ClientInfo* client = acl.getClientByIdx(i);
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// A neighbour that IS an ACL client resolves to a normal index above, so a
|
||||
// scope-query response from it lands here -- match it against the overlay.
|
||||
if (neighbor_discover_active && type == PAYLOAD_TYPE_RESPONSE) {
|
||||
for (int oi = 0; oi < neighbor_discover_count; oi++) {
|
||||
auto& nb = neighbours[neighbor_discover[oi].neighbour_idx];
|
||||
if (client->id.matches(nb.id) && handleNeighborDiscoverResponse(oi, data, len)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
|
||||
uint32_t timestamp;
|
||||
@@ -2683,6 +2737,16 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
pending_discover_tag = 0;
|
||||
pending_discover_until = 0;
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
neighbor_discover_count = 0;
|
||||
neighbor_discover_active = false;
|
||||
neighbor_table_refresh_active = false;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
neighbor_discover_until = 0;
|
||||
next_neighbors_publish = 0;
|
||||
self_scopes_buf[0] = 0;
|
||||
#endif
|
||||
|
||||
memset(default_scope.key, 0, sizeof(default_scope.key));
|
||||
}
|
||||
|
||||
@@ -2694,6 +2758,25 @@ void MyMesh::begin(FILESYSTEM *fs) {
|
||||
// load persisted prefs
|
||||
_cli.loadPrefs(_fs);
|
||||
|
||||
#ifdef SIM_WIFI_SSID
|
||||
// Emulator builds (Wokwi) boot with fresh NVS every run. Seed WiFi so the
|
||||
// observer auto-joins the simulator's network and brings the MQTT bridge up
|
||||
// (WiFi is driven by the bridge task), instead of raising the setup AP that
|
||||
// the emulator can't model. No-op for real firmware (flag never defined).
|
||||
{
|
||||
MQTTPrefs* obs = _cli.getObserverPrefs();
|
||||
if (obs->wifi_ssid[0] == 0) {
|
||||
strncpy(obs->wifi_ssid, SIM_WIFI_SSID, sizeof(obs->wifi_ssid) - 1);
|
||||
obs->wifi_ssid[sizeof(obs->wifi_ssid) - 1] = 0;
|
||||
#ifdef SIM_WIFI_PWD
|
||||
strncpy(obs->wifi_password, SIM_WIFI_PWD, sizeof(obs->wifi_password) - 1);
|
||||
obs->wifi_password[sizeof(obs->wifi_password) - 1] = 0;
|
||||
#endif
|
||||
_prefs.bridge_enabled = 1; // WiFi comes up via the MQTT bridge task
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
acl.load(_fs, self_id);
|
||||
// TODO: key_store.begin();
|
||||
region_map.load(_fs);
|
||||
@@ -7174,6 +7257,36 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, ClientInfo* sender, char *
|
||||
sendNodeDiscoverReq();
|
||||
strcpy(reply, "OK - Discover sent");
|
||||
}
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
} else if (memcmp(command, "discover.scopes", 15) == 0) {
|
||||
const char* sub = command + 15;
|
||||
while (*sub == ' ') sub++;
|
||||
if (*sub != 0) {
|
||||
strcpy(reply, "Err - discover.scopes has no options");
|
||||
} else if (pending_discover_tag != 0 &&
|
||||
!millisHasNowPassed(pending_discover_until) &&
|
||||
!neighbor_discover_active) {
|
||||
// A zero-hop table refresh is already collecting; queue the scope pass
|
||||
// behind it (as a manual, non-periodic request) rather than starting a
|
||||
// second refresh.
|
||||
if (!neighborDiscoverReady(reply)) {
|
||||
// reply already set by neighborDiscoverReady
|
||||
} else {
|
||||
neighbor_table_refresh_active = true;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
long remaining_ms = (long)(pending_discover_until - futureMillis(0));
|
||||
unsigned remaining_secs = remaining_ms > 0
|
||||
? (unsigned)(((unsigned long)remaining_ms + 999UL) / 1000UL) : 0;
|
||||
sprintf(reply, "OK - scopes queued (%us discovery remaining)", remaining_secs);
|
||||
MESH_DEBUG_PRINTLN("Neighbor scopes queued behind active discovery (%us remaining)", remaining_secs);
|
||||
}
|
||||
} else if (!startNeighborDiscover(reply)) {
|
||||
// reply already set by startNeighborDiscover
|
||||
}
|
||||
#elif defined(WITH_MQTT_BRIDGE)
|
||||
} else if (memcmp(command, "discover.scopes", 15) == 0) {
|
||||
strcpy(reply, "Err - not supported (requires PSRAM)");
|
||||
#endif
|
||||
} else{
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
@@ -7232,12 +7345,30 @@ void __attribute__((noinline)) MyMesh::servicePostMeshLoop() {
|
||||
// (so this never returns); on any abort (already up to date, partition change,
|
||||
// download error) it returns and we resume the bridge.
|
||||
Serial.println("OTA: starting update");
|
||||
// Flush the START alert (and CLI reply) out the radio BEFORE teardown blocks
|
||||
// the loop until reboot - otherwise a packet still queued here (busy /
|
||||
// duty-limited channel) is lost when the flash spins the loop and reboots.
|
||||
drainOutbound(OTA_TX_DRAIN_TIMEOUT_MS);
|
||||
setBridgeState(false);
|
||||
char ota_reply[160];
|
||||
if (!_cli.getBoard()->otaFromManifest(getFirmwareVer(), false, ota_reply)) {
|
||||
// OTA teardown barrier (Phase 5): only flash after a CLEAN MQTT shutdown.
|
||||
// A timed-out/forced stop leaves mbedTLS/heap ownership uncertain - writing
|
||||
// firmware then is the observed teardown heap-panic path - so abort and
|
||||
// resume the bridge instead of flashing under uncertain ownership.
|
||||
if (mqtt_bridge && !mqtt_bridge->canFlashAfterStop()) {
|
||||
Serial.println("OTA: aborted, MQTT stop did not complete cleanly - resuming bridge");
|
||||
otaAlert("OTA aborted: MQTT stop unclean, bridge resumed");
|
||||
setBridgeState(true);
|
||||
} else if (!_cli.getBoard()->otaFromManifest(getFirmwareVer(), false, ota_reply)) {
|
||||
Serial.print("OTA: aborted, resuming bridge - "); Serial.println(ota_reply);
|
||||
char ota_alert_msg[160];
|
||||
snprintf(ota_alert_msg, sizeof(ota_alert_msg), "OTA aborted: %s", ota_reply);
|
||||
otaAlert(ota_alert_msg);
|
||||
setBridgeState(true);
|
||||
}
|
||||
// Success path: otaFromManifest() flashes and reboots into the new image
|
||||
// (never returns), so there is no in-boot "success" alert - the START alert
|
||||
// plus the node returning on the new version is the success signal.
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -7275,6 +7406,66 @@ void __attribute__((noinline)) MyMesh::servicePostMeshLoop() {
|
||||
_alerter.onLoop(now);
|
||||
#endif
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// Two-stage periodic neighbors publication:
|
||||
// stage 1 - zero-hop node-discover refreshes the neighbour table (60s window)
|
||||
// stage 2 - anon-regions scope query per neighbour (startNeighborDiscover)
|
||||
// then the table JSON is published and the next cycle is rescheduled.
|
||||
bool periodic_neighbors_enabled = _cli.getObserverPrefs()->mqtt_neighbors_enabled;
|
||||
if (neighbor_discover_active) {
|
||||
loopNeighborDiscover();
|
||||
} else if (neighbor_table_refresh_active) {
|
||||
if (neighbor_table_refresh_periodic && !periodic_neighbors_enabled) {
|
||||
// periodic switched off mid-refresh -> cancel (leave pending_discover_tag alone)
|
||||
neighbor_table_refresh_active = false;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
next_neighbors_publish = 0;
|
||||
} else if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
|
||||
// 60s zero-hop window done -> begin the per-neighbour scope queries
|
||||
bool was_periodic = neighbor_table_refresh_periodic;
|
||||
pending_discover_tag = 0;
|
||||
neighbor_table_refresh_active = false;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
char tmp_reply[80];
|
||||
const char* origin_str = was_periodic ? "periodic" : "manual";
|
||||
if (startNeighborDiscover(tmp_reply)) {
|
||||
MESH_DEBUG_PRINTLN("MQTT %s %s", origin_str, tmp_reply);
|
||||
} else {
|
||||
if (periodic_neighbors_enabled) {
|
||||
next_neighbors_publish = futureMillis(_cli.getObserverPrefs()->mqtt_neighbors_interval);
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("MQTT %s neighbor scope discovery failed: %s", origin_str, tmp_reply);
|
||||
}
|
||||
}
|
||||
} else if (periodic_neighbors_enabled && mqtt_bridge && mqtt_bridge->isRunning()) {
|
||||
if (next_neighbors_publish == 0 ||
|
||||
(next_neighbors_publish != 0 && millisHasNowPassed(next_neighbors_publish))) {
|
||||
if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
|
||||
pending_discover_tag = 0;
|
||||
sendNodeDiscoverReq();
|
||||
MESH_DEBUG_PRINTLN("MQTT periodic neighbor table refresh started");
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("MQTT periodic refresh joined active neighbor discovery");
|
||||
}
|
||||
neighbor_table_refresh_active = true;
|
||||
neighbor_table_refresh_periodic = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Report the schedule state back to the bridge for `get mqtt.status`.
|
||||
if (mqtt_bridge) {
|
||||
if (neighbor_discover_active || neighbor_table_refresh_active) {
|
||||
mqtt_bridge->setNeighborsSchedule(MQTTBridge::NBR_ACTIVE, 0);
|
||||
} else if (next_neighbors_publish == 0 || millisHasNowPassed(next_neighbors_publish)) {
|
||||
mqtt_bridge->setNeighborsSchedule(MQTTBridge::NBR_DUE, 0);
|
||||
} else {
|
||||
long remaining_ms = (long)(next_neighbors_publish - futureMillis(0));
|
||||
uint32_t remaining_secs = remaining_ms > 0 ? (uint32_t)(remaining_ms / 1000) : 0;
|
||||
mqtt_bridge->setNeighborsSchedule(MQTTBridge::NBR_SCHEDULED, remaining_secs);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef WITH_SNMP
|
||||
// Push radio stats to SNMP agent every 2 seconds
|
||||
if (_snmp_agent.isRunning()) {
|
||||
@@ -7295,6 +7486,258 @@ void __attribute__((noinline)) MyMesh::servicePostMeshLoop() {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
#include "helpers/MQTTMessageBuilder.h"
|
||||
#if defined(ESP_PLATFORM)
|
||||
#include <esp_heap_caps.h>
|
||||
#endif
|
||||
|
||||
// This node's own non-flood scope names, same source the anon-regions server
|
||||
// reply uses. Empty string when the node has no scoped regions.
|
||||
void MyMesh::getLocalScopes(char* buf, size_t len) {
|
||||
if (!buf || len == 0) return;
|
||||
buf[0] = 0;
|
||||
region_map.exportNamesTo(buf, (int)len, REGION_DENY_FLOOD);
|
||||
}
|
||||
|
||||
// Client side of the anon-regions request (the server side is handleAnonRegionsReq).
|
||||
// Inner payload: {tag(4)}{ANON_REQ_TYPE_REGIONS}{0x00 = zero-hop reply path}.
|
||||
bool MyMesh::sendAnonRegionsReq(const mesh::Identity& target, uint32_t& tag) {
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
self_id.calcSharedSecret(secret, target);
|
||||
|
||||
tag = getRTCClock()->getCurrentTimeUnique();
|
||||
uint8_t inner[6];
|
||||
memcpy(inner, &tag, 4);
|
||||
inner[4] = ANON_REQ_TYPE_REGIONS;
|
||||
inner[5] = 0x00; // request a zero-hop reply path
|
||||
|
||||
mesh::Packet* pkt = createAnonDatagram(PAYLOAD_TYPE_ANON_REQ, self_id, target, secret, inner, sizeof(inner));
|
||||
if (!pkt) return false;
|
||||
sendDirect(pkt, NULL, 0, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Match a RESPONSE against the pending overlay entry by tag; copy its scope
|
||||
// string (payload after the 8-byte {tag}{clock} header) into the entry.
|
||||
bool MyMesh::handleNeighborDiscoverResponse(int overlay_idx, const uint8_t* data, size_t len) {
|
||||
if (overlay_idx < 0 || overlay_idx >= neighbor_discover_count) return false;
|
||||
NeighborDiscoverEntry& entry = neighbor_discover[overlay_idx];
|
||||
if (entry.status != ND_PENDING || len < 8) return false;
|
||||
|
||||
uint32_t tag;
|
||||
memcpy(&tag, data, 4);
|
||||
if (tag != entry.tag) return false;
|
||||
|
||||
size_t scope_len = len - 8;
|
||||
if (scope_len >= sizeof(entry.scopes)) {
|
||||
scope_len = sizeof(entry.scopes) - 1;
|
||||
}
|
||||
memcpy(entry.scopes, &data[8], scope_len);
|
||||
entry.scopes[scope_len] = 0;
|
||||
entry.status = ND_RESPONDED;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Publish-ordering: most recently heard first, then stronger SNR, then pubkey.
|
||||
// The JSON builder drops the tail if the buffer fills, so the head must be the
|
||||
// most useful entries.
|
||||
static bool neighborPublishEntryComesBefore(
|
||||
const MQTTMessageBuilder::NeighborsMessageEntry& lhs,
|
||||
const MQTTMessageBuilder::NeighborsMessageEntry& rhs) {
|
||||
if (lhs.heard_secs_ago != rhs.heard_secs_ago) {
|
||||
return lhs.heard_secs_ago < rhs.heard_secs_ago; // newer first
|
||||
}
|
||||
if (lhs.snr != rhs.snr) {
|
||||
return lhs.snr > rhs.snr; // stronger first when equally recent
|
||||
}
|
||||
return strcmp(lhs.pubkey_hex, rhs.pubkey_hex) < 0;
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
// ArduinoJson v7 JsonDocument has no real capacity cap (DynamicJsonDocument(N)
|
||||
// is a no-op shim). Keep the pool off internal DRAM and soft-cap peak growth to
|
||||
// the publish buffer size. used only rises on allocate -- conservative for this
|
||||
// single-shot doc (overflow path removes+breaks, so no further growth after free).
|
||||
struct NeighborsDocAllocator : ArduinoJson::Allocator {
|
||||
size_t used = 0;
|
||||
static const size_t kBudget = MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE;
|
||||
|
||||
void* allocate(size_t size) override {
|
||||
if (used >= kBudget || size > kBudget - used) return nullptr;
|
||||
void* p = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (p) used += size;
|
||||
return p;
|
||||
}
|
||||
|
||||
void deallocate(void* ptr) override {
|
||||
heap_caps_free(ptr);
|
||||
}
|
||||
|
||||
void* reallocate(void* ptr, size_t new_size) override {
|
||||
size_t old_size = ptr ? heap_caps_get_allocated_size(ptr) : 0;
|
||||
size_t next_used = (used >= old_size) ? (used - old_size) : 0;
|
||||
if (next_used >= kBudget || new_size > kBudget - next_used) return nullptr;
|
||||
void* p = heap_caps_realloc(ptr, new_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (p) used = next_used + new_size;
|
||||
return p;
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
// Build the neighbors-table JSON and hand it to the bridge, then reschedule.
|
||||
void MyMesh::finishNeighborDiscover() {
|
||||
getLocalScopes(self_scopes_buf, sizeof(self_scopes_buf));
|
||||
|
||||
char self_pubkey_hex[65];
|
||||
mesh::Utils::toHex(self_pubkey_hex, self_id.pub_key, PUB_KEY_SIZE);
|
||||
|
||||
char origin[32];
|
||||
MQTTBridge::getEffectiveMqttOrigin(_prefs.node_name, _cli.getObserverPrefs(), origin, sizeof(origin));
|
||||
|
||||
char timestamp[40];
|
||||
MQTTMessageBuilder::formatIsoTimestampForMqtt(getRTCClock()->getCurrentTime(), 0, nullptr, timestamp, sizeof(timestamp));
|
||||
|
||||
char pubkey_hex[MAX_NEIGHBOURS][65];
|
||||
MQTTMessageBuilder::NeighborsMessageEntry entries[MAX_NEIGHBOURS];
|
||||
uint32_t now_secs = getRTCClock()->getCurrentTime();
|
||||
|
||||
for (int i = 0; i < neighbor_discover_count; i++) {
|
||||
auto& nb = neighbours[neighbor_discover[i].neighbour_idx];
|
||||
mesh::Utils::toHex(pubkey_hex[i], nb.id.pub_key, PUB_KEY_SIZE);
|
||||
entries[i].pubkey_hex = pubkey_hex[i];
|
||||
entries[i].snr = nb.snr / 4.0f;
|
||||
entries[i].heard_secs_ago = (nb.heard_timestamp > 0 && now_secs >= nb.heard_timestamp)
|
||||
? (now_secs - nb.heard_timestamp) : 0;
|
||||
entries[i].scopes = neighbor_discover[i].scopes;
|
||||
switch (neighbor_discover[i].status) {
|
||||
case ND_RESPONDED: entries[i].status = "responded"; break;
|
||||
case ND_SEND_FAILED: entries[i].status = "send_failed"; break;
|
||||
default: entries[i].status = "timeout"; break;
|
||||
}
|
||||
}
|
||||
|
||||
// insertion sort: most useful first (JSON builder drops the tail on overflow)
|
||||
for (int i = 1; i < neighbor_discover_count; i++) {
|
||||
MQTTMessageBuilder::NeighborsMessageEntry entry = entries[i];
|
||||
int j = i;
|
||||
while (j > 0 && neighborPublishEntryComesBefore(entry, entries[j - 1])) {
|
||||
entries[j] = entries[j - 1];
|
||||
j--;
|
||||
}
|
||||
entries[j] = entry;
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
char* json_buf = (char*)heap_caps_malloc(MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE, MALLOC_CAP_SPIRAM);
|
||||
#else
|
||||
char* json_buf = (char*)malloc(MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE);
|
||||
#endif
|
||||
if (!json_buf) {
|
||||
neighbor_discover_active = false;
|
||||
neighbor_discover_count = 0;
|
||||
if (_cli.getObserverPrefs()->mqtt_neighbors_enabled) {
|
||||
next_neighbors_publish = futureMillis(_cli.getObserverPrefs()->mqtt_neighbors_interval);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
NeighborsDocAllocator doc_alloc;
|
||||
JsonDocument doc(&doc_alloc);
|
||||
#else
|
||||
JsonDocument doc;
|
||||
#endif
|
||||
int json_len = MQTTMessageBuilder::buildNeighborsMessage(
|
||||
doc, origin, self_pubkey_hex, timestamp, self_scopes_buf,
|
||||
entries, neighbor_discover_count,
|
||||
json_buf, MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE);
|
||||
|
||||
if (json_len > 0 && mqtt_bridge) {
|
||||
mqtt_bridge->requestPublishNeighbors(json_buf, (size_t)json_len);
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
heap_caps_free(json_buf);
|
||||
#else
|
||||
free(json_buf);
|
||||
#endif
|
||||
|
||||
neighbor_discover_active = false;
|
||||
neighbor_discover_count = 0;
|
||||
if (_cli.getObserverPrefs()->mqtt_neighbors_enabled) {
|
||||
next_neighbors_publish = futureMillis(_cli.getObserverPrefs()->mqtt_neighbors_interval);
|
||||
}
|
||||
}
|
||||
|
||||
// Advance the scope-query phase; publish once all entries resolve or the window
|
||||
// times out (stragglers marked ND_TIMEOUT).
|
||||
void MyMesh::loopNeighborDiscover() {
|
||||
if (!neighbor_discover_active) return;
|
||||
|
||||
bool all_done = true;
|
||||
for (int i = 0; i < neighbor_discover_count; i++) {
|
||||
if (neighbor_discover[i].status == ND_PENDING) { all_done = false; break; }
|
||||
}
|
||||
if (!all_done && !millisHasNowPassed(neighbor_discover_until)) return;
|
||||
if (!all_done) {
|
||||
for (int i = 0; i < neighbor_discover_count; i++) {
|
||||
if (neighbor_discover[i].status == ND_PENDING) neighbor_discover[i].status = ND_TIMEOUT;
|
||||
}
|
||||
}
|
||||
finishNeighborDiscover();
|
||||
}
|
||||
|
||||
// Shared precondition for starting a discovery: PSRAM present + bridge running.
|
||||
bool MyMesh::neighborDiscoverReady(char* reply) {
|
||||
#if defined(ESP_PLATFORM)
|
||||
if (!psramFound()) { strcpy(reply, "Err - PSRAM not available"); return false; }
|
||||
#endif
|
||||
if (!mqtt_bridge || !mqtt_bridge->isRunning()) { strcpy(reply, "Err - MQTT bridge not running"); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
// Snapshot the neighbor table into the overlay and fire one anon-regions query
|
||||
// per heard neighbour; arm the 30s scope-query window.
|
||||
bool MyMesh::startNeighborDiscover(char* reply) {
|
||||
if (neighbor_discover_active) {
|
||||
strcpy(reply, "Err - neighbor discover already active");
|
||||
return false;
|
||||
}
|
||||
if (!neighborDiscoverReady(reply)) {
|
||||
return false; // reply already set
|
||||
}
|
||||
|
||||
getLocalScopes(self_scopes_buf, sizeof(self_scopes_buf));
|
||||
neighbor_discover_count = 0;
|
||||
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
|
||||
if (neighbours[i].heard_timestamp > 0) {
|
||||
neighbor_discover[neighbor_discover_count].neighbour_idx = (uint8_t)i;
|
||||
neighbor_discover[neighbor_discover_count].scopes[0] = 0;
|
||||
neighbor_discover[neighbor_discover_count].status = ND_PENDING;
|
||||
uint32_t tag;
|
||||
if (sendAnonRegionsReq(neighbours[i].id, tag)) {
|
||||
neighbor_discover[neighbor_discover_count].tag = tag;
|
||||
} else {
|
||||
neighbor_discover[neighbor_discover_count].status = ND_SEND_FAILED;
|
||||
}
|
||||
neighbor_discover_count++;
|
||||
}
|
||||
}
|
||||
|
||||
neighbor_discover_active = true;
|
||||
neighbor_discover_until = futureMillis(NEIGHBOR_DISCOVER_TIMEOUT_MS);
|
||||
|
||||
if (neighbor_discover_count == 0) {
|
||||
finishNeighborDiscover();
|
||||
strcpy(reply, "OK - neighbor discover started (0 neighbors, self only)");
|
||||
} else {
|
||||
sprintf(reply, "OK - neighbor discover started (%u neighbors)", (unsigned)neighbor_discover_count);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif // WITH_MQTT_NEIGHBORS
|
||||
|
||||
// To check if there is pending work
|
||||
bool MyMesh::hasPendingWork() const {
|
||||
if (deferred_cli_command.pending || pending_self_advert) return true;
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
#include "helpers/bridges/MQTTBridge.h"
|
||||
#define WITH_BRIDGE
|
||||
#include "helpers/esp32/WebConfigServer.h" // defines WITH_WEBCONFIG on ESP32
|
||||
#endif
|
||||
|
||||
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && !defined(WEBCONFIG_DISABLED)
|
||||
@@ -376,6 +377,44 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
|
||||
uint8_t _wc_slot_restart_mask = 0;
|
||||
#endif
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// Neighbor-scope discovery: a snapshot of the neighbor table overlaid with an
|
||||
// in-flight anon-regions query per neighbor, published to the MQTT neighbors
|
||||
// topic once every neighbor has responded or the window times out.
|
||||
enum NeighborDiscoverStatus : uint8_t {
|
||||
ND_PENDING = 1,
|
||||
ND_RESPONDED = 2,
|
||||
ND_TIMEOUT = 3,
|
||||
ND_SEND_FAILED = 4,
|
||||
};
|
||||
struct NeighborDiscoverEntry {
|
||||
uint8_t neighbour_idx; // index into neighbours[]
|
||||
uint32_t tag; // anon-regions request tag we're waiting on
|
||||
char scopes[96]; // scope names from the response
|
||||
uint8_t status; // NeighborDiscoverStatus
|
||||
};
|
||||
NeighborDiscoverEntry neighbor_discover[MAX_NEIGHBOURS];
|
||||
uint8_t neighbor_discover_count;
|
||||
bool neighbor_discover_active; // scope-query phase in flight
|
||||
bool neighbor_table_refresh_active; // zero-hop table refresh (stage 1) in flight
|
||||
bool neighbor_table_refresh_periodic; // that refresh was kicked by the periodic timer
|
||||
unsigned long neighbor_discover_until; // scope-query timeout deadline
|
||||
unsigned long next_neighbors_publish; // periodic publish deadline (0 = fire ASAP)
|
||||
char self_scopes_buf[96];
|
||||
|
||||
bool sendAnonRegionsReq(const mesh::Identity& target, uint32_t& tag);
|
||||
bool neighborDiscoverReady(char* reply);
|
||||
bool startNeighborDiscover(char* reply);
|
||||
void loopNeighborDiscover();
|
||||
void finishNeighborDiscover();
|
||||
bool handleNeighborDiscoverResponse(int overlay_idx, const uint8_t* data, size_t len);
|
||||
void getLocalScopes(char* buf, size_t len);
|
||||
// Overlay peer indices are offset by this base so onPeerDataRecv can tell a
|
||||
// discovery response apart from a normal ACL-client index.
|
||||
static const int NEIGHBOR_DISCOVER_PEER_BASE = 1000;
|
||||
static const unsigned long NEIGHBOR_DISCOVER_TIMEOUT_MS = 30000;
|
||||
#endif
|
||||
|
||||
bool extractDirectRetryPrefix(const mesh::Packet* packet, uint8_t* prefix, uint8_t& prefix_len) const;
|
||||
int8_t getDirectRetryMinSNRX4() const;
|
||||
uint8_t getDirectRetryCodingRateForSNR(int8_t snr_x4) const;
|
||||
@@ -554,9 +593,6 @@ protected:
|
||||
int getInterferenceThreshold() const override {
|
||||
return _prefs.interference_threshold;
|
||||
}
|
||||
bool getCADEnabled() const override {
|
||||
return _prefs.cad_enabled;
|
||||
}
|
||||
int getAGCResetInterval() const override {
|
||||
return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
|
||||
}
|
||||
@@ -720,7 +756,7 @@ public:
|
||||
AbstractBridge* active_bridge = activeBridge();
|
||||
if (!active_bridge || !active_bridge->isRunning()) return;
|
||||
#ifdef WITH_WEBCONFIG
|
||||
if (_wc_batch_active) {
|
||||
if (_wc_batch_active) { // coalesced: applied once in onConfigBatchEnd()
|
||||
_wc_restart_pending = true;
|
||||
return;
|
||||
}
|
||||
@@ -755,12 +791,52 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(WITH_MQTT_BRIDGE)
|
||||
// Broadcast a key OTA milestone (start/fail only) on the configured alert
|
||||
// channel, in addition to the Serial log -- so an operator who triggered
|
||||
// `ota update` via remote management still gets feedback that lands well after
|
||||
// the command's reply window. Respects the `alert on/off` master switch and
|
||||
// rides the configured alert scope (sendChannel -> resolveAlertScope); a no-op
|
||||
// when alerts are off or no channel is set. Deliberately NOT wired to routine
|
||||
// slot connect/disconnect -- those remain in AlertReporter's fault logic.
|
||||
void otaAlert(const char* msg) {
|
||||
auto* obs = _cli.getObserverPrefs();
|
||||
if (obs && obs->alert_enabled) _alerter.sendText(msg);
|
||||
}
|
||||
|
||||
// Best-effort flush of the outbound packet queue before an OTA teardown that
|
||||
// blocks the loop until reboot. The START alert (otaAlert) and the CLI reply
|
||||
// are queued fire-and-forget (delay 0 / CLI_REPLY_DELAY_MILLIS); once
|
||||
// setBridgeState(false) + otaFromManifest() run they spin the loop task until
|
||||
// the chip reboots, so anything still in the send queue at that point is
|
||||
// silently lost -- the observed "OTA update starting never arrives" case on a
|
||||
// busy / duty-limited channel where the packet can't win a TX slot inside the
|
||||
// 2.5 s window. Pump the mesh loop so already-queued packets get their airtime,
|
||||
// bounded by timeout_ms so a jammed or budget-exhausted channel can't stall the
|
||||
// update. Respects duty cycle / CAD: it only drains what is queued, it does not
|
||||
// force a transmit. Returns instantly on a healthy node (queue already empty).
|
||||
void drainOutbound(uint32_t timeout_ms) {
|
||||
unsigned long start = millis();
|
||||
while (hasOutbound() || _mgr->getOutboundCount(millis()) > 0) {
|
||||
if (millis() - start >= timeout_ms) break;
|
||||
mesh::Mesh::loop(); // base dispatcher only -- drives RX + checkSend()/TX
|
||||
delay(1); // yield to the radio ISR / other FreeRTOS tasks
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Schedule the pull-OTA flash to run from loop() in ~2.5 s, leaving time for the
|
||||
// "Beginning update..." CLI reply (CLI_REPLY_DELAY_MILLIS = 600 ms) to transmit
|
||||
// before the flash blocks the loop and reboots.
|
||||
bool beginDeferredOtaUpdate() override {
|
||||
_ota_update_at = millis() + 2500;
|
||||
if (_ota_update_at == 0) _ota_update_at = 1; // 0 means "none"
|
||||
#if defined(WITH_MQTT_BRIDGE)
|
||||
// Broadcast START now, while the loop still runs (the 2.5 s reply window):
|
||||
// the deferred flash blocks the loop and, on success, reboots -- so a start
|
||||
// alert queued at fire time could never transmit. See otaAlert().
|
||||
otaAlert("OTA update starting");
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -784,7 +860,7 @@ public:
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
if (!mqtt_bridge || !mqtt_bridge->isRunning()) return false;
|
||||
// Marshal onto the MQTT task (Core 0); this runs on the CLI thread (Core 1).
|
||||
return mqtt_bridge->requestForcedNtpSync();
|
||||
return mqtt_bridge->requestForcedNtpSync(0);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
|
||||
@@ -191,6 +191,15 @@ void UITask::loop() {
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef WITH_WEBCONFIG
|
||||
// While the setup portal is up there's no user button to wake the screen
|
||||
// reliably - keep it on so the join instructions stay visible.
|
||||
if (WebConfigServer::getSetupInfo(NULL, 0, NULL, 0)) {
|
||||
if (!_display->isOn()) _display->turnOn();
|
||||
_auto_off = millis() + AUTO_OFF_MILLIS;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (_display->isOn()) {
|
||||
if (millis() >= _next_refresh) {
|
||||
_display->startFrame();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "MyMesh.h"
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#include <algorithm>
|
||||
#include <helpers/RxReservePacketManager.h>
|
||||
#ifdef WITH_WEBCONFIG
|
||||
#include <WiFi.h>
|
||||
@@ -12,6 +13,8 @@ static uint32_t nextRadioApplyRetryDelay(uint8_t& failure_count) {
|
||||
return delay_ms > 30000UL ? 30000UL : delay_ms;
|
||||
}
|
||||
|
||||
#define ANON_REQ_TYPE_REGIONS 0x01 // client side of the anon-regions scope query (neighbors feature)
|
||||
|
||||
#define REPLY_DELAY_MILLIS 1500
|
||||
#define PUSH_NOTIFY_DELAY_MILLIS 2000
|
||||
#define SYNC_PUSH_INTERVAL 1200
|
||||
@@ -31,6 +34,10 @@ static uint32_t nextRadioApplyRetryDelay(uint8_t& failure_count) {
|
||||
|
||||
#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
|
||||
|
||||
// Best-effort bound for the queued CLI reply before OTA blocks the loop and
|
||||
// reboots. Do not let a busy or duty-limited channel stall the update forever.
|
||||
#define OTA_TX_DRAIN_TIMEOUT_MS 5000
|
||||
|
||||
#define LAZY_CONTACTS_WRITE_DELAY 5000
|
||||
|
||||
struct ServerStats {
|
||||
@@ -499,7 +506,21 @@ void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const m
|
||||
|
||||
int MyMesh::searchPeersByHash(const uint8_t *hash) {
|
||||
int n = 0;
|
||||
for (int i = 0; i < acl.getNumClients(); i++) {
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
if (neighbor_discover_active) {
|
||||
for (int i = 0; i < neighbor_discover_count && n < MAX_CLIENTS; i++) {
|
||||
auto& nb = neighbours[neighbor_discover[i].neighbour_idx];
|
||||
// ACL clients already have a matching peer entry and shared secret. Adding
|
||||
// a second overlay entry would decrypt first and intercept their normal
|
||||
// CLI/request traffic for the duration of discovery.
|
||||
if (acl.getClient(nb.id.pub_key, PUB_KEY_SIZE) != nullptr) continue;
|
||||
if (nb.heard_timestamp > 0 && nb.id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = NEIGHBOR_DISCOVER_PEER_BASE + i;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
for (int i = 0; i < acl.getNumClients() && n < MAX_CLIENTS; i++) {
|
||||
if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
|
||||
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
|
||||
}
|
||||
@@ -509,6 +530,15 @@ int MyMesh::searchPeersByHash(const uint8_t *hash) {
|
||||
|
||||
void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
|
||||
int i = matching_peer_indexes[peer_idx];
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
if (neighbor_discover_active && i >= NEIGHBOR_DISCOVER_PEER_BASE) {
|
||||
int oi = i - NEIGHBOR_DISCOVER_PEER_BASE;
|
||||
if (oi >= 0 && oi < neighbor_discover_count) {
|
||||
self_id.calcSharedSecret(dest_secret, neighbours[neighbor_discover[oi].neighbour_idx].id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (i >= 0 && i < acl.getNumClients()) {
|
||||
// lookup pre-calculated shared_secret
|
||||
memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
|
||||
@@ -520,11 +550,34 @@ void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
|
||||
void MyMesh::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 defined(WITH_MQTT_NEIGHBORS)
|
||||
// Overlay response: a heard neighbour (not an ACL client) answering our
|
||||
// anon-regions scope query. Consume it and stop -- it is not a client packet.
|
||||
if (neighbor_discover_active && i >= NEIGHBOR_DISCOVER_PEER_BASE) {
|
||||
int oi = i - NEIGHBOR_DISCOVER_PEER_BASE;
|
||||
if (type == PAYLOAD_TYPE_RESPONSE && oi >= 0 && oi < neighbor_discover_count) {
|
||||
handleNeighborDiscoverResponse(oi, data, len);
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
|
||||
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
|
||||
return;
|
||||
}
|
||||
auto client = acl.getClientByIdx(i);
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// A neighbour that IS an ACL client resolves to a normal index above, so a
|
||||
// scope-query response from it lands here -- match it against the overlay.
|
||||
if (neighbor_discover_active && type == PAYLOAD_TYPE_RESPONSE) {
|
||||
for (int oi = 0; oi < neighbor_discover_count; oi++) {
|
||||
auto& nb = neighbours[neighbor_discover[oi].neighbour_idx];
|
||||
if (client->id.matches(nb.id) && handleNeighborDiscoverResponse(oi, data, len)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (type == PAYLOAD_TYPE_TXT_MSG && len > 5) { // a CLI command or new Post
|
||||
uint32_t sender_timestamp;
|
||||
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
|
||||
@@ -714,6 +767,107 @@ void MyMesh::onAckRecv(mesh::Packet *packet, uint32_t ack_crc) {
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
|
||||
#define CTL_TYPE_NODE_DISCOVER_REQ 0x80
|
||||
#define CTL_TYPE_NODE_DISCOVER_RESP 0x90
|
||||
|
||||
void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
|
||||
// find existing neighbour, else use least recently updated
|
||||
uint32_t oldest_timestamp = 0xFFFFFFFF;
|
||||
NeighbourInfo *neighbour = &neighbours[0];
|
||||
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
|
||||
// if neighbour already known, we should update it
|
||||
if (id.matches(neighbours[i].id)) {
|
||||
neighbour = &neighbours[i];
|
||||
break;
|
||||
}
|
||||
|
||||
// otherwise we should update the least recently updated neighbour
|
||||
if (neighbours[i].heard_timestamp < oldest_timestamp) {
|
||||
neighbour = &neighbours[i];
|
||||
oldest_timestamp = neighbour->heard_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
// update neighbour info
|
||||
neighbour->id = id;
|
||||
neighbour->advert_timestamp = timestamp;
|
||||
neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
|
||||
neighbour->snr = (int8_t)(snr * 4);
|
||||
}
|
||||
|
||||
static bool isShare(const mesh::Packet *packet) {
|
||||
if (packet->hasTransportCodes()) {
|
||||
return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void MyMesh::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 this a zero hop advert (and not via 'Share'), add it to neighbours
|
||||
if (packet->getPathHashCount() == 0 && !isShare(packet)) {
|
||||
AdvertDataParser parser(app_data, app_data_len);
|
||||
if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
|
||||
putNeighbour(id, timestamp, packet->getSNR());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MyMesh::onControlDataRecv(mesh::Packet* packet) {
|
||||
uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
|
||||
// A room server is ADV_TYPE_ROOM, so it does NOT answer node-discover requests
|
||||
// (those filter for repeaters). It only records repeater responses to its own
|
||||
// discovery, to build the neighbour table.
|
||||
if (type == CTL_TYPE_NODE_DISCOVER_RESP && packet->payload_len >= 6) {
|
||||
uint8_t node_type = packet->payload[0] & 0x0F;
|
||||
if (node_type != ADV_TYPE_REPEATER) {
|
||||
return;
|
||||
}
|
||||
if (packet->payload_len < 6 + PUB_KEY_SIZE) {
|
||||
MESH_DEBUG_PRINTLN("onControlDataRecv: DISCOVER_RESP pubkey too short: %d", (uint32_t)packet->payload_len);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
|
||||
pending_discover_tag = 0;
|
||||
return;
|
||||
}
|
||||
uint32_t tag;
|
||||
memcpy(&tag, &packet->payload[2], 4);
|
||||
if (tag != pending_discover_tag) {
|
||||
return;
|
||||
}
|
||||
|
||||
mesh::Identity id(&packet->payload[6]);
|
||||
if (id.matches(self_id)) {
|
||||
return;
|
||||
}
|
||||
putNeighbour(id, getRTCClock()->getCurrentTime(), packet->getSNR());
|
||||
}
|
||||
}
|
||||
|
||||
void MyMesh::sendNodeDiscoverReq() {
|
||||
uint8_t data[10];
|
||||
data[0] = CTL_TYPE_NODE_DISCOVER_REQ; // prefix_only=0
|
||||
data[1] = (1 << ADV_TYPE_REPEATER);
|
||||
getRNG()->random(&data[2], 4); // tag
|
||||
memcpy(&pending_discover_tag, &data[2], 4);
|
||||
pending_discover_until = futureMillis(60000);
|
||||
uint32_t since = 0;
|
||||
memcpy(&data[6], &since, 4);
|
||||
|
||||
auto pkt = createControlData(data, sizeof(data));
|
||||
if (pkt) {
|
||||
sendZeroHop(pkt);
|
||||
}
|
||||
}
|
||||
|
||||
#endif // WITH_MQTT_NEIGHBORS
|
||||
|
||||
MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
|
||||
mesh::RTCClock &rtc, mesh::MeshTables &tables)
|
||||
: mesh::Mesh(radio, ms, rng, rtc, *createObserverPacketManager(32), tables),
|
||||
@@ -802,6 +956,19 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
|
||||
memset(posts, 0, sizeof(posts));
|
||||
_num_posted = _num_post_pushes = 0;
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
pending_discover_tag = 0;
|
||||
pending_discover_until = 0;
|
||||
neighbor_discover_count = 0;
|
||||
neighbor_discover_active = false;
|
||||
neighbor_table_refresh_active = false;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
neighbor_discover_until = 0;
|
||||
next_neighbors_publish = 0;
|
||||
self_scopes_buf[0] = 0;
|
||||
memset(neighbours, 0, sizeof(neighbours));
|
||||
#endif
|
||||
|
||||
memset(default_scope.key, 0, sizeof(default_scope.key));
|
||||
}
|
||||
|
||||
@@ -1301,6 +1468,65 @@ void MyMesh::buildStatsJson(char* buf, size_t buf_size) {
|
||||
}
|
||||
#endif
|
||||
|
||||
void MyMesh::formatNeighborsReply(char *reply) {
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
char *dp = reply;
|
||||
|
||||
// create copy of neighbours list, skipping empty entries so we can sort it separately from main list
|
||||
int16_t neighbours_count = 0;
|
||||
NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
|
||||
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
|
||||
auto neighbour = &neighbours[i];
|
||||
if (neighbour->heard_timestamp > 0) {
|
||||
sorted_neighbours[neighbours_count] = neighbour;
|
||||
neighbours_count++;
|
||||
}
|
||||
}
|
||||
|
||||
// sort neighbours newest to oldest
|
||||
std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
|
||||
return a->heard_timestamp > b->heard_timestamp; // desc
|
||||
});
|
||||
|
||||
for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
|
||||
NeighbourInfo *neighbour = sorted_neighbours[i];
|
||||
|
||||
// add new line if not first item
|
||||
if (i > 0) *dp++ = '\n';
|
||||
|
||||
char hex[10];
|
||||
// get 4 bytes of neighbour id as hex
|
||||
mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
|
||||
|
||||
// add next neighbour
|
||||
uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
|
||||
sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
|
||||
while (*dp)
|
||||
dp++; // find end of string
|
||||
}
|
||||
if (dp == reply) { // no neighbours, need empty response
|
||||
strcpy(dp, "-none-");
|
||||
dp += 6;
|
||||
}
|
||||
*dp = 0; // null terminator
|
||||
#else
|
||||
strcpy(reply, "not supported");
|
||||
#endif
|
||||
}
|
||||
|
||||
void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
|
||||
NeighbourInfo *neighbour = &neighbours[i];
|
||||
if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
|
||||
neighbours[i] = NeighbourInfo(); // clear neighbour entry
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)pubkey; (void)key_len;
|
||||
#endif
|
||||
}
|
||||
|
||||
void MyMesh::formatStatsReply(char *reply) {
|
||||
StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
|
||||
}
|
||||
@@ -1309,11 +1535,16 @@ void MyMesh::formatRadioStatsReply(char *reply) {
|
||||
StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
|
||||
}
|
||||
|
||||
void MyMesh::formatRadioDiagReply(char *reply) {
|
||||
StatsFormatHelper::formatRadioDiag(reply, _radio, radio_driver, *_ms, _err_flags, hasOutbound());
|
||||
}
|
||||
|
||||
void MyMesh::formatPacketStatsReply(char *reply) {
|
||||
StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
|
||||
getNumRecvFlood(), getNumRecvDirect());
|
||||
}
|
||||
|
||||
|
||||
void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply) {
|
||||
if (region_load_active) {
|
||||
if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
|
||||
@@ -1404,6 +1635,45 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
|
||||
Serial.printf("\n");
|
||||
}
|
||||
reply[0] = 0;
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
} else if (memcmp(command, "discover.neighbors", 18) == 0) {
|
||||
const char* sub = command + 18;
|
||||
while (*sub == ' ') sub++;
|
||||
if (*sub != 0) {
|
||||
strcpy(reply, "Err - discover.neighbors has no options");
|
||||
} else {
|
||||
sendNodeDiscoverReq();
|
||||
strcpy(reply, "OK - Discover sent");
|
||||
}
|
||||
} else if (memcmp(command, "discover.scopes", 15) == 0) {
|
||||
const char* sub = command + 15;
|
||||
while (*sub == ' ') sub++;
|
||||
if (*sub != 0) {
|
||||
strcpy(reply, "Err - discover.scopes has no options");
|
||||
} else if (pending_discover_tag != 0 &&
|
||||
!millisHasNowPassed(pending_discover_until) &&
|
||||
!neighbor_discover_active) {
|
||||
// A zero-hop table refresh is already collecting; queue the scope pass
|
||||
// behind it (as a manual, non-periodic request) rather than starting a
|
||||
// second refresh.
|
||||
if (!neighborDiscoverReady(reply)) {
|
||||
// reply already set by neighborDiscoverReady
|
||||
} else {
|
||||
neighbor_table_refresh_active = true;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
long remaining_ms = (long)(pending_discover_until - futureMillis(0));
|
||||
unsigned remaining_secs = remaining_ms > 0
|
||||
? (unsigned)(((unsigned long)remaining_ms + 999UL) / 1000UL) : 0;
|
||||
sprintf(reply, "OK - scopes queued (%us discovery remaining)", remaining_secs);
|
||||
MESH_DEBUG_PRINTLN("Neighbor scopes queued behind active discovery (%us remaining)", remaining_secs);
|
||||
}
|
||||
} else if (!startNeighborDiscover(reply)) {
|
||||
// reply already set by startNeighborDiscover
|
||||
}
|
||||
#elif defined(WITH_MQTT_BRIDGE)
|
||||
} else if (memcmp(command, "discover.scopes", 15) == 0) {
|
||||
strcpy(reply, "Err - not supported (requires PSRAM)");
|
||||
#endif
|
||||
} else{
|
||||
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
|
||||
}
|
||||
@@ -1559,6 +1829,44 @@ void MyMesh::loop() {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(WITH_MQTT_BRIDGE) && defined(OTA_MANIFEST_BASE)
|
||||
if (_ota_update_at && millisHasNowPassed(_ota_update_at)) { // deferred `ota update`
|
||||
_ota_update_at = 0; // clear timer
|
||||
// The "Beginning update..." reply has now been queued. Flush it before OTA
|
||||
// blocks the loop until reboot, then free a running bridge for heap headroom.
|
||||
// Remember its state: an OTA request must not enable MQTT that an operator
|
||||
// had deliberately stopped.
|
||||
Serial.println("OTA: starting update");
|
||||
const bool bridge_was_running = bridge && bridge->isRunning();
|
||||
drainOutbound(OTA_TX_DRAIN_TIMEOUT_MS);
|
||||
|
||||
bool may_flash = true;
|
||||
if (bridge_was_running) {
|
||||
setBridgeState(false);
|
||||
// OTA must not write after a forced/timed-out MQTT shutdown: its TLS/heap
|
||||
// ownership is uncertain until a subsequent clean start/stop cycle.
|
||||
may_flash = bridge && bridge->canFlashAfterStop();
|
||||
if (!may_flash) {
|
||||
Serial.println("OTA: aborted, MQTT stop did not complete cleanly");
|
||||
}
|
||||
}
|
||||
|
||||
char ota_reply[160];
|
||||
if (may_flash && !_cli.getBoard()->otaFromManifest(getFirmwareVer(), false, ota_reply)) {
|
||||
Serial.print("OTA: aborted - "); Serial.println(ota_reply);
|
||||
may_flash = false;
|
||||
}
|
||||
|
||||
// Successful otaFromManifest() reboots and never returns. Restore only a
|
||||
// bridge that was running before this attempt; leave an intentionally
|
||||
// stopped bridge stopped after any OTA refusal or download failure.
|
||||
if (!may_flash && bridge_was_running) {
|
||||
Serial.println("OTA: resuming bridge");
|
||||
setBridgeState(true);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// is pending dirty contacts write needed?
|
||||
if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
|
||||
acl.save(_fs, MyMesh::saveFilter);
|
||||
@@ -1575,6 +1883,85 @@ void MyMesh::loop() {
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
_alerter.onLoop(now);
|
||||
#endif
|
||||
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
// Two-stage periodic neighbors publication:
|
||||
// stage 1 - zero-hop node-discover refreshes the neighbour table (60s window)
|
||||
// stage 2 - anon-regions scope query per neighbour (startNeighborDiscover)
|
||||
// then the table JSON is published and the next cycle is rescheduled.
|
||||
bool periodic_neighbors_enabled = _cli.getObserverPrefs()->mqtt_neighbors_enabled;
|
||||
if (neighbor_discover_active) {
|
||||
loopNeighborDiscover();
|
||||
} else if (neighbor_table_refresh_active) {
|
||||
if (neighbor_table_refresh_periodic && !periodic_neighbors_enabled) {
|
||||
// periodic switched off mid-refresh -> cancel (leave pending_discover_tag alone)
|
||||
neighbor_table_refresh_active = false;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
next_neighbors_publish = 0;
|
||||
} else if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
|
||||
// 60s zero-hop window done -> begin the per-neighbour scope queries
|
||||
bool was_periodic = neighbor_table_refresh_periodic;
|
||||
pending_discover_tag = 0;
|
||||
neighbor_table_refresh_active = false;
|
||||
neighbor_table_refresh_periodic = false;
|
||||
char tmp_reply[80];
|
||||
const char* origin_str = was_periodic ? "periodic" : "manual";
|
||||
if (startNeighborDiscover(tmp_reply)) {
|
||||
MESH_DEBUG_PRINTLN("MQTT %s %s", origin_str, tmp_reply);
|
||||
} else {
|
||||
if (periodic_neighbors_enabled) {
|
||||
next_neighbors_publish = futureMillis(_cli.getObserverPrefs()->mqtt_neighbors_interval);
|
||||
}
|
||||
MESH_DEBUG_PRINTLN("MQTT %s neighbor scope discovery failed: %s", origin_str, tmp_reply);
|
||||
}
|
||||
}
|
||||
} else if (periodic_neighbors_enabled && bridge && bridge->isRunning()) {
|
||||
if (next_neighbors_publish == 0 ||
|
||||
(next_neighbors_publish != 0 && millisHasNowPassed(next_neighbors_publish))) {
|
||||
if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
|
||||
pending_discover_tag = 0;
|
||||
sendNodeDiscoverReq();
|
||||
MESH_DEBUG_PRINTLN("MQTT periodic neighbor table refresh started");
|
||||
} else {
|
||||
MESH_DEBUG_PRINTLN("MQTT periodic refresh joined active neighbor discovery");
|
||||
}
|
||||
neighbor_table_refresh_active = true;
|
||||
neighbor_table_refresh_periodic = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Report the schedule state back to the bridge for `get mqtt.status`.
|
||||
if (bridge) {
|
||||
if (neighbor_discover_active || neighbor_table_refresh_active) {
|
||||
bridge->setNeighborsSchedule(MQTTBridge::NBR_ACTIVE, 0);
|
||||
} else if (next_neighbors_publish == 0 || millisHasNowPassed(next_neighbors_publish)) {
|
||||
bridge->setNeighborsSchedule(MQTTBridge::NBR_DUE, 0);
|
||||
} else {
|
||||
long remaining_ms = (long)(next_neighbors_publish - futureMillis(0));
|
||||
uint32_t remaining_secs = remaining_ms > 0 ? (uint32_t)(remaining_ms / 1000) : 0;
|
||||
bridge->setNeighborsSchedule(MQTTBridge::NBR_SCHEDULED, remaining_secs);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef WITH_SNMP
|
||||
// Push radio stats to SNMP agent every 2 seconds
|
||||
if (_snmp_agent.isRunning()) {
|
||||
static unsigned long last_snmp_stats = 0;
|
||||
if (now - last_snmp_stats >= 2000) {
|
||||
last_snmp_stats = now;
|
||||
_snmp_agent.updateRadioStats(
|
||||
radio_driver.getPacketsRecv(), radio_driver.getPacketsSent(),
|
||||
radio_driver.getPacketsRecvErrors(),
|
||||
(int16_t)_radio->getNoiseFloor(),
|
||||
(int16_t)radio_driver.getLastRSSI(),
|
||||
(int16_t)(radio_driver.getLastSNR() * 4),
|
||||
getNumSentFlood(), getNumSentDirect(),
|
||||
getNumRecvFlood(), getNumRecvDirect(),
|
||||
getTotalAirTime() / 1000, uptime_millis / 1000);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool MyMesh::isMillisTimerDue(unsigned long timestamp) const {
|
||||
@@ -1642,3 +2029,254 @@ bool MyMesh::hasPendingWork() const {
|
||||
|| (saved_radio_apply_pending && !temp_radio_applied))) return true;
|
||||
return isMillisTimerDue(dirty_contacts_expiry);
|
||||
}
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
#include "helpers/MQTTMessageBuilder.h"
|
||||
#if defined(ESP_PLATFORM)
|
||||
#include <esp_heap_caps.h>
|
||||
#endif
|
||||
|
||||
// This node's own non-flood scope names, same source the anon-regions server
|
||||
// reply uses. Empty string when the node has no scoped regions.
|
||||
void MyMesh::getLocalScopes(char* buf, size_t len) {
|
||||
if (!buf || len == 0) return;
|
||||
buf[0] = 0;
|
||||
region_map.exportNamesTo(buf, (int)len, REGION_DENY_FLOOD);
|
||||
}
|
||||
|
||||
// Client side of the anon-regions request (the server side is handleAnonRegionsReq).
|
||||
// Inner payload: {tag(4)}{ANON_REQ_TYPE_REGIONS}{0x00 = zero-hop reply path}.
|
||||
bool MyMesh::sendAnonRegionsReq(const mesh::Identity& target, uint32_t& tag) {
|
||||
uint8_t secret[PUB_KEY_SIZE];
|
||||
self_id.calcSharedSecret(secret, target);
|
||||
|
||||
tag = getRTCClock()->getCurrentTimeUnique();
|
||||
uint8_t inner[6];
|
||||
memcpy(inner, &tag, 4);
|
||||
inner[4] = ANON_REQ_TYPE_REGIONS;
|
||||
inner[5] = 0x00; // request a zero-hop reply path
|
||||
|
||||
mesh::Packet* pkt = createAnonDatagram(PAYLOAD_TYPE_ANON_REQ, self_id, target, secret, inner, sizeof(inner));
|
||||
if (!pkt) return false;
|
||||
sendDirect(pkt, NULL, 0, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Match a RESPONSE against the pending overlay entry by tag; copy its scope
|
||||
// string (payload after the 8-byte {tag}{clock} header) into the entry.
|
||||
bool MyMesh::handleNeighborDiscoverResponse(int overlay_idx, const uint8_t* data, size_t len) {
|
||||
if (overlay_idx < 0 || overlay_idx >= neighbor_discover_count) return false;
|
||||
NeighborDiscoverEntry& entry = neighbor_discover[overlay_idx];
|
||||
if (entry.status != ND_PENDING || len < 8) return false;
|
||||
|
||||
uint32_t tag;
|
||||
memcpy(&tag, data, 4);
|
||||
if (tag != entry.tag) return false;
|
||||
|
||||
size_t scope_len = len - 8;
|
||||
if (scope_len >= sizeof(entry.scopes)) {
|
||||
scope_len = sizeof(entry.scopes) - 1;
|
||||
}
|
||||
memcpy(entry.scopes, &data[8], scope_len);
|
||||
entry.scopes[scope_len] = 0;
|
||||
entry.status = ND_RESPONDED;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Publish-ordering: most recently heard first, then stronger SNR, then pubkey.
|
||||
// The JSON builder drops the tail if the buffer fills, so the head must be the
|
||||
// most useful entries.
|
||||
static bool neighborPublishEntryComesBefore(
|
||||
const MQTTMessageBuilder::NeighborsMessageEntry& lhs,
|
||||
const MQTTMessageBuilder::NeighborsMessageEntry& rhs) {
|
||||
if (lhs.heard_secs_ago != rhs.heard_secs_ago) {
|
||||
return lhs.heard_secs_ago < rhs.heard_secs_ago; // newer first
|
||||
}
|
||||
if (lhs.snr != rhs.snr) {
|
||||
return lhs.snr > rhs.snr; // stronger first when equally recent
|
||||
}
|
||||
return strcmp(lhs.pubkey_hex, rhs.pubkey_hex) < 0;
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
// ArduinoJson v7 JsonDocument has no real capacity cap (DynamicJsonDocument(N)
|
||||
// is a no-op shim). Keep the pool off internal DRAM and soft-cap peak growth to
|
||||
// the publish buffer size. used only rises on allocate -- conservative for this
|
||||
// single-shot doc (overflow path removes+breaks, so no further growth after free).
|
||||
struct NeighborsDocAllocator : ArduinoJson::Allocator {
|
||||
size_t used = 0;
|
||||
static const size_t kBudget = MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE;
|
||||
|
||||
void* allocate(size_t size) override {
|
||||
if (used >= kBudget || size > kBudget - used) return nullptr;
|
||||
void* p = heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (p) used += size;
|
||||
return p;
|
||||
}
|
||||
|
||||
void deallocate(void* ptr) override {
|
||||
heap_caps_free(ptr);
|
||||
}
|
||||
|
||||
void* reallocate(void* ptr, size_t new_size) override {
|
||||
size_t old_size = ptr ? heap_caps_get_allocated_size(ptr) : 0;
|
||||
size_t next_used = (used >= old_size) ? (used - old_size) : 0;
|
||||
if (next_used >= kBudget || new_size > kBudget - next_used) return nullptr;
|
||||
void* p = heap_caps_realloc(ptr, new_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
if (p) used = next_used + new_size;
|
||||
return p;
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
// Build the neighbors-table JSON and hand it to the bridge, then reschedule.
|
||||
void MyMesh::finishNeighborDiscover() {
|
||||
getLocalScopes(self_scopes_buf, sizeof(self_scopes_buf));
|
||||
|
||||
char self_pubkey_hex[65];
|
||||
mesh::Utils::toHex(self_pubkey_hex, self_id.pub_key, PUB_KEY_SIZE);
|
||||
|
||||
char origin[32];
|
||||
MQTTBridge::getEffectiveMqttOrigin(_prefs.node_name, _cli.getObserverPrefs(), origin, sizeof(origin));
|
||||
|
||||
char timestamp[40];
|
||||
MQTTMessageBuilder::formatIsoTimestampForMqtt(getRTCClock()->getCurrentTime(), 0, nullptr, timestamp, sizeof(timestamp));
|
||||
|
||||
char pubkey_hex[MAX_NEIGHBOURS][65];
|
||||
MQTTMessageBuilder::NeighborsMessageEntry entries[MAX_NEIGHBOURS];
|
||||
uint32_t now_secs = getRTCClock()->getCurrentTime();
|
||||
|
||||
for (int i = 0; i < neighbor_discover_count; i++) {
|
||||
auto& nb = neighbours[neighbor_discover[i].neighbour_idx];
|
||||
mesh::Utils::toHex(pubkey_hex[i], nb.id.pub_key, PUB_KEY_SIZE);
|
||||
entries[i].pubkey_hex = pubkey_hex[i];
|
||||
entries[i].snr = nb.snr / 4.0f;
|
||||
entries[i].heard_secs_ago = (nb.heard_timestamp > 0 && now_secs >= nb.heard_timestamp)
|
||||
? (now_secs - nb.heard_timestamp) : 0;
|
||||
entries[i].scopes = neighbor_discover[i].scopes;
|
||||
switch (neighbor_discover[i].status) {
|
||||
case ND_RESPONDED: entries[i].status = "responded"; break;
|
||||
case ND_SEND_FAILED: entries[i].status = "send_failed"; break;
|
||||
default: entries[i].status = "timeout"; break;
|
||||
}
|
||||
}
|
||||
|
||||
// insertion sort: most useful first (JSON builder drops the tail on overflow)
|
||||
for (int i = 1; i < neighbor_discover_count; i++) {
|
||||
MQTTMessageBuilder::NeighborsMessageEntry entry = entries[i];
|
||||
int j = i;
|
||||
while (j > 0 && neighborPublishEntryComesBefore(entry, entries[j - 1])) {
|
||||
entries[j] = entries[j - 1];
|
||||
j--;
|
||||
}
|
||||
entries[j] = entry;
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
char* json_buf = (char*)heap_caps_malloc(MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE, MALLOC_CAP_SPIRAM);
|
||||
#else
|
||||
char* json_buf = (char*)malloc(MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE);
|
||||
#endif
|
||||
if (!json_buf) {
|
||||
neighbor_discover_active = false;
|
||||
neighbor_discover_count = 0;
|
||||
if (_cli.getObserverPrefs()->mqtt_neighbors_enabled) {
|
||||
next_neighbors_publish = futureMillis(_cli.getObserverPrefs()->mqtt_neighbors_interval);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
NeighborsDocAllocator doc_alloc;
|
||||
JsonDocument doc(&doc_alloc);
|
||||
#else
|
||||
JsonDocument doc;
|
||||
#endif
|
||||
int json_len = MQTTMessageBuilder::buildNeighborsMessage(
|
||||
doc, origin, self_pubkey_hex, timestamp, self_scopes_buf,
|
||||
entries, neighbor_discover_count,
|
||||
json_buf, MQTTBridge::NEIGHBORS_JSON_BUFFER_SIZE);
|
||||
|
||||
if (json_len > 0 && bridge) {
|
||||
bridge->requestPublishNeighbors(json_buf, (size_t)json_len);
|
||||
}
|
||||
|
||||
#if defined(ESP_PLATFORM)
|
||||
heap_caps_free(json_buf);
|
||||
#else
|
||||
free(json_buf);
|
||||
#endif
|
||||
|
||||
neighbor_discover_active = false;
|
||||
neighbor_discover_count = 0;
|
||||
if (_cli.getObserverPrefs()->mqtt_neighbors_enabled) {
|
||||
next_neighbors_publish = futureMillis(_cli.getObserverPrefs()->mqtt_neighbors_interval);
|
||||
}
|
||||
}
|
||||
|
||||
// Advance the scope-query phase; publish once all entries resolve or the window
|
||||
// times out (stragglers marked ND_TIMEOUT).
|
||||
void MyMesh::loopNeighborDiscover() {
|
||||
if (!neighbor_discover_active) return;
|
||||
|
||||
bool all_done = true;
|
||||
for (int i = 0; i < neighbor_discover_count; i++) {
|
||||
if (neighbor_discover[i].status == ND_PENDING) { all_done = false; break; }
|
||||
}
|
||||
if (!all_done && !millisHasNowPassed(neighbor_discover_until)) return;
|
||||
if (!all_done) {
|
||||
for (int i = 0; i < neighbor_discover_count; i++) {
|
||||
if (neighbor_discover[i].status == ND_PENDING) neighbor_discover[i].status = ND_TIMEOUT;
|
||||
}
|
||||
}
|
||||
finishNeighborDiscover();
|
||||
}
|
||||
|
||||
// Shared precondition for starting a discovery: PSRAM present + bridge running.
|
||||
bool MyMesh::neighborDiscoverReady(char* reply) {
|
||||
#if defined(ESP_PLATFORM)
|
||||
if (!psramFound()) { strcpy(reply, "Err - PSRAM not available"); return false; }
|
||||
#endif
|
||||
if (!bridge || !bridge->isRunning()) { strcpy(reply, "Err - MQTT bridge not running"); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
// Snapshot the neighbor table into the overlay and fire one anon-regions query
|
||||
// per heard neighbour; arm the 30s scope-query window.
|
||||
bool MyMesh::startNeighborDiscover(char* reply) {
|
||||
if (neighbor_discover_active) {
|
||||
strcpy(reply, "Err - neighbor discover already active");
|
||||
return false;
|
||||
}
|
||||
if (!neighborDiscoverReady(reply)) {
|
||||
return false; // reply already set
|
||||
}
|
||||
|
||||
getLocalScopes(self_scopes_buf, sizeof(self_scopes_buf));
|
||||
neighbor_discover_count = 0;
|
||||
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
|
||||
if (neighbours[i].heard_timestamp > 0) {
|
||||
neighbor_discover[neighbor_discover_count].neighbour_idx = (uint8_t)i;
|
||||
neighbor_discover[neighbor_discover_count].scopes[0] = 0;
|
||||
neighbor_discover[neighbor_discover_count].status = ND_PENDING;
|
||||
uint32_t tag;
|
||||
if (sendAnonRegionsReq(neighbours[i].id, tag)) {
|
||||
neighbor_discover[neighbor_discover_count].tag = tag;
|
||||
} else {
|
||||
neighbor_discover[neighbor_discover_count].status = ND_SEND_FAILED;
|
||||
}
|
||||
neighbor_discover_count++;
|
||||
}
|
||||
}
|
||||
|
||||
neighbor_discover_active = true;
|
||||
neighbor_discover_until = futureMillis(NEIGHBOR_DISCOVER_TIMEOUT_MS);
|
||||
|
||||
if (neighbor_discover_count == 0) {
|
||||
finishNeighborDiscover();
|
||||
strcpy(reply, "OK - neighbor discover started (0 neighbors, self only)");
|
||||
} else {
|
||||
sprintf(reply, "OK - neighbor discover started (%u neighbors)", (unsigned)neighbor_discover_count);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif // WITH_MQTT_NEIGHBORS
|
||||
@@ -28,6 +28,11 @@
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
#include "helpers/bridges/MQTTBridge.h"
|
||||
#define WITH_BRIDGE
|
||||
#include "helpers/esp32/WebConfigServer.h" // defines WITH_WEBCONFIG on ESP32
|
||||
#endif
|
||||
|
||||
#ifdef WITH_SNMP
|
||||
#include "helpers/SNMPAgent.h"
|
||||
#endif
|
||||
|
||||
|
||||
@@ -99,6 +104,13 @@ struct PostInfo {
|
||||
char text[MAX_POST_TEXT_LEN+1];
|
||||
};
|
||||
|
||||
struct NeighbourInfo {
|
||||
mesh::Identity id;
|
||||
uint32_t advert_timestamp;
|
||||
uint32_t heard_timestamp;
|
||||
int8_t snr; // multiplied by 4, user should divide to get float value
|
||||
};
|
||||
|
||||
class MyMesh : public mesh::Mesh, public CommonCLICallbacks
|
||||
#ifdef WITH_WEBCONFIG
|
||||
, public WebConfigServer::Callbacks
|
||||
@@ -127,6 +139,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
|
||||
RegionEntry* recv_pkt_region;
|
||||
TransportKey default_scope;
|
||||
unsigned long set_radio_at, revert_radio_at;
|
||||
unsigned long _ota_update_at = 0; // deferred `ota update` fire time (0 = none scheduled)
|
||||
float pending_freq;
|
||||
float pending_bw;
|
||||
uint8_t pending_sf;
|
||||
@@ -137,9 +150,49 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
|
||||
unsigned long radio_apply_retry_at;
|
||||
uint8_t radio_apply_failures;
|
||||
int matching_peer_indexes[MAX_CLIENTS];
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
NeighbourInfo neighbours[MAX_NEIGHBOURS];
|
||||
uint32_t pending_discover_tag;
|
||||
unsigned long pending_discover_until;
|
||||
enum NeighborDiscoverStatus : uint8_t {
|
||||
ND_PENDING = 1,
|
||||
ND_RESPONDED = 2,
|
||||
ND_TIMEOUT = 3,
|
||||
ND_SEND_FAILED = 4,
|
||||
};
|
||||
struct NeighborDiscoverEntry {
|
||||
uint8_t neighbour_idx;
|
||||
uint32_t tag;
|
||||
char scopes[96];
|
||||
uint8_t status;
|
||||
};
|
||||
NeighborDiscoverEntry neighbor_discover[MAX_NEIGHBOURS];
|
||||
uint8_t neighbor_discover_count;
|
||||
bool neighbor_discover_active;
|
||||
bool neighbor_table_refresh_active;
|
||||
bool neighbor_table_refresh_periodic;
|
||||
unsigned long neighbor_discover_until;
|
||||
unsigned long next_neighbors_publish;
|
||||
char self_scopes_buf[96];
|
||||
|
||||
void putNeighbour(const mesh::Identity& id, uint32_t timestamp, float snr);
|
||||
void sendNodeDiscoverReq();
|
||||
bool sendAnonRegionsReq(const mesh::Identity& target, uint32_t& tag);
|
||||
bool neighborDiscoverReady(char* reply);
|
||||
bool startNeighborDiscover(char* reply);
|
||||
void loopNeighborDiscover();
|
||||
void finishNeighborDiscover();
|
||||
bool handleNeighborDiscoverResponse(int overlay_idx, const uint8_t* data, size_t len);
|
||||
void getLocalScopes(char* buf, size_t len);
|
||||
static const int NEIGHBOR_DISCOVER_PEER_BASE = 1000;
|
||||
static const unsigned long NEIGHBOR_DISCOVER_TIMEOUT_MS = 30000;
|
||||
#endif
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
MQTTBridge* bridge;
|
||||
#endif
|
||||
#ifdef WITH_SNMP
|
||||
MeshSNMPAgent _snmp_agent;
|
||||
#endif
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
AlertReporter _alerter;
|
||||
#endif
|
||||
@@ -193,9 +246,6 @@ protected:
|
||||
int getInterferenceThreshold() const override {
|
||||
return _prefs.interference_threshold;
|
||||
}
|
||||
bool getCADEnabled() const override {
|
||||
return _prefs.cad_enabled;
|
||||
}
|
||||
int getAGCResetInterval() const override {
|
||||
return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds
|
||||
}
|
||||
@@ -215,6 +265,10 @@ protected:
|
||||
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;
|
||||
void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override;
|
||||
#if defined(WITH_MQTT_NEIGHBORS)
|
||||
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override;
|
||||
void onControlDataRecv(mesh::Packet* packet) override;
|
||||
#endif
|
||||
|
||||
#if ENV_INCLUDE_GPS == 1
|
||||
void applyGpsPrefs() {
|
||||
@@ -269,11 +323,11 @@ public:
|
||||
void getRxPsWatchdogCounts(uint32_t* soft, uint32_t* hard) override;
|
||||
bool setRxBoostedGain(bool enable) override;
|
||||
|
||||
void formatNeighborsReply(char *reply) override {
|
||||
strcpy(reply, "not supported");
|
||||
}
|
||||
void formatNeighborsReply(char *reply) override;
|
||||
void removeNeighbor(const uint8_t* pubkey, int key_len) override;
|
||||
void formatStatsReply(char *reply) override;
|
||||
void formatRadioStatsReply(char *reply) override;
|
||||
void formatRadioDiagReply(char *reply) override;
|
||||
void formatPacketStatsReply(char *reply) override;
|
||||
void startRegionsLoad() override;
|
||||
bool saveRegions() override;
|
||||
@@ -317,6 +371,13 @@ public:
|
||||
bridge->setBuildDate(getBuildDate());
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
bridge->setStatsSources(this, _radio, _cli.getBoard(), _ms);
|
||||
#ifdef WITH_SNMP
|
||||
if (_cli.getObserverPrefs()->snmp_enabled) {
|
||||
_snmp_agent.setNodeName(_prefs.node_name);
|
||||
_snmp_agent.setFirmwareVersion(getFirmwareVer());
|
||||
bridge->setSNMPAgent(&_snmp_agent);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
bridge->begin();
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
@@ -335,7 +396,7 @@ public:
|
||||
void restartBridge() override {
|
||||
if (!bridge || !bridge->isRunning()) return;
|
||||
#ifdef WITH_WEBCONFIG
|
||||
if (_wc_batch_active) {
|
||||
if (_wc_batch_active) { // coalesced: applied once in onConfigBatchEnd()
|
||||
_wc_restart_pending = true;
|
||||
return;
|
||||
}
|
||||
@@ -369,6 +430,29 @@ public:
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(WITH_MQTT_BRIDGE)
|
||||
// Pump already-queued mesh traffic before OTA blocks the loop and reboots.
|
||||
// This is deliberately bounded: a jammed or duty-limited channel must not
|
||||
// prevent an update, and Mesh::loop() continues to respect TX constraints.
|
||||
void drainOutbound(uint32_t timeout_ms) {
|
||||
unsigned long start = millis();
|
||||
while (hasOutbound() || _mgr->getOutboundCount(millis()) > 0) {
|
||||
if (millis() - start >= timeout_ms) break;
|
||||
mesh::Mesh::loop();
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Schedule the pull-OTA flash to run from loop() in ~2.5 s, leaving time for the
|
||||
// "Beginning update..." CLI reply (CLI_REPLY_DELAY_MILLIS = 600 ms) to transmit
|
||||
// before the flash blocks the loop and reboots.
|
||||
bool beginDeferredOtaUpdate() override {
|
||||
_ota_update_at = millis() + 2500;
|
||||
if (_ota_update_at == 0) _ota_update_at = 1; // 0 means "none"
|
||||
return true;
|
||||
}
|
||||
|
||||
int getQueueSize() override {
|
||||
return bridge ? bridge->getQueueSize() : 0;
|
||||
}
|
||||
@@ -379,8 +463,11 @@ public:
|
||||
|
||||
bool syncMqttNtp() override {
|
||||
if (!bridge || !bridge->isRunning()) return false;
|
||||
// Marshal onto the MQTT task (Core 0); this runs on the CLI thread (Core 1).
|
||||
return bridge->requestForcedNtpSync();
|
||||
// Queue the sync onto the MQTT task (Core 0) without blocking: this runs on
|
||||
// the Arduino loop task (serial CLI and the web config batch both drain
|
||||
// here), and blocking up to 30 s would stall mesh/radio forwarding. Returns
|
||||
// true once queued; verify with `get mqtt.ntp.diag`.
|
||||
return bridge->requestForcedNtpSync(0);
|
||||
}
|
||||
|
||||
bool runMqttNtpDiag(char* reply, size_t reply_size, bool verbose) override {
|
||||
|
||||
Reference in new issue
Block a user