Handling the pre-existing state of a light in automations

I have an automation which detects a child who has woken up and briefly pops on the stairs lighting for them to find their way in the dark. It works well. What doesn’t work so well is if the fact the automation takes no heed of whether or not the lighting was already on before it kicked in:

    action:
      - service: light.turn_on
        entity_id:  light.attic_stairs
      - service: light.turn_on
        entity_id: light.landings_lighting        
      - wait_template: "{{ is_state('group.PIRs', 'off') }}"
      - service: light.turn_off
        entity_id: light.attic_stairs
      - service: light.turn_off
        entity_id: light.landings_lighting

is there any efficient way I could modify this so that it only turns the lights on/off if a) they need turning on and b) they were off before the automation ran?
If it was just ONE set of lights being controlled, I would control it with a condition check in the actions but that won’t work here

thanks!

Can you elaborate further on how you want it to work?

Is it like this?

  • Only turn on the lights that are currently off. If one light is already on, turn on the other one. If both lights are already on, do nothing.
  • Only turn off the lights that were initially off. Leave on any lights that were initially on.

If what I have described is how you want it to work, try this:

  action:
    - variables:
        lights: >
          {{ expand('light.attic_stairs', 'light.landings_lighting')
             | selectattr('state', 'eq', 'off')
             | map(attribute='entity_id') | list }}
    - condition: template
      value_template: '{{ lights | count > 0 }}'
    - service: light.turn_on
      data:
        entity_id:  '{{ lights }}'     
    - wait_template: "{{ is_state('group.pirs', 'off') }}"
    - service: light.turn_off
      data:
        entity_id: '{{ lights }}'

The automation that will use this action should have its mode set to single (that’s the default).

1 Like

Super cool. Thanks! Will give it a try!!