Hi everyone, I’m building a smart home setup with openHAB and several ESP32 sensor nodes (temperature, humidity, motion). I recently followed this tutorial on using ESP32 with MQTT. It’s a great walkthrough of securing and structuring the MQTT flow: https://www.theengineeringprojects.com/2021/11/esp32-mqtt.html. That gave me a solid foundation for data publishing and topic structure.
Now I’m implementing this in openHAB via the MQTT binding (https://www.openhab.org/addons/bindings/mqtt/) and experimenting with retained vs. non-retained messages. My question is: what’s the recommended way to handle retained messages in openHAB when dealing with dynamic sensor updates, temperature, and motion triggers, without causing stale readings or sync issues?
As a general rule, commands should not use retained while sensor readings and statuses should use retained. But as with all general rules, there can be lots of exceptions.
For the most part, is this a value you want OH (or what ever is subscribing for the data) to receive even if OH wasn’t connected to the MQTT broker when the message was sent? Then you want to use retained. Is this a value whole value is short lived and/or should only be received by the subscriber zero or one times? Then retained should not be used.
So, for example, the online/offline LWT topic works best if when the publisher connects to the broker it publishes “online” as a retained message and then the LWT publishes “offline” as a retained message when the connection is lost. That way, whether OH was connected or not it wil always know if the publisher is online.
But, a command to turn off a light shouldn’t be sent retained because if your ESP32 restarts, it will receive the most recently sent command a second time. On-the-other-hand, that might be desireable behavior as you may want the ESP32 to respond to a commandt that occurred when it was offline or to return to the state it was most recently commanded to.
Newer versions of MQTT support a retained timeout which will cause the broker to store the message as retained but only for a given time. But I don’t think OH supports that, but your ESP32 library might.
Ultimately you have to think about what each of these messages mean and whether it makes sense that a new subscriber receives the message every time they connect, or if the message only has meaning if the client happened to be connected to the broker when the message was sent.
why not use ESPHome and the OpenHab Binding to connect the ESP32 based sensors? I have about 10 ESP’s (climate, particular matter, rain, noise, etc) connected this way and that works fine