Build an MQTT sensor visualizer with paho-mqtt. Run a subscriber thread pushing messages into a priority queue prioritizing critical alerts, and a visualizer thread using matplotlib animation to plot temperature data in real-time.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The plan defines a Python script where a subscriber thread listens via paho-mqtt, pushes parsed JSON messages with priority based on alert level into a priority queue, and the main thread runs a matplotlib animation that consumes the queue to plot temperature data in real-time, highlighting critical alerts. An optional publisher simulator thread can generate test messages for demonstration.
Below is a self‑contained example that ties together all of the pieces you described:
An MQTT subscriber running on its own thread using paho-mqtt.
An in‑memory PriorityQueue that assigns a higher priority to critical alerts than to normal telemetry.
A matplotlib animation loop that consumes the queue and plots temperatures in (near) real time.
You'll need paho-mqtt and matplotlib installed (pip install paho-mqtt matplotlib). Point the client at your broker and topic, or use the built‑in simulator to see it run without external infrastructure.
python
import json
import threading
import queue
import time
import random
from collections import deque
import paho.mqtt.client as mqtt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Thread-safe priority queue; lower number = higher priority
msg_queue = queue.PriorityQueue()
# Simple data buffers for plotting
times = deque(maxlen=200)
temps = deque(maxlen=200)
alerts = deque(maxlen=200)
MQTT_BROKER = "localhost"
MQTT_PORT = 1883
MQTT_TOPIC = "sensors/temperature"
# --- MQTT subscriber callbacks ---
def on_connect(client, userdata, flags, rc):
print("Connected to broker with result code", rc)
client.subscribe(MQTT_TOPIC)
def on_message(client, userdata, msg):
"""Parse incoming messages and push into priority queue."""
try:
payload = msg.payload.decode("utf-8")
data = json.loads(payload)
# Expected payload fields: {"temperature": 23.4, "level": "info"|"critical"}
temp = data.get("temperature")
level = data.get("level", "info")
if temp is None:
return # ignore if no temperature
# compute priority: 0 for critical alerts, 1 for normal messages
priority = 0 if level.lower() == "critical" else 1
# include timestamp as second tuple element to break ties
msg_queue.put((priority, time.time(), data))
except Exception as e:
print("Error handling message:", e)
def mqtt_subscriber():
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_BROKER, MQTT_PORT, keepalive=60)
client.loop_forever()
# --- Optional: simulate publishing sensor data if you don't have a broker ---
def mqtt_simulator():
"""Publish random temperature data, marking some as critical."""
pub = mqtt.Client()
pub.connect(MQTT_BROKER, MQTT_PORT, 60)
pub.loop_start()
try:
while True:
temp = 20 + random.random() * 10
level = "critical" if temp > 27 else "info"
payload = json.dumps({"temperature": temp, "level": level})
pub.publish(MQTT_TOPIC, payload)
time.sleep(1.0)
except KeyboardInterrupt:
pass
finally:
pub.loop_stop()
# --- Matplotlib animation ---
fig, ax = plt.subplots()
line, = ax.plot([], [], color="blue", label="Temperature")
alert_scatter = ax.scatter([], [], color="red", label="Critical")
def init():
ax.set_xlabel("Time (s)")
ax.set_ylabel("Temperature (°C)")
ax.set_title("Real-time Temperature")
ax.legend()
return line, alert_scatter
def update(frame):
# Drain any queued messages, honoring priority
while True:
try:
priority, tstamp, data = msg_queue.get_nowait()
except queue.Empty:
break
times.append(tstamp)
temps.append(data["temperature"])
alerts.append(data.get("level", "info").lower() == "critical")
if not times:
return line, alert_scatter
# Update line plot
t0 = times[0]
xs = [t - t0 for t in times] # convert to relative time
line.set_data(xs, temps)
# Update scatter for critical points
crit_x = [x for x, is_alert in zip(xs, alerts) if is_alert]
crit_y = [y for y, is_alert in zip(temps, alerts) if is_alert]
alert_scatter.set_offsets(list(zip(crit_x, crit_y)) if crit_x else [])
ax.relim()
ax.autoscale_view()
return line, alert_scatter
if __name__ == "__main__":
# Start MQTT subscriber thread
threading.Thread(target=mqtt_subscriber, daemon=True).start()
# Uncomment the next line to run a local simulator publisher
# threading.Thread(target=mqtt_simulator, daemon=True).start()
ani = animation.FuncAnimation(fig, update, init_func=init, interval=500, blit=False)
plt.show()
A few notes on how this works:
queue.PriorityQueue orders items by the first element of the tuple. By using (priority, timestamp, data) you ensure that critical items (priority=0) are processed before normal telemetry (priority=1), and messages of the same priority are ordered by arrival time.
The MQTT client runs in its own thread via loop_forever(), so the main thread is free to run the GUI/animation loop. The daemon=True flag ensures threads exit when the main program exits.
matplotlib.animation.FuncAnimation calls update every 500 ms; in each call we drain the queue and refresh the plot. For simplicity the example uses deques and calls relim/autoscale_view() to adjust axes dynamically.
The optional mqtt_simulator shows how to generate test data if you don't have live MQTT traffic; if you have a broker and publisher already, leave it commented out and adjust MQTT_BROKER/MQTT_TOPIC as needed.