Calling service in a loop with different parameters

Hello,

I have got a list of TRVs I got from:

  trvs:
    name: Thermostats
    selector:
      entity:
        domain: climate
        multiple: true

I now want to calculate and set the temperatures for the trvs, which might be different for every trv. I’m a bit lost how to do this.

In a pseudo-language it would look like:

action:
  {% for _trv in expand(_trvs) %}
   {% set _temperature = ...doing some calculations...  %}
   - service: climate.set_temperature
     data:
        temperature: "{{ _temperature }}"
        hvac_mode: heat
     target: 
        entity_id: "{{ _trv.entity_id }}"
  {% endfor %}

Another idea was to pre-calculate temperatures and store it into an array like:

_arr_of_temperatures: >
  {% set result = namespace(temperature=[]) %}
  {% for _trv in expand(_trvs) %}
   {% set temperature = ... doing some calculations... %}
   {% set result.temperature = result.temperature + [temperature] %}
  {% endfor %}
  {{ result.temperature| list }}

 - service: climate.set_temperature
   data:
     temperature: "{{ _arr_of_temperatures }}"
     hvac_mode: heat
   target: 
     entity_id: _!input trvs

But I couldn’t get anything to work. The first solution throws syntax-errors (of course…), the second gives (of course…) the error: expected float for dictionary value @ data[‘temperature’]

Use a Repeat for Each action, you can use templates to construct the list of dictionaries with your variable keys and values.

- repeat:
    for_each: |
      {% set result = namespace(temperature=[]) %}
      {% for _trv in expand(_trvs) %}
      {% set temperature = ... doing some calculations... %}
      {% set result.temperature = result.temperature + [{'entity': _trv.entity_id , 'temp': temperature}] %}
      {% endfor %}
      {{ result.temperature }}
    sequence:
     - service: climate.set_temperature
       data:
         temperature: "{{ repeat.item.temp }}"
         hvac_mode: heat
       target: 
         entity_id: "{{ repeat.item.entity }}"
1 Like

FYI…

- repeat:
    for_each: |
      {% set result = namespace(temperature=[]) %}
      {% for _trv in expand(_trvs) %}
      {% set temperature = ... doing some calculations... %}
      {% set result.temperature = result.temperature + [{'entity_id': _trv.entity_id , 'temperature': temperature, 'hvac_mode': 'heat'}] %}
      {% endfor %}
      {{ result.temperature }}
    sequence:
     - service: climate.set_temperature
       data: "{{ repeat.item }}"
2 Likes

Greate! Thanks a lot for pulling me into the right direction, very helpfull.