C. Missing client.connect() call before subscribing
D. on_message function not defined
Solution
Step 1: Check connection setup
MQTT client must connect to broker before subscribing.
Step 2: Identify missing connect call
The code lacks client.connect(), so subscription won't work.
Final Answer:
Missing client.connect() call before subscribing -> Option C
Quick Check:
Connect before subscribe to receive messages [OK]
Hint: Always connect client before subscribing to topics [OK]
Common Mistakes:
Skipping client.connect() call
Assuming subscribe works without connection
Confusing loop_start() with connection
5. You want your IoT device to subscribe to control commands on topic home/lights/command and turn lights ON or OFF accordingly. Which code snippet correctly subscribes and handles these commands in Python using MQTT?
hard
A. client = mqtt.Client()
client.connect('broker.hivemq.com')
client.subscribe('home/lights/command')
client.loop_forever()
B. client = mqtt.Client()
client.subscribe('home/lights/command')
client.on_message = lambda c,u,m: print('Lights ON' if m.payload == 'ON' else 'Lights OFF')
client.loop_start()
C. def on_message(client, userdata, message):
if message.payload == 'ON':
print('Lights ON')
client = mqtt.Client()
client.connect('broker.hivemq.com')
client.subscribe('home/lights/command')
client.on_message = on_message
client.loop_forever()