mcpField
H
home-assistant-api

home-assistant-api

github.com/markpittその他2452 回インストール36 週間前に更新
リポジトリ

home-assistant-api について

home-assistant-api は、Home Assistant の 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、次に HTTP の詳細について resources/core-concepts.md

デバイスのオン/オフ
# 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:すべて取得してフィルター処理(1 回の呼び出しで、ローカルで解析)

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 (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

完全なリファレンスは 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 - パフォーマンスのパターン

次のステップ: 上記から該当するタスクを特定し、適切なリソースファイルを読み込んで、実装を進めてください。

コメント