Fan trigger from light switch

I have a light switch in a bathroom I would like to trigger a fan with an overrun. Both of these have the normal on off events (lutron caseta)
Rules would be:
Light on → fan turn on
Light off → wait 2 minutes then turn fan off (unless light has been turned on again in the meantime)

Turn first bit is easy, not sure how to do the second bit.
Is this one automation or two?

This can be one automation, either using a choose condition based on the light state, or using two triggers with trigger id’s (one for turn on event, one for turn off).

For the case of it turning off, you can add a wait_for_trigger action, that waits for the light to turn on again with a 2 minute timeout. If the trigger was met (meaning wait.completed evaluates to true) simply do nothing, and otherwise turn off the fan. You can more or less follow the syntax as set out here: Script Syntax - Home Assistant

EDIT: Magnus’ answer is much simpler and works just as well actually.

Super simple.

triggers:
- trigger: state
  entity_id: light.your_bathroom_light
  to: "on"
- trigger: state
  entity_id: light.your_bathroom_light
  to: "off"
  for:
    minutes: 2
actions:
- action: "fan.turn_{{ trigger.to_state.state }}"
  target:
    entity_id: fan.your_bathroom_fan

Completely untested, may have typos, caveat emptor. :stuck_out_tongue:

Hi,
this will turn off the fan even though the light may be switched on again within the two minutes, or am I wrong?

Nope. If the light’s state switches from off to something different (could be on, but also unavailable or unknown) within the two minute “timer”, the trigger will never fire until it again turns off and stays that way for two consecutive minutes.

Superb! I modified this appropriately and it seems to work well!