Template switch not updating when entity behind value template changed

Hello,

i have a template switch to represent the child lock of my xiaomi air purifier. It works fine when triggered manually, and it also reflects well the state when i change the child lock value from the Xiaomi app.

switch:
  - platform: template
    switches:
      purifier_childlock:
        value_template: "{{ state_attr('fan.purifier_livingroom','child_lock') }}"
        turn_on:
          service: xiaomi_miio.fan_set_child_lock_on
          data:
            entity_id: fan.purifier_livingroom
        turn_off:
          service: xiaomi_miio.fan_set_child_lock_off
          data:
            entity_id: fan.purifier_livingroom

I also have an automation that turns the switch on if it is off, so that it’s always on.

Trigger:

entity_id: switch.purifier_childlock
platform: state
to: 'off'

Action:

alias: ''
data: {}
entity_id: switch.purifier_childlock
service: switch.turn_on

Today i unplugged my purifier, and plugged it again (7:38pm). When the purifier loses power, the child lock will always reset to off (hence my automation!). I was surprised to see that my automation didn’t kick in:

  • i checked the States in the Developer Tools, and saw that the switch was off
  • i checked the Logbook, and saw nothing related to my switch changing state

I tried to trigger the automation manually (8:24pm), and it worked well to toggle the switch on.

Would you know why when the referenced entity of the value_template is available again, the value_template is not updated ?

Can you post a screenshot of the attributes on fan.purifier_livingroom when plugged in. Also take a screenshot of the attributes when not plugged in.

Here is when it’s on and everything is working as expected:

Then after i turned it off:

Then after i turned it on:

And the associated Logbook:

I was thinking, value_template uses state_attr which will return None if the attribute doesn’t exist (which is the case when fan.purifier_livingroom is unavailable. I suppose the template switch will interpret None as off?

In that case when the purifier turns on, since the value_template will still be false, there is no state change, and no automation triggered.

That would also explain the Logbook entry at 9:12am triggered the automation, but since the purifier is unavailable that does nothing.

Maybe i should use the availability_template from the Template Switch?

I changed the config to use the availability_template:

switch:
  - platform: template
    switches:
      purifier_childlock:
        value_template: "{{ is_state_attr('fan.purifier_livingroom','child_lock', true) }}"
        availability_template: "{{ not is_state('fan.purifier_livingroom','unavailable') }}"

Also switched state_attr to is_state_attr for the value_template.

And now it’s working fine !