Problems with automation and motion sensor

I have this automation:

- alias: Accendi Luce Studio Sera
  initial_state: on
  trigger:
    platform: state
    entity_id: binary_sensor.motion_sensor_158d0001ddac9e
    to: 'on'
  condition:
    condition: or
    conditions:
      - condition: sun
        after: 'sunset'
        after_offset: "00:10:00"
      - condition: time
        before: 00:05:00
  action:
    - service: light.turn_on
      entity_id: light.philips_3
      data:
        brightness: 255             
    - service: light.xiaomi_miio_set_scene
      entity_id: light.philips_5
      data:
        scene: '1'
    - delay: 00:07:00
    - service: light.turn_off
      entity_id:
        - light.philips_3
        - light.philips_5

Which in theory must keep light on for 7 minutes, but it’s not as it works… just after 2 minutes the lights go off.
Why? Where it’s wrong?

If the automation triggers again while it’s still running from the first trigger, and it’s “sitting” in the delay, the delay gets canceled and it continues from there. Which means if the motion sensor detects motion and goes ‘on’, then goes ‘off’, and then motion is detected again two minutes after it first detected motion, the automation will get triggered a second time while it’s still running from the first trigger, causing the delay to get canceled and the next step to run which turns off the lights.

The way to deal with this is to move the actions into a script, then in the action part of the automation, first “turn off” the script (i.e., cancel it), then start it. This will cause the script to start from the beginning. So…

Automation:

- alias: Accendi Luce Studio Sera
  initial_state: on
  trigger:
    platform: state
    entity_id: binary_sensor.motion_sensor_158d0001ddac9e
    to: 'on'
  condition:
    condition: or
    conditions:
      - condition: sun
        after: 'sunset'
        after_offset: "00:10:00"
      - condition: time
        before: 00:05:00
  action:
    - service: script.turn_off
      entity_id: script.lights_on_7min
    - service: script.lights_on_7min

Script:

lights_on_7min:
  sequence:
    - service: light.turn_on
      entity_id: light.philips_3
      data:
        brightness: 255             
    - service: light.xiaomi_miio_set_scene
      entity_id: light.philips_5
      data:
        scene: '1'
    - delay: 00:07:00
    - service: light.turn_off
      entity_id:
        - light.philips_3
        - light.philips_5
1 Like

Thanks… i’ll try it and let you know…

Thank you for this post!
I had a problem with my automation switching off when motion is triggered for the second time and your explanation helped me to realise what was going on. Running it as a script sorted that right out.
Thanks!

You’re welcome.

You might be interested in this post where I provide two solutions - the same one as here, and another that ignores further triggers while the script is still running.