tasmota.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 and link-local IPs."""
  21. try:
  22. addr = ipaddress.ip_address(ip)
  23. except ValueError:
  24. return False # Not a valid IP
  25. return not addr.is_loopback and not addr.is_link_local
  26. async def _send_command(
  27. self,
  28. ip: str,
  29. command: str,
  30. username: str | None = None,
  31. password: str | None = None,
  32. ) -> dict | None:
  33. """Send a command to a Tasmota device and return the response."""
  34. if not self._validate_ip(ip):
  35. logger.warning("Blocked Tasmota request to invalid IP: %s", ip)
  36. return None
  37. url = self._build_url(ip, command)
  38. auth = (username, password) if username and password else None
  39. try:
  40. async with httpx.AsyncClient(timeout=self.timeout) as client:
  41. response = await client.get(url, auth=auth)
  42. response.raise_for_status()
  43. return response.json()
  44. except httpx.TimeoutException:
  45. logger.warning("Tasmota device at %s timed out", ip)
  46. return None
  47. except httpx.HTTPStatusError as e:
  48. logger.warning("Tasmota device at %s returned error: %s", ip, e)
  49. return None
  50. except httpx.RequestError as e:
  51. logger.warning("Failed to connect to Tasmota device at %s: %s", ip, e)
  52. return None
  53. except Exception as e:
  54. logger.error("Unexpected error communicating with Tasmota at %s: %s", ip, e)
  55. return None
  56. async def get_status(self, plug: "SmartPlug") -> dict:
  57. """Get current power state and device info.
  58. Returns dict with:
  59. - state: "ON" or "OFF" or None if unreachable
  60. - reachable: bool
  61. - device_name: str or None
  62. """
  63. result = await self._send_command(plug.ip_address, "Power", plug.username, plug.password)
  64. if result is None:
  65. return {"state": None, "reachable": False, "device_name": None}
  66. # Response format: {"POWER":"ON"} or {"POWER":"OFF"}
  67. # Some devices use {"POWER1":"ON"} for multi-relay
  68. state = None
  69. for key in ["POWER", "POWER1"]:
  70. if key in result:
  71. state = result[key]
  72. break
  73. return {"state": state, "reachable": True, "device_name": None}
  74. async def turn_on(self, plug: "SmartPlug") -> bool:
  75. """Turn on the plug. Returns True if successful."""
  76. result = await self._send_command(plug.ip_address, "Power On", plug.username, plug.password)
  77. if result is None:
  78. return False
  79. # Check if the command was successful
  80. state = result.get("POWER") or result.get("POWER1")
  81. success = state == "ON"
  82. if success:
  83. logger.info("Turned ON smart plug '%s' at %s", plug.name, plug.ip_address)
  84. else:
  85. logger.warning("Failed to turn ON smart plug '%s' at %s", plug.name, plug.ip_address)
  86. return success
  87. async def turn_off(self, plug: "SmartPlug") -> bool:
  88. """Turn off the plug. Returns True if successful."""
  89. result = await self._send_command(plug.ip_address, "Power Off", plug.username, plug.password)
  90. if result is None:
  91. return False
  92. # Check if the command was successful
  93. state = result.get("POWER") or result.get("POWER1")
  94. success = state == "OFF"
  95. if success:
  96. logger.info("Turned OFF smart plug '%s' at %s", plug.name, plug.ip_address)
  97. else:
  98. logger.warning("Failed to turn OFF smart plug '%s' at %s", plug.name, plug.ip_address)
  99. return success
  100. async def toggle(self, plug: "SmartPlug") -> bool:
  101. """Toggle the plug state. Returns True if successful."""
  102. result = await self._send_command(plug.ip_address, "Power Toggle", plug.username, plug.password)
  103. if result is None:
  104. return False
  105. state = result.get("POWER") or result.get("POWER1")
  106. success = state in ["ON", "OFF"]
  107. if success:
  108. logger.info("Toggled smart plug '%s' at %s to %s", plug.name, plug.ip_address, state)
  109. return success
  110. async def get_energy(self, plug: "SmartPlug") -> dict | None:
  111. """Get energy monitoring data from the plug.
  112. Returns dict with energy data or None if not available:
  113. - power: Current power in watts
  114. - voltage: Voltage in V
  115. - current: Current in A
  116. - today: Energy used today in kWh
  117. - total: Total energy in kWh
  118. - factor: Power factor (0-1)
  119. """
  120. result = await self._send_command(plug.ip_address, "Status 8", plug.username, plug.password)
  121. if result is None:
  122. return None
  123. # Response format: {"StatusSNS":{"ENERGY":{...}}}
  124. status_sns = result.get("StatusSNS", {})
  125. energy = status_sns.get("ENERGY")
  126. if not energy:
  127. # Device doesn't have energy monitoring
  128. return None
  129. return {
  130. "power": energy.get("Power"), # Current watts
  131. "voltage": energy.get("Voltage"), # Volts
  132. "current": energy.get("Current"), # Amps
  133. "today": energy.get("Today"), # kWh today
  134. "yesterday": energy.get("Yesterday"), # kWh yesterday
  135. "total": energy.get("Total"), # Total kWh
  136. "factor": energy.get("Factor"), # Power factor
  137. "apparent_power": energy.get("ApparentPower"), # VA
  138. "reactive_power": energy.get("ReactivePower"), # VAr
  139. }
  140. async def test_connection(
  141. self,
  142. ip: str,
  143. username: str | None = None,
  144. password: str | None = None,
  145. ) -> dict:
  146. """Test connection to a Tasmota device.
  147. Returns dict with:
  148. - success: bool
  149. - state: current power state or None
  150. - device_name: device name or None
  151. - error: error message if failed
  152. """
  153. # Try to get power status
  154. result = await self._send_command(ip, "Power", username, password)
  155. if result is None:
  156. return {
  157. "success": False,
  158. "state": None,
  159. "device_name": None,
  160. "error": "Could not connect to device",
  161. }
  162. state = result.get("POWER") or result.get("POWER1")
  163. # Try to get device name
  164. status_result = await self._send_command(ip, "Status 0", username, password)
  165. device_name = None
  166. if status_result and "Status" in status_result:
  167. device_name = status_result["Status"].get("DeviceName")
  168. return {
  169. "success": True,
  170. "state": state,
  171. "device_name": device_name,
  172. "error": None,
  173. }
  174. # Singleton instance
  175. tasmota_service = TasmotaService()