Basic MQTT Messaging with paho-mqtt on Raspberry Pi
📖 Scenario: You have a Raspberry Pi connected to a local network. You want to send and receive simple messages using MQTT, a lightweight messaging protocol often used in IoT projects.MQTT messages are sent to topics on a broker. Your Raspberry Pi will publish a message to a topic and also subscribe to the same topic to receive messages.
🎯 Goal: Build a simple Python program using the paho-mqtt library that connects to a public MQTT broker, publishes a message to a topic, and subscribes to the same topic to receive messages.
📋 What You'll Learn
Create a client using the paho-mqtt library
Connect to the public MQTT broker at test.mosquitto.org
Subscribe to the topic 'test/topic'
Publish the message 'Hello from Raspberry Pi!' to 'test/topic'
Print any messages received on 'test/topic'
💡 Why This Matters
🌍 Real World
MQTT is widely used in IoT devices like sensors and smart home gadgets to send data efficiently over networks.
💼 Career
Understanding MQTT and paho-mqtt is useful for roles in IoT development, embedded systems, and network programming.
Progress0 / 4 steps
1
Import paho-mqtt and create MQTT client
Import the paho.mqtt.client module as mqtt and create a client object called client using mqtt.Client().
Raspberry Pi
Hint
Use import paho.mqtt.client as mqtt to import the library.
Create the client with mqtt.Client().
2
Connect to MQTT broker and subscribe to topic
Use the connect method on client to connect to the broker at 'test.mosquitto.org' on port 1883. Then subscribe to the topic 'test/topic' using client.subscribe('test/topic').
Raspberry Pi
Hint
Use client.connect('test.mosquitto.org', 1883) to connect.
Use client.subscribe('test/topic') to subscribe.
3
Define message callback and publish message
Define a function on_message that takes parameters client, userdata, and msg. Inside it, print the topic and payload as a decoded string. Assign this function to client.on_message. Then publish the message 'Hello from Raspberry Pi!' to 'test/topic' using client.publish.
Raspberry Pi
Hint
Define on_message to print the topic and decoded payload.
Assign it to client.on_message.
Publish with client.publish('test/topic', 'Hello from Raspberry Pi!').
4
Start the MQTT client loop and print output
Start the MQTT client network loop with client.loop_start(). Then add a print statement that outputs exactly "MQTT client started and waiting for messages...".
Raspberry Pi
Hint
Use client.loop_start() to run the MQTT client in the background.
Print the status message exactly as shown.
Practice
(1/5)
1. What is the main purpose of the paho-mqtt library on a Raspberry Pi?
easy
A. To send and receive messages using the MQTT protocol
B. To control the Raspberry Pi's GPIO pins
C. To create a web server on the Raspberry Pi
D. To manage file storage on the Raspberry Pi
Solution
Step 1: Understand MQTT protocol usage
MQTT is a messaging protocol used for sending and receiving messages between devices.
Step 2: Identify paho-mqtt library role
The paho-mqtt library allows Raspberry Pi to connect to MQTT brokers to publish and subscribe messages.
Final Answer:
To send and receive messages using the MQTT protocol -> Option A
Quick Check:
paho-mqtt = MQTT messaging [OK]
Hint: Remember: paho-mqtt is for MQTT messaging only [OK]
Common Mistakes:
Confusing paho-mqtt with GPIO control libraries
Thinking it manages web servers
Assuming it handles file storage
2. Which of the following is the correct way to import the paho-mqtt client in Python?
easy
A. import mqtt.paho.client
B. import paho_mqtt_client as mqtt
C. import paho.mqtt.client as mqtt
D. import paho.mqtt as client
Solution
Step 1: Recall correct import syntax
The official paho-mqtt Python client is imported as import paho.mqtt.client as mqtt.
Step 2: Check other options
Other options use incorrect module names or syntax.
Final Answer:
import paho.mqtt.client as mqtt -> Option C
Quick Check:
Correct import = import paho.mqtt.client as mqtt [OK]
Hint: Use dots for module import, underscores are wrong here [OK]
Common Mistakes:
Using underscores instead of dots in import
Swapping module parts order
Importing incomplete module path
3. What will the following code print when a message is received on topic 'test/topic'?
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print(f"Received '{msg.payload.decode()}' on topic '{msg.topic}'")
client = mqtt.Client()
client.on_message = on_message
client.connect('broker.hivemq.com', 1883)
client.subscribe('test/topic')
client.loop_start()
# Assume a message with payload 'Hello' is published to 'test/topic'
medium
A. Received b'Hello' on topic 'test/topic'
B. Received 'Hello' on topic 'test/topic'
C. Received 'Hello' on topic 'broker.hivemq.com'
D. No output because loop_start() is missing
Solution
Step 1: Understand on_message callback
The callback decodes the message payload bytes to string and prints it with the topic.
Step 2: Check code behavior on receiving 'Hello'
The payload 'Hello' is decoded and printed with the subscribed topic 'test/topic'.
Final Answer:
Received 'Hello' on topic 'test/topic' -> Option B
Quick Check:
Decoded payload + topic = Received 'Hello' on topic 'test/topic' [OK]
Hint: Decode payload bytes to string before printing [OK]
Common Mistakes:
Printing raw bytes without decoding
Confusing topic with broker address
Forgetting to start the loop
4. Identify the error in this MQTT client setup code:
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
client.subscribe('home/temperature')
client.on_message = lambda c, u, m: print(m.payload)
# Missing client.loop_forever()
medium
A. The on_message callback is assigned after subscribe()
B. The subscribe topic is invalid
C. The broker address is incorrect
D. The client loop method to process network events is missing
Solution
Step 1: Check client loop usage
MQTT client needs a loop method like loop_forever() or loop_start() to process messages.
Step 2: Verify other parts
Assigning on_message after subscribe is allowed; broker and topic are valid.
Final Answer:
The client loop method to process network events is missing -> Option D
Quick Check:
Missing loop = no message processing [OK]
Hint: Always run client.loop_start() or loop_forever() after setup [OK]
Common Mistakes:
Not running the client loop to handle messages
Thinking on_message must be set before subscribe
Assuming broker or topic is wrong without checking
5. You want your Raspberry Pi to publish temperature data every 10 seconds to topic 'home/temperature' using paho-mqtt. Which code snippet correctly implements this with proper connection, publishing, and loop handling?
A)
import paho.mqtt.client as mqtt
import time
client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
while True:
client.publish('home/temperature', '22.5')
time.sleep(10)
B)
import paho.mqtt.client as mqtt
import time
client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
client.loop_start()
while True:
client.publish('home/temperature', '22.5')
time.sleep(10)
C)
import paho.mqtt.client as mqtt
import time
client = mqtt.Client()
client.loop_start()
client.connect('broker.hivemq.com', 1883)
while True:
client.publish('home/temperature', '22.5')
time.sleep(10)
D)
import paho.mqtt.client as mqtt
import time
client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
client.loop_forever()
while True:
client.publish('home/temperature', '22.5')
time.sleep(10)
hard
A. Connect, start loop, then publish in a loop
B. Connect and publish without starting the loop
C. Start loop before connecting, then publish
D. Use loop_forever() which blocks before publishing
Solution
Step 1: Understand client loop and connection order
Client must connect first, then start the network loop with loop_start() to handle background MQTT tasks.
Step 2: Check each option's order and behavior
Connect and publish without starting the loop connects and publishes without starting the loop, missing network processing. Connect, start loop, then publish in a loop correctly connects, starts loop, then publishes repeatedly. Start loop before connecting, then publish starts loop before connect (incorrect order). Use loop_forever() which blocks before publishing blocks with loop_forever() preventing publishing.
Final Answer:
Connect, start loop, then publish in a loop -> Option A
Quick Check:
Connect -> loop_start() -> publish loop = Connect, start loop, then publish in a loop [OK]
Hint: Always connect before loop_start(), loop_forever() blocks code [OK]
Common Mistakes:
Starting loop before connecting
Not starting loop at all
Using loop_forever() which blocks publishing code
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.