Tech, web, programming, home automation, networking, and geeky blog.

23 Dec 2020

Wemos D1 mini - Talking to Home Assistant via MQTT with Auto Discovery

Home Assistant is a great tool for automating, controlling, logging, and reporting on many home automation and IoT (Internet of Things) devices. Many of these make use of MQTT to talk together, you may have come across this with things like Tasmota.

In this post we’ll look at sending a message to Home Assistant via MQTT from a Wemos D1 Mini, however this would work with any ESP8266 device. Specifically we’ll look at auto discovery for a binary sensor.

In the last post we looked at connecting the Wemos D1 mini to wifi, here we’ll build on that. We’ll need two libraries, so goto Tools->Manage Libraries and add PubSubClient as well as Arduino JSON, then include them at the top of your sketch with the following:

#include <PubSubClient.h>
#include <Arduino_JSON.h>

Below this we need to define the client with PubSubClient client(espClient); where the wifi client has been passed in.

Within the setup() method we need to connect to the MQTT server and send the configuration message for Home Assistant.

client.setServer("", 1883); // Set the IP and port for MQTT.
while (!client.connected()) { // Keep checking if MQTT is connected.
  if (client.connect("Wemos", "myusername", "MyPassw0rd")) { // Connect to MQTT.
    JSONVar root; // Define a JSON variable.
    root["stat_t"] = "wemos/state"; // Set the state topic.
    root["name"] = "wemos"; // Set the name.
    root["uniq_id"] = "wemos"; // Set a unique ID.
    root["dev"]["name"] = "wemos";  // Set the device name.
    root["dev"]["mdl"] = "d1";  // Set the device model.
    root["dev"]["ids"] = "wemos";  // Set the device idenifier.
    root["off_delay"] = 30;  // Set the time after which the device will be marked as being off.
    String message = JSON.stringify(root); // Convert JSON to a string.
    mqttPublish("homeassistant/binary_sensor/wemos/config", message.c_str()); // Send the configuration message to Home Assistant.
    mqttPublish("wemos/state", "ON"); // Tell Home Assistant the device is on.
  } else {
    Serial.print("failed, rc=");
    Serial.print(client.state()); // Print the state if connection fails.
    Serial.println(" try again in 5 seconds");
    delay(5000); // Wait 5 seconds, and try again.

The above code connects to the MQTT, sends the configuration to Home Assistant, then tells Home Assistant the Wemos D1 Mini is on. This was quite tricky to get working, especially with the auto discovery to generate a device and entity within Home asisstant, however this combination of config seemed to work. On the documentation for the binary sensor you’ll find all the different config values.

Once this runs Wemos will be shown as “on” in Home Assistant, after 30 second it will flip to “off”, clicking the reset button will rerun the setup telling Home Assistant the Wemos is on again.

comments powered by Disqus