- alias: Meteo ed Agenda
trigger:
- platform: state
entity_id: input_boolean.mauhome
to: 'on'
- platform: state
entity_id: binary_sensor.motion_sensor_158d0001a92ca1
to: 'on'
condition:
- condition: time
after: '08:30'
before: '10:00'
- condition: template
value_template: '{{(as_timestamp(now()) - as_timestamp(states.automation.meteo_ed_agenda.attributes.last_triggered | default(0)) | int > 5400 )}}'
action:
- service: media_player.volume_set
data_template:
entity_id: media_player.googlehome0461
volume_level: 0.50
- service: tts.google_say
data_template:
entity_id: media_player.googlehome0461
message: >-
… and follows the message i want to be said…
It works good if the motion sensor is activated between the time configured in condition, but if the motion sensor is triggered before that time, the automation start randomly and automatically between that time.
How to change it so it is triggered only if the motion sensor is activated between that time?
I believe there is an issue with using now() in a template. Something about it not updating and staying static to the time the automation was deployed or something.
The issue is using it as part of the sensors (i.e. effectively the trigger) in a template_sensor (since version 0.81). Here it is being used in the condition of an automation.
OK, no problem. Here is what I think is happening.
This part means uses the value for last_triggered or, if it is undefined, it uses zero.
as_timestamp means convert the value into Unix timestamp format. That’s just a big number representing the number of seconds since January 1, 1970.
This part calculates the elapsed time, namely the number of seconds from now() and when the automation triggered previously (last_triggered).
If that integer number is greater than 5400 seconds (int > 5400) then the template evaluates to true.
However, the problem is that if this: as_timestamp(states.automation.meteo_ed_agenda.attributes.last_triggered | default(0)
is zero then the elapsed time is just equal to the current timestamp which is a number much larger than 5400. So the template also evaluate to true even though the elapsed time is not truly 5400 seconds.
So the template’s logic is flawed.
While typing all this, I noticed @petro has already summarized it and posted a solution so I’m going to stop typing now ….
Haha! No problem! You stated the core problem perfectly here:
My guess is last_triggered is undefined immediately after restarting Home Assistant. Effectively, the first time the automation is executed, it has no last_triggered and the template’s faulty logic causes a false-positive (between 8:30 and 10:00).
Your guess is correct. I just restarted, luckily I have 1 automation that isn’t in appdaemon. That automation hasn’t been fired and last_triggered is defined but set to null. Which is why I updated the post. The only concern I have is that I hope last_triggered is a date time object.