Home Assistant 中文文档 下载 App

自动化动作执行——服务调用与流程编排

动作的本质

Home Assistant 自动化的动作就是调用一系列的服务(Services)。服务是 Home Assistant 里"做事"的基本单位——开个灯是一个服务,发个通知是一个服务,重启 Home Assistant 也是一个服务。

最常用的几类动作

Call Service(调用服务)

最核心的动作——调用任意 Home Assistant 服务:

action:
  - service: light.turn_on
    target:
      entity_id: light.living_room
    data:
      brightness_pct: 80
      color_name: warmwhite

三个关键字段:

Run Script(运行脚本)

把一长串动作序列保存成 Script 实体,之后在自动化里引用:

action:
  - service: script.arrive_home_mode

Script 在 Settings → Automations & scenes → Scripts 里创建。适合把"回家模式"、"电影模式"这种组合动作复用。

Delay(延时)

action:
  - service: light.turn_on
    target:
      entity_id: light.kitchen
  - delay:
      seconds: 30
  - service: light.turn_off
    target:
      entity_id: light.kitchen

延时支持以下格式:

Wait(等待条件满足)

Delay 是等固定时间,Wait 是等某个条件满足:

action:
  - service: light.turn_on
    target:
      entity_id: light.living_room
  - wait_for:
      trigger:
        - platform: state
          entity_id: binary_sensor.motion_living_room
          to: "off"
          for:
            minutes: 2
  - service: light.turn_off
    target:
      entity_id: light.living_room

动作序列(Sequence)

一个自动化可以有多个动作,按顺序执行(上一个完成再执行下一个):

action:
  - service: media_player.turn_on
    target:
      entity_id: media_player.sonos_living
  - service: media_player.volume_set
    target:
      entity_id: media_player.sonos_living
    data:
      volume_level: 0.3
  - service: media_player.play_media
    target:
      entity_id: media_player.sonos_living
    data:
      media_content_id: "spotify:playlist:xxx"
      media_content_type: playlist

常用服务清单速查

灯 / 开关

服务用途
light.turn_on / light.turn_off开灯关灯
light.toggle切换
switch.turn_on / switch.turn_off开关控制
cover.open / cover.close / cover.stop窗帘/车库门

气候 / 空调

服务用途
climate.set_temperature设温度
climate.set_hvac_mode设模式(heat/cool/auto/off)
climate.set_preset_mode设预设(home/away/sleep)
fan.turn_on / fan.turn_off风扇

通知

服务用途
notify.mobile_app_me推送到手机
notify.persistent_notification浏览器通知
tts.xxx_say语音朗读

系统

服务用途
homeassistant.restart重启 Home Assistant
homeassistant.check_config检查配置
homeassistant.reload_core_config重新加载 YAML 配置
automation.turn_on / automation.turn_off启用/禁用其他自动化
script.turn_on / script.turn_off启用/禁用脚本

特殊

服务用途
camera.snapshot拍照保存
vacuum.start / vacuum.return_to_base扫地机器人
lock.lock / lock.unlock门锁

用 Template 在动作里动态传值

动作的 data 里可以用 Jinja2 模板插入动态值:

action:
  - service: notify.mobile_app_me
    data:
      title: "车库门提醒"
      message: >
        车库门已开 {{ now().strftime('%H:%M') }}
        状态:{{ states('binary_sensor.garage_door') }}

动作失败处理

动作执行失败(服务不存在、实体不可用、参数错误…)时:

action:
  - service: lock.lock
    target:
      entity_id: lock.front_door
    continue_on_error: false
  - service: notify.mobile_app_me
    data:
      message: 门已锁好