smart_plug_manager.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. Only triggers auto-off on successful completion (status='completed').
  56. Failed prints keep the printer powered on for user investigation.
  57. """
  58. plug = await self._get_plug_for_printer(printer_id, db)
  59. if not plug:
  60. return
  61. if not plug.enabled:
  62. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-off")
  63. return
  64. if not plug.auto_off:
  65. logger.debug(f"Smart plug '{plug.name}' auto_off is disabled")
  66. return
  67. # Only auto-off on successful completion, not on failures
  68. # This allows the user to investigate errors before power-off
  69. if status != "completed":
  70. logger.info(
  71. f"Print on printer {printer_id} ended with status '{status}', "
  72. f"skipping auto-off for plug '{plug.name}' to allow investigation"
  73. )
  74. return
  75. logger.info(
  76. f"Print completed successfully on printer {printer_id}, "
  77. f"scheduling turn-off for plug '{plug.name}'"
  78. )
  79. if plug.off_delay_mode == "time":
  80. self._schedule_delayed_off(plug, plug.off_delay_minutes * 60)
  81. elif plug.off_delay_mode == "temperature":
  82. self._schedule_temp_based_off(plug, printer_id, plug.off_temp_threshold)
  83. def _schedule_delayed_off(self, plug: "SmartPlug", delay_seconds: int):
  84. """Schedule turn-off after delay."""
  85. # Cancel any existing task for this plug
  86. self._cancel_pending_off(plug.id)
  87. logger.info(
  88. f"Scheduling turn-off for plug '{plug.name}' in {delay_seconds} seconds"
  89. )
  90. task = asyncio.create_task(
  91. self._delayed_off(plug.id, plug.ip_address, plug.username, plug.password, delay_seconds)
  92. )
  93. self._pending_off[plug.id] = task
  94. async def _delayed_off(
  95. self,
  96. plug_id: int,
  97. ip_address: str,
  98. username: str | None,
  99. password: str | None,
  100. delay_seconds: int,
  101. ):
  102. """Wait and turn off."""
  103. try:
  104. await asyncio.sleep(delay_seconds)
  105. # Create a minimal plug-like object for the tasmota service
  106. class PlugInfo:
  107. def __init__(self):
  108. self.ip_address = ip_address
  109. self.username = username
  110. self.password = password
  111. self.name = f"plug_{plug_id}"
  112. plug_info = PlugInfo()
  113. await tasmota_service.turn_off(plug_info)
  114. logger.info(f"Turned off plug {plug_id} after time delay")
  115. except asyncio.CancelledError:
  116. logger.debug(f"Delayed turn-off cancelled for plug {plug_id}")
  117. finally:
  118. self._pending_off.pop(plug_id, None)
  119. def _schedule_temp_based_off(
  120. self, plug: "SmartPlug", printer_id: int, temp_threshold: int
  121. ):
  122. """Monitor temperature and turn off when below threshold."""
  123. # Cancel any existing task for this plug
  124. self._cancel_pending_off(plug.id)
  125. logger.info(
  126. f"Scheduling temperature-based turn-off for plug '{plug.name}' "
  127. f"(threshold: {temp_threshold}°C)"
  128. )
  129. task = asyncio.create_task(
  130. self._temp_based_off(
  131. plug.id,
  132. plug.ip_address,
  133. plug.username,
  134. plug.password,
  135. printer_id,
  136. temp_threshold,
  137. )
  138. )
  139. self._pending_off[plug.id] = task
  140. async def _temp_based_off(
  141. self,
  142. plug_id: int,
  143. ip_address: str,
  144. username: str | None,
  145. password: str | None,
  146. printer_id: int,
  147. temp_threshold: int,
  148. ):
  149. """Poll temperature until below threshold, then turn off.
  150. For dual-extruder printers (H2 series), checks both nozzles.
  151. """
  152. try:
  153. check_interval = 10 # seconds
  154. max_wait = 3600 # 1 hour max
  155. elapsed = 0
  156. while elapsed < max_wait:
  157. status = printer_manager.get_status(printer_id)
  158. if status:
  159. temps = status.temperatures or {}
  160. nozzle_temp = temps.get("nozzle", 999)
  161. # Check second nozzle for dual-extruder printers (H2 series)
  162. nozzle_2_temp = temps.get("nozzle_2")
  163. # Get the maximum temperature across all nozzles
  164. max_nozzle_temp = nozzle_temp
  165. if nozzle_2_temp is not None:
  166. max_nozzle_temp = max(nozzle_temp, nozzle_2_temp)
  167. logger.info(
  168. f"Temp check plug {plug_id}: nozzle1={nozzle_temp}°C, "
  169. f"nozzle2={nozzle_2_temp}°C, max={max_nozzle_temp}°C, "
  170. f"threshold={temp_threshold}°C"
  171. )
  172. else:
  173. logger.info(
  174. f"Temp check plug {plug_id}: nozzle={nozzle_temp}°C, "
  175. f"threshold={temp_threshold}°C"
  176. )
  177. if max_nozzle_temp < temp_threshold:
  178. # All nozzles are below threshold, turn off
  179. class PlugInfo:
  180. def __init__(self):
  181. self.ip_address = ip_address
  182. self.username = username
  183. self.password = password
  184. self.name = f"plug_{plug_id}"
  185. plug_info = PlugInfo()
  186. await tasmota_service.turn_off(plug_info)
  187. logger.info(
  188. f"Turned off plug {plug_id} after nozzle temp dropped to "
  189. f"{max_nozzle_temp}°C (threshold: {temp_threshold}°C)"
  190. )
  191. break
  192. await asyncio.sleep(check_interval)
  193. elapsed += check_interval
  194. if elapsed >= max_wait:
  195. logger.warning(
  196. f"Temperature-based turn-off timed out for plug {plug_id} after {max_wait}s"
  197. )
  198. except asyncio.CancelledError:
  199. logger.debug(f"Temperature-based turn-off cancelled for plug {plug_id}")
  200. finally:
  201. self._pending_off.pop(plug_id, None)
  202. def _cancel_pending_off(self, plug_id: int):
  203. """Cancel any pending off task for this plug."""
  204. if plug_id in self._pending_off:
  205. logger.debug(f"Cancelling pending turn-off for plug {plug_id}")
  206. self._pending_off[plug_id].cancel()
  207. del self._pending_off[plug_id]
  208. def cancel_all_pending(self):
  209. """Cancel all pending turn-off tasks."""
  210. for plug_id in list(self._pending_off.keys()):
  211. self._cancel_pending_off(plug_id)
  212. # Global singleton
  213. smart_plug_manager = SmartPlugManager()