These MQTT labs provide complete, runnable code for building IoT systems: ESP32 temperature/humidity publishers with configurable QoS, real-time Python dashboards for data visualization, multi-device home automation with motion-triggered lighting, and systematic debugging exercises for common MQTT connection and delivery issues.
28.1 Learning Objectives
By the end of these labs, you will be able to:
Implement ESP32 MQTT Publishers: Configure and deploy temperature/humidity sensors publishing sensor data to MQTT topics with appropriate QoS levels
Construct Python MQTT Dashboards: Build real-time data visualization subscribers that aggregate and display multi-sensor data streams
Design Multi-Device Home Automation: Architect and develop MQTT-based publish/subscribe communication between motion sensors and actuators
Diagnose MQTT Connection Failures: Systematically analyze and resolve common connection, subscription, and message delivery problems using structured debugging techniques
Evaluate QoS Trade-offs: Compare the energy, bandwidth, and reliability implications of QoS 0, 1, and 2 to justify the appropriate level for a given IoT application
Calculate MQTT Bandwidth and Energy Costs: Apply formulas to estimate network throughput and battery life for sensor fleets under different QoS and publish-interval configurations
Key Concepts
MQTT: Message Queuing Telemetry Transport — pub/sub protocol optimized for constrained IoT devices over unreliable networks
Broker: Central server routing messages from publishers to all matching subscribers by topic pattern
Topic: Hierarchical string (e.g., home/bedroom/temperature) used to route messages to interested subscribers
QoS Level: Quality of Service 0/1/2 trading delivery guarantee for message overhead
Retained Message: Last message on a topic stored by broker for immediate delivery to new subscribers
Last Will and Testament: Pre-configured message published by broker when a client disconnects ungracefully
Persistent Session: Broker stores subscriptions and pending messages allowing clients to resume after disconnection
28.2 For Beginners: MQTT Exercises
These exercises let you practice MQTT concepts through guided activities. From setting up your first broker connection to building a complete sensor monitoring system, each exercise builds your confidence and skills with the protocol that powers millions of IoT devices worldwide.
28.3 Lab 1: ESP32 DHT22 MQTT Publisher with QoS Levels
Objective: Build a temperature/humidity sensor that publishes to MQTT with different QoS levels.
Materials:
ESP32 development board
DHT22 temperature/humidity sensor
10k ohm pull-up resistor
Breadboard and jumper wires
Wi-Fi connection
Wiring Map:
DHT22 VCC -> ESP32 3.3V
DHT22 DATA -> ESP32 GPIO 4 with a 10k ohm pull-up resistor to 3.3V
Data replaceability: If the next reading supersedes the current one → QoS 0
Event vs telemetry: One-time events need delivery guarantees → QoS 1
Idempotency: If receiving twice is safe → QoS 1. If receiving twice causes problems → QoS 2
Battery constraints: QoS 0 uses ~50% less power than QoS 1, and ~66% less than QoS 2
Mixed QoS Strategy:
# Single MQTT client can publish different topics with different QoSclient.publish("sensors/temp", temp, qos=0) # Telemetryclient.publish("events/door", "opened", qos=1) # Alertclient.publish("actuators/lock", "unlock", qos=2) # Command
Cost Impact Example (AWS IoT Core, 10,000 devices): - All QoS 0: 432M msgs/month = $432 - All QoS 1: 864M msgs/month = $864 (2x due to PUBACK) - All QoS 2: 1.73B msgs/month = $1,730 (4x due to handshake) - Mixed strategy (95% QoS 0, 4% QoS 1, 1% QoS 2): $490/month → 72% savings vs all-QoS-2
Check Your Understanding: QoS Selection
Putting Numbers to It
QoS level directly impacts battery life for devices transmitting the same data. Calculate the energy cost per message.
Worked example: ESP32 with Wi-Fi radio transmits 100-byte MQTT messages. Radio consumes 240 mA at 3.3V for TX (0.79 W), 100 mA for RX (0.33 W). Each transmission takes 15 ms.
QoS 0 (fire-and-forget): Energy = 0.79 W × 15 ms = 11.85 mJ per message.
QoS 1 (with PUBACK): Energy = (0.79 W × 15 ms TX) + (0.33 W × 12 ms RX for PUBACK) = 11.85 + 3.96 = 15.81 mJ (33% higher).
QoS 2 (4-part handshake): Energy ≈ (0.79 W × 30 ms TX) + (0.33 W × 24 ms RX) = 23.7 + 7.92 = 31.62 mJ (167% higher than QoS 0).
For battery-powered sensor sending 1 msg/minute (60 msgs/hour): QoS 0 uses 711 mJ/hour, QoS 2 uses 1,897 mJ/hour. Over 5-year deployment (43,800 hours), QoS 2 consumes 83.1 kJ vs 31.1 kJ for QoS 0 — requiring 2.7x larger battery.
28.4 Interactive Calculators
28.4.1 QoS Energy Cost Calculator
Estimate the energy cost per MQTT message and projected battery life based on your radio parameters and QoS level.
28.8.1 Exercise 1: Multi-Room Temperature Monitor with CSV Logging
Objective: Extend Lab 1 by adding persistent data logging and multi-room alert thresholds.
Tasks:
Configure two ESP32 publishers for different rooms (living room and bedroom) using distinct topic hierarchies
Create a Python subscriber that logs all readings to a timestamped CSV file
Implement per-room alert thresholds (e.g., bedroom max 25C, living room max 30C)
Add a wildcard subscription (home/+/temperature) to receive from all rooms with a single subscriber
28.8.2 Exercise 2: Secure MQTT with TLS/SSL
Objective: Implement production-grade MQTT security with encryption.
Tasks:
Generate self-signed certificate for local Mosquitto broker
Configure Mosquitto for TLS on port 8883
Create Python MQTT client with TLS
Test that unencrypted connections are rejected
28.8.3 Exercise 3: MQTT-to-Database Pipeline
Objective: Build a complete data ingestion pipeline from MQTT to persistent storage.
Tasks:
Set up SQLite database for time-series sensor data
Create MQTT subscriber that writes to database
Simulate 5 different sensors publishing various metrics
Query database for average temperature over last hour
28.9 Knowledge Check
Quiz: MQTT Labs
28.10 See Also
Lab structure: Each lab builds on the previous, progressing from simple publisher to dashboard subscriber to multi-device automation to secure deployment.
Unencrypted MQTT exposes device credentials and sensor data to network eavesdroppers — in a building IoT deployment on shared WiFi, this means any connected device can read all sensor data. Always enable TLS 1.2+ on the broker and generate unique client certificates for each device class.
2. Ignoring Last Will and Testament Configuration
Without LWT, there is no automatic notification when a device disconnects ungracefully — missed timeout alarms and false-healthy device status are common consequences. Configure LWT on every device connection to publish an offline status message, enabling real-time fleet health monitoring.
3. Using a Single MQTT Connection for High-Throughput Publishing
A single MQTT connection serializes all publishes through one TCP socket — at 100 messages/second with QoS 1, TCP backpressure creates queuing latency. Use multiple parallel MQTT connections or partition topics across connection pools for throughput above 1,000 messages/second.
Label the Diagram
28.11 What’s Next
MQTT Advanced Topics: Focus on broker clustering, high availability, and production deployment. Read it to apply these lab skills to production-scale systems with redundancy and monitoring.
MQTT Security: Focus on TLS/SSL encryption, authentication, and access control lists. Read it to implement the Lab 2 security exercise and lock down broker deployments.
MQTT Python Patterns: Focus on async subscribers, connection pooling, and error handling. Read it to harden the Lab 2 dashboard into production-grade Python code.
MQTT Introduction: Focus on packet structure, retained messages, and topic design. Read it to reconnect the hands-on labs with the protocol theory behind them.
Sensor Integration: Focus on DHT22 wiring, calibration, and reading reliability. Read it to troubleshoot the hardware issues most likely to appear in Lab 1.
ESP32 Prototyping: Focus on breadboard setup, GPIO configuration, and power budgeting. Read it to plan more reliable battery-powered deployments after finishing these labs.