Home Home automation guides MQTT Discovery with a NodeMCU and Home Assistant

NodeMCU with Sensors in waterproof casing

MQTT Discovery with a NodeMCU and Home Assistant

Back in November 2020, I kicked off a fascinating journey into the world of MQTT and Home Assistant, laying the groundwork for making some awesome smart devices. Let me remind you how I clearly depicted how to create a simple MQTT switch in Home Assistant. No doubt, that step-by-step guide works like a charm, but let's face it, who loves manual work anyway?

If there is anything I dread doing repeatedly, it's looking for a way to automate it. Luckily, Home Assistant doesn't disappoint - with its impressive and pretty handy MQTT discovery feature.

In this post, we'll go on a journey together! I'll reveal some tricks and hacks I've used to make the most of MQTT discovery. Also, you'll get a bonus: I'll share my Arduino program in case you're eyeing this for your projects. Sounds exciting, right?

Here is a quick rundown of the topics we'll cover:

  1. What is MQTT Discovery?
  2. How can you use MQTT Discovery on a NodeMCU?

Let's roll up our sleeves and dive right in! I believe that you will find this feature as enthralling as I have!

What is MQTT Discovery?

At its core, MQTT Discovery is simply the means to guide your MQTT broker (we use Mosquitto running inside of Home Assistant in this example) to the topics it needs to pay attention to. Sounds like a breeze, yes? Well, it is.

In one of my previous posts, I offered some valuable insight into how you can manually instruct Mosquitto to tune into a certain topic. Works perfectly, but when you have more than a handful of devices, it's safe to say the thrill wears off pretty fast.

The beauty of MQTT Discovery lies in its easy automation. Your MQTT device (an Arduino in our scenario) shoots a message to a discovery topic on the MQTT broker. This message tells it which topic to pay heed to for messages. As a result, your MQTT device pops up on the broker's radar without you breaking a sweat over manual configuration. Basically, your MQTT broker will always be in-the-know about all devices that have declared their presence - and this requires zero effort from you!

Home Assistant has an in-built discovery topic which I use quite often - MQTT discovery topic. I primarily use my MQTT devices as plant sensors, and currently, my device houses three sensors. Each sensor has a unique 'state' and logically, each requires its very own discovery topic. In my case, my discovery topics are: - homeassistant/sensor/plant_sensor_1/temperature/config - homeassistant/sensor/plant_sensor_1/humidity/config - homeassistant/sensor/plant_sensor_1/moisture/config

Imagine having to register each of these sensors manually for each MQTT device. The drudgery will not only be tiring, but you'd spend more time on configuration than genuinely enjoying the functionalities of your smart devices! With MQTT Discovery, all I do is connect the Arduino to a power source and voila! The MQTT broker instantly recognizes it and its various attendant sensors. Talk about convenience!

How can you use MQTT Discovery on an NodeMCU?

So how does it look like when you're coding MQTT Discovery on your Arduino or NodeMCU? Surprisingly, it bears a lot of similarity to the manual coding in Home Assistant. Except for a tiny twist: instead of setting up each sensor in Home Assistant, you're doing it in your Arduino program and then shipping it to Home Assistant.

I'll skip the technicalities on a few things for now:

  • Wi-Fi setup in your Arduino program
  • Reading Sensor data in your Arduino program
  • Sending MQTT sensor data to Home Assistant

Each of these topics is worthy of its own blog post! But worry not, they're all included in the code sample for a complete picture. Enough chit-chat, let's dive into some code!

Sending the discovery message

There are two major prerequisites to sending the discovery message:

  • Active Wi-Fi connection
  • A correctly configured Pubsub client

You can get all the juicy details on this in the full code sample provided later. I've organized the discovery messages into functions for tidiness and to prevent intermingling with the main Arduino program.

Here's a sneak peek of the discovery message for the temperature sensor of a particular device:

This script distinctly points out a value_template for this sensor. The entire state of the MQTT device, comprising the values of three sensors, is sent as a JSON object to Home Assistant.

Since Home Assistant would be puzzled about what to do with such an object, we have to guide it on how to extract the temperature sensor's value from this JSON object. By referring to the incoming JSON string as a JSON object, we can use dot notation to get nested values. A pipe is used to specify a default value (zero in this case) for instances when there is no moisture sensor or if something goes awry.

By dispatching this JSON object to the MQTT discovery topic, Home Assistant now knows how to handle the messages it receives.

For more context on how this discovery function fits into the grand scheme of things, my full script is available just below.

The Full Arduino program

Here's the action-packed script as promised:

On the face of it, it might seem a bit strange due to the empty loop function. Well, that's because I'm leveraging the 'Deep Sleep' mode of the NodeMCU to save on energy. After the script has successfully delivered all sensor data to Home Assistant, the NodeMCU powers itself off and revives after a 60-second gap. This helps my regular batteries last significantly longer.

However, keep in mind that this is a general approach, you may have a unique use for the script.

Conclusion

MQTT Discovery has completely transformed my experience with MQTT devices. Gone are the days when I had to manually register devices in Home Assistant - the devices now conveniently self-register. This practically eliminates the likelihood of typos and other human-induced errors. Hooking up a new device is as simple as powering it on and leaving the rest to MQTT discovery magic.

Couple this with tools like Grafana and InfluxDB, and you'll see the sensor values pop right up after you plug in your device.

I hope this has been as informative and enjoyable for you as it was for me! Stay tuned for more posts on the topics not discussed here today, like Wi-Fi connections for the NodeMCU.

Posted on: Feb 2, 2022 Last updated at: Jan 7, 2024

Frequently asked questions

What is MQTT Discovery?
MQTT Discovery is a feature of Home Assistant which enables your home automation system to automatically detect new devices that are connected to your MQTT broker.
What is NodeMCU?
NodeMCU is an open-source firmware and development kit that helps with prototyping IoT devices.
Why is MQTT Discovery important?
MQTT Discovery saves time by eliminating the need for manual configuration of each new device added to your smart home setup.
How do I enable MQTT Discovery in Home Assistant?
MQTT Discovery is enabled by default in Home Assistant, but you can verify that it's enabled by checking the configuration.yaml file.
How do I connect a NodeMCU to my smart home using MQTT Discovery?
You can connect a NodeMCU to your smart home using MQTT Discovery by flashing it with an appropriate firmware and configuring the MQTT broker credentials in the device.
What are the benefits of using MQTT Discovery?
The benefits of using MQTT Discovery include saving time, automating the process of device discovery, and reducing errors in configuration.
What if my device doesn't support MQTT Discovery?
If your device doesn't support MQTT Discovery, you may need to manually configure the device in Home Assistant by adding it to the configuration.yaml file.
How can I troubleshoot MQTT Discovery issues?
MQTT Discovery issues can be resolved by checking device firmware updates, verifying compatible versions of Home Assistant and MQTT broker, and reviewing the configuration.yaml file.
What other devices can I connect to my smart home using MQTT Discovery?
You can connect a wide range of IoT devices to your smart home using MQTT Discovery including sensors, switches, and cameras.
Is MQTT Discovery secure?
MQTT Discovery is secure when the MQTT broker is configured correctly with appropriate security measures such as encryption and authentication.