
Welcome back! Today we dive into the secret language of smart homes. How does your smart switch tell your hub it was flipped without instantly killing its battery? The answer is MQTT (Message Queuing Telemetry Transport). Itâs a lightweight protocol that lets your devices aggressively gossip with each other through a central broker. Time to start the rumor mill.
When you have dozens (or hundreds) of devices on a network, having them constantly ask âDid anything happen? Did anything happen?â is incredibly inefficient. MQTT solves this by using a Publish/Subscribe (PubSub) model.
Here is why itâs the gold standard for smart homes and IoT:
Think of MQTT like a radio station.
home/livingroom/temperature).home/livingroom/temperature).Letâs look at how easy it is to speak MQTT using an ESP32 and the popular PubSubClient library in Arduino.
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* mqtt_server = "192.168.1.100"; // Your MQTT Broker IP
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void callback(char* topic, byte* message, unsigned int length) {
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
// If a message is received on the topic, do something!
if (String(topic) == "home/livingroom/light") {
if(messageTemp == "on") {
digitalWrite(LED_BUILTIN, HIGH);
} else if(messageTemp == "off") {
digitalWrite(LED_BUILTIN, LOW);
}
}
}
void reconnect() {
while (!client.connected()) {
// Attempt to connect
if (client.connect("ESP32Client")) {
// Once connected, publish an announcement...
client.publish("home/livingroom/status", "online");
// ... and resubscribe
client.subscribe("home/livingroom/light");
} else {
delay(5000); // Wait 5 seconds before retrying
}
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop(); // Keeps the MQTT connection alive
}
In this snippet, our ESP32 is both a publisher (announcing itâs online) and a subscriber (listening for commands to turn its light on or off).
With MQTT under your belt, you can integrate custom hardware into Home Assistant, Node-RED, and virtually any other smart home platform effortlessly. Stay tuned for the next lesson where weâll set up our own Mosquitto broker!
To follow along with this lesson, youâll need the following components: