Inverting a binary sensor - unexpected behaviour

Hello, everyone,

I use Home Assistant via docker from my self-built NAS.
Primarily I use different Xiaomi Aquara sensors with MQTT, this works very well so far.
Since there are no affordable rain sensors for Zigbee on the market, I soldered two cables to an Aqara door sensor and soldered them to a “rain sensor board” (looks like this):
Picture

This means that if the board gets wet, the circuit is closed.

The problem is that the contacts are mixed up for my purpose.
If the circuit is open, I get an “on” message in HASS and HASS shows it wrong:

https://www.home-assistant.io/integrations/binary_sensor/

–> door sensor: on = open
–> moisture: off = wet

I tried to write a template for this myself, but failed to implement it, because the state is always shown as “dry”:

configuration.yaml:

binary_sensor:
  - platform: template
    sensors:
      regenfall:
        friendly_name: "Regensensor_virtuell"
        device_class: moisture
        value_template: >-
          {% if is_state('binary_sensor.0x00158d0004a01943_contact', 'off') %}
            on
          {% else %}
            off
          {% endif %}

Result:

What am I doing wrong here?

Just do

value_template: "{{ is_state('binary_sensor.0x00158d0004a01943_contact', 'off') }}"

Template binary sensors are on when the value template is True and off if it’s False.

Might also want to set an availability template in case the sensor goes to unavailable (up to you):

availability_template: "{{ not is_state('binary_sensor.0x00158d0004a01943_contact', 'unavailable') }}"

That works. Thanks a lot! :+1: