14  Lab: First MQTT Message

mqtt
lab
first
message
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.0.0.1 Step 1: Environment Setup (10 min)

# Install the MQTT client library
pip install paho-mqtt

# Verify installation
python -c "import paho.mqtt.client as mqtt; print('MQTT library ready!')"

14.0.0.2 Step 2: Connect to Public Broker (10 min)

Create a file called mqtt_subscriber.py:

import paho.mqtt.client as mqtt

# Callback when connected
def 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 received
def on_message(client, userdata, msg):
    print(f"Received: {msg.topic} -> {msg.payload.decode()}")

# Create client and set callbacks
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

# Connect to public broker (test.mosquitto.org)
client.connect("test.mosquitto.org", 1883, 60)

# Start listening
print("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.

\[ \text{Total Size} = \text{MQTT Fixed Header (2 bytes)} + \text{Topic Length} + \text{Payload} \]

Worked example: Topic "iotclass/lab1/temperature" = 27 bytes. Payload = 5 bytes ("25.3C"). MQTT QoS 0 overhead = 2-byte fixed header. Total packet size = 2 + 27 + 5 = 34 bytes. For 500 sensors publishing every 15 minutes: 500 × 96 msgs/day × 34 bytes = 1.632 MB/day. At $0.10/MB cellular data cost = $0.16/day or $4.90/month for the entire network.

Try it yourself:

Checkpoint 1

Run the subscriber: python mqtt_subscriber.py

You should see: “Connected with result code 0”

If you see a different code, check your internet connection.

14.0.0.3 Step 3: Publish Messages (15 min)

Create a file called mqtt_publisher.py:

import paho.mqtt.client as mqtt
import time
import random

client = mqtt.Client()
client.connect("test.mosquitto.org", 1883, 60)

# Simulate temperature readings
for i in range(5):
    temperature = round(20 + random.uniform(-5, 10), 1)
    message = f"{temperature}C"

    client.publish("iotclass/lab1/temperature", message)
    print(f"Published: {message}")
    time.sleep(2)

client.disconnect()
print("Done!")
Checkpoint 2

With subscriber running in one terminal, run publisher in another:

python mqtt_publisher.py

You should see messages appear in the subscriber terminal.

14.0.0.4 Step 4: Experiment (10 min)

Try these modifications:

  1. Change the topic: Use iotclass/lab1/yourname/temperature
  2. Add QoS: Modify publish to use qos=1 for at-least-once delivery, then watch for duplicate-handling implications
  3. JSON payload: Send {"temp": 25.5, "unit": "C"} instead of plain text

14.0.0.5 Lab Validation

Success Criteria

You have completed this lab when you can:

14.0.0.6 What’s Next?