smart_plug_manager.py 23 KB

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