Invert a binary_sensor with template

Trying but failing, any help?

The below give error

 - platform: template 
    sensors: 
        terrace_rain_sensor: 
          value_template: >-
   {%- if is_state("binary_sensor.rain_sensor_terrace", "off")
              -%}
          On
          {%- else -%}
          Off
          {%- endif %}
        device_class: moisture
        friendly_name: Rain sensor terrace

Your indentation is incorrect. And you need to use all lower case for the states. Try:

  - platform: template
    sensors:
      terrace_rain_sensor:
        value_template: >
          {% if is_state("binary_sensor.rain_sensor_terrace", "off") %}
            on
          {% else %}
            off
          {% endif %}
        device_class: moisture
        friendly_name: Rain sensor terrace

Thanks I will try, following other examples I can across the below code which does not give error when checking configuration. What do you think?

Also other issue I see when the origin binary_sensor is Unavailable, also the inverted binary_sensor should give Unavailable not off …

  - platform: template 
    sensors:
        terrace_rain_sensor: 
           friendly_name: Rain sensor terrace
           entity_id: 
             - binary_sensor.rain_sensor_terrace
           value_template: >-
              {%- if is_state("binary_sensor.rain_sensor_terrace", "on") -%}
              Dry
              {%- else -%}
              Wet
              {%- endif -%}

your configuration does give error, I have to take out device_class, then there is no error

Sorry, my mistake. Try this:

  - platform: template
    sensors:
      terrace_rain_sensor:
        value_template: >
          {{ is_state("binary_sensor.rain_sensor_terrace", "off") }}
        device_class: moisture
        friendly_name: Rain sensor terrace

Not sure why it wouldn’t accept the device_class option. Unless you’re using an older version of HA that didn’t implement that yet for template binary sensors, or didn’t accept moisture as an option. When you get an error it’s helpful to share the detailed error message rather than just saying it didn’t work. Often there is useful clues in the error message.

BTW, you can’t set a template binary_sensor to unavailable. You could do that with a template sensor, though.

Ops: I was puttig the code under sensor: and not under binary_sensor: all the time … that’s why all the problems.
YOur code works fine, thanks

1 Like