homeassistant.py 15 KB

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