what i want is this to trigger when the attribute ‘mains’ goes from ‘False’ to ‘True’. However when i restart HA, it fires even when going from ‘Unknown’ to ‘True’ also.
In short, how do i set this trigger so that the ‘mains’ attribute triggers when going from ‘False’ to ‘True’ only?
Actually, I think the way to do it (i.e., prevent the automation running on a state change where the old state did not exist) is simply to check trigger.from_state. Also, since the attribute is already a bool the trigger can be simplified, too. @febalci try:
I see. I hadn’t considered the possibility that if the previous state was ‘unknown’ then trigger.from_state isn’t defined (and that’s all the condition needs to test).
@123 and @pnbruckner thanks a lot for your help. This was a two way automation to understand whether mains power is Off or On. “{{ trigger.from_state }}” alone did not work in ‘False’ to ‘True’ condition. So i combined both your suggestions and made some changes like:
- alias: Power Back On
trigger:
- platform: template
value_template: '{{state_attr(''sensor.crow_alarm_system'',''mains'') }}'
condition:
condition: template
value_template: >
{{ trigger.from_state is defined }}
Not exactly sure why had to make the changes you did, but then again I don’t know the full behavior of sensor.crow_alarm_system either. As long as it works for you, that’s the main thing.
Generally when quoting a template that also uses quotes inside, you should quote the entire template with one kind of quote, and use the other inside. The typical way is use double-quotes for the entire template and single quotes inside. So:
- alias: Home Power
trigger:
- platform: state
entity_id: sensor.home_power
condition:
condition: template
value_template: >
{{ trigger.from_state.state != 'unknown' }}
action:
- service: notify.pushover
data_template:
message: >
{% if is_state('sensor.home_power','True') %}
Power On...
{% else %}
Power Off!!!
{% endif %}
I also found out (at last) how to write to log file for automation debugging purposes:
action:
- service: system_log.write
data_template:
message: "The state of the switch is from: {{trigger.from_state.state}} tgo:{{trigger.to_state.state}}"
level: warning