Consider this Python code using paho-mqtt to connect to a broker and print connection status.
What will be printed when the client successfully connects?
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected successfully") else: print(f"Connection failed with code {rc}") client = mqtt.Client() client.on_connect = on_connect client.connect("test.mosquitto.org", 1883, 60) client.loop_start()
Check the meaning of rc == 0 in the on_connect callback.
When the client connects successfully, the return code rc is 0, so it prints "Connected successfully".
This code subscribes to topic home/temperature and prints the message payload.
What will be printed if a message with payload 25.5 arrives?
import paho.mqtt.client as mqtt def on_message(client, userdata, msg): print(f"Received message: {msg.payload.decode()}") client = mqtt.Client() client.on_message = on_message client.connect("test.mosquitto.org", 1883, 60) client.subscribe("home/temperature") client.loop_start()
Remember to decode the message payload from bytes to string.
The payload is bytes, so decoding it to string prints the actual message content.
Look at this code snippet. The client subscribes but never receives messages. What is the problem?
import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("test.mosquitto.org", 1883, 60) client.subscribe("home/livingroom") # Missing loop_start or loop_forever call
Check if the client processes network events after subscribing.
The client must run loop_start() or loop_forever() to handle incoming messages. Without it, messages are not received.
Choose the code snippet that publishes the message "Hello" to topic test/topic with QoS level 1.
Check the correct parameter names and valid QoS values (0, 1, or 2).
The publish method uses payload for message and QoS must be 0, 1, or 2. Option C uses correct parameters and QoS 1.
This client subscribes to sensor/# and publishes to sensor/temperature. How many messages will the client receive?
import paho.mqtt.client as mqtt received = [] def on_message(client, userdata, msg): received.append(msg.topic) client = mqtt.Client() client.on_message = on_message client.connect("test.mosquitto.org", 1883, 60) client.subscribe("sensor/#") client.loop_start() client.publish("sensor/temperature", "22.5") import time time.sleep(1) # wait for message client.loop_stop() print(len(received))
Consider if the client receives its own published messages on subscribed topics.
The client subscribes to sensor/#, which matches sensor/temperature. The client receives its own published message, so received has one entry.