Better way to achieve an automation?

I’m wondering if there is a better or more elegant way to achieve what I need.

In my bathroom I have some hue gu10s, a hue dimmer, and a hue motion sensor.

What I want is for the lights to come on as soon as someone walks in the room, hue is doing this fine. The other requirements I’m wanting Home assistant to handle.

The first requirement is that the light go off after a predefined amount of time.

The second requirement is if there is still movement the lights should stay on for longer.

The third requirement is that hitting the on button on the dimmer will override the lights automatically going off for instances when people are having a bath or shower.

So my first automation triggers when the bathroom lights come on, it starts a script which has a delay for 2 mins then turns the lights off.

The second automation triggers on a state change of the motion sensor and if the script to wait for 2 mind and turn the lights off is running it just restarts this script so it will wait another 2 full mins until turning them off.

My third automation is triggered by a button press on the hue dimmer and just cancels the script that turns the lights off after 2mins.

Am I using the best solutions for my requirements?

Cheers.

You are speaking about script, a better way to do that is to the use the new timer component.

automation:
  - alias: Turn on bathroom lights when there is movement
    trigger:
      - platform: hue_motion
    action:
      - service: timer.start
        entity_id: timer.timer_bathroom
      - service: light.turn_on
        entity_id: light.bathroom_light
  - alias: Turn off bathroom lights at end of timer
    trigger:
      - platform: event
        event_type: timer.finished
        event_data:
          entity_id: timer.timer_bathroom
    action:
      - service: light.turn_off
        data:
          entity_id: light.bathroom_light
          transition: 50
		  
timer:
  timer_bathroom:
    duration: '00:02:00'

In addition you can add a condition in the “turn off” automation that check the state of a sensor, sensor that would be toogled by the press on the buttons.
Simply canceling the timer wouldn’t work, as any movement would restart the timer.

There might still be some syntax correction to do in the script I posted, this one was adapted from one of my script and is not necessarily 100% correct.

You can see the original code here (I also use different brightness and duration depending on the time of day)

https://pastebin.com/vUqKG6Pr