tasmota.py 7.1 KB

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