smart_plug_manager.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. self._scheduler_task: asyncio.Task | None = None
  19. self._last_schedule_check: dict[int, str] = {} # plug_id -> "HH:MM" last executed
  20. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  21. """Set the event loop for async operations."""
  22. self._loop = loop
  23. def start_scheduler(self):
  24. """Start the background scheduler for time-based plug control."""
  25. if self._scheduler_task is None:
  26. self._scheduler_task = asyncio.create_task(self._schedule_loop())
  27. logger.info("Smart plug scheduler started")
  28. def stop_scheduler(self):
  29. """Stop the background scheduler."""
  30. if self._scheduler_task:
  31. self._scheduler_task.cancel()
  32. self._scheduler_task = None
  33. logger.info("Smart plug scheduler stopped")
  34. async def _schedule_loop(self):
  35. """Background loop that checks scheduled on/off times every minute."""
  36. while True:
  37. try:
  38. await self._check_schedules()
  39. except Exception as e:
  40. logger.error(f"Error in schedule check: {e}")
  41. # Wait until the next minute
  42. await asyncio.sleep(60)
  43. async def _check_schedules(self):
  44. """Check all plugs for scheduled on/off times."""
  45. from backend.app.core.database import async_session
  46. from backend.app.models.smart_plug import SmartPlug
  47. current_time = datetime.now().strftime("%H:%M")
  48. async with async_session() as db:
  49. result = await db.execute(
  50. select(SmartPlug).where(
  51. SmartPlug.enabled == True,
  52. SmartPlug.schedule_enabled == True,
  53. )
  54. )
  55. plugs = result.scalars().all()
  56. for plug in plugs:
  57. # Check if we should turn on
  58. if plug.schedule_on_time == current_time:
  59. last_check = self._last_schedule_check.get(plug.id)
  60. if last_check != f"on:{current_time}":
  61. logger.info(f"Schedule: Turning on plug '{plug.name}' at {current_time}")
  62. success = await tasmota_service.turn_on(plug)
  63. if success:
  64. plug.last_state = "ON"
  65. plug.last_checked = datetime.utcnow()
  66. self._last_schedule_check[plug.id] = f"on:{current_time}"
  67. # Check if we should turn off
  68. if plug.schedule_off_time == current_time:
  69. last_check = self._last_schedule_check.get(plug.id)
  70. if last_check != f"off:{current_time}":
  71. logger.info(f"Schedule: Turning off plug '{plug.name}' at {current_time}")
  72. success = await tasmota_service.turn_off(plug)
  73. if success:
  74. plug.last_state = "OFF"
  75. plug.last_checked = datetime.utcnow()
  76. self._last_schedule_check[plug.id] = f"off:{current_time}"
  77. # Mark printer offline if linked
  78. if plug.printer_id:
  79. printer_manager.mark_printer_offline(plug.printer_id)
  80. await db.commit()
  81. async def _get_plug_for_printer(
  82. self, printer_id: int, db: AsyncSession
  83. ) -> "SmartPlug | None":
  84. """Get the smart plug linked to a printer."""
  85. from backend.app.models.smart_plug import SmartPlug
  86. result = await db.execute(
  87. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  88. )
  89. return result.scalar_one_or_none()
  90. async def on_print_start(self, printer_id: int, db: AsyncSession):
  91. """Called when a print starts - turn on plug if configured."""
  92. plug = await self._get_plug_for_printer(printer_id, db)
  93. if not plug:
  94. return
  95. if not plug.enabled:
  96. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-on")
  97. return
  98. if not plug.auto_on:
  99. logger.debug(f"Smart plug '{plug.name}' auto_on is disabled")
  100. return
  101. # Cancel any pending off task
  102. self._cancel_pending_off(plug.id)
  103. # Turn on the plug
  104. logger.info(f"Print started on printer {printer_id}, turning on plug '{plug.name}'")
  105. success = await tasmota_service.turn_on(plug)
  106. if success:
  107. # Update last state and reset auto_off_executed
  108. plug.last_state = "ON"
  109. plug.last_checked = datetime.utcnow()
  110. plug.auto_off_executed = False # Reset flag when turning on
  111. await db.commit()
  112. async def on_print_complete(
  113. self, printer_id: int, status: str, db: AsyncSession
  114. ):
  115. """Called when a print completes - schedule turn off if configured.
  116. Only triggers auto-off on successful completion (status='completed').
  117. Failed prints keep the printer powered on for user investigation.
  118. """
  119. plug = await self._get_plug_for_printer(printer_id, db)
  120. if not plug:
  121. return
  122. if not plug.enabled:
  123. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-off")
  124. return
  125. if not plug.auto_off:
  126. logger.debug(f"Smart plug '{plug.name}' auto_off is disabled")
  127. return
  128. # Only auto-off on successful completion, not on failures
  129. # This allows the user to investigate errors before power-off
  130. if status != "completed":
  131. logger.info(
  132. f"Print on printer {printer_id} ended with status '{status}', "
  133. f"skipping auto-off for plug '{plug.name}' to allow investigation"
  134. )
  135. return
  136. logger.info(
  137. f"Print completed successfully on printer {printer_id}, "
  138. f"scheduling turn-off for plug '{plug.name}'"
  139. )
  140. if plug.off_delay_mode == "time":
  141. self._schedule_delayed_off(plug, printer_id, plug.off_delay_minutes * 60)
  142. elif plug.off_delay_mode == "temperature":
  143. self._schedule_temp_based_off(plug, printer_id, plug.off_temp_threshold)
  144. def _schedule_delayed_off(self, plug: "SmartPlug", printer_id: int, delay_seconds: int):
  145. """Schedule turn-off after delay."""
  146. # Cancel any existing task for this plug
  147. self._cancel_pending_off(plug.id)
  148. logger.info(
  149. f"Scheduling turn-off for plug '{plug.name}' in {delay_seconds} seconds"
  150. )
  151. task = asyncio.create_task(
  152. self._delayed_off(plug.id, plug.ip_address, plug.username, plug.password, printer_id, delay_seconds)
  153. )
  154. self._pending_off[plug.id] = task
  155. async def _delayed_off(
  156. self,
  157. plug_id: int,
  158. ip_address: str,
  159. username: str | None,
  160. password: str | None,
  161. printer_id: int,
  162. delay_seconds: int,
  163. ):
  164. """Wait and turn off."""
  165. try:
  166. await asyncio.sleep(delay_seconds)
  167. # Create a minimal plug-like object for the tasmota service
  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. success = await tasmota_service.turn_off(plug_info)
  176. logger.info(f"Turned off plug {plug_id} after time delay")
  177. # Mark auto_off_executed in database and update printer status
  178. if success:
  179. await self._mark_auto_off_executed(plug_id)
  180. # Mark the printer as offline immediately
  181. printer_manager.mark_printer_offline(printer_id)
  182. except asyncio.CancelledError:
  183. logger.debug(f"Delayed turn-off cancelled for plug {plug_id}")
  184. finally:
  185. self._pending_off.pop(plug_id, None)
  186. def _schedule_temp_based_off(
  187. self, plug: "SmartPlug", printer_id: int, temp_threshold: int
  188. ):
  189. """Monitor temperature and turn off when below threshold."""
  190. # Cancel any existing task for this plug
  191. self._cancel_pending_off(plug.id)
  192. logger.info(
  193. f"Scheduling temperature-based turn-off for plug '{plug.name}' "
  194. f"(threshold: {temp_threshold}°C)"
  195. )
  196. task = asyncio.create_task(
  197. self._temp_based_off(
  198. plug.id,
  199. plug.ip_address,
  200. plug.username,
  201. plug.password,
  202. printer_id,
  203. temp_threshold,
  204. )
  205. )
  206. self._pending_off[plug.id] = task
  207. async def _temp_based_off(
  208. self,
  209. plug_id: int,
  210. ip_address: str,
  211. username: str | None,
  212. password: str | None,
  213. printer_id: int,
  214. temp_threshold: int,
  215. ):
  216. """Poll temperature until below threshold, then turn off.
  217. For dual-extruder printers (H2 series), checks both nozzles.
  218. """
  219. try:
  220. check_interval = 10 # seconds
  221. max_wait = 3600 # 1 hour max
  222. elapsed = 0
  223. while elapsed < max_wait:
  224. status = printer_manager.get_status(printer_id)
  225. if status:
  226. temps = status.temperatures or {}
  227. nozzle_temp = temps.get("nozzle", 999)
  228. # Check second nozzle for dual-extruder printers (H2 series)
  229. nozzle_2_temp = temps.get("nozzle_2")
  230. # Get the maximum temperature across all nozzles
  231. max_nozzle_temp = nozzle_temp
  232. if nozzle_2_temp is not None:
  233. max_nozzle_temp = max(nozzle_temp, nozzle_2_temp)
  234. logger.info(
  235. f"Temp check plug {plug_id}: nozzle1={nozzle_temp}°C, "
  236. f"nozzle2={nozzle_2_temp}°C, max={max_nozzle_temp}°C, "
  237. f"threshold={temp_threshold}°C"
  238. )
  239. else:
  240. logger.info(
  241. f"Temp check plug {plug_id}: nozzle={nozzle_temp}°C, "
  242. f"threshold={temp_threshold}°C"
  243. )
  244. if max_nozzle_temp < temp_threshold:
  245. # All nozzles are below threshold, turn off
  246. class PlugInfo:
  247. def __init__(self):
  248. self.ip_address = ip_address
  249. self.username = username
  250. self.password = password
  251. self.name = f"plug_{plug_id}"
  252. plug_info = PlugInfo()
  253. success = await tasmota_service.turn_off(plug_info)
  254. logger.info(
  255. f"Turned off plug {plug_id} after nozzle temp dropped to "
  256. f"{max_nozzle_temp}°C (threshold: {temp_threshold}°C)"
  257. )
  258. # Mark auto_off_executed in database and update printer status
  259. if success:
  260. await self._mark_auto_off_executed(plug_id)
  261. # Mark the printer as offline immediately
  262. printer_manager.mark_printer_offline(printer_id)
  263. break
  264. await asyncio.sleep(check_interval)
  265. elapsed += check_interval
  266. if elapsed >= max_wait:
  267. logger.warning(
  268. f"Temperature-based turn-off timed out for plug {plug_id} after {max_wait}s"
  269. )
  270. except asyncio.CancelledError:
  271. logger.debug(f"Temperature-based turn-off cancelled for plug {plug_id}")
  272. finally:
  273. self._pending_off.pop(plug_id, None)
  274. async def _mark_auto_off_executed(self, plug_id: int):
  275. """Disable auto-off after it was executed (one-shot behavior)."""
  276. try:
  277. from backend.app.core.database import async_session
  278. from backend.app.models.smart_plug import SmartPlug
  279. async with async_session() as db:
  280. result = await db.execute(
  281. select(SmartPlug).where(SmartPlug.id == plug_id)
  282. )
  283. plug = result.scalar_one_or_none()
  284. if plug:
  285. plug.auto_off = False # Disable auto-off (one-shot behavior)
  286. plug.auto_off_executed = False # Reset the flag
  287. plug.last_state = "OFF"
  288. plug.last_checked = datetime.utcnow()
  289. await db.commit()
  290. logger.info(f"Auto-off executed and disabled for plug {plug_id}")
  291. except Exception as e:
  292. logger.warning(f"Failed to update plug {plug_id} after auto-off: {e}")
  293. def _cancel_pending_off(self, plug_id: int):
  294. """Cancel any pending off task for this plug."""
  295. if plug_id in self._pending_off:
  296. logger.debug(f"Cancelling pending turn-off for plug {plug_id}")
  297. self._pending_off[plug_id].cancel()
  298. del self._pending_off[plug_id]
  299. def cancel_all_pending(self):
  300. """Cancel all pending turn-off tasks."""
  301. for plug_id in list(self._pending_off.keys()):
  302. self._cancel_pending_off(plug_id)
  303. # Global singleton
  304. smart_plug_manager = SmartPlugManager()