Existing customer? Login
This comprehensive tutorial covers MQTT from fundamentals to advanced topics, helping you implement efficient and reliable IoT messaging with the industry-standard protocol.
MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe network protocol designed for constrained devices and low-bandwidth, high-latency, or unreliable networks. Originally developed by IBM in the late 1990s for monitoring oil pipelines via satellite, MQTT has since become the de facto standard for IoT communications.
Key characteristics of MQTT include:
The broker is the central hub of any MQTT system. It receives all messages from clients, filters them, and distributes them to the appropriate subscribers. The broker is responsible for:
MQTT clients are any devices that run an MQTT library and connect to the broker over a network. A client can be:
Topics are the addressing mechanism in MQTT. They are UTF-8 strings organized in a hierarchical structure with levels separated by forward slashes (/). For example:
home/livingroom/temperature
building/floor1/room3/humidity
device/12345/status
This hierarchical structure allows for flexible message filtering using wildcards:
home/+/temperature # Matches home/livingroom/temperature but not home/livingroom/kitchen/temperature
home/# # Matches home/livingroom/temperature, home/kitchen/light, etc.
Best practices for topic design:
MQTT provides three Quality of Service (QoS) levels that guarantee different levels of message delivery:
Message is delivered at most once, with no confirmation. "Fire and forget."
Use when: Occasional message loss is acceptable, like sensor readings sent frequently.
Message is delivered at least once, with confirmation. Messages might be delivered multiple times.
Use when: Message must be delivered, but duplicate processing is acceptable.
Message is delivered exactly once, using a four-step handshake.
Use when: Message must be delivered exactly once, like billing or critical commands.
Higher QoS levels provide more reliable delivery but require more bandwidth and introduce more latency. Choose the appropriate QoS level based on your application's requirements for reliability versus efficiency.
An MQTT message consists of:
When a client publishes a message with the retain flag set to true, the broker stores the message. When new clients subscribe to that topic, they immediately receive the last retained message, even if it was published before they subscribed.
This is useful for:
MQTT allows clients to register a "last will" message with the broker during connection. If the client disconnects ungracefully (without sending a proper DISCONNECT message), the broker will publish this last will message to a specified topic.
This is particularly useful for:
import paho.mqtt.client as mqtt
# Callbacks
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# Subscribe to topics on successful connect
client.subscribe("home/temperature")
def on_message(client, userdata, msg):
print(f"Received message on {msg.topic}: {msg.payload.decode()}")
# Create client instance
client = mqtt.Client()
# Assign callbacks
client.on_connect = on_connect
client.on_message = on_message
# Optional: Set username and password
client.username_pw_set("username", "password")
# Optional: Enable TLS/SSL
# client.tls_set(ca_certs="ca.crt")
# Connect to broker
client.connect("mqtt.example.com", 1883, 60)
# Start networking loop
client.loop_forever()
const mqtt = require('mqtt');
// Connect to broker
const client = mqtt.connect('mqtt://mqtt.example.com:1883', {
username: 'username',
password: 'password',
clientId: 'mqttjs_client_' + Math.random().toString(16).substr(2, 8)
});
// Handle connection events
client.on('connect', function () {
console.log('Connected to MQTT broker');
// Subscribe to topics
client.subscribe('home/temperature', function (err) {
if (!err) {
// Publish a message
client.publish('home/status', 'Hello MQTT!');
}
});
});
// Handle incoming messages
client.on('message', function (topic, message) {
console.log(`Received message on ${topic}: ${message.toString()}`);
});
# Publish a non-retained message with QoS 0
client.publish("home/temperature", "22.5", qos=0, retain=False)
# Publish a retained message with QoS 1
client.publish("home/status", "online", qos=1, retain=True)
# Publish a message with QoS 2
client.publish("home/alert", "Motion detected!", qos=2, retain=False)
// Publish a non-retained message with QoS 0
client.publish('home/temperature', '22.5', { qos: 0, retain: false });
// Publish a retained message with QoS 1
client.publish('home/status', 'online', { qos: 1, retain: true });
// Publish a message with QoS 2
client.publish('home/alert', 'Motion detected!', { qos: 2, retain: false });
# Subscribe to a single topic with QoS 1
client.subscribe("home/temperature", qos=1)
# Subscribe to multiple topics with different QoS levels
client.subscribe([
("home/temperature", 0),
("home/humidity", 1),
("home/+/status", 2) # Using wildcard
])
// Subscribe to a single topic with QoS 1
client.subscribe('home/temperature', { qos: 1 });
// Subscribe to multiple topics with different QoS levels
client.subscribe({
'home/temperature': { qos: 0 },
'home/humidity': { qos: 1 },
'home/+/status': { qos: 2 } // Using wildcard
});
Securing MQTT communications is crucial, especially for IoT applications that may transmit sensitive data or control critical systems. Here are key security considerations:
MQTT supports username/password authentication, which should be enabled to prevent unauthorized access:
Transport Layer Security (TLS) should be used to encrypt MQTT traffic:
Implement topic-level access control to restrict which clients can publish/subscribe to specific topics:
Additional network security measures should be considered:
When a client connects to a broker, it can choose whether to start a clean session or resume a persistent session:
Persistent sessions are useful for clients with intermittent connectivity, as they won't miss messages published while they were offline.
For large-scale MQTT deployments, you might need to connect multiple brokers:
These approaches help build distributed, scalable MQTT systems that can span multiple networks or geographic regions.
The latest version of MQTT (5.0) introduces several new features:
MQTT is widely used in home automation systems to connect and control smart devices:
Popular platforms like Home Assistant, OpenHAB, and Node-RED use MQTT as their communication backbone.
Manufacturing and industrial applications leverage MQTT for monitoring and control:
MQTT's reliability and efficiency make it ideal for industrial environments where timely data delivery is critical.
MQTT excels in remote monitoring applications:
Its low bandwidth requirements and support for unreliable networks make it perfect for remote deployments.
Healthcare applications benefit from MQTT's reliability:
MQTT's QoS levels ensure critical health data is delivered reliably, while its lightweight nature supports resource-constrained medical devices.
MQTT.pro provides a fully-managed, serverless MQTT broker service that simplifies implementation and scaling of MQTT-based applications:
MQTT has become the protocol of choice for IoT and messaging applications due to its efficiency, flexibility, and reliability. This tutorial has covered the essentials of MQTT, from basic concepts to advanced features and real-world implementations.
By understanding topics, QoS levels, security considerations, and implementation best practices, you're now equipped to build robust MQTT-based systems for various applications.
With MQTT.pro's serverless broker service, you can focus on building your application rather than managing infrastructure, while ensuring security, scalability, and reliability for your MQTT communications.