Template Sensor for Healthy State w/ last_changed

I’m trying to build a binary_sensor template, the idea will be to check if the HVAC system is ON and if any doors have been opened.

The template will be much more complex than what I’m describing here, this is the simplified version with just the “problem”.

So, I have the following template, which works:

{{is_state('binary_sensor.kitchen_door', 'on') and is_state('climate.kitchen', 'heat')}}

But this changes to true state immediately when a door is opened, what I want is to change to true just a few seconds after the door is opened (the same behavior as in automations)

So, I have this:

{% set last_changed = (as_timestamp(now())-as_timestamp(states.binary_sensor.kitchen_door.last_changed)) | int %}
{{is_state('binary_sensor.kitchen_door', 'on') and is_state('climate.kitchen', 'heat') and last_changed > 10}}

The problem with the template above is that last_changed is not updated systematically, which makes the code very erratic, sometimes it changes after 12 seconds, sometimes 20 seconds, and it has taken me about 40 seconds. which is a long time and not acceptable for my usecase.

This is very simple to do with automations, but I want to build a binary_sensor instead.

Does anyone know a better way to achieve this?

Check for “delay_on” option for template sensors.

The problem with your current solution is you are making assumptions about how often this template is evaluated. If you enter your template in developer tools you will get the answer you didn’t expect - The start of every minute due to your use of now() which is specifically called out in the template documentation.

{96B78BCF-18F6-48E2-9FEC-221BB5DCB2B8}

Ohh… I wasn’t aware of the delay_on

I was using frontend to create my templates, it seems this option is only available in yaml, but yaml also works for me so I’ll give it a try…

Thanks

Shame on me :cry:

I’ve been using Home Assistant for about 3 years, I’ve never read this before and it seems like it was always present in the box after the template results…

Now the question remains whether the same behavior exists in the template sensors, because I haven’t tested it (only in the developer tools), but I’m going to do my tests now…

Thanks