smart_plug_manager.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 import select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from backend.app.services.printer_manager import printer_manager
  9. from backend.app.services.tasmota import tasmota_service
  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.is_(True),
  52. SmartPlug.schedule_enabled.is_(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(self, printer_id: int, db: AsyncSession) -> "SmartPlug | None":
  82. """Get the smart plug linked to a printer."""
  83. from backend.app.models.smart_plug import SmartPlug
  84. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  85. return result.scalar_one_or_none()
  86. async def on_print_start(self, printer_id: int, db: AsyncSession):
  87. """Called when a print starts - turn on plug if configured."""
  88. plug = await self._get_plug_for_printer(printer_id, db)
  89. if not plug:
  90. return
  91. if not plug.enabled:
  92. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-on")
  93. return
  94. if not plug.auto_on:
  95. logger.debug(f"Smart plug '{plug.name}' auto_on is disabled")
  96. return
  97. # Cancel any pending off task
  98. self._cancel_pending_off(plug.id)
  99. # Turn on the plug
  100. logger.info(f"Print started on printer {printer_id}, turning on plug '{plug.name}'")
  101. success = await tasmota_service.turn_on(plug)
  102. if success:
  103. # Update last state and reset auto_off_executed
  104. plug.last_state = "ON"
  105. plug.last_checked = datetime.utcnow()
  106. plug.auto_off_executed = False # Reset flag when turning on
  107. await db.commit()
  108. async def on_print_complete(self, printer_id: int, status: str, db: AsyncSession):
  109. """Called when a print completes - schedule turn off if configured.
  110. Only triggers auto-off on successful completion (status='completed').
  111. Failed prints keep the printer powered on for user investigation.
  112. """
  113. plug = await self._get_plug_for_printer(printer_id, db)
  114. if not plug:
  115. return
  116. if not plug.enabled:
  117. logger.debug(f"Smart plug '{plug.name}' is disabled, skipping auto-off")
  118. return
  119. if not plug.auto_off:
  120. logger.debug(f"Smart plug '{plug.name}' auto_off is disabled")
  121. return
  122. # Only auto-off on successful completion, not on failures
  123. # This allows the user to investigate errors before power-off
  124. if status != "completed":
  125. logger.info(
  126. f"Print on printer {printer_id} ended with status '{status}', "
  127. f"skipping auto-off for plug '{plug.name}' to allow investigation"
  128. )
  129. return
  130. logger.info(f"Print completed successfully on printer {printer_id}, scheduling turn-off for plug '{plug.name}'")
  131. if plug.off_delay_mode == "time":
  132. self._schedule_delayed_off(plug, printer_id, plug.off_delay_minutes * 60)
  133. elif plug.off_delay_mode == "temperature":
  134. self._schedule_temp_based_off(plug, printer_id, plug.off_temp_threshold)
  135. def _schedule_delayed_off(self, plug: "SmartPlug", printer_id: int, delay_seconds: int):
  136. """Schedule turn-off after delay."""
  137. # Cancel any existing task for this plug
  138. self._cancel_pending_off(plug.id)
  139. logger.info(f"Scheduling turn-off for plug '{plug.name}' in {delay_seconds} seconds")
  140. # Mark as pending in database (survives restarts)
  141. asyncio.create_task(self._mark_auto_off_pending(plug.id, True))
  142. task = asyncio.create_task(
  143. self._delayed_off(plug.id, plug.ip_address, plug.username, plug.password, printer_id, delay_seconds)
  144. )
  145. self._pending_off[plug.id] = task
  146. async def _delayed_off(
  147. self,
  148. plug_id: int,
  149. ip_address: str,
  150. username: str | None,
  151. password: str | None,
  152. printer_id: int,
  153. delay_seconds: int,
  154. ):
  155. """Wait and turn off."""
  156. try:
  157. await asyncio.sleep(delay_seconds)
  158. # Create a minimal plug-like object for the tasmota service
  159. class PlugInfo:
  160. def __init__(self):
  161. self.ip_address = ip_address
  162. self.username = username
  163. self.password = password
  164. self.name = f"plug_{plug_id}"
  165. plug_info = PlugInfo()
  166. success = await tasmota_service.turn_off(plug_info)
  167. logger.info(f"Turned off plug {plug_id} after time delay")
  168. # Mark auto_off_executed in database and update printer status
  169. if success:
  170. await self._mark_auto_off_executed(plug_id)
  171. # Mark the printer as offline immediately
  172. printer_manager.mark_printer_offline(printer_id)
  173. except asyncio.CancelledError:
  174. logger.debug(f"Delayed turn-off cancelled for plug {plug_id}")
  175. finally:
  176. self._pending_off.pop(plug_id, None)
  177. def _schedule_temp_based_off(self, plug: "SmartPlug", printer_id: int, temp_threshold: int):
  178. """Monitor temperature and turn off when below threshold."""
  179. # Cancel any existing task for this plug
  180. self._cancel_pending_off(plug.id)
  181. logger.info(f"Scheduling temperature-based turn-off for plug '{plug.name}' (threshold: {temp_threshold}°C)")
  182. # Mark as pending in database (survives restarts)
  183. asyncio.create_task(self._mark_auto_off_pending(plug.id, True))
  184. task = asyncio.create_task(
  185. self._temp_based_off(
  186. plug.id,
  187. plug.ip_address,
  188. plug.username,
  189. plug.password,
  190. printer_id,
  191. temp_threshold,
  192. )
  193. )
  194. self._pending_off[plug.id] = task
  195. async def _temp_based_off(
  196. self,
  197. plug_id: int,
  198. ip_address: str,
  199. username: str | None,
  200. password: str | None,
  201. printer_id: int,
  202. temp_threshold: int,
  203. ):
  204. """Poll temperature until below threshold, then turn off.
  205. For dual-extruder printers (H2 series), checks both nozzles.
  206. """
  207. try:
  208. check_interval = 10 # seconds
  209. max_wait = 3600 # 1 hour max
  210. elapsed = 0
  211. while elapsed < max_wait:
  212. status = printer_manager.get_status(printer_id)
  213. if status:
  214. temps = status.temperatures or {}
  215. nozzle_temp = temps.get("nozzle", 999)
  216. # Check second nozzle for dual-extruder printers (H2 series)
  217. nozzle_2_temp = temps.get("nozzle_2")
  218. # Get the maximum temperature across all nozzles
  219. max_nozzle_temp = nozzle_temp
  220. if nozzle_2_temp is not None:
  221. max_nozzle_temp = max(nozzle_temp, nozzle_2_temp)
  222. logger.info(
  223. f"Temp check plug {plug_id}: nozzle1={nozzle_temp}°C, "
  224. f"nozzle2={nozzle_2_temp}°C, max={max_nozzle_temp}°C, "
  225. f"threshold={temp_threshold}°C"
  226. )
  227. else:
  228. logger.info(f"Temp check plug {plug_id}: nozzle={nozzle_temp}°C, threshold={temp_threshold}°C")
  229. if max_nozzle_temp < temp_threshold:
  230. # All nozzles are below threshold, turn off
  231. class PlugInfo:
  232. def __init__(self):
  233. self.ip_address = ip_address
  234. self.username = username
  235. self.password = password
  236. self.name = f"plug_{plug_id}"
  237. plug_info = PlugInfo()
  238. success = await tasmota_service.turn_off(plug_info)
  239. logger.info(
  240. f"Turned off plug {plug_id} after nozzle temp dropped to "
  241. f"{max_nozzle_temp}°C (threshold: {temp_threshold}°C)"
  242. )
  243. # Mark auto_off_executed in database and update printer status
  244. if success:
  245. await self._mark_auto_off_executed(plug_id)
  246. # Mark the printer as offline immediately
  247. printer_manager.mark_printer_offline(printer_id)
  248. break
  249. await asyncio.sleep(check_interval)
  250. elapsed += check_interval
  251. if elapsed >= max_wait:
  252. logger.warning(f"Temperature-based turn-off timed out for plug {plug_id} after {max_wait}s")
  253. except asyncio.CancelledError:
  254. logger.debug(f"Temperature-based turn-off cancelled for plug {plug_id}")
  255. finally:
  256. self._pending_off.pop(plug_id, None)
  257. async def _mark_auto_off_pending(self, plug_id: int, pending: bool):
  258. """Mark a plug as having a pending auto-off (survives restarts)."""
  259. try:
  260. from backend.app.core.database import async_session
  261. from backend.app.models.smart_plug import SmartPlug
  262. async with async_session() as db:
  263. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  264. plug = result.scalar_one_or_none()
  265. if plug:
  266. plug.auto_off_pending = pending
  267. plug.auto_off_pending_since = datetime.utcnow() if pending else None
  268. await db.commit()
  269. logger.debug(f"Marked plug {plug_id} auto_off_pending={pending}")
  270. except Exception as e:
  271. logger.warning(f"Failed to update plug {plug_id} pending state: {e}")
  272. async def _mark_auto_off_executed(self, plug_id: int):
  273. """Disable auto-off after it was executed (one-shot behavior)."""
  274. try:
  275. from backend.app.core.database import async_session
  276. from backend.app.models.smart_plug import SmartPlug
  277. async with async_session() as db:
  278. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  279. plug = result.scalar_one_or_none()
  280. if plug:
  281. plug.auto_off = False # Disable auto-off (one-shot behavior)
  282. plug.auto_off_executed = False # Reset the flag
  283. plug.auto_off_pending = False # Clear pending state
  284. plug.auto_off_pending_since = None
  285. plug.last_state = "OFF"
  286. plug.last_checked = datetime.utcnow()
  287. await db.commit()
  288. logger.info(f"Auto-off executed and disabled for plug {plug_id}")
  289. except Exception as e:
  290. logger.warning(f"Failed to update plug {plug_id} after auto-off: {e}")
  291. def _cancel_pending_off(self, plug_id: int):
  292. """Cancel any pending off task for this plug."""
  293. if plug_id in self._pending_off:
  294. logger.debug(f"Cancelling pending turn-off for plug {plug_id}")
  295. self._pending_off[plug_id].cancel()
  296. del self._pending_off[plug_id]
  297. # Clear pending state in database
  298. asyncio.create_task(self._mark_auto_off_pending(plug_id, False))
  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. async def resume_pending_auto_offs(self):
  304. """Resume any pending auto-offs that were interrupted by a restart.
  305. Called on startup to check for plugs that had auto-off pending but
  306. never completed (e.g., due to service restart).
  307. """
  308. try:
  309. from backend.app.core.database import async_session
  310. from backend.app.models.smart_plug import SmartPlug
  311. async with async_session() as db:
  312. # Find all plugs with pending auto-off
  313. result = await db.execute(
  314. select(SmartPlug).where(
  315. SmartPlug.auto_off_pending.is_(True),
  316. SmartPlug.printer_id.isnot(None),
  317. )
  318. )
  319. pending_plugs = result.scalars().all()
  320. for plug in pending_plugs:
  321. # Check how long it's been pending (timeout after 2 hours)
  322. if plug.auto_off_pending_since:
  323. elapsed = (datetime.utcnow() - plug.auto_off_pending_since).total_seconds()
  324. if elapsed > 7200: # 2 hours
  325. logger.warning(
  326. f"Auto-off for plug '{plug.name}' was pending for {elapsed / 60:.0f} minutes, "
  327. f"clearing stale pending state"
  328. )
  329. plug.auto_off_pending = False
  330. plug.auto_off_pending_since = None
  331. await db.commit()
  332. continue
  333. logger.info(f"Resuming pending auto-off for plug '{plug.name}' (printer {plug.printer_id})")
  334. # Resume the appropriate off mode
  335. if plug.off_delay_mode == "temperature":
  336. self._schedule_temp_based_off(plug, plug.printer_id, plug.off_temp_threshold)
  337. else:
  338. # For time mode, just turn off immediately since delay already passed
  339. logger.info(f"Time-based auto-off was pending, turning off plug '{plug.name}' now")
  340. class PlugInfo:
  341. def __init__(self, p):
  342. self.ip_address = p.ip_address
  343. self.username = p.username
  344. self.password = p.password
  345. self.name = p.name
  346. success = await tasmota_service.turn_off(PlugInfo(plug))
  347. if success:
  348. await self._mark_auto_off_executed(plug.id)
  349. printer_manager.mark_printer_offline(plug.printer_id)
  350. if pending_plugs:
  351. logger.info(f"Resumed {len(pending_plugs)} pending auto-off(s)")
  352. except Exception as e:
  353. logger.warning(f"Failed to resume pending auto-offs: {e}")
  354. # Global singleton
  355. smart_plug_manager = SmartPlugManager()