Source: IoT Communication Protocols

Data gathered from sensors and sent to the cloud = telemetry

HTTP (not ideal for IoT)

Characteristics that make HTTP problematic for IoT:

  • Request-response: client must always pull — no server-push
  • Stateless: no persistent connection, each request independent
  • Large headers: uncompressed overhead (~8 bytes header)
  • DNS lookup: 3-way handshake overhead
  • Constant polling = slow OR power/data intensive

Pub/Sub Pattern

Two actors:

  • Broker: server that accepts messages, routes them to subscribers
  • Clients: publish messages to topics OR subscribe to receive them

A cloud service is also a client — connects to broker, subscribes to telemetry topics.

MQTT

Message Queuing Telemetry Transport — lightweight pub/sub protocol.

Originally designed for oil pipeline monitoring (unreliable connectivity). Facebook Messenger is the world’s largest MQTT network.

  • Manages messages asynchronously over a network socket
  • Messages can be 2 bytes to 256 MB
  • UTF-8 encoded headers/topics; payload encoding is app-defined (JSON, binary, etc.)
  • Can be open/public or encrypted (username/password or certificates)

Topics & Wildcards

Topic hierarchy example: sensors/<FLOOR>/temperature/<HVAC_UNIT_ID>

SubscriptionWhat you get
sensors/floor3/temperature/+All temp sensors on floor 3
sensors/+/temperature/+All temp data, all floors
sensors/#Everything on all floors
sensors/floor10/#All topics on floor 10
  • # = multi-level wildcard (replaces remaining levels)
  • + = single-level wildcard (replaces one level)

QoS Levels

QoSNameDelivery guarantee
0At most once (Fire & Forget)Sent once, no acknowledgement
1At least onceRetried until ACK received
2Exactly onceTwo-level handshake, no duplicates

Default QoS = 0. If subscriber defines lower QoS than publisher, broker uses subscriber’s lower value.

Sessions

Session typeBehavior
Clean (CleanSession=true)Broker stores nothing, purges previous subscriptions
Persistent (CleanSession=false)Broker stores subscriptions and missed QoS 1/2 messages

KeepAlive

Time interval (seconds) — client and broker ping each other at this interval to detect dead connections.

Last Will & Testament (LWT)

Client provides LWT message+topic on connect. If client disconnects unexpectedly, broker sends the LWT on its behalf — notifies other clients of disconnection.

Retained Messages

Message with retained=true. Broker stores the last retained message per topic. New subscribers receive it immediately upon subscribing (instant status update).

HTTP vs MQTT Comparison

CriteriaMQTTHTTP
ComplexitySimple, lightweightMore complex
EnergyMore efficientLess efficient
DirectionBi-directionalUni-directional (client initiates)
ArchitecturePub/SubRequest/Response
ConnectionCan stay openCloses after every request
Delivery assuranceQoS 0/1/2None
Header size~2 bytes~8 bytes

paho-mqtt Python 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, retain=False
    mqtt_client.loop()
    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()
    time.sleep(1)

Public brokers

  • test.mosquitto.org (Eclipse Foundation)
  • broker.emqx.io (EMQX)

See Also