Analyzing the Application Scope
I'm focused on grasping the application's core function: real-time sensor data visualization from MQTT. I've broken down the project into key areas, specifically the data source, data processing, the visualization aspect, and the interaction with MQTT. This will drive the feature selection.
Considering Architectural Options
I'm now weighing the choices for the visualization component. Matplotlib is appealing for its simplicity, particularly using FuncAnimation. But I'm also considering Plotly/Dash and PyQtGraph for their interactive and performance advantages, especially if the sensor data load is substantial. Streamlit might be a quick path to a basic demo, but real-time performance might be a drawback.
Formulating the Implementation Plan
I've sketched out the initial steps for implementation. Firstly, the simulator needs to generate and publish data. Second, the subscriber, which will also be the visualizer, needs to connect, receive data, and update the plot. The plan prioritizes a simple Matplotlib setup, leveraging FuncAnimation, while using a public MQTT broker for ease of use. Key steps include library installation and broker selection to make the demo immediately runnable.
Finalizing Code and Testing
I'm now iterating on the subscriber/visualizer code, ensuring data flows smoothly from the MQTT callback to the plotting function. I'm focusing on managing the data buffer and ensuring the animation updates efficiently. The publisher's code is already simplified. Testing will be next; I plan to deploy on a local machine with the simulator and a simple Matplotlib graph.
Considering Future Improvements
I'm now contemplating additional features and refinements. The current focus is on a basic but functional demo. After that, I'll assess the practicality of JSON payloads over the current float data. Furthermore, I'll think about more advanced user interface elements, as well as a brief description of how Streamlit could provide a more advanced solution.
Detailing Code Implementation
I'm deep in the implementation details. I've got the publisher and subscriber scripts outlined and am working through the data flow. The key is now ensuring the MQTT data updates the Matplotlib plot correctly, using FuncAnimation. I'm focusing on data buffering and effective animation refreshes.
Here is a complete, step-by-step Python solution to visualize real-time sensor data using MQTT and Matplotlib.
We will create two scripts:
sensor_sim.py: Simulates a sensor sending data (Temperature & Humidity).
monitor.py: Subscribes to the MQTT topic and plots the data in real-time.
Prerequisites
You will need to install the MQTT client library and the plotting library:
pip install paho-mqtt matplotlib
1. The Data Generator (sensor_sim.py)
Since you might not have a physical IoT device ready, this script acts as a fake sensor publishing JSON data every second.
import time
import random
import json
import paho.mqtt.client as mqtt
# MQTT Brokers (Public test broker)
BROKER = "broker.emqx.io"
PORT = 1883
TOPIC = "python/mqtt/sensor"
def connect_mqtt():
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.connect(BROKER, PORT, 60)
return client
def publish(client):
while True:
time.sleep(1)
# Simulate sensor data
temperature = round(random.uniform(20.0, 30.0), 2)
humidity = round(random.uniform(30.0, 60.0), 2)
payload = json.dumps({
"temperature": temperature,
"humidity": humidity
})
result = client.publish(TOPIC, payload)
status = result[0]
if status == 0:
print(f"Sent `{payload}` to topic `{TOPIC}`")
else:
print("Failed to send message to topic")
if __name__ == '__main__':
client = connect_mqtt()
client.loop_start()
print("Simulator started...")
publish(client)
2. The Real-Time Visualizer (monitor.py)
This is the main application. It listens for messages in the background and updates a Matplotlib graph on the main thread.
import json
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime
import paho.mqtt.client as mqtt
# Settings
BROKER = "broker.emqx.io"
PORT = 1883
TOPIC = "python/mqtt/sensor"
# Data buffers for plotting
max_points = 50
times = []
temps = []
hums = []
# Setup Plot
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
fig.suptitle('Real-time Sensor Data over MQTT')
def on_connect(client, userdata, flags, rc, properties=None):
if rc == 0:
print("Connected to MQTT Broker!")
client.subscribe(TOPIC)
else:
print("Failed to connect, return code %d\n", rc)
def on_message(client, userdata, msg):
try:
payload = msg.payload.decode()
data = json.loads(payload)
# Get current time string
current_time = datetime.now().strftime('%H:%M:%S')
# Append data to lists
times.append(current_time)
temps.append(data["temperature"])
hums.append(data["humidity"])
# Limit lists to max_points to keep graph readable
if len(times) > max_points:
times.pop(0)
temps.pop(0)
hums.pop(0)
print(f"Received: {data}")
except Exception as e:
print(f"Error parsing message: {e}")
def animate(i):
# Clear axes to avoid overwriting
ax1.clear()
ax2.clear()
# Plot Temperature
ax1.plot(times, temps, label='Temperature (°C)', color='tab:red')
ax1.legend(loc='upper left')
ax1.set_ylabel('Temp (°C)')
ax1.grid(True)
# Plot Humidity
ax2.plot(times, hums, label='Humidity (%)', color='tab:blue')
ax2.legend(loc='upper left')
ax2.set_ylabel('Humidity (%)')
ax2.set_xlabel('Time')
ax2.grid(True)
# Rotate x-axis labels for better readability
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30) # Make room for labels
# Setup MQTT Client
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
try:
print("Connecting to broker...")
client.connect(BROKER, PORT, 60)
# Start MQTT logic in a background thread
client.loop_start()
# Start Animation
# interval=1000 means the plot updates every 1000ms (1 second)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
except KeyboardInterrupt:
print("Disconnecting...")
client.loop_stop()
client.disconnect()
How to Run It
-
Start the Viewer:
Open a terminal and run the visualizer first. It will open a blank window and wait for data.
python monitor.py
-
Start the Simulator:
Open a second terminal window and run the simulator.
python sensor_sim.py
-
Result:
You will see the graph in monitor.py start updating automatically every second as data arrives from the simulator via the public MQTT broker.
How it Works
- Threading:
paho-mqtt has a client.loop_start() command. This creates a background thread that handles network traffic. This is crucial because Matplotlib (and most GUIs) must run on the Main Thread to draw the window.
- The Buffer: We use simple Python lists (
times, temps, hums) as a buffer. The MQTT thread adds data to the end, and we trim the start of the list if it gets longer than max_points.
- Animation:
FuncAnimation calls the animate function every 1000ms. This function wipes the graph and redraws the lines based on the current state of the lists.