📖 Scenario: You are working on a Raspberry Pi project that listens to control messages sent over MQTT. These messages tell the Pi to perform actions like turning on a light or starting a motor.To do this, you need to subscribe to specific MQTT topics and handle incoming messages.
🎯 Goal: Build a simple Python program that connects to an MQTT broker, subscribes to control topics, and prints the received messages.
📋 What You'll Learn
Create a dictionary called mqtt_config with broker details
Create a list called control_topics with the topics to subscribe
Write a function called on_message to handle incoming messages
Subscribe to the topics in control_topics
Print the received messages with topic and payload
💡 Why This Matters
🌍 Real World
MQTT is widely used in IoT projects to control devices remotely. Subscribing to control topics lets your Raspberry Pi react to commands sent from other devices or apps.
💼 Career
Understanding MQTT and how to subscribe to topics is important for IoT developers, embedded systems engineers, and anyone working with connected devices.
Progress0 / 4 steps
1
Setup MQTT configuration dictionary
Create a dictionary called mqtt_config with these exact entries: 'broker': 'test.mosquitto.org', 'port': 1883, and 'client_id': 'raspberry_pi_client'.
Raspberry Pi
Hint
Use curly braces {} to create a dictionary with keys and values.
2
Create list of control topics
Create a list called control_topics with these exact strings: 'home/livingroom/light' and 'home/kitchen/motor'.
Raspberry Pi
Hint
Use square brackets [] to create a list with the given topic strings.
3
Define message handling function and subscribe
Import paho.mqtt.client as mqtt. Create a client using mqtt.Client(mqtt_config['client_id']). Define a function called on_message that takes client, userdata, and message as parameters and prints Received message on {message.topic}: {message.payload.decode()}. Set this function as the client's on_message callback. Connect the client to mqtt_config['broker'] and mqtt_config['port']. Subscribe to all topics in control_topics using a for loop.
Raspberry Pi
Hint
Use the paho-mqtt library to create a client and subscribe to topics.
4
Start the MQTT client loop and print messages
Start the MQTT client loop with client.loop_start(). Add a print statement print('Subscribed to control topics and waiting for messages...') to show the program is ready.
Raspberry Pi
Hint
Use client.loop_start() to keep the client listening for messages.
Practice
(1/5)
1. What is the main purpose of subscribing to control topics on a Raspberry Pi using MQTT?
easy
A. To send commands from the Raspberry Pi to other devices
B. To update the Raspberry Pi operating system automatically
C. To store data locally on the Raspberry Pi
D. To listen and react to control commands sent to the Raspberry Pi
Solution
Step 1: Understand MQTT subscription
Subscribing means the Raspberry Pi listens to messages on a topic.
Step 2: Identify the purpose of control topics
Control topics send commands that the Raspberry Pi should react to.
Final Answer:
To listen and react to control commands sent to the Raspberry Pi -> Option D
Quick Check:
Subscribing = Listening to commands [OK]
Hint: Subscribing means listening, not sending commands [OK]
Common Mistakes:
Confusing subscribing with publishing
Thinking subscription stores data
Assuming it updates the OS
2. Which of the following is the correct Python syntax to subscribe to an MQTT topic named "home/lights/control" using the Paho MQTT client?
easy
A. client.connect("home/lights/control")
B. client.sub("home/lights/control")
C. client.subscribe("home/lights/control")
D. client.listen("home/lights/control")
Solution
Step 1: Recall Paho MQTT subscribe method
The method to subscribe to a topic is subscribe().
Step 2: Match the correct syntax
Using client.subscribe("home/lights/control") is correct syntax.
Final Answer:
client.subscribe("home/lights/control") -> Option C
Quick Check:
Subscribe method is subscribe() [OK]
Hint: Subscribe uses .subscribe(), not .sub() or .listen() [OK]
Common Mistakes:
Using .sub() instead of .subscribe()
Confusing subscribe with connect
Using non-existent methods like .listen()
3. Given the following code snippet, what will be printed when a message with payload "ON" is received on the topic "home/lights/control"?
Before subscribing, the client must connect to the MQTT broker.
Step 2: Identify missing connect call
The code lacks client.connect() call, so subscription won't work.
Final Answer:
Missing client.connect() before subscribing -> Option B
Quick Check:
Must connect before subscribe [OK]
Hint: Always connect client before subscribing [OK]
Common Mistakes:
Skipping client.connect() call
Confusing callback function names
Thinking loop_start() is wrong here
5. You want your Raspberry Pi to subscribe to multiple control topics: "home/lights/control" and "home/thermostat/control". Which code snippet correctly subscribes to both and handles messages differently based on the topic?
hard
A. client.subscribe(["home/lights/control", "home/thermostat/control"])
def on_message(client, userdata, message):
topic = message.topic
if topic == "home/lights/control":
print("Light control received")
elif topic == "home/thermostat/control":
print("Thermostat control received")
client.on_message = on_message
B. client.subscribe("home/lights/control")
client.subscribe("home/thermostat/control")
def on_message(client, userdata, message):
if message.payload == "light":
print("Light control")
else:
print("Thermostat control")
client.on_message = on_message
client.subscribe(["home/lights/control", "home/thermostat/control"])
def on_message(client, userdata, message):
topic = message.topic
if topic == "home/lights/control":
print("Light control received")
elif topic == "home/thermostat/control":
print("Thermostat control received")
client.on_message = on_message uses a list to subscribe to both topics at once, which is valid.
Step 2: Handle messages based on topic
The on_message function checks message.topic to differentiate actions.
Final Answer:
correctly subscribes to both topics and handles them separately -> Option A
Quick Check:
Subscribe list + topic check = correct [OK]
Hint: Subscribe with list and check message.topic [OK]
Common Mistakes:
Passing multiple topics as separate arguments
Checking payload instead of topic for routing
Subscribing after setting callback incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.