How to make a template sensor

I am trying to make a sensor that I can use in an automation. I got the code from Home Assistant - Alert.

I used the Developer section to make sure I got the parameters correct.

Here is my code:

binary_sensor:
  - platform: template
    sensors:
      tilt_battery_low:
        value_template: "{{ state_attr('zwave.ecolink_garage_door_tilt_sensor', 'battery_level') < 50 }}"
        friendly_name: "Tilt battery is low"

I get an error in the log stating there is an error in this code. The error text doesn’t provide any clue to me, other than something is wrong.

I appreciate any help!

Please try this as template.

{{ state_attr('zwave.ecolink_garage_door_tilt_sensor', 'battery_level') | int < 50 }}

This makes the state_attr a int to compare with 50

The important thing to know is that the state of entities in Home Assistant are always strings and you can’t compare a string to a number.

So before doing the comparison you must convert the string to a number. We have two filters to do this:

| int converts the string to an integer (no decimal/fractional part), ('1.234' ) | int == 1

| float converts the sting to a floating point number, (has a fractional part). ('1.234' ) | float == 1.234

Attributes of entities in Home Assistant recently obtained the ability to be more types than just string.

Thanks for the quick and perfect assistance! Converting to int did the trick!

1 Like