87 lines
2.3 KiB
Markdown
87 lines
2.3 KiB
Markdown
# MQTT Integration Instructions for ESP32 Financial Dashboard
|
|
|
|
## Overview
|
|
This guide shows how to integrate MQTT into your existing `bitcoin_dashboard` firmware.
|
|
|
|
## Files to Add
|
|
|
|
1. **mqtt_module.h** - Header file for MQTT functionality
|
|
2. **mqtt_module.cpp** - Implementation
|
|
|
|
## Changes to main.cpp
|
|
|
|
### 1. Add includes at top (after existing includes)
|
|
|
|
```cpp
|
|
#include "mqtt_module.h"
|
|
```
|
|
|
|
### 2. Add MQTT configuration (after existing defines)
|
|
|
|
```cpp
|
|
#define MQTT_SERVER "mqtt.yourdomain.com"
|
|
#define MQTT_PORT 9001
|
|
#define MQTT_USER "esp32"
|
|
#define MQTT_PASS "your_password"
|
|
#define MQTT_TOPIC "finance/prices"
|
|
```
|
|
|
|
### 3. Create MQTT module instance (after existing global variables)
|
|
|
|
```cpp
|
|
MQTTModule mqtt;
|
|
```
|
|
|
|
### 4. Initialize MQTT in setup() (after WiFi connection succeeds)
|
|
|
|
```cpp
|
|
mqtt.begin(MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASS);
|
|
mqtt.setTopic(MQTT_TOPIC);
|
|
```
|
|
|
|
### 5. Update MQTT in loop() (add at start of loop)
|
|
|
|
```cpp
|
|
void loop() {
|
|
mqtt.update(); // Add this line at the start of loop()
|
|
|
|
// ... rest of existing loop code
|
|
}
|
|
```
|
|
|
|
### 6. Keep existing updatePrices() as fallback
|
|
|
|
The existing `updatePrices()` function remains unchanged. It will:
|
|
- Be called on the 3-minute refresh interval
|
|
- Serve as fallback if MQTT disconnects
|
|
- Continue to work transparently
|
|
|
|
## How It Works
|
|
|
|
1. **Server polls APIs** every 3 minutes, publishes to MQTT
|
|
2. **ESP32 subscribes** to topic, receives updates immediately
|
|
3. **On MQTT message**: `_parsePriceData()` updates prices, sets `needsRefresh = true`
|
|
4. **Main loop** redraws screen when `needsRefresh` is true
|
|
5. **Fallback**: If MQTT disconnects, existing HTTP polling continues
|
|
|
|
## Benefits
|
|
|
|
- **95% fewer API calls** - Server polls once, all devices receive
|
|
- **25x smaller payload** - ~2KB JSON vs ~50KB per device
|
|
- **Instant updates** - No 3-minute wait
|
|
- **Graceful fallback** - HTTP polling if MQTT fails
|
|
|
|
## Testing
|
|
|
|
1. Deploy server stack with Docker Compose
|
|
2. Flash modified firmware to one test device
|
|
3. Monitor Serial output for MQTT connection messages
|
|
4. Verify prices update when server publishes
|
|
|
|
## Configuration
|
|
|
|
Edit these values in main.cpp:
|
|
- `MQTT_SERVER` - Your domain (Caddy handles TLS)
|
|
- `MQTT_PORT` - 9001 for WebSocket, 1883 for raw MQTT
|
|
- `MQTT_USER` / `MQTT_PASS` - From Mosquitto password file
|
|
- `MQTT_TOPIC` - Must match aggregator config
|