smart_plug_manager.py 18 KB

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