Subscribing to control topics lets your Raspberry Pi listen for commands or messages. This helps it react to changes or instructions from other devices or programs.
0
0
Subscribing to control topics in Raspberry Pi
Introduction
You want your Raspberry Pi to turn on a light when it receives a command.
You need to monitor sensor data sent from another device.
You want to control a robot remotely by sending commands.
You want to update your Raspberry Pi settings from a phone app.
You want to receive alerts or notifications from other devices.
Syntax
Raspberry Pi
import paho.mqtt.client as mqtt def on_message(client, userdata, message): print(f"Received message: {message.payload.decode()} on topic {message.topic}") client = mqtt.Client() client.on_message = on_message client.connect("broker.hivemq.com", 1883) client.subscribe("control/topic") client.loop_forever()
This example uses the MQTT protocol, common for control topics.
The on_message function runs when a message arrives.
Examples
Subscribe to the topic
home/lights to receive light control messages.Raspberry Pi
client.subscribe("home/lights")Subscribe to multiple topics with different quality of service levels.
Raspberry Pi
client.subscribe([("home/lights", 0), ("home/temperature", 1)])
Define a function to handle incoming messages and print their content.
Raspberry Pi
def on_message(client, userdata, message): print(f"Topic: {message.topic}, Message: {message.payload.decode()}")
Sample Program
This program connects to a public MQTT broker and subscribes to the control/topic. It prints any messages received on that topic for 10 seconds.
Raspberry Pi
import paho.mqtt.client as mqtt def on_message(client, userdata, message): print(f"Received message: {message.payload.decode()} on topic {message.topic}") client = mqtt.Client() client.on_message = on_message client.connect("broker.hivemq.com", 1883) client.subscribe("control/topic") client.loop_start() import time # Keep the program running for 10 seconds to receive messages for i in range(10): print(f"Waiting for messages... {i+1}") time.sleep(1) client.loop_stop() client.disconnect()
OutputSuccess
Important Notes
Make sure your Raspberry Pi is connected to the internet to reach the MQTT broker.
You can replace broker.hivemq.com with your own MQTT broker address.
Use client.loop_start() and client.loop_stop() to run the network loop in the background.
Summary
Subscribing lets your Raspberry Pi listen for messages on specific topics.
Use MQTT client libraries like paho-mqtt to subscribe and handle messages.
Define a function to process messages and keep the client running to receive them.