I want to turn a light on with movement and keep it on until no movement is detected for xx minutes
This is off the HA cookbook site
Do I need one automation for the “Turn on kitchen light when there is movement” part and a second one for the “Turn off kitchen light 10 minutes after last movement”
When I see two aliases in one code, is that a giveaway to me that I need two?
automation:
- alias: Turn on kitchen light when there is movement
trigger:
platform: state
entity_id: sensor.motion_sensor
to: 'on'
action:
service: light.turn_on
entity_id: light.kitchen_light
- alias: Turn off kitchen light 10 minutes after last movement
trigger:
platform: state
entity_id: sensor.motion_sensor
to: 'off'
for:
minutes: 10
action:
service: light.turn_off
entity_id: light.kitchen_light
I like this a lot, very succinct. If someone needs to do a more complicated action, multiple actions, not use a template, etc… I recommend the wait_for_trigger. I only re-iterate because I feel like this newish feature is not well known!
As a refinement, you may want to add the following condition to the automation:
condition: >
{{ (trigger.to_state.state == 'on' and is_state('light.kitchen', 'off')) or
(trigger.to_state.state == 'off' and is_state('light.kitchen', 'on')) }}
Basically, it prevents turning on the light if the light is already on (and turning it off if it is already off). This prevents sending needless commands to the light.
The reason it calls homeassistant.turn_on (or turn_off) is because the entities aren’t all the same domain but a combination of light and switch domains.