Bird
Raised Fist0
Raspberry Piprogramming~10 mins

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

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

Practice

(1/5)
1.

What is the main role of the MQTT broker in a multi-device network?

easy
A. It routes messages between devices based on topics.
B. It stores all device data permanently.
C. It assigns IP addresses to devices.
D. It encrypts messages automatically.

Solution

  1. Step 1: Understand MQTT broker function

    The MQTT broker acts as a central hub that receives messages from devices and forwards them to others subscribed to the same topic.
  2. Step 2: Eliminate incorrect roles

    The broker does not store data permanently, assign IPs, or encrypt messages by default; its main job is message routing.
  3. Final Answer:

    It routes messages between devices based on topics. -> Option A
  4. Quick Check:

    MQTT broker = message router [OK]
Hint: Broker routes messages by topic, not storing or assigning IPs [OK]
Common Mistakes:
  • Thinking broker stores all data permanently
  • Confusing broker with network router
  • Assuming broker assigns IP addresses
2.

Which of the following is the correct way to connect a Raspberry Pi MQTT client using the paho-mqtt Python library?

client = mqtt.Client(____)
easy
A. subscribe_topic
B. broker_address
C. mqtt.connect()
D. "unique_client_id"

Solution

  1. Step 1: Identify client ID parameter

    The mqtt.Client() constructor takes a unique client ID string to identify the device to the broker.
  2. Step 2: Understand other options

    Broker address is used in connect()</>, not in Client()</>. Methods like connect() or topics are not valid constructor arguments.
  3. Final Answer:

    "unique_client_id" -> Option D
  4. Quick Check:

    Client ID goes in Client() constructor [OK]
Hint: Client ID string goes inside Client() constructor [OK]
Common Mistakes:
  • Passing broker address to Client() instead of connect()
  • Using method calls as constructor arguments
  • Confusing topic names with client ID
3.

Given this Python code snippet using paho-mqtt on a Raspberry Pi, what will be printed when a message with payload 'ON' is received on topic 'home/livingroom/light'?

def on_message(client, userdata, msg):
    if msg.topic == 'home/livingroom/light':
        print(f"Light status: {msg.payload.decode()}")

client = mqtt.Client("pi1")
client.on_message = on_message
client.connect("broker.local")
client.subscribe("home/livingroom/light")
client.loop_start()
medium
A. Light status: b'ON'
B. Light status: ON
C. Light status: None
D. No output

Solution

  1. Step 1: Understand message payload decoding

    The payload is a byte string, so msg.payload.decode() converts it to a normal string, here 'ON'.
  2. Step 2: Check print statement output

    The print uses an f-string to show "Light status: ON" exactly when the topic matches.
  3. Final Answer:

    Light status: ON -> Option B
  4. Quick Check:

    Decoded payload prints as string [OK]
Hint: Decode payload bytes to string before printing [OK]
Common Mistakes:
  • Printing raw bytes without decoding
  • Not subscribing to the correct topic
  • Missing the on_message callback assignment
4.

Identify the error in this MQTT client setup code on a Raspberry Pi:

client = mqtt.Client()
client.connect("broker.local")
client.subscribe("home/kitchen/temperature")
client.loop_forever()

# Missing on_message callback assignment
medium
A. The on_message callback is not assigned, so messages won't be processed.
B. The client ID is missing in mqtt.Client() constructor.
C. The subscribe topic is invalid syntax.
D. loop_forever() should be called before connect().

Solution

  1. Step 1: Check callback assignment

    Without assigning client.on_message, received messages have no handler and won't be processed.
  2. Step 2: Verify other parts

    Client ID is optional but recommended; subscribe syntax is correct; loop_forever() must be after connect().
  3. Final Answer:

    The on_message callback is not assigned, so messages won't be processed. -> Option A
  4. Quick Check:

    Missing on_message means no message handling [OK]
Hint: Always assign on_message callback to process messages [OK]
Common Mistakes:
  • Ignoring on_message callback assignment
  • Thinking client ID is mandatory
  • Calling loop_forever() before connect()
5.

You want to control multiple Raspberry Pi devices in different rooms using MQTT. Each device should only receive messages for its room. Which is the best way to organize MQTT topics and client IDs?

  • Device 1 in living room
  • Device 2 in kitchen

Choose the best topic and client ID setup.

hard
A. Use topics livingroom and kitchen but same client ID pi for both devices.
B. Use the same topic home/all for both and client IDs pi1 and pi2.
C. Use topics like home/livingroom/# and home/kitchen/# with client IDs pi_livingroom and pi_kitchen.
D. Use random topics and client IDs for each device without pattern.

Solution

  1. Step 1: Organize topics by room

    Using hierarchical topics like home/livingroom/# and home/kitchen/# lets devices subscribe only to their room's messages.
  2. Step 2: Assign unique client IDs

    Unique client IDs like pi_livingroom and pi_kitchen avoid connection conflicts and identify devices clearly.
  3. Final Answer:

    Use topics like home/livingroom/# and home/kitchen/# with client IDs pi_livingroom and pi_kitchen. -> Option C
  4. Quick Check:

    Unique IDs + room topics = clean multi-device MQTT [OK]
Hint: Use unique client IDs and room-based topics [OK]
Common Mistakes:
  • Using same client ID for multiple devices
  • Subscribing all devices to a single topic
  • Not organizing topics by device location
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard