Switch off light with presence detection

Hi everybody…

maybe someone can help me with my automation. There is a “loophole” that the lights are not switched
off automatically. The logic should be as follows:

  1. When the PIR recognizes moving and the illuminance is lower than 20 lux the lights should switch on
  2. Delay of one minute
  3. If the PIR recognizes a moving during the delay the automation starts again (mode: restart)
  4. Checking the distance of the BLE-Tracker. If over 2m the condition is true and the lights are switched off. Else the automation should start again.

Sometimes the lights keep on and I can’t find the “loophole”. Has anybody an idea?.

alias: >-
  Licht im Büro an, wenn Lux über 20 und Bewegungsmelder. Aus nach 1 Minute oder
  Restart
trigger:
  - platform: state
    entity_id: binary_sensor.pir_office
action:
  - choose:
      - conditions:
          - condition: template
            value_template: '{{ trigger.to_state.state == ''on'' }}'
          - condition: numeric_state
            entity_id: sensor.illuminance_office
            below: '20'
        sequence:
          - service: light.turn_on
            data: {}
            target:
              device_id: 35b44602c424f22fc6abd4017aa6b192
    default:
      - delay:
          hours: 0
          minutes: 1
          seconds: 0
          milliseconds: 0
      - condition: or
        conditions:
          - condition: state
            entity_id: sensor.gallifrey_distance_in_m
            state: unknown
          - condition: numeric_state
            entity_id: sensor.gallifrey_distance_in_m
            above: '2'
      - service: light.turn_off
        data: {}
        target:
          device_id: 35b44602c424f22fc6abd4017aa6b192
mode: restart

Best regards
Goran

Check the automation traces: