Control lights based on motion and brightness

Unfortunately there is a small bug in this automation. If the lights are turned on the brightness in the room will (obviously) increase. This will cause the automation to sometimes turn off the lights again.
To fix this I changed the automation to keep the lights on as long as there is motion. This needs the target selector in the condition though which is not supported.
Fortunately I found a workaround (at least if you only use entities) and added it to my Github as version 2. An in-depth explanation can also be found on my blog.

Here is the updated code:

blueprint:
  name: Motion and brightness activated Light V2
  description: Turn on a light when motion is detected and it is dark enough or night.
  domain: automation
  source_url: https://github.com/OliverHi/blueprints/blob/f010d88630fa3e0d68074905b1258e8580f3b2f6/motion_brightness_light.yaml
  input:
    motion_entity:
      name: Motion Sensor
      selector:
        entity:
          domain: binary_sensor
          device_class: motion
    brightness_entity:
      name: Lux/Brightness Sensor
      selector:
        entity:
          device_class: illuminance
    light_target:
      name: Light(s) to control
      selector:
        target:
          entity:
            domain: light
    brightness_trigger:
      name: Maximum brightness
      description: Brightness trigger level. If it gets any brighter the lights will not be turned on.
      default: 20
      selector:
        number:
          min: 0
          max: 1000
          unit_of_measurement: lx
    no_motion_wait:
      name: Wait time
      description: Time to leave the light on after last motion is detected.
      default: 120
      selector:
        number:
          min: 0
          max: 3600
          unit_of_measurement: seconds

# If motion is detected within the delay,
# we restart the script.
mode: restart
max_exceeded: silent

# making the input variable usable in the condition
variables:
  lights: !input "light_target"

trigger:
  platform: state
  entity_id: !input motion_entity
  from: "off"
  to: "on"

condition:
  - condition: or
    conditions:
      - "{{ expand(lights.entity_id) | selectattr('state', '==', 'on') | list | count > 0 }}" # some lights in the group are on
      - condition: numeric_state
        entity_id: !input brightness_entity
        below: !input brightness_trigger

action:
  - service: light.turn_on
    target: !input light_target
  - wait_for_trigger:
      platform: state
      entity_id: !input motion_entity
      from: "on"
      to: "off"
  - delay: !input no_motion_wait
  - service: light.turn_off
    target: !input light_target
2 Likes