ha-automation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Home 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:
  1. Incorrect trigger syntax - Using deprecated formats or invalid entity IDs
  2. Missing condition operators - Forgetting
    and
    /
    or
    /
    not
    conjunctions
  3. Jinja2 template errors - Undefined variables or incorrect filter usage
  4. Blueprint parameterization issues - Missing
    !input
    substitutions or misaligned selectors
本技能可避免常见的自动化错误,包括:
  1. 触发器语法错误 - 使用已弃用的格式或无效的实体ID
  2. 缺少条件运算符 - 忘记使用
    and
    /
    or
    /
    not
    连接符
  3. Jinja2模板错误 - 未定义变量或过滤器使用不当
  4. 蓝图参数化问题 - 缺少
    !input
    替换或选择器不匹配

Quick Reference: Automation Structure

快速参考:自动化结构

Basic Automation Format

基础自动化格式

yaml
automation: !include automations.yaml
yaml
automation: !include automations.yaml

Single Automation File

单个自动化文件

yaml
- alias: "My Automation"
  description: "What this automation does"
  trigger: ...
  condition: ...
  action: ...
  mode: single
yaml
- alias: "我的自动化"
  description: "该自动化的作用"
  trigger: ...
  condition: ...
  action: ...
  mode: single

Triggers Quick Reference

触发器快速参考

State Trigger

状态触发器

yaml
trigger:
  platform: state
  entity_id: light.bedroom
  from: "off"
  to: "on"
  for:
    minutes: 5
yaml
trigger:
  platform: state
  entity_id: light.bedroom
  from: "off"
  to: "on"
  for:
    minutes: 5

Numeric State Trigger

数值状态触发器

yaml
trigger:
  platform: numeric_state
  entity_id: sensor.temperature
  above: 25
  below: 30
yaml
trigger:
  platform: numeric_state
  entity_id: sensor.temperature
  above: 25
  below: 30

Time 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: 0
yaml
trigger:
  platform: time_pattern
  hours: "*/2"  # 每2小时
  minutes: 0

Device Trigger

设备触发器

yaml
trigger:
  platform: device
  device_id: abc123...
  domain: light
  type: turned_on
yaml
trigger:
  platform: device
  device_id: abc123...
  domain: light
  type: turned_on

Event Trigger

事件触发器

yaml
trigger:
  platform: event
  event_type: call_service
  event_data:
    domain: light
yaml
trigger:
  platform: event
  event_type: call_service
  event_data:
    domain: light

MQTT 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_id
yaml
trigger:
  platform: webhook
  webhook_id: my_webhook_id

Sun Trigger

太阳状态触发器

yaml
trigger:
  platform: sun
  event: sunrise
  offset: "-00:30:00"  # 30 min before sunrise
yaml
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: enter
yaml
trigger:
  platform: zone
  entity_id: device_tracker.john
  zone: zone.home
  event: enter

Template 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: 25
yaml
condition:
  - condition: numeric_state
    entity_id: sensor.temperature
    above: 20
    below: 25

Time Condition

时间条件

yaml
condition:
  - condition: time
    after: "08:00:00"
    before: "20:00:00"
    weekday:
      - mon
      - tue
      - wed
yaml
condition:
  - condition: time
    after: "08:00:00"
    before: "20:00:00"
    weekday:
      - mon
      - tue
      - wed

Sun Condition

太阳状态条件

yaml
condition:
  - condition: sun
    after: sunrise
    before: sunset
yaml
condition:
  - condition: sun
    after: sunrise
    before: sunset

Template 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: 20
yaml
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: 20
yaml
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: 366
yaml
action:
  - service: light.turn_on
    target:
      entity_id: light.bedroom
    data:
      brightness: 255
      color_temp: 366

Call Service (Multiple Targets)

调用服务(多目标)

yaml
action:
  - service: light.turn_on
    target:
      entity_id:
        - light.bedroom
        - light.living_room
      area_id: downstairs
yaml
action:
  - service: light.turn_on
    target:
      entity_id:
        - light.bedroom
        - light.living_room
      area_id: downstairs

Choose (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: 1
yaml
action:
  - repeat:
      count: 3
      sequence:
        - service: light.toggle
          target:
            entity_id: light.bedroom
        - delay:
            seconds: 1

Delay

延迟

yaml
action:
  - delay:
      minutes: 5
yaml
action:
  - delay:
      minutes: 5

Wait 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.bedroom
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.bedroom

Parallel Actions

并行动作

yaml
action:
  - parallel:
      - service: light.turn_off
        target:
          entity_id: light.bedroom
      - service: switch.turn_off
        target:
          entity_id: switch.fan
yaml
action:
  - parallel:
      - service: light.turn_off
        target:
          entity_id: light.bedroom
      - service: switch.turn_off
        target:
          entity_id: switch.fan

Automation 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 runs
yaml
mode: single  # 默认 - 取消之前的运行
mode: restart  # 重新触发时重启
mode: queued  # 最多排队10个重新触发的运行
mode: parallel  # 允许同时运行多个实例
mode: queued  # with max: 10  # 限制排队运行数量

Jinja2 Template Cheatsheet

Jinja2 模板速查表

Common Variables

常用变量

  • states('entity.id')
    - Get entity state
  • state_attr('entity.id', 'attribute')
    - Get entity attribute
  • now()
    - Current datetime
  • as_timestamp('2024-01-01')
    - Convert to timestamp
  • trigger
    - Trigger object (if in trigger template)
  • 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 list
jinja2
{{ 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 default
jinja2
{{ "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_level
yaml
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_level

Blueprint Selectors

蓝图选择器

yaml
undefined
yaml
undefined

Entity 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"
undefined
selector: select: options: - label: "选项1" value: "value1" - label: "选项2" value: "value2"
undefined

Common Mistakes to Avoid

需避免的常见错误

❌ Don't: Use old trigger format

❌ 错误示例:使用旧版触发器格式

yaml
trigger:
  - platform: state
    entity_id: light.bedroom
yaml
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 check
yaml
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: 255
yaml
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: 255
yaml
action:
  - service: light.turn_on
    target:
      entity_id: light.bedroom
    data:
      brightness: 255

Best Practices

最佳实践

  1. Use descriptive alias names - Make automation purposes clear
  2. Add descriptions - Explain why the automation exists
  3. Test with Developer Tools - Verify templates before deployment
  4. Use choose for complex logic - More readable than multiple automations
  5. Organize by room or function - Use
    !include
    to split large files
  6. Set appropriate mode - Choose single/restart/queued based on use case
  7. Add for: condition - Prevent false triggers from brief state changes
  8. Use templates for flexibility - Enable parameter passing in blueprints
  1. 使用描述性别名 - 明确自动化的用途
  2. 添加描述 - 说明自动化存在的原因
  3. 用开发者工具测试 - 部署前验证模板
  4. 用choose处理复杂逻辑 - 比多个自动化更易读
  5. 按房间或功能组织 - 使用
    !include
    拆分大文件
  6. 设置合适的模式 - 根据使用场景选择single/restart/queued
  7. 添加for:条件 - 避免短暂状态变化导致的误触发
  8. 用模板提升灵活性 - 在蓝图中启用参数传递

Troubleshooting

故障排查

Template Shows "Error"

模板显示“Error”

  • Check template in Developer Tools > Template
  • Verify entity IDs exist:
    homeassistant.entity_ids
  • Use
    | default("value")
    filter for optional attributes
  • 在开发者工具>模板中检查模板
  • 验证实体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
    !input variable_name
    syntax (YAML 1.2 tag)
  • Check selector type matches input type
  • Ensure blueprint is in correct folder:
    config/blueprints/automation/
  • 验证
    !input variable_name
    语法(YAML 1.2标签)
  • 检查选择器类型与输入类型是否匹配
  • 确保蓝图位于正确文件夹:
    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)
  • 嵌套引号时需转义

Official Resources

官方资源