home-assistant
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHome Assistant
Home Assistant
Overview
概述
This skill helps users integrate Home Assistant into their projects, whether to control smart home devices or to ingest sensor data and state information. The skill guides users through connection setup, validates credentials, and provides comprehensive API reference documentation for both Python and Node.js.
本技能可帮助用户将Home Assistant集成到自己的项目中,无论是用于控制智能家居设备,还是采集传感器数据和状态信息。该技能会引导用户完成连接设置、验证凭据,并提供Python和Node.js的全面API参考文档。
When to Use This Skill
何时使用本技能
Use this skill when users want to:
- Connect their application to Home Assistant
- Control smart home devices (lights, switches, thermostats, etc.)
- Read sensor data or entity states from Home Assistant
- Automate home control based on custom logic
- Build dashboards or monitoring tools using Home Assistant data
- Integrate Home Assistant into existing Python or Node.js projects
当用户有以下需求时,可使用本技能:
- 将应用程序连接到Home Assistant
- 控制智能家居设备(灯光、开关、恒温器等)
- 从Home Assistant读取传感器数据或实体状态
- 根据自定义逻辑实现家庭控制自动化
- 利用Home Assistant数据构建仪表板或监控工具
- 将Home Assistant集成到现有的Python或Node.js项目中
Connection Setup Workflow
连接设置流程
Step 1: Collect Connection Information
步骤1:收集连接信息
Collect two pieces of information from the user:
- Home Assistant URL: The web address where Home Assistant is accessible
- Long-Lived Access Token: Authentication token for API access
向用户收集两项信息:
- Home Assistant URL:可访问Home Assistant的网址
- Long-Lived Access Token:用于API访问的身份验证令牌
Step 2: Normalize the URL
步骤2:标准化URL
If the user provides a URL with a path component (e.g., ), normalize it by removing everything after the host and port. The base URL should only include the scheme, host, and port:
http://homeassistant.local:8123/lovelace/dashboard- ✓ Correct:
http://homeassistant.local:8123 - ✗ Incorrect:
http://homeassistant.local:8123/lovelace/dashboard
如果用户提供的URL包含路径部分(例如 ),请通过移除主机和端口之后的所有内容来标准化URL。基础URL应仅包含协议、主机和端口:
http://homeassistant.local:8123/lovelace/dashboard- ✓ 正确格式:
http://homeassistant.local:8123 - ✗ 错误格式:
http://homeassistant.local:8123/lovelace/dashboard
Step 3: Help Users Find Their Token
步骤3:帮助用户查找令牌
If users don't know where to find their Long-Lived Access Token, provide these instructions:
- Log into Home Assistant web interface
- Click on the user profile (bottom left, user icon or name)
- Click on the "Security" tab
- Scroll down to the "Long-Lived Access Tokens" section
- Click "Create Token"
- Give the token a name (e.g., "My Project")
- Copy the generated token (it will only be shown once)
如果用户不知道如何获取Long-Lived Access Token,请提供以下说明:
- 登录Home Assistant网页界面
- 点击用户资料(左下角,用户图标或名称)
- 点击“安全”选项卡
- 向下滚动到“Long-Lived Access Tokens”区域
- 点击“Create Token”
- 为令牌命名(例如“My Project”)
- 复制生成的令牌(仅会显示一次)
Step 4: Validate the Connection
步骤4:验证连接
Use curl to test the connection and retrieve Home Assistant configuration information.
bash
curl -X GET \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
<URL>/api/configExample:
bash
curl -X GET \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "Content-Type: application/json" \
http://homeassistant.local:8123/api/configSuccess output:
json
{
"location_name": "Home",
"latitude": 37.7749,
"longitude": -122.4194,
"elevation": 0,
"unit_system": {
"length": "km",
"mass": "g",
"temperature": "°C",
"volume": "L"
},
"time_zone": "America/Los_Angeles",
"version": "2024.1.0",
"config_dir": "/config",
"allowlist_external_dirs": [],
"allowlist_external_urls": [],
"components": ["automation", "light", "switch", ...],
"config_source": "storage"
}Key information from the response:
- : Home Assistant version (e.g., "2024.1.0")
version - : Name of the Home Assistant instance
location_name - : Configured time zone
time_zone - : List of loaded components/integrations
components
Failure scenarios:
Authentication failure (401):
json
{"message": "Invalid authentication"}Connection failure:
curl: (7) Failed to connect to homeassistant.local port 8123: Connection refusedIf authentication fails, verify:
- The Long-Lived Access Token is correct
- The token hasn't been deleted or expired
- The URL is correct (including http/https and port)
使用curl测试连接并获取Home Assistant配置信息。
bash
curl -X GET \
-H "Authorization: Bearer <TOKEN>" \
-H "Content-Type: application/json" \
<URL>/api/config示例:
bash
curl -X GET \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "Content-Type: application/json" \
http://homeassistant.local:8123/api/config成功输出:
json
{
"location_name": "Home",
"latitude": 37.7749,
"longitude": -122.4194,
"elevation": 0,
"unit_system": {
"length": "km",
"mass": "g",
"temperature": "°C",
"volume": "L"
},
"time_zone": "America/Los_Angeles",
"version": "2024.1.0",
"config_dir": "/config",
"allowlist_external_dirs": [],
"allowlist_external_urls": [],
"components": ["automation", "light", "switch", ...],
"config_source": "storage"
}响应中的关键信息:
- : Home Assistant版本(例如"2024.1.0")
version - : Home Assistant实例的名称
location_name - : 配置的时区
time_zone - : 已加载的组件/集成列表
components
失败场景:
身份验证失败(401):
json
{"message": "Invalid authentication"}连接失败:
curl: (7) Failed to connect to homeassistant.local port 8123: Connection refused如果身份验证失败,请检查:
- Long-Lived Access Token是否正确
- 令牌是否未被删除或过期
- URL是否正确(包括http/https和端口)
Step 5: Proceed with Implementation
步骤5:进行实现开发
Once the connection is validated, help the user implement their integration based on their programming language and requirements.
连接验证通过后,根据用户使用的编程语言和需求,帮助他们完成集成开发。
Core Interaction Patterns
核心交互模式
IMPORTANT: The following WebSocket API commands form the core of how users should interact with Home Assistant. These leverage the automation engine and keep scripts minimal by using native Home Assistant syntax.
重要提示:以下WebSocket API命令是用户与Home Assistant交互的核心方式。这些命令利用自动化引擎,通过使用Home Assistant原生语法将脚本保持在最简形式。
Automation Engine Commands (WebSocket API)
自动化引擎命令(WebSocket API)
These commands require WebSocket API connection and provide the most powerful and flexible way to interact with Home Assistant:
这些命令需要WebSocket API连接,是与Home Assistant交互的最强大、最灵活的方式:
1. subscribe_trigger - Listen for Specific Events
1. subscribe_trigger - 监听特定事件
Use this when: You want to be notified when specific conditions occur (state changes, time patterns, webhooks, etc.)
Command structure:
json
{
"type": "subscribe_trigger",
"trigger": {
"platform": "state",
"entity_id": "binary_sensor.motion_sensor",
"to": "on"
},
"variables": {
"custom_var": "value"
}
}Why use this: Instead of subscribing to all state changes and filtering, subscribe directly to the triggers you care about. This is more efficient and uses Home Assistant's native trigger syntax.
适用场景:当你希望在特定条件发生时收到通知(状态变化、时间模式、Webhook等)
命令结构:
json
{
"type": "subscribe_trigger",
"trigger": {
"platform": "state",
"entity_id": "binary_sensor.motion_sensor",
"to": "on"
},
"variables": {
"custom_var": "value"
}
}使用优势:无需订阅所有状态变化再进行过滤,直接订阅你关注的触发器。这种方式更高效,且使用Home Assistant原生的触发器语法。
2. test_condition - Test Conditions Server-Side
2. test_condition - 服务器端条件测试
Use this when: You need to check if a condition is met without implementing the logic in your script
Command structure:
json
{
"type": "test_condition",
"condition": {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"above": 20
},
"variables": {
"custom_var": "value"
}
}Why use this: Offload condition logic to Home Assistant. Your script stays simple while using Home Assistant's powerful condition engine.
适用场景:当你需要检查某个条件是否满足,但不想在脚本中实现该逻辑时
命令结构:
json
{
"type": "test_condition",
"condition": {
"condition": "numeric_state",
"entity_id": "sensor.temperature",
"above": 20
},
"variables": {
"custom_var": "value"
}
}使用优势:将条件逻辑委托给Home Assistant处理。你的脚本可以保持简洁,同时利用Home Assistant强大的条件引擎。
3. execute_script - Execute Multiple Actions
3. execute_script - 执行多个动作
Use this when: You need to execute a sequence of actions, including , delays, service calls, and more
wait_for_triggerCommand structure:
json
{
"type": "execute_script",
"sequence": [
{
"service": "light.turn_on",
"target": {"entity_id": "light.living_room"}
},
{
"wait_for_trigger": [
{
"platform": "state",
"entity_id": "binary_sensor.motion",
"to": "off",
"for": {"minutes": 5}
}
]
},
{
"service": "light.turn_off",
"target": {"entity_id": "light.living_room"}
}
],
"variables": {
"custom_var": "value"
}
}Why use this:
- Execute complex automation logic using native Home Assistant syntax
- Use to wait for events
wait_for_trigger - Chain multiple actions together
- Keep your script minimal - all logic is in HA syntax
- Getting response data: To get response from service calls, store the result in a response variable and set it as the script result
Example with response data:
json
{
"type": "execute_script",
"sequence": [
{
"service": "weather.get_forecasts",
"target": {"entity_id": "weather.home"},
"response_variable": "weather_data"
},
{
"stop": "Done",
"response_variable": "weather_data"
}
]
}适用场景:当你需要执行一系列动作,包括、延迟、服务调用等时
wait_for_trigger命令结构:
json
{
"type": "execute_script",
"sequence": [
{
"service": "light.turn_on",
"target": {"entity_id": "light.living_room"}
},
{
"wait_for_trigger": [
{
"platform": "state",
"entity_id": "binary_sensor.motion",
"to": "off",
"for": {"minutes": 5}
}
]
},
{
"service": "light.turn_off",
"target": {"entity_id": "light.living_room"}
}
],
"variables": {
"custom_var": "value"
}
}使用优势:
- 使用Home Assistant原生语法执行复杂的自动化逻辑
- 使用等待事件
wait_for_trigger - 将多个动作串联执行
- 保持脚本最简 - 所有逻辑都使用HA语法
- 获取响应数据:要获取服务调用的响应,将结果存储到响应变量中并设置为脚本结果
带响应数据的示例:
json
{
"type": "execute_script",
"sequence": [
{
"service": "weather.get_forecasts",
"target": {"entity_id": "weather.home"},
"response_variable": "weather_data"
},
{
"stop": "Done",
"response_variable": "weather_data"
}
]
}Essential Registry Information
重要注册表信息
To understand Home Assistant's information architecture, also use:
- config/entity_registry/list: Learn about entities and their unique IDs
- config/device_registry/list: Learn about devices and their entities
- config/area_registry/list: Understand how spaces are organized
- config/floor_registry/list: Multi-floor layout information
要了解Home Assistant的信息架构,还可以使用:
- config/entity_registry/list:了解实体及其唯一ID
- config/device_registry/list:了解设备及其关联的实体
- config/area_registry/list:了解空间的组织方式
- config/floor_registry/list:多层布局信息
Current state of the home
家庭当前状态
If the user is building an application that wants to represent the current state of the home, use:
- subscribe_entities: Get real-time updates on all entity states (Home Assistant JS WebSocket has built-in support for this)
如果用户正在构建一个需要展示家庭当前状态的应用,请使用:
- subscribe_entities:获取所有实体状态的实时更新(Home Assistant JS WebSocket内置对此的支持)
Implementation Guidance
实现指导
Python Projects
Python项目
For Python-based projects, refer to the Python API reference:
- File:
references/python_api.md - Usage: Load this reference when implementing Python integrations
- Contains:
- Example code: Python scripts demonstrating common use cases.
- Key operations: Automation engine commands, getting states, calling services, subscribing to events, error handling
对于基于Python的项目,请参考Python API参考文档:
- 文件:
references/python_api.md - 用途:在实现Python集成时加载此参考文档
- 包含内容:
- 示例代码:展示常见用例的Python脚本
- 核心操作:自动化引擎命令、获取状态、调用服务、订阅事件、错误处理
Node.js Projects
Node.js项目
For Node.js-based projects, refer to the Node.js API reference:
- File:
references/node_api.md - Usage: Load this reference when implementing Node.js integrations
- Contains:
- WebSocket API examples using library
home-assistant-js-websocket
- WebSocket API examples using
对于基于Node.js的项目,请参考Node.js API参考文档:
- 文件:
references/node_api.md - 用途:在实现Node.js集成时加载此参考文档
- 包含内容:
- 使用库的WebSocket API示例
home-assistant-js-websocket
- 使用
Best Practices
最佳实践
- Error Handling: Always implement proper error handling for network failures and authentication issues
- Connection Testing: Validate connections before proceeding with implementation
- Real-time Updates: For monitoring scenarios, use WebSocket APIs instead of polling REST endpoints
- 错误处理:始终为网络故障和身份验证问题实现完善的错误处理机制
- 连接测试:在进行实现开发前先验证连接
- 实时更新:对于监控场景,使用WebSocket API而非轮询REST端点
Testing with empty-hass
使用empty-hass进行测试
If users want to test their code without connecting to a real Home Assistant instance, they can use empty-hass, a CLI tool that starts an empty Home Assistant instance with pre-configured authentication.
如果用户希望在不连接真实Home Assistant实例的情况下测试代码,可以使用empty-hass,这是一个CLI工具,可启动一个带有预配置身份验证的空Home Assistant实例。
Quick Start
快速开始
Run empty-hass using uvx (requires Python with uv installed):
bash
uvx --from git+https://github.com/balloob/empty-hass empty-hassThis will start a Home Assistant instance on with:
http://localhost:8123- A pre-onboarded configuration (skips the setup wizard)
- A temporary configuration directory (cleaned up on exit)
Run with to see available options and login credentials:
--helpbash
uvx --from git+https://github.com/balloob/empty-hass empty-hass --helpThis is useful for:
- Testing API integration code before connecting to a production instance
- Development and debugging without affecting real devices
- CI/CD pipelines that need a Home Assistant instance for testing
使用uvx运行empty-hass(需要安装了uv的Python环境):
bash
uvx --from git+https://github.com/balloob/empty-hass empty-hass这将在启动一个Home Assistant实例,包含:
http://localhost:8123- 预配置的初始化设置(跳过设置向导)
- 临时配置目录(退出时会自动清理)
运行查看可用选项和登录凭据:
--helpbash
uvx --from git+https://github.com/balloob/empty-hass empty-hass --help这适用于:
- 在连接生产实例前测试API集成代码
- 进行开发和调试,而不影响真实设备
- 需要Home Assistant实例进行测试的CI/CD流水线
Common Integration Patterns
常见集成模式
Data Dashboard
数据仪表板
Read sensor states and display them in a custom dashboard or monitoring application.
读取传感器状态并在自定义仪表板或监控应用中展示。
Automation Logic
自动化逻辑
Subscribe to entity state changes and trigger custom actions based on conditions.
订阅实体状态变化,并根据条件触发自定义动作。
External Triggers
外部触发器
Call Home Assistant services from external events (webhooks, scheduled jobs, user actions).
从外部事件(Webhook、定时任务、用户操作)调用Home Assistant服务。
Data Export
数据导出
Retrieve historical data from Home Assistant for analysis or backup purposes.
从Home Assistant检索历史数据用于分析或备份。