Automation: If then else ->delay->turn off

I’ve been struggling with this automation for a bit, unfortunately it am in way over my head…

What I’m trying to do is:

when a movement is detected -> turn on light1 if door sensor open -> wait for 2 min with no movement -> turn off light1

and

when a movement is detected -> turn on light2 if door sensor closed -> wait for 2 min with no movement -> turn off light

These are the basic working automations that I’m trying to modify, can anyone help me achieve this?

- id: '1593100009023'
  alias: Movimento Wc
  description: ''
  trigger:
  - device_id: 5e88486a997f4e0e86f16dc3074c3b71
    domain: binary_sensor
    entity_id: binary_sensor.tradfri_motion_sensor_2
    platform: device
    type: motion
  condition:
  - condition: state
    entity_id: binary_sensor.porta_laura
    state: 'on'
  action:
  - device_id: b72300cf3d7d451d825ab4aa840b8bc7
    domain: switch
    entity_id: switch.shelly_wc_espelho
    type: turn_on
- id: '1593101341636'
  alias: movimento wc laura a dormir
  description: ''
  trigger:
  - device_id: 5e88486a997f4e0e86f16dc3074c3b71
    domain: binary_sensor
    entity_id: binary_sensor.tradfri_motion_sensor_2
    platform: device
    type: motion
  condition:
  - condition: state
    entity_id: binary_sensor.porta_laura
    state: 'off'
  action:
  - device_id: b72300cf3d7d451d825ab4aa840b8bc7
    domain: switch
    entity_id: switch.shelly_wc
    type: turn_off

Turn on the required switch:

  trigger:
  - platform: state
    entity_id: binary_sensor.tradfri_motion_sensor_2
    to: 'on'
  action:
  - service: switch.turn_on
    data_template:
      entity_id: {% switch.shelly_wc_espelho if is_state('binary_sensor.porta_laura', 'on') else switch.shelly_wc %}

Turn them both off after two minutes of no movement:

  trigger:
    platform: state
    entity_id: binary_sensor.tradfri_motion_sensor_2
    to: 'off'
    for:
      minutes: 2
  action:
    service: switch.turn_off
    entity_id: 
      - switch.shelly_wc
      - switch.shelly_wc_espelho
1 Like

Hey thanks for the response, it does the job i will try to add a condition to the second automation to only turn off if previsious state was off, so that if someone uses the switch rather the motion (in the bathtub the motion doesnt get detected so the light would turn off mid bath) the light wont turn off after no movement, would it work?

See here: