home-assistant-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHome Assistant REST API Orchestration Skill
Home Assistant REST API 编排技能
This skill provides access to the Home Assistant REST API for building integrations, automating smart home devices, and managing Home Assistant instances programmatically.
本技能提供对Home Assistant REST API的访问权限,用于构建集成、自动化智能家居设备以及以程序化方式管理Home Assistant实例。
Quick Reference: When to Load Which Resource
快速参考:何时加载对应资源
| Task | Load Resource |
|---|---|
| Setting up authentication, understanding API basics, HTTP methods | |
| Querying entity states, updating states, monitoring changes | |
| Controlling lights, climate, locks, and other devices | |
| Understanding light, switch, sensor, climate entity types | |
| Server-side template queries, complex filters, aggregations | |
| System configuration, component discovery, error logs | |
| Complete code examples, client libraries, patterns | |
| 任务 | 加载资源 |
|---|---|
| 设置身份验证、了解API基础知识、HTTP方法 | |
| 查询实体状态、更新状态、监控变更 | |
| 控制灯光、温控、门锁及其他设备 | |
| 了解灯光、开关、传感器、温控等实体类型 | |
| 服务器端模板查询、复杂筛选、聚合操作 | |
| 系统配置、组件发现、错误日志 | |
| 完整代码示例、客户端库、实现模式 | |
Orchestration Protocol
编排协议
Phase 1: Task Analysis
阶段1:任务分析
Identify what the user needs to accomplish:
Authentication & Setup?
- Getting started with Home Assistant API
- Creating or managing tokens
- Configuring HTTP clients
→ Load
resources/core-concepts.md
Query or Monitor State?
- "What is the temperature in the kitchen?"
- "Is the front door locked?"
- "Get all lights that are on"
- "Monitor entity changes"
→ Load
resources/state-management.md
Control a Device?
- "Turn on the kitchen light"
- "Set thermostat to 22°C"
- "Lock the front door"
- "Play music on speaker"
→ Load (then find entity type in
resources/service-reference.md)resources/entity-types.md
Understand Entity Types?
- "What attributes does a climate entity have?"
- "What services are available for locks?"
- "How do I control a media player?"
→ Load
resources/entity-types.md
Complex Query or Data Aggregation?
- "Count all lights that are on"
- "Get devices with low battery"
- "Average temperature from all sensors"
- "Conditional logic based on time of day"
→ Load
resources/templates.md
System Management or Discovery?
- "What components are loaded?"
- "What services are available?"
- "Check configuration validity"
- "View error logs"
→ Load
resources/system-config.md
Practical Working Example?
- Code in Python, Node.js, Bash, curl
- Integration patterns
- Error handling
- Multi-entity operations
→ Load
resources/examples.md
明确用户需要完成的任务:
身份验证与设置?
- Home Assistant API入门
- 创建或管理令牌
- 配置HTTP客户端
→ Load
resources/core-concepts.md
查询或监控状态?
- "厨房的温度是多少?"
- "前门是否锁上了?"
- "获取所有处于开启状态的灯光"
- "监控实体变更"
→ Load
resources/state-management.md
控制设备?
- "打开厨房的灯"
- "将温控器设置为22°C"
- "锁上前门"
- "在扬声器上播放音乐"
→ Load (然后在
resources/service-reference.md中查找实体类型)resources/entity-types.md
了解实体类型?
- "温控实体有哪些属性?"
- "门锁有哪些可用服务?"
- "如何控制媒体播放器?"
→ Load
resources/entity-types.md
复杂查询或数据聚合?
- "统计处于开启状态的灯光数量"
- "获取电量低的设备"
- "获取所有传感器的平均温度"
- "基于时间段的条件逻辑"
→ Load
resources/templates.md
系统管理或组件发现?
- "已加载哪些组件?"
- "有哪些可用服务?"
- "检查配置有效性"
- "查看错误日志"
→ Load
resources/system-config.md
实用工作示例?
- Python、Node.js、Bash、curl代码
- 集成模式
- 错误处理
- 多实体操作
→ Load
resources/examples.md
Phase 2: Endpoint Selection
阶段2:端点选择
Use this decision tree to select the right API endpoint:
Do you need to...
│
├─ GET INFORMATION?
│ ├─ Get one entity's state? → GET /api/states/{entity_id}
│ ├─ Get all entity states? → GET /api/states (then filter)
│ ├─ Get configuration? → GET /api/config
│ ├─ List available services? → GET /api/services
│ ├─ Discover event types? → GET /api/events
│ ├─ Query historical data? → GET /api/history/period/{timestamp}
│ ├─ Get error log? → GET /api/error_log
│ ├─ Complex query/computation? → POST /api/template
│ └─ Check system status? → GET /api/
│
├─ CONTROL A DEVICE?
│ ├─ Light (on/off/brightness)? → POST /api/services/light/{service}
│ ├─ Switch? → POST /api/services/switch/{service}
│ ├─ Climate/thermostat? → POST /api/services/climate/{service}
│ ├─ Lock? → POST /api/services/lock/{service}
│ ├─ Cover/blinds? → POST /api/services/cover/{service}
│ ├─ Media player? → POST /api/services/media_player/{service}
│ ├─ Fan? → POST /api/services/fan/{service}
│ ├─ Camera? → POST /api/services/camera/{service}
│ └─ Any service? → POST /api/services/{domain}/{service}
│
├─ MODIFY STATE (NOT FOR DEVICE CONTROL)?
│ ├─ Create/update state? → POST /api/states/{entity_id}
│ ├─ Delete state? → DELETE /api/states/{entity_id}
│ └─ Fire custom event? → POST /api/events/{event_type}
│
└─ MANAGE SYSTEM?
├─ Validate config? → POST /api/config/core/check_config
├─ Reload config? → POST /api/services/homeassistant/reload_core_config
├─ Restart Home Assistant? → POST /api/services/homeassistant/restart
├─ Get components list? → GET /api/components
├─ Update entity metadata? → POST /api/services/homeassistant/update_entity
└─ Check error log? → GET /api/error_log使用以下决策树选择合适的API端点:
Do you need to...
│
├─ GET INFORMATION?
│ ├─ Get one entity's state? → GET /api/states/{entity_id}
│ ├─ Get all entity states? → GET /api/states (then filter)
│ ├─ Get configuration? → GET /api/config
│ ├─ List available services? → GET /api/services
│ ├─ Discover event types? → GET /api/events
│ ├─ Query historical data? → GET /api/history/period/{timestamp}
│ ├─ Get error log? → GET /api/error_log
│ ├─ Complex query/computation? → POST /api/template
│ └─ Check system status? → GET /api/
│
├─ CONTROL A DEVICE?
│ ├─ Light (on/off/brightness)? → POST /api/services/light/{service}
│ ├─ Switch? → POST /api/services/switch/{service}
│ ├─ Climate/thermostat? → POST /api/services/climate/{service}
│ ├─ Lock? → POST /api/services/lock/{service}
│ ├─ Cover/blinds? → POST /api/services/cover/{service}
│ ├─ Media player? → POST /api/services/media_player/{service}
│ ├─ Fan? → POST /api/services/fan/{service}
│ ├─ Camera? → POST /api/services/camera/{service}
│ └─ Any service? → POST /api/services/{domain}/{service}
│
├─ MODIFY STATE (NOT FOR DEVICE CONTROL)?
│ ├─ Create/update state? → POST /api/states/{entity_id}
│ ├─ Delete state? → DELETE /api/states/{entity_id}
│ └─ Fire custom event? → POST /api/events/{event_type}
│
└─ MANAGE SYSTEM?
├─ Validate config? → POST /api/config/core/check_config
├─ Reload config? → POST /api/services/homeassistant/reload_core_config
├─ Restart Home Assistant? → POST /api/services/homeassistant/restart
├─ Get components list? → GET /api/components
├─ Update entity metadata? → POST /api/services/homeassistant/update_entity
└─ Check error log? → GET /api/error_logPhase 3: Execution & Validation
阶段3:执行与验证
Before Calling API:
- Do you have correct entity_id? (domain.name format)
- Are you using the right HTTP method? (GET vs POST vs DELETE)
- Is your authentication token valid?
- For service calls, do you have the right parameters?
During Execution:
- Handle error responses appropriately (401, 404, 500, etc.)
- Retry on network errors with exponential backoff
- Monitor performance for polling operations
After Execution:
- Verify response matches expectation
- Check for error codes in response
- Cache results if applicable
调用API前:
- 你是否拥有正确的entity_id?(格式为domain.name)
- 你是否使用了正确的HTTP方法?(GET、POST、DELETE)
- 你的身份验证令牌是否有效?
- 对于服务调用,你是否拥有正确的参数?
执行过程中:
- 适当处理错误响应(401、404、500等)
- 网络错误时使用指数退避策略重试
- 监控轮询操作的性能
执行完成后:
- 验证响应是否符合预期
- 检查响应中的错误代码
- 适用时缓存结果
Common Task Patterns
常见任务模式
Query Current State
查询当前状态
bash
undefinedbash
undefinedGet one light's state
Get one light's state
GET /api/states/light.kitchen
GET /api/states/light.kitchen
Get temperature reading
Get temperature reading
GET /api/states/sensor.temperature
GET /api/states/sensor.temperature
Get all lights
Get all lights
GET /api/states
GET /api/states
Then filter: .[] | select(.entity_id | startswith("light."))
Then filter: .[] | select(.entity_id | startswith("light."))
Load: `resources/state-management.md` then `resources/core-concepts.md` for HTTP details
加载:`resources/state-management.md`,然后获取HTTP细节请查看`resources/core-concepts.md`Turn on/off Devices
开关设备
bash
undefinedbash
undefinedTurn on light with brightness
Turn on light with brightness
POST /api/services/light/turn_on
{"entity_id": "light.kitchen", "brightness": 200}
POST /api/services/light/turn_on
{"entity_id": "light.kitchen", "brightness": 200}
Turn off all lights
Turn off all lights
POST /api/services/light/turn_off
{"entity_id": "all"}
POST /api/services/light/turn_off
{"entity_id": "all"}
Toggle switch
Toggle switch
POST /api/services/switch/toggle
{"entity_id": "switch.coffee_maker"}
Load: `resources/service-reference.md` + `resources/entity-types.md` for specific parametersPOST /api/services/switch/toggle
{"entity_id": "switch.coffee_maker"}
加载:`resources/service-reference.md` + `resources/entity-types.md`获取特定参数Query Multiple Entities
查询多个实体
Option 1: Multiple API calls (simple, high bandwidth)
bash
GET /api/states/light.kitchen
GET /api/states/light.living_room
GET /api/states/light.bedroomOption 2: Get all and filter (one call, parse locally)
bash
GET /api/states选项1:多次API调用(简单,但带宽占用高)
bash
GET /api/states/light.kitchen
GET /api/states/light.living_room
GET /api/states/light.bedroom选项2:获取全部结果后筛选(单次调用,本地解析)
bash
GET /api/statesFilter in client: select by entity_id prefix
在客户端筛选:按entity_id前缀选择
**Option 3: Server-side template** (most efficient)
```bash
POST /api/template
{"template": "{{ states.light | selectattr('state', 'eq', 'on') | list | length }}"}Load: for advanced queries
resources/templates.md
**选项3:服务器端模板**(效率最高)
```bash
POST /api/template
{"template": "{{ states.light | selectattr('state', 'eq', 'on') | list | length }}"}加载:获取高级查询方法
resources/templates.mdBatch Operations
批量操作
bash
undefinedbash
undefinedBad: Multiple sequential API calls
不推荐:多次顺序API调用
POST /api/services/light/turn_on {"entity_id": "light.kitchen"}
POST /api/services/light/turn_on {"entity_id": "light.living_room"}
POST /api/services/light/turn_on {"entity_id": "light.bedroom"}
POST /api/services/light/turn_on {"entity_id": "light.kitchen"}
POST /api/services/light/turn_on {"entity_id": "light.living_room"}
POST /api/services/light/turn_on {"entity_id": "light.bedroom"}
Better: Array of entities in one call
推荐:单次调用中传入实体数组
POST /api/services/light/turn_on
{"entity_id": ["light.kitchen", "light.living_room", "light.bedroom"]}
POST /api/services/light/turn_on
{"entity_id": ["light.kitchen", "light.living_room", "light.bedroom"]}
Best: Use Home Assistant script (for complex multi-step)
最佳方案:使用Home Assistant脚本(适用于复杂多步骤操作)
POST /api/services/script/turn_on
{"entity_id": "script.my_scene"}
Load: `resources/examples.md` for working code patternsPOST /api/services/script/turn_on
{"entity_id": "script.my_scene"}
加载:`resources/examples.md`获取可用代码模式Entity Type Quick Reference
实体类型快速参考
Read-Only (Sensors)
只读型(传感器)
- - Numeric/text readings
sensor.* - - On/off detection
binary_sensor.* - - Camera snapshots
camera.*
Load: for attributes
resources/entity-types.md- - 数值/文本读数
sensor.* - - 开关状态检测
binary_sensor.* - - 摄像头快照
camera.*
加载:获取属性详情
resources/entity-types.mdControllable Entities
可控制实体
- - Lights (on/off, brightness, color)
light.* - - Switches (on/off)
switch.* - - Thermostats (temperature, mode)
climate.* - - Blinds, doors (open/close, position)
cover.* - - Locks (lock/unlock)
lock.* - - Fans (on/off, speed, oscillate)
fan.* - - Media devices (play/pause, volume)
media_player.*
Load: then
resources/entity-types.mdresources/service-reference.md- - 灯光(开关、亮度、颜色)
light.* - - 开关(开关)
switch.* - - 温控器(温度、模式)
climate.* - - 百叶窗、门(开关、位置)
cover.* - - 门锁(锁/解锁)
lock.* - - 风扇(开关、风速、摇头)
fan.* - - 媒体设备(播放/暂停、音量)
media_player.*
加载:,然后查看
resources/entity-types.mdresources/service-reference.mdMeta Entities (Non-device)
元实体(非设备)
- - Automations (trigger, turn on/off)
automation.* - - Scripts (turn on/off)
script.* - - Scenes (activate)
scene.* - - Entity groups
group.* - - Location tracking
person.* - - Device tracking
device_tracker.* - - Input helpers
input_*
- - 自动化(触发、开关)
automation.* - - 脚本(开关)
script.* - - 场景(激活)
scene.* - - 实体组
group.* - - 位置追踪
person.* - - 设备追踪
device_tracker.* - - 输入助手
input_*
Status Entities
状态实体
- - "home" or "not_home"
person.* - - Location state
device_tracker.* - - "above_horizon" or "below_horizon"
sun.sun - - Weather conditions
weather.*
- - "home"或"not_home"
person.* - - 位置状态
device_tracker.* - - "above_horizon"或"below_horizon"
sun.sun - - 天气状况
weather.*
Service Call Parameters
服务调用参数
Most Common Services
最常用服务
| Domain | Service | Key Parameters |
|---|---|---|
| light | turn_on | entity_id, brightness, rgb_color, transition |
| light | turn_off | entity_id, transition |
| switch | turn_on | entity_id |
| switch | turn_off | entity_id |
| climate | set_temperature | entity_id, temperature, hvac_mode |
| climate | set_hvac_mode | entity_id, hvac_mode |
| cover | open_cover | entity_id |
| cover | set_cover_position | entity_id, position (0-100) |
| lock | lock | entity_id, code (optional) |
| lock | unlock | entity_id, code (optional) |
| fan | turn_on | entity_id, percentage, preset_mode |
| media_player | play_media | entity_id, media_content_id, media_content_type |
| notify | mobile_app_* | message, title, data |
| automation | trigger | entity_id |
| script | turn_on | entity_id |
| scene | turn_on | entity_id, transition |
Load: for complete reference
resources/service-reference.md| 领域 | 服务 | 关键参数 |
|---|---|---|
| light | turn_on | entity_id, brightness, rgb_color, transition |
| light | turn_off | entity_id, transition |
| switch | turn_on | entity_id |
| switch | turn_off | entity_id |
| climate | set_temperature | entity_id, temperature, hvac_mode |
| climate | set_hvac_mode | entity_id, hvac_mode |
| cover | open_cover | entity_id |
| cover | set_cover_position | entity_id, position (0-100) |
| lock | lock | entity_id, code (可选) |
| lock | unlock | entity_id, code (可选) |
| fan | turn_on | entity_id, percentage, preset_mode |
| media_player | play_media | entity_id, media_content_id, media_content_type |
| notify | mobile_app_* | message, title, data |
| automation | trigger | entity_id |
| script | turn_on | entity_id |
| scene | turn_on | entity_id, transition |
加载:获取完整参考
resources/service-reference.mdResponse Handling
响应处理
Success (200)
成功(200)
json
{
"entity_id": "light.kitchen",
"state": "on",
"attributes": {...},
"last_changed": "...",
"last_updated": "...",
"context": {...}
}json
{
"entity_id": "light.kitchen",
"state": "on",
"attributes": {...},
"last_changed": "...",
"last_updated": "...",
"context": {...}
}Authorization Error (401)
授权错误(401)
json
{
"error": "Unauthorized",
"message": "Invalid authentication provided"
}Solution: Check token, regenerate if needed
json
{
"error": "Unauthorized",
"message": "Invalid authentication provided"
}解决方法: 检查令牌,必要时重新生成
Not Found (404)
未找到资源(404)
json
{
"error": "Entity not found",
"message": "No entity found for domain 'light' and name 'nonexistent'"
}Solution: Verify entity_id exists, check spelling
json
{
"error": "Entity not found",
"message": "No entity found for domain 'light' and name 'nonexistent'"
}解决方法: 验证entity_id是否存在,检查拼写
Bad Request (400)
错误请求(400)
json
{
"error": "Invalid JSON",
"message": "..."
}Solution: Validate JSON syntax, required fields
json
{
"error": "Invalid JSON",
"message": "..."
}解决方法: 验证JSON语法及必填字段
Server Error (500)
服务器错误(500)
Solution: Check HA error log, restart if needed
Load: for detailed error handling
resources/core-concepts.md解决方法: 查看Home Assistant错误日志,必要时重启
加载:获取详细错误处理方法
resources/core-concepts.mdPython Example Workflow
Python示例工作流
python
import requests
class HomeAssistant:
def __init__(self, url, token):
self.url = url
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# State queries
def get_state(self, entity_id):
"""Load: state-management.md"""
return requests.get(f"{self.url}/api/states/{entity_id}",
headers=self.headers).json()
# Service calls
def turn_on_light(self, entity_id, brightness=None):
"""Load: service-reference.md + entity-types.md"""
data = {"entity_id": entity_id}
if brightness:
data["brightness"] = brightness
return requests.post(
f"{self.url}/api/services/light/turn_on",
headers=self.headers,
json=data
).json()
# Complex queries
def count_on_lights(self):
"""Load: templates.md"""
template = "{{ states.light | selectattr('state', 'eq', 'on') | list | length }}"
resp = requests.post(
f"{self.url}/api/template",
headers=self.headers,
json={"template": template}
)
return int(resp.json()['result'])python
import requests
class HomeAssistant:
def __init__(self, url, token):
self.url = url
self.headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# State queries
def get_state(self, entity_id):
"""Load: state-management.md"""
return requests.get(f"{self.url}/api/states/{entity_id}",
headers=self.headers).json()
# Service calls
def turn_on_light(self, entity_id, brightness=None):
"""Load: service-reference.md + entity-types.md"""
data = {"entity_id": entity_id}
if brightness:
data["brightness"] = brightness
return requests.post(
f"{self.url}/api/services/light/turn_on",
headers=self.headers,
json=data
).json()
# Complex queries
def count_on_lights(self):
"""Load: templates.md"""
template = "{{ states.light | selectattr('state', 'eq', 'on') | list | length }}"
resp = requests.post(
f"{self.url}/api/template",
headers=self.headers,
json={"template": template}
)
return int(resp.json()['result'])Usage
Usage
ha = HomeAssistant("http://localhost:8123", "YOUR_TOKEN")
ha = HomeAssistant("http://localhost:8123", "YOUR_TOKEN")
Query state
Query state
kitchen = ha.get_state("light.kitchen")
print(f"Kitchen light: {kitchen['state']}")
kitchen = ha.get_state("light.kitchen")
print(f"Kitchen light: {kitchen['state']}")
Control device
Control device
ha.turn_on_light("light.kitchen", brightness=200)
ha.turn_on_light("light.kitchen", brightness=200)
Complex query
Complex query
count = ha.count_on_lights()
print(f"{count} lights are on")
Load: `resources/examples.md` for complete working examplescount = ha.count_on_lights()
print(f"{count} lights are on")
加载:`resources/examples.md`获取完整工作示例Decision Matrix: Which Task?
决策矩阵:对应任务?
| I want to... | Load Resource | Example |
|---|---|---|
| Understand how to authenticate | core-concepts.md | Getting access token |
| Query temperature or sensor value | state-management.md | GET /api/states/sensor.temp |
| Turn on a light | service-reference.md → entity-types.md | POST /api/services/light/turn_on |
| Find devices with low battery | templates.md | Server-side template query |
| Understand light color options | entity-types.md | Brightness, RGB, HS color |
| Count how many lights are on | templates.md | selectattr filter |
| Check if config is valid | system-config.md | POST /api/config/core/check_config |
| Write working Python code | examples.md | Complete client implementation |
| Handle errors properly | core-concepts.md → examples.md | Retry logic, error codes |
| Batch control multiple devices | service-reference.md → examples.md | Array of entity_ids |
| 我想要... | 加载资源 | 示例 |
|---|---|---|
| 了解如何进行身份验证 | core-concepts.md | 获取访问令牌 |
| 查询温度或传感器数值 | state-management.md | GET /api/states/sensor.temp |
| 打开灯光 | service-reference.md → entity-types.md | POST /api/services/light/turn_on |
| 找到电量低的设备 | templates.md | 服务器端模板查询 |
| 了解灯光颜色选项 | entity-types.md | 亮度、RGB、HS颜色 |
| 统计处于开启状态的灯光数量 | templates.md | selectattr筛选 |
| 检查配置是否有效 | system-config.md | POST /api/config/core/check_config |
| 编写可用的Python代码 | examples.md | 完整客户端实现 |
| 正确处理错误 | core-concepts.md → examples.md | 重试逻辑、错误代码 |
| 批量控制多个设备 | service-reference.md → examples.md | entity_ids数组 |
Recommended Learning Path
推荐学习路径
New to Home Assistant API?
- - Understand authentication and basics
resources/core-concepts.md - - Learn to query state
resources/state-management.md - - Learn to control devices
resources/service-reference.md - - See working code
resources/examples.md
Building an integration?
- - Error handling, timeouts
resources/core-concepts.md - - Client setup, retry logic
resources/examples.md - - Available operations
resources/service-reference.md - - Complex queries
resources/templates.md
Power user optimizations?
- - Server-side queries
resources/templates.md - - Discovery, caching
resources/system-config.md - - Performance patterns
resources/examples.md
Next Step: Identify your task above, load the appropriate resource file, and proceed with implementation.
Home Assistant API新手?
- - 了解身份验证和基础知识
resources/core-concepts.md - - 学习查询状态
resources/state-management.md - - 学习控制设备
resources/service-reference.md - - 查看可用代码
resources/examples.md
构建集成?
- - 错误处理、超时设置
resources/core-concepts.md - - 客户端设置、重试逻辑
resources/examples.md - - 可用操作
resources/service-reference.md - - 复杂查询
resources/templates.md
高级用户优化?
- - 服务器端查询
resources/templates.md - - 组件发现、缓存
resources/system-config.md - - 性能优化模式
resources/examples.md
下一步: 从上述内容中确定你的任务,加载对应的资源文件,然后开始实现。