On door open, turn on, then off a set of lights filtered in template

Here’s what I’m attempting to do: When I open a door, I want to look at the state of three lights, if any of them are off, I want to turn them on, then off 5 min later (leaving any of the three on that were on to begin with).

What I have works to select only the lights that were off, but I’m not sure how to ‘remember’ which set of lights I turned on so that I only turn those off.

Here’s what I have so far:

- alias: Dog Potty Lights
  trigger:
    - platform: state
      entity_id: binary_sensor.back_door
      from: 'off'
      to: 'on'
  condition:
    condition: or  # 'when dark' condition: either after sunset or before sunrise
    conditions:
      - condition: sun
        after: sunset
      - condition: sun
        before: sunrise
  action:
    - service: switch.turn_on
      data_template:
        entity_id: >
          {% set my_list = [states.switch.garage_outside_light, 
                            states.switch.back_door_light, 
                            states.switch.patio_lights] 
          | rejectattr('state','equalto','on')
          | map(attribute='entity_id' ) 
          | join(', ') %}
          {{my_list}}      
    - delay: 0:05:00
    - service: switch.turn_off
      data_template: 
        entity_id: {{ my_list }}

That last line is the part that doest work because my_list is no longer defined.

I’m relatively new to HA, so any help would be appreciated!

Use input_booleans?

I figured out a way using scripts. First, my automation looks like this:

- alias: Dog Potty Lights
  trigger:
    - platform: state
      entity_id: binary_sensor.back_door
      from: 'off'
      to: 'on'
  condition:
    condition: or  # 'when dark' condition: either after sunset or before sunrise
    conditions:
      - condition: sun
        after: sunset
      - condition: sun
        before: sunrise
  action:
      service: script.timed_lights
      data_template:
        delay: '00:05:00'
        # pass a list of lights, rulling out the ones that are already on
        lights: >
          {{ [states.switch.garage_outside_light, 
                            states.switch.back_door_light, 
                            states.switch.patio_lights] 
          | rejectattr('state','equalto','on')
          | map(attribute='entity_id' ) 
          | join(', ') }}

This makes a list and puts it in the variable lights and it puts a desired delay time in delay, which are passed to my script timed_lights which looks like so:

timed_lights:
  sequence:
    - service: switch.turn_on
      data_template:
        entity_id: "{{lights}}"
    - delay: "{{delay}}"
    - service: switch.turn_off
      data_template:
        entity_id: "{{lights}}"
2 Likes