Get Last Triggered for ALL automations in Template Editor

So I had a spare ten minutes and I thought that when you get random actions : -
What caused that ?

So you know the time and if you could list out the automations with their last triggered attribute … stick it in the template editor and …
It would be even nicer if it listed in date order (or reverse, hey ! I’m wishing here ! :smiley: )

What I came up with just gives me garbage
Anyone got any ideas about making this useful ??

{% for state in states.automation -%}
{{ state.entity_id | selectattr('last_triggered') ~ ' - ' ~ state.entity_id }}
{{ '' }}
{%- endfor %}

I found a feature request but no follow up
List of Automations sorted according their "triggered last" timestamp (only 11 days old)

Okay, I got inspired by Phil’s recent post : -

But adapting this to the above (AND using the last 10 hours :heart: ) : -

{% set from = (utcnow()|as_timestamp - 10*60*60) | timestamp_utc %}
{% set from = strptime(from ~ '+0000', '%Y-%m-%d %H:%M:%S%z') %}
{% set autos = states.automation | selectattr('state.last_triggered', '>', from)
                | map(attribute='entity_id') | join(', ') %}
{{ autos }}

Still complains that : -
"Error rendering template: UndefinedError: 'str object' has no attribute 'last_triggered' "

So still missing a way to get ‘last_triggered’ to template recursively :sob:

Not exactly sure what you want the output to look like, but here’s possibly a start:

{% for state in states.automation
     |selectattr('attributes.last_triggered')
     |sort(attribute='attributes.last_triggered', reverse=true) -%}
{{ state.attributes.last_triggered }} : {{ state.name }}
{% endfor %}

The selectattr() is required to filter out any automations whose last_triggered is none, otherwise the sort won’t work.

5 Likes

Ahhhh !, the magic ingredient
Thanks I’ll take a look and report back
Many Thanks

Why do you need sleep ? Its barely lunch time with you at the moment ? (Have you been burning the candle at both ends again ? :rofl: )

Edit : Didn’t need to change a thing – Perfect !
Thanks again !
:+1:

Yeah, I kept getting unknown template errors until I finally realized you can’t sort a list that contains both datetime objects and None values (a datetime can’t be compared with “<” or with “>” to None.)

To answer your questions, let’s leave it at this – it’s hell getting old!!

@Mutt
How are you using this template?

I’ve been thinking of how to use this thing. Perhaps store its list in a sensor’s attributes. The tricky part is supplying the sensor with appropriate entities to monitor (so it updates itself efficiently and in a timely fashion). I could list all the automation entity_ids but that’s a drag and nullifies the flexibility and elegance of Phil’s template (which doesn’t need an explicit list of automations).

If I used an automation, instead of a sensor, then maybe I could have it listen for call_service events which are typically the result of an automation’s action calling a service. However, then I have to be careful to exclude that automation from Phil’s template otherwise some sort of nasty recursion might be spawned. Even so, this automation would have to store the data somewhere … possibly publish it for use by an MQTT Sensor (in its attributes) … all very roundabout indeed.

Ideas?

NOTE
Even if I stuff the list in a sensor’s attributes, it will probably be mangled in the Attributes column of the States page. Some other means to display it is needed.

of course there’s this wonderful other option we have:

  - type: custom:auto-entities
    card:
      type: entities
      title: All Automations on
      show_header_toggle: false
    filter:
      include:
        - domain: automation
          state: 'on'
          options:
            secondary_info: last-triggered
    sort:
      method: attribute
      attribute: last_triggered
      reverse: true

and for scripts eg, I use:

  - type: custom:auto-entities
    card:
      type: entities
      title: All Scripts
      show_header_toggle: false
    filter:
      include:
        - domain: script
          options:
            secondary_info: last-triggered
#      exclude:
#        - attributes:
#            last_triggered: null
    sort:
      method: attribute
      attribute: last_triggered
      reverse: true
#      count: 20
2 Likes

It doesn’t happen very often (twice to my recollection over 3 years, so has maybe happened a dozen more I didn’t observe) but one of my speakers went off and the second a light came on.
The speaker I have no clue as it’s a very complex single automation based on a very complex binary sensor (multiple time slots, occupation, manual) but life360 was having a bad day (jumped us away from home (erroneously) ??? (this is a guess based on the notifications I got from life360 saying they were having server problems) ) so probably that. (Edit: this particular automation has been tested 6 ways from sunday, gone over line by line and is as bulletproof as possible)
The light however has me mystified, so I want to track the offending automation down.
If it does it again I’ll just paste the template into the editor and the results can narrow down my search.
I ‘may’ have found the local_time myself once I started playing with it but yours certainly helped, I’ll probably mod it further to include (say) 'from 3 hrs ago, and the hour following'.
I wasn’t planning on turning this into a sensor, it’s just a debugging tool like I use other templates to write some lovelace yaml in a repetitive ordered form

I tried the first one you suggested, for automations, and it appears to have a problem handling automations that have “Never triggered”. When it encounters one, it reset its sorting sequence.

For example:

  • “32 seconds ago”
  • “5 minutes ago”
  • “3 days ago”
  • “4 weeks ago”
  • “7 weeks ago”
  • Never triggered
  • “1 hour ago”
  • “22 hours ago”
  • “1 week ago”
  • Never triggered
  • “12 minutes ago”
  • “17 minutes ago”

I tried using this template (which eliminates automations that never triggered) but that style of entity filtering seems to lose the ability to support options with secondary-info: last-triggered

type: 'custom:auto-entities'
card:
  type: entities
  title: All Automations on
  show_header_toggle: false
filter:
  template: |
    {{ states.automation
       | selectattr('attributes.last_triggered')
       | sort(attribute='attributes.last_triggered', reverse=true)
       | map(attribute='entity_id')
       | list | join(', ') }}
sort:
  method: attribute
  attribute: last_triggered

Yes, you can exclude the ‘null’, check my script card doing so (commented)

1 Like

I focused so much on the first card that I didn’t examine the second one! :man_facepalming:

Thanks again!

So, I went to ‘limit’ the window for last triggered I was interested in, and tried : -

{% set timepoint = 2 %}
{% set timepoint = now() | as_timestamp - timepoint * 60 * 60 %}
{% set offset = 30 %}
{% set timefrom = timepoint - offset * 60 %}
{% set timeto = timepoint + offset * 60 %}
{% for state in states.automation | selectattr('attributes.last_triggered')
    | sort(attribute='attributes.last_triggered', reverse=true)
    | selectattr('state.last_triggered', '>', timefrom)
    | selectattr('state.last_triggered', '<', timeto) -%}
{{ state.attributes.last_triggered.timestamp() | timestamp_local }} : {{ state.name }}
{% endfor %}

I originally went with x < value < y but that gave a similar error and consulting the list of builtin functions couldn’t find a ‘window’ limit test, so I split it into two separate tests.
This too failed.
I’m thinking this must be (yet again) a failure based on last_triggered == none
but thought that had been filtered out by the first cast.
Maybe they work from right to left but changing order and parenthesis (in my limited tests given I’m groping in the dark and the possible permutations) yield similar results. :sob:

So If I’m interested in what happened 2 and a hafl hours ago I’d set timepoint to be 2.5 and if I wanted a 40 minutes window (each side) the offset = 40

FWIW, based on Marius’ suggestion, I’m able to have the auto-entities card display all automations that have triggered in the past 24 hours.

type: 'custom:auto-entities'
card:
  type: entities
  title: Active Automations
  show_header_toggle: false
filter:
  include:
    - domain: automation
      state: 'on'
      options:
        secondary_info: last-triggered
  exclude:
    - attributes:
        last_triggered: null
    - last_updated: ">= 1440"
sort:
  method: attribute
  attribute: last_triggered
  reverse: true

The only glitch is that if you increase 1440 (number of minutes in 24 hours) it seems to have no effect other than, beyond about 2500 it suddenly displays all my automations, regardless of when they triggered (i.e. days or even weeks ago). So if you only want to present automations that have triggered in the past 24 hours (in the UI), this does a neat job.

1 Like

Marius,
I think this is a neat option, but generally don’t want this guff occupying ‘real estate’ on any of my interface screens

BUT

Why would you comment out the null filter ? It would seem that this is pretty much required for any useful display of this (just trying to understand)
(My issue here being that a LOT of my automations are copied from other instances and set up for rooms (etc.) where the infrastructure isn’t even installed yet)

to show all available scripts/automations in the frontend (I have them for on and off automations too, to shorten the listings a bit…)

1 Like

Would you happen to know a way to make the auto-entities card display the automations without a toggle button next to each one? In other words, just show the automation’s friendly_name and, for secondary_info, the number of minutes since it was triggered.

I guess instead of the entities card, some sort of custom card would be needed?

type: 'custom:auto-entities'
card:
  type: entities #<------- custom card here?
  title: Active Automations
  show_header_toggle: false

Found this as I searched for “last_triggered” attribute.

When is this attribute updated? Directly if the trigger triggers or only if something happens after checking the condition?

trigger:
  - platform: time_pattern
    minutes: /15
condition:
  - condition: numeric_state
    entity_id: yahoofinance.isin
    attribute: fiftyDayAverageChange
    below: '3'
action:
  - service: notify.mobile_app_iphone

So should last_triggered be updated each 15 minutes regardless of the rest or only if the condition meets and the fiftyDayAverageChange in this example is below 3?

For me last_triggered should show last triggered and not last_done_something_after_triggered.

For the automation to be ‘triggered’ it must actually reach the ‘action’ part.
i.e. ‘trigger’ fired and ‘condition’ passed.

o.k. Is it working here this way as well, but wonder why this attribute is then not named last_action or whatever, perhaps as a second attribute. last_triggered is and should for me last_triggered.

Who is responsible for this miss-wording? :wink:

It’s a general name that covers 99% of meaningful usage cases.
As you have found, having it updated every 15 minutes (in your usage case) is just pointless
I suspect it was inherited from a time when ‘conditions’ did not exist.
If you really want the last_evaluated time then remove the condition - call a script in the action and then put your condition as the first step in the script.
Think about what you want and then do it
Arguing semantics won’t actually get you anywhere as 95% of the userbase is familiar with these terms how they are used (having implemented them as such) and anything else would cause a major breaking change.