0
0
Raspberry Piprogramming~10 mins

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

Choose your learning style9 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.