Why trigger.to>trigger.from stopped to work?

I have small automation that updates car data when it is refueled. It was working fine until today morning. I cannot find the logic why it failed. Here is the automation code:

id: log_car_refuel
alias: Log Car Refuel
initial_state: true
trigger:
  platform: state
  entity_id: sensor.audi_q5_tank_level
condition:
  - condition: template
    value_template: '{{ trigger.to_state.state > trigger.from_state.state }}'
action:
  - service: notify.mobile_app_mireks_iphone
    data:
      title: Car refulelled
      message: Car refuelled at {{ states('sensor.audi_q5_mileage') }} km
  - service: input_number.set_value
    data_template:
      entity_id: input_number.last_refuel
      value: '{{ states('sensor.audi_q5_mileage') }}'
  - service: input_text.set_value
    data_template:
      entity_id: input_text.last_refuel_date
      value: '{{ as_timestamp(now()) | timestamp_custom('%B %d, %Y - %H:%M') }}'

So as you can see it is triggered by fuel level change and executes under condition that trigger.to is bigger than trigger.from (so only if fuel is added to the tank). When I refueled car today mornig, automation was properly triggered, but actions were not executed, as traces shows that condition was not met:

Executed: 17 November 2022 at 07:35:28
Result:
result: false
entities: []

at the same time I can see in the sensor history, that it changed at that time:


What happened? Any idea?

You’re comparing the current and previous states as strings not as numbers.

    value_template: '{{ trigger.to_state.state|float(0) > trigger.from_state.state|float(0) }}'
1 Like

OK, will test this… But it means that now I’m comparing 2 strings, and previously automation was always triggering when the fuel level was not increasing to 100% but dropping to 99% (99 is bigger than any other number in range represented as string). For this additional condition had to be fulfilled, that I was driving long enough after refueling to allow for such drop… weird…

It worked because you got lucky

Go to Developer tools → Template and paste the following:

{{ '9' > '8' }} / {{ 9 > 8 }}
{{ '10' > '8' }} / {{ 10 > 8 }}

You’ll discover you get

True / True
False / True

Why? Because the ASCII value for 1 comes before the ASCII value for 8. See here for some more.

3 Likes