Motion-activated Light Extended

MOTION ACTIVATE LIGHT EXTENDED - New version

This is blueprint for Home Assistant intended to help to create automations to turn on/off lights as a reaction of a movement sensor.
This is an evolution of standard motion activated light.

In this blueprint, I’ve supported some important additional features intended to improve the flexibility of the component.

  • Ability to activate enable/disable the motion activation light based on sunset and sunlight

  • Ability to override the sunset / sunrise conditional activation based on the weather

  • Ability to define a timeout after that the light turn off also if movement sensor is already on (useful to situations in which sensors sometimes fails to communicate deactivation due to connectivity problems).

  • NEW - Ability to don’t execute the blueprint if the light (or the lights) is already on (prevent auto-turn-off if the light was turned on manually). This option is false by default to preserve backward compatibility. When enabled, it ensures that the blueprint does not trigger if at least one of the lights associated with the motion sensor is on. The purpose of this is to prevent the automation from turning off the light at the end of the period if it was manually turned on with a switch rather than by the motion sensor (thx to @wgumaa for the suggestion)

All this options can be activated or not so you can freely combine them. For use the blueprint in its more general form you need one or more entities of this domains/class:

  • binary_sensor / motion
  • light
  • weather

Open your Home Assistant instance and show the blueprint import dialog with a specific blueprint pre-filled.

blueprint:
  name: "Motion-activated Light extended"
  description: "Turn on a light when a movement occurs"
  domain: automation
  source_url: https://github.com/giannisigalotti/HomeAssistant/blob/main/blueprints/motion-activated-light.yaml
  input:
    motion_entity:
      name: "Motion sensor"
      selector:
        entity:
          domain: binary_sensor
          device_class: motion
    light_target:
      name: Light
      selector:
        target:
          entity:
            domain: light
    no_motion_wait:
      name: "Wait time"
      description: "The time to wait before turning off the light after no movement is detected."
      default: 120
      selector:
        number:
          min: 0
          max: 3600
          unit_of_measurement: seconds
    skip_if_light_is_on:
      name: Do not execute if the light is already on (prevent auto-turn-off if the light was turned on manually).
      selector:
        boolean:
      default: false
    no_sunset_handling:
      name: "Disable day/night management?"
      description: "When you turn this option to off, you can define how many hour before sunset and after sunshine the automation turn on the light"
      selector:
        boolean:
      default: false
    wheater_handling:
      name: "Enable meteo managment?"
      description: "Does it also take weather into account to enable/disable motion sensors (use the time range only when it's sunny and disable otherwise)?"
      selector:
        boolean:
      default: false
    wheater_entity:
      name: "Weather status sensor"
      description: "This sensor is used only with the Meteo managment option to determine if the weather is sunny or not (useful if you are in a room usually dark in case of bad weather condition"
      selector:
        entity:
          domain:
            - weather
          multiple: false
      default: "weather.home"
    sunset_start_hh:
      name: "Pre-sunset hours activation"
      description: "How many hours before sunset does the management activate (negative numbers indicate a delay)?"
      selector:
        number:
          min: 0
          max: 12
          unit_of_measurement: hours
      default: 0
    sunset_start_mm:
      name: "Pre-sunset minutes activation"
      description: "How many minutes before sunset does the management activate (negative numbers indicate a delay)?"
      selector:
        number:
          min: 0
          max: 59
          unit_of_measurement: minutes
      default: 0
    sunrise_start_hh:
      name: "Post-sunrise hours activation"
      description: "How many hours after sunrise does the management deactivate (negative numbers indicate an advance)?"
      selector:
        number:
          min: 0
          max: 12
          unit_of_measurement: hours
      default: 0
    sunrise_start_mm:
      name: "Post-sunrise minutes activation"
      description: "How many minutes after sunrise does the management deactivate (negative numbers indicate an advance)?"
      selector:
        number:
          min: 0
          max: 59
          unit_of_measurement: minutes
      default: 0
    timeout:
      name: "Deactivation timeout?"
      description: "After how many minutes does the switch turn off automatically (-1 if no timeout)"
      selector:
        number:
          min: -1
          max: 60
          unit_of_measurement: minutes
      default: 5
# If motion is detected within the delay,
# we restart the script.
mode: restart
max_exceeded: silent

trigger:
  platform: state
  entity_id: !input motion_entity
  from: "off"
  to: "on"
variables:
  # Make input my_input available as a script level variable
  dusk_start_hour: !input sunset_start_hh
  dusk_start_minute: !input sunset_start_mm
  rising_start_hour: !input sunrise_start_hh
  rising_start_minute: !input sunrise_start_mm
  use_weather: !input wheater_handling
  skip_light_on: !input skip_if_light_is_on
  target_lights: !input light_target
  force_skip: >
    {{ skip_light_on and
        (expand(
                  (([] if target_lights.device_id is undefined
                  else target_lights.device_id | device_entities
                  if target_lights.device_id is string
                  else target_lights.device_id | map('device_entities') | sum(start=[]) )
                  +
                  ([] if target_lights.entity_id is undefined
                  else [target_lights.entity_id]
                  if target_lights.entity_id is string
                  else target_lights.entity_id ))
                 | select('search', '^light\.') | list
              ) | selectattr('state', 'eq', 'on') | list | length  > 0)
    }}
  sun_rising: >
    {% if (states.sun.sun.state == "above_horizon") %}
        {{ states.sun.sun.last_changed }}
    {%- else -%}
        {{ states.sun.sun.attributes.next_rising }}
    {%- endif %}
  sun_dusk: >
    {% if (states.sun.sun.state == "above_horizon") %}
        {{ states.sun.sun.attributes.next_dusk }}
    {%- else -%}
        {{ states.sun.sun.last_changed }}
    {%- endif %}
  wheater_sensor: !input wheater_entity
  no_sunny_wheater: >
    {{ states(wheater_sensor) != 'sunny' and use_weather }}
condition:
  - condition: and
    conditions:
        - condition: template
          value_template: "{{ not force_skip }}"
        - condition: or
          conditions:
              - condition: template
                value_template: !input no_sunset_handling
              - condition: template
                value_template: "{{ no_sunny_wheater }}"
              - condition: and
                conditions:
                  -  "{{ as_timestamp(now()) >= ((as_timestamp(sun_dusk) - dusk_start_hour*3600 - dusk_start_minute*60) )}}"
                  -  "{{ as_timestamp(now()) < ((as_timestamp(sun_rising) + rising_start_hour*3600 + rising_start_minute*60) )}}"
action:
  - service: light.turn_on
    target: !input light_target
  - wait_for_trigger:
      platform: state
      entity_id: !input motion_entity
      from: "on"
      to: "off"
    timeout:
      hours: 0
      minutes: !input timeout
      seconds: 0
      milliseconds: 0
  - delay: !input no_motion_wait
  - service: light.turn_off
    target: !input light_target
5 Likes

Looks good, but in my experience someone or several someones will ask to not trigger for different and random reasons. My suggestion is to add a user entered conditional. I put them in many of my blueprints and it should provide users the ability to skip days or change the hours or have an override if they are interacting with something else or the infinite number of things users can think of.

You can lift the code from one of by blueprints linked below if that’s something you think is beneficial…

Thanks for contributing to the community!

2 Likes

@bladerunner70 Gianni,

This is good, but I find that the CCTV motion detection sees that change caused by the light being turned off, as being enough to say that motion has been detected.
This then causes the light to turn off, then immediately turn back on… i.e. an endless loop of the light going on, off, on etc.

Is there any chance you could add a pause/delay so that after turning off, it won’t trigger again within x seconds? Or alternatively maybe a condition that the light hasn’t just been turned off in the last x seconds?

Thanks.

@bladerunner70 thank you for the blueprint.
One bug i see is that the weather entity used in ‘no_sunny_wheater’ variable is not the same as ‘wheater_entity’.
So unless someone has pirateweather as their weather, that part will not work.
Thank you.

Thank you for signaling issue. I’ve found also another issue and committed in repo but forgot to signal here and to change the url of the blueprint.
I’ll try to fix also your problem ASAP

I’ve fixed the issue. Thanks for signaling.

Excuse me for the delay. I’m not sure to understand the problem. Seems to me that you motion sensor have a very short duration time. Is it right? usually, motion sensors change state when a motion is found and then keep that state since motion finishes. But based on your description, seems to me that in your case the motion sensor detect movement and turn on, but turns off imediatly… am I right?

Hi. i am using your blueprints now, for the weather, what does it mean? if i toggle on, then it will ignore the hours before/after if the weather is not sunny or?

Gianni, thanks for the blueprint! I see many additional variables that could influence whether motion should trigger a light, like various weather forecast APIs, indoor/outdoor light levels, cloud cover percentage, sun elevation, or presence status (to avoid the cat turning on the lights). While it’s possible to keep adding all these factors to the blueprint, my suggestion is to keep it simple: allow users to define a binary input. If it’s ‘on,’ motion triggers the light; if it’s ‘off,’ it doesn’t. This way, we can manage the logic for when the lights should turn on or stay off. Thanks!

No, it’s the opposite, if you turn it on it will consider the hour before/after if weather is sunny. The idea is that if you have a room well illuminated during day and you haven’t a light sensor, you can use weather forecast to decide if automation have to run.

ahhhh that makes a lot of sense :slight_smile:

Hi

I tried the Home assistant blueprint and now this one.

both do not give the option to choose my motion sensors (Sonoff-snzb-03)

what am i doing wrong ?
\Thomas

@bladerunner70, Firstly, this is an amazing blueprint. I found several others but this works best for me. I am using it in 3 rooms; Entrance, Garage, and my Utility room.

For the motion sensor that triggers the lights on I am using my alarm system (Paradox).

However there is one small annoyance that i noticed that could be fixed with a simple condition.

Here is my use case:

Garage Light off - Walk in - Light on (i have it set for 60 seconds) - if no motion then light off after 60 seconds.

However, If i turn on the garage light before I enter - light on - but after 60 seconds no motion its off.

Could you put a condition that checks the light entity state making sure its off before running the automation? This way if the light is on, it will stay on until the user turns it off.

Maybe adding this to the top of the code?

condition:
  - condition: state
    entity_id: !input light_target
    state: "off"
  - condition: or
    conditions:
      - condition: template
        value_template: !input no_sunset_handling 
      - condition: template
        value_template: "{{ no_sunny_wheater }}"
      - condition: and
        conditions:
          - "{{ as_timestamp(now()) >= ((as_timestamp(sun_dusk) - dusk_start_hour*3600 - dusk_start_minute*60) )}}"
          - "{{ as_timestamp(now()) < ((as_timestamp(sun_rising) + rising_start_hour*3600 + rising_start_minute*60) )}}"

Thanks, very helpful! :+1:

Hi Thomas, I saw no reply, so perhaps your question has not been answered already. I had the same problem.
I copied the entity id:
grafik
and pasted it in the blueprint input field.

I understand your suggestion. Your idea is to avoid turning off the light if it’s already on, or probably to avoid running the automation if the light is already on. I think it’s a good point, even though it seemed like a strange use case to me because, in my scenarios, it’s impossible to turn on the light without triggering the motion sensor. Moreover, I see a significant drawback in implementing this behavior, related to the fact that, at the moment, the blueprint can control not just a single light but an entire room or multiple lights. In this situation, evaluating the condition ‘if the light is on’ is not straightforward, so I need to think about how to handle this properly.
One possibility is to check the state of all lights and decide that if at least one is turned on, I can skip execution. Alternatively, and perhaps better, I could make this behavior optional by linking it to a flag and restricting it to cases where a single light is targeted.
I’ll try to find the best solution to the problem and than I’ll modify the blueprint. I have also to take care of backward compatibility so please be a bit patient :slight_smile:

I’m happy you find this blueprint useful.
Thank you

1 Like

Gotcha! In my use case, the lights (although physically multiple are a single entity). I do see now in the blueprint that you can have multiple entities (and they don’t have to be lights either). So i get your point.

I like your ideas and both options especially the one about checking the states although that might be harder to do. It could be an optional switch so people can choose to have this feature or not.

Thanks for taking the time and no rush! Will be happy to test!

Hi @wgumaa I’m happy to tell you that I’ve added requested behavior to the blueprint.
To activate it, you have simply to choose “Do not execute if the light is already on” option and the blueprint will check if one of the target lights is turned on and, in this situation, the automation will be skipped.
It took me some time because the general task to check selected target lights it’s a bit complex in general.
I hope this can help you!
Regards

1 Like

Thanks @bladerunner70! I just test and works well!! Thanks!!!

@bladerunner70 Hi, I tested again this morning and it did not work this time. I had the light on and again after 60 seconds (my time) the light went off.

The trace does show off but the light went off.