Is it possible to have a binary sensor template default to keeping the current value when its input sensor goes unavailable?

I have a binary sensor, which detects if there is anything using power in the bathroom, and is defined like this:

- binary_sensor:
    - name: "Bathroom power usage"
      unique_id: 'bathroom_power_usage'
      state: "{{ states('sensor.bathrooms')|float > 10 }}"

My problem is that the sensor.bathrooms sensor often reports unavailable for a second, and so this template isn’t constantly true for the length of time I need to trigger alerts.

I know defaults exist, so I could make it default to true, but I’d rather find a smarter solution that won’t assume the state is true if the sensor goes unavailable for a long time. The ideal solution would be something where I could tell the template to not change the state based on an unavailable input. So if the binary sensor were currently false, and the input sensor went unavailable for a second it would remain false, but if the binary sensor were currently true, and the input sensor went unavailable it would remain true.

I’ve been trying to figure out if this is possible, but I’m not sure it is. I’ve been trying to do something where I use the current state of the binary sensor itself as a default value for that binary sensor, but can’t seem to get that to work.

Any ideas?

Try this:

state: >
  {% if states('sensor.bathrooms')|is_number %}
    {{ states('sensor.bathrooms')|float > 10 }}
  {% else %}
    {{ this.state }}
  {% endif %}
2 Likes

Awesome, thank you, just tested and that worked.

I ended up coming up with this similar template after posting

state: >
  {% if is_number(states('sensor.bathrooms')) %}
    {{states('sensor.bathrooms')|float > 10 }}
  {% else %}
    {{ states('binary_sensor.bathroom_power_usage_default')|bool }}
  {% endif %}

But my version does not work. I guess this.state is the magic I was looking for.

You nearly had it. This would also have worked:

state: >
  {% if is_number(states('sensor.bathrooms')) %}
    {{states('sensor.bathrooms')|float > 10 }}
  {% else %}
    {{ states('binary_sensor.bathroom_power_usage')|bool }}
  {% endif %}

Not sure why you tacked _default on to the end of the entity id.

Ah ok, so at the risk of confusing things, the reason I added _default to that one was because it was a new sensor I created to test this out, so the name was different. Turns out the real reason mine didn’t work, was because I had assumed the unique_id (which I am specifying) would be what the entity_id (which I didn’t explicitly specify) was, but looks like it used the name instead to derive the entity_id. I fixed the entity_id in my version and it does now work as well. this.state is much cleaner though so I’ll keep that.

Thanks again for the help.