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:
- What is MQTT Discovery?
- 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