Which code snippet correctly subscribes to both and handles messages differently based on the topic?
hard🚀 Application Q15 of 15
Raspberry Pi - MQTT for IoT
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?
Aclient.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
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]
Quick Trick:Subscribe with list and check message.topic [OK]
Common Mistakes:
MISTAKES
Passing multiple topics as separate arguments
Checking payload instead of topic for routing
Subscribing after setting callback incorrectly
Master "MQTT for IoT" in Raspberry Pi
9 interactive learning modes - each teaches the same concept differently