How to track which automation turned a light on?

I have multiple automations and a physical and virtual switch which can turn my hallway lights on/off.

I need to stop them all interfering with each other, and so need to maintain some state/property “on” the light, to know what turned it on.

For example, if the motion detector turns it on, i want it to be turned off after 30s.

But, if the light is already on, and the motion detector triggers, i can either turn it on again (no-op), or choose not to because its already on - ok. But when the occupancy clears, I want to turn the light off, but only if it was the occupancy detector that turned it on in the first place.

This is just one example, there are many use cases.

What the best way to store the state? Do I need to make a helper “variable” and maintain the state in there? But then I need to make a separate helper for every device affected this way, doesnt seem elegant.

Is there a built in mechanism for this im missing?

Thanks

The use case you described here is easiest, IMO, with a timer.

Your automation might look this this:

  trigger: motion detected
  condition: light is off
  action: turn on light
  action: start timer (30 seconds)

Then in a separate automation (or the same one if you want to use trigger ids and a choose action)

  trigger: event timer.finished
  action: turn off light

Since the timer only runs if the light was off when the motion was detected, you know for sure it should be turned off when the timer finishes.

Thanks

Trigger IDs look useful, thanks.

Re timers, ok, I guess i can keep clearing any existing timer before setting up a new one…

Its still complicated but a solution at least.

I cant be the first to have this issue, feels like there should be a first class solution by now…

Thanks