How do I do this Automation?

Hi. I am super new to home assistant. I hope you can help me with an automation that I want to do.

I have two fence doors named fence_A and fence_B. I want the switch named light.kitchen to turn on if either fence_A or fence_B is open. If both fence_A and fence_B are closed, then I want light.kitchen to turn off.

Help!

Here’s the logic flow

IF a == Open OR b == Open then turn on light

IF a == closed AND b == closed then turn off light

For the open you can just set the trigger to be as described above with “or” logic. For the closed though you will need to use “or” logic for the trigger but have a condition for “and”.

What are the actual door entity_id’s? I.e., sensor.fence_A, binary_sensor.fence_A, cover.fence_A, switch.fence_A, …? For this example I’ll just assume they’re binary_sensor’s (where open corresponds to a state of ‘on’, and closed corresponds to a state of ‘off’.) Adjust accordingly if your sensors are something else.

You can do this in one automation using a state trigger, and service_template in the action part:

- alias: Change kitchen light per fence doors
  trigger:
    platform: state
    entity_id: binary_sensor.fence_A, binary_sensor.fence_B
  action:
    service_template: >
      # If either fence door is open, turn on light. Else turn it off.
      {% if is_state('binary_sensor.fence_A', 'on') or
            is_state('binary_sensor.fence_B', 'on') %}
        light.turn_on
      {% else %}
        light.turn_off
      {% endif %}
    entity_id: light.kitchen

So, whenever either door changes the action will run. If either door is open, the light is turned on. Otherwise (i.e., both doors closed) the light will be turned off.

Thank you sooooooooooo much.

Thanks for the service template?

One, question. In a different use case could this be changed to and to require both states to be met for the action?

Not sure what you mean. Could you describe the use case you’re thinking of?

Sorry

action:
    service_template: >
      # If either fence door is open, turn on light. Else turn it off.
      {% if is_state('binary_sensor.fence_A', 'on') and
            is_state('binary_sensor.fence_B', 'on') %}
        light.turn_on
      {% else %}
        light.turn_off
      {% endif %}
    entity_id: light.kitchen
  1. can ‘and’ be used like added above. 2. Would this act such that if fence_a and fence_b are ‘on’ the light would turn on, but if only one is on or both off the light would turn off?

Yes, and yes. :slight_smile:

1 Like