MQTT (Message Queuing Telemetry Transport)
1. Basic Definition
MQTT is a lightweight, publish-subscribe (pub/sub) based messaging protocol designed for constrained devices and low-bandwidth, high-latency, or unreliable networks (e.g., IoT, satellite links, cellular networks). Developed by IBM in 1999 and standardized by OASIS/ISO (ISO/IEC 20922), it prioritizes minimal network overhead, low power consumption, and reliable message delivery—making it the de facto standard for IoT (Internet of Things) communication. Unlike traditional request-response protocols (e.g., HTTP), MQTT uses a broker-based pub/sub model to decouple message senders (publishers) and receivers (subscribers).
2. Core Architecture & Workflow
MQTT follows a client-broker architecture with three key roles:
2.1 Key Roles
- Publisher: A client (e.g., sensor, smart thermostat) that sends messages to a specific “topic” (no direct connection to subscribers).
- Subscriber: A client (e.g., mobile app, cloud server) that registers interest in one or more topics to receive relevant messages.
- Broker: A central server that receives messages from publishers, filters them by topic, and forwards them to all subscribed clients (core responsibility: message routing and delivery).
2.2 Basic Workflow
生成失败,请重试
生成失败,请重试
![]()
豆包
你的 AI 助手,助力每日工作学习
- Subscribers connect to the broker and subscribe to topics (e.g.,
sensor/room1/temperature). - Publishers connect to the broker and publish messages to the same topics.
- The broker matches published messages to subscribed topics and delivers messages to all relevant subscribers.
- Clients (publishers/subscribers) disconnect after communication (or maintain a persistent connection).
3. Core Features & Syntax
3.1 Key Features
- Lightweight: Minimal packet size (fixed header is only 2 bytes) and low code footprint (suitable for microcontrollers like ESP8266/ESP32).
- QoS (Quality of Service) Levels: Three levels to balance reliability and overhead:QoS LevelDescriptionUse Case0 (At Most Once)”Fire and forget”—message is delivered 0 or 1 times (no acknowledgment).Non-critical data (e.g., real-time sensor readings).1 (At Least Once)Message is delivered at least once (broker/client acknowledges receipt; retransmits if no ACK).Critical data (e.g., device command to turn on a pump).2 (Exactly Once)Message is delivered exactly once (4-way handshake to prevent duplicates).Mission-critical data (e.g., financial transactions, medical data).
- Persistent Connections: Supports keep-alive packets to maintain connections even with intermittent network access.
- Last Will and Testament (LWT): A pre-configured message the broker sends to a topic if a client disconnects unexpectedly (e.g., notify “device/room1/offline” if a sensor loses power).
- Retained Messages: The broker stores the last message for a topic and delivers it to new subscribers (e.g., send the latest temperature to a new app that just subscribed).
3.2 Topic Syntax
Topics are UTF-8 strings that act as message “addresses” with hierarchical structure (separated by /):
- Valid Examples:
sensor/room1/temp,device/esp32/command,iot/factory/machine1/status - Wildcards: For flexible subscription:
+: Single-level wildcard (matches one level, e.g.,sensor/+/tempmatchessensor/room1/tempbut notsensor/room1/floor1/temp).#: Multi-level wildcard (matches all subsequent levels, must be the last character, e.g.,sensor/room1/#matchessensor/room1/temp,sensor/room1/humidity).
4. Typical Application Scenarios
- IoT Device Communication: Smart home (thermostats, lights, cameras), industrial IoT (factory sensors, machinery monitoring), wearable devices (fitness trackers).
- Remote Monitoring: Environmental monitoring (weather stations, air quality sensors) sending data to cloud servers over low-bandwidth networks.
- Mobile/Embedded Systems: Real-time data transmission between battery-powered devices (minimal power consumption).
- Machine-to-Machine (M2M): Communication between industrial equipment, vehicles (telematics), and backend systems.
- Messaging for Constrained Networks: Satellite communication, rural cellular networks (low bandwidth/high latency).
5. Implementation & Tools
5.1 Popular MQTT Brokers
- Eclipse Mosquitto: Open-source, lightweight broker (ideal for small-scale deployments).
- EMQ X (EMQX): Scalable open-source broker for enterprise/IoT platforms.
- AWS IoT Core/Azure IoT Hub/Google Cloud IoT: Cloud-managed MQTT brokers (no self-hosting required).
5.2 Client Libraries (Cross-Language Support)
- Python:
paho-mqtt(most widely used) - C/C++:
Eclipse Paho C(for embedded devices) - JavaScript/Node.js:
mqtt.js - Arduino/ESP32:
PubSubClient
5.3 Simple Code Example (Python with Paho-MQTT)
Step 1: Install the library
bash
运行
pip install paho-mqtt
Step 2: Publisher Code (send temperature data)
python
运行
import paho.mqtt.client as mqtt
import time
# Configure broker connection
BROKER = "test.mosquitto.org" # Public test broker
PORT = 1883
TOPIC = "sensor/room1/temperature"
# Create client instance
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
# Connect to broker
client.connect(BROKER, PORT, 60)
# Publish messages in a loop
try:
temp = 25.0
while True:
# Publish temperature (QoS 0)
client.publish(TOPIC, payload=str(temp), qos=0)
print(f"Published: {temp}°C to {TOPIC}")
temp += 0.5
time.sleep(2)
except KeyboardInterrupt:
client.disconnect()
print("Disconnected from broker")
Step 3: Subscriber Code (receive temperature data)
python
运行
import paho.mqtt.client as mqtt
# Configure broker/topic
BROKER = "test.mosquitto.org"
PORT = 1883
TOPIC = "sensor/room1/temperature"
# Callback for when a message is received
def on_message(client, userdata, msg):
print(f"Received message on {msg.topic}: {msg.payload.decode()}°C")
# Create client and set callback
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_message = on_message
# Connect and subscribe
client.connect(BROKER, PORT, 60)
client.subscribe(TOPIC, qos=0)
# Keep running to receive messages
client.loop_forever()
6. Comparison with HTTP (IoT Context)
| Feature | MQTT | HTTP |
|---|---|---|
| Communication Model | Pub/Sub (decoupled) | Request-Response (coupled) |
| Overhead | Very low (2-byte fixed header) | High (large headers, cookies) |
| Connection Type | Persistent (keep-alive) | Stateless (per-request) |
| Power Consumption | Low (ideal for batteries) | High (frequent reconnections) |
| Use Case | Real-time IoT messaging | Web APIs, file transfers |
- iPhone 15 Pro Review: Ultimate Features and Specs
- iPhone 15 Pro Max: Key Features and Specifications
- iPhone 16: Features, Specs, and Innovations
- iPhone 16 Plus: Key Features & Specs
- iPhone 16 Pro: Premium Features & Specs Explained
- iPhone 16 Pro Max: Features & Innovations Explained
- iPhone 17 Pro: Features and Innovations Explained
- iPhone 17 Review: Features, Specs, and Innovations
- iPhone Air Concept: Mid-Range Power & Portability
- iPhone 13 Pro Max Review: Features, Specs & Performance
- iPhone SE Review: Budget Performance Unpacked
- iPhone 14 Review: Key Features and Upgrades
- Apple iPhone 14 Plus: The Ultimate Mid-range 5G Smartphone
- iPhone 14 Pro: Key Features and Innovations Explained
- Why the iPhone 14 Pro Max Redefines Smartphone Technology
- iPhone 15 Review: Key Features and Specs
- iPhone 15 Plus: Key Features and Specs Explained
- iPhone 12 Mini Review: Compact Powerhouse Unleashed
- iPhone 12: Key Features and Specs Unveiled
- iPhone 12 Pro: Premium Features and 5G Connectivity
- Why the iPhone 12 Pro Max is a Top Choice in 2023
- iPhone 13 Mini: Compact Powerhouse in Your Hand
- iPhone 13: Key Features and Specs Overview
- iPhone 13 Pro Review: Features and Specifications






















Leave a comment