Previous Values for State Attributes

I would like to write an automation that triggers when a numeric state attribute suddenly decreases by greater than “X” units. The automation would need to compare the current value of a state attribute against the previous value of a state attribute. Is this possible?

Unfortunately, the point of reference intermittently changes, and therefore I cannot use a fixed value.

Examples:

  • If the media player decreases the attribute ‘volume_level’ by more than 0.2 units (in less than ‘Y’ seconds), mute the media player.
  • If the media player increases the attribute ‘volume_level’ by more than 0.2 units (in less than ‘Y’ seconds), unmute the media player.

Additional Examples:

  • If a freezer temperature sensor value increases more than 20% from previous steady state value (in 10 minutes), trigger alert automation
  • If stock ticker price drops more than 5% (in < 30 minutes), trigger alert automation

The above examples are not the automations that I intend to write, however they exhibit similar logic. If this is possible, I imagine it will use templates

{{ PREVIOUS state_attr("media_player.chromecast", "volume_level") - CURRENT  state_attr("media_player.chromecast", "volume_level") > 0.2  }}

If this is not possible I wonder if I could use the derivative helper to trigger an automation based on the rate of change in numeric values.

Couple of ways.

Create an automation that triggers off a state change of the entity (e,g the volume)

Within that automation you have trigger.from_state and trigger.to_state which have the old and new values respectively.

Or create a template sensor with a trigger and for the calculation subtract the difference

{{ trigger.from_state.state | int - trigger.to_state.state | int }}

And then trigger an automation based on this sensor exceeding your threshold.

1 Like