Calculating average values over entities

I feel like I should find a simple answer to this, but I am at a loss after several hours of trying to get this to work. What I want to accomplish is simply this: Calculate the average value over two or more entities while catching unavailable states using a default value or similar. Below is a snippet with two approaches to the templating.

- platform: template
  sensors:
    temperature_average_upstairs:
      friendly_name: "Average Temperature Upstairs"
      unit_of_measurement: "°C"
      value_template: >-
        {{ ( ( ( states('sensor.temperature_average_bedroom') | default(20) | float ) + ( states('sensor.temperature_average_balcony') | default(20) | float ) ) / 2 ) | round(1) }}

The thing is the snippet works when no entities are unavailable. But as a matter of fact some entities are unavailable for quite some time. So HA warns me, that this template will fail in the future and also the resulting sensor entity stays unavailable until all entities in the template become available.

HA Warning Message
2021-10-26 21:40:26 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'float' got invalid input 'unknown' when rendering template '{{ ( ( ( states('sensor.temperature_average_bedroom') | default(20) | float ) + ( states('sensor.temperature_average_balcony') | default(20) | float ) ) / 2 ) | round(1) }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2021.12

I hope I could make myself clear, cause it is late and my head is spinning. Will clarify if questions arise.
Thanks in advance for any input!

Here is how I average alot of temperatures

sensor:
  - platform: min_max
    name: "Main Floor Average Temperature"
    type: mean
    round_digits: 1
    entity_ids:
      - sensor.familyroomsensors_air_temperature
      - sensor.homeseer_z_wave_plus_leak_sensor_air_temperature
      - sensor.family_room_se_air_temperature
      - sensor.kitchen_flood_sensor_air_temperature_2
      - sensor.main_floor_temperature
      - sensor.mil_bath_leak_sensor_air_temperature_2
      - sensor.mud_room_fibaro_air_temperature_2
      - sensor.study_motion_d_air_temperature

This is then a sensor that can be acted on like any other sensor.

Here is documentation on min_max.

3 Likes

See, the solution was kind of obvious. I am missing a little customization with that sensor, but it does the job, is supported by HA and spares me the hassle of templating. Cheers!

There is also the statistics integration as an option.

Or there is a custom average component as well that is really useful for this kind of thing

Or there is a custom average component as well that is really useful for this kind of thing

Just commenting here for future reference: The average filter is available in HA Core natively since 2021.11.

you mean time-simple-moving-average from Filter - Home Assistant ?