mcpField
H
home-assistant-api

home-assistant-api

github.com/markpitt其他2452 次安装36 周前更新
代码仓库

关于 home-assistant-api

home-assistant-api 是面向 Home Assistant 集成开发与智能家居自动化的 API 技能,按任务引导选择参考资料和 REST API 端点,涵盖状态查询、设备控制与系统管理。

主要功能

  1. 01按任务选择 API 参考资料
  2. 02查询与监控实体状态
  3. 03控制灯光、温控和锁等设备
  4. 04使用模板执行复杂查询
  5. 05处理系统配置与错误日志
  6. 06提供批量操作和代码示例

适用场景

  1. 01查询传感器读数或门锁状态
  2. 02批量控制多个灯具
  3. 03筛选设备并汇总状态
  4. 04检查配置或查看错误日志

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/markpitt/claude-skills --skill home-assistant-api

安装后在 Claude Code 中输入/home-assistant-api确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

REFACTOR_SUMMARY.md
SKILL_NEW.md
resources/
core-concepts.md
entity-types.md
examples.md
service-reference.md
state-management.md
system-config.md
templates.md

详细介绍

Home Assistant REST API 编排技能

此技能提供对 Home Assistant REST API 的访问,用于构建集成、自动化智能家居设备,以及以编程方式管理 Home Assistant 实例。

快速参考:何时加载哪个资源

任务加载资源
设置身份验证、了解 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

编排协议

阶段 1:任务分析

确定用户需要完成什么:

身份验证与设置?

  • 开始使用 Home Assistant API
  • 创建或管理令牌
  • 配置 HTTP 客户端 → 加载 resources/core-concepts.md

查询或监控状态?

  • “厨房的温度是多少?”
  • “前门锁上了吗?”
  • “获取所有已开启的灯”
  • “监控实体变化” → 加载 resources/state-management.md

控制设备?

  • “打开厨房的灯”
  • “将恒温器设为 22°C”
  • “锁上前门”
  • “通过扬声器播放音乐” → 加载 resources/service-reference.md(然后在 resources/entity-types.md 中查找实体类型)

了解实体类型?

  • “气候实体有哪些属性?”
  • “门锁有哪些可用服务?”
  • “如何控制媒体播放器?” → 加载 resources/entity-types.md

复杂查询或数据聚合?

  • “统计所有已开启的灯”
  • “获取电量低的设备”
  • “计算所有传感器的平均温度”
  • “基于一天中的时间执行条件逻辑” → 加载 resources/templates.md

系统管理或发现?

  • “加载了哪些组件?”
  • “有哪些可用服务?”
  • “检查配置是否有效”
  • “查看错误日志” → 加载 resources/system-config.md

实际操作示例?

  • Python、Node.js、Bash、curl 代码
  • 集成模式
  • 错误处理
  • 多实体操作 → 加载 resources/examples.md
阶段 2:选择端点

使用此决策树选择合适的 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
阶段 3:执行与验证

调用 API 前:

  1. 是否有正确的 entity_id?(domain.name 格式)
  2. 是否使用了正确的 HTTP 方法?(GET、POST 还是 DELETE)
  3. 身份验证令牌是否有效?
  4. 对于服务调用,是否有正确的参数?

执行期间:

  • 妥善处理错误响应(401、404、500 等)
  • 网络错误时采用指数退避重试
  • 监控轮询操作的性能

执行后:

  • 验证响应是否符合预期
  • 检查响应中的错误代码
  • 适用时缓存结果

常见任务模式

查询当前状态
# Get one light's state
GET /api/states/light.kitchen

# Get temperature reading
GET /api/states/sensor.temperature

# Get all lights
GET /api/states
# Then filter: .[] | select(.entity_id | startswith("light."))

加载:resources/state-management.md,然后加载 resources/core-concepts.md 了解 HTTP 详情

打开/关闭设备
# Turn on light with brightness
POST /api/services/light/turn_on
{"entity_id": "light.kitchen", "brightness": 200}

# Turn off all lights
POST /api/services/light/turn_off
{"entity_id": "all"}

# Toggle switch
POST /api/services/switch/toggle
{"entity_id": "switch.coffee_maker"}

加载:resources/service-reference.md + resources/entity-types.md,了解具体参数

查询多个实体

选项 1:多次 API 调用(简单,带宽占用高)

GET /api/states/light.kitchen
GET /api/states/light.living_room
GET /api/states/light.bedroom

选项 2:获取全部并筛选(一次调用,在本地解析)

GET /api/states
# Filter in client: select by entity_id prefix

选项 3:服务端模板(效率最高)

POST /api/template
{"template": "{{ states.light | selectattr('state', 'eq', 'on') | list | length }}"}

加载:resources/templates.md,了解高级查询

批量操作
# Bad: Multiple sequential API calls
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"]}

# Best: Use Home Assistant script (for complex multi-step)
POST /api/services/script/turn_on
{"entity_id": "script.my_scene"}

加载:resources/examples.md,了解可用代码模式

实体类型快速参考

只读(传感器)
  • sensor.* - 数值/文本读数
  • binary_sensor.* - 开/关检测
  • camera.* - 摄像头快照

加载:resources/entity-types.md,了解属性

可控实体
  • light.* - 灯(开/关、亮度、颜色)
  • switch.* - 开关(开/关)
  • climate.* - 恒温器(温度、模式)
  • cover.* - 百叶窗、门(打开/关闭、位置)
  • lock.* - 门锁(上锁/解锁)
  • fan.* - 风扇(开/关、速度、摆动)
  • media_player.* - 媒体设备(播放/暂停、音量)

加载:resources/entity-types.md,然后加载 resources/service-reference.md

元实体(非设备)
  • automation.* - 自动化(触发、启用/停用)
  • script.* - 脚本(启用/停用)
  • scene.* - 场景(激活)
  • group.* - 实体组
  • person.* - 位置跟踪
  • device_tracker.* - 设备跟踪
  • input_* - 输入辅助项
状态实体
  • person.* - “home”或“not_home”
  • device_tracker.* - 位置状态
  • sun.sun - “above_horizon”或“below_horizon”
  • weather.* - 天气状况

服务调用参数

最常见的服务
域服务关键参数
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 以查看完整参考

响应处理

成功(200)
{
  "entity_id": "light.kitchen",
  "state": "on",
  "attributes": {...},
  "last_changed": "...",
  "last_updated": "...",
  "context": {...}
}
授权错误(401)
{
  "error": "Unauthorized",
  "message": "Invalid authentication provided"
}

解决方案: 检查令牌,必要时重新生成

未找到(404)
{
  "error": "Entity not found",
  "message": "No entity found for domain 'light' and name 'nonexistent'"
}

解决方案: 确认 entity_id 存在,并检查拼写

请求无效(400)
{
  "error": "Invalid JSON",
  "message": "..."
}

解决方案: 验证 JSON 语法和必填字段

服务器错误(500)

解决方案: 检查 HA 错误日志,必要时重启

加载:resources/core-concepts.md 以详细了解错误处理

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
ha = HomeAssistant("http://localhost:8123", "YOUR_TOKEN")

# Query state
kitchen = ha.get_state("light.kitchen")
print(f"Kitchen light: {kitchen['state']}")

# Control device
ha.turn_on_light("light.kitchen", brightness=200)

# Complex query
count = ha.count_on_lights()
print(f"{count} lights are on")

加载:resources/examples.md 以查看完整的可运行示例

决策矩阵:选择哪项任务?

我想要……加载资源示例
了解如何进行身份验证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 数组

推荐的学习路径

初次接触 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 - 性能模式

下一步: 确认上方与你的任务对应的部分,加载相应的资源文件,然后开始实施。

评论

支持 Markdown