An approach to Home Assistant

State machines

I'm a couple of years into my Home Assistant journey now and one thing I have learned is it is not a hobby with an end goal. It's a never-ending hunt for perfect solutions. Pretty much every aspect of it that I thought was finished, I've come back to and refined.

As I've learned more about what works and what doesn't, I'm applying some of the techniques I've learned through web development and I'm moving my setup into a state-driven system.

This is inspired by the concept of state-machines, where basically the system adheres to a logic structure designed in a way that prevents something being in a state that doesn't make sense. You can't walk through the door unless the door is open.

This approach should produce more reliable systems because it avoids many of the conflicts that typically plague software and create bugs and failures.

Because home automation is a complex arrangement of triggers and actions which can all be happening asynchronously, it's the ideal problem for a state-machine to solve.

An example

I'm using PIR and mmWave sensors to determine whether somebody's in the office. I use this to control the lights and heating in there.

Typically what happens is, I walk into the office and the PIR sensor fires immediately. At this point, the mmWave sensor hasn't caught up so the two sensors are telling different stories; one says the room is occupied, the other says not.

A minute later, the mmWave sensor has put its glasses on, realised I'm in the room and the two sensors are now in agreement.

For a while.

I've been sat down doing important things that don't involve waving my arms around so the PIR sensor has got bored and reported that it has stopped detecting motion. The sensors are disagreeing again.

All this means that any automation based on occupancy need to know which sensor to trust at any one moment.

This is where a Helper can... help. I created a boolean helper called Office Occupied. When either sensor detects a person, it switches to true. When both sensors stop detecting, it switches to false.

I then changed all my automations to be driven by the Helper and not the devices.

This has several advantages.

  • I have one sensor to tell me if somebody's in the office, so I can display this
  • the decisions around occupancy are contained in one place; they don't need to be repeated for every occupancy-based automation
  • I can replace any of the sensors and I only have to update the Helper toggle automation
  • It's easy to add more presence sensors or other ways of detecting occupancy. Any new trigger can just flip the boolean to true and the automations will already know what to do.

While a true/false switch is as simple as a state machine can get, the experiment was a success and I've gone on to make more sophisticated state machine solutions.

What that impossible perfection looks like for me now is for the whole system to run as a state machine.