Quick answer: MicroPython on the ESP32 usually includes the umqtt.simple client (if import umqtt.simple fails, run import mip; mip.install("umqtt.simple")). Connect to Wi-Fi, then:
from umqtt.simple import MQTTClient
c = MQTTClient("esp32-01", "192.168.1.50", user="esp32", password="secret", keepalive=60)
c.connect()
c.publish(b"home/esp32-01/temperature", b"23.5")To receive, call c.set_callback(fn), then c.subscribe(b"home/esp32-01/led/set"), and call c.check_msg() regularly in your loop (it doesn't block). umqtt.simple doesn't reconnect by itself, so wrap the loop in try/except OSError and reconnect. The complete, reconnecting sketch with Last Will, JSON payloads and LED control is below.
| What you need | Notes |
|---|---|
| ESP32 running MicroPython | Install MicroPython |
| An MQTT broker | Mosquitto on a Pi/PC (install guide), or a public test broker for a first try |
| A way to watch messages | mosquitto_sub, MQTT Explorer or Node-RED |
| Optional: LED on GPIO23, DHT22 on GPIO4 | For the full example |
MQTT in one minute
Devices never talk to each other directly. They connect to a broker, publish messages to topics such as home/esp32-01/temperature, and subscribe to topics they care about. A command topic (…/led/set) and a state topic (…/led/state) keep "what was asked" separate from "what happened". Retained messages give new subscribers the last value instantly, and a Last Will lets the broker announce offline if the ESP32 disappears. Full explanation: MQTT explained: broker, topics, QoS, retained and Last Will.
| Library | Use it when |
|---|---|
umqtt.simple | You want a tiny, dependable client and you'll handle reconnects yourself (this guide) |
umqtt.robust | You want automatic reconnect inside publish/check_msg (a thin wrapper over simple) |
mqtt_as (community) | Larger asyncio projects that must never block |
1. Connect to Wi-Fi (non-fatal)
import network, time
def wifi_connect(ssid, password, timeout_s=20):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(ssid, password)
start = time.time()
while not wlan.isconnected() and time.time() - start < timeout_s:
time.sleep_ms(250)
print("Wi-Fi:", wlan.ifconfig()[0] if wlan.isconnected() else "not connected")
return wlan.isconnected()More on Wi-Fi, static IPs and reconnects: MicroPython ESP32 Wi-Fi.
2. First publish and subscribe
import time
from umqtt.simple import MQTTClient
def on_msg(topic, msg):
print("Received", topic, msg)
c = MQTTClient(b"esp32-01", "192.168.1.50", port=1883,
user=b"esp32", password=b"secret", keepalive=60)
c.set_callback(on_msg)
# must be set before subscribe()
c.connect()
c.subscribe(b"home/esp32-01/test")
c.publish(b"home/esp32-01/hello", b"Hello from MicroPython")
for _ in range(30):
# listen for 30 s
c.check_msg()
# non-blocking; calls on_msg if a message arrived
time.sleep(1)
c.disconnect()Watch and answer from your computer:
mosquitto_sub -h 192.168.1.50 -u esp32 -P secret -t 'home/esp32-01/#' -v
mosquitto_pub -h 192.168.1.50 -u esp32 -P secret -t 'home/esp32-01/test' -m 'ping'Topics and payloads can be str or bytes; the callback always receives bytes, so compare with msg == b"ON" or decode with msg.decode(). wait_msg() also exists, but it blocks until a message arrives, so use check_msg() in anything that does other work.
3. Complete project: sensor + LED + Last Will + auto-reconnect
This main.py publishes DHT22 readings as JSON every 30 seconds, switches an LED from MQTT, reports the LED state (retained), announces online/offline, and recovers from Wi-Fi or broker outages without rebooting.
import network, time, json, machine, dht
from machine import Pin
from umqtt.simple import MQTTClient
WIFI_SSID, WIFI_PASS = "YOUR_WIFI", "YOUR_PASSWORD"
BROKER, USER, PASS = "192.168.1.50", "esp32", "secret"
DEV = "esp32-01"
T_STATE = "home/{}/sensor".format(DEV).encode()
T_LED_SET = "home/{}/led/set".format(DEV).encode()
T_LED_ST = "home/{}/led/state".format(DEV).encode()
T_STATUS = "home/{}/status".format(DEV).encode()
led = Pin(23, Pin.OUT, value=0)
sensor = dht.DHT22(Pin(4))
client = None
def wifi_up():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(WIFI_SSID, WIFI_PASS)
for _ in range(40):
if wlan.isconnected():
break
time.sleep_ms(250)
return wlan.isconnected()
def on_msg(topic, msg):
if topic == T_LED_SET and msg in (b"ON", b"OFF"):
led.value(1 if msg == b"ON" else 0)
client.publish(T_LED_ST, msg, retain=True)
def mqtt_up():
global client
client = MQTTClient(DEV, BROKER, user=USER, password=PASS, keepalive=60)
client.set_last_will(T_STATUS, b"offline", retain=True)
client.set_callback(on_msg)
client.connect()
client.publish(T_STATUS, b"online", retain=True)
client.subscribe(T_LED_SET)
client.publish(T_LED_ST, b"ON" if led.value() else b"OFF", retain=True)
print("MQTT connected")
def publish_reading():
try:
sensor.measure()
data = {"t": sensor.temperature(), "h": sensor.humidity()}
client.publish(T_STATE, json.dumps(data))
except OSError as e:
print("Sensor read failed:", e) # skip, don't publish a fake value
last_pub = time.ticks_ms() - 30000
while True:
try:
if client is None:
if not wifi_up():
raise OSError("no Wi-Fi")
mqtt_up()
client.check_msg()
if time.ticks_diff(time.ticks_ms(), last_pub) >= 30000:
last_pub = time.ticks_ms()
publish_reading()
time.sleep_ms(100)
except OSError as e:
print("Connection problem:", e, "- retrying in 5 s")
try:
client.disconnect()
except Exception:
pass
client = None
time.sleep(5)Test it:
mosquitto_pub -h 192.168.1.50 -u esp32 -P secret -t 'home/esp32-01/led/set' -m ONand watch home/esp32-01/led/state change to ON. Unplug the ESP32 and, after about 1.5× the keepalive (roughly 90 s here), the broker publishes offline on home/esp32-01/status.
Design notes
| Choice | Why |
|---|---|
JSON payload {"t":24.6,"h":51.2} | One message per reading, easy for Node-RED and Home Assistant to parse |
| Command and state on separate topics | Dashboards show what the board did, not just what was asked |
| State and status retained, commands not | A reconnecting board never replays an old ON command |
| Unique client ID per board | Two boards with the same ID kick each other off the broker in a loop |
ticks_ms / ticks_diff timing | Keeps check_msg() running so commands arrive within a fraction of a second |
QoS: umqtt.simple publishes at QoS 0 by default; publish(topic, msg, qos=1) waits for the broker's acknowledgement. Subscriptions accept qos=0 or 1. For a home sensor, QoS 0 for readings and QoS 1 for commands is plenty.
TLS: for brokers on the internet, connect on port 8883 with ssl=True (newer firmware also takes an ssl context). Keep plain 1883 on your LAN only.
Using the data in Home Assistant and Node-RED
Home Assistant (with the MQTT integration set up) can read the JSON readings with a few lines in configuration.yaml:
mqtt:
sensor:
- name: "ESP32-01 Temperature"
state_topic: "home/esp32-01/sensor"
value_template: "{{ value_json.t }}"
unit_of_measurement: "°C"
device_class: temperature
availability_topic: "home/esp32-01/status"
- name: "ESP32-01 Humidity"
state_topic: "home/esp32-01/sensor"
value_template: "{{ value_json.h }}"
unit_of_measurement: "%"
device_class: humidity
availability_topic: "home/esp32-01/status"
switch:
- name: "ESP32-01 LED"
command_topic: "home/esp32-01/led/set"
state_topic: "home/esp32-01/led/state"
availability_topic: "home/esp32-01/status"The default payload_on/payload_off (ON/OFF) and payload_available/payload_not_available (online/offline) already match this script, so no extra settings are needed. Reload the MQTT entities (or restart), and the sensor, humidity and LED switch appear, greyed out whenever the ESP32 is offline.
Node-RED: an mqtt in node on home/esp32-01/sensor set to output a parsed JSON object gives you msg.payload.t and msg.payload.h for gauges and charts; an mqtt out node publishing ON/OFF to home/esp32-01/led/set switches the LED. A ready-made dashboard pattern is in ESP32 DHT11 + BMP280 Node-RED dashboard.
4. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ImportError: no module named 'umqtt' | Firmware without umqtt | import mip; mip.install("umqtt.simple") while on Wi-Fi |
OSError: [Errno 113] ECONNABORTED / EHOSTUNREACH on connect | Wrong broker IP, broker down, or firewall | Ping the broker; check port 1883 is open |
MQTTException: 5 | Not authorised: wrong user/password or anonymous disabled | Fix credentials (MQTT troubleshooting) |
MQTTException: 4 | Bad username or password | Re-check both; watch for spaces |
| Callback never runs | set_callback after subscribe, or check_msg() not called | Set the callback first; call check_msg() in the loop |
Comparing msg == "ON" is always False | Callback gets bytes | Compare with b"ON" or use msg.decode() |
| Disconnects every minute or so | No traffic within keepalive, or duplicate client ID | Call check_msg() regularly (umqtt pings as needed); unique client IDs |
| Board freezes when Wi-Fi drops | Blocking wait_msg() or no exception handling | Use check_msg() and the reconnect loop above |
OSError: -202 | DNS lookup failed for the broker hostname | Use the broker's IP address, or check DNS |
FAQ
Is umqtt built into MicroPython? On the official ESP32 and ESP8266 firmware, usually yes (umqtt.simple and umqtt.robust). On other boards install it with mip.
umqtt.simple or umqtt.robust? Robust adds automatic reconnect inside publish and check_msg, but you still need to handle Wi-Fi drops. The explicit loop above is clearer and works with either.
Can MicroPython talk to Home Assistant? Yes, through Home Assistant's MQTT integration: publish discovery messages to homeassistant/…/config, as in the Arduino MQTT temperature sensor, or add YAML MQTT sensors.
Can I use a public broker? For a quick test, yes (test.mosquitto.org), but anyone can read and write your topics. Use your own broker for anything real.
Next steps
- MQTT explained: QoS, retained and Last Will.
- Node-RED with Mosquitto: build a dashboard for these topics.
- MicroPython DHT22 on ESP32 and SSD1306 OLED.
- MQTT topic naming best practices.
Official reference: umqtt.simple in micropython-lib.
Make reconnects predictable and messages trustworthy
A reconnect loop should recover without flooding the broker or starving the rest of the program. After a connection failure, wait before retrying and increase the delay gradually, for example 1, 2, 4, 8 and then 15 seconds, with a small random variation if many devices may reconnect together. Reset the delay after a stable connection. Keep Wi-Fi recovery and MQTT recovery as separate steps: the ESP32 may still be associated with the access point even when the broker is unavailable.
Use a clear topic contract before connecting dashboards or automations. A practical device might publish telemetry to home/esp32-01/telemetry, accept commands on home/esp32-01/led/set, report the confirmed output on home/esp32-01/led/state, and publish availability on home/esp32-01/status. Do not report a requested state as though it has already happened; publish the state only after the GPIO or actuator has actually changed.
Choose MQTT delivery options according to the data:
- QoS 0 is often enough for frequent temperature updates where the next reading will arrive soon.
- QoS 1 is useful for commands or important state changes when delivery should be acknowledged, but the receiver must tolerate duplicates.
- Retained messages are useful for the latest state or availability, not for a stream of historical samples.
- Last Will reports an unexpected disconnect. Publish online after a successful connection and configure the will before connecting.
Secure the broker connection
The example's username and password are sent over an ordinary TCP connection unless TLS is configured. Use a private broker network for experiments, unique credentials per device, and broker-side topic permissions so one device cannot publish to every topic. For traffic crossing an untrusted network, configure TLS and validate the broker certificate using a MicroPython build and client configuration that support it. Never paste real Wi-Fi or broker credentials into a public article, repository or screenshot.
When a device repeatedly reconnects, check the broker log and the client identifier. Two devices using the same client ID can disconnect one another because the broker treats them as the same client. Also check keepalive timing, access-control rules, DNS/IP changes and whether the router isolates wireless clients.




