Parametrized Entities in Home Assistant Scripts

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 want to use AC for heating.

For a solution to this problem, I wrote a script which toggles cooling. I have 4 AC units so I parametrized it with AC entity parameter. We do this by adding a fields section, which, whenever the script is used, also adds a drop down list to the GUI, where we can manually select the affected entity. It 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 template entities, so we have to use a Template Condition. (sidenote: Don’t assume that something supports templates just because it seems logical. I saw Github issues about not supporting templates that HA developers reject, because documentation doesn’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

I despise “coding in YAML” but so far there’s no way around it when we deal with templates. I find it the easiest to set up general structure of the script from the GUI and then fill the templates via the built-in text editor.

For debugging of Python dialect inside the Jinja templates, I find a template editor in Developer Tools » Template to be very useful. Just remember to 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_bedroom" %}
{{ is_state(ac, "off") }}