Using timers in my setup
Thu 08 June 2023
In my previous article I explained how I've created atomic automations. This helps me getting things tidy and my automations working and manageable. Up till now, if I wanted to keep lights on for a certain amount of time after motion detected, I used the following construction:
"Motion On":
- trigger:
- motion detected
- action:
- event: motion_on
"Porch Light On":
- trigger:
- event: motion_on
- event: welcome_home_lights
- action:
- switch light on
The 'welcome_home_lights' event is not used in this example, but shows how other events could turn lights on as well.
"Motion Off":
- trigger:
- motion cleared for X minutes
- action:
- event: motion_off
"Porch Light Off":
- trigger:
- event: motion_off
- event: all_lights_off
- action:
- switch light off
For the 'for X minutes' in the "Motion Off" automation I used a time helper, which could be controlled outside the automation, but I wanted this to be robuster. One of the arguments to use timers is that they survive a restart of Home Assistant. Besides that I just wanted to test if I could fit this into my 'one automation, one action' strategy.
The way I handled this is:
- the timer starts after "Motion Off"
- if motion is detected during timer countdown, the timer is reset
- after the timer finishes, the light should switch off
Using this structure, I don't have to modify "Motion On" and "Motion Off", but I need to add three automations for the timer (besides the timer helper, of course), and I need to modify the trigger that turns off the light.
First I create the new automations:
"Timer - start":
- trigger:
- event: motion_off
- action:
- start timer
"Timer - cancel":
- trigger:
- event: motion_on
- action:
- cancel timer
"Timer - finished":
- trigger:
- timer finished
- action:
- event: timer_finished
and then the altered "Porch Light Off":
- trigger:
- event: timer_finished
- event: all_lights_off
- action:
- switch light off
And that was all to it. I could easily fit those timer actions into the motion automations, but then I mix a sensor with some other automation, which again could result in a spaghetti of automations, which I don't want.