[ERRO] Dúvida em automação

Boa tarde,

Estou a criar uma automação e obtenho o seguinte erro:

CZ | Exaustor: Error executing script. Unexpected error for call_service at pos 1: Error rendering service name template: UndefinedError: 'trigger' is undefined
4:43:50 PM – Automation (ERROR)

Automação:

- id: '1590939726102'
  alias: CZ | Exaustor
  description: Disponilibizar exaustor em função do estado da janela
  trigger:
  - entity_id: binary_sensor.wd_cozinha_janela
    platform: state
    to: 'on'
  - entity_id: binary_sensor.wd_cozinha_janela
    platform: state
    to: 'off'
  condition: []
  action:
  - entity_id: switch.sw_exaustor
    service_template: >
      '{% if is_state(trigger.to_state.state, "on") %} switch.turn_on
      {% elif is_state(trigger.to_state.state, "off") %} switch.turn_off 
      {% endif %}'

Se puderem ajudar, agradeço :slight_smile:

O erro diz Error executing script mas o que colocaste é uma automação… A diferença entre as duas é que os scripts não usam trigger.

Viva @j_assuncao,

Mas eu fiz uma automação e não um scritp e obtenho o erro qd exceuto a automação.

Fui confirmar, e não possuo nenhum script que faça refª às entidades do código acima.

Partilho detalhes do erro:

Log Details (ERROR)
Logger: homeassistant.components.automation
Source: helpers/service.py:119
Integration: Automation (documentation, issues)
First occurred: 5:44:42 PM (1 occurrences)
Last logged: 5:44:42 PM

CZ | Exaustor: Error executing script. Unexpected error for call_service at pos 1: Error rendering service name template: UndefinedError: 'trigger' is undefined
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 228, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/usr/local/lib/python3.7/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'trigger' is undefined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 114, in async_prepare_call_from_config
    domain_service = config[CONF_SERVICE_TEMPLATE].async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 230, in async_render
    raise TemplateError(err)
homeassistant.exceptions.TemplateError: UndefinedError: 'trigger' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 153, in _async_step
    self, f"_async_{cv.determine_script_action(self._action)}_step"
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 623, in _async_call_service_step
    *self._prep_call_service_step(), blocking=True, context=self._context
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 252, in _prep_call_service_step
    return async_prepare_call_from_config(self._hass, self._action, self._variables)
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 119, in async_prepare_call_from_config
    ) from ex
homeassistant.exceptions.HomeAssistantError: Error rendering service name template: UndefinedError: 'trigger' is undefined

Viva,

Já resolvi o problema.

Partilho o código, poderá ser útil para alguém:

- id: '1590939726102'
  alias: CZ | Exaustor
  description: Disponilibizar exaustor em função do estado da janela
  trigger:
  - entity_id: binary_sensor.wd_cozinha_janela
    from: 'off'
    platform: state
    to: 'on'
  - entity_id: binary_sensor.wd_cozinha_janela
    from: 'on'
    platform: state
    to: 'off'
  condition: []
  action:
  - service_template: >
      {% if is_state('binary_sensor.wd_cozinha_janela', 'on') %} switch.turn_on
      {% elif is_state('binary_sensor.wd_cozinha_janela', 'off') %} switch.turn_off
      {% endif %}
    entity_id: switch.sw_exaustor
2 Curtiram

Viva,

Para não abrir outro tópico (mas se acharem por bem, assim o farei), tenho uma dúvida com este template:

{% set temperatura_sala = states | selectattr('entity_id', 'in', state_attr('group.sensores_temp','entity_id'))
        | selectattr('state') | list | map(attribute='state')
        | join(', ') %} 

Temperaturas: {{ temperatura_sala }}

Este template devolve-me o seguinte resultado:

Temperaturas: 23.5, 23.6

E está correto. :slight_smile:

Gostava é que me devolvesse algo do género:

Temperaturas: Sala 1 - 23.5ºC, Sala 2 - 23.6ºC

Questão: como fazer?

Obg

1 Curtiu

Boas,

assim muito rapidamente tens uma forma que não é a ideal mas resolve esta situação. Se quiseres usar para outras situações já não dá

Basicamente é mudares o join e meteres Sala 1 depois de Temperaturas:

Assim:

{% set temperatura_sala = states | selectattr('entity_id', 'in', state_attr('group.sensores_temp','entity_id'))
        | selectattr('state') | list | map(attribute='state')
        | join(', Sala 2 - ') %} 

Temperaturas: Sala 1 - {{ temperatura_sala }}

De qualquer das maneiras acho que ficas mais bem servido com este:

{%- set entities = expand('group.sensores_temp') -%} 

Temperaturas: {% for e in entities -%}
                {{e.name}} - {{ e.state }}{{e.attributes.unit_of_measurement}}
                {%- if not loop.last -%}, {% endif -%}
              {%- endfor -%}
2 Curtiram

@ricreis394,

funciona mt bem :+1:

Obrigado :slightly_smiling_face:

1 Curtiu

Copyright © 2017-2021. Todos os direitos reservados
CPHA.pt - info@cpha.pt


FAQ | Termos de Serviço/Regras | Política de Privacidade