Automations no longer trigger when condition already met after rebooting HA (since an update to core)

It’s worth mentioning that I tend to allow an overhead of approx 100W so they do not toggle on or off the moment there is enough energy being produced to cover their consumption.

That can lead to some pretty complex conditions though, with a lot of repetitions unless you move all the logic out of the triggers and keep it only in the conditions (e.g. trigger on any change to sensor state but do the “above/below” test in the condition). I don’t know if that would drive any increased computational load, or if it’s equivalent.

Troon, all good points, but the ‘watches’ determined when you load an automation are the things you are trying to avoid, as this consumes ‘some’ processor overhead (some would argue a tiny insignificant part (which I’d tend to agree with)) but generally ALL these are followed by an ‘evaluation’, especially when it’s a template trigger (of which, I’m massively guilty of) (and yours is a fairly complex template trigger).
Regardless : -
If you put ALL the ‘requirements’ in the conditions then you’d need a fairly frequent trigger to evaluate often enough to not miss an event (but you could still miss it by 59 seconds even if you use sensor.time (or time: minutes: /1) (note: seconds: /1 would just spam everything) AND then you’d have to do ALL the evaluations every minute. Very inefficient.
Much better to use state triggers where you can and then only do an evaluation when a state changes.

Well, that depends, if just the one instance then suck it up, alternatively (and this can be massively more efficient *) create a binary_sensor.
* when I ran on a Pi4 I replaced ALL my switched time conditions into binary_sensor’s and my processor use went from 5% down to 1% Note an example use was a speaker (I have 4 of them), on between (say) 08:00 and 10:00 and again 16:00 to 19:00 but only if we were home AND the TV was not on (the music runs 24/7 but I just turn the speakers on and off). My time triggers are text comparisons where possible (evaluate on sensor.time change 1/min rather than time: which evaluates every second) etc. (So 4 times * 86400 down to 1440)
I’ve added about 30 automations since then and have moved to a NUC but I’m still at 1% but that’s mainly for the reboot/reload/config check times

1 Like

Agreed — it’s just a question if it’s better to:

  1. keep the trigger block simple (but as lengthy as it needs to be) with a list of entities to watch for state changes, then do the logic only in the condition; or
  2. do the logic in both blocks (with e.g. numeric_state) to try to reduce the number of trigger events, at the cost of duplicating the logic; or possibly even
  3. make the trigger block a potentially hideous template to cover all the required logic, obviating the need for conditions at all.

As you say, it’s likely a case-by-case judgement of how far to go and how many automations are needed to do a job.

Trying to handle things like HA restarts can make the required logic hard to work out and even worse to implement with and and or condition blocks.

Just seen your edit, and I do suggest a binary sensor a few screens up. I use that in my config for timespans and things like light level thresholds. I believe now() only triggers every minute, incidentally [ref].

1 Like

What do you do about snow cover ?

Yep ! - and that was an update ‘nagged’ for by Taras (@123) (thanks to bdraco) this is a workaround to allow backwards compatibility in some templates (it originally (well since 0.112 I think) was not meant to trigger any updates - but bdraco yielded this concession)
:rofl:
I avoid now() in all triggers and only use it in ‘some’ conditions (ie “was this automation fired less than 20 secs ago ?”) but it’s often useful just to get something to read as a timestamp
:man_shrugging:

FWIW, the use of now() in a template is a handy replacement for states('sensor.time'). However, both cause the template to be evaluated (at least) every minute which, depending on the use-case, can be either efficient or inefficient.

An example of inefficiency is where you only need to evaluate the template infrequently, like every day (or like in this situation, only after startup). That’s where the recently introduced Trigger-based Template Sensor really shines. It allows me to create a Template Sensor that is evaluated only when its Trigger fires. That means I can use a Time Trigger, executing at midnight, to evaluate the template only once per day (at the start of the day). A Trigger Template Sensor can use any kind of trigger (State, Numeric State, Time, Time Pattern, Event, etc).

1 Like

That’s interesting but for your example I’d just use sensor.date
I am genuinely interested in a more relevant and unique example could be used ?
Also the now() vs sensor.time efficiency thing - do you have examples of the yin and yang ?
I was recently involved in a chat with "will insert tag when I find his name @septillion " but he pointed out a very useful example of using now() to get timestamps from other objects (not just differences)
Let me get to a workstation (5 or 15 mins depending on how distracted I get)

Edit:
At Workstation :smiley:
Recently saw a “re-surfaced post” where petro was getting the date timestamp (no hours/minutes/seconds etc.) and he used : -

"{{ (states.sensor.date.last_changed.replace(hour=0,minute=0,second=0,microsecond=0)).strftime('%Y-%m-%d') }}"

Which Is pretty much what I’ve always used but septillion pointed out a couple of alternatives (3&5 below) : -

1dt {{ states.sensor.date.last_changed }}
2dt {{ states.sensor.date.last_changed.replace(hour=0,minute=0,second=0,microsecond=0) }}
3dt {{ states.sensor.date.last_changed.date() }}
4dt {{ states('input_datetime.id_meds_date_statin') }}
5dt {{ now().fromtimestamp(state_attr('input_datetime.id_meds_date_statin','timestamp')).date() }}

1ts {{ as_timestamp(states.sensor.date.last_changed) }}
2ts {{ as_timestamp(states.sensor.date.last_changed.replace(hour=0,minute=0,second=0,microsecond=0)) }}
3ts {{ as_timestamp(states.sensor.date.last_changed.date()) }}
4ts {{ as_timestamp(states('input_datetime.id_meds_date_statin')) }}
5ts {{ as_timestamp(now().fromtimestamp(state_attr('input_datetime.id_meds_date_statin','timestamp'))) }}

All these are to account for a restart in the day where ‘last_changed’ may be way off midnight AND easy to get timestamps from

  1. I realise that 1. above ‘should’ always be pretty close to midnight but it never is ‘bob-on’ and could be way off following a restart.
  2. This is petro’s normal way of dealing with this
  3. Simple and brilliant
  4. Fairly standard (from an input_datetime)
  5. A ‘bit’ longer winded but I’d never seen this form before (from an input_datetime)
    Just change the input_datetime to one that exists on your system

Which works if it’s the only time-based reference in the template. However, if the template also does some datetime arithmetic involving now() or sensor.time then it will be evaluated every minute (and not just once a day).

Not sure what you are referring to; both will cause the template to be evaluated every minute. Main difference is that one produces a datetime object and the other a string. When there’s a need to do time-based arithmetic, the datetime object is more useful.

So the example given in the documentation : -

template:
  - trigger:
      - platform: webhook
        webhook_id: my-super-secret-webhook-id
    sensor:
      - name: "Webhook Temperature"
        state: "{{ trigger.json.temperature }}"
      - name: "Webhook Humidity"
        state: "{{ trigger.json.humidity }}"

Could just as easily be : -

template:
  - trigger:
      - platform: state
        entity_id: sensor.date
    sensor:
      - name: "mutt_dist"
          value_template: "{{ '%.3f' | format(distance(states.device_tracker.life360_muttley)) }}"

Would give me a sensor giving my distance from home at midnight each day, ignoring all the other changes during the day ???
I read that in the annoucement but their description and it’s sample use sort of “were irrelevant”
I’m still a bit lost to put this into a context where it could be generally used. I get the pont where the webhook value changes then you could update, but what determines the polling ? why couldn’t you just set up a sensor for that web hook and trigger an automation on that update too ?? Obviously I’m missing something (a lot).

Yes but it’s not a long walk to as_timestamp(states.sensor.time.last_changed)
admittedly 40 more charachters but I did say I used now() in conditions etc.

No I just made an assumption that you were saying this was more efficient than that but not if other was true. My assumption - my error - I understand :+1:

Yes. Alternatively you could use a Time Trigger which does a better job of explaining when it triggers:

  - trigger:
      - platform: time
        at: '00:00:00'

But again that has to set a watch that evaluates every second - very bad
vs : -

    trigger:
      - platform: template
        value_template: "{{ states('sensor.time') == '14:00' }}"

So easier via an automation
(only 1440 minutes in a day Vs 86400 seconds )

Any trigger you use that employs time will be based on an internal (one-second) clock-tick. If the goal is to minimize template evaluation at each ‘tick’, a Time Trigger has no template to evaluate.

Don’t overlook the fact that sensor.time is driven by the same internal clock as the Time Trigger.

Yes (and now() is worse as it has to interogate the actual physical hardware clock (ticks dependent on cpu frequency which is why now() always gives you a decimal second (as it should) ) as opposed to internal states so it’s much more time intensive)
So the ‘HA clock’ is updated once/second
and sensor.time is updated 1/minute
Both these are internal updates
The text comparison is ‘more complex’ but only has to be checked 1440 times so unless it is more than 59 times more intensive then you are still ahead of the game (my tests on such evaluations (see above) indicate that it’s about (only) 15 (or less) times more inefficient [from my processor gains on the same hardware])

If relies on sensor.time which also relies on the internal clock (and its 1-second tick). Every 60 ticks, the sensor state is updated which then causes the template (in your example) to be evaluated.

The Time Trigger is governed by the same internal clock as sensor.time and subject to the 1-second tick. The primary difference is that nothing gets evaluated every 60 ticks, it simply triggers on the first tick of each new day.

Anyway, I’ve run out of time (no pun intended) and if I haven’t convinced you, that’s OK.

1 Like

Yep, I feel the same and that’s okay too
From previous discussion with pnbruckner I understood that any time: trigger required 84600 evaluations per day. I’ve also seen that bdraco considered such to be ‘trivial’ So I’m willing to be swayed. But the empiracle evidence suggests text*1440 << time*84600
I would welcome anyone who can carve this in stone one way or another

As always Taras it has been a pleasure and an education - many thanks

Except the “text” in that equation is sensor.time which is constantly being serviced by the internal clock (every second until 60 seconds accumulate and then it updates the sensor’s state). If you ignore that fact then you should hold the Time Trigger to same standard in which case it only updates once at the scheduled time. :man_shrugging:

am I correct that where we before had to store the value of a current power meter in a input_number, and save that in an automation with eg platform time, at ‘00:00:00’ and feed that to a template sensor (we can record, so it doesn’t get lost during restarts)

and doing so for all power sensors with dedicated Input_numbers, we can now use the trigger based template sensor to do that for us directly, without the need for an intermediary Input_number:

template:
  - trigger:
      - platform: time
        at: '00:00:00'
    sensor:
      - name: Network usage daystart
        state: >
          {{states('sensor.network_usage')}}
      - name: Network power daystart
        state: >
          {{states('sensor.network_power')}}
      - etc etc

since I have all of these usage and power sensors in a group, I wonder if we could create a template to auto build the sensors?

right now I did it in Python, but maybe we can now create that more easily in core HA?

groupPower = 'group.z_wave_switches'

# idPower = ''
# sensor_valuePower = ''

for entity_id in hass.states.get(groupPower).attributes['entity_id']:
    statePower = hass.states.get(entity_id).object_id
    idPower = statePower.split('_power_daystart')[0]

    input_idPower = 'input_number.{}_power_daystart'.format(idPower);
    sensor_idPower = 'sensor.{}_actueel'.format(idPower);

#################################################################################
# Select Input_number and set value to the corresponding sensor
#################################################################################

# get sensor value
    sensor_valuePower = hass.states.get(sensor_idPower).state
#
# and assign to input_number
    hass.services.call(
        'input_number',
        'set_value',
        {'entity_id': input_idPower,
         'value': sensor_valuePower}
        )

I have no experience with the scenario you described (employing input_numbers, automations, template sensors, etc) but the example of the Trigger-based Template Sensors you proposed makes sensor to me.

ok thanks, nevermind the auto creating with the groups for now, right now I am puzzling with:

template:
  - trigger:
      - platform: time
        at: '00:00:00'
    sensor:
      afzuigkap_zolder_power_daystart:
        name: Afzuigkap zolder power daystart
        state: >
          {{states('sensor.afzuigkap_zolder_actueel')|float}}
        unit_of_measurement: W
      toaster_keuken_power_daystart:
        name: Toaster keuken power daystart
        state: >
          {{states('sensor.toaster_keuken_actueel')|float}}
        unit_of_measurement: W
      subwoofer_auditorium_power_daystart:
        name: Subwoofer auditorium power daystart
        state: >
          {{states('sensor.subwoofer_auditorium_actueel')|float}}
        unit_of_measurement: W
etcetc

and

and of course I copied too much of the old template sensors, but still, even correcting it like:

template:
  - trigger:
      - platform: time
        at: '00:00:00'
    sensor:
      - name: Afzuigkap zolder power daystart
        state: >
          {{states('sensor.afzuigkap_zolder_actueel')|float}}
        unit_of_measurement: W
      - name: Toaster keuken power daystart
        state: >
          {{states('sensor.toaster_keuken_actueel')|float}}
        unit_of_measurement: W
      - name: Subwoofer auditorium power daystart
        state: >
          {{states('sensor.subwoofer_auditorium_actueel')|float}}
        unit_of_measurement: W

yields the identical error? heck, it does even error out on:

template:
  - trigger:
      - platform: time
        at: '00:00:00'
    sensor:
      - name: Afzuigkap zolder power daystart
        state: >
          {{states('sensor.afzuigkap_zolder_actueel')|float}}
        unit_of_measurement: W

and Ive also tried to quote all fields, and used single line template… anyone please spot the error?

edit

there’s no error, its a bug probably, or at least not fully developed yet. It’s the fact these sensors are configured in a package. When written in configuration.yaml, the config checks ok.