Compare current sensor value with last sensor value

Hello everybody,

Is there a way to compare the current sensor value with last recorded sensor value when using the platform: template-sensor? My idea is to only record the data of a sensor when the change in data is bigger than a given value. E.g., only record the new data of a temperature sensor when the change since the last recorded data is more than 1°C.

In ESPHome I’m using the lambda filter in a similar way. You can just define a static value like shown below. It keeps the last stored value like you would expect from a static variable in C and than compare this to the new value.

# Only store a new value if the deltato the last stored value is smaller than 0.3
filters:
  - lambda: |-
      float MAX_DIFFERENCE = 0.3;  // adjust this!
      static float last_value = NAN;
      if (isnan(last_value) || std::abs(x - last_value) < MAX_DIFFERENCE)
        {
          last_value = x;
          return (x*(-1.0));
        }
      else
        return {};

I’m currently struggling to get the last stored value in Home Assistant. Is there a way to do so, no matter if a static variable will be used or an dedicated Home Assistant function.

Have a look in trigger for template sensors in the docs and then use the from and to values from the trigger, e.g.

{% if is_number(trigger.from_state.state) and (float(trigger.to_state.state,default=0) > float(trigger.from_state.state,default=0)) %}