I'm curious... why does this automation toggle on and off?

I have an automation that will turn on my mud room light when I open the door. I’m trying to be clever by combining the “on” and “off” commands into a single automation, separated by a five minute delay. This works well the first time I open the door; the light turns on and then turns back off five minutes later.

But if I open the door again during that five minutes, the light instantly turns off. If I repeatedly open/close the door, the light toggles on and off with each opening of the door.

Can someone help me understand why it does that? It seems to me that, when I open the door the second time, HA would merely restart the five minute delay timer instead of turning the light off. I know that I can (and perhaps should) just write an “on” automation and an “off” automation, but I’d really like to better understand why this doesn’t work. Thanks in advance!

  - alias: Turn on Mud Room light when door opens, then off 5 minutes later
    trigger:
      platform: state
      entity_id: sensor.MudRoomDoor
      from: 'closed'
      to: 'open'
    action:
      - service: homeassistant.turn_on
        entity_id: light.MudRoomLight
      - delay: '00:05:00'
      - service: homeassistant.turn_off
        entity_id: light.MudRoomLight

Have you tried using the service light.turn_on (and off) instead of homeassistant.turn_on (and off)? You might also try adding a condition that checks the state of the light. This would make it only trigger for the initial time you open the door and then turn off the light 5 minutes later regardless of how many times you open the door during that period.

  - alias: Turn on Mud Room light when door opens, then off 5 minutes later
    trigger:
      platform: state
      entity_id: sensor.MudRoomDoor
      from: 'closed'
      to: 'open'
    condition:
      condition: state
      entity_id: light.MudRoomLight
      state: 'off'
    action:
      - service: light.turn_on
        entity_id: light.MudRoomLight
      - delay: '00:05:00'
      - service: light.turn_off
        entity_id: light.MudRoomLight

I’ve never been able to find clear guidance regarding when to use the ‘homeassistant’ service versus, say, light. As a result I’ve always used 'homeassistant for everything because it seems to just work, but I don’t really understand proper usage.

I tried the ‘light’ service in the automation, but nothing changed.

Then I added the condition that you defined and it works a treat. Thanks! I got so wrapped around the axle wondering why the automation was behaving the way it does that I didn’t really think about other solutions.

In any event, you’re a genius! Thanks so much for your help.