MQTT is an IoT messaging protocol that doesn’t actually require a broker to function, despite what most people think.
Let’s see it in action. Imagine you have a temperature sensor in your living room, and you want to send its readings to a dashboard running on your laptop.
First, we need a way for the sensor to send messages and for the dashboard to receive them. This is where MQTT comes in. It’s a publish-subscribe (pub/sub) model. Publishers send messages to "topics," and subscribers listen to those topics to receive messages.
Here’s a basic setup using mosquitto, a popular open-source MQTT broker, and two simple Python scripts: one for publishing and one for subscribing.
1. Setting up the Broker (The "Hub")
On your laptop, install mosquitto. On Debian/Ubuntu:
sudo apt update
sudo apt install mosquitto mosquitto-clients
Then, start the broker:
sudo systemctl start mosquitto
By default, it runs on port 1883.
2. The Publisher (The "Sensor")
This Python script will simulate our temperature sensor. It connects to the broker and publishes a temperature reading every 5 seconds to the topic home/livingroom/temperature.
import paho.mqtt.client as mqtt
import time
import random
broker_address = "localhost"
port = 1883
topic = "home/livingroom/temperature"
client = mqtt.Client()
client.connect(broker_address, port)
while True:
temperature = round(random.uniform(18.0, 24.0), 2)
message = str(temperature)
client.publish(topic, message)
print(f"Published: {message} to {topic}")
time.sleep(5)
Run this script in a terminal: python publisher.py
3. The Subscriber (The "Dashboard")
This script connects to the broker, subscribes to the home/livingroom/temperature topic, and prints any messages it receives.
import paho.mqtt.client as mqtt
broker_address = "localhost"
port = 1883
topic = "home/livingroom/temperature"
def on_message(client, userdata, msg):
print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")
client = mqtt.Client()
client.on_message = on_message
client.connect(broker_address, port)
client.subscribe(topic)
print(f"Subscribed to topic: {topic}")
client.loop_forever()
Run this script in another terminal: python subscriber.py
You’ll see the subscriber printing the temperature readings published by the publisher. The broker, mosquitto in this case, acts as an intermediary. Publishers send messages to it, and it forwards those messages to all active subscribers for that topic.
The beauty of MQTT lies in its simplicity and efficiency. It was designed for constrained devices and unreliable networks, which are common in IoT. Its small code footprint and low bandwidth usage make it ideal for devices with limited processing power and memory.
The core components are the Client (your sensor or dashboard), the Broker (the central hub), and Topics (hierarchical strings like home/livingroom/temperature that categorize messages). Clients connect to the broker, then they can either publish messages to specific topics or subscribe to topics to receive messages. The broker handles routing these messages.
A key feature is Quality of Service (QoS). QoS 0 ("at most once") means a message might be lost. QoS 1 ("at least once") guarantees delivery but might send duplicates. QoS 2 ("exactly once") ensures a message is delivered exactly one time, but it’s the most overhead. Your choice depends on your application’s tolerance for message loss versus performance.
Another crucial concept is Last Will and Testament (LWT). A client can configure a message and a topic to be published by the broker if the client disconnects unexpectedly. This is invaluable for monitoring device status. For example, a device could set an LWT message of "offline" to the topic home/livingroom/status. If the device crashes, the broker will publish "offline" to that status topic, allowing other systems to know it’s no longer available.
The surprising truth about MQTT’s pub/sub model is that the broker doesn’t need to store messages indefinitely. It only needs to hold onto a message for the duration of its delivery to currently connected subscribers. If no one is subscribed to a topic, the broker can simply discard the message (unless specific features like persistent sessions are used). This is why it’s so lightweight – it’s not a queue in the traditional sense, but a real-time message distribution system.
The next concept you’ll likely encounter is managing connections, security, and advanced topic filtering.