rest_smart_plug.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. """Service for controlling smart plugs via generic REST/HTTP API."""
  2. import json
  3. import logging
  4. from typing import TYPE_CHECKING, Any
  5. import httpx
  6. if TYPE_CHECKING:
  7. from backend.app.models.smart_plug import SmartPlug
  8. logger = logging.getLogger(__name__)
  9. class RESTSmartPlugService:
  10. """Service for controlling smart plugs via generic REST/HTTP API.
  11. Supports any home automation platform with an HTTP API (openHAB, ioBroker, FHEM, Node-RED, etc.).
  12. """
  13. def __init__(self, timeout: float = 10.0):
  14. self.timeout = timeout
  15. @staticmethod
  16. def _url_error(url: str) -> str | None:
  17. """Return why *url* is rejected by the LAN-service policy, else None.
  18. Split out from ``_validate_url`` so ``test_connection`` can tell the
  19. user which rule the URL broke instead of a single fixed sentence.
  20. """
  21. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  22. try:
  23. assert_safe_lan_service_url(url, label="REST plug URL")
  24. except ValueError as exc:
  25. return str(exc)
  26. return None
  27. @staticmethod
  28. def _validate_url(url: str) -> bool:
  29. """Apply the shared LAN-service SSRF policy to a REST plug URL.
  30. Delegates to ``_url_safety.assert_safe_lan_service_url`` — the same
  31. guard Spoolman, the notification providers and the LAN-service
  32. settings use — rather than reimplementing a narrower check. The
  33. hand-rolled version this replaces got the policy wrong in both
  34. directions: it rejected a literal ``127.0.0.1`` (so an openHAB or
  35. Node-RED instance on the same host could only be reached by spelling
  36. it ``localhost``), while allowing every target the shared policy
  37. rejects unconditionally — Alibaba/AWS-IPv6 metadata endpoints,
  38. numeric-encoded IPs, multicast and the unspecified address — because
  39. anything that wasn't a bare IP literal fell through to ``True``.
  40. Loopback and RFC-1918 stay permitted on purpose: a REST-controlled
  41. plug bridge running next to Bambuddy is the normal topology.
  42. """
  43. return RESTSmartPlugService._url_error(url) is None
  44. def _parse_headers(self, headers_json: str | None) -> dict[str, str]:
  45. """Parse JSON string to dict of headers."""
  46. if not headers_json:
  47. return {}
  48. try:
  49. headers = json.loads(headers_json)
  50. if isinstance(headers, dict):
  51. return {str(k): str(v) for k, v in headers.items()}
  52. except (json.JSONDecodeError, TypeError):
  53. logger.warning("Failed to parse REST headers JSON: %s", headers_json)
  54. return {}
  55. @staticmethod
  56. def _extract_json_path(data: Any, path: str) -> Any:
  57. """Extract value using dot notation (e.g., 'state' or 'data.power.status')."""
  58. if not path:
  59. return None
  60. parts = path.split(".")
  61. current = data
  62. for part in parts:
  63. if isinstance(current, dict) and part in current:
  64. current = current[part]
  65. else:
  66. return None
  67. return current
  68. async def _send_request(
  69. self,
  70. url: str,
  71. method: str = "POST",
  72. headers: dict[str, str] | None = None,
  73. body: str | None = None,
  74. ) -> httpx.Response | None:
  75. """Send an HTTP request and return the response."""
  76. if not self._validate_url(url):
  77. logger.warning("Blocked REST request to invalid URL: %s", url)
  78. return None
  79. try:
  80. async with httpx.AsyncClient(timeout=self.timeout) as client:
  81. kwargs: dict[str, Any] = {"headers": headers or {}}
  82. if body is not None:
  83. # Try to detect if body is JSON
  84. try:
  85. json.loads(body)
  86. kwargs["content"] = body
  87. if "Content-Type" not in (headers or {}):
  88. kwargs["headers"]["Content-Type"] = "application/json"
  89. except (json.JSONDecodeError, TypeError):
  90. kwargs["content"] = body
  91. response = await client.request(method.upper(), url, **kwargs)
  92. response.raise_for_status()
  93. return response
  94. except httpx.TimeoutException:
  95. logger.warning("REST smart plug at %s timed out", url)
  96. return None
  97. except httpx.HTTPStatusError as e:
  98. logger.warning("REST smart plug at %s returned error: %s", url, e)
  99. return None
  100. except httpx.RequestError as e:
  101. logger.warning("Failed to connect to REST smart plug at %s: %s", url, e)
  102. return None
  103. except Exception as e:
  104. logger.error("Unexpected error communicating with REST smart plug at %s: %s", url, e)
  105. return None
  106. async def turn_on(self, plug: "SmartPlug") -> bool:
  107. """Turn on the plug. Returns True if successful."""
  108. if not plug.rest_on_url:
  109. logger.warning("No ON URL configured for REST plug '%s'", plug.name)
  110. return False
  111. headers = self._parse_headers(plug.rest_headers)
  112. method = plug.rest_method or "POST"
  113. response = await self._send_request(plug.rest_on_url, method, headers, plug.rest_on_body)
  114. if response is not None:
  115. logger.info("Turned ON REST smart plug '%s' via %s %s", plug.name, method, plug.rest_on_url)
  116. return True
  117. logger.warning("Failed to turn ON REST smart plug '%s'", plug.name)
  118. return False
  119. async def turn_off(self, plug: "SmartPlug") -> bool:
  120. """Turn off the plug. Returns True if successful."""
  121. if not plug.rest_off_url:
  122. logger.warning("No OFF URL configured for REST plug '%s'", plug.name)
  123. return False
  124. headers = self._parse_headers(plug.rest_headers)
  125. method = plug.rest_method or "POST"
  126. response = await self._send_request(plug.rest_off_url, method, headers, plug.rest_off_body)
  127. if response is not None:
  128. logger.info("Turned OFF REST smart plug '%s' via %s %s", plug.name, method, plug.rest_off_url)
  129. return True
  130. logger.warning("Failed to turn OFF REST smart plug '%s'", plug.name)
  131. return False
  132. async def toggle(self, plug: "SmartPlug") -> bool:
  133. """Toggle the plug state by checking status first."""
  134. status = await self.get_status(plug)
  135. if status["state"] == "ON":
  136. return await self.turn_off(plug)
  137. else:
  138. return await self.turn_on(plug)
  139. async def get_status(self, plug: "SmartPlug") -> dict:
  140. """Get current power state.
  141. Returns dict with:
  142. - state: "ON" or "OFF" or None if unreachable
  143. - reachable: bool
  144. - device_name: None (REST plugs don't report device names)
  145. """
  146. if not plug.rest_status_url:
  147. return {"state": None, "reachable": True, "device_name": None}
  148. headers = self._parse_headers(plug.rest_headers)
  149. response = await self._send_request(plug.rest_status_url, "GET", headers)
  150. if response is None:
  151. return {"state": None, "reachable": False, "device_name": None}
  152. # Try to extract state from response
  153. state = None
  154. try:
  155. data = response.json()
  156. if plug.rest_status_path:
  157. raw_value = self._extract_json_path(data, plug.rest_status_path)
  158. if raw_value is not None:
  159. on_value = (plug.rest_status_on_value or "ON").upper()
  160. state = "ON" if str(raw_value).upper() == on_value else "OFF"
  161. else:
  162. # No path configured — try common patterns
  163. raw_value = str(data).upper() if not isinstance(data, dict) else None
  164. if raw_value in ("ON", "TRUE", "1"):
  165. state = "ON"
  166. elif raw_value in ("OFF", "FALSE", "0"):
  167. state = "OFF"
  168. except Exception:
  169. # Response is not JSON — try raw text
  170. text = response.text.strip().upper()
  171. on_value = (plug.rest_status_on_value or "ON").upper()
  172. state = "ON" if text == on_value else "OFF"
  173. return {"state": state, "reachable": True, "device_name": None}
  174. async def get_energy(self, plug: "SmartPlug") -> dict | None:
  175. """Get energy monitoring data.
  176. Each value can come from its own URL or fall back to the shared status URL.
  177. Multipliers convert units (e.g. Wh → kWh with multiplier 0.001).
  178. Two distinct energy counters, because devices differ in which they have
  179. (#2539):
  180. - ``rest_energy_path`` — energy used **today**, resetting at midnight.
  181. - ``rest_energy_total_path`` — a **lifetime** counter that never resets.
  182. A Shelly exposes only this one (``aenergy.total``, in Wh). Reading it as
  183. "today" is wrong all day long, and leaves Total and the hourly snapshots
  184. — which the Statistics page's date filters run on — permanently empty.
  185. Yesterday is not read from the device: no REST device we know of reports
  186. it. It is derived from the lifetime counter's snapshots instead, in
  187. ``services.plug_energy_history``.
  188. Returns dict with energy data or None if not available.
  189. """
  190. if not plug.rest_power_path and not plug.rest_energy_path and not plug.rest_energy_total_path:
  191. return None
  192. headers = self._parse_headers(plug.rest_headers)
  193. energy: dict[str, float | None] = {}
  194. power_url = plug.rest_power_url or plug.rest_status_url if plug.rest_power_path else None
  195. energy_url = plug.rest_energy_url or plug.rest_status_url if plug.rest_energy_path else None
  196. # The lifetime counter almost always rides on the same response as the
  197. # today counter (one Shelly RPC call returns both `apower` and
  198. # `aenergy.total`), so it shares the energy URL and the dedupe below
  199. # collapses them into a single fetch.
  200. total_url = plug.rest_energy_url or plug.rest_status_url if plug.rest_energy_total_path else None
  201. # Fetch data — deduplicate when several resolve to the same URL
  202. fetched: dict[str, Any] = {}
  203. for url in {power_url, energy_url, total_url} - {None}:
  204. fetched[url] = await self._fetch_json(url, headers)
  205. def _read(path: str | None, url: str | None, multiplier: float | None) -> float | None:
  206. if not path or not url or fetched.get(url) is None:
  207. return None
  208. raw = self._extract_json_path(fetched[url], path)
  209. if raw is None:
  210. return None
  211. try:
  212. return float(raw) * (multiplier or 1.0)
  213. except (ValueError, TypeError):
  214. return None
  215. power = _read(plug.rest_power_path, power_url, plug.rest_power_multiplier)
  216. if power is not None:
  217. energy["power"] = power
  218. today = _read(plug.rest_energy_path, energy_url, plug.rest_energy_multiplier)
  219. if today is not None:
  220. energy["today"] = today
  221. total = _read(plug.rest_energy_total_path, total_url, plug.rest_energy_total_multiplier)
  222. if total is not None:
  223. energy["total"] = total
  224. return energy if energy else None
  225. async def _fetch_json(self, url: str, headers: dict[str, str]) -> Any:
  226. """Fetch a URL and parse JSON response. Returns parsed data or None."""
  227. response = await self._send_request(url, "GET", headers)
  228. if response is None:
  229. return None
  230. try:
  231. return response.json()
  232. except Exception:
  233. return None
  234. async def test_connection(self, url: str, method: str = "GET", headers: str | None = None) -> dict:
  235. """Test connection to a REST endpoint.
  236. Returns dict with:
  237. - success: bool
  238. - error: error message if failed
  239. """
  240. url_error = self._url_error(url)
  241. if url_error:
  242. return {"success": False, "error": url_error}
  243. parsed_headers = self._parse_headers(headers)
  244. try:
  245. async with httpx.AsyncClient(timeout=self.timeout) as client:
  246. response = await client.request(method.upper(), url, headers=parsed_headers)
  247. response.raise_for_status()
  248. return {"success": True, "error": None}
  249. except httpx.TimeoutException:
  250. return {"success": False, "error": "Connection timed out"}
  251. except httpx.HTTPStatusError as e:
  252. return {"success": False, "error": f"HTTP {e.response.status_code}: {e.response.reason_phrase}"}
  253. except httpx.RequestError as e:
  254. return {"success": False, "error": f"Connection failed: {e}"}
  255. except Exception as e:
  256. return {"success": False, "error": str(e)}
  257. # Singleton instance
  258. rest_smart_plug_service = RESTSmartPlugService()