MQTT and IoT Protocols
HTTP vs MQTT
| Criteria | HTTP | MQTT |
|---|---|---|
| Architecture | Request/Response | Publish/Subscribe |
| Direction | Uni-directional (client initiates) | Bi-directional |
| Connection | Closes after every request | Can stay open |
| Header size | ~8 bytes | ~2 bytes |
| Energy efficiency | Less efficient | More efficient |
| Delivery assurance | None | QoS 0/1/2 |
| Complexity | More complex | Simple, lightweight |
HTTP problem for IoT: client must constantly pull — slow (infrequent) OR power-intensive (constant).
Pub/Sub Architecture
[Device] --publish--> [Broker] --forward--> [Cloud Service]
[Cloud Service] --publish--> [Broker] --forward--> [Device]
- Client: any device or service — can publish AND subscribe
- Broker: server that accepts, routes, and stores messages
MQTT Topics
Hierarchical naming: sensors/<FLOOR>/temperature/<HVAC_ID>
Wildcards
| Subscription | Matches | Wildcard |
|---|---|---|
sensors/floor3/temperature/+ | All sensors on floor 3 | + = single level |
sensors/+/temperature/+ | All temps, all floors | + |
sensors/# | Everything under sensors/ | # = multi-level |
sensors/floor10/# | All topics on floor 10 | # |
+replaces exactly one topic level#replaces remaining topic levels (must be last)
QoS (Quality of Service)
| QoS | Name | How it works |
|---|---|---|
| 0 | At most once (Fire & Forget) | Sent once, no ACK |
| 1 | At least once | Retried until ACK received (may duplicate) |
| 2 | Exactly once | Two-level handshake, no duplicates |
Default = QoS 0. If subscriber requests lower QoS than publisher, broker uses the lower value.
Sessions
| Type | CleanSession | Behavior |
|---|---|---|
| Clean | true | Broker stores nothing, fresh each connection |
| Persistent | false | Broker stores subscriptions + missed QoS 1/2 messages |
KeepAlive
Interval (seconds) that broker and client must ping each other. Detects dead connections.
Last Will & Testament (LWT)
Set at connect time. If client disconnects unexpectedly, broker publishes the LWT message on client’s behalf — notifies others of disconnection.
Retained Messages
Message with retain=True. Broker stores the last retained message per topic. New subscribers get it immediately upon subscribing (instant status update without waiting).
Complete paho-mqtt Code
Install
pip install paho-mqttPublisher
import paho.mqtt.client as mqtt
import json, time, random
rnd = random.Random()
common_key = 'd5a4d5e6-d597-4bd4-8196-5f51d12345'
topic_name = common_key + '/temperature'
client_name = common_key + 'publisher'
mqtt_client = mqtt.Client(client_name)
mqtt_client.connect('test.mosquitto.org')
print("MQTT connected!")
while True:
temp = rnd.randint(-10, 30)
payload = json.dumps({'temperature': temp})
print("Sending telemetry", payload)
mqtt_client.publish(topic_name, payload) # QoS=0 by default
mqtt_client.loop() # process network events
time.sleep(3)Subscriber
import paho.mqtt.client as mqtt
import time
common_key = 'd5a4d5e6-d597-4bd4-8196-5f51d12345'
client_name = common_key + 'subscriber'
topic_name = common_key + '/temperature'
mqtt_client = mqtt.Client(client_name)
mqtt_client.connect('test.mosquitto.org')
print("MQTT connected!")
def message_received(mqtt_client, userdata, message):
print(f'Received message: {message.payload}')
mqtt_client.on_message = message_received
mqtt_client.subscribe(topic_name)
while True:
mqtt_client.loop() # must call regularly to process incoming messages
time.sleep(1)Public Brokers
test.mosquitto.org(Eclipse Foundation)broker.emqx.io(EMQX)
See Also
- MQTT Broker concept, Sub concept, QoS concept, Telemetry concept
- IoT System Architecture topic
- iot-communication-protocols source