Sensor templates: trigger.from_state how to extract this value?

Im looking to compare the last value of a sensor to the new value -
I have a sensor which just collects a ever-increasing sequence number,
the sensor is checking lorawan frame numbers are sequential to detect lost frames; 1,2,3,5… = we lost frame 4).

I have tried the automation; with a condition:
{{ (trigger.to_state.state|int - trigger.from_state.state|int) > 1 }}

But this only triggers if we loose one (or more frames), I need a better way to count lost frames as we are losing a few in a row at some times.

Can anyone suggest how I can actually get the value of trigger.from_state so I can then do a basic math template to find the difference between the successive values?

sensor value = (trigger.to_state.state|int - trigger.from_state.state|int)

or can I parse this value out in my automation in an MQTT payload (for example)?

Cheers all!

Some ideas:

Use a triggered template sensor to store the from state - if triggered sensors support trigger.from_state.

Store it in an input_number.

Publish it as a retained message to an mqtt topic. Use an mqtt sensor to retrieve the value.

The first method wont restore on Home Assistant restart the other two will.

Alternatively, do the math in your automation.

Thanks for the help, here’s what seems to work:

# get the previous value of a sensor example from:
# https://www.home-assistant.io/docs/automation/templating/
template:
  - trigger:
    - platform: state
      entity_id:
        - sensor.waterit0005_ttn_meta_framecount
    sensor:
      - name: waterit0005_ttn_meta_framecount_last
        state: '{{ trigger.from_state.state }}'

1 Like

Hi,

I am trying to do something similar, but I am very new to HA.

Just struggling with the indentation - where exactly do I place it within my config files with other custom template sensors.

Hamish