MQTT - get last value to do calculation

Hi guys,

I’m getting a message through mqtt that contain pulse and a timestamp, but to calculate the current power usage, I need to use the previous value and find the time difference and number pulses there was between the messages. What is the best approach to do this in HA. Right now I just have a python script that can handle it, but if I want to do the full integration in HA.

Here is how the mqtt message would look like

{
  "extenderPulses": 1234,
  "extenderTimestamp": 12345
}

the script I have now, just saves the old value, and when there is a new message it takes new message extenderPulses and do a substraction with the old value, the same with the extenderTimestamp.

So what is the best approach.

to insert the json message into a sensor and setup a automation that triggers on change of the sensor, and then calculate the current power, by. using from_state and to_state, and then update the currrent power sensor, or is there a more elegant way to do it.

Basically that but with a trigger-based template sensor instead of an automation: