Condition template to check entity(switch) available or not

Hi,

I have sonoff TH16 with state in Hass template as follows:

template: {{ states.switch.sonoff_10008dxxxx }}

result:
<template TemplateState(<state switch.sonoff_10008dxxxx=off; manufacturer=SONOFF, model=TH16, sw_version=PSA-BHA-GL v2.6.0, cloud=online, rssi=-38, temperature=26.0, friendly_name=Water heater 1, supported_features=0, icon=mdi:water-boiler @ 2020-12-04T13:17:39.929194+07:00>)>

I though {{ states.switch.sonoff_10008dxxxx.attributes.cloud == online }} should return TRUE value.

but HASS return result in below.

{{ states.switch.sonoff_10008dxxxx.attributes.cloud != online }}  ----> TRUE
{{ states.switch.sonoff_10008dxxxx.attributes.cloud == online }} ----> FALSE

Can you explain if I do wrong or misunderstanding here.

Thank you

1 Like

Try this:

{{ states.switch.sonoff_10008dxxxx.attributes.cloud != 'online' }}  
{{ states.switch.sonoff_10008dxxxx.attributes.cloud == 'online' }}
1 Like

thanks @tom_l . Like a magic :heart: :heart: :heart:

1 Like

You should use this format though, to prevent errors:

{{ state_attr('switch.sonoff_10008dxxxx', 'cloud') != 'online' }}  
{{ state_attr('switch.sonoff_10008dxxxx', 'cloud') == 'online' }}

thanks @tom_l . I tried and both return False

{{ state_attr('sonoff_10008dxxxx', 'cloud') }}

return None. Oh, i found typing error in above missing switch. before sonoff. Thank you :heart:

1 Like

in automation we will have syntax problem with the mark " ’ ". here is working code just for anyone need it

    - condition: template
      value_template: '{{ state_attr("switch.sonoff_10008dxxxx", "cloud") != "online" }}'

Not if you put the double quotes outside the template (the preferred style):

  - condition: template
      value_template: "{{ state_attr('switch.sonoff_10008dxxxx', 'cloud') != 'online' }}"

The other way is the way the UI editor does it, escaping the single quotes with a single quote:

  - condition: template
      value_template: '{{ state_attr(''switch.sonoff_10008dxxxx'', ''cloud'') != ''online'' }}'

It’s awful. Don’t do this.

The final way is with no quotes outside a multi line template:

  - condition: template
      value_template: >
        {{ state_attr('switch.sonoff_10008dxxxx', 'cloud') != 'online' }}
1 Like

thanks @tom_l I often got trouble with the syntax in automation. your examples so helpful for me. :heart: :heart: :heart: