Template Errors

I have a bunch of automatons that increment a counter each time a motion detector is activated. I would like to consolidate these into a single automation.

I tied the following automation, but HA complains with Message malformed: not a valid value for dictionary value @ data[‘action’][0][‘entity_id’] when I save.

Any thoughts on resolving this?

alias: counter - motion activated test
description: ''
trigger:
  - platform: state
    from: 'off'
    to: 'on'
    entity_id: binary_sensor.motion_breakfast
  - platform: state
    from: 'off'
    to: 'on'
    entity_id: binary_sensor.motion_front_door
  - platform: state
    entity_id: binary_sensor.motion_gameroom
    from: 'off'
    to: 'on'
condition: []
action:
  - service: counter.increment
    data: {}
    entity_id: |
      {% if (trigger.entity_id) == 'binary_sensor.motion_breakfast' %}
        counter.motbreakfast
      {% elif (trigger.entity_id) == 'binary_sensor.motion_front_door' %}
        counter.motfdoor
      {% elif (trigger.entity_id) == 'binary_sensor.motion_gameroom' %}
        counter.motgameroom
      {% else %}
        counter.motgameroom
      {% endif %}
mode: single

Thanks!

The error is due to incorrect indentation. Change it to this:

action:
  - service: counter.increment
    data:
      entity_id: |
        {% if ( ...etc...

I would like to make a suggestion. If you make the counters have the same names as their associated binary_sensors, you can simplify the template.

action:
  - service: counter.increment
    data:
      entity_id: "counter.{{ trigger.to_state.object_id }}"

Thanks Taras! That resolved the problem. Thank you for the suggestion as well; I’ll likely implement in order to simplify my code.

1 Like

You can also consolidate your trigger section.

trigger:
  - platform: state
    entity_id:
      - binary_sensor.motion_breakfast
      - binary_sensor.motion_front_door
      - binary_sensor.motion_gameroom
    from: 'off'
    to: 'on'

You’re welcome!

Please consider marking my post (above) with the Solution tag. It will automatically place a check-mark next to the topic’s title. It serves to indicate that this topic has an accepted solution and helps other users find answers to similar questions.