Bird
0
0

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
Bclient.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
Cclient.subscribe("home/lights/control", "home/thermostat/control") def on_message(client, userdata, message): print("Control received") client.on_message = on_message
Dclient.subscribe("home/lights/control") def on_message(client, userdata, message): print("Control received") client.on_message = on_message client.subscribe("home/thermostat/control")
Step-by-Step Solution
Solution:
  1. Step 1: Subscribe to multiple topics correctly

    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.
  2. Step 2: Handle messages based on topic

    The on_message function checks message.topic to differentiate actions.
  3. Final Answer:

    correctly subscribes to both topics and handles them separately -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes