tasmota.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. """Service for communicating with Tasmota devices via HTTP API."""
  2. import ipaddress
  3. import logging
  4. from typing import TYPE_CHECKING
  5. import httpx
  6. if TYPE_CHECKING:
  7. from backend.app.models.smart_plug import SmartPlug
  8. logger = logging.getLogger(__name__)
  9. class TasmotaService:
  10. """Service for communicating with Tasmota devices via HTTP API."""
  11. def __init__(self, timeout: float = 5.0):
  12. self.timeout = timeout
  13. def _build_url(self, ip: str, command: str) -> str:
  14. """Build Tasmota command URL."""
  15. # URL encode the command
  16. cmd = command.replace(" ", "%20")
  17. return f"http://{ip}/cm?cmnd={cmd}"
  18. @staticmethod
  19. def _validate_ip(ip: str) -> bool:
  20. """Block cloud metadata, loopback and link-local destinations.
  21. Deliberately stricter than the shared LAN-service guard, and kept that
  22. way: a Tasmota plug is always a separate device on the LAN, so a bare
  23. IP literal is the only sensible value. Anything that is not one —
  24. including a symbolic hostname — still fails closed here, which is why
  25. this does not simply delegate to ``assert_safe_lan_service_url``.
  26. What it borrows from the shared guard is the destination set that is
  27. dangerous under any topology: cloud-metadata endpoints beyond the AWS
  28. IPv4 address (Alibaba's 100.100.100.200, AWS's fd00:ec2::254),
  29. multicast and unspecified addresses, and IPv4-mapped IPv6 encodings
  30. used to smuggle any of the above past the per-class checks.
  31. """
  32. from backend.app.api.routes._url_safety import CLOUD_METADATA_IPS, unwrap_ipv4_mapped
  33. try:
  34. addr = ipaddress.ip_address(ip)
  35. except ValueError:
  36. return False # Not a valid IP
  37. effective = unwrap_ipv4_mapped(addr)
  38. if effective in CLOUD_METADATA_IPS:
  39. return False
  40. if effective.is_multicast or effective.is_unspecified:
  41. return False
  42. return not effective.is_loopback and not effective.is_link_local
  43. async def _send_command(
  44. self,
  45. ip: str,
  46. command: str,
  47. username: str | None = None,
  48. password: str | None = None,
  49. ) -> dict | None:
  50. """Send a command to a Tasmota device and return the response."""
  51. if not self._validate_ip(ip):
  52. logger.warning("Blocked Tasmota request to invalid IP: %s", ip)
  53. return None
  54. url = self._build_url(ip, command)
  55. auth = (username, password) if username and password else None
  56. try:
  57. async with httpx.AsyncClient(timeout=self.timeout) as client:
  58. response = await client.get(url, auth=auth)
  59. response.raise_for_status()
  60. return response.json()
  61. except httpx.TimeoutException:
  62. logger.warning("Tasmota device at %s timed out", ip)
  63. return None
  64. except httpx.HTTPStatusError as e:
  65. logger.warning("Tasmota device at %s returned error: %s", ip, e)
  66. return None
  67. except httpx.RequestError as e:
  68. logger.warning("Failed to connect to Tasmota device at %s: %s", ip, e)
  69. return None
  70. except Exception as e:
  71. logger.error("Unexpected error communicating with Tasmota at %s: %s", ip, e)
  72. return None
  73. async def get_status(self, plug: "SmartPlug") -> dict:
  74. """Get current power state and device info.
  75. Returns dict with:
  76. - state: "ON" or "OFF" or None if unreachable
  77. - reachable: bool
  78. - device_name: str or None
  79. """
  80. result = await self._send_command(plug.ip_address, "Power", plug.username, plug.password)
  81. if result is None:
  82. return {"state": None, "reachable": False, "device_name": None}
  83. # Response format: {"POWER":"ON"} or {"POWER":"OFF"}
  84. # Some devices use {"POWER1":"ON"} for multi-relay
  85. state = None
  86. for key in ["POWER", "POWER1"]:
  87. if key in result:
  88. state = result[key]
  89. break
  90. return {"state": state, "reachable": True, "device_name": None}
  91. async def turn_on(self, plug: "SmartPlug") -> bool:
  92. """Turn on the plug. Returns True if successful."""
  93. result = await self._send_command(plug.ip_address, "Power On", plug.username, plug.password)
  94. if result is None:
  95. return False
  96. # Check if the command was successful
  97. state = result.get("POWER") or result.get("POWER1")
  98. success = state == "ON"
  99. if success:
  100. logger.info("Turned ON smart plug '%s' at %s", plug.name, plug.ip_address)
  101. else:
  102. logger.warning("Failed to turn ON smart plug '%s' at %s", plug.name, plug.ip_address)
  103. return success
  104. async def turn_off(self, plug: "SmartPlug") -> bool:
  105. """Turn off the plug. Returns True if successful."""
  106. result = await self._send_command(plug.ip_address, "Power Off", plug.username, plug.password)
  107. if result is None:
  108. return False
  109. # Check if the command was successful
  110. state = result.get("POWER") or result.get("POWER1")
  111. success = state == "OFF"
  112. if success:
  113. logger.info("Turned OFF smart plug '%s' at %s", plug.name, plug.ip_address)
  114. else:
  115. logger.warning("Failed to turn OFF smart plug '%s' at %s", plug.name, plug.ip_address)
  116. return success
  117. async def toggle(self, plug: "SmartPlug") -> bool:
  118. """Toggle the plug state. Returns True if successful."""
  119. result = await self._send_command(plug.ip_address, "Power Toggle", plug.username, plug.password)
  120. if result is None:
  121. return False
  122. state = result.get("POWER") or result.get("POWER1")
  123. success = state in ["ON", "OFF"]
  124. if success:
  125. logger.info("Toggled smart plug '%s' at %s to %s", plug.name, plug.ip_address, state)
  126. return success
  127. async def get_energy(self, plug: "SmartPlug") -> dict | None:
  128. """Get energy monitoring data from the plug.
  129. Returns dict with energy data or None if not available:
  130. - power: Current power in watts
  131. - voltage: Voltage in V
  132. - current: Current in A
  133. - today: Energy used today in kWh
  134. - total: Total energy in kWh
  135. - factor: Power factor (0-1)
  136. """
  137. result = await self._send_command(plug.ip_address, "Status 8", plug.username, plug.password)
  138. if result is None:
  139. return None
  140. # Response format: {"StatusSNS":{"ENERGY":{...}}}
  141. status_sns = result.get("StatusSNS", {})
  142. energy = status_sns.get("ENERGY")
  143. if not energy:
  144. # Device doesn't have energy monitoring
  145. return None
  146. return {
  147. "power": energy.get("Power"), # Current watts
  148. "voltage": energy.get("Voltage"), # Volts
  149. "current": energy.get("Current"), # Amps
  150. "today": energy.get("Today"), # kWh today
  151. "yesterday": energy.get("Yesterday"), # kWh yesterday
  152. "total": energy.get("Total"), # Total kWh
  153. "factor": energy.get("Factor"), # Power factor
  154. "apparent_power": energy.get("ApparentPower"), # VA
  155. "reactive_power": energy.get("ReactivePower"), # VAr
  156. }
  157. async def test_connection(
  158. self,
  159. ip: str,
  160. username: str | None = None,
  161. password: str | None = None,
  162. ) -> dict:
  163. """Test connection to a Tasmota device.
  164. Returns dict with:
  165. - success: bool
  166. - state: current power state or None
  167. - device_name: device name or None
  168. - error: error message if failed
  169. """
  170. # Try to get power status
  171. result = await self._send_command(ip, "Power", username, password)
  172. if result is None:
  173. return {
  174. "success": False,
  175. "state": None,
  176. "device_name": None,
  177. "error": "Could not connect to device",
  178. }
  179. state = result.get("POWER") or result.get("POWER1")
  180. # Try to get device name
  181. status_result = await self._send_command(ip, "Status 0", username, password)
  182. device_name = None
  183. if status_result and "Status" in status_result:
  184. device_name = status_result["Status"].get("DeviceName")
  185. return {
  186. "success": True,
  187. "state": state,
  188. "device_name": device_name,
  189. "error": None,
  190. }
  191. # Singleton instance
  192. tasmota_service = TasmotaService()