After completing this chapter, you will be able to:
Implement MQTT publish/subscribe messaging using Python and a public broker
Build an end-to-end IoT data pipeline from sensor simulation through MQTT, InfluxDB, and Grafana
Apply structured lab methodologies with clear objectives, validation checkpoints, and success criteria
Select appropriate lab exercises based on your skill level (beginner, intermediate, or advanced)
For Beginners: Hands-On Labs
These labs are guided experiments where you build real IoT systems step by step. Each lab tells you exactly what you need, walks you through the process, and includes checkpoints to verify you are on track. Even if you have never programmed a microcontroller before, the beginner labs start with the basics – like sending your first message between two devices – and gradually build up to more complex projects.
In 60 Seconds
Structured laboratory exercises spanning beginner to advanced levels, including MQTT messaging, sensor data pipelines (MQTT to InfluxDB to Grafana), LoRaWAN simulation, sensor calibration, TLS security setup, and edge computing architecture labs. Each lab includes objectives, materials, step-by-step instructions, and validation checkpoints.
Chapter Scope (Avoiding Duplicate Hubs)
This chapter focuses on guided lab execution and validation checkpoints.
Use Simulations Hub when you need exploratory experimentation before implementation.
Use this chapter when you are ready to implement, validate, and document practical outcomes.
14.2 Hands-On Labs Hub
Learning by Doing
This hub provides structured laboratory exercises that take you from theory to practice. Each lab includes clear objectives, required materials, step-by-step instructions, and validation checkpoints.
Dual-Track Lab Pattern (Deep + Guided)
To keep labs rigorous and accessible:
Deep prep: Read the underlying theory chapter first.
Guided execution: Follow the lab steps and checkpoints exactly.
Reinforcement: Pair each lab with one simulator run and one quiz/game check.
Transfer: Write one design decision based on measured results.
This prevents “copy-paste completion” and builds real engineering judgment.
Reinforcement MappingLong-Term RetentionReinforcement tool:IoT Games Hub
Validation: Challenge completion.
14.5 Networking & Protocols Labs
14.5.1 Lab 1: Your First MQTT Message (Beginner)
Lab Overview
Duration: 45 minutes | Difficulty: Beginner
Learning Objectives:
Understand publish/subscribe messaging pattern
Connect to an MQTT broker
Send and receive messages programmatically
Observe message flow in real-time
Materials Needed:
Computer with Python 3.8+
Internet connection
Text editor or IDE
Prerequisites: Basic Python knowledge
14.5.1.1 Step 1: Environment Setup (10 min)
# Install the MQTT client librarypip install paho-mqtt# Verify installationpython-c"import paho.mqtt.client as mqtt; print('MQTT library ready!')"
14.5.1.2 Step 2: Connect to Public Broker (10 min)
Create a file called mqtt_subscriber.py:
import paho.mqtt.client as mqtt# Callback when connecteddef on_connect(client, userdata, flags, rc):print(f"Connected with result code {rc}")# Subscribe to a test topic client.subscribe("iotclass/lab1/temperature")# Callback when message receiveddef on_message(client, userdata, msg):print(f"Received: {msg.topic} -> {msg.payload.decode()}")# Create client and set callbacksclient = mqtt.Client()client.on_connect = on_connectclient.on_message = on_message# Connect to public broker (test.mosquitto.org)client.connect("test.mosquitto.org", 1883, 60)# Start listeningprint("Waiting for messages... Press Ctrl+C to stop")client.loop_forever()
Putting Numbers to It
MQTT publish/subscribe messaging adds protocol overhead to every message. For a 20-byte sensor payload, the total packet size includes MQTT headers.
Extension project: Multi-gateway simulation and ADR analysis.
Outcome: Multi-protocol expertise.
Application-Specific Paths:
Interview prep (1 week): Lab 1 + Lab 2 + written documentation gives you a 30-minute live demo for technical interviews
Thesis/capstone (1 month): Combine Lab 2 (data pipeline) + Lab 3 (LoRaWAN) + custom ML model for a complete research project
Certification prep (3 hours): Lab 1 + Lab 2 gives hands-on proof of MQTT and time-series database competency
Weekend project (6 hours): Lab 2 with custom sensors (add DHT22 to ESP32) creates a working home monitoring system
Validation Checkpoint: Do NOT skip the “Lab Validation” success criteria at the end of each lab. If you cannot check all boxes, you are not ready to move forward.
Worked Example: Building Lab 2 Sensor Dashboard from Scratch in 90 Minutes
A student with basic Python knowledge wants to complete Lab 2 (Sensor Data Pipeline) in one sitting. Here’s the detailed timeline with actual commands and expected outcomes:
t=0-15 min: Infrastructure Setup
Create project directory: mkdir iot-lab2 && cd iot-lab2
Create docker-compose.yml (copy from lab), mosquitto.conf with 3 lines
Run docker-compose up -d — wait 2 minutes for images to download (first time only)
Verify: docker-compose ps shows all 3 services “Up” (green status)
Expected issue: InfluxDB takes 30 seconds to initialize — if Grafana shows “connection refused,” wait 1 minute
t=15-35 min: Bridge MQTT to InfluxDB
Get InfluxDB token: http://localhost:8086, create admin account, copy API token from Settings → Tokens
Use the Docker service name influxdb, not localhost, and paste the API token you created earlier.
Test connection: should see green “Data source is working” message
Create new dashboard → Add panel → Time series visualization
Flux query builder: FROM bucket “sensors”, FILTER measurement = “sensor_reading”, FILTER _field = “temperature”, aggregate MEAN with 10s window
Add second query for humidity field
Panel title: “Smart Home Sensor Readings”, Y-axis label: “Value”, legend: show field names
Save dashboard as “IoT Lab 2”
Verify: See 3 lines (living_room, bedroom, kitchen temperatures) updating every 5 seconds
Success validation (t=90): Run all 3 terminals (bridge, simulator, Grafana), screenshot shows live updating graph with 10+ minutes of data. All Lab 2 success criteria boxes checked: ✓ Docker containers running, ✓ MQTT → InfluxDB flow, ✓ Grafana real-time dashboard, ✓ Can explain each component’s role.
Common Mistake: Skipping Checkpoint Validation and Debugging for 2 Hours
What they do wrong: A student starts Lab 2, follows the Docker Compose instructions, types docker-compose up -d, sees “done” in the terminal, and immediately jumps to writing the Python bridge script. After 30 minutes of coding, they run the script and get “Connection refused” errors. They spend 2 hours debugging Python code, reinstalling libraries, checking firewalls, and reading InfluxDB documentation — all while the actual problem is that InfluxDB container failed to start due to a port conflict.
Why it fails: Checkpoint 1 in Lab 2 explicitly says “Verify all services are running: docker-compose ps”. The student skipped this 10-second check. If they had run it, they would have seen InfluxDB status: “Restarting” instead of “Up”, indicating a startup failure. Running docker-compose logs influxdb would immediately show “Error: port 8086 already in use by process 4521”. Killing that process and restarting takes 2 minutes.
Correct approach: Treat every lab checkpoint as a STOP sign, not a suggestion. Checkpoints are placed at points where >50% of students encounter issues if they skip validation. For Lab 2: - Checkpoint 1 (t=15 min): Run docker-compose ps and verify all 3 services show “Up” status. If any show “Restarting” or “Exit 1”, STOP and fix before proceeding. - Checkpoint 2 (t=50 min): Run curl http://localhost:8086/ping and expect HTTP 204 response. If connection refused, InfluxDB is not ready — wait 30 seconds and retry. - Checkpoint 3 (t=70 min): Before building the Grafana dashboard, confirm that InfluxDB has data:
If the result is empty, the bridge is not working yet, so fix that before moving to Grafana.
Real-world consequence: A student spent 8 hours on Lab 2 across 3 days, repeatedly restarting from scratch because they never validated intermediate steps. After learning checkpoint discipline, they completed Lab 3 (LoRaWAN, more complex) in 2.5 hours — faster than Lab 2 despite higher difficulty — because they caught 4 issues at checkpoints instead of debugging compound failures.
Match Lab Exercises to Skill Outcomes
Order: Lab Execution with Checkpoint Discipline
Place these lab execution steps in the correct order.
Key Takeaway
Hands-on labs build practical skills that reading alone cannot provide. Follow the progression from beginner (single protocol) to intermediate (full data pipelines) to advanced (multi-technology integration), and always validate your understanding with the success criteria at the end of each lab.
14.11 See Also
Code Snippet Library — Ready-to-use code for lab implementations
Simulations Hub — Practice concepts before hardware labs
Quiz Hub — Validate each lab concept with targeted checks
IoT Games Hub — Reinforce key concepts with short challenge loops
Common Pitfalls
1. Starting Advanced Labs Without Completing Prerequisite Labs
Advanced labs build on skills from foundational labs — they assume you can already set up an MQTT broker, write basic sensor code, and interpret protocol captures. Jumping to advanced labs without prerequisite completion causes frustrating failures that require debugging foundational issues mid-lab.
2. Skipping the Lab Setup Verification Step
Most labs include a “verify your environment” section before the main exercises. Skipping this step to save time results in discovering environmental issues (missing libraries, wrong port, incorrect broker URL) mid-lab, requiring restart. Completing setup verification takes 5 minutes; debugging mid-lab takes 30-60 minutes.
3. Completing Labs Without Documenting Your Findings
Lab exercises produce measurements, configurations, and observations that are valuable for future reference. Completing labs without notes means repeating setup work when you return to a topic or troubleshoot a production system with similar characteristics. Keep a lab notebook with findings, configurations used, and unexpected behaviors observed.
🧠 Knowledge Check
14.12 What’s Next
In the next chapter, we’ll explore the Tool Discovery Hub, which helps you search and filter 280+ interactive simulations, calculators, and visualizations. You’ll learn about:
How to find the right interactive tool for any IoT topic using category and difficulty filters
Prerequisite chains and “learn next” recommendations for structured skill building
Curated tool learning paths for protocol mastery, power optimization, data pipelines, and security design
Before moving on, complete one full lab cycle: 1. Finish a lab with all checkpoints. 2. Run one matching simulator. 3. Complete one quiz or game challenge.
PreviousSimulation Resources Move from simulation planning into practical implementation labs.
CurrentHands-On Labs Hub Stay here when you need structured lab execution, checkpoints, and validation guidance.
NextTool Discovery Hub Continue into the searchable catalog of tools that complement lab work.