Shutdown button press that makes shure heating cycle is not active on espresso machine

I have a espresso machine (pluged in to a Shelly enegry metering WiFi relay) that goes into a heating cycle every 4 to 5 minutes for 30 seconds. With automated time base shutdown I can make sure that the macine is using under 5 W of power. For that I use the following automation:

alias: turn of coffee machine at 18:00 if power is under 5W and try again in 2 minutes 
description: 
trigger:
  - platform: time
    at: "18:00:00"
  - platform: time
    at: "18:02:00"
condition:
  - condition: device
    type: is_on
    device_id: 790e2fcad3177fa66b897xxx
    entity_id: 43fa57a2d840aa67290bbxxx
    domain: switch
  - type: is_power
    condition: device
    device_id: 790e2fcad3177fa66b897xxx
    entity_id: 61ab9d154a9050e501edxxx
    domain: sensor
    below: 5
action:
  - type: turn_off
    device_id: 790e2fcad3177fa66b897xxx
    entity_id: 43fa57a2d840aa67290bbxxx
    domain: switch
mode: single

When I manually switch the machine off (by pressing a button on frontend) I would like to:

  1. make sure power consuption is below 5 W
  2. If not, wait for power consuption to be under 5 W
  3. Turn power off

I have tried a bunch of automations with out luck. What do you suggest I should do? Use a helper or template? What type…?

Thanks!

To answer my own question. I made a script that I call when I press the button.

alias: turn off espesso machine safely
sequence:
  - if:
      - type: is_power
        condition: device
        device_id: 790e2fcad3177fa66b89718c1fxxxxxx
        entity_id: 61ab9d154a9050e501ed482a73xxxxxx
        domain: sensor
        below: 5
    then:
      - type: turn_off
        device_id: 790e2fcad3177fa66b89718c1fxxxxxx
        entity_id: 43fa57a2d840aa67290bb55f17xxxxxx
        domain: switch
    else:
      - delay:
          hours: 0
          minutes: 1
          seconds: 0
          milliseconds: 0
      - if:
          - type: is_power
            condition: device
            device_id: 790e2fcad3177fa66b89718c1fxxxxxx
            entity_id: 61ab9d154a9050e501ed482a73xxxxxx
            domain: sensor
            below: 5
        then:
          - type: turn_off
            device_id: 790e2fcad3177fa66b89718c1xxxxxx
            entity_id: 43fa57a2d840aa67290bb55f1xxxxxx
            domain: switch
        else:
          - service: notify.notify
            data:
              message: Can't turn of the machine
mode: restart

I am sure that it could be more optimal. And I will make it a toggle-version since now I can only turn the power of.