home-assistant-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Home 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

快速参考:何时加载对应资源

TaskLoad Resource
Setting up authentication, understanding API basics, HTTP methods
resources/core-concepts.md
Querying entity states, updating states, monitoring changes
resources/state-management.md
Controlling lights, climate, locks, and other devices
resources/service-reference.md
Understanding light, switch, sensor, climate entity types
resources/entity-types.md
Server-side template queries, complex filters, aggregations
resources/templates.md
System configuration, component discovery, error logs
resources/system-config.md
Complete code examples, client libraries, patterns
resources/examples.md
任务加载资源
设置身份验证、了解API基础知识、HTTP方法
resources/core-concepts.md
查询实体状态、更新状态、监控变更
resources/state-management.md
控制灯光、温控、门锁及其他设备
resources/service-reference.md
了解灯光、开关、传感器、温控等实体类型
resources/entity-types.md
服务器端模板查询、复杂筛选、聚合操作
resources/templates.md
系统配置、组件发现、错误日志
resources/system-config.md
完整代码示例、客户端库、实现模式
resources/examples.md

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
    resources/service-reference.md
    (then find entity type in
    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_log

Phase 3: Execution & Validation

阶段3:执行与验证

Before Calling API:
  1. Do you have correct entity_id? (domain.name format)
  2. Are you using the right HTTP method? (GET vs POST vs DELETE)
  3. Is your authentication token valid?
  4. 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前:
  1. 你是否拥有正确的entity_id?(格式为domain.name)
  2. 你是否使用了正确的HTTP方法?(GET、POST、DELETE)
  3. 你的身份验证令牌是否有效?
  4. 对于服务调用,你是否拥有正确的参数?
执行过程中:
  • 适当处理错误响应(401、404、500等)
  • 网络错误时使用指数退避策略重试
  • 监控轮询操作的性能
执行完成后:
  • 验证响应是否符合预期
  • 检查响应中的错误代码
  • 适用时缓存结果

Common Task Patterns

常见任务模式

Query Current State

查询当前状态

bash
undefined
bash
undefined

Get 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
undefined
bash
undefined

Turn 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 parameters
POST /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.bedroom
Option 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/states

Filter 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:
resources/templates.md
for advanced queries

**选项3:服务器端模板**(效率最高)
```bash
POST /api/template
{"template": "{{ states.light | selectattr('state', 'eq', 'on') | list | length }}"}
加载:
resources/templates.md
获取高级查询方法

Batch Operations

批量操作

bash
undefined
bash
undefined

Bad: 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 patterns
POST /api/services/script/turn_on {"entity_id": "script.my_scene"}

加载:`resources/examples.md`获取可用代码模式

Entity Type Quick Reference

实体类型快速参考

Read-Only (Sensors)

只读型(传感器)

  • sensor.*
    - Numeric/text readings
  • binary_sensor.*
    - On/off detection
  • camera.*
    - Camera snapshots
Load:
resources/entity-types.md
for attributes
  • sensor.*
    - 数值/文本读数
  • binary_sensor.*
    - 开关状态检测
  • camera.*
    - 摄像头快照
加载:
resources/entity-types.md
获取属性详情

Controllable Entities

可控制实体

  • light.*
    - Lights (on/off, brightness, color)
  • switch.*
    - Switches (on/off)
  • climate.*
    - Thermostats (temperature, mode)
  • cover.*
    - Blinds, doors (open/close, position)
  • lock.*
    - Locks (lock/unlock)
  • fan.*
    - Fans (on/off, speed, oscillate)
  • media_player.*
    - Media devices (play/pause, volume)
Load:
resources/entity-types.md
then
resources/service-reference.md
  • light.*
    - 灯光(开关、亮度、颜色)
  • switch.*
    - 开关(开关)
  • climate.*
    - 温控器(温度、模式)
  • cover.*
    - 百叶窗、门(开关、位置)
  • lock.*
    - 门锁(锁/解锁)
  • fan.*
    - 风扇(开关、风速、摇头)
  • media_player.*
    - 媒体设备(播放/暂停、音量)
加载:
resources/entity-types.md
,然后查看
resources/service-reference.md

Meta Entities (Non-device)

元实体(非设备)

  • automation.*
    - Automations (trigger, turn on/off)
  • script.*
    - Scripts (turn on/off)
  • scene.*
    - Scenes (activate)
  • group.*
    - Entity groups
  • person.*
    - Location tracking
  • device_tracker.*
    - Device tracking
  • input_*
    - Input helpers
  • automation.*
    - 自动化(触发、开关)
  • script.*
    - 脚本(开关)
  • scene.*
    - 场景(激活)
  • group.*
    - 实体组
  • person.*
    - 位置追踪
  • device_tracker.*
    - 设备追踪
  • input_*
    - 输入助手

Status Entities

状态实体

  • person.*
    - "home" or "not_home"
  • device_tracker.*
    - Location state
  • sun.sun
    - "above_horizon" or "below_horizon"
  • weather.*
    - Weather conditions
  • person.*
    - "home"或"not_home"
  • device_tracker.*
    - 位置状态
  • sun.sun
    - "above_horizon"或"below_horizon"
  • weather.*
    - 天气状况

Service Call Parameters

服务调用参数

Most Common Services

最常用服务

DomainServiceKey Parameters
lightturn_onentity_id, brightness, rgb_color, transition
lightturn_offentity_id, transition
switchturn_onentity_id
switchturn_offentity_id
climateset_temperatureentity_id, temperature, hvac_mode
climateset_hvac_modeentity_id, hvac_mode
coveropen_coverentity_id
coverset_cover_positionentity_id, position (0-100)
locklockentity_id, code (optional)
lockunlockentity_id, code (optional)
fanturn_onentity_id, percentage, preset_mode
media_playerplay_mediaentity_id, media_content_id, media_content_type
notifymobile_app_*message, title, data
automationtriggerentity_id
scriptturn_onentity_id
sceneturn_onentity_id, transition
Load:
resources/service-reference.md
for complete reference
领域服务关键参数
lightturn_onentity_id, brightness, rgb_color, transition
lightturn_offentity_id, transition
switchturn_onentity_id
switchturn_offentity_id
climateset_temperatureentity_id, temperature, hvac_mode
climateset_hvac_modeentity_id, hvac_mode
coveropen_coverentity_id
coverset_cover_positionentity_id, position (0-100)
locklockentity_id, code (可选)
lockunlockentity_id, code (可选)
fanturn_onentity_id, percentage, preset_mode
media_playerplay_mediaentity_id, media_content_id, media_content_type
notifymobile_app_*message, title, data
automationtriggerentity_id
scriptturn_onentity_id
sceneturn_onentity_id, transition
加载:
resources/service-reference.md
获取完整参考

Response 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:
resources/core-concepts.md
for detailed error handling
解决方法: 查看Home Assistant错误日志,必要时重启
加载:
resources/core-concepts.md
获取详细错误处理方法

Python 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 examples
count = ha.count_on_lights() print(f"{count} lights are on")

加载:`resources/examples.md`获取完整工作示例

Decision Matrix: Which Task?

决策矩阵:对应任务?

I want to...Load ResourceExample
Understand how to authenticatecore-concepts.mdGetting access token
Query temperature or sensor valuestate-management.mdGET /api/states/sensor.temp
Turn on a lightservice-reference.md → entity-types.mdPOST /api/services/light/turn_on
Find devices with low batterytemplates.mdServer-side template query
Understand light color optionsentity-types.mdBrightness, RGB, HS color
Count how many lights are ontemplates.mdselectattr filter
Check if config is validsystem-config.mdPOST /api/config/core/check_config
Write working Python codeexamples.mdComplete client implementation
Handle errors properlycore-concepts.md → examples.mdRetry logic, error codes
Batch control multiple devicesservice-reference.md → examples.mdArray of entity_ids
我想要...加载资源示例
了解如何进行身份验证core-concepts.md获取访问令牌
查询温度或传感器数值state-management.mdGET /api/states/sensor.temp
打开灯光service-reference.md → entity-types.mdPOST /api/services/light/turn_on
找到电量低的设备templates.md服务器端模板查询
了解灯光颜色选项entity-types.md亮度、RGB、HS颜色
统计处于开启状态的灯光数量templates.mdselectattr筛选
检查配置是否有效system-config.mdPOST /api/config/core/check_config
编写可用的Python代码examples.md完整客户端实现
正确处理错误core-concepts.md → examples.md重试逻辑、错误代码
批量控制多个设备service-reference.md → examples.mdentity_ids数组

Recommended Learning Path

推荐学习路径

New to Home Assistant API?
  1. resources/core-concepts.md
    - Understand authentication and basics
  2. resources/state-management.md
    - Learn to query state
  3. resources/service-reference.md
    - Learn to control devices
  4. resources/examples.md
    - See working code
Building an integration?
  1. resources/core-concepts.md
    - Error handling, timeouts
  2. resources/examples.md
    - Client setup, retry logic
  3. resources/service-reference.md
    - Available operations
  4. resources/templates.md
    - Complex queries
Power user optimizations?
  1. resources/templates.md
    - Server-side queries
  2. resources/system-config.md
    - Discovery, caching
  3. resources/examples.md
    - Performance patterns

Next Step: Identify your task above, load the appropriate resource file, and proceed with implementation.
Home Assistant API新手?
  1. resources/core-concepts.md
    - 了解身份验证和基础知识
  2. resources/state-management.md
    - 学习查询状态
  3. resources/service-reference.md
    - 学习控制设备
  4. resources/examples.md
    - 查看可用代码
构建集成?
  1. resources/core-concepts.md
    - 错误处理、超时设置
  2. resources/examples.md
    - 客户端设置、重试逻辑
  3. resources/service-reference.md
    - 可用操作
  4. resources/templates.md
    - 复杂查询
高级用户优化?
  1. resources/templates.md
    - 服务器端查询
  2. resources/system-config.md
    - 组件发现、缓存
  3. resources/examples.md
    - 性能优化模式

下一步: 从上述内容中确定你的任务,加载对应的资源文件,然后开始实现。