Howto add a timer?

Hi,
What am i doing wrong with my timer setup? Only thing i want to do when i press fan on it has a 30min timer. when i click again it starts it from beginning if not it stops after 30 minutes.

Code under which is done with ui

alias: Fläkt 30min
description: ""
trigger:
  - platform: state
    entity_id:
      - switch.takflakt
    from: "off"
    to: "on"
condition: []
action:
  - service: timer.start
    data: {}
    target:
      entity_id: timer.flakt
  - delay: ""
  - type: turn_off
    device_id: e9b5883591e4f7fa305c551121622228
    entity_id: switch.takflakt
    domain: switch
mode: single

I assume it’s turning off straight away?

You’ll need 2 automations, not one:

alias: Fläkt 30min
description: ""
trigger:
  - platform: state
    entity_id:
      - switch.takflakt
    from: "off"
    to: "on"
condition: []
action:
  - service: timer.start
    data: {}
    target:
      entity_id: timer.flakt
mode: single
alias: "Timerstop"
id: "Timerstop"
trigger:
  - platform: event
    event_type: timer.finished
    event_data:
      entity_id: timer.flakt
action:
  - type: turn_off
    device_id: e9b5883591e4f7fa305c551121622228
    entity_id: switch.takflakt
    domain: switch

Apologies if I got the indents wrong.

Many thanks for fast answer!

As long as it’s the right answer :slight_smile:

If you are interested, here’s how to consolidate the two automations:

alias: Fläkt 30min
description: ""
trigger:
  - platform: state
    entity_id: switch.takflakt
    from: 'off'
    to: 'on'
  - platform: event
    event_type: timer.finished
    event_data:
      entity_id: timer.flakt
condition: []
action:
  - if: "{{ trigger platform == 'state' }}"
    then:
      - service: timer.start
        target:
          entity_id: timer.flakt
    else:
      - service: switch.turn_off
        target:
          entity_id: switch.takflakt
mode: single

Alternately, you can use the State Trigger’s for option to achieve the same result without using a timer entity. However, the disadvantage is that the for option cannot survive a restart (it gets reset) whereas a timer can (if you specify restore: true when configuring the timer).

alias: Fläkt 30min
description: ""
trigger:
  - platform: state
    entity_id: switch.takflakt
    from: 'off'
    to: 'on'
    for:
      minutes: 30
condition: []
action:
  - service: switch.turn_off
    target:
      entity_id: switch.takflakt
mode: single