tasmota.py 7.3 KB

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