perkun.eu Services Portfolio Blog About Contact PL
← Blog

9/20/2021

First steps with MQTT and Raspberry Pi — the IoT protocol worth knowing

TL;DR: MQTT is pub-sub for IoT. 10 lines of Python and you have a device sending data over the network. A Mosquitto broker on a Raspberry Pi is a great starting point.

MQTT (Message Queuing Telemetry Transport) was created in 1999 for monitoring oil pipelines. Today it is the de facto standard in IoT — from industrial sensors to smart home devices. Why is it worth knowing before you start playing with IoT?

Why MQTT when there’s HTTP

HTTP is great for websites and APIs. For IoT it has problems: every device would either need an HTTP server or regularly poll a central server. Polling means either latency or flooding the server with requests.

MQTT flips the model: devices connect to a broker and publish messages on topics. Any client interested in a topic subscribes to it and gets messages in real time. The broker stores the last value — a new device that joins immediately gets the current state.

Installing Mosquitto on Raspberry Pi

sudo apt update && sudo apt install mosquitto mosquitto-clients -y
sudo systemctl enable mosquitto
sudo systemctl start mosquitto

Test from the command line — two terminals:

# Terminal 1 — subscriber
mosquitto_sub -h localhost -t "home/living-room/temperature"

# Terminal 2 — publisher
mosquitto_pub -h localhost -t "home/living-room/temperature" -m "22.5"

Python publisher (paho-mqtt)

import paho.mqtt.client as mqtt
import time, random

client = mqtt.Client()
client.connect("localhost", 1883)

while True:
    temperatura = round(20 + random.uniform(-2, 2), 1)
    client.publish("dom/salon/temperatura", temperatura)
    time.sleep(10)

Python subscriber

import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    print(f"{msg.topic}: {msg.payload.decode()}")

client = mqtt.Client()
client.on_message = on_message
client.connect("localhost", 1883)
client.subscribe("dom/#")  # subscribes to all topics under "dom/"
client.loop_forever()

Topic hierarchy

The topic dom/salon/temperatura is a convention, not a requirement. But it’s worth following: building/floor/room/sensor. The wildcard # subscribes to everything below, + is one level: dom/+/temperatura subscribes to temperatures from all rooms.

What’s next

Mosquitto on a Raspberry Pi is a good broker for home projects and small industrial deployments (< 100 devices). For larger scale: EMQX or HiveMQ. For persisting data from MQTT: Node-RED → InfluxDB → Grafana — that’s a separate article.