As I am moving my automations from AppDaemon to native HA (with pyscript for the more complicated ones) I realize that I often have automations where I do something when the state of an entity is on, and something else when it is off.
A typical example is a water leak: when it is on all hell breaks loose (several notifications of several kinds) and when it is off I just send one or two cancellations for persistent ones.
In Python it is simply a case of if/then/else - is there an equivalent in the native automations?
(worst case I will send the info to pyscript and do the conditional actions there)
Thank you very much - this is exactly what I was looking for. I added the code below directly in automations.yaml (as a reference if someone was looking for something similar), but it was also properly rendered in the GUI (in the form of nested blocks - very nice.
- id: 36f2fd76-36dc-4ce6-b168-967b416a96fe
alias: fuite salle de bain
trigger:
- platform: state
entity_id: binary_sensor.waterleak_sdb_water_leak
action:
- choose:
- conditions:
- condition: state
entity_id: binary_sensor.waterleak_sdb_water_leak
state: 'on'
sequence:
- service: notify.gotify_alert
data:
message: fuite salle de bain
- service: mqtt.publish
data:
topic: alert
payload: fuite salle de bain
- conditions:
- condition: state
entity_id: binary_sensor.waterleak_sdb_water_leak
state: 'off'
sequence:
- service: mqtt.publish
data:
topic: alert
payload: ''
mode: single
trigger = 'input_boolean.test_1 == "on"' # or something much more complicated
@state_trigger(trigger)
def when_it_is_on():
pass
@state_trigger(f"not ({trigger})")
def when_it_is_off():
pass
Obviously, for very simple “on” or “off” type situations it’s more readable to just write the whole trigger in state_trigger. But if your trigger gets complex, just negating it with “not” can handle both sides. There are other ways, of course, but I find this to be the cleanest for most cases.