@alteriom/painlessmesh 1.7.5 → 1.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/README.md +92 -6
  3. package/RELEASE_GUIDE.md +36 -0
  4. package/docs/MQTT_BRIDGE_COMMANDS.md +10 -10
  5. package/docs/MQTT_BRIDGE_IMPLEMENTATION_SUMMARY.md +1 -1
  6. package/docs/MQTT_SCHEMA_COMPLIANCE.md +57 -2
  7. package/docs/PHASE1_GUIDE.md +1 -1
  8. package/docs/alteriom/overview.md +2 -2
  9. package/docs/architecture/plugin-system.md +1 -1
  10. package/docs/archive/RELEASE_SUMMARY.md +1 -1
  11. package/docs/releases/RELEASE_CHECKLIST_v1.7.5.md +315 -0
  12. package/docs/releases/RELEASE_CHECKLIST_v1.7.6.md +389 -0
  13. package/docs/releases/RELEASE_PLAN_v1.7.6.md +816 -0
  14. package/docs/releases/RELEASE_SUMMARY_v1.7.6.md +436 -0
  15. package/docs/releases/RELEASE_SUMMARY_v1.7.7.md +391 -0
  16. package/docs/troubleshooting/PAINLESSMESH_V1.7.4_COMPILATION_ISSUES.md +547 -0
  17. package/docs/v1.7.7_MQTT_IMPROVEMENTS.md +776 -0
  18. package/docs/wiki/API-Reference.md +2 -2
  19. package/docs/wiki/Complete-Documentation.md +1 -1
  20. package/examples/alteriom/README.md +137 -3
  21. package/examples/alteriom/alteriom.ino +1 -1
  22. package/examples/alteriom/alteriom_sensor_package.hpp +557 -2
  23. package/examples/alteriomImproved/alteriom_sensor_package.hpp +1 -1
  24. package/examples/alteriomImproved/improved_sensor_node.ino +1 -1
  25. package/examples/alteriomMetricsHealth/alteriom_sensor_package.hpp +796 -0
  26. package/examples/alteriomMetricsHealth/metrics_health_node.ino +418 -0
  27. package/examples/alteriomMetricsHealth/platformio.ini +26 -0
  28. package/examples/alteriomPhase1/alteriom_sensor_package.hpp +1 -1
  29. package/examples/alteriomPhase1/phase1_features.ino +2 -2
  30. package/examples/alteriomPhase2/alteriom_sensor_package.hpp +1 -1
  31. package/examples/alteriomSensorNode/alteriom_sensor_node.ino +1 -1
  32. package/examples/alteriomSensorNode/alteriom_sensor_package.hpp +1 -1
  33. package/examples/bridge/enhanced_mqtt_bridge.hpp +610 -0
  34. package/examples/bridge/enhanced_mqtt_bridge_example.ino +226 -0
  35. package/examples/meshCommandNode/alteriom_sensor_package.hpp +1 -1
  36. package/examples/mqttCommandBridge/alteriom_sensor_package.hpp +1 -1
  37. package/examples/mqttTopologyTest/mqttTopologyTest.ino +5 -1
  38. package/library.json +1 -1
  39. package/library.properties +1 -1
  40. package/package.json +2 -2
  41. package/src/painlessmesh/mesh.hpp +0 -11
  42. package/src/painlessmesh/scheduler_queue.cpp +0 -77
  43. package/src/painlessmesh/scheduler_queue.hpp +0 -34
@@ -0,0 +1,776 @@
1
+ # Version 1.7.7 - Enhanced MQTT Communication for Metrics & Health Monitoring
2
+
3
+ ## Overview
4
+
5
+ Version 1.7.7 introduces two new specialized packages designed to enhance MQTT communication efficiency for monitoring mesh networks. These packages provide comprehensive visibility into system performance, proactive problem detection, and predictive maintenance capabilities.
6
+
7
+ ## New Package Types
8
+
9
+ ### MetricsPackage (Type 204)
10
+
11
+ A comprehensive performance metrics package designed for real-time dashboards, capacity planning, and network optimization.
12
+
13
+ #### Purpose
14
+
15
+ - **Real-time Monitoring** - Track system performance in real-time
16
+ - **Capacity Planning** - Identify bottlenecks and plan upgrades
17
+ - **Performance Optimization** - Analyze and improve system efficiency
18
+ - **Troubleshooting** - Diagnose performance issues quickly
19
+
20
+ #### Key Metrics Categories
21
+
22
+ **CPU and Processing:**
23
+ - `cpuUsage` (uint8_t) - CPU usage percentage (0-100)
24
+ - `loopIterations` (uint32_t) - Loop iterations per second
25
+ - `taskQueueSize` (uint16_t) - Number of pending tasks
26
+
27
+ **Memory Metrics:**
28
+ - `freeHeap` (uint32_t) - Current free heap memory in bytes
29
+ - `minFreeHeap` (uint32_t) - Minimum free heap since boot
30
+ - `heapFragmentation` (uint32_t) - Heap fragmentation percentage
31
+ - `maxAllocHeap` (uint32_t) - Largest allocatable block
32
+
33
+ **Network Performance:**
34
+ - `bytesReceived` (uint32_t) - Total bytes received
35
+ - `bytesSent` (uint32_t) - Total bytes sent
36
+ - `packetsReceived` (uint16_t) - Total packets received
37
+ - `packetsSent` (uint16_t) - Total packets sent
38
+ - `packetsDropped` (uint16_t) - Packets dropped
39
+ - `currentThroughput` (uint16_t) - Current throughput in bytes/sec
40
+
41
+ **Timing and Latency:**
42
+ - `avgResponseTime` (uint32_t) - Average response time in microseconds
43
+ - `maxResponseTime` (uint32_t) - Maximum response time in microseconds
44
+ - `avgMeshLatency` (uint16_t) - Average mesh latency in milliseconds
45
+
46
+ **Connection Quality:**
47
+ - `connectionQuality` (uint8_t) - Overall connection quality score (0-100)
48
+ - `wifiRSSI` (int8_t) - WiFi RSSI in dBm
49
+
50
+ **Metadata:**
51
+ - `collectionTimestamp` (uint32_t) - When metrics were collected
52
+ - `collectionInterval` (uint32_t) - Interval between collections in ms
53
+
54
+ #### Example Usage
55
+
56
+ ```cpp
57
+ #include "alteriom_sensor_package.hpp"
58
+ using namespace alteriom;
59
+
60
+ void collectAndSendMetrics() {
61
+ MetricsPackage metrics;
62
+ metrics.from = mesh.getNodeId();
63
+
64
+ // Collect CPU metrics
65
+ metrics.cpuUsage = calculateCPUUsage();
66
+ metrics.loopIterations = getLoopsPerSecond();
67
+ metrics.taskQueueSize = scheduler.size();
68
+
69
+ // Collect memory metrics
70
+ metrics.freeHeap = ESP.getFreeHeap();
71
+ metrics.minFreeHeap = getMinHeapSinceBoot();
72
+ #ifdef ESP32
73
+ metrics.maxAllocHeap = ESP.getMaxAllocHeap();
74
+ #else
75
+ metrics.heapFragmentation = ESP.getHeapFragmentation();
76
+ metrics.maxAllocHeap = ESP.getMaxFreeBlockSize();
77
+ #endif
78
+
79
+ // Collect network metrics
80
+ metrics.bytesReceived = getTotalBytesRx();
81
+ metrics.bytesSent = getTotalBytesTx();
82
+ metrics.currentThroughput = calculateThroughput();
83
+
84
+ // Connection quality
85
+ metrics.connectionQuality = calculateConnectionQuality();
86
+ metrics.wifiRSSI = WiFi.RSSI();
87
+
88
+ // Metadata
89
+ metrics.collectionTimestamp = mesh.getNodeTime();
90
+ metrics.collectionInterval = 30000; // 30 seconds
91
+
92
+ // Send metrics
93
+ mesh.sendBroadcast(metrics.toJsonString());
94
+ }
95
+ ```
96
+
97
+ #### MQTT Integration
98
+
99
+ When using with the MQTT bridge, metrics are published to:
100
+ - `mesh/metrics/{node_id}` - Per-node metrics
101
+ - `mesh/metrics/aggregated` - Aggregated mesh-wide metrics
102
+
103
+ #### Dashboard Integration
104
+
105
+ **Grafana:**
106
+ ```json
107
+ {
108
+ "cpu_usage": "${cpuUsage}",
109
+ "free_heap": "${freeHeap}",
110
+ "throughput": "${currentThroughput}",
111
+ "rssi": "${wifiRSSI}",
112
+ "quality": "${connectionQuality}"
113
+ }
114
+ ```
115
+
116
+ **InfluxDB Line Protocol:**
117
+ ```
118
+ metrics,node_id=12345 cpu=${cpuUsage},heap=${freeHeap},throughput=${currentThroughput} ${timestamp}
119
+ ```
120
+
121
+ ### HealthCheckPackage (Type 605)
122
+
123
+ A proactive health monitoring package designed for early problem detection, predictive maintenance, and automated alerting.
124
+
125
+ #### Purpose
126
+
127
+ - **Proactive Detection** - Identify problems before they cause failures
128
+ - **Predictive Maintenance** - Estimate time to failure and plan maintenance
129
+ - **Automated Alerting** - Trigger alerts based on health thresholds
130
+ - **Root Cause Analysis** - Provide detailed health indicators for troubleshooting
131
+
132
+ #### Health Status Levels
133
+
134
+ - **2 (Healthy)** - All systems operating normally
135
+ - **1 (Warning)** - Some issues detected, monitoring required
136
+ - **0 (Critical)** - Immediate attention required
137
+
138
+ #### Problem Flags (Bit Flags)
139
+
140
+ | Flag | Value | Description |
141
+ |------|-------|-------------|
142
+ | Low Memory | 0x0001 | Free memory below threshold |
143
+ | High CPU | 0x0002 | CPU usage above threshold |
144
+ | Connection Instability | 0x0004 | Frequent reconnections |
145
+ | High Packet Loss | 0x0008 | Packet loss above threshold |
146
+ | Network Congestion | 0x0010 | Network congestion detected |
147
+ | Low Battery | 0x0020 | Battery level critical |
148
+ | Thermal Warning | 0x0040 | Temperature above safe limit |
149
+ | Mesh Partition | 0x0080 | Mesh network partitioned |
150
+ | OTA in Progress | 0x0100 | Firmware update active |
151
+ | Configuration Error | 0x0200 | Configuration issue detected |
152
+
153
+ #### Health Scores (0-100)
154
+
155
+ Each component (memory, network, performance) has a health score:
156
+ - **90-100** - Excellent
157
+ - **70-89** - Good
158
+ - **50-69** - Fair
159
+ - **30-49** - Poor
160
+ - **0-29** - Critical
161
+
162
+ #### Key Fields
163
+
164
+ **Overall Health:**
165
+ - `healthStatus` (uint8_t) - Overall status (0-2)
166
+ - `problemFlags` (uint16_t) - Bit flags for specific problems
167
+
168
+ **Component Health:**
169
+ - `memoryHealth` (uint8_t) - Memory health score (0-100)
170
+ - `memoryTrend` (uint32_t) - Memory loss rate in bytes/hour
171
+ - `networkHealth` (uint8_t) - Network health score (0-100)
172
+ - `packetLossPercent` (uint8_t) - Current packet loss percentage
173
+ - `reconnectionCount` (uint8_t) - Reconnections in last hour
174
+ - `performanceHealth` (uint8_t) - Performance health score (0-100)
175
+ - `missedDeadlines` (uint32_t) - Missed task deadlines
176
+ - `maxLoopTime` (uint16_t) - Maximum loop execution time in ms
177
+
178
+ **Environmental:**
179
+ - `temperature` (int8_t) - Device temperature in Celsius
180
+ - `temperatureHealth` (uint8_t) - Temperature health score
181
+
182
+ **Stability:**
183
+ - `uptime` (uint32_t) - Uptime in seconds
184
+ - `crashCount` (uint16_t) - Crash/restart count
185
+ - `lastRebootReason` (uint32_t) - Last reboot reason code
186
+
187
+ **Predictive:**
188
+ - `estimatedTimeToFailure` (uint16_t) - Estimated hours until failure (0=unknown)
189
+ - `recommendations` (TSTRING) - Recommended actions
190
+
191
+ #### Example Usage
192
+
193
+ ```cpp
194
+ void performHealthCheck() {
195
+ HealthCheckPackage health;
196
+ health.from = mesh.getNodeId();
197
+
198
+ // Calculate component health scores
199
+ uint8_t memHealth = calculateMemoryHealth();
200
+ uint8_t netHealth = calculateNetworkHealth();
201
+ uint8_t perfHealth = calculatePerformanceHealth();
202
+
203
+ // Determine overall health status
204
+ if (memHealth < 30 || netHealth < 30 || perfHealth < 30) {
205
+ health.healthStatus = 0; // Critical
206
+ } else if (memHealth < 60 || netHealth < 60 || perfHealth < 60) {
207
+ health.healthStatus = 1; // Warning
208
+ } else {
209
+ health.healthStatus = 2; // Healthy
210
+ }
211
+
212
+ // Set problem flags
213
+ health.problemFlags = 0;
214
+ if (memHealth < 60) health.problemFlags |= 0x0001;
215
+ if (perfHealth < 60) health.problemFlags |= 0x0002;
216
+ if (netHealth < 60) health.problemFlags |= 0x0004;
217
+
218
+ // Component health
219
+ health.memoryHealth = memHealth;
220
+ health.memoryTrend = calculateMemoryTrend();
221
+ health.networkHealth = netHealth;
222
+ health.packetLossPercent = getPacketLossPercent();
223
+ health.performanceHealth = perfHealth;
224
+
225
+ // Predictive indicators
226
+ if (health.memoryTrend > 0) {
227
+ uint32_t freeHeap = ESP.getFreeHeap();
228
+ health.estimatedTimeToFailure = freeHeap / health.memoryTrend;
229
+ }
230
+
231
+ // Recommendations
232
+ if (health.healthStatus == 0) {
233
+ health.recommendations = "CRITICAL: Immediate attention required";
234
+ } else if (health.healthStatus == 1) {
235
+ if (memHealth < 60) {
236
+ health.recommendations = "Increase memory allocation";
237
+ } else if (netHealth < 60) {
238
+ health.recommendations = "Check network connections";
239
+ }
240
+ } else {
241
+ health.recommendations = "System operating normally";
242
+ }
243
+
244
+ // Send health check
245
+ mesh.sendBroadcast(health.toJsonString());
246
+ }
247
+ ```
248
+
249
+ #### Alert Integration
250
+
251
+ **Home Assistant:**
252
+ ```yaml
253
+ - platform: mqtt
254
+ name: "Mesh Node Health"
255
+ state_topic: "mesh/health/12345"
256
+ value_template: "{{ value_json.healthStatus }}"
257
+ json_attributes_topic: "mesh/health/12345"
258
+ json_attributes_template: "{{ value_json | tojson }}"
259
+ ```
260
+
261
+ **Alerting Rules:**
262
+ ```yaml
263
+ alerts:
264
+ - name: critical_health
265
+ condition: healthStatus == 0
266
+ action: send_notification
267
+ - name: memory_warning
268
+ condition: memoryHealth < 60
269
+ action: log_warning
270
+ - name: predicted_failure
271
+ condition: estimatedTimeToFailure < 24
272
+ action: schedule_maintenance
273
+ ```
274
+
275
+ ## Collection Intervals
276
+
277
+ ### Recommended Intervals
278
+
279
+ | Package Type | Interval | Use Case |
280
+ |--------------|----------|----------|
281
+ | MetricsPackage | 30-60s | Normal monitoring |
282
+ | MetricsPackage | 10-30s | Active troubleshooting |
283
+ | MetricsPackage | 5-10s | Critical performance analysis |
284
+ | HealthCheckPackage | 60s | Normal health monitoring |
285
+ | HealthCheckPackage | 30s | Warning state monitoring |
286
+ | HealthCheckPackage | 10s | Critical state monitoring |
287
+
288
+ ### Configurable Collection
289
+
290
+ ```cpp
291
+ // In setup()
292
+ #define METRICS_INTERVAL 30000 // 30 seconds
293
+ #define HEALTH_INTERVAL 60000 // 60 seconds
294
+
295
+ Task taskMetrics(METRICS_INTERVAL, TASK_FOREVER, &sendMetrics);
296
+ Task taskHealth(HEALTH_INTERVAL, TASK_FOREVER, &sendHealthCheck);
297
+
298
+ userScheduler.addTask(taskMetrics);
299
+ userScheduler.addTask(taskHealth);
300
+
301
+ taskMetrics.enable();
302
+ taskHealth.enable();
303
+
304
+ // Dynamic adjustment based on health status
305
+ void adjustCollectionIntervals(uint8_t healthStatus) {
306
+ if (healthStatus == 0) { // Critical
307
+ taskMetrics.setInterval(10000); // 10 seconds
308
+ taskHealth.setInterval(10000);
309
+ } else if (healthStatus == 1) { // Warning
310
+ taskMetrics.setInterval(20000); // 20 seconds
311
+ taskHealth.setInterval(30000);
312
+ } else { // Healthy
313
+ taskMetrics.setInterval(60000); // 60 seconds
314
+ taskHealth.setInterval(60000);
315
+ }
316
+ }
317
+ ```
318
+
319
+ ## MQTT Bridge Integration
320
+
321
+ ### Publishing Topics
322
+
323
+ #### Per-Node Topics
324
+ - `mesh/metrics/{node_id}` - Individual node metrics
325
+ - `mesh/health/{node_id}` - Individual node health checks
326
+
327
+ #### Aggregated Topics
328
+ - `mesh/metrics/aggregated` - Mesh-wide aggregated metrics
329
+ - `mesh/health/summary` - Overall mesh health summary
330
+ - `mesh/alerts` - Active alerts across the mesh
331
+
332
+ ### Message Format (Updated for @alteriom/mqtt-schema v0.7.2+)
333
+
334
+ Packages now include the `message_type` field for 90% faster message classification:
335
+
336
+ ```json
337
+ {
338
+ "schema_version": 1,
339
+ "device_id": "ALT-12345",
340
+ "timestamp": "2025-10-23T21:30:00Z",
341
+ "type": 204,
342
+ "message_type": 204,
343
+ "from": 12345,
344
+ "cpuUsage": 45,
345
+ "freeHeap": 100000,
346
+ "currentThroughput": 8192,
347
+ "connectionQuality": 85,
348
+ "wifiRSSI": -55,
349
+ ...
350
+ }
351
+ ```
352
+
353
+ **Message Type Codes:**
354
+ - **204:** MetricsPackage - SENSOR_METRICS (aligns with schema v0.7.2+)
355
+ - **605:** HealthCheckPackage - MESH_METRICS (mesh performance health)
356
+
357
+ ## Implementation Guide
358
+
359
+ ### Basic Implementation
360
+
361
+ See `examples/alteriom/metrics_health_node.ino` for a complete working example.
362
+
363
+ ### Integration with Existing Code
364
+
365
+ ```cpp
366
+ #include "alteriom_sensor_package.hpp"
367
+ using namespace alteriom;
368
+
369
+ // Add to your existing mesh node
370
+ void setup() {
371
+ // ... existing mesh setup ...
372
+
373
+ // Add metrics collection task
374
+ userScheduler.addTask(Task(30000, TASK_FOREVER, []() {
375
+ MetricsPackage metrics;
376
+ // ... populate metrics ...
377
+ mesh.sendBroadcast(metrics.toJsonString());
378
+ }));
379
+
380
+ // Add health check task
381
+ userScheduler.addTask(Task(60000, TASK_FOREVER, []() {
382
+ HealthCheckPackage health;
383
+ // ... populate health data ...
384
+ mesh.sendBroadcast(health.toJsonString());
385
+ }));
386
+ }
387
+ ```
388
+
389
+ ### Gateway Bridge Integration
390
+
391
+ ```cpp
392
+ // In MQTT bridge receivedCallback
393
+ void receivedCallback(uint32_t from, String& msg) {
394
+ DynamicJsonDocument doc(2048);
395
+ deserializeJson(doc, msg);
396
+
397
+ uint8_t msgType = doc["type"];
398
+
399
+ switch(msgType) {
400
+ case 204: // MetricsPackage
401
+ publishMetricsToMQTT(from, doc);
402
+ break;
403
+ case 605: // HealthCheckPackage (MESH_METRICS)
404
+ publishHealthToMQTT(from, doc);
405
+ checkForAlerts(doc);
406
+ break;
407
+ }
408
+ }
409
+
410
+ void publishMetricsToMQTT(uint32_t from, JsonDocument& doc) {
411
+ String topic = "mesh/metrics/" + String(from);
412
+ String payload;
413
+ serializeJson(doc, payload);
414
+ mqttClient.publish(topic.c_str(), payload.c_str());
415
+ }
416
+
417
+ void checkForAlerts(JsonDocument& doc) {
418
+ uint8_t healthStatus = doc["health"];
419
+ uint16_t problemFlags = doc["problems"];
420
+
421
+ if (healthStatus == 0) {
422
+ String alertTopic = "mesh/alerts/critical";
423
+ String alertMsg = "Critical health on node " + String(doc["from"].as<uint32_t>());
424
+ mqttClient.publish(alertTopic.c_str(), alertMsg.c_str());
425
+ }
426
+ }
427
+ ```
428
+
429
+ ## Performance Considerations
430
+
431
+ ### Memory Usage
432
+
433
+ - **MetricsPackage**: ~200 bytes per message
434
+ - **HealthCheckPackage**: ~250 bytes per message (including recommendations string)
435
+ - **Total overhead**: <1KB for both packages with reasonable collection intervals
436
+
437
+ ### Network Bandwidth
438
+
439
+ With 10 nodes and recommended intervals:
440
+ - **Metrics (30s)**: 10 nodes × 200 bytes / 30s = ~67 bytes/sec
441
+ - **Health (60s)**: 10 nodes × 250 bytes / 60s = ~42 bytes/sec
442
+ - **Total**: ~109 bytes/sec = minimal overhead
443
+
444
+ ### Optimization Tips
445
+
446
+ 1. **Adjust intervals based on load** - Increase intervals during normal operation
447
+ 2. **Use selective reporting** - Only send metrics that changed significantly
448
+ 3. **Aggregate at gateway** - Combine multiple node metrics before MQTT publish
449
+ 4. **Compress recommendations** - Use short, standardized recommendation codes
450
+ 5. **Throttle during congestion** - Reduce collection frequency when network is busy
451
+
452
+ ## Testing
453
+
454
+ ### Unit Tests
455
+
456
+ Run the comprehensive test suite:
457
+ ```bash
458
+ ./bin/catch_metrics_health_packages
459
+ ```
460
+
461
+ Tests validate:
462
+ - Serialization/deserialization
463
+ - Field preservation
464
+ - Edge cases (min/max values)
465
+ - Problem flag handling
466
+ - Health status levels
467
+ - Integration with painlessMesh plugin system
468
+
469
+ ### Integration Testing
470
+
471
+ ```cpp
472
+ // Test metrics collection
473
+ void testMetrics() {
474
+ MetricsPackage metrics;
475
+ metrics.from = 12345;
476
+ metrics.cpuUsage = 45;
477
+ metrics.freeHeap = 100000;
478
+
479
+ auto var = protocol::Variant(&metrics);
480
+ auto metrics2 = var.to<MetricsPackage>();
481
+
482
+ assert(metrics2.cpuUsage == 45);
483
+ assert(metrics2.freeHeap == 100000);
484
+ }
485
+
486
+ // Test health monitoring
487
+ void testHealth() {
488
+ HealthCheckPackage health;
489
+ health.from = 12345;
490
+ health.healthStatus = 1;
491
+ health.problemFlags = 0x0001;
492
+
493
+ auto var = protocol::Variant(&health);
494
+ auto health2 = var.to<HealthCheckPackage>();
495
+
496
+ assert(health2.healthStatus == 1);
497
+ assert(health2.problemFlags == 0x0001);
498
+ }
499
+ ```
500
+
501
+ ## Migration from Previous Versions
502
+
503
+ ### From v1.7.6
504
+
505
+ No breaking changes. Simply add the new packages to your code:
506
+
507
+ ```cpp
508
+ // Add new includes
509
+ #include "alteriom_sensor_package.hpp"
510
+ using namespace alteriom;
511
+
512
+ // Add new collection tasks
513
+ // ... see examples above ...
514
+ ```
515
+
516
+ ### Backward Compatibility
517
+
518
+ - All existing packages (200-203) continue to work unchanged
519
+ - New packages (204, 604, 605) are optional additions
520
+ - No changes required to existing code
521
+ - Can be adopted incrementally
522
+
523
+ ## Best Practices
524
+
525
+ 1. **Start with conservative intervals** - Begin with 60s intervals and adjust based on needs
526
+ 2. **Monitor memory usage** - Watch heap fragmentation when enabling new packages
527
+ 3. **Implement health-based throttling** - Reduce collection frequency when unhealthy
528
+ 4. **Use problem flags effectively** - Check specific flags rather than just status
529
+ 5. **Act on recommendations** - Implement automated responses to common recommendations
530
+ 6. **Set up alerting** - Configure alerts for critical health status
531
+ 7. **Track trends** - Use memoryTrend to detect slow memory leaks
532
+ 8. **Test thoroughly** - Validate metrics accuracy in your specific environment
533
+
534
+ ## Troubleshooting
535
+
536
+ ### High Memory Usage
537
+
538
+ - Increase collection intervals
539
+ - Reduce number of active packages
540
+ - Use shorter recommendation strings
541
+ - Check for memory leaks using memoryTrend
542
+
543
+ ### Network Congestion
544
+
545
+ - Increase collection intervals
546
+ - Use SINGLE routing instead of BROADCAST for some packages
547
+ - Implement throttling based on network health
548
+ - Reduce message size by removing optional fields
549
+
550
+ ### Inaccurate Metrics
551
+
552
+ - Calibrate CPU usage calculation for your use case
553
+ - Validate timing measurements
554
+ - Check clock synchronization across mesh
555
+ - Verify RSSI readings match reality
556
+
557
+ ## Future Enhancements
558
+
559
+ Planned for v1.8.0:
560
+ - Compressed metric packages for large meshes
561
+ - Historical trend storage in gateway
562
+ - Automatic threshold tuning
563
+ - Machine learning-based failure prediction
564
+ - Integration with cloud monitoring services
565
+
566
+ ## Enhanced MQTT Bridge
567
+
568
+ ### Overview
569
+
570
+ The enhanced MQTT bridge (`examples/bridge/enhanced_mqtt_bridge.hpp`) extends the basic MQTT status bridge with command handlers and aggregation capabilities.
571
+
572
+ ### Features
573
+
574
+ 1. **Command Handlers** - Request metrics and health checks on-demand
575
+ 2. **Aggregated Statistics** - Mesh-wide metrics and health summaries
576
+ 3. **Automatic Caching** - Stores recent metrics for aggregation
577
+ 4. **Alert Detection** - Automatic critical health alerting
578
+ 5. **Response Topics** - Dedicated topics for command responses
579
+
580
+ ### MQTT Topics
581
+
582
+ #### Subscribe Topics (Commands)
583
+
584
+ | Topic | Payload | Description |
585
+ |-------|---------|-------------|
586
+ | `mesh/command/request_metrics` | `{"node_id": 0}` | Request metrics (0=all nodes) |
587
+ | `mesh/command/request_health` | `{"node_id": 12345}` | Request health check |
588
+ | `mesh/command/get_aggregated` | `{}` | Get current aggregated stats |
589
+
590
+ #### Publish Topics (Data)
591
+
592
+ | Topic | Description | Update Frequency |
593
+ |-------|-------------|------------------|
594
+ | `mesh/metrics/{node_id}` | Individual node metrics | When received from node |
595
+ | `mesh/health/{node_id}` | Individual node health | When received from node |
596
+ | `mesh/aggregated/metrics` | Mesh-wide metrics | Configurable (default 60s) |
597
+ | `mesh/aggregated/health` | Mesh health summary | Configurable (default 60s) |
598
+ | `mesh/alerts/critical` | Critical health alerts | When critical detected |
599
+ | `mesh/response/metrics` | Metrics command response | When node responds |
600
+ | `mesh/response/health` | Health command response | When node responds |
601
+
602
+ ### Aggregated Metrics Format
603
+
604
+ ```json
605
+ {
606
+ "node_count": 10,
607
+ "avg_cpu": 42,
608
+ "avg_heap": 125000,
609
+ "min_heap": 95000,
610
+ "max_heap": 150000,
611
+ "total_throughput": 81920,
612
+ "avg_quality": 87,
613
+ "min_quality": 65,
614
+ "max_quality": 98,
615
+ "avg_rssi": -58,
616
+ "timestamp": "2025-10-23T21:30:00Z"
617
+ }
618
+ ```
619
+
620
+ ### Aggregated Health Format
621
+
622
+ ```json
623
+ {
624
+ "node_count": 10,
625
+ "mesh_health": 2,
626
+ "healthy_nodes": 8,
627
+ "warning_nodes": 2,
628
+ "critical_nodes": 0,
629
+ "aggregated_problems": 5,
630
+ "avg_memory_health": 82,
631
+ "avg_network_health": 88,
632
+ "avg_performance_health": 90,
633
+ "timestamp": "2025-10-23T21:30:00Z"
634
+ }
635
+ ```
636
+
637
+ ### Example Usage
638
+
639
+ #### Request Metrics from All Nodes
640
+
641
+ ```bash
642
+ mosquitto_pub -h localhost -t mesh/command/request_metrics \
643
+ -m '{"node_id": 0}'
644
+ ```
645
+
646
+ #### Request Health from Specific Node
647
+
648
+ ```bash
649
+ mosquitto_pub -h localhost -t mesh/command/request_health \
650
+ -m '{"node_id": 12345}'
651
+ ```
652
+
653
+ #### Get Current Aggregated Statistics
654
+
655
+ ```bash
656
+ mosquitto_pub -h localhost -t mesh/command/get_aggregated -m '{}'
657
+ ```
658
+
659
+ #### Subscribe to Aggregated Metrics
660
+
661
+ ```bash
662
+ mosquitto_sub -h localhost -t mesh/aggregated/metrics
663
+ ```
664
+
665
+ #### Subscribe to Critical Alerts
666
+
667
+ ```bash
668
+ mosquitto_sub -h localhost -t mesh/alerts/critical
669
+ ```
670
+
671
+ ### Integration Example
672
+
673
+ ```cpp
674
+ #include "enhanced_mqtt_bridge.hpp"
675
+
676
+ // In setup()
677
+ EnhancedMqttBridge bridge(mesh, mqttClient);
678
+ bridge.setTopicPrefix("mesh/");
679
+ bridge.enableAggregation(true);
680
+ bridge.setAggregationInterval(60000); // 60 seconds
681
+ bridge.begin();
682
+
683
+ // In loop()
684
+ bridge.update();
685
+
686
+ // In MQTT callback
687
+ void mqttCallback(char* topic, byte* payload, unsigned int length) {
688
+ String topicStr = String(topic);
689
+ String payloadStr = String((char*)payload).substring(0, length);
690
+ bridge.handleMQTTMessage(topicStr, payloadStr);
691
+ }
692
+ ```
693
+
694
+ ### Configuration
695
+
696
+ ```cpp
697
+ // Set custom topic prefix
698
+ bridge.setTopicPrefix("alteriom/mesh/");
699
+
700
+ // Set device ID
701
+ bridge.setDeviceId("GATEWAY-001");
702
+
703
+ // Enable/disable aggregation
704
+ bridge.enableAggregation(true);
705
+
706
+ // Set aggregation interval
707
+ bridge.setAggregationInterval(30000); // 30 seconds
708
+ ```
709
+
710
+ ### Mesh Node Implementation
711
+
712
+ Nodes must respond to command requests:
713
+
714
+ ```cpp
715
+ void receivedCallback(uint32_t from, String& msg) {
716
+ DynamicJsonDocument doc(1024);
717
+ deserializeJson(doc, msg);
718
+
719
+ uint8_t msgType = doc["type"];
720
+
721
+ if (msgType == 201) { // CommandPackage
722
+ uint8_t command = doc["cmd"];
723
+
724
+ if (command == 210) { // Request metrics
725
+ sendMetrics();
726
+ } else if (command == 211) { // Request health
727
+ sendHealthCheck();
728
+ }
729
+ }
730
+ }
731
+ ```
732
+
733
+ ### Performance Considerations
734
+
735
+ **Memory Usage:**
736
+ - Cache size: ~100 bytes per node (max 20 nodes)
737
+ - Total overhead: ~2KB for bridge + caching
738
+
739
+ **Network Bandwidth:**
740
+ - Aggregated metrics: ~200 bytes every 60s
741
+ - Per-node metrics: ~200 bytes when received
742
+ - Critical alerts: ~150 bytes when detected
743
+
744
+ **Optimization:**
745
+ - Adjust cache size via `MAX_STORED_NODES` constant
746
+ - Increase aggregation interval for lower bandwidth
747
+ - Disable aggregation if not needed
748
+
749
+ ## Support
750
+
751
+ - **GitHub Issues**: https://github.com/Alteriom/painlessMesh/issues
752
+ - **Documentation**: https://alteriom.github.io/painlessMesh/
753
+ - **Examples**: `examples/alteriom/metrics_health_node.ino`, `examples/bridge/enhanced_mqtt_bridge_example.ino`
754
+
755
+ ## Changelog
756
+
757
+ ### v1.7.7 (2025-10-23)
758
+
759
+ **Added:**
760
+ - MetricsPackage (Type 204) for comprehensive performance monitoring
761
+ - HealthCheckPackage (Type 605) for proactive health monitoring (MESH_METRICS)
762
+ - Complete test suite for new packages
763
+ - Example implementation in `metrics_health_node.ino`
764
+ - Documentation for MQTT integration
765
+ - Dashboard integration examples
766
+
767
+ **Improved:**
768
+ - MQTT communication efficiency for metrics and health monitoring
769
+ - Problem detection and alerting capabilities
770
+ - Predictive maintenance support
771
+ - Memory leak detection
772
+
773
+ **Compatibility:**
774
+ - 100% backward compatible with v1.7.6
775
+ - All existing packages (200-203) unchanged
776
+ - Optional adoption of new features