How can I achieve this automation?

I have a bathroom under the stairs which has no natural light. I have a contact sensor on the door and smart switch on the light. I would like to light to turn on when I open the door and the light to turn off when I exit the bathroom so when the door opens again. Please could someone help me achieve this using either homeassistant automations or node red.

description: "Bathroom light when door changes"
mode: single
trigger:
  - platform: state
    entity_id:
      - binary_sensor.bathroom_door_contact_sensor_contact
    from: "off"
    to: "on"
    id: door_open
  - platform: state
    entity_id:
      - binary_sensor.bathroom_door_contact_sensor_contact
    from: "on"
    to: "off"
condition: []
action:
  - if:
      - condition: trigger
        id:
          - door_open
    then:
      - service: light.turn_on
        metadata: {}
        data: {}
        target:
          entity_id: light.bathroom_sink_light_1
    else:
      - service: light.turn_off
        target:
          entity_id:
            - light.bathroom_sink_light_1
        data: {}

I forgot to add what @Nick4 stated. This relies on the door being closed every time. Otherwise the light will just stay on. Personally, I would add either a PIR motion sensor or a presence sensor in and then use the door contact sensor to disable the motion timeout (for those long sessions on the throne lol).

@hanzala-123: be aware that this only works IF EVERYBODY closes the door after entering and closing again after leaving.

1 Like

thank you very much!