Bird
0
0

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'?

medium📝 Predict Output Q13 of 15
Raspberry Pi - MQTT for IoT

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()
ALight status: b'ON'
BLight status: ON
CLight status: None
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand message payload decoding

    The payload is a byte string, so msg.payload.decode() converts it to a normal string, here 'ON'.
  2. Step 2: Check print statement output

    The print uses an f-string to show "Light status: ON" exactly when the topic matches.
  3. Final Answer:

    Light status: ON -> Option B
  4. Quick Check:

    Decoded payload prints as string [OK]
Quick Trick: Decode payload bytes to string before printing [OK]
Common Mistakes:
MISTAKES
  • Printing raw bytes without decoding
  • Not subscribing to the correct topic
  • Missing the on_message callback assignment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes