Sensor value templates code problem

Hello,

I have the following sensor created in my configuration.yaml:

  - platform: template
    sensors:
      office_window:
          icon_template: mdi:window-open
          friendly_name: Sensor Office Window
          value_template: >
            {%  if is_state('binary_sensor.geam_office', 'on')  %}
            DESCHIS
            {% else %}
            INCHIS
            {% endif %}
            {% if states('binary_sensor.geam_office') == 'unavailable' %}
              {{ states('sensor.office_window') }}
            {% else %}
              {{ states('binary_sensor.geam_office') }}
            {% endif %} `

In the first if part I tried to convert On/Off message to Inchis/Deschis and in the second one l ignored the Unavailable status of the sensor ( the window sensor go in sleep mode after 15 seconds)
Everything works but now I have the both messages from sensor on Glance card:
INCHIS Off and DESCHIS On
Screenshot 2022-07-14 at 15-44-09 Overview – Home Assistant

Can somebody help me please?
Thanks
Marius

So, if I understand you correctly, the issue with your existing binary sensor is that it turns “unavailable” so you want to keep the previous open/closed state?

I have never tried this type of circular reference in a template sensor, but maybe it works for you and what’s now missing is to combine the different states. One edge case to test is for example what this sensor does right after Home Assistant starts while the binary sensor is unavailable.

My recommendation is to stick to a binary sensor and set its device class so that on/off are automatically translated to open/closed in your language. Try this:

template:
  - binary_sensor:
      - name: Office Window
        device_class: window
        state: >
          {% if states('binary_sensor.geam_office') == 'unavailable' %}
            {{ states('binary_sensor.office_window') }}
          {% else %}
            {{ states('binary_sensor.geam_office') }}
          {% endif %}
1 Like

Hi,
Thank you very much and appreciate!
Works perfectly!
Cheers!
Marius

1 Like