How can I get the initial state of an MQTT switch?

You’ve found a good work around but it is unfortunate that the Arduino library doesn’t support QoS. Though given the limited memory I suppose they had to cut something. Most of the time, particularly in HA situations one can live with a default QoS, particularly if one sets up heartbeats, acks, queries, and/or other ways to confirm the message made it and write rules and code to handle multiple copies of the same message.

I myself implemented a query (i.e. publish a message which caused the devices to report their current state) and recently implemented a heartbeat.

Also, don’t forget about the LWT. Once I started using those it became almost trivial to detect and identify when devices go offline and depending on actuators in place address the problem.

NOTE: adding a temp/humidity sensor that reports on a set period makes a great heartbeat :slight_smile:

However, I can see some cases, particularly when one is dealing with irrigation and power generation where one might want to use something like QoS 2 on top of some of the other mechanisms described. A missed message or a duplicate message could have bad to catastrophic consequences.

And the more logic that one can push off to MQTT the less I have to write. :wink:

Have a look at the Time Of Day and Separation of Behaviors design patterns. What you are describing is really close to a simple state machine and the ToD plus SoB design patterns get you most of the way to a state machine.

I could see implementing a Switch for when the “tank demand” messages are allowed to pass through or not. Then another rule or set of rules that calculates whether or not the home is in the right state to allow it and set the Switch accordingly.

The tl;dr is that by separating the calculation of state from the logic that cares about state it becomes far easier to control, maintain, and understand the rules logic. And there are tons of ways to develop, model, and understand state machines which can become important as someone’s HA becomes more and more complex. And since you are “automating all the things!” :slight_smile: you might get to the point that using tools to help model your environment might become helpful.

I completely agree. You also get to leverage the work done to set up the broker and comms in the first place. Adding a new device becomes almost trivial. I am very grateful that I set up Mosquitto back when I started to play with Mqttitude (now called OwnTracks).

I’m glad to see you making so much progress. If you have any lessons learned or challenges you have overcome I bet the community would love to read about them.

1 Like