0
0
Raspberry Piprogramming~10 mins

Multi-device MQTT network in Raspberry Pi - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Multi-device MQTT network
Start Devices
Connect to MQTT Broker
Subscribe to Topics
Publish Messages
Receive Messages
Process Messages
Repeat Publish/Receive
Disconnect Devices
End
Each device connects to the MQTT broker, subscribes to topics, publishes messages, receives messages, processes them, and repeats until disconnect.
Execution Sample
Raspberry Pi
import paho.mqtt.client as mqtt

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

client = mqtt.Client("device1")
client.on_message = on_message
client.connect("broker.hivemq.com")
client.subscribe("home/temperature")
client.loop_start()
client.publish("home/temperature", "22.5")
This code connects a device to an MQTT broker, subscribes to a topic, listens for messages, and publishes a temperature reading.
Execution Table
StepActionEvaluationResult
1Create MQTT client with ID 'device1'Client createdClient object ready
2Assign on_message callbackCallback setReady to receive messages
3Connect to broker 'broker.hivemq.com'Connection attemptConnected successfully
4Subscribe to topic 'home/temperature'Subscription requestSubscribed successfully
5Start network loopLoop runningListening for messages
6Publish message '22.5' to 'home/temperature'Publish requestMessage sent
7Receive message on 'home/temperature'Message receivedon_message called, prints message
8Process message in on_messagePrint outputOutput: Received 22.5 on home/temperature
9Loop continuesWaiting for more messagesReady for next messages
10Disconnect clientDisconnect requestDisconnected cleanly
💡 Client disconnects or program ends, stopping message loop
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 6After Step 8Final
clientNoneConnected client objectSubscribed clientPublished messageReceived message processedDisconnected client
Key Moments - 3 Insights
Why do we need to start the network loop with loop_start()?
The network loop listens for incoming messages and handles communication. Without loop_start(), the client won't receive messages or keep the connection alive, as shown in step 5 of the execution_table.
What happens if we publish a message before subscribing to the topic?
Publishing before subscribing is allowed, but the client won't receive messages on that topic until it subscribes. The execution_table shows subscription happens before publishing to ensure messages are received.
Why does the on_message callback print the received message?
The on_message function is called automatically when a message arrives on a subscribed topic. It prints the message to show the device received and processed it, as seen in steps 7 and 8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the client start listening for incoming messages?
AStep 3
BStep 6
CStep 5
DStep 8
💡 Hint
Refer to step 5 where loop_start() is called to start the network loop.
According to variable_tracker, what is the state of 'client' after step 6?
ADisconnected client
BPublished message
CSubscribed client
DNone
💡 Hint
Check the 'After Step 6' column for 'client' in variable_tracker.
If the client never subscribes to a topic, what will happen when a message is published to that topic?
AThe client will ignore the message
BThe client will receive and print the message
CThe client will disconnect automatically
DThe client will crash
💡 Hint
Refer to key_moments about subscription order and message reception.
Concept Snapshot
Multi-device MQTT network:
- Devices connect to a broker
- Subscribe to topics to receive messages
- Publish messages to topics
- Use a network loop to listen continuously
- on_message callback processes incoming messages
- Disconnect cleanly when done
Full Transcript
In a multi-device MQTT network, each device connects to a central broker. Devices subscribe to topics to receive messages and publish messages to share data. The network loop runs continuously to listen for messages. When a message arrives, the on_message function processes it. Devices repeat publishing and receiving until they disconnect. This example shows a device connecting, subscribing to 'home/temperature', publishing a temperature value, receiving it back, and printing it. The network loop is essential to keep communication active.