Single automation to turn light on/off based on door sensor open/closed

I’ve currently got some automations created to turn a light on when a door opens & another to turn the light off when the door closes. Is it possible to collapse this logic into a single automation?

alias: Pantry Open
  description: ''
  trigger:
  - entity_id: binary_sensor.wyzesense_77a065bb
    platform: state
    to: 'on'
  condition: []
  action:
  - device_id: ee102a0712ed451d9a2b08610c2e3f19
    domain: light
    entity_id: light.hue_ambiance_lamp_2
    type: turn_on

alias: Pantry Closed
  description: ''
  trigger:
  - entity_id: binary_sensor.wyzesense_77a065bb
    platform: state
    to: 'off'
  condition: []
  action:
  - device_id: ee102a0712ed451d9a2b08610c2e3f19
    domain: light
    entity_id: light.hue_ambiance_lamp_2
    type: turn_off

If it isn’t broken, don’t fix it!

If you did want to condense it into a single automation though, here’s one way to do it:

- alias: Turn pantry light on/off
  initial_state: true
  trigger:
  - platform: state
    entity_id: binary_sensor.wyzesense_77a065bb
  action:
  - service_template: "light.turn_{{ trigger.to_state.state }}"
    entity_id: light.hue_ambiance_lamp_2

That did the trick thanks. Will reduce my number of automations nicely.

And seems to behave as wanted if the door was already open, but light turned on from the switch, but are guessing that’s what the ‘trigger.to_state.state’ is doing to match the light state to the sensor state.

1 Like

With the enhancements to automations in 0.114, you can also do something like this, and more straightforward to edit in the UI as well.

I use automations like this to turn on/off lights in closets based on whether the door is open. A side-benefit is that it implicitly reminds people to close doors when they’re done in the closet.

- id: DoorLightsCloset
  alias: Door Lights - Closet
  description: ''
  trigger:
  - entity_id: binary_sensor.closet_door
    platform: state
  condition:
  - after: sunrise
    before: sunset
    condition: sun
  action:
  - choose:
    - conditions:
      - condition: state
        entity_id: binary_sensor.closet_door
        state: 'on'
      - condition: state
        entity_id: light.closet
        state: 'off'
      sequence:
      - entity_id: light.closet
        service: light.turn_on
        data:
          brightness_pct: 100
          color_temp: 200
    - conditions:
      - condition: state
        entity_id: binary_sensor.closet_door
        state: 'off'
      - condition: state
        entity_id: light.closet
        state: 'on'
      sequence:
      - entity_id: light.closet
        service: light.turn_off
    default:
    - delay: 00:00:01
  mode: single
4 Likes