Has anyone seen an if-else block executing the code on both the then and the else sides on an automation?
This automation simply turns the lights on at sunset and off at sunrise. The surprising thing is that once every few days it will execute light.turn_on in the then block and continue to also execute light.turn_off inside the else block.
alias: Night Lighting - Outside
description: Turns on or off the outside lights according to time of day
trigger:
- platform: sun
event: sunset
offset: '00:15:00'
id: sunset
- platform: sun
event: sunrise
offset: '-00:15:00'
id: sunrise
condition: []
action:
- if:
- condition: trigger
id: sunset
then:
- service: light.turn_on
data: {}
target:
entity_id: light.front_lights_switch
else:
- service: light.turn_off
data: {}
target:
entity_id: light.front_lights_switch
mode: single
In this trace you can see that both sides of the if-else ran during the same triggering:
I think if/then is only supported in scripts, not in automations. Not sure why it doesn’t throw an error, unless you are just testing and haven’t restarted HA since adding?
Read this:
I could of course be wrong, haven’t written automations for a while…
scripts are just simply the action section of an automation. All options in scripts are valid for the action section of an automation.
the automation docs also pretty much states as much:
Automation Actions
The action of an automation rule is what is being executed when a rule fires. The action part follows the script syntax which can be used to interact with anything via services or events. For services you can specify the entity_id that it should apply to and optional service parameters (to specify for example the brightness).
That’s one interpretation of what happened. Here’s another:
When Home Assistant turns on an entity, the entity must acknowledge the command. If the acknowledgement isn’t received promptly, Home Assistant sets the entity back to its original state (off).
Notice in the Trace Timeline that it indicates
Call Service ‘Light: Turn on’ Front lights
then it reports it turned on the entities followed by turning them off. There’s no indication of
Call Service ‘Light: Turn off’ Front lights
FWIW, you can reduce the automation to this:
alias: Night Lighting - Outside
description: Turns on or off the outside lights according to time of day
trigger:
- platform: sun
event: sunset
offset: '00:15:00'
- platform: sun
event: sunrise
offset: '-00:15:00'
condition: []
action:
- service: "light.turn_{{ iif(trigger.event == 'sunset', 'on', 'off') }}"
target:
entity_id: light.front_lights_switch
mode: single
That makes sense. It must be that the trace is informing of the state correction when there’s acknowledgment delay, not about calling the light.turn_off service.