自动化动作执行——服务调用与流程编排
动作的本质
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
三个关键字段:
service:服务名(domain.action格式,如light.turn_on、notify.mobile_app_me)target:目标实体 / 区域 / 设备(可以用 entity_id、area_id、device_id、floor_id)data:服务的参数(不同服务有不同参数,在 Developer Tools → Services 可以查)
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
延时支持以下格式:
seconds: 10minutes: 5hours: 1time: "22:00:00"(等到某个时间)
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') }}
动作失败处理
动作执行失败(服务不存在、实体不可用、参数错误…)时:
- 自动化不会整体中断——继续执行后面的动作
- 失败信息在 Traces 里可以看到(Settings → Automations & scenes → 该自动化 → Traces)
- 如果你想让某个动作失败时中断后续,可以在动作前加
continue_on_error: false:
action:
- service: lock.lock
target:
entity_id: lock.front_door
continue_on_error: false
- service: notify.mobile_app_me
data:
message: 门已锁好