This is a great request for building a sophisticated MQTT-based sensor visualization system. Let me break down what we need to create:
- An MQTT subscriber that listens to sensor data
- A priority queue to handle different message types (critical alerts should be prioritized)
- A visualizer thread that uses matplotlib animation for real-time plotting
- Proper threading and synchronization
Key components:
- Use
paho-mqtt for MQTT communication
- Use
queue.PriorityQueue for message prioritization
- Use
matplotlib.animation.FuncAnimation for real-time plotting
- Proper threading with thread-safe operations
- Configuration for MQTT broker
Let me create a comprehensive example with:
- A sensor simulator (can publish test data)
- Main application with subscriber
- Priority queue management
- Real-time visualization with matplotlib
- Alert handling
- Clean shutdown
Here's what I'll include:
- Temperature sensor data
- Alert levels (normal, warning, critical)
- Real-time plotting of multiple sensors
- Alert notification system
- Configurable thresholds
- Proper error handling
MQTT Sensor Visualizer with Real-Time Plotting
I'll build a complete system with an MQTT subscriber, priority queue, and real-time matplotlib visualization.
1. Installation
pip install paho-mqtt matplotlib numpy colorama
2. Main Sensor Visualizer
# mqtt_sensor_visualizer.py
import paho.mqtt.client as mqtt
import threading
import queue
from queue import PriorityQueue
from dataclasses import dataclass
from typing import Dict, List
import json
import time
from datetime import datetime
from enum import Enum
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class AlertLevel(Enum):
"""Priority levels for alerts"""
NORMAL = 3
WARNING = 2
CRITICAL = 1
@dataclass
class SensorMessage:
"""Priority queue message structure"""
priority: int
timestamp: float
sensor_id: str
sensor_name: str
temperature: float
humidity: float
alert_level: AlertLevel
message: str
def __lt__(self, other):
"""Compare for priority queue (lower number = higher priority)"""
if self.priority != other.priority:
return self.priority < other.priority
return self.timestamp < other.timestamp
def __eq__(self, other):
return self.priority == other.priority
class MQTTSubscriber:
"""Manages MQTT subscription and message priority queue"""
def __init__(
self,
broker_address: str = "localhost",
broker_port: int = 1883,
queue_size: int = 100,
thresholds: Dict = None
):
self.broker_address = broker_address
self.broker_port = broker_port
self.message_queue: PriorityQueue = PriorityQueue(maxsize=queue_size)
self.running = False
self.client = mqtt.Client(client_id="sensor_visualizer")
# Temperature thresholds
self.thresholds = thresholds or {
'warning': 35.0,
'critical': 45.0,
'low_critical': 0.0
}
# Setup MQTT callbacks
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect
def _on_connect(self, client, userdata, flags, rc):
"""MQTT connection callback"""
if rc == 0:
logger.info("Connected to MQTT broker")
# Subscribe to all sensor topics
client.subscribe("sensors/#", qos=1)
else:
logger.error(f"Connection failed with code {rc}")
def _on_message(self, client, userdata, msg):
"""MQTT message callback"""
try:
payload = json.loads(msg.payload.decode())
sensor_id = payload.get('sensor_id', 'unknown')
sensor_name = payload.get('sensor_name', 'Unknown Sensor')
temperature = payload.get('temperature', 0.0)
humidity = payload.get('humidity', 0.0)
# Determine alert level
alert_level, alert_msg = self._determine_alert_level(
temperature, sensor_name
)
# Create sensor message with priority
sensor_msg = SensorMessage(
priority=alert_level.value,
timestamp=time.time(),
sensor_id=sensor_id,
sensor_name=sensor_name,
temperature=temperature,
humidity=humidity,
alert_level=alert_level,
message=alert_msg
)
# Try to add to queue (non-blocking)
try:
self.message_queue.put_nowait(sensor_msg)
except queue.Full:
logger.warning("Message queue full, dropping oldest message")
try:
self.message_queue.get_nowait()
self.message_queue.put_nowait(sensor_msg)
except queue.Empty:
pass
except json.JSONDecodeError:
logger.error(f"Failed to decode message: {msg.payload}")
except Exception as e:
logger.error(f"Error processing message: {e}")
def _determine_alert_level(self, temperature: float, sensor_name: str):
"""Determine alert level based on temperature"""
if temperature >= self.thresholds['critical']:
return (
AlertLevel.CRITICAL,
f"🔴 CRITICAL: {sensor_name} at {temperature}°C"
)
elif temperature >= self.thresholds['warning']:
return (
AlertLevel.WARNING,
f"🟡 WARNING: {sensor_name} at {temperature}°C"
)
elif temperature <= self.thresholds['low_critical']:
return (
AlertLevel.CRITICAL,
f"🔴 CRITICAL: {sensor_name} at {temperature}°C (freezing)"
)
else:
return AlertLevel.NORMAL, f"✅ {sensor_name}: {temperature}°C"
def _on_disconnect(self, client, userdata, rc):
"""MQTT disconnection callback"""
if rc != 0:
logger.warning(f"Unexpected disconnection: {rc}")
else:
logger.info("Disconnected from MQTT broker")
def start(self):
"""Start MQTT connection"""
self.running = True
try:
self.client.connect(self.broker_address, self.broker_port, keepalive=60)
self.client.loop_start()
logger.info(f"Connecting to {self.broker_address}:{self.broker_port}")
except Exception as e:
logger.error(f"Failed to connect: {e}")
self.running = False
def stop(self):
"""Stop MQTT connection"""
self.running = False
self.client.loop_stop()
self.client.disconnect()
logger.info("MQTT subscriber stopped")
def get_message(self, timeout: float = 0.5) -> SensorMessage:
"""Get next message from priority queue"""
try:
return self.message_queue.get(timeout=timeout)
except queue.Empty:
return None
def queue_size(self) -> int:
"""Get current queue size"""
return self.message_queue.qsize()
3. Real-Time Visualizer
# realtime_visualizer.py
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
from collections import deque, defaultdict
from datetime import datetime, timedelta
import numpy as np
from typing import Dict, Deque, Tuple
import threading
class RealtimeVisualizer:
"""Real-time temperature visualization using matplotlib"""
def __init__(
self,
max_points: int = 100,
update_interval: int = 1000,
time_window: int = 300
):
self.max_points = max_points
self.update_interval = update_interval # milliseconds
self.time_window = time_window # seconds
# Data storage
self.sensor_data: Dict[str, Deque] = defaultdict(
lambda: deque(maxlen=max_points)
)
self.sensor_info: Dict[str, Dict] = {}
self.alert_history: Deque = deque(maxlen=20)
self.lock = threading.Lock()
# Setup figure and subplots
self.fig = plt.figure(figsize=(16, 10))
self.fig.suptitle(
'MQTT Sensor Monitor - Real-Time Temperature Visualization',
fontsize=16,
fontweight='bold'
)
# Create grid for subplots
gs = self.fig.add_gridspec(3, 2, hspace=0.3, wspace=0.3)
self.ax_temp = self.fig.add_subplot(gs[0:2, 0]) # Temperature plot
self.ax_humidity = self.fig.add_subplot(gs[0:2, 1]) # Humidity plot
self.ax_alerts = self.fig.add_subplot(gs[2, :]) # Alerts log
self._setup_plots()
# Color map for sensors
self.colors = {
'sensor_1': '#FF6B6B',
'sensor_2': '#4ECDC4',
'sensor_3': '#45B7D1',
'sensor_4': '#FFA07A',
}
def _setup_plots(self):
"""Initialize plot settings"""
# Temperature plot
self.ax_temp.set_title('Temperature Over Time', fontweight='bold')
self.ax_temp.set_xlabel('Time')
self.ax_temp.set_ylabel('Temperature (°C)')
self.ax_temp.grid(True, alpha=0.3)
self.ax_temp.set_ylim(-10, 60)
# Humidity plot
self.ax_humidity.set_title('Humidity Over Time', fontweight='bold')
self.ax_humidity.set_xlabel('Time')
self.ax_humidity.set_ylabel('Humidity (%)')
self.ax_humidity.grid(True, alpha=0.3)
self.ax_humidity.set_ylim(0, 100)
# Alerts log
self.ax_alerts.set_title('Alert Log', fontweight='bold')
self.ax_alerts.axis('off')
def add_data(self, sensor_msg):
"""Add sensor data to visualization"""
with self.lock:
sensor_id = sensor_msg.sensor_id
# Store sensor info
self.sensor_info[sensor_id] = {
'name': sensor_msg.sensor_name,
'alert_level': sensor_msg.alert_level,
'last_update': sensor_msg.timestamp
}
# Store measurements
self.sensor_data[sensor_id].append({
'time': datetime.fromtimestamp(sensor_msg.timestamp),
'temp': sensor_msg.temperature,
'humidity': sensor_msg.humidity
})
# Log alerts
if sensor_msg.alert_level.value < 3: # Not normal
self.alert_history.appendleft({
'time': datetime.fromtimestamp(sensor_msg.timestamp),
'message': sensor_msg.message,
'level': sensor_msg.alert_level
})
def _plot_temperature(self):
"""Plot temperature data"""
self.ax_temp.clear()
self.ax_temp.set_title('Temperature Over Time', fontweight='bold')
self.ax_temp.set_xlabel('Time')
self.ax_temp.set_ylabel('Temperature (°C)')
self.ax_temp.grid(True, alpha=0.3)
self.ax_temp.set_ylim(-10, 60)
with self.lock:
for sensor_id, data in self.sensor_data.items():
if data:
times = [d['time'] for d in data]
temps = [d['temp'] for d in data]
sensor_name = self.sensor_info[sensor_id]['name']
color = self.colors.get(sensor_id, '#95E1D3')
# Plot line
self.ax_temp.plot(
times, temps,
marker='o',
label=sensor_name,
color=color,
linewidth=2,
markersize=4,
alpha=0.7
)
# Highlight last point
last_time = times[-1]
last_temp = temps[-1]
alert_level = self.sensor_info[sensor_id]['alert_level']
marker_color = self._get_alert_color(alert_level)
self.ax_temp.plot(
last_time, last_temp,
marker='o',
color=marker_color,
markersize=10,
zorder=5
)
self.ax_temp.legend(loc='upper left', fontsize=9)
self.ax_temp.xaxis.set_major_formatter(
DateFormatter('%H:%M:%S')
)
self.ax_temp.xaxis.set_major_locator(
mdates.AutoDateLocator()
)
self.fig.autofmt_xdate(rotation=45)
def _plot_humidity(self):
"""Plot humidity data"""
self.ax_humidity.clear()
self.ax_humidity.set_title('Humidity Over Time', fontweight='bold')
self.ax_humidity.set_xlabel('Time')
self.ax_humidity.set_ylabel('Humidity (%)')
self.ax_humidity.grid(True, alpha=0.3)
self.ax_humidity.set_ylim(0, 100)
with self.lock:
for sensor_id, data in self.sensor_data.items():
if data:
times = [d['time'] for d in data]
humidities = [d['humidity'] for d in data]
sensor_name = self.sensor_info[sensor_id]['name']
color = self.colors.get(sensor_id, '#95E1D3')
# Plot area
self.ax_humidity.fill_between(
times, humidities,
alpha=0.3,
color=color,
label=sensor_name
)
self.ax_humidity.plot(
times, humidities,
marker='s',
color=color,
linewidth=2,
markersize=4
)
self.ax_humidity.legend(loc='upper left', fontsize=9)
self.ax_humidity.xaxis.set_major_formatter(
DateFormatter('%H:%M:%S')
)
self.ax_humidity.xaxis.set_major_locator(
mdates.AutoDateLocator()
)
def _plot_alerts(self):
"""Display alert history"""
self.ax_alerts.clear()
self.ax_alerts.set_title('Alert Log', fontweight='bold')
self.ax_alerts.axis('off')
with self.lock:
y_position = 0.95
for i, alert in enumerate(list(self.alert_history)[:10]):
color = self._get_alert_color(alert['level'])
time_str = alert['time'].strftime('%H:%M:%S')
text = f"{time_str} - {alert['message']}"
self.ax_alerts.text(
0.05, y_position, text,
transform=self.ax_alerts.transAxes,
fontsize=9,
verticalalignment='top',
bbox=dict(
boxstyle='round',
facecolor=color,
alpha=0.3,
edgecolor=color
)
)
y_position -= 0.09
def _get_alert_color(self, alert_level):
"""Get color based on alert level"""
from realtime_visualizer import AlertLevel
if alert_level == AlertLevel.CRITICAL:
return '#FF6B6B' # Red
elif alert_level == AlertLevel.WARNING:
return '#FFD93D' # Yellow
else:
return '#6BCB77' # Green
def update(self, frame):
"""Animation update function"""
self._plot_temperature()
self._plot_humidity()
self._plot_alerts()
return []
def animate(self):
"""Start animation"""
ani = animation.FuncAnimation(
self.fig,
self.update,
interval=self.update_interval,
blit=True,
cache_frame_data=False
)
return ani
def show(self):
"""Display visualization"""
self.animate()
plt.tight_layout()
plt.show()
4. Main Application
# mqtt_visualizer_main.py
import sys
import signal
import threading
import time
from mqtt_sensor_visualizer import MQTTSubscriber, AlertLevel
from realtime_visualizer import RealtimeVisualizer
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class SensorVisualizerApp:
"""Main application coordinating MQTT subscriber and visualizer"""
def __init__(
self,
broker_address: str = "localhost",
broker_port: int = 1883
):
# Temperature thresholds
self.thresholds = {
'warning': 35.0,
'critical': 45.0,
'low_critical': 0.0
}
# Initialize components
self.subscriber = MQTTSubscriber(
broker_address=broker_address,
broker_port=broker_port,
thresholds=self.thresholds
)
self.visualizer = RealtimeVisualizer(
max_points=100,
update_interval=500
)
self.running = True
self.processor_thread = None
self.stats = {
'messages_processed': 0,
'alerts_received': 0
}
def process_messages(self):
"""Thread function to process messages from priority queue"""
logger.info("Message processor started")
while self.running:
msg = self.subscriber.get_message(timeout=1.0)
if msg:
# Process message
self.visualizer.add_data(msg)
self.stats['messages_processed'] += 1
# Log alerts
if msg.alert_level != AlertLevel.NORMAL:
self.stats['alerts_received'] += 1
logger.warning(msg.message)
# Print stats periodically
if self.stats['messages_processed'] % 10 == 0:
self._print_stats()
logger.info("Message processor stopped")
def _print_stats(self):
"""Print application statistics"""
queue_size = self.subscriber.queue_size()
logger.info(
f"Stats - Processed: {self.stats['messages_processed']}, "
f"Alerts: {self.stats['alerts_received']}, "
f"Queue: {queue_size}"
)
def start(self):
"""Start the application"""
logger.info("Starting Sensor Visualization App")
# Start MQTT subscriber
self.subscriber.start()
time.sleep(1) # Give MQTT time to connect
# Start message processor thread
self.processor_thread = threading.Thread(
target=self.process_messages,
daemon=True
)
self.processor_thread.start()
# Setup signal handlers for graceful shutdown
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
logger.info("Application started, starting visualization...")
# Start visualization (blocks)
self.visualizer.show()
def _signal_handler(self, sig, frame):
"""Handle shutdown signals"""
logger.info("Shutdown signal received")
self.stop()
sys.exit(0)
def stop(self):
"""Stop the application"""
logger.info("Stopping application...")
self.running = False
if self.processor_thread:
self.processor_thread.join(timeout=5)
self.subscriber.stop()
self._print_stats()
logger.info("Application stopped")
def main():
"""Main entry point"""
app = SensorVisualizerApp(
broker_address="localhost",
broker_port=1883
)
app.start()
if __name__ == "__main__":
main()
5. Sensor Data Simulator
# sensor_simulator.py
import paho.mqtt.client as mqtt
import json
import time
import math
import random
import threading
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class SensorSimulator:
"""Simulates MQTT sensor data"""
def __init__(
self,
broker_address: str = "localhost",
broker_port: int = 1883,
num_sensors: int = 3
):
self.broker_address = broker_address
self.broker_port = broker_port
self.num_sensors = num_sensors
self.client = mqtt.Client(client_id="sensor_simulator")
self.running = False
# Sensor state
self.sensor_state = {
f"sensor_{i}": {
'base_temp': 20 + random.randint(0, 10),
'base_humidity': 50 + random.randint(-10, 10),
'trend': random.choice([-0.5, 0, 0.5])
}
for i in range(1, num_sensors + 1)
}
def connect(self):
"""Connect to MQTT broker"""
try:
self.client.connect(self.broker_address, self.broker_port)
self.client.loop_start()
logger.info(f"Connected to {self.broker_address}:{self.broker_port}")
except Exception as e:
logger.error(f"Connection failed: {e}")
def publish_sensor_data(self):
"""Simulate and publish sensor data"""
self.running = True
iteration = 0
while self.running:
for sensor_id, state in self.sensor_state.items():
# Simulate temperature with trend and noise
iteration_offset = iteration * 0.05
noise = random.gauss(0, 1)
temperature = (
state['base_temp'] +
state['trend'] * iteration_offset +
5 * math.sin(iteration_offset) +
noise
)
# Simulate humidity
humidity = (
state['base_humidity'] +
15 * math.sin(iteration_offset + math.pi) +
random.gauss(0, 2)
)
humidity = max(0, min(100, humidity)) # Clamp to 0-100
# Create payload
payload = {
'sensor_id': sensor_id,
'sensor_name': f"Room {sensor_id.split('_')[1]}",
'temperature': round(temperature, 2),
'humidity': round(humidity, 2),
'timestamp': time.time()
}
# Publish
topic = f"sensors/{sensor_id}"
self.client.publish(
topic,
json.dumps(payload),
qos=1
)
logger.debug(
f"{sensor_id}: {temperature:.2f}°C, {humidity:.2f}%"
)
iteration += 1
time.sleep(1)
def start(self):
"""Start sensor simulator"""
self.connect()
thread = threading.Thread(
target=self.publish_sensor_data,
daemon=True
)
thread.start()
logger.info(f"Simulator started with {self.num_sensors} sensors")
return thread
def stop(self):
"""Stop simulator"""
self.running = False
self.client.loop_stop()
logger.info("Simulator stopped")
def main():
"""Run simulator"""
simulator = SensorSimulator(
broker_address="localhost",
broker_port=1883,
num_sensors=3
)
try:
thread = simulator.start()
thread.join()
except KeyboardInterrupt:
logger.info("Shutting down...")
simulator.stop()
if __name__ == "__main__":
main()
6. Docker Compose for MQTT Broker
# docker-compose.yml
version: '3.8'
services:
mosquitto:
image: eclipse-mosquitto:2
container_name: mqtt_broker
ports:
- "1883:1883"
- "9001:9001"
volumes:
- ./mosquitto/config:/mosquitto/config
- ./mosquitto/data:/mosquitto/data
- ./mosquitto/log:/mosquitto/log
environment:
- TZ=UTC
networks:
- mqtt_network
networks:
mqtt_network:
driver: bridge
7. Usage Guide
# 1. Start MQTT broker
docker-compose up -d
# 2. In Terminal 1 - Run sensor simulator
python sensor_simulator.py
# 3. In Terminal 2 - Run visualizer
python mqtt_visualizer_main.py
8. Advanced Features Example
# advanced_features.py
"""Advanced features for the visualizer"""
import statistics
from collections import deque
from datetime import datetime, timedelta
class AnalyticsEngine:
"""Analyze sensor data trends"""
def __init__(self, window_size: int = 30):
self.window_size = window_size
self.data_windows = {}
def add_reading(self, sensor_id: str, temperature: float):
"""Add temperature reading"""
if sensor_id not in self.data_windows:
self.data_windows[sensor_id] = deque(maxlen=self.window_size)
self.data_windows[sensor_id].append(temperature)
def get_statistics(self, sensor_id: str) -> dict:
"""Calculate statistics for sensor"""
if sensor_id not in self.data_windows:
return {}
data = list(self.data_windows[sensor_id])
if not data:
return {}
return {
'mean': statistics.mean(data),
'median': statistics.median(data),
'stdev': statistics.stdev(data) if len(data) > 1 else 0,
'min': min(data),
'max': max(data),
'trend': self._calculate_trend(data)
}
def _calculate_trend(self, data: list) -> str:
"""Calculate temperature trend"""
if len(data) < 2:
return "STABLE"
recent = statistics.mean(data[-5:])
older = statistics.mean(data[:5])
diff = recent - older
if diff > 1:
return "RISING"
elif diff < -1:
return "FALLING"
else:
return "STABLE"
class AlertManager:
"""Manage alerts with persistence"""
def __init__(self, max_alerts: int = 1000):
self.alerts = deque(maxlen=max_alerts)
self.alert_counts = {}
def log_alert(self, sensor_id: str, alert_type: str, message: str):
"""Log an alert"""
alert = {
'timestamp': datetime.now(),
'sensor_id': sensor_id,
'type': alert_type,
'message': message
}
self.alerts.append(alert)
# Track alert frequency
key = f"{sensor_id}:{alert_type}"
self.alert_counts[key] = self.alert_counts.get(key, 0) + 1
def get_recent_alerts(self, minutes: int = 10) -> list:
"""Get alerts from last N minutes"""
cutoff = datetime.now() - timedelta(minutes=minutes)
return [
a for a in self.alerts
if a['timestamp'] > cutoff
]
def get_top_alerts(self, limit: int = 5) -> list:
"""Get most frequent alerts"""
return sorted(
self.alert_counts.items(),
key=lambda x: x[1],
reverse=True
)[:limit]
class DataExporter:
"""Export sensor data to various formats"""
@staticmethod
def export_csv(sensor_data: dict, filename: str = "sensor_data.csv"):
"""Export to CSV"""
import csv
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Timestamp', 'Sensor', 'Temperature', 'Humidity'])
for sensor_id, data in sensor_data.items():
for reading in data:
writer.writerow([
reading['time'].isoformat(),
sensor_id,
reading['temp'],
reading['humidity']
])
@staticmethod
def export_json(sensor_data: dict, filename: str = "sensor_data.json"):
"""Export to JSON"""
import json
from datetime import datetime
data = {}
for sensor_id, readings in sensor_data.items():
data[sensor_id] = [
{
'time': r['time'].isoformat(),
'temp': r['temp'],
'humidity': r['humidity']
}
for r in readings
]
with open(filename, 'w') as f:
json.dump(data, f, indent=2)
Key Features:
✅ Priority Queue Management
- Critical alerts prioritized automatically
- Efficient task scheduling
✅ Real-Time Visualization
- Live temperature plotting
- Humidity tracking
- Alert history
✅ Threading Safety
- Lock-protected data access
- Daemon threads
✅ MQTT Integration
- Paho-MQTT subscriber
- QoS support
- Automatic reconnection
✅ Analytics
- Trend detection
- Statistics calculation
- Alert frequency tracking
✅ Data Export
This production-ready system handles real-time sensor monitoring with proper synchronization!