脚本语法


脚本是家庭助理将执行的一系列操作。脚本可作为独立的实体可用脚本组件但也可以嵌入 自动化 Alexa / Amazon Echo配置。

When the script is executed within an automation the trigger variable is available. See 可用触发数据.

脚本语法基本结构是包含操作的键/值映射列表。如果脚本仅包含1个操作,则可以省略包装列表。

All actions support an optional alias.

# Example script integration containing script syntax
script:
  example_script:
    sequence:
      # This is written using the Script Syntax
      - alias: "Turn on ceiling light"
        service: light.turn_on
        target:
          entity_id: light.ceiling
      - alias: "Notify that ceiling light is turned on"
        service: notify.notify
        data:
          message: "Turned on the ceiling light!"

致电服务

最重要的是致电服务的行动。这可以以各种方式完成。对于所有不同的可能性,看看服务呼叫页面.

- alias: "Bedroom lights on"
  service: light.turn_on
  target:
    entity_id: group.bedroom
  data:
    brightness: 100

激活一个场景

脚本 may also use a shortcut syntax for activating scenes instead of calling the scene.turn_on service.

- scene: scene.morning_living_room

变量

变量操作允许您设置/覆盖将在其操作之后通过模板访问的变量。也可以看看脚本变量如何定义在整个脚本中可访问的变量。

- alias: "Set variables"
  variables:
    entities: 
      - light.kitchen
      - light.living_room
    brightness: 100
- alias: "Control lights"
  service: light.turn_on
  target:
    entity_id: "{{ entities }}"
  data:
    brightness: "{{ brightness }}"

测试一个条件

While executing a script you can add a condition to stop further execution. When a condition does not return true, the script will stop executing. There are many different conditions which are documented at the 条件页面.

# If paulus is home, continue to execute the script below these lines
- alias: "Check if Paulus is home"
  condition: state
  entity_id: device_tracker.paulus
  state: "home"

延迟

延迟对于临时暂停脚本并在以后的时刻启动它是有用的。我们支持延迟的不同语法,如下所示。

# Seconds
# Waits 5 seconds
- alias: " 等待  5s"
  delay: 5
# HH:MM
# Waits 1 hour
- delay: "01:00"
# HH:MM:SS
# Waits 1.5 minutes
- delay: "00:01:30"
# Supports milliseconds, seconds, minutes, hours, days
# Can be used in combination, at least one required
# Waits 1 minute
- delay:
    minutes: 1

所有表单都接受模板。

# Waits however many minutes input_number.minute_delay is set to
- delay: "{{ states('input_number.minute_delay') | multiply(60) | int }}"

等待

这些操作允许脚本等待系统中的实体以模板指定的特定状态,或者某些事件以由一个或多个触发器表示的事件发生。

等待模板

此操作评估模板,如果为true,则脚本将继续。如果没有,那么它将等到它是真的。

The template is re-evaluated whenever an entity ID that it references changes state. If you use non-deterministic functions like now() in the template it will not be continuously re-evaluated, but only when an entity ID that is referenced is changed. If you need to periodically re-evaluate the template, reference a sensor from the 时间和日期将细本或每日更新的组件。


# Wait until media player is stopped
- alias: " 等待  until media player is stopped"
  wait_template: "{{ is_state('media_player.floor', 'stop') }}"

等待触发器

This action can use the same triggers that are available in an automation’s trigger section. See 自动化触发器。只要任何触发器都触发,脚本将继续。所有先前定义的trigger_variables., 变量 脚本变量传递给扳机。

# Wait for a custom event or light to turn on and stay on for 10 sec
- alias: " 等待  for MY_EVENT or light on"
  wait_for_trigger:
    - platform: event
      event_type: MY_EVENT
    - platform: state
      entity_id: light.LIGHT
      to: "on"
      for: 10

等待超时

With both types of waits it is possible to set a timeout after which the script will continue its execution if the condition/event is not satisfied. Timeout has the same syntax as delay, and like delay, also accepts templates.

# Wait for sensor to change to 'on' up to 1 minute before continuing to execute.
- wait_template: "{{ is_state('binary_sensor.entrance', 'on') }}"
  timeout: "00:01:00"

You can also get the script to abort after the timeout by using optional continue_on_timeout: false.


# Wait for IFTTT event or abort after specified timeout.
- wait_for_trigger:
    - platform: event
      event_type: ifttt_webhook_received
      event_data:
        action: connected_to_network
  timeout:
    minutes: "{{ timeout_minutes }}"
  continue_on_timeout: false

Without continue_on_timeout: false the script will always continue since the default for continue_on_timeout is true.

等待变量

After each time a wait completes, either because the condition was met, the event happened, or the timeout expired, the variable wait will be created/updated to indicate the result.

多变的 描述
wait.completed Exists only after wait_template. true if the condition was met, false otherwise
wait.trigger Exists only after wait_for_trigger. Contains information about which trigger fired. (See 可用触发数据.) Will be none if no trigger happened before timeout expired
wait.remaining Timeout remaining, or none if a timeout was not specified

这可以用于根据是否满足条件,或者在实现单个超时总体上依次满足的情况,或者使用多个等待的不同动作。

# Take different actions depending on if condition was met.
- wait_template: "{{ is_state('binary_sensor.door', 'on') }}"
  timeout: 10
- choose:
    - conditions: "{{ not wait.completed }}"
      sequence:
        - service: script.door_did_not_open
  default:
    - service: script.turn_on
      target:
        entity_id:
          - script.door_did_open
          - script.play_fanfare

# Wait a total of 10 seconds.
- wait_template: "{{ is_state('binary_sensor.door_1', 'on') }}"
  timeout: 10
  continue_on_timeout: false
- service: switch.turn_on
  target:
    entity_id: switch.some_light
- wait_for_trigger:
    - platform: state
      entity_id: binary_sensor.door_2
      to: "on"
      for: 2
  timeout: "{{ wait.remaining }}"
  continue_on_timeout: false
- service: switch.turn_off
  target:
    entity_id: switch.some_light

火灾

此操作允许您发射活动。事件可用于许多事情。它可以触发自动化或指示发生的另一个集成。例如,在下面的示例中,它用于在日志中创建条目。

- alias: "Fire LOGBOOK_ENTRY event"
  event: LOGBOOK_ENTRY
  event_data:
    name: Paulus
    message: is waking up
    entity_id: device_tracker.paulus
    domain: light

您还可以使用Event_Data以自定义数据启动事件。这可以用来将数据传递给等待另一个脚本 an event trigger.

The event_data accepts templates.

- event: MY_EVENT
  event_data:
    name: myEvent
    customData: "{{ myCustomVariable }}"

提升和消耗自定义事件

The following automation example shows how to raise a custom event called event_light_state_changed with entity_id as the event data. The action part could be inside a script or an automation.

- alias: "Fire Event"
  trigger:
    - platform: state
      entity_id: switch.kitchen
      to: "on"
  action:
    - event: event_light_state_changed
      event_data:
        state: "on"

The following automation example shows how to capture the custom event event_light_state_changed with an 事件自动化触发器, and retrieve corresponding entity_id that was passed as the event trigger data, see 可用触发数据更多细节。

- alias: "Capture Event"
  trigger:
    - platform: event
      event_type: event_light_state_changed
  action:
    - service: notify.notify
      data:
        message: "kitchen light is turned {{ trigger.event.data.state }}"

重复一组行动

此操作允许您重复一系列其他操作。嵌套完全支持。 有三种方法可以控制序列运行多少次。

计算重复

此表格接受计数值。该值可以由模板指定,在这种情况下 达到重复步骤时呈现模板。

script:
  flash_light:
    mode: restart
    sequence:
      - service: light.turn_on
        target:
          entity_id: "light.{{ light }}"
      - alias: "Cycle light 'count' times"
        repeat:
          count: "{{ count|int * 2 - 1 }}"
          sequence:
            - delay: 2
            - service: light.toggle
              target:
                entity_id: "light.{{ light }}"
  flash_hallway_light:
    sequence:
      - alias: "Flash hallway light 3 times"
        service: script.flash_light
        data:
          light: hallway
          count: 3

循环时

此表格接受条件列表(见条件页面用于评估的可用选项每次序列 是跑步。序列将运行 只要 条件评估为true。

script:
  do_something:
    sequence:
      - service: script.get_ready_for_something
      - alias: "Repeat the sequence AS LONG AS the conditions are true"
        repeat:
          while:
            - condition: state
              entity_id: input_boolean.do_something
              state: "on"
            # Don't do it too many times
            - condition: template
              value_template: "{{ repeat.index <= 20 }}"
          sequence:
            - service: script.something

The while也接受A.模板条件的速记表示. For example:

- while: "{{ is_state('sensor.mode', 'Home') and repeat.index < 10 }}"
  sequence:
    - ...

重复直到

此表格接受评估的条件列表每次序列 是跑步。因此,序列总是至少运行一次。序列将运行 直到 条件评估为true。

automation:
  - trigger:
      - platform: state
        entity_id: binary_sensor.xyz
        to: "on"
    condition:
      - condition: state
        entity_id: binary_sensor.something
        state: "off"
    mode: single
    action:
      - alias: "Repeat the sequence UNTIL the conditions are true"
        repeat:
          sequence:
            # Run command that for some reason doesn't always work
            - service: shell_command.turn_something_on
            # Give it time to complete
            - delay:
                milliseconds: 200
          until:
            # Did it work?
            - condition: state
              entity_id: binary_sensor.something
              state: "on"

直到 也接受A.模板条件的速记表示. For example:

- until: "{{ is_state('device_tracker.iphone', 'home') }}"
  sequence:
    - ...

重复循环变量

A variable named repeat is defined within the repeat action (i.e., it is available inside sequence, while & 直到 .) 它包含以下字段:

场地 描述
first 在重复序列的第一次迭代期间为真
index 循环的迭代号:1,2,3,...
last 在重复序列的最后一次迭代期间,这仅适用于计数循环

选择一组行动

此操作允许您从序列列表中选择其他操作的序列。 嵌套完全支持。

每个序列都与条件列表配对。 (见条件页面有关可用选项以及如何处理多个条件。)运行条件的第一个序列将运行。 An 可选的 default sequence can be included which will be run only if none of the sequences from the list are run.

一个 可选的 alias can be added to each of the sequences, excluding the default sequence.

The choose action can be used like an “if” statement. The first conditions/sequence pair is like the “if/then”, and can be used just by itself. Or additional pairs can be added, each of which is like an “elif/then”. And lastly, a default can be added, which would be like the “else.”

# Example with just an "if"
automation:
  - trigger:
      - platform: state
        entity_id: binary_sensor.motion
        to: "on"
    action:
      - choose:
          - alias: "IF nobody home, sound the alarm!"
            conditions:
              - condition: state
                entity_id: group.family
                state: not_home
            sequence:
              - service: script.siren
                data:
                  duration: 60
      - service: light.turn_on
        target:
          entity_id: all
# Example with "if" 和 "else"
automation:
  - trigger:
      - platform: state
        entity_id: binary_sensor.motion
    mode: queued
    action:
      - alias: "Turn on front lights if motion detected, else turn off"
        choose:
          # IF motion detected
          - alias: "Motion detected"
            conditions: "{{ trigger.to_state.state == 'on' }}"
            sequence:
              - service: script.turn_on
                target:
                  entity_id:
                    - script.slowly_turn_on_front_lights
                    - script.announce_someone_at_door
        # ELSE (i.e., motion stopped)
        default:
          - service: light.turn_off
            target:
              entity_id: light.front_lights
# Example with "if", "elif" 和 "else"
automation:
  - trigger:
      - platform: state
        entity_id: input_boolean.simulate
        to: "on"
    mode: restart
    action:
      - choose:
          # IF morning
          - conditions:
              - condition: template
                value_template: "{{ now().hour < 9 }}"
            sequence:
              - service: script.sim_morning
          # ELIF day
          - conditions:
              - condition: template
                value_template: "{{ now().hour < 18 }}"
            sequence:
              - service: light.turn_off
                target:
                  entity_id: light.living_room
              - service: script.sim_day
        # ELSE night
        default:
          - service: light.turn_off
            target:
              entity_id: light.kitchen
          - delay:
              minutes: "{{ range(1, 11)|random }}"
          - service: light.turn_off
            target:
              entity_id: all

conditions也接受A.模板条件的速记表示. For example:

automation:
  - trigger:
      - platform: state
        entity_id: input_select.home_mode
    action:
      - choose:
          - conditions: >
              {{ trigger.to_state.state == 'Home' and
                 is_state('binary_sensor.all_clear', 'on') }}
            sequence:
              - service: script.arrive_home
                data:
                  ok: true
          - conditions: >
              {{ trigger.to_state.state == 'Home' and
                 is_state('binary_sensor.all_clear', 'off') }}
            sequence:
              - service: script.turn_on
                target:
                  entity_id: script.flash_lights
              - service: script.arrive_home
                data:
                  ok: false
          - conditions: "{{ trigger.to_state.state == 'Away' }}"
            sequence:
              - service: script.left_home

More choose can be used together. This is the case of an IF-IF.

以下示例显示了单个自动化如何控制与彼此无关但具有共同触发器的实体。

When the sun goes below the horizon, the porchgarden lights must turn on. If someone is watching the TV in the living room, there is a high chance that someone is in that room, therefore the living room lights have to turn on too. The same concept applies to the studio room.

# Example with "if" 和 "if"
automation:
  - alias: "Turn lights on when the sun gets dim and if some room is occupied"
      trigger:
        - platform: numeric_state
          entity_id: sun.sun
          attribute: elevation
          below: 4
      action:
        # This must always apply
        - service: light.turn_on
          data:
            brightness: 255
            color_temp: 366
          target:
            entity_id:
              - light.porch
              - light.garden
        # IF a entity is ON
        - choose:
            - conditions:
                - condition: state
                  entity_id: binary_sensor.livingroom_tv
                  state: "on"
              sequence:
                - service: light.turn_on
                  data:
                    brightness: 255
                    color_temp: 366
                  target:
                    entity_id: light.livingroom
         # IF another entity not related to the previous, is ON
        - choose:
            - conditions:
                - condition: state
                  entity_id: binary_sensor.studio_pc
                  state: "on"
              sequence:
                - service: light.turn_on
                  data:
                    brightness: 255
                    color_temp: 366
                  target:
                    entity_id: light.studio