Comparing states of two entities

I have two contact sensors, one detecting when a door has been opened, and another when a handle has been raised.

When the handle is raised, and the door is closed, it engages the doors deadlocks.

I’d like a binary sensor to show whether or not the deadlocks are engaged.

The logic I need is as follows:-

If the door is opened at any time, deadlocks are false (disengaged)
If the handle is raised whilst the door is closed, then the deadlocks are engaged.
The state of the handle should be ignored whilst the door is open.

I can do this with an automation and an input boolean helper, but wondered whether or not this is doable with a template sensor ?

It helps if you give us the actual entity ids. But here’s the idea with made up ids:

template:
  - binary_sensor:
      - name: Deadlock
        state: "{{ is_state('sensor.handle','raised') and is_state('binary_sensor.door','off') }}"

Those entities id’s work fine for this exercise.

However, the problem is the handle state.

The handle is only raised momentarily to engage the deadlock, so to get the deadlock into a ‘true’ state, the above works fine, but once deadlocks are true, the handle could be lowered. Only the door opening can change the deadlock state to false.

My pseudo code:-

if deadlocks are false and handle is raised and door is shut then deadlocks are true.
if door is opened then deadlocks are false.

If you provide them, we don’t have to spend brainpower making them up.

That logic sounds like you need a trigger-based template sensor:

template:
  - trigger:
      - trigger: state
        entity_id:
          - sensor.handle
          - binary_sensor.door
    binary_sensor:
      - name: Deadlock
        state: >
          {% if is_state('sensor.handle','raised') and is_state('binary_sensor.door','off') %}
            on
          {% elif is_state('binary_sensor.door','on') %}
            off
          {% else %}
            {{ this.state }}
          {% endif %}

Door handle sensor entity is:-

binary_sensor.aqara_contact_front_door_handle_opening_9

And the door open/close is:-

binary_sensor.lumi_lumi_sensor_magnet_aq2_opening

Thanks, I’ll try that out.

Then it won’t have a state of raised but will be on or off. I’m sure you can work it out from there, though.

yeah I figured that… the code looks great.

I’ve always stayed way from trigger based templates, preferring automations, because they basically look very similar, but I thought I would use this as an exercise to learn a bit more about them.

Yeah, they are similar. Before they existed, you’d be using an automation to manipulate an input_boolean to do this job, but they make it much cleaner.

Exactly… which was going to be my first approach until I remembered there could be another way. Thankyou both for you speedy help this morning.