Turn off lights only when turned on by specific automstio

I have an automation "Late Nigh“ which turns on a light to 25% with motion at night.

I run this automation to turn it off.

The issue is, if I manually turn the light on via Lovelace, this automation turns it off with this automation.

How do I only fire this only when the light was turned on by my “Late Night” automation?

alias: Family Late Night Off
description: ''
trigger:
  - platform: state
    entity_id: group.motion
    to: 'off'
condition: []
action:
  - type: turn_off
    device_id: 590beba5ec0e512480b9434b741a1ee9
    entity_id: light.family_room_right
    domain: light
mode: single

When someone controls an entity via the Lovelace UI, Home Assistant knows who they are because they had to login with a user account. That means their actions are known and identified by a property called user_id. In contrast, an automation doesn’t identify itself with user_id so its value is none. It’s this difference that be used to determine if a trigger was caused by a person or an automation.

For example, the following condition checks if the State Trigger was caused by an automation (because it’s checking if user_id is none).

condition:
  - condition: template
    value_template: '{{ trigger.to_state.context.user_id == none }}'

The challenge of applying this technique to your situation is that your automation’s trigger is monitoring a motion sensor which is never turned on/off by a person via the Lovelace UI so the user_id will always be none.

I have an idea for how to achieve your goal but first I need to test it before I propose you try it.

Create input_boolean.family_room_manual and then try this automation:

alias: Family Late Night Off
description: ''
trigger:
- id: 'motion'
  platform: state
  entity_id: group.motion
  to: 'off'
  for: '00:00:05'
- id: 'light'
  platform: state
  entity_id: light.family_room_right
condition: []
action:
- choose:
  - conditions:
    - "{{ trigger.id == 'motion' }}"
    - "{{ is_state('input_boolean.family_room_manual', 'off') }}"
    - "{{ is_state('light.family_room_right', 'on') }}"
    sequence:
    - service: light.turn_off
      target:
        entity_id: light.family_room_right
  - conditions:
    - "{{ trigger.id == 'light' }}"
    - "{{ trigger.to_state.context.user_id != none }}"
    sequence:
    - service: "input_boolean.turn_{{ trigger.to_state.state }}"
      target:
        entity_id: input_boolean.family_room_manual
mode: queued

How it works

The input_boolean serves to indicate if the light was turned on/off by user via the UI.

  • When you turn on the light via the UI, it will enable the input_boolean. The motion sensor will be prohibited from turning off the light.
  • When you turn off the light via the UI, it will disable the input_boolean. The motion sensor will be permitted to turn off the light.
3 Likes