Condition or Wait on attribute

Hi,

So I’m going round in circles over this, wondering if any experts can set me right here please…

I have an air purifier, I want an automation that turns it off when the air_quality attribute has been excellent for 30 minutes, even if it was excellent when it was turned on.

What I’ve got doesn’t work, and I know why, but I just can’t figure what the right way is.

This below doesn’t work because I guess the wait_for_trigger is never triggered if air_quality is already excellent when the action happens.

Any suggestions?

- id: fan_auto_off
  alias: Fan Off On Clean Air
  trigger:
  - platform: state
    entity_id: fan.levoit_131_air_purifier
    to: "on"
  action:
    - wait_for_trigger:
        - platform: state
          entity_id: fan.levoit_131_air_purifier
          attribute: air_quality
          to: "excellent"
          for: "00:30:00" 
      timeout:
        minutes: "04:00:00"
    - service: logbook.log
      data_template:
        name: Turning off air purifier
        message: Air quality has been excellent for 30 minutes
    - service: homeassistant.turn_off
      entity_id: fan.levoit_131_air_purifier

Thank you

Had a brainwave when I woke up this morning, after extensive messing around and testing, this works as it should:

- id: fan_auto_off
  alias: Fan Off On Clean Air
  trigger:
  - platform: state
    entity_id: fan.levoit_131_air_purifier
    to: "on"
  action:
    - wait_for_trigger:
        - platform: template
          value_template: "{{ is_state_attr('fan.levoit_131_air_purifier', 'air_quality', 'excellent')}}"
          for: "00:30:00"
      timeout: "04:00:00"
    - service: logbook.log
      data_template:
        name: Turning off air purifier
        message: Air quality has been excellent for 30 minutes
    - service: homeassistant.turn_off
      entity_id: fan.levoit_131_air_purifier