Automation Trigger and Condition Timing Issue

I’m trying to do something that I’m not sure will work reliably and need advice.

I have a sensor that updates every minute.

Every time the sensor updates I want to capture the results of the sensor value in the “previous” state and in the “current” state. I’ve got that worked out using two input_texts (current_value & previous_value) and a script that gets triggered when the sensor changes that puts the input_text.current_value into the input_text.previous_value and then updates the input_text.current value with the new value of the sensor.

Then I want to trigger several automations using the change in state of the sensor as a trigger and using a comparison between the current_value & previous_value input_texts as a condition (current_value > previous value). That part is pretty straight forward so I’ve got all of that worked out.

so far so good…

The potential problem:

If the register shift moving the current_value into the previous_value then updating the current_value always takes place before the automations notice the state of the sensor changing and triggering then everything will work as expected. If the register shift gets delayed until after the trigger happens for the automations then they will not meet the conditions for the automation to run even tho, technically, they should run.

The question I have is how can I be sure that the register shift always occurs prior to the automations triggering?

EDIT:

Or am I being concerned for no reason? Will this ever be a problem?

Why don’t you just use an automation that is triggered by a state change in the sensor, and have a condition that compares trigger.to_state to trigger.from_state? Seems like you’re just duplicating what is already available.

Possibly…

I only want it to run if the current value is more than the previous value. but i won’t necessarily know the values. it could go from 1 to 2, 1 to 4, 5 to 3, 6 to 0, etc.

is it possible to define the ‘to’ & ‘from’ using a variable? I’ve only ever seen that done by defining constants.

Or can I just use {{ trigger.to_state > trigger.from_state }} in a condition template?

Pretty much, something like this:

- alias: blah
  trigger:
    platform: state
    entity_id: WHATEVER
  condition:
    condition: template
    value_template: >
      {{ trigger.to_state.state|float > trigger.from_state.state|float }}
  action:
    ...

Depending on the details you may also want to account for trigger.to_state or trigger.from_state being None, or either …state being ‘unknown’, etc., but that’s the basic idea.

ok. I’m already triggering off the state change of the sensor so I’ll just add in the condition.

thanks again for the tip.