I ran the same Python MQTT publisher five times through a link that first loses its acknowledgements and then drops completely. 300 temperature readings each run. QoS 0 lost 92 of them, which is what QoS 0 promises. QoS 1 lost nothing and delivered 20 twice, also as promised. QoS 2, the “exactly once” level, lost 51.
The protocol was not at fault. The client re-sent its whole backlog at once after reconnecting, the broker allows only 20 unfinished QoS 1/2 messages per client, and the extra ones were refused with a reason code the client never looked at. A small flow-control window in application code fixed it: 300 of 300, zero duplicates.
This post builds the whole smart-home telemetry path in Python and tests each MQTT feature against a real broker, not a mock:
- Run a local Mosquitto broker and a throwaway one per test.
- Design topics as
home/<site>/<room>/<device>/<metric>and use the+and#wildcards. - Write a paho-mqtt 2.x client (the callback API changed in 2.0).
- Publish a retained online/offline status with a Last Will.
- Store readings in SQLite with de-duplication and a per-minute rollup.
- Break the network on purpose and measure QoS 0, 1 and 2.
- Use MQTT 5 persistent sessions (
clean_start, Session Expiry Interval) so a collector restart loses nothing.
Versions: Python 3.13.18, paho-mqtt 2.1.0, Mosquitto 2.0.18 (Ubuntu 24.04 package), pytest 9.2.0, SQLite 3.53.1. Every output block below is copied from a real run.
The setup
A smart home produces many small, frequent readings. A broad overview of IoT in real estate lists the usual sources: temperature, humidity and air-quality sensors, occupancy and motion sensors, leak and vibration sensors for predictive maintenance, smart meters and locks. Each is a device on a flaky wireless link that sends a number every few seconds.
MQTT fits that shape: a broker in the middle, publishers that only know a topic name, and subscribers that pick the slice they care about. The OASIS MQTT 5.0 standard (approved on March 7, 2019) defines three delivery levels: at most once, at least once, and exactly once. The rest of this post checks what those words mean once a real network gets involved.
Architecture: paho-mqtt sensors publish JSON readings and a retained status to Mosquitto; a collector with a persistent session subscribes to home/flat1/# and writes to SQLite; on the right, the topic tree and four wildcard filters with what each one selects
The code layout:
telemetry/ broker.py # start a throwaway Mosquitto on a free port topics.py # topic builder and parser device.py # Sensor: paho-mqtt 2.x client, Last Will, flow-control window collector.py # Collector: wildcard subscription, persistent session store.py # SQLite: dedup + per-minute rollup flaky.py # TCP proxy that drops acks or cuts the link experiments/ # qos_drop.py, offline_session.py, lwt_demo.py tests/ # 18 tests, all against a real broker demo.py Step 1. Run a local broker
Mosquitto is in the Ubuntu archive, so no Docker is needed:
sudo apt-get install -y mosquitto mosquitto-clients python -m venv .venv && . .venv/bin/activate pip install paho-mqtt==2.1.0 pytest==9.2.0 Tests are easier with a private broker per test: a fresh process, a free port, no leftover state. This helper writes a minimal config and waits for the port:
"""Start a throwaway Mosquitto broker on a free localhost port.""" import contextlib import pathlib import socket import subprocess import tempfile import time def free_port() -> int: with socket.socket() as s: s.bind(("127.0.0.1", 0)) return s.getsockname()[1] @contextlib.contextmanager def mosquitto(extra_conf: str = "", log=None): port = free_port() with tempfile.TemporaryDirectory() as tmp: conf = pathlib.Path(tmp, "mosquitto.conf") conf.write_text( f"listener {port} 127.0.0.1\n" "allow_anonymous true\n" "persistence false\n" "log_dest stderr\n" "log_type error\n" + extra_conf ) proc = subprocess.Popen(["mosquitto", "-c", str(conf)], stderr=log) try: deadline = time.monotonic() + 5 while time.monotonic() < deadline: with contextlib.suppress(OSError): socket.create_connection(("127.0.0.1", port), 0.2).close() break time.sleep(0.05) else: raise RuntimeError("mosquitto did not start") yield port finally: proc.terminate() proc.wait(5) persistence false keeps everything in memory, which is what a test wants. In production you want the opposite (more on that at the end).
Step 2. Design the topic tree before the first publish
Topics are the API of an MQTT system; once devices in the field publish to them, renaming is a firmware update. The scheme here is home/<site>/<room>/<device>/<metric>:
-
sitelets one broker serve several flats or buildings. -
roombeforedevicematches how people ask questions (“what is the temperature in the kitchen?”). -
devicein the topic means a consumer knows the sender without parsing the payload. HiveMQ’s topic guide recommends embedding the client ID for the same reason. -
metriclast, sohome/+/+/+/temperatureselects every thermometer.
The builder is strict on purpose. A segment with a space, an upper-case letter, a /, a +, a # or a leading $ never reaches the broker:
"""Topic scheme: home/<site>/<room>/<device>/<metric>.""" import re from typing import NamedTuple SEGMENT = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$") class Topic(NamedTuple): site: str room: str device: str metric: str def build(site: str, room: str, device: str, metric: str) -> str: for part in (site, room, device, metric): if not SEGMENT.match(part): # rejects "", "/", "+", "#", spaces, upper case, leading "$" raise ValueError(f"bad topic segment: {part!r}") return f"home/{site}/{room}/{device}/{metric}" def parse(topic: str) -> Topic: parts = topic.split("/") if len(parts) != 5 or parts[0] != "home": raise ValueError(f"not a telemetry topic: {topic!r}") return Topic(*parts[1:]) def status_topic(site: str, room: str, device: str) -> str: return build(site, room, device, "status") The two wildcards behave a little differently from shell globs. + replaces exactly one level. # replaces all remaining levels, must be the last character, and also matches the parent level itself. Topics that start with $ (the broker’s own $SYS/... statistics) are not matched by a filter that starts with a wildcard, so # does not drown your collector in broker metrics. paho ships topic_matches_sub, so these rules can be pinned in a unit test:
def test_wildcard_semantics(): t = "home/flat1/kitchen/th01/temperature" assert matches("home/+/+/+/temperature", t) assert matches("home/flat1/#", t) assert matches("home/flat1/#", "home/flat1") # '#' includes the parent level assert not matches("home/+/temperature", t) # '+' is exactly one level assert not matches("#", "$SYS/broker/uptime") # '$' topics hidden from wildcards The same rules are also checked against the real broker in test_wildcards_on_real_broker: three subscribers (home/+/+/+/temperature, home/flat2/#, #) and four published topics including the bare parent home/flat2. Mosquitto agrees with paho on every one, and the # subscriber receives nothing under $SYS.
Step 3. A paho-mqtt 2.x client (the callback API changed)
If you copy a paho MQTT Python example from an older tutorial, the first line fails on 2.x:
mqtt.Client("sensor-1") ValueError: Unsupported callback API version: version 2.0 added a callback_api_version, see docs/migrations.rst for details Since 2.0 the first argument of Client() is the callback API version. CallbackAPIVersion.VERSION1 still works but is deprecated. With VERSION2, every callback gets reason_code and properties, for MQTT 3.1.1 and 5 alike:
| Callback | VERSION2 signature |
|---|---|
on_connect | (client, userdata, flags, reason_code, properties); flags.session_present |
on_disconnect | (client, userdata, flags, reason_code, properties) |
on_subscribe | (client, userdata, mid, reason_code_list, properties) |
on_publish | (client, userdata, mid, reason_code, properties) |
The migration guide says the old rc == 0 check still works because 0 means success in both versions. A reason code of 0x80 or higher is a failure; ReasonCode.is_failure tells you that directly.
Here is the sensor. The payload carries boot (random per process start), seq (a counter) and the device timestamp. Those three fields make de-duplication possible later. The flow-control window is explained in Step 5, after the experiment that made it necessary.
"""A simulated smart-home sensor that publishes telemetry over MQTT 5.""" import json import threading import time import uuid import paho.mqtt.client as mqtt from paho.mqtt.enums import CallbackAPIVersion from paho.mqtt.packettypes import PacketTypes from paho.mqtt.properties import Properties from . import topics class Sensor: def __init__(self, port, site, room, device, *, qos=1, session_expiry=0, flow_control=True): self.site, self.room, self.device, self.qos = site, room, device, qos self.port, self.session_expiry = port, session_expiry self.boot = uuid.uuid4().hex[:8] # changes on every restart self.seq = 0 self.status = topics.status_topic(site, room, device) # Flow control: QoS 1/2 messages paho holds that the broker has not # finished acknowledging. Kept below the broker's Receive Maximum. self.flow_control = flow_control self.window = 10 # until CONNACK tells us the real limit self.unacked = 0 self.rejected = 0 # PUBACK/PUBCOMP reason code >= 0x80 self.cond = threading.Condition() self.connected = threading.Event() self.client = mqtt.Client( CallbackAPIVersion.VERSION2, # required since paho-mqtt 2.0 client_id=f"sensor-{device}", protocol=mqtt.MQTTv5, ) # Last Will: the broker publishes this if we vanish without DISCONNECT. self.client.will_set(self.status, "offline", qos=1, retain=True) self.client.reconnect_delay_set(min_delay=1, max_delay=4) self.client.on_connect = self._on_connect self.client.on_publish = self._on_publish def _on_connect(self, client, userdata, flags, reason_code, properties): if reason_code.is_failure: return receive_max = getattr(properties, "ReceiveMaximum", 65535) with self.cond: self.window = max(1, receive_max - 1) # one slot for the status self.unacked += 1 # Retained, so anyone subscribing later still sees the current state. client.publish(self.status, "online", qos=1, retain=True) self.connected.set() def _on_publish(self, client, userdata, mid, reason_code, properties): # Called for PUBACK (QoS 1) and PUBCOMP (QoS 2); QoS 0 right after send. with self.cond: if reason_code.is_failure: self.rejected += 1 # e.g. 0x97 Quota exceeded: NOT delivered self.unacked = max(0, self.unacked - 1) self.cond.notify_all() def start(self): props = Properties(PacketTypes.CONNECT) props.SessionExpiryInterval = self.session_expiry self.client.connect("127.0.0.1", self.port, keepalive=5, properties=props) self.client.loop_start() assert self.connected.wait(5), "sensor did not connect" return self def publish(self, metric, value, ts=None, timeout=30): self.seq += 1 payload = json.dumps({"boot": self.boot, "seq": self.seq, "ts": ts or time.time(), "value": value}) topic = topics.build(self.site, self.room, self.device, metric) if self.qos and self.flow_control: with self.cond: # back-pressure instead of an unbounded burst if not self.cond.wait_for(lambda: self.unacked < self.window, timeout): raise TimeoutError("broker has not acknowledged in time") self.unacked += 1 elif self.qos: with self.cond: self.unacked += 1 return self.client.publish(topic, payload, qos=self.qos) def stop(self): # A clean DISCONNECT discards the Will, so announce "offline" ourselves. self.client.publish(self.status, "offline", qos=1, retain=True).wait_for_publish(3) self.client.disconnect() self.client.loop_stop() Three details matter:
-
will_set()must be called beforeconnect(). The broker stores the Will and publishes it only if the connection ends without a normal DISCONNECT. - The Will and the
onlinemessage use the same retained topic, so the retained value is always the latest state. - A clean
disconnect()discards the Will. The MQTT 5 spec deletes the Will when the server receives DISCONNECT with reason code 0x00, sostop()publishesofflineitself.
Step 4. Collector and SQLite: de-duplicate, then aggregate
The collector holds one wildcard subscription and a persistent session (clean_start=False, SessionExpiryInterval=3600). It only subscribes when the broker says it has no session for us; if the session is present, the subscription is already there.
"""Collector: one wildcard subscription, persistent session, dedup into SQLite.""" import json import threading import paho.mqtt.client as mqtt from paho.mqtt.enums import CallbackAPIVersion from paho.mqtt.packettypes import PacketTypes from paho.mqtt.properties import Properties from . import topics class Collector: def __init__(self, port, store, *, client_id="collector", topic_filter="home/#", qos=1, session_expiry=3600, clean_start=False): self.port, self.store = port, store self.topic_filter, self.qos = topic_filter, qos self.session_expiry, self.clean_start = session_expiry, clean_start self.session_present = None self.events = [] # status changes, in arrival order self.ready = threading.Event() self.client = mqtt.Client(CallbackAPIVersion.VERSION2, client_id=client_id, protocol=mqtt.MQTTv5) self.client.on_connect = self._on_connect self.client.on_message = self._on_message self.client.on_subscribe = self._on_subscribe def _on_connect(self, client, userdata, flags, reason_code, properties): self.session_present = flags.session_present if not flags.session_present: # broker forgot us: (re)subscribe client.subscribe(self.topic_filter, qos=self.qos) else: self.ready.set() def _on_subscribe(self, client, userdata, mid, reason_code_list, properties): # v2 callback: one ReasonCode per filter; >= 0x80 means the broker refused it if all(not rc.is_failure for rc in reason_code_list): self.ready.set() def _on_message(self, client, userdata, msg): t = topics.parse(msg.topic) if t.metric == "status": status = msg.payload.decode() self.events.append((t.device, status, msg.retain)) self.store.set_status(t.device, Source:https://dev.to/kate_steeleeee/python-mqtt-for-smart-home-telemetry-qos-under-a-dropped-link-last-will-and-persistent-sessions-7bmRelated posts

Chorus Coding Will Be the Norm. Here's How to Keep Up.
From Accounting Graduate to GoHighLevel Agency Founder

