I have built a template sensor that takes all of the power entities in an area and combines them into a new template sensor. the problem is that my logs are filled with errors in the logs that a loop has beed detected as the template sensor also exists in the area that its capturing (and rightfully so)
I want to add a filter to exclude the template sensor name from the calculation but i am struggling to find the right name for the attribute to exclude
{% for s in states.sensor %}
{% if s.state != 'unavailable' and s.attributes.device_class == 'power' and s.attributes.unit_of_measurement == 'W' and area_name(s.entity_id) == 'Living Room' and s.state >= '0' and **s.attributes.friendly_name** != 'Power-Area-Living Room-Total' %}
{% set ns.states = ns.states + [ s.state | float ] %}
{% endif %}
{% endfor %}
{{ ns.states | sum | round(2) }}
```
As already mentioned, rewrite to only use filters. I would probably do it something like below, completely untested so may well contain typos or other errors you need to correct.
Not quite sure whether this.entity_id is available to a template sensor, if not replace it with whatever hardcoded entity id your sensor has. Couldnāt quite figure out how to filter on area_name in just the one expression, so had to store an intermediate result in a variable and do a zip.
The only problem i have is that the selectattr for >= 0 āselectattr(āstateā, ā>=ā, 0)ā returns TypeError: ā>=ā not supported between instances of āstrā and āintā
I am not sure who to do a type change on state to make it work. Its not a huge problem as its just a sanity check in case i have a sensor that reading negative (some CT clamps are funny like that )
Ok final code to take an area and add all the power sensors to give you a power reading. This takes all the lines above and puts it into a single template sensor
If the goal is compute the sum of all power sensors in a specific area, itās preferable for the template to start by selecting all power sensors in the area (as opposed to starting with all sensors in the state machine).
This is great thank you! You are right in that i have been able to remove one filter and still get the same result, now the final step it to make it a repeatable template with something like this so every time i add an area the sensor gets auto generated!
This was an unexpected rabbit hole of leaning thanks for everyones contributions!
Please consider marking my post with the Solution tag. Users looking for answers to similar questions will be led directly to the most concise way to filter entities within a given area.