The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(homeassistant): domain describer dispatch table, shared session factory, drop _build_adapter shim
Tekniumede7bf1869f0
diff --git a/plugins/platforms/homeassistant/adapter.py b/plugins/platforms/homeassistant/adapter.pyindex dd185be7a9f..a358a7b6de8 100644--- a/plugins/platforms/homeassistant/adapter.py+++ b/plugins/platforms/homeassistant/adapter.py@@ -3,10 +3,8 @@Listens on the HA WebSocket API; ``state_changed`` events become MessageEvents.Outbound messages are delivered as HA persistent notifications.-Requires:-- aiohttp (already in messaging extras)-- HASS_TOKEN env var (Long-Lived Access Token)-- HASS_URL env var (default: http://homeassistant.local:8123)+Requires aiohttp (messaging extras), HASS_TOKEN (Long-Lived Access Token) and+HASS_URL (default: http://homeassistant.local:8123)."""import asyncio@@ -16,7 +14,7 @@ import osimport timeimport uuidfrom datetime import datetime-from typing import Any, Dict, Optional, Set+from typing import Any, Callable, Dict, Optional, Settry:import aiohttp@@ -26,17 +24,9 @@ except ImportError:aiohttp = None # type: ignore[assignment]from gateway.config import Platform, PlatformConfig-from gateway.platforms.base import (- gateway_trust_env,- BasePlatformAdapter,- MessageEvent,- MessageType,- SendResult,-)-+from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, MessageEvent, MessageType, SendResultfrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secret-logger = logging.getLogger(__name__)@@ -62,6 +52,40 @@ def _triggered(val: str) -> str:return "triggered" if val == "on" else "cleared"+def _describe_climate(name, old_val, new_val, attrs) -> str:+ temp = attrs.get("current_temperature", "?")+ target = attrs.get("temperature", "?")+ return (+ f"[Home Assistant] {name}: HVAC mode changed from "+ f"'{old_val}' to '{new_val}' (current: {temp}, target: {target})"+ )+++def _describe_sensor(name, old_val, new_val, attrs) -> str:+ unit = attrs.get("unit_of_measurement", "")+ return f"[Home Assistant] {name}: changed from {old_val}{unit} to {new_val}{unit}"+++def _describe_on_off(name, old_val, new_val, attrs) -> str:+ return f"[Home Assistant] {name}: turned {_on_off(new_val)}"+++# domain -> (name, old_val, new_val, attrs) -> human-readable description+_DOMAIN_DESCRIBERS: Dict[str, Callable[..., str]] = {+ "climate": _describe_climate,+ "sensor": _describe_sensor,+ "binary_sensor": lambda name, old_val, new_val, attrs: (+ f"[Home Assistant] {name}: {_triggered(new_val)} (was {_triggered(old_val)})"+ ),+ "light": _describe_on_off,+ "switch": _describe_on_off,+ "fan": _describe_on_off,+ "alarm_control_panel": lambda name, old_val, new_val, attrs: (+ f"[Home Assistant] {name}: alarm state changed from '{old_val}' to '{new_val}'"+ ),+}++class HomeAssistantAdapter(BasePlatformAdapter):"""HA WebSocket adapter: ``state_changed`` events → MessageEvents, withdomain/entity filtering and per-entity cooldowns against event floods."""@@ -76,12 +100,10 @@ class HomeAssistantAdapter(BasePlatformAdapter):self._rest_session: Optional["aiohttp.ClientSession"] = Noneself._listen_task: Optional[asyncio.Task] = Noneself._msg_id: int = 0-extra = config.extra or {}url = extra.get("url") or os.getenv("HASS_URL", "http://homeassistant.local:8123")self._hass_url: str = url.rstrip("/")self._hass_token: str = config.token or _get_scoped_secret("HASS_TOKEN", "")-self._watch_domains: Set[str] = set(extra.get("watch_domains", []))self._watch_entities: Set[str] = set(extra.get("watch_entities", []))self._ignore_entities: Set[str] = set(extra.get("ignore_entities", []))@@ -93,6 +115,10 @@ class HomeAssistantAdapter(BasePlatformAdapter):self._msg_id += 1return self._msg_id+ @staticmethod+ def _new_session() -> "aiohttp.ClientSession":+ return aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), trust_env=gateway_trust_env())+# -- Connection lifecycle -----------------------------------------------async def connect(self, *, is_reconnect: bool = False) -> bool:@@ -103,14 +129,11 @@ class HomeAssistantAdapter(BasePlatformAdapter):if not self._hass_token:logger.warning("[%s] No HASS_TOKEN configured", self.name)return False-try:if not await self._ws_connect():return False# Dedicated REST session for send() calls- self._rest_session = aiohttp.ClientSession(- timeout=aiohttp.ClientTimeout(total=30), trust_env=gateway_trust_env(),- )+ self._rest_session = self._new_session()if not self._watch_domains and not self._watch_entities and not self._watch_all:logger.warning("[%s] No watch_domains, watch_entities, or watch_all configured. "@@ -130,29 +153,20 @@ class HomeAssistantAdapter(BasePlatformAdapter):async def _ws_connect(self) -> bool:"""Open the WebSocket, authenticate, and subscribe to ``state_changed``."""ws_url = self._hass_url.replace("https://", "wss://").replace("http://", "ws://")- self._session = aiohttp.ClientSession(- timeout=aiohttp.ClientTimeout(total=30), trust_env=gateway_trust_env(),- )+ self._session = self._new_session()self._ws = await self._session.ws_connect(f"{ws_url}/api/websocket", heartbeat=30, timeout=30)-msg = await self._ws.receive_json()if msg.get("type") != "auth_required":logger.error("Expected auth_required, got: %s", msg.get("type"))await self._cleanup_ws()return False-await self._ws.send_json({"type": "auth", "access_token": self._hass_token})msg = await self._ws.receive_json()if msg.get("type") != "auth_ok":logger.error("Auth failed: %s", msg)await self._cleanup_ws()return False-- await self._ws.send_json({- "id": self._next_id(),- "type": "subscribe_events",- "event_type": "state_changed",- })+ await self._ws.send_json({"id": self._next_id(), "type": "subscribe_events", "event_type": "state_changed"})msg = await self._ws.receive_json()if not msg.get("success"):logger.error("Failed to subscribe to events: %s", msg)@@ -177,7 +191,6 @@ class HomeAssistantAdapter(BasePlatformAdapter):except asyncio.CancelledError:passself._listen_task = None-await self._cleanup_ws()if self._rest_session and not self._rest_session.closed:await self._rest_session.close()@@ -196,14 +209,12 @@ class HomeAssistantAdapter(BasePlatformAdapter):returnexcept Exception as e:logger.warning("[%s] WebSocket error: %s", self.name, e)-if not self._running:returndelay = self._BACKOFF_STEPS[min(backoff_idx, len(self._BACKOFF_STEPS) - 1)]logger.info("[%s] Reconnecting in %ds...", self.name, delay)await asyncio.sleep(delay)backoff_idx += 1-try:await self._cleanup_ws()if await self._ws_connect():@@ -241,39 +252,26 @@ class HomeAssistantAdapter(BasePlatformAdapter):entity_id: str = event_data.get("entity_id", "")if not entity_id or not self._passes_filters(entity_id):return-now = time.time()if (now - self._last_event_time.get(entity_id, 0)) < self._cooldown_seconds:returnself._last_event_time[entity_id] = now-message = self._format_state_change(entity_id, event_data.get("old_state", {}), event_data.get("new_state", {}),)if not message:return-source = self.build_source(- chat_id="ha_events",- chat_name="Home Assistant Events",- chat_type="channel",- user_id="homeassistant",- user_name="Home Assistant",+ chat_id="ha_events", chat_name="Home Assistant Events", chat_type="channel",+ user_id="homeassistant", user_name="Home Assistant",)await self.handle_message(MessageEvent(- text=message,- message_type=MessageType.TEXT,- source=source,- message_id=f"ha_{entity_id}_{int(now)}",- timestamp=datetime.now(),+ text=message, message_type=MessageType.TEXT, source=source,+ message_id=f"ha_{entity_id}_{int(now)}", timestamp=datetime.now(),))@staticmethod- def _format_state_change(- entity_id: str,- old_state: Dict[str, Any],- new_state: Dict[str, Any],- ) -> Optional[str]:+ def _format_state_change(entity_id: str, old_state: Dict[str, Any], new_state: Dict[str, Any]) -> Optional[str]:"""Convert a state_changed event into a human-readable description."""if not new_state:return None@@ -281,37 +279,17 @@ class HomeAssistantAdapter(BasePlatformAdapter):new_val = new_state.get("state", "unknown")if old_val == new_val:return None-attrs = new_state.get("attributes", {})name = attrs.get("friendly_name", entity_id)- domain = _domain_of(entity_id)-- if domain == "climate":- temp = attrs.get("current_temperature", "?")- target = attrs.get("temperature", "?")- return (- f"[Home Assistant] {name}: HVAC mode changed from "- f"'{old_val}' to '{new_val}' (current: {temp}, target: {target})"- )- if domain == "sensor":- unit = attrs.get("unit_of_measurement", "")- return f"[Home Assistant] {name}: changed from {old_val}{unit} to {new_val}{unit}"- if domain == "binary_sensor":- return f"[Home Assistant] {name}: {_triggered(new_val)} (was {_triggered(old_val)})"- if domain in {"light", "switch", "fan"}:- return f"[Home Assistant] {name}: turned {_on_off(new_val)}"- if domain == "alarm_control_panel":- return f"[Home Assistant] {name}: alarm state changed from '{old_val}' to '{new_val}'"+ describe = _DOMAIN_DESCRIBERS.get(_domain_of(entity_id))+ if describe is not None:+ return describe(name, old_val, new_val, attrs)return f"[Home Assistant] {name} ({entity_id}): changed from '{old_val}' to '{new_val}'"# -- Outbound messaging -------------------------------------------------async def send(- self,- chat_id: str,- content: str,- reply_to: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,+ self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,) -> SendResult:"""Send a notification via HA REST API (persistent_notification.create).@@ -349,13 +327,8 @@ class HomeAssistantAdapter(BasePlatformAdapter):async def _standalone_send(- pconfig,- chat_id: str,- message: str,- *,- thread_id: Optional[str] = None,- media_files: Optional[list] = None,- force_document: bool = False,+ pconfig, chat_id: str, message: str, *,+ thread_id: Optional[str] = None, media_files: Optional[list] = None, force_document: bool = False,) -> Dict[str, Any]:"""Send via the HA ``notify.notify`` service without a live gateway adapter.@@ -365,20 +338,16 @@ async def _standalone_send("""if not AIOHTTP_AVAILABLE:return {"error": "aiohttp not installed. Run: pip install aiohttp"}-extra = getattr(pconfig, "extra", {}) or {}hass_url = (extra.get("url") or os.getenv("HASS_URL", "")).rstrip("/")token = (getattr(pconfig, "token", None) or _get_scoped_secret("HASS_TOKEN", "")).strip()if not hass_url or not token:return {"error": "Home Assistant standalone send: HASS_URL and HASS_TOKEN must both be set"}-url = f"{hass_url}/api/services/notify/notify"headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}payload = {"message": message, "target": chat_id}try:- async with aiohttp.ClientSession(- timeout=aiohttp.ClientTimeout(total=30), trust_env=gateway_trust_env(),- ) as session:+ async with HomeAssistantAdapter._new_session() as session:async with session.post(url, headers=headers, json=payload) as resp:if resp.status not in {200, 201}:body = await resp.text()@@ -400,16 +369,12 @@ def _is_connected(config) -> bool:return bool((gateway_mod.get_env_value("HASS_TOKEN") or "").strip())-def _build_adapter(config):- return HomeAssistantAdapter(config)--def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(name="homeassistant",label="Home Assistant",- adapter_factory=_build_adapter,+ adapter_factory=HomeAssistantAdapter,check_fn=check_ha_requirements,validate_config=validate_ha_config,is_connected=_is_connected,