Bird
Raised Fist0
Raspberry Piprogramming~10 mins

Subscribing to control topics in Raspberry Pi - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Subscribing to control topics
Start Program
↓
Initialize MQTT Client
↓
Connect to Broker
↓
Subscribe to Control Topic
↓
Wait for Messages
↓
On Message Received
↓
Process Control Command
↓
Loop Back to Wait
The program starts, connects to the MQTT broker, subscribes to control topics, waits for messages, and processes commands when received.
Execution Sample
Raspberry Pi
import paho.mqtt.client as mqtt

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

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
client.subscribe("home/control")
client.loop_forever()
This code connects to a public MQTT broker, subscribes to the 'home/control' topic, and prints any received messages.
Execution Table
StepActionEvaluationResult
1Import MQTT librarySuccesspaho.mqtt.client module ready
2Define on_message callbackFunction createdReady to handle messages
3Create MQTT clientClient object createdClient ready
4Assign on_message callbackCallback setClient will handle messages
5Connect to brokerConnection attemptConnected to broker.hivemq.com:1883
6Subscribe to 'home/control'Subscription request sentSubscribed successfully
7Start loop_foreverListening for messagesWaiting for messages
8Message received on 'home/control'Trigger on_messagePrint message content
9Process messagePrint outputOutput: Received: home/control -> <message>
10Loop continuesWait for next messageReady for next message
💡 Program runs indefinitely until manually stopped
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 6After Step 8
clientNoneMQTT Client objectConnected clientSubscribed clientClient with message callback triggered
Key Moments - 3 Insights
Why do we assign the on_message function to client.on_message?
Assigning on_message to client.on_message tells the client what to do when a message arrives, as shown in step 4 and triggered in step 8.
What happens if the client does not subscribe to the topic?
If the client does not subscribe (step 6), it will not receive messages on that topic, so on_message will never be called.
Why does the program use loop_forever()?
loop_forever() (step 7) keeps the program running and listening for messages continuously, as explained in the exit note.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the client variable after step 5?
ADisconnected client object
BConnected client object
CNone
DSubscribed client object
💡 Hint
Check variable_tracker column 'After Step 5' and execution_table step 5
At which step does the program start listening for messages?
AStep 4
BStep 6
CStep 7
DStep 8
💡 Hint
Look at execution_table step 7 description
If the subscription to 'home/control' is removed, what changes in the execution?
Aon_message will never be triggered
BClient will not connect to broker
CProgram will crash at step 6
DMessages will still be received
💡 Hint
Refer to key_moments question 2 and execution_table step 6
Concept Snapshot
Subscribing to control topics with MQTT:
- Import MQTT client library
- Define on_message callback to handle messages
- Connect client to broker
- Subscribe to control topic
- Use loop_forever() to listen continuously
- on_message triggers on receiving messages
Full Transcript
This example shows how a Raspberry Pi program subscribes to control topics using MQTT. First, it imports the MQTT library and defines a function to handle incoming messages. Then, it creates an MQTT client, assigns the message handler, and connects to a broker. After subscribing to the 'home/control' topic, the program enters a loop waiting for messages. When a message arrives, the on_message function runs and prints the message. The program keeps running until stopped.

Practice

(1/5)
1. What is the main purpose of subscribing to control topics on a Raspberry Pi using MQTT?
easy
A. To send commands from the Raspberry Pi to other devices
B. To update the Raspberry Pi operating system automatically
C. To store data locally on the Raspberry Pi
D. To listen and react to control commands sent to the Raspberry Pi

Solution

  1. Step 1: Understand MQTT subscription

    Subscribing means the Raspberry Pi listens to messages on a topic.
  2. Step 2: Identify the purpose of control topics

    Control topics send commands that the Raspberry Pi should react to.
  3. Final Answer:

    To listen and react to control commands sent to the Raspberry Pi -> Option D
  4. Quick Check:

    Subscribing = Listening to commands [OK]
Hint: Subscribing means listening, not sending commands [OK]
Common Mistakes:
  • Confusing subscribing with publishing
  • Thinking subscription stores data
  • Assuming it updates the OS
2. Which of the following is the correct Python syntax to subscribe to an MQTT topic named "home/lights/control" using the Paho MQTT client?
easy
A. client.connect("home/lights/control")
B. client.sub("home/lights/control")
C. client.subscribe("home/lights/control")
D. client.listen("home/lights/control")

Solution

  1. Step 1: Recall Paho MQTT subscribe method

    The method to subscribe to a topic is subscribe().
  2. Step 2: Match the correct syntax

    Using client.subscribe("home/lights/control") is correct syntax.
  3. Final Answer:

    client.subscribe("home/lights/control") -> Option C
  4. Quick Check:

    Subscribe method is subscribe() [OK]
Hint: Subscribe uses .subscribe(), not .sub() or .listen() [OK]
Common Mistakes:
  • Using .sub() instead of .subscribe()
  • Confusing subscribe with connect
  • Using non-existent methods like .listen()
3. Given the following code snippet, what will be printed when a message with payload "ON" is received on the topic "home/lights/control"?
def on_message(client, userdata, message):
    if message.payload.decode() == "ON":
        print("Turning lights ON")
    else:
        print("Turning lights OFF")

client.subscribe("home/lights/control")
client.on_message = on_message
medium
A. Turning lights ON
B. Turning lights OFF
C. No output
D. Error: decode() not found

Solution

  1. Step 1: Decode the message payload

    The payload is decoded to string and compared to "ON".
  2. Step 2: Check the condition and print output

    Since payload is "ON", it prints "Turning lights ON".
  3. Final Answer:

    Turning lights ON -> Option A
  4. Quick Check:

    Payload "ON" triggers print "Turning lights ON" [OK]
Hint: Decode payload before comparing strings [OK]
Common Mistakes:
  • Not decoding payload before comparison
  • Assuming no output without explicit print
  • Thinking decode() causes error
4. Identify the error in this MQTT subscription code snippet for Raspberry Pi:
def on_message(client, userdata, message):
    print(message.payload)

client.on_message = on_message
client.subscribe("home/lights/control")
client.loop_start()
medium
A. Incorrect callback function name
B. Missing client.connect() before subscribing
C. Using loop_start() instead of loop_forever()
D. No error, code is correct

Solution

  1. Step 1: Check connection setup

    Before subscribing, the client must connect to the MQTT broker.
  2. Step 2: Identify missing connect call

    The code lacks client.connect() call, so subscription won't work.
  3. Final Answer:

    Missing client.connect() before subscribing -> Option B
  4. Quick Check:

    Must connect before subscribe [OK]
Hint: Always connect client before subscribing [OK]
Common Mistakes:
  • Skipping client.connect() call
  • Confusing callback function names
  • Thinking loop_start() is wrong here
5. You want your Raspberry Pi to subscribe to multiple control topics: "home/lights/control" and "home/thermostat/control". Which code snippet correctly subscribes to both and handles messages differently based on the topic?
hard
A. client.subscribe(["home/lights/control", "home/thermostat/control"]) def on_message(client, userdata, message): topic = message.topic if topic == "home/lights/control": print("Light control received") elif topic == "home/thermostat/control": print("Thermostat control received") client.on_message = on_message
B. client.subscribe("home/lights/control") client.subscribe("home/thermostat/control") def on_message(client, userdata, message): if message.payload == "light": print("Light control") else: print("Thermostat control") client.on_message = on_message
C. client.subscribe("home/lights/control", "home/thermostat/control") def on_message(client, userdata, message): print("Control received") client.on_message = on_message
D. client.subscribe("home/lights/control") def on_message(client, userdata, message): print("Control received") client.on_message = on_message client.subscribe("home/thermostat/control")

Solution

  1. Step 1: Subscribe to multiple topics correctly

    client.subscribe(["home/lights/control", "home/thermostat/control"]) def on_message(client, userdata, message): topic = message.topic if topic == "home/lights/control": print("Light control received") elif topic == "home/thermostat/control": print("Thermostat control received") client.on_message = on_message uses a list to subscribe to both topics at once, which is valid.
  2. Step 2: Handle messages based on topic

    The on_message function checks message.topic to differentiate actions.
  3. Final Answer:

    correctly subscribes to both topics and handles them separately -> Option A
  4. Quick Check:

    Subscribe list + topic check = correct [OK]
Hint: Subscribe with list and check message.topic [OK]
Common Mistakes:
  • Passing multiple topics as separate arguments
  • Checking payload instead of topic for routing
  • Subscribing after setting callback incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard