I am using xiaomi open door sensor and it works fine, but i need show then the door was opened last time. So I made template sensor bases on state last_changed
but here one problem. It show any statuses changed, but how i can track only last change for
{{ states.binary_sensor.openclose_11.state }} is “on”? because when i reboot HA that sensor show the status “unavailable” and it update the template sensor. I need only state == “on”. How to do it and ignore “off” and “unavailable” states?
I use the variable integration from HACS which is better than looking at last_changed as it preserves the data through a reboot of HA. I have a templates automation that watches all doors being opened and updates the correct variable. Each variable also has attributes that track the last 3 openings.
Sorry for jumping into an old thread. I’m trying to overcome the exact same problem as you DukeNuken. I’ve been playing with the sql sensor for the last few hours to try and get around the reboot issue, so far, no luck!
Were you able to find a solution?
Edit: 10mins after posting this I worked it out by using the SQL sensor
- name: Front Door Last Open
query: "select last_changed from states where entity_id = 'binary_sensor.lumi_door_front_door' and state = 'on' order by last_changed desc;"
column: 'last_changed'
value_template: "{{ as_timestamp(value~'+00:00') | timestamp_local }}"
automation:
- alias: "Motion Update"
mode: queued
trigger:
- platform: state
entity_id: binary_sensor.living_room_51_20
to: "on"
- platform: state
entity_id: binary_sensor.kitchen_52_20
to: "on"
action:
- service: script.last_variable_update
data:
history_entity_id: "{{trigger.entity_id}}"
prefix: "last_"
The important connection is that the last part of the triggered entity (in my example, “living_room_51_20” and “kitchen_52_20” match up with a defined variable with name - in my example, I use “last_” as the prefix so my variables are named “last_living_room_51_20” and “last_kitchen_52_20”.
I then track the last 5 times the entity switched to on - though you could easily increase to more history just by adding extra lines to the script.
I use a similar script & auto (not listed here) that tracks the date, time, and location of the last 5 entities that reported motion and the last 5 doors there were opened.