I would like to measure the time a door is in the open position by measuring the time difference between two successive “off” to “on” sensor changes. I’ve found and tried variations of other templates that I’ve seen from others, but I consistently get an error message in developer tools template editor: “trigger” is undefined.
I attach an example template. I’d really appreciate help! Thanks.
template:
- trigger:
- platform: state
entity_id: binary_sensor.front_door_hive_sensor_opening
from: 'off'
to: 'on'
sensor:
- name: Door Opened Duration
unique_id: door_open_duration
state: "{{ (trigger.to_state.last_updated | as_timestamp - trigger.from_state.last_updated | as_timestamp) | int }}"
You cannot test templates that rely on the trigger variable in the Template Editor because the variable has no value there. Nor can you configure trigger-based template sensors in the Template Sensor Helper menu… they must be configured in YAML.
Can you give a broader description of what you are trying to accomplish? The state duration is already available for triggers and some conditions, so a sensor like this shouldn’t be necessary for most uses I can think of…
If you are determined to use this method, make sure to use the last_changed property, since it is specific to the entity’s state.
Thanks. That’s very helpful. Configuring in YAML works perfectly.
My intention was to create an entity that would indicate how long my front door had been left open for.
As a matter of curiosity, how would I access state duration for a trigger?
triggers:
- alias: Trigger when the door has been opened for 1 minute
trigger: state
entity_id: binary_sensor.front_door_hive_sensor_opening
from: 'off'
to: 'on'
for: "00:01:00"
Thanks. I probably haven’t explained what I’d hoped to achieve clearly enough.
I wanted to create an entity that would record how long the front door had been left open for when it was last opened.
I’m not sure a trigger that indicates the door has been opened for 1 minute would help me with that.