Creating a helper that does arbitrary computation over a stream of past values?

I have some air quality sensors that report raw PM 2.5 values, and I’d like to compute an AQI (Air Quality Index) value from the values recorded over the past 24 hours. Normally the AQI is computed on-device, but the device keeps rebooting, losing the past values and restarting the computation.

I’d like to do this computation in Home Assistant, using a helper, but none of the helper classes seem to do what I want.

Is there a helper that can perform an arbitrary calculation over a stream of past values?

The statistics integration allows you to define a custom sensor based on another sensor’s past values. They’re not exactly “arbitrary” but there are a lot of calculations available. Check it out and see if one of them works for you. These sensors have to be configured in YAML config file, not in the GUI.

1 Like

The statistics integration is a nice starting point, but insufficient for my needs; I can get the mean of the various values tracked, but after that, I need to apply a piecewise linear transformation to the mean values, and I haven’t quite figured out how to do that.

For more niche calculations of historical values, you still have a few options, but they require more coding and/or external help. Not knowing what specific math you have in mind with your transformation, I’ll just mention a few high-level ideas.

  • Check out the SQL Integration which lets you make arbitrary queries to the recorder (history) database. If you’re proficient in SQL you can do a lot of calculations just within the query alone.

  • There’s also the command-line sensor, which lets you launch a linux command/script at a set interval. Using REST calls or Sqlite queries you could retrieve your sensor data and return the desired value, but I suspect spawning shell processes too often would result in significant overhead and could bog down the server if called often.

  • Failing that, you can take a look at AppDaemon, an add-on which lets you write custom python scripts with HA triggers (e.g. a state change of your base sensor). While AppDaemon can set_state on a custom sensor, skimming the docs it wasn’t clear to me whether that sensor was persistent (may not get recorded and/or survive reboot) without some workarounds like sending MQTT messages.

  • There’s also the option of making your own integration, which requiring the most code, is virtually unlimited what you can do with it.

  • Finally, there are options outside of HA as well. Integrations like InfluxDB can export sensor readings to an external database where you can use tools native to those DBs (e.g. Kapacitor) for additional calculations, which can be fed back into HA using webhooks or REST API.