"""
Real-time Sensor Data Visualizer using MQTT and Matplotlib.
This Python application subscribes to an MQTT topic for sensor data (e.g., temperature),
parses incoming messages as float values, and visualizes them in a live updating plot.
Requirements:
- pip install paho-mqtt matplotlib numpy
Usage:
1. Run this script.
2. It connects to the public broker 'test.mosquitto.org' and subscribes to 'sensors/temperature'.
3. Publish test data using MQTT tools, e.g.:
- mosquitto_pub -h test.mosquitto.org -t sensors/temperature -m "23.5"
- Or use the publisher example below.
4. Watch the plot update in real-time!
Publisher Example (run in another terminal):
```bash
while true; do
mosquitto_pub -h test.mosquitto.org -t sensors/temperature -m "$(python3 -c 'import random; print(random.uniform(20, 30))')"
sleep 1
done
Or save this as publisher.py and run it:
python
import paho.mqtt.client as mqtt
import time
import random
import json
client = mqtt.Client()
client.connect("test.mosquitto.org", 1883, 60)
client.loop_start()
while True:
data = {"value": random.uniform(20, 30), "timestamp": time.time()}
client.publish("sensors/temperature", json.dumps(data))
print(f"Published: {data}")
time.sleep(1)
"""
import paho.mqtt.client as mqtt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from collections import deque
import time
import json
import sys
Configuration
BROKER = "test.mosquitto.org"
PORT = 1883
TOPIC = "sensors/temperature"
MAX_POINTS = 200 # Maximum data points to display (deque maxlen)
UPDATE_INTERVAL_MS = 1000 # Plot update interval in ms
Global data storage: deque of (timestamp, value) tuples
data = deque(maxlen=MAX_POINTS)
MQTT Client setup
client = mqtt.Client()
client.on_connect = lambda c, userdata, flags, rc: (
print(f"Connected to MQTT broker with code {rc}"),
c.subscribe(TOPIC),
print(f"Subscribed to topic '{TOPIC}'")
)
def on_message(client, userdata, msg):
"""Callback for incoming MQTT messages."""
try:
payload_str = msg.payload.decode('utf-8')
# Try JSON first, fallback to float
try:
d = json.loads(payload_str)
value = float(d.get('value', d))
except json.JSONDecodeError:
value = float(payload_str)
code
timestamp = time.time()
data.append((timestamp, value))
print(f"Received on '{msg.topic}': {value} at {timestamp}")
except (ValueError, KeyError, TypeError) as e:
print(f"Failed to parse message '{payload_str}': {e}")
client.on_message = on_message
Connect and start loop in background thread
try:
client.connect(BROKER, PORT, 60)
client.loop_start()
except Exception as e:
print(f"Failed to connect to MQTT broker: {e}")
sys.exit(1)
2. Save the code as `mqtt_visualizer.py`.
3. Run: `python mqtt_visualizer.py`.
4. Publish data (see inline examples) to see the plot update live!
### Features
- **Real-time updates**: Plot refreshes every 1 second with new data.
- **History buffer**: Keeps last 200 points; oldest discarded.
- **Dynamic scaling**: X-axis shows time relative to latest sample; Y-axis auto-scales.
- **Robust parsing**: Handles plain floats or JSON `{"value": 23.5}`.
- **Public broker**: Works out-of-the-box with `test.mosquitto.org`.
- **Graceful shutdown**: Ctrl+C or close plot window.
Customize `BROKER`, `TOPIC`, `MAX_POINTS` as needed. For private brokers, add username/password via `client.username_pw_set()`.