Turn Off Script

I want to share my script for turning switches (in general entities) on and off.
The idea is to add the possibility in Lovelace to toggle states after a certain amount of time.

alias: Turn off timer
variables:
  nextState: >-
    {% if is_state(entity_id, 'on') %}turn_off{% else %}turn_on{%
    endif                                                                                                                                                                         
    %}
sequence:
  - data:
      name: Turn off timer
      message: >-
        Triggered by '{{entity_id}}', action '{{action}}', minutes
        '{{minutes}}', hours '{{hours}}'. Calculated '{{nextState}}'
      domain: timer
      entity_id: script.turn_off_timer
    action: logbook.log
  - delay:
      hours: "{% if hours %}{{ hours }}{% else %}0{% endif %}"
      minutes: "{% if minutes %}{{ minutes }}{% else %}10{% endif %}"
      seconds: 0
      milliseconds: 0
  - data: {}
    target:
      entity_id: "{{entity_id}}"
    action: >-
      homeassistant.{% if action %}{{ action }}{% else %}{{ nextState }}{% endif
      %}
mode: parallel
icon: mdi:timer-10
max: 10

This script can be called as a service and the input parameters are as follows:

  • entity_id (required): The id of the entity to be changed
  • action (optional): The target state of the entity (turn_off, turn_on)
  • hours (optional): Time delay in hours. If none is provided, then 0
  • minutes(optional): Time delay in minutes. If none is provided, then 10

I use it on lovelace buttons as a “hold option” like this:

type: custom:mushroom-entity-card
entity: switch.wz_nintendo
hold_action:
  action: perform-action
  perform_action: script.turn_off_timer
  target: {}
  data:
    entity_id: switch.wz_nintendo
tap_action:
  action: toggle

This would toggle the Nintendo after 10 minutes, as no time attributes where given.

The script runs in parallel and can be stopped using a simple Entities Card.
All script runs will appear on the list.

type: entities
entities:
  - entity: script.turn_off_timer

2025-02-03 12_05_57-Oscar – Home Assistant

For debugging purposes, the script also writes a log entry, showing the input data and the expected new entity state.

1 Like