I’m trying to create a binary sensor, which will be true when electricity is “cheap” and false when it’s “expensive”. Cheap one is mon-fri from 22:00 ÷ 06:00 and on holidays. I didn’t find any similar question (and solution) here, thus my question:
I wonder, what’s “or” and “and” priority when creating template binary sensor?
I created sample below, but am i thinking correctly regarding priorities? I intentionally created bigger indentations to be easily readable.
Or is there a more simple solution?
- name: cheap electricity
state: >
{{
is_state('binary_sensor.today_is_holiday', 'on')
or
(
is_state('binary_sensor.delovni_dan', 'on')
and
(
(now() > today_at("10:05"))
and
(now() < today_at("15:55"))
)
)
}}
This is the order of operation. Keep in mind multiplication and division are at the same level in order of operation, so reading left to right takes precedence when doing that. and and or do the same thing, they are weighted equally and left to right takes precedence.
Parenthesis are honored first. So, if you’re unclear of your order of operation, just add parenthesis.
you essentially have:
a or (b and c and d)
nested and’s don’t make a difference because with and you need them all to resolve true. You can also use reduce your code by making a better comparison. I.e. 3 <= x <= 7, checks to see if x is in the range 3 to 7.
- name: cheap electricity
state: >
{% set a = is_state('binary_sensor.today_is_holiday', 'on') %}
{% set b = is_state('binary_sensor.delovni_dan', 'on') %}
{% set t1 = today_at("10:05") %}
{% set t2 = today_at("15:55") %}
{{ a or (b and t1 < now() < t2) }}
Just keep in mind that statements like this bail when they meet a requirement that satisfies the whole check. In your case, if is_state('binary_sensor.today_is_holiday', 'on') is true, the rest will not be evaluated because you already satisfy the if statement. That means, you should check everything in line instead of making variables like I just did:
Thanks a lot for explanation! It’s more clear now. So, basically it’s correct to add parenthesis, it’s just not very human friendly for understanding when i return to this months later. Your example is way better in this way.
Regarding holidays: if it’s holiday then it’s ok for rest of conditions NOT to be evaluated, since at holidays it’s “cheap” electricity all day anyway. It’s either holiday, saturday, sunday, or 22:00 until 06:00 mon-fri ( that’s “sensor.delovni_dan” condition)