How MQTT Works: Publish-Subscribe Model Explained
The
MQTT protocol works on a publish-subscribe model where devices called publishers send messages to a broker on specific topics. Subscribers register interest in these topics, and the broker forwards messages from publishers to all subscribers, enabling efficient and decoupled communication.Syntax
The MQTT publish-subscribe model involves three main parts:
- Publisher: Sends messages to a topic on the broker.
- Broker: Receives messages from publishers and forwards them to subscribers.
- Subscriber: Listens to topics and receives messages from the broker.
Topics are strings that categorize messages, like channels. Publishers and subscribers do not communicate directly but through the broker.
plaintext
mqttClient.publish(topic, message) mqttClient.subscribe(topic)
Example
This example shows a simple MQTT client publishing a message and another subscribing to receive it using the paho-mqtt Python library.
python
import paho.mqtt.client as mqtt broker = "test.mosquitto.org" topic = "home/temperature" # Subscriber callback def on_message(client, userdata, msg): print(f"Received message: {msg.payload.decode()} on topic {msg.topic}") # Subscriber setup subscriber = mqtt.Client() subscriber.on_message = on_message subscriber.connect(broker) subscriber.subscribe(topic) subscriber.loop_start() # Publisher setup publisher = mqtt.Client() publisher.connect(broker) publisher.publish(topic, "22.5 C") import time time.sleep(2) # Wait to receive message subscriber.loop_stop()
Output
Received message: 22.5 C on topic home/temperature
Common Pitfalls
Common mistakes when using MQTT publish-subscribe include:
- Not subscribing to the correct topic, so messages are missed.
- Forgetting to start the network loop in clients, which stops message processing.
- Using the same client ID for multiple clients, causing connection conflicts.
- Not handling connection loss or reconnection properly.
Always verify topic names and ensure clients run their network loops to receive messages.
plaintext
Wrong: subscriber.subscribe("home/temperature1") # Typo in topic Right: subscriber.subscribe("home/temperature")
Quick Reference
| Concept | Description |
|---|---|
| Publisher | Sends messages to a topic on the broker |
| Subscriber | Receives messages by subscribing to topics |
| Broker | Central server that routes messages between clients |
| Topic | String identifier for message channels |
| QoS | Quality of Service levels for message delivery guarantees |
Key Takeaways
MQTT uses a broker to route messages from publishers to subscribers via topics.
Publishers send messages to topics; subscribers receive messages by subscribing to those topics.
Clients must run a network loop to process incoming and outgoing messages.
Correct topic names and unique client IDs are essential to avoid communication issues.
MQTT is lightweight and ideal for devices with limited resources.