Stuck on how to do Value_Template

Hope someone can help here, basically I have a few template sensors setup with the following value_template:

      value_template: >-
        {% if states('sensor_battery_level') | float < 15 %}
            on
        {% else %}
            off
        {% endif %}

When home assistant is up and running etc this works fine and gives on and off just as it should, the problem is that during a restart or if there is an issue with a sensor and the sensors state is “unavailable” my template above sets my sensor to “on” which causes major issues. I need it to default to “off” all the time unless the sensor drops below 15

What can I do?

Use an elif for unavailable and return off

Thanks for the quick reply but I have already tried and failed, not sure what I was doing wrong

Can you post examples?

Is this a binary sensor?
If so, your template can be simplified to:

      value_template: >
        {{ states('sensor_battery_level') | float < 15 }}

I think I would put the “unavailable” test first since the first thing to return true is what gets returned. So if it’s unavailable but the < 15 test gets evaluated first it will be true and it won’t get past that point and will return ‘on’ instead of the desired ‘off’.

There’s a typo here:

        {{ states('sensor_battery_level') | float < 15 }}

That should be

sensor.battery_level

not

sensor_battery_level

Try this:

      value_template: >-
        {% set bl = states('sensor.battery_level') %}
        {{ 'off' if bl == 'unavailable' or bl | int >= 15 else 'on' }}

EDIT

Correction. Added int filter to convert string to integer. Fixed typo.

This sounds like it should work so have given it a go but it doesn’t seem to work

This is my code:

- platform: template
  sensors:
    hallway_motion_battery_low:
      value_template: >-
        {% set bl = states('sensor.hallway_motion_sensor_battery_level') %}
        {{ 'off' if bl == 'unavailable' or bl >= 15 else 'on' }}

Any ideas?

I’ve added a small correction to the original template. I overlooked to convert the string value to integer and I stupidly copied the original typo!

Try it again.

      value_template: >-
        {% set bl = states('sensor.battery_level') %}
        {{ 'off' if bl == 'unavailable' or bl | int >= 15 else 'on' }}
1 Like

Thank you soo much I was able to get it work using your code!! Thank you!

1 Like