The following Trigger-based Template Sensor monitors a binary_sensor (like a door) and reports the longest time it was left on its longest attribute (in seconds). The 5 highest values are reported in its openings attribute including the time when it was turned on and off.
The sensor’s state value simply reports the most recent time when the binary_sensor was turned off.
template:
- trigger:
- platform: state
entity_id: binary_sensor.front_door
from: 'on'
to: 'off'
- platform: time
at: "00:00:00"
sensor:
- name: Door Openings
unique_id: template_door_openings
state: "{{ now().timestamp() | timestamp_custom() }}"
attributes:
longest: >
{% if trigger.platform == 'state' %}
{% set current = this.attributes.get('openings', []) | map(attribute='duration') | list %}
{% set new = [(now() - trigger.from_state.last_changed).total_seconds() | int(0)] %}
{{ ((new + current) | sort(reverse=true))[0] }}
{% else %}
unknown
{% endif %}
openings: >
{% if trigger.platform == 'state' %}
{% set current = this.attributes.get('openings', []) %}
{% set new = [{
"opened": (trigger.from_state.last_changed | as_local).isoformat(),
"closed": now().isoformat(),
"duration": (now() - trigger.from_state.last_changed).total_seconds() | int(0) }] %}
{{ ((new + current) | sort(reverse=true, attribute='duration'))[:5] }}
{% else %}
{{ [] }}
{% endif %}