%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#ecf0f1'}}}%%
sequenceDiagram
participant ESP32
participant Broker as MQTT Broker<br/>(test.mosquitto.org)
participant Laptop
ESP32->>ESP32: Read DHT22<br/>Temp: 24C
ESP32->>Broker: Publish to<br/>iot/sensors/temperature
Note right of Broker: Message stored
Laptop->>Broker: Subscribe to<br/>iot/sensors/temperature
Broker->>Laptop: Forward message<br/>24C
Note over ESP32,Laptop: Temperature > 25C triggers alert
ESP32->>Broker: Publish 26C
Broker->>Laptop: Alert: High temp!
1203 MQTT Implementation - Getting Started
1203.1 Learning Objectives
By the end of this chapter, you will be able to:
- Understand MQTT System Components: Identify the three essential parts (broker, publisher, subscriber) and how they connect
- Use Browser Simulators: Run MQTT code in Wokwi simulators without any hardware setup
- Build Your First Publisher: Create a Python script that sends sensor data to an MQTT broker
- Build Your First Subscriber: Create a Python script that receives and displays MQTT messages
- Choose Your Learning Path: Decide between simulator-based learning and real hardware projects
1203.2 Prerequisites
Before diving into this chapter, you should be familiar with:
- MQTT Fundamentals: Understanding MQTT architecture, publish-subscribe patterns, topics, and basic protocol operations is essential before implementing practical applications
- MQTT QoS and Session: Knowledge of Quality of Service levels (QoS 0, 1, 2) and session management (clean vs persistent) helps in choosing appropriate configurations for different use cases
- Programming fundamentals: Basic experience with Python helps work through the code examples
1203.3 Getting Started (For Beginners)
1203.3.1 What Will You Learn in This Chapter? (Simple Explanation)
In previous chapters, you learned what MQTT is (the theory). In this chapter, you’ll learn how to actually build MQTT applications (the practice).
Analogy: It’s like learning to drive a car.
- Previous chapters = Driving theory (how gears work, traffic rules, car parts)
- This chapter = Getting behind the wheel and actually driving!
1203.3.2 The Three Essential MQTT Components
Every MQTT system needs three parts:
| Component | Role | Simple Analogy | Your Implementation |
|---|---|---|---|
| MQTT Broker | Message post office | Central mailbox at your street | Mosquitto, HiveMQ, test.mosquitto.org |
| Publisher | Sends messages | Someone dropping letters in mailbox | ESP32 with temperature sensor |
| Subscriber | Receives messages | Someone checking mailbox for letters | Python dashboard on your laptop |
Simple flow:
ESP32 (Publisher) → Broker (test.mosquitto.org) → Your Laptop (Subscriber)
"Temp: 24°C" [Routes message] "Display: 24°C"
1203.3.3 Your First MQTT Project: What You’ll Build
Goal: Create a complete IoT temperature monitoring system.
What happens: 1. ESP32 reads temperature from DHT22 sensor every 10 seconds 2. ESP32 publishes temperature to topic: iot/sensors/temperature 3. Broker (test.mosquitto.org) receives and stores the message 4. Your laptop subscribes to iot/sensors/temperature and displays readings 5. Bonus: Alert system triggers when temperature > 25C
Visual flow:
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22'}}}%%
graph LR
subgraph Hardware["Hardware Layer"]
ESP["ESP32<br/>Wi-Fi + GPIO"]
DHT["DHT22<br/>Temp/Humidity"]
end
subgraph Network["Network Layer"]
Wi-Fi["Wi-Fi<br/>Connection"]
BROKER["MQTT Broker<br/>test.mosquitto.org"]
end
subgraph Application["Application Layer"]
CLI["CLI Client<br/>mosquitto_sub"]
DASH["Dashboard<br/>Web UI"]
end
DHT --> ESP --> Wi-Fi --> BROKER
BROKER --> CLI
BROKER --> DASH
style Hardware fill:#E67E22,stroke:#2C3E50
style Network fill:#16A085,stroke:#2C3E50
style Application fill:#2C3E50,stroke:#16A085
This diagram shows the three-layer lab architecture: hardware (ESP32 + sensor), network (Wi-Fi + MQTT broker), and application (monitoring tools).
1203.3.4 Two Ways to Try MQTT (Choose Your Path)
Path 1: Browser Simulator (Easiest) - No hardware needed - Works immediately - Perfect for learning - Not real sensors
How: Scroll down to the “Interactive Simulator” section and click Play!
Path 2: Real Hardware (Best for learning) - Real sensors (actual temperature readings) - Full IoT experience - Can deploy anywhere - Requires ESP32 + DHT22 sensor
Hardware needed: - ESP32 DevKit v1 ($4-7 on Amazon/AliExpress) - DHT22 temperature sensor ($3-5) - Breadboard + jumper wires ($5 for kit) - USB cable (usually included with ESP32)
Total cost: ~$12-20 (reusable for many projects)
1203.3.5 Common Beginner Questions
Q: Do I need to install an MQTT broker on my computer?
A: No! You can use free public brokers like: - test.mosquitto.org (most popular) - broker.hivemq.com - mqtt.eclipseprojects.io
These are perfect for learning and testing. For production projects, you’ll want your own broker.
Q: What’s the difference between ESP32 code and Python code?
A: They do different jobs: - ESP32 code (C/C++): Runs on the microcontroller near your sensor (publisher) - Python code: Runs on your computer to display data (subscriber)
Both talk to the same MQTT broker!
Q: Can multiple devices subscribe to the same topic?
A: Yes! That’s the beauty of MQTT. You can have: - Your laptop showing temperature on a dashboard - Your phone app showing the same data - A database logger saving historical data - An alert system checking for high temperatures
All subscribed to iot/sensors/temperature simultaneously!
Q: What if my Wi-Fi disconnects?
A: MQTT is designed for unreliable networks: - The broker stores messages (if you use QoS > 0) - Your client will automatically reconnect - You won’t lose critical data
This is why MQTT is perfect for IoT (where Wi-Fi isn’t always reliable).
1203.3.6 Self-Check: Are You Ready?
Question: You want to build a soil moisture monitor that sends alerts to your phone when plants need watering. Which component runs where?
Click to see the answer
Answer:
Publisher (ESP32 in the garden): - Reads soil moisture sensor - Publishes to topic: garden/moisture/plant1 - Example message: {"moisture": 45, "status": "needs_water"}
Broker (in the cloud): - test.mosquitto.org or your own broker - Receives messages from ESP32 - Routes to subscribers
Subscriber (on your phone): - Python script or mobile app - Subscribes to garden/moisture/plant1 - Triggers push notification when moisture < 50%
Why this works: - ESP32 stays near the plant (wired to sensor) - Your phone can be anywhere with internet - Broker bridges them across the internet - Multiple family members can all get alerts (multiple subscribers)
Ready to build? The sections below provide three complete implementations:
- Interactive Simulators - No hardware, start immediately
- Python Examples - Publisher/Subscriber code you can run on your laptop
- Lab Exercise - Complete ESP32 project with real sensors
Let’s start with the browser simulator so you can see MQTT in action right now!
1203.4 Interactive Simulator
1203.4.1 Try MQTT in Your Browser
Below is a live ESP32 simulator running MQTT code. You can modify the code and see it work!
{sim id="mqtt-esp32-dht22"}
- Click the green “Play” button to run the simulation
- The ESP32 will connect to a public MQTT broker
- Watch the Serial Monitor for messages
- Try modifying the topic name or message
- No hardware needed - runs entirely in your browser!
1203.5 Example Code: MQTT Publisher
Here’s a complete example using Python to publish temperature data:
# Python MQTT Publisher Example
import paho.mqtt.client as mqtt
import time
import random
# MQTT Broker settings
BROKER = "test.mosquitto.org" # Public test broker
PORT = 1883
TOPIC = "iotclass/sensors/temperature"
# Create MQTT client (paho-mqtt 2.0+ API)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="TempSensor_001")
# Connect to broker
print(f"Connecting to {BROKER}...")
client.connect(BROKER, PORT)
# Publish temperature readings
try:
while True:
# Simulate temperature sensor
temp = round(20 + random.uniform(-5, 5), 2)
# Publish message
client.publish(TOPIC, f"{temp}")
print(f"Published: {temp}C to {TOPIC}")
time.sleep(5) # Wait 5 seconds
except KeyboardInterrupt:
print("Stopping publisher...")
client.disconnect()1203.6 Example Code: MQTT Subscriber
And here’s how to receive those messages:
# Python MQTT Subscriber Example
import paho.mqtt.client as mqtt
BROKER = "test.mosquitto.org"
PORT = 1883
TOPIC = "iotclass/sensors/temperature"
# Callback when connection is established (paho-mqtt 2.0+ signature)
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with reason code {reason_code}")
client.subscribe(TOPIC)
print(f"Subscribed to {TOPIC}")
# Callback when message is received
def on_message(client, userdata, msg):
temp = float(msg.payload.decode())
print(f"Received: {temp}C from {msg.topic}")
# Alert if temperature is too high
if temp > 25:
print("Warning: High temperature detected!")
# Create and configure client (paho-mqtt 2.0+ API)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="Dashboard_001")
client.on_connect = on_connect
client.on_message = on_message
# Connect and start listening
client.connect(BROKER, PORT)
client.loop_forever() # Block and listen for messages1203.7 Lab Exercise: Build a Temperature Monitoring System
Goal: Create a complete IoT system with MQTT
What You’ll Build: - Temperature sensor (publisher) - Dashboard (subscriber) - Alert system (subscriber)
Hardware Needed (or use simulator): - ESP32 or Arduino - DHT22 temperature sensor - Wi-Fi connection
Steps:
- Set up MQTT broker (use free public broker or install Mosquitto)
- Program ESP32 to read temperature and publish to MQTT
- Create Python subscriber to display data
- Add alert system for threshold detection
Starter Code: Use the publisher/subscriber examples above or try the simulator!
1203.8 Summary
This chapter introduced the fundamentals of MQTT implementation:
- Three Core Components: Every MQTT system needs a broker (message router), publisher (data sender), and subscriber (data receiver)
- Browser Simulators: Wokwi provides free, hardware-free MQTT experimentation with real ESP32 code execution
- Python Publisher/Subscriber: The paho-mqtt library enables easy MQTT client creation with just 15-20 lines of code
- Public Brokers: test.mosquitto.org and similar free brokers are perfect for learning (but not for production)
- Learning Paths: Choose between simulator-based learning (no hardware) or real ESP32 projects ($12-20 investment)
1203.9 What’s Next
Continue with MQTT Python Patterns and Security to learn production-ready coding patterns, error handling, and security considerations. Then progress to MQTT Hands-On Labs for complete ESP32 projects with sensors, home automation, and TLS security configuration.