ha-automation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHome Assistant Automation Expert
Home Assistant 自动化专家
Master Home Assistant automations, scripts, blueprints, and Jinja2 templating with confidence.
自信掌握Home Assistant自动化、脚本、蓝图以及Jinja2模板技术。
Before You Start
开始前须知
This skill prevents common automation mistakes including:
- Incorrect trigger syntax - Using deprecated formats or invalid entity IDs
- Missing condition operators - Forgetting /
and/orconjunctionsnot - Jinja2 template errors - Undefined variables or incorrect filter usage
- Blueprint parameterization issues - Missing substitutions or misaligned selectors
!input
本技能可避免常见的自动化错误,包括:
- 触发器语法错误 - 使用已弃用的格式或无效的实体ID
- 缺少条件运算符 - 忘记使用/
and/or连接符not - Jinja2模板错误 - 未定义变量或过滤器使用不当
- 蓝图参数化问题 - 缺少替换或选择器不匹配
!input
Quick Reference: Automation Structure
快速参考:自动化结构
Basic Automation Format
基础自动化格式
yaml
automation: !include automations.yamlyaml
automation: !include automations.yamlSingle Automation File
单个自动化文件
yaml
- alias: "My Automation"
description: "What this automation does"
trigger: ...
condition: ...
action: ...
mode: singleyaml
- alias: "我的自动化"
description: "该自动化的作用"
trigger: ...
condition: ...
action: ...
mode: singleTriggers Quick Reference
触发器快速参考
State Trigger
状态触发器
yaml
trigger:
platform: state
entity_id: light.bedroom
from: "off"
to: "on"
for:
minutes: 5yaml
trigger:
platform: state
entity_id: light.bedroom
from: "off"
to: "on"
for:
minutes: 5Numeric State Trigger
数值状态触发器
yaml
trigger:
platform: numeric_state
entity_id: sensor.temperature
above: 25
below: 30yaml
trigger:
platform: numeric_state
entity_id: sensor.temperature
above: 25
below: 30Time Trigger
时间触发器
yaml
trigger:
platform: time
at: "10:30:00"yaml
trigger:
platform: time
at: "10:30:00"Time Pattern Trigger
时间模式触发器
yaml
trigger:
platform: time_pattern
hours: "*/2" # Every 2 hours
minutes: 0yaml
trigger:
platform: time_pattern
hours: "*/2" # 每2小时
minutes: 0Device Trigger
设备触发器
yaml
trigger:
platform: device
device_id: abc123...
domain: light
type: turned_onyaml
trigger:
platform: device
device_id: abc123...
domain: light
type: turned_onEvent Trigger
事件触发器
yaml
trigger:
platform: event
event_type: call_service
event_data:
domain: lightyaml
trigger:
platform: event
event_type: call_service
event_data:
domain: lightMQTT Trigger
MQTT触发器
yaml
trigger:
platform: mqtt
topic: home/front_door/status
payload: "opened"yaml
trigger:
platform: mqtt
topic: home/front_door/status
payload: "opened"Webhook Trigger
Webhook触发器
yaml
trigger:
platform: webhook
webhook_id: my_webhook_idyaml
trigger:
platform: webhook
webhook_id: my_webhook_idSun Trigger
太阳状态触发器
yaml
trigger:
platform: sun
event: sunrise
offset: "-00:30:00" # 30 min before sunriseyaml
trigger:
platform: sun
event: sunrise
offset: "-00:30:00" # 日出前30分钟Zone Trigger
区域触发器
yaml
trigger:
platform: zone
entity_id: device_tracker.john
zone: zone.home
event: enteryaml
trigger:
platform: zone
entity_id: device_tracker.john
zone: zone.home
event: enterTemplate Trigger
模板触发器
yaml
trigger:
platform: template
value_template: "{{ state_attr('light.bedroom', 'brightness') > 200 }}"yaml
trigger:
platform: template
value_template: "{{ state_attr('light.bedroom', 'brightness') > 200 }}"Conditions Quick Reference
条件快速参考
State Condition
状态条件
yaml
condition:
- condition: state
entity_id: light.bedroom
state: "on"yaml
condition:
- condition: state
entity_id: light.bedroom
state: "on"Numeric State Condition
数值状态条件
yaml
condition:
- condition: numeric_state
entity_id: sensor.temperature
above: 20
below: 25yaml
condition:
- condition: numeric_state
entity_id: sensor.temperature
above: 20
below: 25Time Condition
时间条件
yaml
condition:
- condition: time
after: "08:00:00"
before: "20:00:00"
weekday:
- mon
- tue
- wedyaml
condition:
- condition: time
after: "08:00:00"
before: "20:00:00"
weekday:
- mon
- tue
- wedSun Condition
太阳状态条件
yaml
condition:
- condition: sun
after: sunrise
before: sunsetyaml
condition:
- condition: sun
after: sunrise
before: sunsetTemplate Condition
模板条件
yaml
condition:
- condition: template
value_template: "{{ states('light.bedroom') == 'on' }}"yaml
condition:
- condition: template
value_template: "{{ states('light.bedroom') == 'on' }}"Combining Conditions
组合条件
yaml
condition:
- condition: and
conditions:
- condition: state
entity_id: light.bedroom
state: "on"
- condition: numeric_state
entity_id: sensor.temperature
above: 20yaml
condition:
- condition: or
conditions:
- condition: state
entity_id: binary_sensor.motion
state: "on"
- condition: state
entity_id: light.bedroom
state: "on"yaml
condition:
- condition: and
conditions:
- condition: state
entity_id: light.bedroom
state: "on"
- condition: numeric_state
entity_id: sensor.temperature
above: 20yaml
condition:
- condition: or
conditions:
- condition: state
entity_id: binary_sensor.motion
state: "on"
- condition: state
entity_id: light.bedroom
state: "on"Actions Quick Reference
动作快速参考
Call Service Action
调用服务动作
yaml
action:
- service: light.turn_on
target:
entity_id: light.bedroom
data:
brightness: 255
color_temp: 366yaml
action:
- service: light.turn_on
target:
entity_id: light.bedroom
data:
brightness: 255
color_temp: 366Call Service (Multiple Targets)
调用服务(多目标)
yaml
action:
- service: light.turn_on
target:
entity_id:
- light.bedroom
- light.living_room
area_id: downstairsyaml
action:
- service: light.turn_on
target:
entity_id:
- light.bedroom
- light.living_room
area_id: downstairsChoose (If/Then/Else)
选择(If/Then/Else)
yaml
action:
- choose:
- conditions:
- condition: state
entity_id: light.bedroom
state: "on"
sequence:
- service: light.turn_off
target:
entity_id: light.bedroom
- conditions:
- condition: state
entity_id: light.bedroom
state: "off"
sequence:
- service: light.turn_on
target:
entity_id: light.bedroom
default:
- service: notification.send
data:
message: "Unable to determine light state"yaml
action:
- choose:
- conditions:
- condition: state
entity_id: light.bedroom
state: "on"
sequence:
- service: light.turn_off
target:
entity_id: light.bedroom
- conditions:
- condition: state
entity_id: light.bedroom
state: "off"
sequence:
- service: light.turn_on
target:
entity_id: light.bedroom
default:
- service: notification.send
data:
message: "无法确定灯光状态"Repeat (Loop)
重复(循环)
yaml
action:
- repeat:
count: 3
sequence:
- service: light.toggle
target:
entity_id: light.bedroom
- delay:
seconds: 1yaml
action:
- repeat:
count: 3
sequence:
- service: light.toggle
target:
entity_id: light.bedroom
- delay:
seconds: 1Delay
延迟
yaml
action:
- delay:
minutes: 5yaml
action:
- delay:
minutes: 5Wait for Trigger
等待触发器
yaml
action:
- wait_for_trigger:
platform: state
entity_id: binary_sensor.motion
to: "off"
timeout:
minutes: 30
- service: light.turn_off
target:
entity_id: light.bedroomyaml
action:
- wait_for_trigger:
platform: state
entity_id: binary_sensor.motion
to: "off"
timeout:
minutes: 30
- service: light.turn_off
target:
entity_id: light.bedroomParallel Actions
并行动作
yaml
action:
- parallel:
- service: light.turn_off
target:
entity_id: light.bedroom
- service: switch.turn_off
target:
entity_id: switch.fanyaml
action:
- parallel:
- service: light.turn_off
target:
entity_id: light.bedroom
- service: switch.turn_off
target:
entity_id: switch.fanAutomation Modes
自动化模式
yaml
mode: single # Default - cancel previous run
mode: restart # Restart on retrigger
mode: queued # Queue up to 10 retriggered runs
mode: parallel # Allow multiple simultaneous runs
mode: queued # with max: 10 # Limit queued runsyaml
mode: single # 默认 - 取消之前的运行
mode: restart # 重新触发时重启
mode: queued # 最多排队10个重新触发的运行
mode: parallel # 允许同时运行多个实例
mode: queued # with max: 10 # 限制排队运行数量Jinja2 Template Cheatsheet
Jinja2 模板速查表
Common Variables
常用变量
- - Get entity state
states('entity.id') - - Get entity attribute
state_attr('entity.id', 'attribute') - - Current datetime
now() - - Convert to timestamp
as_timestamp('2024-01-01') - - Trigger object (if in trigger template)
trigger
- - 获取实体状态
states('entity.id') - - 获取实体属性
state_attr('entity.id', 'attribute') - - 当前日期时间
now() - - 转换为时间戳
as_timestamp('2024-01-01') - - 触发器对象(在触发器模板中可用)
trigger
Filters
过滤器
jinja2
{{ value | float(0) }} # Convert to float with default
{{ value | int(0) }} # Convert to int with default
{{ value | round(2) }} # Round to 2 decimal places
{{ value | timestamp_custom("%Y-%m-%d") }} # Format timestamp
{{ value | replace("old", "new") }} # Replace string
{{ value | lower }} # Lowercase
{{ value | upper }} # Uppercase
{{ value | length }} # Get length
{{ list | list }} # Convert to listjinja2
{{ value | float(0) }} # 转换为浮点数,默认值为0
{{ value | int(0) }} # 转换为整数,默认值为0
{{ value | round(2) }} # 四舍五入到2位小数
{{ value | timestamp_custom("%Y-%m-%d") }} # 格式化时间戳
{{ value | replace("old", "new") }} # 替换字符串
{{ value | lower }} # 转换为小写
{{ value | upper }} # 转换为大写
{{ value | length }} # 获取长度
{{ list | list }} # 转换为列表Conditionals
条件语句
jinja2
{% if states('light.bedroom') == 'on' %}
Light is on
{% elif states('light.bedroom') == 'off' %}
Light is off
{% else %}
Unknown
{% endif %}jinja2
{% if states('light.bedroom') == 'on' %}
灯光已开启
{% elif states('light.bedroom') == 'off' %}
灯光已关闭
{% else %}
状态未知
{% endif %}Loops
循环语句
jinja2
{% for entity in states.light %}
{{ entity.name }}: {{ entity.state }}
{% endfor %}jinja2
{% for entity in states.light %}
{{ entity.name }}: {{ entity.state }}
{% endfor %}Math Operations
数学运算
jinja2
{{ 5 + 3 }} # Addition
{{ 10 - 4 }} # Subtraction
{{ 3 * 4 }} # Multiplication
{{ 20 / 4 }} # Division
{{ 17 % 5 }} # Modulo (remainder)jinja2
{{ 5 + 3 }} # 加法
{{ 10 - 4 }} # 减法
{{ 3 * 4 }} # 乘法
{{ 20 / 4 }} # 除法
{{ 17 % 5 }} # 取模(余数)String Operations
字符串操作
jinja2
{{ "hello " + "world" }} # Concatenation
{{ value is string }} # Type checking
{{ value is number }}
{{ value is defined }} # Check if variable exists
{{ value | default("fallback") }} # Provide defaultjinja2
{{ "hello " + "world" }} # 字符串拼接
{{ value is string }} # 类型检查
{{ value is number }}
{{ value is defined }} # 检查变量是否存在
{{ value | default("fallback") }} # 设置默认值Debugging Templates
模板调试
Use Developer Tools > Template in Home Assistant UI to test templates in real-time.
在Home Assistant界面的开发者工具>模板中实时测试模板。
Blueprint Creation Basics
蓝图创建基础
Blueprint Structure
蓝图结构
yaml
blueprint:
name: "Friendly Name"
description: "What this blueprint does"
domain: automation
source_url: "https://github.com/user/repo/path/to/blueprint.yaml"
input:
my_light:
name: "Light to control"
description: "The light entity to control"
selector:
entity:
domain: light
brightness_level:
name: "Brightness"
description: "Brightness percentage (0-100)"
selector:
number:
min: 0
max: 100
unit_of_measurement: "%"
duration:
name: "Duration"
description: "How long to stay on"
selector:
number:
min: 1
max: 60
unit_of_measurement: "minutes"
my_bool:
name: "Enable feature"
selector:
boolean:
trigger: ...
condition: ...
action:
- service: light.turn_on
target:
entity_id: !input my_light
data:
brightness: !input brightness_levelyaml
blueprint:
name: "友好名称"
description: "该蓝图的作用"
domain: automation
source_url: "https://github.com/user/repo/path/to/blueprint.yaml"
input:
my_light:
name: "要控制的灯光"
description: "要控制的灯光实体"
selector:
entity:
domain: light
brightness_level:
name: "亮度"
description: "亮度百分比(0-100)"
selector:
number:
min: 0
max: 100
unit_of_measurement: "%"
duration:
name: "持续时间"
description: "保持开启的时长"
selector:
number:
min: 1
max: 60
unit_of_measurement: "minutes"
my_bool:
name: "启用功能"
selector:
boolean:
trigger: ...
condition: ...
action:
- service: light.turn_on
target:
entity_id: !input my_light
data:
brightness: !input brightness_levelBlueprint Selectors
蓝图选择器
yaml
undefinedyaml
undefinedEntity selector
实体选择器
selector:
entity:
domain: light
selector:
entity:
domain: light
Device selector
设备选择器
selector:
device:
integration: zwave
manufacturer: Philips
selector:
device:
integration: zwave
manufacturer: Philips
Area selector
区域选择器
selector:
area:
selector:
area:
Number selector
数值选择器
selector:
number:
min: 0
max: 100
step: 5
unit_of_measurement: "%"
selector:
number:
min: 0
max: 100
step: 5
unit_of_measurement: "%"
Text selector
文本选择器
selector:
text:
multiline: true
selector:
text:
multiline: true
Boolean selector
布尔选择器
selector:
boolean:
selector:
boolean:
Select (dropdown)
下拉选择器
selector:
select:
options:
- label: "Option 1"
value: "value1"
- label: "Option 2"
value: "value2"
undefinedselector:
select:
options:
- label: "选项1"
value: "value1"
- label: "选项2"
value: "value2"
undefinedCommon Mistakes to Avoid
需避免的常见错误
❌ Don't: Use old trigger format
❌ 错误示例:使用旧版触发器格式
yaml
trigger:
- platform: state
entity_id: light.bedroomyaml
trigger:
- platform: state
entity_id: light.bedroom✅ Do: Use nested structure
✅ 正确示例:使用嵌套结构
yaml
trigger:
- platform: state
entity_id: light.bedroom
to: "on"yaml
trigger:
- platform: state
entity_id: light.bedroom
to: "on"❌ Don't: Mix trigger and condition logic
❌ 错误示例:混合触发器与条件逻辑
yaml
trigger:
- platform: state
entity_id: light.bedroom
to: "on"
condition:
- condition: state
entity_id: light.bedroom
to: "on" # Redundant!yaml
trigger:
- platform: state
entity_id: light.bedroom
to: "on"
condition:
- condition: state
entity_id: light.bedroom
to: "on" # 冗余!✅ Do: Use trigger for change detection, condition for state verification
✅ 正确示例:用触发器检测变化,用条件验证状态
yaml
trigger:
- platform: state
entity_id: light.bedroom
condition:
- condition: numeric_state
entity_id: sensor.temperature
above: 20 # Additional checkyaml
trigger:
- platform: state
entity_id: light.bedroom
condition:
- condition: numeric_state
entity_id: sensor.temperature
above: 20 # 额外检查❌ Don't: Forget entity_id in service calls
❌ 错误示例:服务调用中忘记实体ID
yaml
action:
- service: light.turn_on
data:
brightness: 255yaml
action:
- service: light.turn_on
data:
brightness: 255✅ Do: Specify target entity
✅ 正确示例:指定目标实体
yaml
action:
- service: light.turn_on
target:
entity_id: light.bedroom
data:
brightness: 255yaml
action:
- service: light.turn_on
target:
entity_id: light.bedroom
data:
brightness: 255Best Practices
最佳实践
- Use descriptive alias names - Make automation purposes clear
- Add descriptions - Explain why the automation exists
- Test with Developer Tools - Verify templates before deployment
- Use choose for complex logic - More readable than multiple automations
- Organize by room or function - Use to split large files
!include - Set appropriate mode - Choose single/restart/queued based on use case
- Add for: condition - Prevent false triggers from brief state changes
- Use templates for flexibility - Enable parameter passing in blueprints
- 使用描述性别名 - 明确自动化的用途
- 添加描述 - 说明自动化存在的原因
- 用开发者工具测试 - 部署前验证模板
- 用choose处理复杂逻辑 - 比多个自动化更易读
- 按房间或功能组织 - 使用拆分大文件
!include - 设置合适的模式 - 根据使用场景选择single/restart/queued
- 添加for:条件 - 避免短暂状态变化导致的误触发
- 用模板提升灵活性 - 在蓝图中启用参数传递
Troubleshooting
故障排查
Template Shows "Error"
模板显示“Error”
- Check template in Developer Tools > Template
- Verify entity IDs exist:
homeassistant.entity_ids - Use filter for optional attributes
| default("value")
- 在开发者工具>模板中检查模板
- 验证实体ID是否存在:
homeassistant.entity_ids - 对可选属性使用过滤器
| default("value")
Automation Doesn't Trigger
自动化未触发
- Verify entity IDs and state values (case-sensitive)
- Check trigger.yaml syntax with YAML validator
- Review automation logs in Settings > Developer Tools > Logs
- 验证实体ID和状态值(区分大小写)
- 用YAML验证器检查trigger.yaml语法
- 在设置>开发者工具>日志中查看自动化日志
Blueprint Input Not Working
蓝图输入无法工作
- Verify syntax (YAML 1.2 tag)
!input variable_name - Check selector type matches input type
- Ensure blueprint is in correct folder:
config/blueprints/automation/
- 验证语法(YAML 1.2标签)
!input variable_name - 检查选择器类型与输入类型是否匹配
- 确保蓝图位于正确文件夹:
config/blueprints/automation/
Jinja2 Syntax Error
Jinja2语法错误
- Check for undefined variables - use
| default() - Verify filter syntax:
value | filter_name(arg) - Don't use quotes inside quotes without escaping
- 检查未定义的变量 - 使用
| default() - 验证过滤器语法:
value | filter_name(arg) - 嵌套引号时需转义