MQTT: Lightweight messages for the Internet of Things
In short: MQTT is a lean publish/subscribe protocol with which sensors and devices exchange small messages via a broker, even on a weak connection.
In more detail: A temperature sensor with a small microcontroller should send measured values and a smartphone display them. HTTP would be too heavy for such small devices and poor connections. MQTT (Message Queuing Telemetry Transport) has a minimum header of only two bytes and runs over TCP. It is standard in smart homes (Home Assistant, Zigbee2MQTT) and industry (IIoT).
In Depth
Principle: broker and topics
All participants connect to a broker (for example Mosquitto, EMQX). Messages are published under topics, named hierarchically:
home/livingroom/temperature -> 21.5
home/kitchen/light/set -> ON
Whoever subscribes to a topic gets every new message. With wildcards you subscribe to several: + for one level (home/+/temperature), # for everything below (home/#).
Reliability: QoS and retain
- QoS 0: at most once, without acknowledgement (fast).
- QoS 1: at least once (can arrive twice).
- QoS 2: exactly once (more costly).
- Retained messages: the broker keeps the last message of a topic; new subscribers receive it immediately (for example current state).
- Last will: a message that the broker publishes when the device’s connection drops unexpectedly (“offline”).
Example
With the program mosquitto on the command line:
mosquitto_sub -h broker.local -t 'home/+/temperature'
mosquitto_pub -h broker.local -t 'home/livingroom/temperature' -m '21.5'
In Arduino/ESP32 programs a library such as PubSubClient suffices.
Security
Standard MQTT sends in plain text on port 1883. Use TLS (port 8883), user name and password or certificates and set access rights per topic (ACL). An open broker on the internet is quickly used by strangers. Publish brokers only if necessary and keep them up to date. The protocol now has MQTT 5 with better error codes and properties.
See also: Publish/subscribe, ESP32, Smart home, TLS