Dynamic, label based template calculations

Hi,

Still learning after years of HA. Getting deeper into templating. Would some of you mind taking a look at the code I came up with for summing up all current power consumption in the house for any entity labeled Power and with a device class of power? Can this be further shortened?

Here we go:

{{ expand(label_entities(label_id('Power')))
   |rejectattr('state', 'in', ['unavailable','unknown'])
   |selectattr('attributes.device_class', 'eq', 'power')
   |map(attribute='state')
   |map('float')
   |list
   |sum
   |round(0)
}} W

As a followup to that logic, I don’t assume any UI cards (other than markup) allow for label based selection of entities to be included or listed - would be so powerful to select entities by label - like automations can.

Any help is very much appreciated!

{{ expand(label_entities('Power'))
   | rejectattr('state', 'in', ['unavailable','unknown'])
   | selectattr('attributes.device_class', 'eq', 'power')
   | map(attribute='state')
   | map('float')
   | sum
   | round(0)
}}
1 Like

Auto-Entities

One note on the template: Not all entities have a device class assigned, so if you want to use the label without having to check you will need to incorporate a filter to select for having a defined device class prior to selecting for a specific value of the device class.