Parametrized Entities in Home Assistant Scripts
- Home Assistant, Jinja
- 5
- 5
- finished
Home Assistant has a convenient climate.toggle
action to turn on and
off Air Conditioners. But here’s the catch: all AC units in my house can either
heat or cool and Home Assistant doesn’t remember the last AC state. Each time
climate.toggle
turns AC on, it enables the first possible state: heating.
Except some extraordinary situations, I don’t heat air with AC, so this isn’t
desirable behavior for me. For a solution to this problem, I thought about
writing a script which would toggle just the cooling. I don’t want to write a
separate script for each unit, but just one with AC entity parameter.
To parametrize a script we may add a fields
section, which enables entity
selection with a drop down list presented in the UI whenever we use a script.
Selected entity will be available as a variable in Jinja templates in the
script. This is convenient, but most of Home Assistant conditions or actions
don’t support templated entities, so we have to use a Template Condition.
(sidenote: Don’t assume that something supports templates just because it
seems logical. I saw many Github issues about not supporting templates that
were rejected, because documentation didn’t explicitly said that they are
supported.)
Here’s the full script:
fields:
ac:
selector:
entity:
multiple: false
name: AC
description: Air Conditioner Device
default: climate.my_air_conditioner
sequence:
- if:
- condition: template
value_template: |
{{ is_state(ac, "off") }}
then:
- data:
hvac_mode: cool
target:
entity_id: "{{ ac }}"
action: climate.set_hvac_mode
else:
- data:
hvac_mode: "off"
target:
entity_id: "{{ ac }}"
action: climate.set_hvac_mode
alias: Toggle AC
icon: mdi:air-conditioner
When “coding in YAML” (sidenote: I despise coding in YAML, be it Home Assistant, Ansible, or any other application.) I find it the easiest to set up the general building blocks (like fields and if-else statements) from the GUI and then fill the templates via the built-in text editor. Home Assistant’s Graphical Editor doesn’t support templates anyway.
For debugging, I find a template editor in Developer Tools » Template to be
super useful. Just remember to first set all the necessary Jinja variables. For
example, I had a problem with evaluating is_state()
function, so I pasted the
following:
{% set ac = "climate.haier_ac_sypialnia" %}
{{ is_state(ac, "off") }}