Condition below/above with calculation

Hi,

I have an automation where I add a condition which is comparing two sensors. Like this:

alias: An
trigger:
  - platform: time
    at: "05:30:00"
condition:
  - condition: numeric_state
    entity_id: sensor.A
    below: sensor.B
action:
  - type: turn_on
[...]

Now I want to change the condition to be only true if sensor.A is below this calculation: (sensor.B - 5).

How do I do this? I have not seen anything related in the condition docs.
I tried the following but I am getting syntax errors on both:
below: sensor.B - 5
{below: sensor.B - 5 }

Thanks!

/KNEBB

You can adjust the “input” value before testing (docs). Here, checking A<(B-5) is the same as checking (A+5)<B:

condition:
  - condition: numeric_state
    entity_id: sensor.A
    value_template: "{{ state.state|float(0) + 5 }}"
    below: sensor.B

Alternatively, for more flexibility in case things get more complicated, use a template condition:

condition:
  - condition: template
    value_template: "{{ states('sensor.A')|float(0) < states('sensor.B')|float(0) - 5 }}"

Or shorthand:

condition:
  - "{{ states('sensor.A')|float(0) < states('sensor.B')|float(0) - 5 }}"

Note that for comparison of numeric states in templates, you need to convert the state (which is always a stirng) to a number. That’s what |float() does, and the number in brackets is what to use if the sensor state cannot be converted.

Thank you so much!

Up to now I have no clue about the template stuff.

So thanks a lot for the explanation, it is easier to understand now wwhat the syntax means.

/KNEBB

Can I use a sensor or anything else in the brackets?
So intead of
...| float(0)...
...| float(sensor.C)...

It might be:
...| float(sensor.C | float(0))...

?

/KNEBB

Yes. Have a play in Developer Tools / Template. Paste this in:

{% set x = "5" %}
{% set y = "hello" %}

{{ x|float(y) }}

and you’ll see the output is 5. Change the value of x from "5" to "z" and you’ll see the output becomes "hello".

To access the state of a sensor, use states(entity_id).

Here, if my temperature sensor failed, the second line would return an error and the third line would return 2. Without the second float() in the third line, the calculation would fail (can’t convert "x" to a number, then can’t add the number 2 to the string "5.1").

The two links at the top of that page give you all the information you need.

1 Like

Yes, but you probably want the state of the sensor:

...float(states('sensor.c')|float(0))...
1 Like