homeassistant.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. """Service for communicating with Home Assistant via REST API."""
  2. import asyncio
  3. import logging
  4. from typing import TYPE_CHECKING
  5. from urllib.parse import urlparse
  6. import httpx
  7. if TYPE_CHECKING:
  8. from backend.app.models.smart_plug import SmartPlug
  9. logger = logging.getLogger(__name__)
  10. class HomeAssistantService:
  11. """Service for controlling Home Assistant entities via REST API."""
  12. def __init__(self, timeout: float = 10.0):
  13. self.timeout = timeout
  14. self.base_url: str = ""
  15. self.token: str = ""
  16. def configure(self, url: str, token: str):
  17. """Configure HA connection settings."""
  18. self.base_url = url.rstrip("/") if url else ""
  19. self.token = token or ""
  20. def _headers(self) -> dict:
  21. return {
  22. "Authorization": f"Bearer {self.token}",
  23. "Content-Type": "application/json",
  24. }
  25. async def get_status(self, plug: "SmartPlug") -> dict:
  26. """Get current state of HA entity.
  27. Returns dict with:
  28. - state: "ON" or "OFF" or None if unreachable
  29. - reachable: bool
  30. - device_name: str or None
  31. """
  32. if not self.base_url or not self.token:
  33. return {"state": None, "reachable": False, "device_name": None}
  34. try:
  35. async with httpx.AsyncClient(timeout=self.timeout) as client:
  36. response = await client.get(
  37. f"{self.base_url}/api/states/{plug.ha_entity_id}",
  38. headers=self._headers(),
  39. )
  40. response.raise_for_status()
  41. data = response.json()
  42. state_value = data.get("state", "").lower()
  43. # Normalize to ON/OFF
  44. if state_value == "on":
  45. state = "ON"
  46. elif state_value == "off":
  47. state = "OFF"
  48. else:
  49. state = None
  50. return {
  51. "state": state,
  52. "reachable": True,
  53. "device_name": data.get("attributes", {}).get("friendly_name"),
  54. }
  55. except Exception as e:
  56. logger.warning("Failed to get HA entity state for %s: %s", plug.ha_entity_id, e)
  57. return {"state": None, "reachable": False, "device_name": None}
  58. async def turn_on(self, plug: "SmartPlug") -> bool:
  59. """Turn on HA entity. Returns True if successful."""
  60. success = await self._call_service(plug, "turn_on")
  61. if success:
  62. logger.info("Turned ON HA entity '%s' (%s)", plug.name, plug.ha_entity_id)
  63. return success
  64. async def turn_off(self, plug: "SmartPlug") -> bool:
  65. """Turn off HA entity. Returns True if successful."""
  66. success = await self._call_service(plug, "turn_off")
  67. if success:
  68. logger.info("Turned OFF HA entity '%s' (%s)", plug.name, plug.ha_entity_id)
  69. return success
  70. async def toggle(self, plug: "SmartPlug") -> bool:
  71. """Toggle HA entity. Returns True if successful."""
  72. success = await self._call_service(plug, "toggle")
  73. if success:
  74. logger.info("Toggled HA entity '%s' (%s)", plug.name, plug.ha_entity_id)
  75. return success
  76. async def _call_service(self, plug: "SmartPlug", action: str) -> bool:
  77. """Call HA service on entity."""
  78. if not self.base_url or not self.token or not plug.ha_entity_id:
  79. return False
  80. domain = plug.ha_entity_id.split(".")[0] # "switch", "light", etc.
  81. try:
  82. async with httpx.AsyncClient(timeout=self.timeout) as client:
  83. response = await client.post(
  84. f"{self.base_url}/api/services/{domain}/{action}",
  85. headers=self._headers(),
  86. json={"entity_id": plug.ha_entity_id},
  87. )
  88. response.raise_for_status()
  89. return True
  90. except Exception as e:
  91. logger.warning("Failed to %s HA entity %s: %s", action, plug.ha_entity_id, e)
  92. return False
  93. async def get_energy(self, plug: "SmartPlug") -> dict | None:
  94. """Get energy data from HA sensor entities or switch attributes.
  95. First tries dedicated sensor entities if configured, then falls back
  96. to checking the switch entity's attributes.
  97. Returns dict with energy data or None if not available.
  98. """
  99. if not self.base_url or not self.token:
  100. return None
  101. power = None
  102. today = None
  103. total = None
  104. try:
  105. async with httpx.AsyncClient(timeout=self.timeout) as client:
  106. # Fetch power from dedicated sensor entity if configured
  107. if plug.ha_power_entity:
  108. power = await self._get_sensor_value(client, plug.ha_power_entity)
  109. # Fetch today's energy from dedicated sensor entity if configured
  110. if plug.ha_energy_today_entity:
  111. today = await self._get_sensor_value(client, plug.ha_energy_today_entity)
  112. # Fetch total energy from dedicated sensor entity if configured
  113. if plug.ha_energy_total_entity:
  114. total = await self._get_sensor_value(client, plug.ha_energy_total_entity)
  115. # Fallback: try switch entity attributes (original behavior)
  116. if power is None:
  117. response = await client.get(
  118. f"{self.base_url}/api/states/{plug.ha_entity_id}",
  119. headers=self._headers(),
  120. )
  121. response.raise_for_status()
  122. attrs = response.json().get("attributes", {})
  123. power = attrs.get("current_power_w") or attrs.get("power")
  124. if today is None:
  125. today = attrs.get("today_energy_kwh")
  126. if total is None:
  127. total = attrs.get("total_energy_kwh")
  128. if power is None:
  129. return None
  130. return {
  131. "power": power,
  132. "voltage": None,
  133. "current": None,
  134. "today": today,
  135. "total": total,
  136. "yesterday": None,
  137. "factor": None,
  138. "apparent_power": None,
  139. "reactive_power": None,
  140. }
  141. except Exception as e:
  142. logger.debug("Failed to get HA energy data: %s", e)
  143. return None
  144. async def _get_sensor_value(self, client: httpx.AsyncClient, entity_id: str) -> float | None:
  145. """Fetch numeric value from a HA sensor entity."""
  146. try:
  147. response = await client.get(
  148. f"{self.base_url}/api/states/{entity_id}",
  149. headers=self._headers(),
  150. )
  151. response.raise_for_status()
  152. state = response.json().get("state")
  153. if state and state not in ("unknown", "unavailable"):
  154. return float(state)
  155. except Exception:
  156. pass # Sensor read is best-effort; caller handles None
  157. return None
  158. @staticmethod
  159. def _validate_url(url: str) -> str | None:
  160. """Normalise a caller-supplied HA URL, or return None if it is unsafe.
  161. The stored ``ha_url`` setting is already validated at the schema layer
  162. (``LAN_SERVICE_URL_SETTINGS`` in schemas/settings.py), but
  163. ``test_connection`` takes its URL straight from the request body, so
  164. the same policy has to be applied here.
  165. Delegates to ``_url_safety.assert_safe_lan_service_url`` rather than
  166. the string blocklist this replaces. That blocklist only knew three
  167. literal hostnames plus a ``169.254.`` prefix and never parsed the
  168. hostname as an IP, so it let through the Alibaba (100.100.100.200)
  169. and AWS-IPv6 (fd00:ec2::254) metadata endpoints, numeric-encoded
  170. loopback, multicast, and IPv4-mapped IPv6 encodings of the IMDS
  171. address it did know about.
  172. Loopback and RFC-1918 remain permitted — Home Assistant is a
  173. LAN-resident service by design, and the shared guard is documented
  174. that way.
  175. """
  176. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  177. try:
  178. assert_safe_lan_service_url(url, label="Home Assistant URL")
  179. except ValueError:
  180. return None
  181. # Guard passed, so the scheme is http/https and a hostname is present;
  182. # re-parse only to drop query/fragment and normalise the authority.
  183. parsed = urlparse(url)
  184. if not parsed.hostname:
  185. return None
  186. # urlparse strips the brackets off an IPv6 literal, so they have to go
  187. # back on or the rebuilt URL is unparseable ("http://fd00::1:8123").
  188. host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
  189. return f"{parsed.scheme.lower()}://{host}" + (f":{parsed.port}" if parsed.port else "") + (parsed.path or "")
  190. async def test_connection(self, url: str, token: str) -> dict:
  191. """Test connection to Home Assistant.
  192. Returns dict with:
  193. - success: bool
  194. - message: str or None (HA message on success)
  195. - error: str or None (error message on failure)
  196. """
  197. safe_url = self._validate_url(url)
  198. if not safe_url:
  199. return {"success": False, "message": None, "error": "Invalid Home Assistant URL"}
  200. try:
  201. async with httpx.AsyncClient(timeout=self.timeout) as client:
  202. response = await client.get(
  203. f"{safe_url.rstrip('/')}/api/",
  204. headers={"Authorization": f"Bearer {token}"},
  205. )
  206. response.raise_for_status()
  207. data = response.json()
  208. return {
  209. "success": True,
  210. "message": data.get("message", "Connected"),
  211. "error": None,
  212. }
  213. except httpx.HTTPStatusError as e:
  214. if e.response.status_code == 401:
  215. return {"success": False, "message": None, "error": "Invalid access token"}
  216. return {"success": False, "message": None, "error": f"HTTP {e.response.status_code}"}
  217. except httpx.TimeoutException:
  218. return {"success": False, "message": None, "error": "Connection timeout"}
  219. except httpx.ConnectError:
  220. return {"success": False, "message": None, "error": "Could not connect to Home Assistant"}
  221. except Exception as e:
  222. return {"success": False, "message": None, "error": str(e)}
  223. async def list_entities(self, url: str, token: str, search: str | None = None) -> list[dict]:
  224. """List available entities from HA.
  225. Always filters to switch/light/input_boolean/script — the only domains
  226. the SmartPlugBase.ha_entity_id pattern accepts. When a search query is
  227. provided it narrows the same domain-filtered list by entity_id or
  228. friendly_name substring (case-insensitive).
  229. Previously search bypassed the domain filter, which let users pick a
  230. sensor.* or binary_sensor.* entity from the dropdown that the backend
  231. schema would then reject with the cryptic Pydantic pattern error
  232. (#1388). Picking what you can't save isn't a useful UX.
  233. Returns list of entity dicts with:
  234. - entity_id: str
  235. - friendly_name: str
  236. - state: str
  237. - domain: str
  238. """
  239. # Allowed domains for smart plug control — must mirror the regex in
  240. # backend/app/schemas/smart_plug.py:17 (SmartPlugBase.ha_entity_id).
  241. allowed_domains = {"switch", "light", "input_boolean", "script"}
  242. try:
  243. async with httpx.AsyncClient(timeout=self.timeout) as client:
  244. response = await client.get(
  245. f"{url.rstrip('/')}/api/states",
  246. headers={"Authorization": f"Bearer {token}"},
  247. )
  248. response.raise_for_status()
  249. entities = []
  250. search_lower = search.lower().strip() if search else None
  251. for entity in response.json():
  252. entity_id = entity.get("entity_id", "")
  253. domain = entity_id.split(".")[0] if "." in entity_id else ""
  254. friendly_name = entity.get("attributes", {}).get("friendly_name", entity_id)
  255. if domain not in allowed_domains:
  256. continue
  257. if search_lower and (
  258. search_lower not in entity_id.lower() and search_lower not in friendly_name.lower()
  259. ):
  260. continue
  261. entities.append(
  262. {
  263. "entity_id": entity_id,
  264. "friendly_name": friendly_name,
  265. "state": entity.get("state"),
  266. "domain": domain,
  267. }
  268. )
  269. return sorted(entities, key=lambda x: x["friendly_name"].lower())
  270. except Exception as e:
  271. logger.warning("Failed to list HA entities: %s", e)
  272. return []
  273. async def list_sensor_entities(self, url: str, token: str) -> list[dict]:
  274. """List available sensor entities for energy monitoring.
  275. Returns list of sensor entities with power/energy units.
  276. """
  277. try:
  278. async with httpx.AsyncClient(timeout=self.timeout) as client:
  279. response = await client.get(
  280. f"{url.rstrip('/')}/api/states",
  281. headers={"Authorization": f"Bearer {token}"},
  282. )
  283. response.raise_for_status()
  284. # Valid units for energy monitoring sensors (lowercase for case-insensitive matching)
  285. power_units = {"w", "kw", "mw"}
  286. energy_units = {"kwh", "wh", "mwh"}
  287. valid_units = power_units | energy_units
  288. entities = []
  289. for entity in response.json():
  290. entity_id = entity.get("entity_id", "")
  291. domain = entity_id.split(".")[0] if "." in entity_id else ""
  292. # Filter to sensor domain only
  293. if domain != "sensor":
  294. continue
  295. attrs = entity.get("attributes", {})
  296. unit = attrs.get("unit_of_measurement", "")
  297. # Only include sensors with power/energy units (case-insensitive)
  298. if unit.lower() in valid_units:
  299. entities.append(
  300. {
  301. "entity_id": entity_id,
  302. "friendly_name": attrs.get("friendly_name", entity_id),
  303. "state": entity.get("state"),
  304. "unit_of_measurement": unit,
  305. }
  306. )
  307. return sorted(entities, key=lambda x: x["friendly_name"].lower())
  308. except Exception as e:
  309. logger.warning("Failed to list HA sensor entities: %s", e)
  310. return []
  311. async def list_display_entities(self, url: str, token: str, search: str | None = None) -> list[dict]:
  312. """List entities that can be bound to a printer for display (#1148, #448).
  313. Covers every ``binary_sensor.*`` plus the ``sensor.*`` entities that
  314. carry a reading. Distinct from ``list_sensor_entities``, which exists
  315. for a plug's energy monitoring and therefore only admits power/energy
  316. units — an enclosure thermometer is exactly what that one filters out.
  317. A ``sensor.*`` qualifies when it has a unit or its state parses as a
  318. number. That drops the text sensors (``sensor.washing_machine_status``)
  319. that the card has no way to render as a value.
  320. """
  321. try:
  322. async with httpx.AsyncClient(timeout=self.timeout) as client:
  323. response = await client.get(
  324. f"{url.rstrip('/')}/api/states",
  325. headers={"Authorization": f"Bearer {token}"},
  326. )
  327. response.raise_for_status()
  328. entities = []
  329. search_lower = search.lower().strip() if search else None
  330. for entity in response.json():
  331. entity_id = entity.get("entity_id", "")
  332. domain = entity_id.split(".")[0] if "." in entity_id else ""
  333. if domain not in ("binary_sensor", "sensor"):
  334. continue
  335. attrs = entity.get("attributes", {})
  336. unit = attrs.get("unit_of_measurement")
  337. state = entity.get("state")
  338. if domain == "sensor" and not unit and as_float(state) is None:
  339. continue
  340. friendly_name = attrs.get("friendly_name") or entity_id
  341. if search_lower and (
  342. search_lower not in entity_id.lower() and search_lower not in friendly_name.lower()
  343. ):
  344. continue
  345. entities.append(
  346. {
  347. "entity_id": entity_id,
  348. "friendly_name": friendly_name,
  349. "state": state,
  350. "domain": domain,
  351. "device_class": attrs.get("device_class"),
  352. "unit_of_measurement": unit,
  353. }
  354. )
  355. return sorted(entities, key=lambda x: x["friendly_name"].lower())
  356. except Exception as e:
  357. logger.warning("Failed to list HA display entities: %s", e)
  358. return []
  359. async def fetch_states(self, entity_ids: list[str]) -> dict[str, dict | None]:
  360. """Read several entities in one pass, keyed by entity_id.
  361. One GET per entity over a shared client rather than a single
  362. ``/api/states`` sweep: the poller only ever wants a handful of bound
  363. entities, and pulling every state in the user's Home Assistant on a
  364. 15-second cadence is a lot of payload to throw away.
  365. A ``None`` value means that entity could not be read — the callers
  366. treat that as "no opinion" rather than as a state, so an unreachable
  367. Home Assistant never trips an alert or holds a print.
  368. """
  369. if not entity_ids:
  370. return {}
  371. if not self.base_url or not self.token:
  372. return dict.fromkeys(entity_ids)
  373. async with httpx.AsyncClient(timeout=self.timeout) as client:
  374. async def _one(entity_id: str) -> tuple[str, dict | None]:
  375. try:
  376. response = await client.get(
  377. f"{self.base_url}/api/states/{entity_id}",
  378. headers=self._headers(),
  379. )
  380. response.raise_for_status()
  381. return entity_id, response.json()
  382. except Exception as e:
  383. logger.debug("Failed to read HA entity %s: %s", entity_id, e)
  384. return entity_id, None
  385. results = await asyncio.gather(*(_one(e) for e in entity_ids))
  386. return dict(results)
  387. def as_float(value) -> float | None:
  388. """Parse a HA state to a number, or None for "unknown"/"unavailable"/text."""
  389. try:
  390. return float(value)
  391. except (TypeError, ValueError):
  392. return None
  393. # Singleton instance
  394. homeassistant_service = HomeAssistantService()