smart_plug_manager.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """Manager for smart plug automation and delayed turn-off."""
  2. import asyncio
  3. import logging
  4. from datetime import datetime
  5. from typing import TYPE_CHECKING
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from sqlalchemy import select
  8. from backend.app.services.tasmota import tasmota_service
  9. from backend.app.services.printer_manager import printer_manager
  10. if TYPE_CHECKING:
  11. from backend.app.models.smart_plug import SmartPlug
  12. logger = logging.getLogger(__name__)
  13. class SmartPlugManager:
  14. """Manages smart plug automation and delayed turn-off."""
  15. def __init__(self):
  16. self._pending_off: dict[int, asyncio.Task] = {} # plug_id -> task
  17. self._loop: asyncio.AbstractEventLoop | None = None
  18. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  19. """Set the event loop for async operations."""
  20. self._loop = loop
  21. async def _get_plug_for_printer(
  22. self, printer_id: int, db: AsyncSession
  23. ) -> "SmartPlug | None":
  24. """Get the smart plug linked to a printer."""
  25. from backend.app.models.smart_plug import SmartPlug
  26. result = await db.execute(
  27. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  28. )
  29. return result.scalar_one_or_none()
  30. async def on_print_start(self, printer_id: int, db: AsyncSession):
  31. """Called when a print starts - turn on plug if configured."""
  32. plug = await self._get_plug_for_printer(printer_id, db)
  33. if not plug:
  34. return
  35. if not plug.enabled:
  36. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-on")
  37. return
  38. if not plug.auto_on:
  39. logger.debug(f"Smart plug '{plug.name}' auto_on is disabled")
  40. return
  41. # Cancel any pending off task
  42. self._cancel_pending_off(plug.id)
  43. # Turn on the plug
  44. logger.info(f"Print started on printer {printer_id}, turning on plug '{plug.name}'")
  45. success = await tasmota_service.turn_on(plug)
  46. if success:
  47. # Update last state
  48. plug.last_state = "ON"
  49. plug.last_checked = datetime.utcnow()
  50. await db.commit()
  51. async def on_print_complete(
  52. self, printer_id: int, status: str, db: AsyncSession
  53. ):
  54. """Called when a print completes - schedule turn off if configured."""
  55. plug = await self._get_plug_for_printer(printer_id, db)
  56. if not plug:
  57. return
  58. if not plug.enabled:
  59. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-off")
  60. return
  61. if not plug.auto_off:
  62. logger.debug(f"Smart plug '{plug.name}' auto_off is disabled")
  63. return
  64. logger.info(
  65. f"Print completed on printer {printer_id} (status: {status}), "
  66. f"scheduling turn-off for plug '{plug.name}'"
  67. )
  68. if plug.off_delay_mode == "time":
  69. self._schedule_delayed_off(plug, plug.off_delay_minutes * 60)
  70. elif plug.off_delay_mode == "temperature":
  71. self._schedule_temp_based_off(plug, printer_id, plug.off_temp_threshold)
  72. def _schedule_delayed_off(self, plug: "SmartPlug", delay_seconds: int):
  73. """Schedule turn-off after delay."""
  74. # Cancel any existing task for this plug
  75. self._cancel_pending_off(plug.id)
  76. logger.info(
  77. f"Scheduling turn-off for plug '{plug.name}' in {delay_seconds} seconds"
  78. )
  79. task = asyncio.create_task(
  80. self._delayed_off(plug.id, plug.ip_address, plug.username, plug.password, delay_seconds)
  81. )
  82. self._pending_off[plug.id] = task
  83. async def _delayed_off(
  84. self,
  85. plug_id: int,
  86. ip_address: str,
  87. username: str | None,
  88. password: str | None,
  89. delay_seconds: int,
  90. ):
  91. """Wait and turn off."""
  92. try:
  93. await asyncio.sleep(delay_seconds)
  94. # Create a minimal plug-like object for the tasmota service
  95. class PlugInfo:
  96. def __init__(self):
  97. self.ip_address = ip_address
  98. self.username = username
  99. self.password = password
  100. self.name = f"plug_{plug_id}"
  101. plug_info = PlugInfo()
  102. await tasmota_service.turn_off(plug_info)
  103. logger.info(f"Turned off plug {plug_id} after time delay")
  104. except asyncio.CancelledError:
  105. logger.debug(f"Delayed turn-off cancelled for plug {plug_id}")
  106. finally:
  107. self._pending_off.pop(plug_id, None)
  108. def _schedule_temp_based_off(
  109. self, plug: "SmartPlug", printer_id: int, temp_threshold: int
  110. ):
  111. """Monitor temperature and turn off when below threshold."""
  112. # Cancel any existing task for this plug
  113. self._cancel_pending_off(plug.id)
  114. logger.info(
  115. f"Scheduling temperature-based turn-off for plug '{plug.name}' "
  116. f"(threshold: {temp_threshold}°C)"
  117. )
  118. task = asyncio.create_task(
  119. self._temp_based_off(
  120. plug.id,
  121. plug.ip_address,
  122. plug.username,
  123. plug.password,
  124. printer_id,
  125. temp_threshold,
  126. )
  127. )
  128. self._pending_off[plug.id] = task
  129. async def _temp_based_off(
  130. self,
  131. plug_id: int,
  132. ip_address: str,
  133. username: str | None,
  134. password: str | None,
  135. printer_id: int,
  136. temp_threshold: int,
  137. ):
  138. """Poll temperature until below threshold, then turn off.
  139. For dual-extruder printers (H2 series), checks both nozzles.
  140. """
  141. try:
  142. check_interval = 10 # seconds
  143. max_wait = 3600 # 1 hour max
  144. elapsed = 0
  145. while elapsed < max_wait:
  146. status = printer_manager.get_status(printer_id)
  147. if status:
  148. temps = status.temperatures or {}
  149. nozzle_temp = temps.get("nozzle", 999)
  150. # Check second nozzle for dual-extruder printers (H2 series)
  151. nozzle_2_temp = temps.get("nozzle_2")
  152. # Get the maximum temperature across all nozzles
  153. max_nozzle_temp = nozzle_temp
  154. if nozzle_2_temp is not None:
  155. max_nozzle_temp = max(nozzle_temp, nozzle_2_temp)
  156. logger.debug(
  157. f"Checking temp for plug {plug_id}: nozzle1={nozzle_temp}°C, "
  158. f"nozzle2={nozzle_2_temp}°C, max={max_nozzle_temp}°C, "
  159. f"threshold={temp_threshold}°C"
  160. )
  161. else:
  162. logger.debug(
  163. f"Checking temp for plug {plug_id}: nozzle={nozzle_temp}°C, "
  164. f"threshold={temp_threshold}°C"
  165. )
  166. if max_nozzle_temp < temp_threshold:
  167. # All nozzles are below threshold, turn off
  168. class PlugInfo:
  169. def __init__(self):
  170. self.ip_address = ip_address
  171. self.username = username
  172. self.password = password
  173. self.name = f"plug_{plug_id}"
  174. plug_info = PlugInfo()
  175. await tasmota_service.turn_off(plug_info)
  176. logger.info(
  177. f"Turned off plug {plug_id} after nozzle temp dropped to "
  178. f"{max_nozzle_temp}°C (threshold: {temp_threshold}°C)"
  179. )
  180. break
  181. await asyncio.sleep(check_interval)
  182. elapsed += check_interval
  183. if elapsed >= max_wait:
  184. logger.warning(
  185. f"Temperature-based turn-off timed out for plug {plug_id} after {max_wait}s"
  186. )
  187. except asyncio.CancelledError:
  188. logger.debug(f"Temperature-based turn-off cancelled for plug {plug_id}")
  189. finally:
  190. self._pending_off.pop(plug_id, None)
  191. def _cancel_pending_off(self, plug_id: int):
  192. """Cancel any pending off task for this plug."""
  193. if plug_id in self._pending_off:
  194. logger.debug(f"Cancelling pending turn-off for plug {plug_id}")
  195. self._pending_off[plug_id].cancel()
  196. del self._pending_off[plug_id]
  197. def cancel_all_pending(self):
  198. """Cancel all pending turn-off tasks."""
  199. for plug_id in list(self._pending_off.keys()):
  200. self._cancel_pending_off(plug_id)
  201. # Global singleton
  202. smart_plug_manager = SmartPlugManager()