Template sensor Help needed

I want to create a template sensor that will compare the states (time) of the 2 sensors (Door sensor & motion sensor) to define the occupancy status of my bathroom.

i understand that {{ ((as_timestamp(states.binary_sensor.touch_less_toilet_door_sensor.last_changed)) | int) }} returns the last changed state time of the binary sensor .(iresspective it was ON or OFF change.

In the above, how do I template to get the last changed ON state only?

I basically want to compare the time of ON state of Door senor with ON state of motion senor & decide occupancy status
please help

I would create two SQL Sensors, one for each binary_sensor, that retrieves the last time they turned 'on', then use those in a third template sensor that compares them. E.g.,

sensor:
  - platform: sql
    queries:
      - name: Toilet Door Last Open
        query: "SELECT * FROM states WHERE entity_id = 'binary_sensor.touch_less_toilet_door_sensor' AND state = 'on' ORDER BY state_id DESC LIMIT 1;"
        column: last_changed

EDIT: I suppose for someone who knows more about SQL this could all be done in one query, but I only know a few basics. :slightly_smiling_face:

1 Like