Sensor average template for dynamic list of entities

Hi, I currently have 8 entities in my lounge that report temperature, for which I’ve templated the following:

{% set room_sensors = states.sensor | 
  selectattr('entity_id', 'in', area_entities('lounge')) |
  selectattr('attributes.device_class', 'eq', 'temperature') |
  rejectattr('entity_id', 'is_hidden_entity') |
  rejectattr('attributes.is_group', 'eq', true) |
  rejectattr('attributes.entity_id', 'defined') |
list %}

{% for s in room_sensors %}
  {{ s.state }}
{% endfor %}

which produces this:

11.25

  13

  14

  13

  14

  11.47

  11.2

  11

What I’m trying to get is a template sensor showing the average from all of the sensors but also allows adding or removing sensors without having to edit the template.

I’m currently using a template sensor that lists each entity by entity_id but as I move the sensors around frequently it means a lot of changing the code.

I’ve searched for a couple of hours and found nothing that helps and I’ve gone as far as my knowledge allows. Can anyone suggest how it can be done please?

Thanks, Matt

{{ states.sensor | 
  selectattr('entity_id', 'in', area_entities('lounge')) |
  selectattr('attributes.device_class', 'eq', 'temperature') |
  rejectattr('entity_id', 'is_hidden_entity') |
  rejectattr('attributes.is_group', 'eq', true) |
  rejectattr('attributes.entity_id', 'defined') |
  map(attribute='state') |
  map('float', 0) | average(0) }}
1 Like

Wow, that was super quick…you obviously know your stuff! Thank you so much, it works perfectly.

1 Like