← Back to archive

Repo of the Day

peterhinch/micropython-mqtt

Published: Jan 27, 2024

Open repository ↗

A 'resilient' asynchronous MQTT driver. Plus a means of using an ESP8266 to bring MQTT to non-networked targets.

Summary

peterhinch/micropython-mqtt is an asynchronous MQTT client library for MicroPython, designed to keep running through WiFi and broker outages. It is built on uasyncio/asyncio and uses non-blocking sockets, making it suitable for IoT firmware on resource-constrained devices. The driver supports ESP8266, ESP32 (including S2/S3), Pyboard D, Raspberry Pi Pico W, Arduino Nano RP2040 Connect, and the Unix build of MicroPython.

What it is useful for

This library is useful when you need an MQTT client on a microcontroller that does not have to be babysat. The README lists concrete problems with the official umqtt client: it can hang on a blocking socket, fail to recover after a WiFi dropout, and provide only partial qos==1 support. This driver addresses each of those by transparently reconnecting after outages, performing qos==1 retransmission, and implementing the keepalive mechanism so the broker's "last will" works.

Typical use cases include sensors that publish to a topic and subscribe to control messages, Pico W or ESP32 nodes running for long periods unattended, and devices that may be near the edge of WiFi range. The README documents eight weeks of continuous runtime on a Pyboard D with about 1M messages. There is also optional MQTTv5 support, at the cost of roughly 3KiB of extra RAM.

Documented limitations to be aware of: qos==2 is not supported, message size should be designed around 1KiB due to RAM, and on the ESP32 an incorrect WiFi password takes about a minute to time out. The ESP8266 cannot compile the module; it must be frozen as bytecode, where it uses about 50% of RAM.

How engineers can use it

Installation on most boards is documented as:

$ mpremote mip install github:peterhinch/micropython-mqtt

Then edit the included mqtt_local_example.py, set config['server'], config['ssid'], and config['wifi_pw'], and save it as mqtt_local.py on the device path.

A typical application creates an MQTTClient from the config dict, calls await client.connect(), and then either awaits client.publish(...) or iterates over client.queue. The client.up event fires whenever connectivity is re-established, so subscriptions can be renewed in a loop. The README's range.py demo is suggested as a starting point for a working subscribe and publish loop. For ESP8266 install notes, SSL/TLS, deep-sleep behavior, and the full constructor dictionary, the README is the source of truth.