Bird
0
0

Given this MQTT subscription code on a Raspberry Pi, what will be printed when a message arrives?

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

Given this MQTT subscription code on a Raspberry Pi, what will be printed when a message arrives?

def on_message(client, userdata, msg):
    print(f"Topic: {msg.topic}, Message: {msg.payload.decode()}")

client.subscribe("home/livingroom/temperature")
client.on_message = on_message

ANo output because on_message is not called
BTopic: home/livingroom/temperature, Message: 22.5
CTopic: home/livingroom/temperature, Message: b'22.5'
DTopic: home/livingroom, Message: temperature
Step-by-Step Solution
Solution:
  1. Step 1: Understand on_message callback

    When a message arrives, on_message prints the topic and decoded payload string.
  2. Step 2: Decode payload bytes to string

    msg.payload.decode() converts bytes to string, so output shows readable message like '22.5'.
  3. Final Answer:

    Topic: home/livingroom/temperature, Message: 22.5 -> Option B
  4. Quick Check:

    Decoded payload prints as string, not bytes [OK]
Quick Trick: Decode payload bytes to string before printing [OK]
Common Mistakes:
MISTAKES
  • Printing raw bytes without decode
  • Confusing topic string
  • Assuming callback not triggered

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes