Consider a Raspberry Pi subscribing to an MQTT topic home/lights/control. The callback prints the received message payload.
What will be printed when the message payload is ON?
import paho.mqtt.client as mqtt def on_message(client, userdata, msg): print(f"Received message: {msg.payload.decode()}") client = mqtt.Client() client.on_message = on_message client.connect("broker.hivemq.com", 1883, 60) client.subscribe("home/lights/control") # Simulate receiving a message class Msg: payload = b"ON" on_message(client, None, Msg())
Remember that MQTT message payloads are bytes and need decoding.
The msg.payload is a bytes object. Using decode() converts it to a string. So the printed message is exactly Received message: ON.
You want your Raspberry Pi to subscribe to all control topics under home, such as home/lights/control and home/thermostat/control. Which subscription topic pattern should you use?
The plus sign + matches exactly one topic level.
The pattern home/+/control matches topics with exactly three levels where the middle level can be anything, like home/lights/control. The # wildcard matches all subtopics but would include unwanted topics.
The Raspberry Pi subscribes to home/lights/control but the callback never prints any message. What is the problem?
import paho.mqtt.client as mqtt def on_message(client, userdata, msg): print(f"Message: {msg.payload.decode()}") client = mqtt.Client() client.on_message = on_message client.connect("broker.hivemq.com", 1883, 60) client.subscribe("home/lights/control") # Missing client.loop_forever() or client.loop_start() here
MQTT clients need to run a loop to receive messages.
Without calling client.loop_start() or client.loop_forever(), the client does not listen for incoming messages, so the callback is never triggered.
You want to subscribe your Raspberry Pi MQTT client to home/lights/control and home/thermostat/control in one call. Which code is correct?
Refer to the Paho MQTT subscribe method for multiple topics.
The subscribe() method accepts a list of tuples for multiple topics with QoS. Option B uses the correct syntax. Option B is invalid because subscribe expects one topic or a list. Option B uses a dict which is not accepted. Option B calls subscribe twice, not one call.
Your Raspberry Pi subscribes to home/+/control. The broker publishes messages to these topics:
- home/lights/control
- home/thermostat/control
- home/lights/status
- home/garden/control
- home/lights/control/extra
How many messages will your client receive?
The plus sign + matches exactly one topic level.
The subscription home/+/control matches topics with exactly three levels where the middle level can be anything. The matching topics are home/lights/control, home/thermostat/control, and home/garden/control. The topic home/lights/status does not match because last level is not 'control'. The topic home/lights/control/extra has four levels and does not match.