The paho-mqtt library helps your Raspberry Pi talk to other devices using MQTT, a simple messaging system. It lets your Pi send and receive messages easily.
0
0
paho-mqtt library usage in Raspberry Pi
Introduction
You want your Raspberry Pi to send sensor data to a server or another device.
You want your Raspberry Pi to receive commands from a phone or computer.
You want to connect multiple Raspberry Pis or devices to share information.
You want a lightweight way to communicate over the internet or local network.
You want to build smart home projects that talk to each other.
Syntax
Raspberry Pi
import paho.mqtt.client as mqtt # Create a client client = mqtt.Client() # Connect to broker client.connect('broker_address', 1883) # Publish a message client.publish('topic/name', 'message') # Subscribe to a topic client.subscribe('topic/name') # Start listening for messages client.loop_start()
The 'broker_address' is the server that handles messages.
'topic/name' is like a channel where messages are sent and received.
Examples
This example connects to a public MQTT broker and sends a message to the 'home/livingroom' topic.
Raspberry Pi
import paho.mqtt.client as mqtt client = mqtt.Client() client.connect('test.mosquitto.org', 1883) client.publish('home/livingroom', 'Hello from Raspberry Pi!')
This example listens for messages on 'home/livingroom' and prints them when received.
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('test.mosquitto.org', 1883) client.subscribe('home/livingroom') client.loop_start()
Sample Program
This program connects to a public MQTT broker, subscribes to 'test/topic', sends a message to the same topic, and prints any received messages.
Raspberry Pi
import paho.mqtt.client as mqtt import time 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('test.mosquitto.org', 1883) client.subscribe('test/topic') client.loop_start() # Publish a message client.publish('test/topic', 'Hello MQTT!') # Wait to receive messages time.sleep(2) client.loop_stop()
OutputSuccess
Important Notes
Always call loop_start() or loop_forever() to process network events and receive messages.
MQTT topics are case-sensitive and hierarchical, like folders.
Use public brokers for testing, but for real projects, use a private broker for security.
Summary
paho-mqtt lets your Raspberry Pi send and receive messages using MQTT.
You connect to a broker, publish messages, and subscribe to topics to listen.
Use callbacks to handle incoming messages and keep the client running with loop methods.