Binary quorum sensor

I want to create a binary sensor, which is on, when at least other two sensors are on, using the following definition:

binary_sensor:
  black_chair_quorum_2:
    friendly_name: "Black Chair Quorum 2"
    value_template: >-
        {% set count = 0 %}
        {% for sensor in ['binary_sensor.chair2_opening_5', 'binary_sensor.2_opening_5', 'binary_sensor.black_chair_3_opening_5'] %}
          {% if is_state(sensor, 'on') %}
            {% set count = count + 1 %}
          {% endif %}
        {% endfor %}
        {{ count >= 2 }}

This unfortunately does not work. The counter value is always 0, so the sensor is always off.

How can I define a quorum sensor, which is on, if at least other two are on?

configuration.yaml

template:
  - binary_sensor:
      - name: "Black Chair Quorum 2"
        state: >
          {{ [ 'binary_sensor.chair2_opening_5',
               'binary_sensor.2_opening_5',
               'binary_sensor.black_chair_3_opening_5' ]|selectattr('state','eq','on')|list|count >= 2 }}

Also just FYI this is not a good entity id:

binary_sensor.2_opening_5

Starting an entity id with a number can cause issues. See: https://www.home-assistant.io/docs/configuration/templating/#entity_id-that-begins-with-a-number

Does selectattr() work with an entity_id string?

I had to use
… map('states') | select('eq','on') …

1 Like

This didn’t work because of scope: the count inside the loop is a different variable to the one outside. To directly fix your code, you’d need a namespace:

    value_template: >-
        {% set ns = namespace(count = 0) %}
        {% for sensor in ['binary_sensor.chair2_opening_5', 'binary_sensor.2_opening_5', 'binary_sensor.black_chair_3_opening_5'] %}
          {% if is_state(sensor, 'on') %}
            {% set ns.count = ns.count + 1 %}
          {% endif %}
        {% endfor %}
        {{ ns.count >= 2 }}

Better solution using modern format:

template:
  - binary_sensor:
      - name: "Black Chair Quorum 2"
        state: "{{ ('binary_sensor.chair2_opening_5', 'binary_sensor.2_opening_5', 'binary_sensor.black_chair_3_opening_5' )|select('is_state','on')|list|count >= 2 }}"

EDIT: I see others have answered whilst I was typing this, but will leave here anyway as an explanation of why yours didn’t work; as well as a slightly different approach to the solution.

You could create this via the UI: create a template binary sensor with just the bits in {{ ... }} in the State template box:

Thanks a lot folks for a quick and rich on ideas reply!

It’s widen my mind on what Jinja templates can offer and brought the light on what has really happened with the state of the poor variable count.

I’m coming from this discussion empowered and even more confident about the bright future of HomeAssistant!

Special thanks on @tom_l for the notice about sensor id. I was not aware of this limitation. I’ve renamed immediately. It is always pays out giving speaking names names for entities.