Concept explainer · Intermediate · 3 min read
MQTT and Home Assistant for ESP32
Send Sensor Data and Control Relays
By Geekobot Learning Team · Updated 24 Oct 2026
On this page
MQTT is a lightweight messaging system: devices publish messages to named topics on a broker, and anything subscribed to that topic receives them. For a smart home, run the Mosquitto broker on Home Assistant, have your ESP32 publish sensor readings (for example home/livingroom/temperature) and subscribe to a command topic to switch a relay. MQTT discovery messages make the entities appear in Home Assistant automatically. ESPHome is a no-code alternative.
Key specs at a glance
- Pattern
- Publish / subscribe through a broker
- Broker
- Mosquitto (Home Assistant add-on or any Linux box)
- Port
- 1883 (plain), 8883 (TLS)
- QoS
- 0 at most once, 1 at least once, 2 exactly once
- Library
- PubSubClient or AsyncMqttClient on ESP32
- Alternative
- ESPHome with its native Home Assistant API
MQTT in five ideas
- 1Broker: a server that receives every message and passes it on. Devices never talk directly.
- 2Topics: text paths such as
home/garden/soilorhome/pump/set. Use+for one level and#for all levels when subscribing. - 3Publish: send a message to a topic.
- 4Subscribe: ask the broker for every message on a topic.
- 5Retained messages and last will: a retained message is kept for new subscribers (good for the last known state); a last-will message is published by the broker if a device drops off (good for 'offline' status).
Setting up Home Assistant and Mosquitto
- 1In Home Assistant, install the Mosquitto broker add-on (Settings, Add-ons) and start it.
- 2Create a Home Assistant user for your devices (for example
mqtt_esp) and use its username and password in the ESP32 code. - 3Add the MQTT integration (Settings, Devices and services); it usually finds the broker automatically.
- 4Use MQTT Explorer or the integration's 'Listen to a topic' tool to watch messages while testing.
Home Assistant itself can run on a Raspberry Pi, a mini PC or a virtual machine.
ESP32 code: publish temperature, control a relay
Install PubSubClient by Nick O'Leary. The example publishes a value every 30 seconds and switches a relay on GPIO 26 when Home Assistant sends ON or OFF.
#include <WiFi.h>
#include <PubSubClient.h>
const char* WIFI_SSID = "your-wifi";
const char* WIFI_PASS = "your-password";
const char* MQTT_HOST = "192.168.1.10"; // Home Assistant IP
const char* MQTT_USER = "mqtt_esp";
const char* MQTT_PASS = "secret";
const int RELAY = 26;
WiFiClient net;
PubSubClient mqtt(net);
unsigned long lastSend = 0;
void onMessage(char* topic, byte* payload, unsigned int len) {
String msg;
for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];
if (String(topic) == "home/pump/set") {
digitalWrite(RELAY, msg == "ON" ? HIGH : LOW);
mqtt.publish("home/pump/state", msg.c_str(), true); // retained state
}
}
void connectMqtt() {
while (!mqtt.connected()) {
if (mqtt.connect("esp32-pump", MQTT_USER, MQTT_PASS,
"home/pump/status", 0, true, "offline")) {
mqtt.publish("home/pump/status", "online", true);
mqtt.subscribe("home/pump/set");
} else {
delay(2000);
}
}
}
void setup() {
pinMode(RELAY, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
mqtt.setServer(MQTT_HOST, 1883);
mqtt.setCallback(onMessage);
}
void loop() {
if (!mqtt.connected()) connectMqtt();
mqtt.loop();
if (millis() - lastSend > 30000) {
lastSend = millis();
float temp = 27.4; // replace with your sensor reading
mqtt.publish("home/pump/temperature", String(temp, 1).c_str());
}
}Make entities appear automatically: MQTT discovery
Home Assistant listens on homeassistant/<component>/<object_id>/config. Publish a retained JSON config once at start-up and the entity appears with no YAML. For the temperature above, publish to homeassistant/sensor/esp32pump_temp/config:
{"name":"Pump temperature","state_topic":"home/pump/temperature","unit_of_measurement":"°C","device_class":"temperature","unique_id":"esp32pump_temp"}
For the relay, use the switch component with command_topic home/pump/set and state_topic home/pump/state. PubSubClient's default packet size is 256 bytes, so call mqtt.setBufferSize(512) before sending long config messages.
MQTT or ESPHome?
ESPHome lets you describe sensors and relays in a short YAML file, builds the firmware for you, and connects to Home Assistant through its own native API (MQTT optional). It is faster for standard sensors and supports over-the-air updates. Write your own MQTT code when you need custom logic, non-Home Assistant brokers, or devices that also talk to other systems such as Node-RED or a cloud service.
Common mistakes to avoid
- Hard-coding a blocking reconnect loop that stops the rest of the code forever.
- Forgetting mqtt.loop(), so incoming messages never arrive.
- Publishing state without the retain flag, so Home Assistant shows 'unknown' after a restart.
- Using the same client ID on two devices; they keep kicking each other off.
- Leaving the broker open with no username and password.
Frequently asked questions
What is MQTT used for?
Sending small messages between devices through a central broker. It is the standard way for DIY sensors and switches to talk to Home Assistant, Node-RED and many IoT platforms.
Do I need a broker for MQTT?
Yes. Devices only talk to the broker. Mosquitto is the usual choice and runs as a Home Assistant add-on.
What port does MQTT use?
1883 for plain connections and 8883 for TLS-encrypted connections.
Is ESPHome better than writing MQTT code?
For standard sensors and relays with Home Assistant, ESPHome is quicker. Custom MQTT code gives more control and works with any broker or platform.
What is MQTT QoS?
Quality of service: 0 sends once with no confirmation, 1 guarantees delivery at least once, 2 exactly once. QoS 0 or 1 suits most home sensors.
Parts for this guide
- ₹74View
Terms in this guide
Projects that use it
Put this into practice: 249 step-by-step builds in our project library use parts from this guide.
Keep learning
Sources
- OASIS MQTT 3.1.1 and 5.0 specifications
- Home Assistant MQTT integration and discovery documentation
- PubSubClient library documentation
- ESPHome documentation
Written by the Geekobot team from manufacturer datasheets. Always check the datasheet for the exact part and variant you buy.

