Merging two binary sensors into one template sensor

Hello! I got problem with combining two binary sensors into one template sensor. After creating new template sensor it doesn’t show any status - it refreshes each time for 5 minutes and it displays unknown status and it starts counting again from 5 min. (tried to replace open/ close to on/ off but still with no luck). Is it also possible to refresh template sensor each 10 sec? My code looks like that:

- name: brama_wjazdowa
      unique_id: "Brama wjazdowa"
      state: >-
        {% if is_state('binary_sensor.brama1_contact', 'open' ) %}
        {% if is_state('binary_sensor.brama2_contact', 'closed' ) %}
            otwarta
        {% endif %}
        {% elif is_state('binary_sensor.brama1_contact', 'closed' ) %}
        {% if is_state('binary_sensor.brama2_contact', 'open' ) %}
            zamknięta
        {% else %}
             w ruchu
        {% endif %}
        {% endif %}
      attributes:
        attribute: "{{ now().minute }}" 

Thank you in advance for any info and help!

Indenting looks out and the “if” logic is a bit suspect so how about something like this:

- name: brama_wjazdowa
  unique_id: "Brama wjazdowa"
  state: >-
    {% if is_state('binary_sensor.brama1_contact', 'open') and is_state('binary_sensor.brama2_contact', 'closed') %}
       otwarta
    {% elif is_state('binary_sensor.brama1_contact', 'closed') and is_state('binary_sensor.brama2_contact', 'open') %}
       zamknięta
    {% else %}
       w ruchu
    {% endif %}
  attributes:
    attribute: "{{ now().minute }}"

Note that I have not tested the above but hope it helps.

As the previous poster pointed out the ifs are not covering all cases. For instance, both sensors open would not yield a result. Also make sure using the developer tools that the state is actually open and closed and not on and off. The if suggestion above looks to be much better, but still may be wrong regarding the actual states the sensors return.

As to your question a out refreshing: template sensors update when needed based on the entities used. Putting in an an attribute for a minute creates extra work for Home assistant, but does not improve the result. So I would not do that at all. Just fix the template so it does what you need and let HA figure out when to update it.

Agree, binary sensors are always on or off, not open or closed. Open or closed are labels for representation purposes based on entity class.

Thank you for fast respond - all answers are correct and the new template sensor works like I intended!

2 Likes