Increment an input_boolean depending on trigger.entity_id?

So, I want to add one to an input_boolean every time a binary_sensor with (nearly) the same name has a state change. I’ve been round in circles with this and ended up with the following which doesn’t seem to work but I am sure is close.

Because I’m using trigger.entity_id it is hard to find a way to test this in the developer tools.

  - alias: Increment sensor activation count
    trigger:
      - platform: state
        entity_id:
        - binary_sensor.front_door
        - binary_sensor.back_door
        - binary_sensor.side_door
    action:
      - service: input_number.set_value
        data_template:
          entity_id: "input_number.{{ states('trigger.entity_id').split('.')[1] }}_activations"
          value: >
            {% set entity = 'input_number.' + [trigger.entity_id].split(".")[1] + '_activations' %}
              {{ states(entity) | int + 1 }}

By the way the list of entities is lot longer so I don’t really want to code a separate clause for each one.

Have you considered using a Counter instead of an input_number? Might make things easier since there’s a counter.increment service.

If you want to test templates that use the trigger variable in the template editor, you can enter this first:

{% set trigger = {'entity_id': 'blah.blah', 'to_state': {'state': '123'}} %}

etc. I do this all the time.

But the main problem with your automation is the way you’re using the trigger variable. At a minimum, you need to change it to:

  - alias: Increment sensor activation count
    trigger:
      - platform: state
        entity_id:
        - binary_sensor.front_door
        - binary_sensor.back_door
        - binary_sensor.side_door
    action:
      - service: input_number.set_value
        data_template:
          entity_id: "input_number.{{ trigger.entity_id.split('.')[1] }}_activations"
          value: >
            {% set entity = 'input_number.' + trigger.entity_id.split(".")[1] + '_activations' %}
              {{ states(entity) | int + 1 }}
1 Like

I hadn’t but I will. Thank you.

And thank you too for the test template which I will store away for future use, and the code corrections even if now I don’t end up using them.

Counters worked brilliantly. Until I realised they get reset after every HA restart! :scream: