MQTT and IoT Protocols

HTTP vs MQTT

CriteriaHTTPMQTT
ArchitectureRequest/ResponsePublish/Subscribe
DirectionUni-directional (client initiates)Bi-directional
ConnectionCloses after every requestCan stay open
Header size~8 bytes~2 bytes
Energy efficiencyLess efficientMore efficient
Delivery assuranceNoneQoS 0/1/2
ComplexityMore complexSimple, 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

SubscriptionMatchesWildcard
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)

QoSNameHow it works
0At most once (Fire & Forget)Sent once, no ACK
1At least onceRetried until ACK received (may duplicate)
2Exactly onceTwo-level handshake, no duplicates

Default = QoS 0. If subscriber requests lower QoS than publisher, broker uses the lower value.

Sessions

TypeCleanSessionBehavior
CleantrueBroker stores nothing, fresh each connection
PersistentfalseBroker 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-mqtt

Publisher

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