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
})
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.
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