Jinja template to show the last ON state of a group of sensors

Just wondering if there is a way to show, of a group of sensors, which one most recently had their status toggled to ‘on’?

Like this, but ONLY for if the state was an ON change, not an OFF change

        value_template: >
                {%- set pirs = [states.binary_sensor.balcong, states.binary_sensor.sit, states.binary_sensor.front_door, states.binary_sensor.kitchen, states.binary_sensor.attic] %}
                {% for pir in pirs %}
                  {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
                    {{ pir.name }}
                  {% endif %}
                {% endfor %}
        value_template: >
          {%- set pirs = [states.binary_sensor.balcong, states.binary_sensor.sit, states.binary_sensor.front_door, states.binary_sensor.kitchen, states.binary_sensor.attic] %}
          {%- set pirs = pirs | selectattr('state','eq','on') | list %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}
1 Like

Thanks so much Petro. This works to an extent but for some reason the graph is able to identify the sensor but the state is blank? I will have a fiddle with the template myself to see if I can figure out why this might be. But thanks again!!

dsa

refresh your page, CTRL+F5

Hmmm! No, I wasn’t going mad, it seems hit and miss! I wonder if it’s because one of my PIR sensors has the word PIR in its name? However it’s not JUST that PIR which isn’t working. Another PIR called “Front Door Area” doesn’t work either. Kitchen for example is fine. Wonder if it’s sensors which have two words in their name?

mult edmails

@petro really sorry to bother you after you’ve been so helpful, sadly still struggling, do you think moving to single word sensors would solve the problem of missing states?

I don’t think that is the issue. This template will only output information when everything is on. If nothing is on, it will be empty. Which is what you are seeing.

ahhhhh sorry, that would explain it. I misunderstood the solution. So maybe there is no way to simply show the last sensor to be triggered ‘on’ (even if it’s not currently on!). My bad. But thanks for your help!

Hoping this might be the answer

Testing now!

You’re still struggling with this? FYI when you respond, respond to the person not the thread. Responding to the thread will not notify who you respond to. I could have built you a template 3 years ago.