Bird
0
0

What will the following code print when a message is received on topic 'test/topic'?

medium📝 Predict Output Q13 of 15
Raspberry Pi - MQTT for IoT
What will the following code print when a message is received on topic 'test/topic'?
import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    print(f"Received '{msg.payload.decode()}' on topic '{msg.topic}'")

client = mqtt.Client()
client.on_message = on_message
client.connect('broker.hivemq.com', 1883)
client.subscribe('test/topic')
client.loop_start()

# Assume a message with payload 'Hello' is published to 'test/topic'
AReceived b'Hello' on topic 'test/topic'
BReceived 'Hello' on topic 'test/topic'
CReceived 'Hello' on topic 'broker.hivemq.com'
DNo output because loop_start() is missing
Step-by-Step Solution
Solution:
  1. Step 1: Understand on_message callback

    The callback decodes the message payload bytes to string and prints it with the topic.
  2. Step 2: Check code behavior on receiving 'Hello'

    The payload 'Hello' is decoded and printed with the subscribed topic 'test/topic'.
  3. Final Answer:

    Received 'Hello' on topic 'test/topic' -> Option B
  4. Quick Check:

    Decoded payload + topic = Received 'Hello' on topic 'test/topic' [OK]
Quick Trick: Decode payload bytes to string before printing [OK]
Common Mistakes:
MISTAKES
  • Printing raw bytes without decoding
  • Confusing topic with broker address
  • Forgetting to start the loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes