MQTT helps many devices talk to each other easily. It is like a post office for small messages between devices.
Multi-device MQTT network in Raspberry Pi
import paho.mqtt.client as mqtt # Create client client = mqtt.Client(client_id) # Connect to broker client.connect(broker_address, port) # Publish message def publish(topic, message): client.publish(topic, message) # Subscribe to topic def on_message(client, userdata, msg): print(f"Received {msg.payload.decode()} on {msg.topic}") client.on_message = on_message client.subscribe(topic) # Start listening client.loop_start()
Use a unique client_id for each device to avoid conflicts.
The broker is the central server that passes messages between devices.
client = mqtt.Client("device1") client.connect("broker.hivemq.com", 1883) client.publish("home/livingroom/temperature", "22")
def on_message(client, userdata, msg): print(f"Got message: {msg.payload.decode()} on topic {msg.topic}") client.on_message = on_message client.subscribe("home/livingroom/temperature") client.loop_start()
This program shows two devices: one sends messages about light status, the other listens and prints them.
import paho.mqtt.client as mqtt import time # Device 1: Publisher client1 = mqtt.Client("device1") client1.connect("broker.hivemq.com", 1883) # Device 2: Subscriber client2 = mqtt.Client("device2") def on_message(client, userdata, msg): print(f"Device2 received: {msg.payload.decode()} on {msg.topic}") client2.on_message = on_message client2.connect("broker.hivemq.com", 1883) client2.subscribe("home/room1/light") client2.loop_start() # Device1 publishes messages for i in range(3): message = f"Light status {i}" print(f"Device1 publishing: {message}") client1.publish("home/room1/light", message) time.sleep(1) client2.loop_stop()
Make sure all devices use the same broker address and topic names to communicate.
MQTT uses small messages, so it works well on low-power devices like Raspberry Pi.
Use client.loop_start() to listen for messages without blocking your program.
MQTT lets many devices send and receive small messages easily.
Each device connects to a broker and uses topics to organize messages.
Use unique client IDs and matching topics for smooth communication.
Practice
What is the main role of the MQTT broker in a multi-device network?
Solution
Step 1: Understand MQTT broker function
The MQTT broker acts as a central hub that receives messages from devices and forwards them to others subscribed to the same topic.Step 2: Eliminate incorrect roles
The broker does not store data permanently, assign IPs, or encrypt messages by default; its main job is message routing.Final Answer:
It routes messages between devices based on topics. -> Option AQuick Check:
MQTT broker = message router [OK]
- Thinking broker stores all data permanently
- Confusing broker with network router
- Assuming broker assigns IP addresses
Which of the following is the correct way to connect a Raspberry Pi MQTT client using the paho-mqtt Python library?
client = mqtt.Client(____)
Solution
Step 1: Identify client ID parameter
Themqtt.Client()constructor takes a unique client ID string to identify the device to the broker.Step 2: Understand other options
Broker address is used inconnect()</>, not inClient()</>. Methods likeconnect()or topics are not valid constructor arguments.Final Answer:
"unique_client_id" -> Option DQuick Check:
Client ID goes in Client() constructor [OK]
- Passing broker address to Client() instead of connect()
- Using method calls as constructor arguments
- Confusing topic names with client ID
Given this Python code snippet using paho-mqtt on a Raspberry Pi, what will be printed when a message with payload 'ON' is received on topic 'home/livingroom/light'?
def on_message(client, userdata, msg):
if msg.topic == 'home/livingroom/light':
print(f"Light status: {msg.payload.decode()}")
client = mqtt.Client("pi1")
client.on_message = on_message
client.connect("broker.local")
client.subscribe("home/livingroom/light")
client.loop_start()Solution
Step 1: Understand message payload decoding
The payload is a byte string, somsg.payload.decode()converts it to a normal string, here 'ON'.Step 2: Check print statement output
The print uses an f-string to show "Light status: ON" exactly when the topic matches.Final Answer:
Light status: ON -> Option BQuick Check:
Decoded payload prints as string [OK]
- Printing raw bytes without decoding
- Not subscribing to the correct topic
- Missing the on_message callback assignment
Identify the error in this MQTT client setup code on a Raspberry Pi:
client = mqtt.Client()
client.connect("broker.local")
client.subscribe("home/kitchen/temperature")
client.loop_forever()
# Missing on_message callback assignmentSolution
Step 1: Check callback assignment
Without assigningclient.on_message, received messages have no handler and won't be processed.Step 2: Verify other parts
Client ID is optional but recommended; subscribe syntax is correct; loop_forever() must be after connect().Final Answer:
The on_message callback is not assigned, so messages won't be processed. -> Option AQuick Check:
Missing on_message means no message handling [OK]
- Ignoring on_message callback assignment
- Thinking client ID is mandatory
- Calling loop_forever() before connect()
You want to control multiple Raspberry Pi devices in different rooms using MQTT. Each device should only receive messages for its room. Which is the best way to organize MQTT topics and client IDs?
- Device 1 in living room
- Device 2 in kitchen
Choose the best topic and client ID setup.
Solution
Step 1: Organize topics by room
Using hierarchical topics likehome/livingroom/#andhome/kitchen/#lets devices subscribe only to their room's messages.Step 2: Assign unique client IDs
Unique client IDs likepi_livingroomandpi_kitchenavoid connection conflicts and identify devices clearly.Final Answer:
Use topics like home/livingroom/# and home/kitchen/# with client IDs pi_livingroom and pi_kitchen. -> Option CQuick Check:
Unique IDs + room topics = clean multi-device MQTT [OK]
- Using same client ID for multiple devices
- Subscribing all devices to a single topic
- Not organizing topics by device location
Ready to prove it?
Pass the test and this pattern moves unknown
