smart_plug_manager.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. """Manager for smart plug automation and delayed turn-off."""
  2. import asyncio
  3. import logging
  4. from datetime import datetime, timezone
  5. from typing import TYPE_CHECKING
  6. from sqlalchemy import select
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from backend.app.services.homeassistant import homeassistant_service
  9. from backend.app.services.printer_manager import printer_manager
  10. from backend.app.services.tasmota import tasmota_service
  11. if TYPE_CHECKING:
  12. from backend.app.models.smart_plug import SmartPlug
  13. logger = logging.getLogger(__name__)
  14. class SmartPlugManager:
  15. """Manages smart plug automation and delayed turn-off."""
  16. def __init__(self):
  17. self._pending_off: dict[int, asyncio.Task] = {} # plug_id -> task
  18. self._loop: asyncio.AbstractEventLoop | None = None
  19. self._scheduler_task: asyncio.Task | None = None
  20. self._last_schedule_check: dict[int, str] = {} # plug_id -> "HH:MM" last executed
  21. async def get_service_for_plug(self, plug: "SmartPlug", db: AsyncSession | None = None):
  22. """Get the appropriate service for the plug type.
  23. For HA plugs, configures the service with current settings from DB.
  24. """
  25. if plug.plug_type == "homeassistant":
  26. # Configure HA service with current settings
  27. await self._configure_ha_service(db)
  28. return homeassistant_service
  29. return tasmota_service
  30. async def _configure_ha_service(self, db: AsyncSession | None = None):
  31. """Configure the HA service with URL and token from settings."""
  32. from backend.app.api.routes.settings import get_homeassistant_settings
  33. try:
  34. if db:
  35. # Use provided session
  36. ha_settings = await get_homeassistant_settings(db)
  37. else:
  38. # Create new session
  39. from backend.app.core.database import async_session
  40. async with async_session() as session:
  41. ha_settings = await get_homeassistant_settings(session)
  42. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  43. except Exception as e:
  44. logger.warning("Failed to configure HA service: %s", e)
  45. def set_event_loop(self, loop: asyncio.AbstractEventLoop):
  46. """Set the event loop for async operations."""
  47. self._loop = loop
  48. def start_scheduler(self):
  49. """Start the background scheduler for time-based plug control."""
  50. if self._scheduler_task is None:
  51. self._scheduler_task = asyncio.create_task(self._schedule_loop())
  52. logger.info("Smart plug scheduler started")
  53. def stop_scheduler(self):
  54. """Stop the background scheduler."""
  55. if self._scheduler_task:
  56. self._scheduler_task.cancel()
  57. self._scheduler_task = None
  58. logger.info("Smart plug scheduler stopped")
  59. async def _schedule_loop(self):
  60. """Background loop that checks scheduled on/off times every minute."""
  61. while True:
  62. try:
  63. await self._check_schedules()
  64. except Exception as e:
  65. logger.error("Error in schedule check: %s", e)
  66. # Wait until the next minute
  67. await asyncio.sleep(60)
  68. async def _check_schedules(self):
  69. """Check all plugs for scheduled on/off times."""
  70. from backend.app.core.database import async_session
  71. from backend.app.models.smart_plug import SmartPlug
  72. current_time = datetime.now().strftime("%H:%M")
  73. async with async_session() as db:
  74. result = await db.execute(
  75. select(SmartPlug).where(
  76. SmartPlug.enabled.is_(True),
  77. SmartPlug.schedule_enabled.is_(True),
  78. )
  79. )
  80. plugs = result.scalars().all()
  81. for plug in plugs:
  82. service = await self.get_service_for_plug(plug, db)
  83. # Check if we should turn on
  84. if plug.schedule_on_time == current_time:
  85. last_check = self._last_schedule_check.get(plug.id)
  86. if last_check != f"on:{current_time}":
  87. logger.info("Schedule: Turning on plug '%s' at %s", plug.name, current_time)
  88. success = await service.turn_on(plug)
  89. if success:
  90. plug.last_state = "ON"
  91. plug.last_checked = datetime.now(timezone.utc)
  92. self._last_schedule_check[plug.id] = f"on:{current_time}"
  93. # Check if we should turn off
  94. if plug.schedule_off_time == current_time:
  95. last_check = self._last_schedule_check.get(plug.id)
  96. if last_check != f"off:{current_time}":
  97. logger.info("Schedule: Turning off plug '%s' at %s", plug.name, current_time)
  98. success = await service.turn_off(plug)
  99. if success:
  100. plug.last_state = "OFF"
  101. plug.last_checked = datetime.now(timezone.utc)
  102. self._last_schedule_check[plug.id] = f"off:{current_time}"
  103. # Mark printer offline if linked
  104. if plug.printer_id:
  105. printer_manager.mark_printer_offline(plug.printer_id)
  106. await db.commit()
  107. async def _get_plug_for_printer(self, printer_id: int, db: AsyncSession) -> "SmartPlug | None":
  108. """Get the main (non-script) smart plug linked to a printer.
  109. When multiple plugs are assigned (e.g., a power plug + secondary HA switch),
  110. returns the main power plug for automation control.
  111. """
  112. from backend.app.models.smart_plug import SmartPlug
  113. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  114. plugs = result.scalars().all()
  115. if not plugs:
  116. return None
  117. # Prefer non-script, non-secondary plugs (main power plug)
  118. for plug in plugs:
  119. is_script = (
  120. plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script.")
  121. )
  122. if not is_script:
  123. return plug
  124. # All are scripts, return the first one
  125. return plugs[0]
  126. async def on_print_start(self, printer_id: int, db: AsyncSession):
  127. """Called when a print starts - turn on plug if configured."""
  128. plug = await self._get_plug_for_printer(printer_id, db)
  129. if not plug:
  130. return
  131. if not plug.enabled:
  132. logger.debug("Smart plug '%s' is disabled, skipping auto-on", plug.name)
  133. return
  134. if not plug.auto_on:
  135. logger.debug("Smart plug '%s' auto_on is disabled", plug.name)
  136. return
  137. # Cancel any pending off task
  138. self._cancel_pending_off(plug.id)
  139. # Turn on the plug
  140. logger.info("Print started on printer %s, turning on plug '%s'", printer_id, plug.name)
  141. service = await self.get_service_for_plug(plug, db)
  142. success = await service.turn_on(plug)
  143. if success:
  144. # Update last state and reset auto_off_executed
  145. plug.last_state = "ON"
  146. plug.last_checked = datetime.now(timezone.utc)
  147. plug.auto_off_executed = False # Reset flag when turning on
  148. await db.commit()
  149. async def on_print_complete(self, printer_id: int, status: str, db: AsyncSession):
  150. """Called when a print completes - schedule turn off if configured.
  151. Only triggers auto-off on successful completion (status='completed').
  152. Failed prints keep the printer powered on for user investigation.
  153. """
  154. plug = await self._get_plug_for_printer(printer_id, db)
  155. if not plug:
  156. return
  157. if not plug.enabled:
  158. logger.debug("Smart plug '%s' is disabled, skipping auto-off", plug.name)
  159. return
  160. if not plug.auto_off:
  161. logger.debug("Smart plug '%s' auto_off is disabled", plug.name)
  162. return
  163. # Skip auto-off for HA script entities (scripts can only be triggered, not turned off)
  164. if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
  165. logger.debug("Smart plug '%s' is a HA script entity, skipping auto-off", plug.name)
  166. return
  167. # Only auto-off on successful completion, not on failures
  168. # This allows the user to investigate errors before power-off
  169. if status != "completed":
  170. logger.info(
  171. f"Print on printer {printer_id} ended with status '{status}', "
  172. f"skipping auto-off for plug '{plug.name}' to allow investigation"
  173. )
  174. return
  175. logger.info(
  176. "Print completed successfully on printer %s, scheduling turn-off for plug '%s'", printer_id, plug.name
  177. )
  178. if plug.off_delay_mode == "time":
  179. self._schedule_delayed_off(plug, printer_id, plug.off_delay_minutes * 60)
  180. elif plug.off_delay_mode == "temperature":
  181. self._schedule_temp_based_off(plug, printer_id, plug.off_temp_threshold)
  182. def _schedule_delayed_off(self, plug: "SmartPlug", printer_id: int, delay_seconds: int):
  183. """Schedule turn-off after delay."""
  184. # Cancel any existing task for this plug
  185. self._cancel_pending_off(plug.id)
  186. logger.info("Scheduling turn-off for plug '%s' in %s seconds", plug.name, delay_seconds)
  187. # Mark as pending in database (survives restarts)
  188. asyncio.create_task(self._mark_auto_off_pending(plug.id, True))
  189. task = asyncio.create_task(
  190. self._delayed_off(
  191. plug.id,
  192. plug.plug_type,
  193. plug.ip_address,
  194. plug.ha_entity_id,
  195. plug.username,
  196. plug.password,
  197. printer_id,
  198. delay_seconds,
  199. )
  200. )
  201. self._pending_off[plug.id] = task
  202. async def _delayed_off(
  203. self,
  204. plug_id: int,
  205. plug_type: str,
  206. ip_address: str | None,
  207. ha_entity_id: str | None,
  208. username: str | None,
  209. password: str | None,
  210. printer_id: int,
  211. delay_seconds: int,
  212. ):
  213. """Wait and turn off."""
  214. try:
  215. await asyncio.sleep(delay_seconds)
  216. # Create a minimal plug-like object for the service
  217. class PlugInfo:
  218. def __init__(self):
  219. self.plug_type = plug_type
  220. self.ip_address = ip_address
  221. self.ha_entity_id = ha_entity_id
  222. self.username = username
  223. self.password = password
  224. self.name = f"plug_{plug_id}"
  225. plug_info = PlugInfo()
  226. service = await self.get_service_for_plug(plug_info)
  227. success = await service.turn_off(plug_info)
  228. logger.info("Turned off plug %s after time delay", plug_id)
  229. # Mark auto_off_executed in database and update printer status
  230. if success:
  231. await self._mark_auto_off_executed(plug_id)
  232. # Mark the printer as offline immediately
  233. printer_manager.mark_printer_offline(printer_id)
  234. except asyncio.CancelledError:
  235. logger.debug("Delayed turn-off cancelled for plug %s", plug_id)
  236. finally:
  237. self._pending_off.pop(plug_id, None)
  238. def _schedule_temp_based_off(self, plug: "SmartPlug", printer_id: int, temp_threshold: int):
  239. """Monitor temperature and turn off when below threshold."""
  240. # Cancel any existing task for this plug
  241. self._cancel_pending_off(plug.id)
  242. logger.info("Scheduling temperature-based turn-off for plug '%s' (threshold: %s°C)", plug.name, temp_threshold)
  243. # Mark as pending in database (survives restarts)
  244. asyncio.create_task(self._mark_auto_off_pending(plug.id, True))
  245. task = asyncio.create_task(
  246. self._temp_based_off(
  247. plug.id,
  248. plug.plug_type,
  249. plug.ip_address,
  250. plug.ha_entity_id,
  251. plug.username,
  252. plug.password,
  253. printer_id,
  254. temp_threshold,
  255. )
  256. )
  257. self._pending_off[plug.id] = task
  258. async def _temp_based_off(
  259. self,
  260. plug_id: int,
  261. plug_type: str,
  262. ip_address: str | None,
  263. ha_entity_id: str | None,
  264. username: str | None,
  265. password: str | None,
  266. printer_id: int,
  267. temp_threshold: int,
  268. ):
  269. """Poll temperature until below threshold, then turn off.
  270. For dual-extruder printers (H2 series), checks both nozzles.
  271. """
  272. try:
  273. check_interval = 10 # seconds
  274. max_wait = 3600 # 1 hour max
  275. elapsed = 0
  276. while elapsed < max_wait:
  277. status = printer_manager.get_status(printer_id)
  278. if status:
  279. temps = status.temperatures or {}
  280. nozzle_temp = temps.get("nozzle", 999)
  281. # Check second nozzle for dual-extruder printers (H2 series)
  282. nozzle_2_temp = temps.get("nozzle_2")
  283. # Get the maximum temperature across all nozzles
  284. max_nozzle_temp = nozzle_temp
  285. if nozzle_2_temp is not None:
  286. max_nozzle_temp = max(nozzle_temp, nozzle_2_temp)
  287. logger.info(
  288. f"Temp check plug {plug_id}: nozzle1={nozzle_temp}°C, "
  289. f"nozzle2={nozzle_2_temp}°C, max={max_nozzle_temp}°C, "
  290. f"threshold={temp_threshold}°C"
  291. )
  292. else:
  293. logger.info(
  294. "Temp check plug %s: nozzle=%s°C, threshold=%s°C", plug_id, nozzle_temp, temp_threshold
  295. )
  296. if max_nozzle_temp < temp_threshold:
  297. # All nozzles are below threshold, turn off
  298. class PlugInfo:
  299. def __init__(self):
  300. self.plug_type = plug_type
  301. self.ip_address = ip_address
  302. self.ha_entity_id = ha_entity_id
  303. self.username = username
  304. self.password = password
  305. self.name = f"plug_{plug_id}"
  306. plug_info = PlugInfo()
  307. service = await self.get_service_for_plug(plug_info)
  308. success = await service.turn_off(plug_info)
  309. logger.info(
  310. f"Turned off plug {plug_id} after nozzle temp dropped to "
  311. f"{max_nozzle_temp}°C (threshold: {temp_threshold}°C)"
  312. )
  313. # Mark auto_off_executed in database and update printer status
  314. if success:
  315. await self._mark_auto_off_executed(plug_id)
  316. # Mark the printer as offline immediately
  317. printer_manager.mark_printer_offline(printer_id)
  318. break
  319. await asyncio.sleep(check_interval)
  320. elapsed += check_interval
  321. if elapsed >= max_wait:
  322. logger.warning("Temperature-based turn-off timed out for plug %s after %ss", plug_id, max_wait)
  323. except asyncio.CancelledError:
  324. logger.debug("Temperature-based turn-off cancelled for plug %s", plug_id)
  325. finally:
  326. self._pending_off.pop(plug_id, None)
  327. async def _mark_auto_off_pending(self, plug_id: int, pending: bool):
  328. """Mark a plug as having a pending auto-off (survives restarts)."""
  329. try:
  330. from backend.app.core.database import async_session
  331. from backend.app.models.smart_plug import SmartPlug
  332. async with async_session() as db:
  333. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  334. plug = result.scalar_one_or_none()
  335. if plug:
  336. plug.auto_off_pending = pending
  337. plug.auto_off_pending_since = datetime.now(timezone.utc) if pending else None
  338. await db.commit()
  339. logger.debug("Marked plug %s auto_off_pending=%s", plug_id, pending)
  340. except Exception as e:
  341. logger.warning("Failed to update plug %s pending state: %s", plug_id, e)
  342. async def _mark_auto_off_executed(self, plug_id: int):
  343. """Disable auto-off after it was executed (one-shot behavior)."""
  344. try:
  345. from backend.app.core.database import async_session
  346. from backend.app.models.smart_plug import SmartPlug
  347. async with async_session() as db:
  348. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  349. plug = result.scalar_one_or_none()
  350. if plug:
  351. plug.auto_off = False # Disable auto-off (one-shot behavior)
  352. plug.auto_off_executed = False # Reset the flag
  353. plug.auto_off_pending = False # Clear pending state
  354. plug.auto_off_pending_since = None
  355. plug.last_state = "OFF"
  356. plug.last_checked = datetime.now(timezone.utc)
  357. await db.commit()
  358. logger.info("Auto-off executed and disabled for plug %s", plug_id)
  359. except Exception as e:
  360. logger.warning("Failed to update plug %s after auto-off: %s", plug_id, e)
  361. def _cancel_pending_off(self, plug_id: int):
  362. """Cancel any pending off task for this plug."""
  363. if plug_id in self._pending_off:
  364. logger.debug("Cancelling pending turn-off for plug %s", plug_id)
  365. self._pending_off[plug_id].cancel()
  366. del self._pending_off[plug_id]
  367. # Clear pending state in database
  368. asyncio.create_task(self._mark_auto_off_pending(plug_id, False))
  369. def cancel_all_pending(self):
  370. """Cancel all pending turn-off tasks."""
  371. for plug_id in list(self._pending_off.keys()):
  372. self._cancel_pending_off(plug_id)
  373. async def resume_pending_auto_offs(self):
  374. """Resume any pending auto-offs that were interrupted by a restart.
  375. Called on startup to check for plugs that had auto-off pending but
  376. never completed (e.g., due to service restart).
  377. """
  378. try:
  379. from backend.app.core.database import async_session
  380. from backend.app.models.smart_plug import SmartPlug
  381. async with async_session() as db:
  382. # Find all plugs with pending auto-off
  383. result = await db.execute(
  384. select(SmartPlug).where(
  385. SmartPlug.auto_off_pending.is_(True),
  386. SmartPlug.printer_id.isnot(None),
  387. )
  388. )
  389. pending_plugs = result.scalars().all()
  390. for plug in pending_plugs:
  391. # Check how long it's been pending (timeout after 2 hours)
  392. if plug.auto_off_pending_since:
  393. pending_since = plug.auto_off_pending_since
  394. if pending_since.tzinfo is None:
  395. pending_since = pending_since.replace(tzinfo=timezone.utc)
  396. elapsed = (datetime.now(timezone.utc) - pending_since).total_seconds()
  397. if elapsed > 7200: # 2 hours
  398. logger.warning(
  399. f"Auto-off for plug '{plug.name}' was pending for {elapsed / 60:.0f} minutes, "
  400. f"clearing stale pending state"
  401. )
  402. plug.auto_off_pending = False
  403. plug.auto_off_pending_since = None
  404. await db.commit()
  405. continue
  406. logger.info("Resuming pending auto-off for plug '%s' (printer %s)", plug.name, plug.printer_id)
  407. # Resume the appropriate off mode
  408. if plug.off_delay_mode == "temperature":
  409. self._schedule_temp_based_off(plug, plug.printer_id, plug.off_temp_threshold)
  410. else:
  411. # For time mode, just turn off immediately since delay already passed
  412. logger.info("Time-based auto-off was pending, turning off plug '%s' now", plug.name)
  413. service = await self.get_service_for_plug(plug, db)
  414. success = await service.turn_off(plug)
  415. if success:
  416. await self._mark_auto_off_executed(plug.id)
  417. printer_manager.mark_printer_offline(plug.printer_id)
  418. if pending_plugs:
  419. logger.info("Resumed %s pending auto-off(s)", len(pending_plugs))
  420. except Exception as e:
  421. logger.warning("Failed to resume pending auto-offs: %s", e)
  422. # Global singleton
  423. smart_plug_manager = SmartPlugManager()