Help with Template Sensor: Count lights in the same area as the sensor

Hello all,

I’m trying to create a template sensor that counts all light entities (state: on) that are in the same area as the template sensor itself. Somehow I cannot access the area of the template sensor - can someone point me in the right direction? This is what I have at the moment:

{% set target_entities = area_entities(area_name(this.entity_id)) %}
{{ (states.light | 
    selectattr('state', 'eq', 'on') | 
    rejectattr('entity_id', 'in', label_entities('Group')) | 
    rejectattr('entity_id', 'in', label_entities('Helper')) | 
    selectattr('entity_id', 'in', 
      target_entities) | list | length) | int(0) }}

Specifically, it seems that this.entity_id is not working correctly.

Hope someone knows what I’m missing here :slight_smile:

Edit:

The following works correctly but doesn’t use the area of the template sensor since it’s hardcoded:

{% set area = 'Keuken' %}
{% set target_entities = area_entities(area) %}
{{ (states.light | 
    selectattr('state', 'eq', 'on') | 
    rejectattr('entity_id', 'in', label_entities('Group')) | 
    rejectattr('entity_id', 'in', label_entities('Helper')) | 
    selectattr('entity_id', 'in', 
      target_entities) | list | length) | int(0) }}

Seems to work if you provide a default…

{% set target_entities = area_entities(area_name(this.entity_id)|default('Keuken', 1)) %}
{{ target_entities
| select('contains', 'light.')
| select('is_state', 'on')
| reject('in', label_entities('Group')) 
| reject('in', label_entities('Helper'))
| list | length }}

Thanks for your help, but providing a default will just always use that area for the template, not the area of the template sensor.

In my testing it works for the desired Area once you assign an Area to the template sensor entity. If you are using a Template Helper, ignore what the Preview is telling you, the actual sensor state should be correct.