chumicro-mqtt
A non-blocking MQTT 3.1.1 client (QoS 0 + 1) that fits inside your runner tick. MQTT is the lightweight publish/subscribe protocol most IoT brokers speak.
Publish and subscribe at QoS 0 or QoS 1, set a last will, retain messages, and match wildcard topics. Messages published before the broker connection is up wait in a bounded queue and go out on connect, and inbound size limits keep one huge payload from exhausting a small heap. No threads, no async: the client does a bounded slice of work per tick, so a slow broker or a large message never stalls the rest of your loop. Built on chumicro-sockets (TCP + TLS) and chumicro-timing (ticks).
Part of the ChuMicro family: small, focused Python libraries for microcontrollers and laptops. Browse all libraries.
Install
# CircuitPython (after `circup bundle-add ChuMicro/ChuMicro-Bundle`)
circup install chumicro_mqtt
# MicroPython
mpremote mip install github:ChuMicro/ChuMicro-Bundle/chumicro_mqtt
# CPython
pip install chumicro-mqtt
For bundle setup, pre-compiled .mpy bundles, the experimental channel, and details on PyPI naming, see the chumicro INSTALL guide.
Quick example
from chumicro_timing import ticks_ms
from chumicro_mqtt import MQTTClient
# On CircuitPython pass radio=wifi.radio; the kwarg is ignored on MP / CPython.
# from_config builds the transport factory: the client dials the broker
# non-blocking (one connect phase per tick) and self-heals after drops.
client = MQTTClient.from_config(
{"mqtt.broker.host": "broker.example.com", "mqtt.broker.port": 1883},
radio=wifi.radio,
)
client.on_message = lambda topic, payload: print(topic, payload)
client.connect()
# Drive from a tick loop.
while True:
now = ticks_ms()
if client.check(now):
client.handle(now)
QoS 0 + QoS 1 are implemented; QoS 2 raises UnsupportedQoSError. Last-will, retained messages, wildcard topic matching (topic_matches), and a structured oversized-message policy are all built in.
What's included
| Symbol | Purpose |
|---|---|
MQTTClient(socket, *, client_id, ...) |
Main client. Runner-shaped (check(now_ms)/handle(now_ms)). Topics go on the wire exactly as written. |
client.publish(topic, payload, *, qos=0, retain=False, on_publish=None) |
QoS 0 or 1. Before CONNECTED, the when_disconnected policy applies (queue / raise). |
client.subscribe(topic, qos=0, *, on_subscribe=None) |
Single-topic subscribe. A declaration valid in any state: call it before connect() and the first CONNACK sends it (self-heal reconnects replay it); on_subscribe fires once on the granting SUBACK. |
client.unsubscribe(topic, *, on_unsubscribe=None) |
Mirror of subscribe: retracts the declaration in any state, sends UNSUBSCRIBE when CONNECTED. |
client.on_message + topic_matches(topic, pattern) |
Inbound routing: the catch-all callback plus the public wildcard matcher (+ one segment, # trailing tail). |
client.connect() / .disconnect() |
Lifecycle. |
MQTTClient(..., when_disconnected="queue", pre_connect_queue_size=8) |
Pre-connect publish policy ("queue" / "raise") and the queue bound. |
WhenOversized.{DROP_SILENT,DROP_WITH_EVENT,DISCONNECT} |
Policy for inbound PUBLISHes larger than rx_buffer_size. |
ProtocolState.{DISCONNECTED,AWAITING_TRANSPORT,CONNECTING,CONNECTED,FAILED} |
Lifecycle states. AWAITING_TRANSPORT appears while a transport_factory drives the transport up. |
MQTTBackpressureError |
Raised when an outbound publish overflows max_tx_queue_size (or the pre-connect queue under "queue"). Drain via handle() and retry. |
MQTTError / MQTTConnectError / MQTTProtocolError / UnsupportedQoSError |
Exceptions. |
topic_matches(topic, pattern) |
Public wildcard matcher. Encoder + decoder primitives (encode_publish, encode_varlen, decode_varlen, encode_string) stay internal to chumicro_mqtt._wire. |
Tuning for tick-latency vs throughput
handle() does exactly one recv_into and one send per tick, so each call yields back to the runner after one socket syscall. Three MQTTClient(...) constructor knobs let you trade tick fairness for throughput:
| Knob | Default | What it bounds |
|---|---|---|
recv_budget_per_tick |
1024 (bytes) |
Cap on the single per-tick recv_into call. Without it, an oversized-tier rolling drain of a multi-KB inbound PUBLISH would draw the whole payload in one syscall; the cap means it arrives across several ticks instead, keeping each tick short. Raise for fast big-blob ingestion at the cost of per-syscall latency. |
max_tx_queue_size |
20 packets |
Hard cap on pending outbound packets. Sized for the runner-shaped sensor profile (publish every N seconds; queue stays near zero). Appending past the cap raises MQTTBackpressureError; protocol-internal traffic (PUBACK responses, retransmits, PINGREQ) bypasses the cap so QoS-1 / keepalive contracts hold. Failed QoS-1 publishes roll back the packet_id allocation cleanly so the id pool isn't leaked on backpressure. Raise for bursty publishers; each slot pins ~8 bytes long-lived on MP / CP. |
send_timeout_seconds |
inherits ack_timeout_seconds (5 s) |
Maximum time the socket can stay non-writable with a packet queued before the client transitions to FAILED. Re-arms on every successful send: a steady drip of small sends never trips it, only a stalled socket does. Catches NAT-style silent-drops on the outbound path that would otherwise let the queue grow until MQTTBackpressureError. |
Where this fits
Depends on chumicro-sockets (TCP + TLS) and chumicro-timing for ticks. Used directly in app code; no other ChuMicro library depends on it.
Platform support
Works on CPython, MicroPython, and CircuitPython.
Examples
| Example | What it shows |
|---|---|
telemetry.py |
Periodic QoS-1 publish on a real CP/MP board. Brings wifi up, connects to a broker, subscribes to a command topic, publishes a synthetic reading every N seconds while an LED-blink counter verifies the publish never blocks waiting for PUBACK. Reads wifi and broker config from runtime_config.msgpack (chumicro-workspace) with a constants fallback. Broker host and port must be set explicitly; the library refuses to silently dial a third-party broker. Cross-runtime (CP + MP). |
bench.py |
Self-driving validation bench. Deploy it and watch serial: the device runs the scenarios end-to-end (steady inline, oversized drain, oversize-topic, QoS-1 round-trip, sustained burst, keepalive) against a real broker and prints a pass/fail summary table. Used to confirm the library's heap-bounded oversize handling and the two-tier inbound model behave as advertised on a 256 KB-RAM-class board. Optional companion bench_host.py (host-side, needs pip install paho-mqtt) captures the verdict from the broker and can publish a 64 KB hostile payload for extra oversized-tier stress. |
Wiring wifi and broker config for the examples
The hardware-facing examples need wifi credentials and a broker host and port. The telemetry example reads [wifi] for credentials and [telemetry] for the broker host, port, and topic, from a runtime_config.msgpack (chumicro-workspace) with a constants fallback in the file. The library itself never reads TOML. It takes a chumicro-sockets socket and goes, so config wiring stays in the application layer.
Memory and leak testing
A host-side suite uses tracemalloc to verify the client doesn't leak across its hot paths: QoS 0 and QoS 1 publish, inbound recv, and subscribe/unsubscribe cycles.
Contributing
Issues, bug reports, and pull requests are welcome, and so is "I ran it on this board and here's what happened", some of the most useful feedback a hardware project can get. Development happens in the ChuMicro repository, whose contributing guide covers setup and the test workflow.
Docs
📖 Stable docs · Experimental docs
Find this library
- PyPI: chumicro-mqtt
- Bundle: ChuMicro-Bundle (CircuitPython & MicroPython)
- Experimental bundle: ChuMicro-Bundle-Experimental
- Source: libraries/mqtt
License
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file chumicro_mqtt-0.28.2.tar.gz.
File metadata
- Download URL: chumicro_mqtt-0.28.2.tar.gz
- Upload date:
- Size: 101.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0244f2eac24b19842038e78967cba3afb7a02372ba2661ca29a72cf6ac736764
|
|
| MD5 |
8d162658ccea6e00560bbbd6a9f5a252
|
|
| BLAKE2b-256 |
17cf7cbaf8eba1be4670967e6d439a2fda747ea231c11f2a684c17bf1355bd12
|
Provenance
The following attestation bundles were made for chumicro_mqtt-0.28.2.tar.gz:
Publisher:
promote.yml on ChuMicro/ChuMicro
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
chumicro_mqtt-0.28.2.tar.gz -
Subject digest:
0244f2eac24b19842038e78967cba3afb7a02372ba2661ca29a72cf6ac736764 - Sigstore transparency entry: 2385771689
- Sigstore integration time:
-
Permalink:
ChuMicro/ChuMicro@8cff500e8abdfbc94ed759d398a7070815901d4f -
Branch / Tag:
refs/heads/main - Owner: https://github.com/ChuMicro
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
promote.yml@8cff500e8abdfbc94ed759d398a7070815901d4f -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file chumicro_mqtt-0.28.2-py3-none-any.whl.
File metadata
- Download URL: chumicro_mqtt-0.28.2-py3-none-any.whl
- Upload date:
- Size: 26.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
59fdfb8b0e8a4fd82d2719dc5ac585ae32febbbc5d0be49d83498a230797aab1
|
|
| MD5 |
80f26a4e56e0ad35496193bca91c19e9
|
|
| BLAKE2b-256 |
656fef1861522fbd527153788ff7ac08da48ff0e597b1360460381035234b5ce
|
Provenance
The following attestation bundles were made for chumicro_mqtt-0.28.2-py3-none-any.whl:
Publisher:
promote.yml on ChuMicro/ChuMicro
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
chumicro_mqtt-0.28.2-py3-none-any.whl -
Subject digest:
59fdfb8b0e8a4fd82d2719dc5ac585ae32febbbc5d0be49d83498a230797aab1 - Sigstore transparency entry: 2385772367
- Sigstore integration time:
-
Permalink:
ChuMicro/ChuMicro@8cff500e8abdfbc94ed759d398a7070815901d4f -
Branch / Tag:
refs/heads/main - Owner: https://github.com/ChuMicro
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
promote.yml@8cff500e8abdfbc94ed759d398a7070815901d4f -
Trigger Event:
workflow_dispatch
-
Statement type: