I “wanted” to create an automation, which informs me, when a window is open for over an hour. So I created the following action:
- if:
- condition: and
conditions:
- condition: state
entity_id: binary_sensor.window
state: "on"
- condition: template
value_template: {{ (now() - states['binary_sensor.window'].last_changed) >= timedelta(minutes=60) }}
then:
- service: notify.xyz
data:
message: The window can be closed!
The first condition correctly resolves to TRUE, but the second condition always resolves to FALSE (even if the window is open for over 2 hours.
In the developer tools the condition correctly resolves to TRUE.
That should solve the problem. You should re-think how you’re doing this in terms of what you’re triggering on, though. I’d suggest something like this (untested):
alias: Alert if window open
description: Sends a notification if the window has been open for an hour
id: 78d5d4d0-d353-4e67-b0d2-e7f19416f6d1
trigger:
- platform: state
entity_id: binary_sensor.window
to: 'on'
for:
hours:1
action:
- service: notify.xyz
data:
message: The window can be closed!
Regarding your proposal:
If I’m correct the notification is only send once after one hour. What I want to archieve is that I get a notification every x minutes after one hour as long as the window stays open. Is there also a “cleaner” way to do that?
Using a time_pattern trigger, checks every five minutes and sends the notification if the window has been open for at least an hour:
alias: Alert if window open
description: Sends a notification every five minutes if the window has been open for at least an hour
id: 870fff24-b02e-45d7-8328-42bae810023e
trigger:
- platform: time_pattern
minutes: "\5"
condition:
- condition: state
entity_id: binary_sensor.window
to: 'on'
for:
hours:1
action:
- service: notify.xyz
data:
message: The window can be closed!
Note that this may not send the first trigger until almost 65 minutes after the window has opened, if you open it just after one of the checks (e.g. open at 13:21, first alert at 14:25).
In my mind, this method is a little more elegant and less resource-intensive than evaluating a template every minute — but in practice, you won’t notice the difference.