A variable just stores some data for reuse. The actual logic goes under the script sequence or automation actions. You’d keep the value as you have done, and then use that with an if or choose statement.
action:
- variables:
alexa_area: "{{ area_name(states('sensor.last_alexa')) }}"
- if: "{{ alexa_area == 'bedroom' }}"
then:
... your "then" actions go here ...
else:
... your "else" actions go here ...
Automation Example 2
action:
- if: "{{ area_name(states('sensor.last_alexa')) == 'bedroom') }}"
then:
... your "then" actions go here ...
else:
... your "else" actions go here ...
Now a more difficult one… And If I wanted to use “choose” instead of “If”?
Is that possible? I need it because I have a lot of condition to test and some of them are true even if I just want to use the first one.
Imagine I have my car with a 40% soc…
If “soc” is <20 is false
If “soc” is <60 is true… but If “soc” is <70 or <80 and so on is also true and because of that I need to use the “choose” function instead of If…
“If” was just the first step to understand how can I create this action…
Can you help me? Do you think it’s possible (I mean in the variable definition to use it as a global variable in the automation template)?
Yes, you can use a either an if/elif construct or a dictionary. In both methods you need to take care with the order of options based on the comparison type you are using. The cases are rendered from top to bottom and the first one to render true will be returned. You can avoid some problems by using chained comparisons and <= instead of < where appropriate:
Well @Didgeridrew, I manage to do what I show bellow. It’s not pretty programing but it seams to do the work and only use the fist formula that it’s true…
This gave me an error (I think just a syntax one, but I’m not fiding the correct way to emend it)
Message malformed: invalid template (TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: ‘elif’ or ‘else’ or ‘endif’. The innermost block that needs to be closed is ‘if’.) for dictionary value @ data[‘variables’][‘tempo’]
I also had a problem that I wanted to solve by having the script decide based on the value of a variable.
Finally, after a little investigation and quite a few tests, this solution worked for me:
Where ‘priority’ is a variable that comes from an automation and if it’s “normal” it won’t talk after 9pm (e.g. “Your phone is charged”), but if ‘priority’ = alarm, it won’t check the time, always speaks (e.g. smoke or leak alarm)