Not sure I get the question. If, for example, a number helper or sensor is used to store the last recorded number of open
entities, it would be instantiated by HA with a default value of zero.
The incrementing and decrementing of this variable would be handled by the automation, so the state wouldn’t need to be defined by a template. Something like the following:
automation:
trigger:
- platform: template
value_template: "{{ states.binary_sensor | selectattr('entity_id', 'search', '<KEYWORD>') | selectattr('state', 'eq', 'on') | list | count != states('input_number.open_sensors') | int(0) }}"
variables:
current_open_count: "{{ states.binary_sensor | selectattr('entity_id', 'search', '<KEYWORD>') | selectattr('state', 'eq', 'on') | list | count }}"
newly_closed_entities: >
{{ states.binary_sensor | selectattr('entity_id', 'search', '<KEYWORD>') | selectattr('state', 'eq', 'off') | selectattr('entity_id', 'in', states('input_text.open_entities').split(',')) | map(attribute='entity_id') | list }}
action:
- repeat:
sequence:
- choose:
- conditions:
- condition: template
value_template: '{{ current_open_count < states(''input_number.open_sensors'') | int(0) }}'
sequence:
- service: input_number.decrement
target:
entity_id: input_number.open_sensors
# Not sure what the OP wants to do at this point, lets say notify
- service: notify.phone_id
data:
message: >
{{ newly_closed_entities[repeat.index] }} has closed.
- service: input_text.set_value
data:
# Wouldn't be surprised if there is a better way to pull a value out of the list, but I don't feel like finding it for this example
value: "{{ newly_closed_entities | rejectattr('entity_id', 'eq', newly_closed_entities[repeat.index] | join(',') }}"
- conditions:
- condition: template
value_template: '{{ current_open_count > states(''input_number.open_sensors'') | int(0) }}'
sequence:
# Just copy the above, but opposite
# Increment, notify opened, add entity to list
until:
- condition: template
value_template: '{{ current_open_count == states(''input_number.open_sensors'') | int(0) }}'
The above assumes there are two helpers, input_number.open_sensors
and input_text. open_entities
. These can be instantiated as zero and an empty string, respectively, and the above should handle the population, I think. Also, I’m sure there are plenty of mistakes in there, I couldn’t actually test anything other than some of the templates and I got tired of writing it but I’m hoping it’ll still get the point across.
Am I incorrect in thinking something like the above could theoretically handle an unknown list of sensors?