Catch any fan that is running for longer than 30 minutes and turn it off

We have a problem in our fan switches for different places: they are attached to the same 3 gang light switches and they continuously get turned on by mistake. I want to have an automation that catches these and turn them off if they run for longer than X minutes.

Below is working to some extent but not entirely:

alias: Catch long fan runs
description: ""
trigger:
  - platform: state
    entity_id:
      - light.all_fans
    to: "on"
    for:
      hours: 0
      minutes: 40
      seconds: 0
condition: []
action:
  - variables:
      v_trigger_sensor_entity: |
        {{ expand(state_attr('light.all_fans','entity_id'))
          |selectattr('state','eq','on')
          |map(attribute='entity_id')
          |join(', ') }}
      v_trigger_sensor_name: |
        {{ expand(state_attr('light.all_fans','entity_id'))
          |selectattr('state','eq','on')
          |map(attribute='name')
          |join('\n') }}
  - device_id: XXX
    domain: mobile_app
    type: notify
    message: {{ v_trigger_sensor_name }} running for a long time, turning it off
    title: Long fan run
    enabled: true
  - service: light.turn_off
    data: {}
    target:
      entity_id: "{{ v_trigger_sensor_entity }}"
mode: single

I obviously created a light group light.all_fans that has all the fans in it.

The problem / improvement area is the following: because the trigger is any fan is running for longer than X, when it is triggered the automation switches all the fans off even if they were just turned on.

Can anyone think of a bit more elegant solution to turn only the fan that’s running for longer than X minutes off?

There is always the option of creating one automation per fan but obviously that’s not too elegant :slight_smile:

List all the fans as separate triggers.

1 Like

I’m also sharing the code of what @tom_l suggested, in case anyone wants to use it. It works like a charm, thanks for the help.

description: ""
trigger:
  - platform: state
    entity_id:
      - light.fan1
      - light.fan2
      - light.fan3
    to: "on"
    for:
      hours: 0
      minutes: 45
      seconds: 0
condition: []
action:
  - service: homeassistant.turn_off
    data_template:
      entity_id: "{{ trigger.to_state.entity_id }}"
  - device_id: XXX
    domain: mobile_app
    type: notify
    message: >-
      {{ state_attr(trigger.to_state.entity_id, 'friendly_name') }} running for longer than 45 mins,
      turning it off
    title: Long fan run
    enabled: true
mode: single
alias: Catch long fan runs - v2