tasmota.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 test_connection(
  122. self,
  123. ip: str,
  124. username: str | None = None,
  125. password: str | None = None,
  126. ) -> dict:
  127. """Test connection to a Tasmota device.
  128. Returns dict with:
  129. - success: bool
  130. - state: current power state or None
  131. - device_name: device name or None
  132. - error: error message if failed
  133. """
  134. # Try to get power status
  135. result = await self._send_command(ip, "Power", username, password)
  136. if result is None:
  137. return {
  138. "success": False,
  139. "state": None,
  140. "device_name": None,
  141. "error": "Could not connect to device",
  142. }
  143. state = result.get("POWER") or result.get("POWER1")
  144. # Try to get device name
  145. status_result = await self._send_command(ip, "Status 0", username, password)
  146. device_name = None
  147. if status_result and "Status" in status_result:
  148. device_name = status_result["Status"].get("DeviceName")
  149. return {
  150. "success": True,
  151. "state": state,
  152. "device_name": device_name,
  153. "error": None,
  154. }
  155. # Singleton instance
  156. tasmota_service = TasmotaService()