0
0
Raspberry Piprogramming~10 mins

Multi-device MQTT network in Raspberry Pi

Choose your learning style9 modes available
Introduction

MQTT helps many devices talk to each other easily. It is like a post office for small messages between devices.

You want several Raspberry Pis to share sensor data in a smart home.
You need to control lights and fans from different devices remotely.
You want to collect temperature readings from many devices in a garden.
You want devices to send alerts to each other quickly and simply.
Syntax
Raspberry Pi
import paho.mqtt.client as mqtt

# Create client
client = mqtt.Client(client_id)

# Connect to broker
client.connect(broker_address, port)

# Publish message
def publish(topic, message):
    client.publish(topic, message)

# Subscribe to topic
def on_message(client, userdata, msg):
    print(f"Received {msg.payload.decode()} on {msg.topic}")

client.on_message = on_message
client.subscribe(topic)

# Start listening
client.loop_start()

Use a unique client_id for each device to avoid conflicts.

The broker is the central server that passes messages between devices.

Examples
This example connects a device named 'device1' to a public broker and sends a temperature reading.
Raspberry Pi
client = mqtt.Client("device1")
client.connect("broker.hivemq.com", 1883)
client.publish("home/livingroom/temperature", "22")
This example listens for messages on the temperature topic and prints them when received.
Raspberry Pi
def on_message(client, userdata, msg):
    print(f"Got message: {msg.payload.decode()} on topic {msg.topic}")

client.on_message = on_message
client.subscribe("home/livingroom/temperature")
client.loop_start()
Sample Program

This program shows two devices: one sends messages about light status, the other listens and prints them.

Raspberry Pi
import paho.mqtt.client as mqtt
import time

# Device 1: Publisher
client1 = mqtt.Client("device1")
client1.connect("broker.hivemq.com", 1883)

# Device 2: Subscriber
client2 = mqtt.Client("device2")

def on_message(client, userdata, msg):
    print(f"Device2 received: {msg.payload.decode()} on {msg.topic}")

client2.on_message = on_message
client2.connect("broker.hivemq.com", 1883)
client2.subscribe("home/room1/light")
client2.loop_start()

# Device1 publishes messages
for i in range(3):
    message = f"Light status {i}"
    print(f"Device1 publishing: {message}")
    client1.publish("home/room1/light", message)
    time.sleep(1)

client2.loop_stop()
OutputSuccess
Important Notes

Make sure all devices use the same broker address and topic names to communicate.

MQTT uses small messages, so it works well on low-power devices like Raspberry Pi.

Use client.loop_start() to listen for messages without blocking your program.

Summary

MQTT lets many devices send and receive small messages easily.

Each device connects to a broker and uses topics to organize messages.

Use unique client IDs and matching topics for smooth communication.