Help with average indoor temperature sensor

I have many sensors that report temperature, but some go to sleep or are slow to update. I’d like to take all of the sensors that have updated within a certain period (ie last hour) and only average those.

So far I have a script averaging all online temperature sensors and reporting back how many it counted. I can get last_changed from the state of the sensor, but how can I compare it to current time?

tempEntities = ["sensor.entry_temperature","sensor.kitchen_temperature", "sensor.etc"]
sensorsTotal = len(tempEntities)
tempsCounted = 0
tempsTotal = 0

# look up each entity_id
for entity_id in tempEntities:
  # copy it's state
  state = hass.states.get(entity_id)

  # If not None, add up and increase counter
  if state.state is not 'unknown':
     tempsCounted = tempsCounted + 1
     tempsTotal = tempsTotal + int(float(state.state))

# Get average
averageTemp = tempsTotal / tempsCounted

hass.states.set('sensor.average_indoor_temp', averageTemp, {
    'unit_of_measurement': '°F',
    'friendly_name': 'Indoor Temp',
    'icon': 'mdi:thermometer',
    'temps_counted': tempsCounted,
    'temps_total': sensorsTotal
})
1 Like

How are you deciding when to take a reading?

Any time a sensor updates, rate limited by 5 minutes

- alias: 'Update Average Indoor Temperature'
  trigger:
    - platform: state
      entity_id: sensor.1, sensor.2, sensor.etc
  action:
    - service: automation.turn_off
      entity_id: automation.update_average_indoor_temperature

    - service: python_script.average_temp

    # Rate limit
    - delay:
        minutes: 5
    - service: automation.turn_on
      entity_id: automation.update_average_indoor_temperature

Maybe I don’t understand what you are trying to do, but wouldn’t the min/max component do what you want? You can set it to “mean” and get an average of various sensors. I use it to average all of my indoor temperature sensors (which are various sensor types/manf) and I haven’t had any issues.

https://home-assistant.io/components/sensor.min_max/

For time, setup https://home-assistant.io/components/sensor.time_date/ and read the state.

I’m not sure if scripts are good for taking an average over an hour, perhaps custom component better for that

It appears you are right, I was not aware of the min/max sensor, and it does almost exactly what I was trying to accomplish here. The statistics component will also calculate the mean.

I did get some python guidance elsewhere and will redo my script as a programming exercise, I’ll post it when I get around to it