tasmota.py 7.6 KB

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