smart_plug_manager.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. """Manager for smart plug automation and delayed turn-off."""
  2. import asyncio
  3. import logging
  4. import time
  5. from datetime import datetime, timezone
  6. from typing import TYPE_CHECKING
  7. from sqlalchemy import select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.tasks import spawn_background_task
  10. from backend.app.services.homeassistant import homeassistant_service
  11. from backend.app.services.mqtt_relay import mqtt_relay
  12. from backend.app.services.plug_energy import get_plug_energy, mqtt_has_lifetime_counter
  13. from backend.app.services.printer_manager import printer_manager
  14. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  15. from backend.app.services.tasmota import tasmota_service
  16. from backend.app.utils.local_time import next_local_hour, to_naive_utc, utcnow_naive
  17. if TYPE_CHECKING:
  18. from backend.app.models.smart_plug import SmartPlug
  19. logger = logging.getLogger(__name__)
  20. async def publish_plug_state(
  21. plug_id: int, plug_name: str, printer_id: int | None, *, on: bool, ha_entity_id: str | None = None
  22. ) -> None:
  23. """Tell the MQTT relay a plug was switched (smart_plugs/on or /off).
  24. Called after every successful on or off command, whatever sent it, also when
  25. the plug already was in that state. A Home Assistant script run through its
  26. entity is not a switch and publishes nothing. The printer name is read from
  27. the database: the connection cache keeps a renamed printer's old name and has
  28. none for an inactive one. Never raises: the plug did switch, and a broker
  29. problem must not turn that into an error.
  30. """
  31. if ha_entity_id and ha_entity_id.startswith("script."):
  32. return
  33. if not mqtt_relay.enabled or not mqtt_relay.connected:
  34. return
  35. try:
  36. printer_name = None
  37. if printer_id:
  38. from backend.app.core import database
  39. from backend.app.models.printer import Printer
  40. async with database.async_session() as db:
  41. printer_name = (
  42. await db.execute(select(Printer.name).where(Printer.id == printer_id))
  43. ).scalar_one_or_none()
  44. await mqtt_relay.on_smart_plug_state(
  45. plug_id=plug_id,
  46. plug_name=plug_name,
  47. state="on" if on else "off",
  48. printer_id=printer_id,
  49. printer_name=printer_name,
  50. )
  51. except Exception as e:
  52. logger.debug("MQTT relay: failed to publish the state of plug %s: %s", plug_id, e)
  53. def _is_script_plug(plug) -> bool:
  54. """A Home Assistant script entity: it can be run, not switched."""
  55. return (
  56. getattr(plug, "plug_type", None) == "homeassistant"
  57. and bool(getattr(plug, "ha_entity_id", None))
  58. and plug.ha_entity_id.startswith("script.")
  59. )
  60. def is_monitor_only(plug) -> bool:
  61. """An MQTT plug: Bambuddy subscribes to it and never publishes, so it can
  62. be neither turned on nor off (#3583). Its auto on / auto off default to on
  63. and the UI hides both, so every switching path must skip it itself."""
  64. return getattr(plug, "plug_type", None) == "mqtt"
  65. def can_turn_off(plug) -> bool:
  66. """Whether an automatic turn-off can switch this plug off (#3583).
  67. Not a Home Assistant script, which can only be run, and not a monitor-only
  68. MQTT plug. Turning on is narrower on purpose: a script linked to a printer
  69. is run by the auto-on paths, so they skip only :func:`is_monitor_only`.
  70. """
  71. return not _is_script_plug(plug) and not is_monitor_only(plug)
  72. async def run_linked_scripts(printer_id: int, plug_state: str, db: AsyncSession) -> None:
  73. """Run the HA scripts linked to a printer after its power plug switched.
  74. ON runs the scripts set to "Run when printer turns on", OFF those set to
  75. "Run when printer turns off". Never raises: a script that fails must not
  76. undo the switch that triggered it.
  77. """
  78. from backend.app.models.smart_plug import SmartPlug
  79. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  80. for plug in result.scalars().all():
  81. # "Enabled" is the script's automation switch, as at print start.
  82. if not _is_script_plug(plug) or not plug.enabled:
  83. continue
  84. if plug_state == "ON" and plug.auto_on:
  85. logger.info("Auto-triggering script '%s' on printer power-on", plug.name)
  86. elif plug_state == "OFF" and plug.auto_off:
  87. logger.info("Auto-triggering script '%s' on printer power-off", plug.name)
  88. else:
  89. continue
  90. try:
  91. service = await smart_plug_manager.get_service_for_plug(plug, db)
  92. await service.turn_on(plug) # Scripts are triggered by calling turn_on
  93. except Exception as e:
  94. logger.error("Failed to trigger script '%s': %s", plug.name, e)
  95. # (printer_id, state) -> when its scripts last ran after an automatic switch.
  96. # Two plugs feeding one printer both auto-off after a print; the printer
  97. # turned off once.
  98. _recent_automatic_script_runs: dict[tuple[int, str], float] = {}
  99. _AUTOMATIC_SCRIPT_RUN_WINDOW_S = 120.0
  100. async def run_linked_scripts_after_automatic_switch(printer_id: int | None, plug, plug_state: str) -> None:
  101. """Linked scripts for a printer's power plug switched by Bambuddy itself.
  102. Only for a plug that feeds the printer: an accessory switching is not the
  103. printer turning on or off. Print start is not routed here -- it runs the
  104. "on" scripts itself, as linked plugs with auto-on.
  105. """
  106. if not printer_id or _is_script_plug(plug) or not getattr(plug, "controls_printer_power", True):
  107. return
  108. now = time.monotonic()
  109. last = _recent_automatic_script_runs.get((printer_id, plug_state))
  110. if last is not None and now - last < _AUTOMATIC_SCRIPT_RUN_WINDOW_S:
  111. return
  112. _recent_automatic_script_runs[(printer_id, plug_state)] = now
  113. from backend.app.core.database import async_session
  114. try:
  115. async with async_session() as db:
  116. await run_linked_scripts(printer_id, plug_state, db)
  117. except Exception as e:
  118. logger.warning("Could not run the scripts linked to printer %s: %s", printer_id, e)
  119. class SmartPlugManager:
  120. """Manages smart plug automation and delayed turn-off."""
  121. def __init__(self):
  122. self._pending_off: dict[int, asyncio.Task] = {} # plug_id -> task
  123. self._scheduler_task: asyncio.Task | None = None
  124. self._snapshot_task: asyncio.Task | None = None
  125. self._power_alert_task: asyncio.Task | None = None
  126. self._relay_energy_task: asyncio.Task | None = None
  127. self._last_schedule_check: dict[int, str] = {} # plug_id -> "HH:MM" last executed
  128. async def get_service_for_plug(self, plug: "SmartPlug", db: AsyncSession | None = None):
  129. """Get the appropriate service for the plug type.
  130. For HA plugs, configures the service with current settings from DB.
  131. """
  132. if plug.plug_type == "homeassistant":
  133. # Configure HA service with current settings
  134. await self._configure_ha_service(db)
  135. return homeassistant_service
  136. if plug.plug_type == "rest":
  137. return rest_smart_plug_service
  138. return tasmota_service
  139. async def _configure_ha_service(self, db: AsyncSession | None = None):
  140. """Configure the HA service with URL and token from settings."""
  141. from backend.app.api.routes.settings import get_homeassistant_settings
  142. try:
  143. if db:
  144. # Use provided session
  145. ha_settings = await get_homeassistant_settings(db)
  146. else:
  147. # Create new session
  148. from backend.app.core.database import async_session
  149. async with async_session() as session:
  150. ha_settings = await get_homeassistant_settings(session)
  151. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  152. except Exception as e:
  153. logger.warning("Failed to configure HA service: %s", e)
  154. def start_scheduler(self):
  155. """Start the background scheduler for time-based plug control."""
  156. if self._scheduler_task is None:
  157. self._scheduler_task = asyncio.create_task(self._schedule_loop())
  158. logger.info("Smart plug scheduler started")
  159. if self._snapshot_task is None:
  160. self._snapshot_task = asyncio.create_task(self._snapshot_loop())
  161. logger.info("Smart plug energy snapshot loop started")
  162. if self._power_alert_task is None:
  163. self._power_alert_task = asyncio.create_task(self._power_alert_loop())
  164. logger.info("Smart plug power alert loop started")
  165. if self._relay_energy_task is None:
  166. self._relay_energy_task = asyncio.create_task(self._relay_energy_loop())
  167. logger.info("Smart plug MQTT relay energy loop started")
  168. def stop_scheduler(self):
  169. """Stop the background scheduler."""
  170. if self._scheduler_task:
  171. self._scheduler_task.cancel()
  172. self._scheduler_task = None
  173. logger.info("Smart plug scheduler stopped")
  174. if self._snapshot_task:
  175. self._snapshot_task.cancel()
  176. self._snapshot_task = None
  177. logger.info("Smart plug energy snapshot loop stopped")
  178. if self._power_alert_task:
  179. self._power_alert_task.cancel()
  180. self._power_alert_task = None
  181. logger.info("Smart plug power alert loop stopped")
  182. if self._relay_energy_task:
  183. self._relay_energy_task.cancel()
  184. self._relay_energy_task = None
  185. logger.info("Smart plug MQTT relay energy loop stopped")
  186. async def _schedule_loop(self):
  187. """Background loop that checks scheduled on/off times every minute."""
  188. while True:
  189. try:
  190. await self._check_schedules()
  191. except Exception as e:
  192. logger.error("Error in schedule check: %s", e)
  193. # Wait until the next minute
  194. await asyncio.sleep(60)
  195. async def _power_alert_loop(self):
  196. """Background loop that checks plugs with power alerts on, once a minute.
  197. Without it an alert would only be noticed while someone had a printer
  198. page open, since the plug status is otherwise only read for display.
  199. """
  200. from backend.app.core import database
  201. from backend.app.services.power_alerts import check_all_plugs
  202. await asyncio.sleep(30)
  203. while True:
  204. try:
  205. # Looked up on each pass: a backup restore replaces the session factory.
  206. async with database.async_session() as db:
  207. await check_all_plugs(db)
  208. except Exception as e:
  209. logger.error("Error in power alert check: %s", e)
  210. await asyncio.sleep(60)
  211. async def _snapshot_loop(self):
  212. """Background loop that captures each plug's lifetime energy counter.
  213. Powers date-range queries in "total consumption" energy mode (#941) and,
  214. since #2539, the derived Today / Yesterday figures for every plug that
  215. reports only a cumulative counter.
  216. Ticks on the local hour rather than every 3600s from boot. That is what
  217. makes the derivation exact: a drifting timer leaves the last snapshot
  218. before midnight up to an hour early, and an hour of a printer's draw is
  219. a real number of watt-hours to lose off the day boundary. Aligning to the
  220. *local* hour also lands a tick on local midnight in the half-hour-offset
  221. timezones (India, Nepal), where midnight is not on a UTC hour at all.
  222. """
  223. # Short warm-up delay so other services finish booting; still gives us an
  224. # initial snapshot well before the first boundary.
  225. await asyncio.sleep(30)
  226. while True:
  227. try:
  228. await self._capture_energy_snapshots()
  229. except Exception as e:
  230. logger.error("Error in energy snapshot capture: %s", e)
  231. now = datetime.now(timezone.utc)
  232. delay = (next_local_hour(now) - now).total_seconds()
  233. await asyncio.sleep(max(delay, 60))
  234. async def _relay_energy_loop(self):
  235. """Background loop that publishes every plug's energy to the MQTT relay, once a minute.
  236. The relay's smart_plugs/energy topic has nothing else feeding it: the
  237. plug status is otherwise only read for display, for power alerts and,
  238. hourly, for the lifetime counter.
  239. """
  240. from backend.app.core import database
  241. await asyncio.sleep(30)
  242. while True:
  243. try:
  244. # Looked up on each pass: a backup restore replaces the session factory.
  245. async with database.async_session() as db:
  246. await self._publish_energy_to_relay(db)
  247. except Exception as e:
  248. logger.error("Error publishing plug energy to the MQTT relay: %s", e)
  249. await asyncio.sleep(60)
  250. async def _publish_energy_to_relay(self, db: AsyncSession) -> None:
  251. """Read each enabled plug's power and energy and publish it to the MQTT relay.
  252. Nothing is read while the relay is off or disconnected: on an install
  253. without the relay this costs no request to any plug.
  254. """
  255. from backend.app.models.smart_plug import SmartPlug
  256. if not mqtt_relay.enabled or not mqtt_relay.connected:
  257. return
  258. plugs = (await db.execute(select(SmartPlug).where(SmartPlug.enabled.is_(True)))).scalars().all()
  259. for plug in plugs:
  260. # An MQTT plug's values are its last message; once it stops
  261. # reporting they are stale, not a reading.
  262. if plug.plug_type == "mqtt" and not mqtt_relay.smart_plug_service.is_reachable(plug.id):
  263. continue
  264. try:
  265. energy = await get_plug_energy(plug, db)
  266. except Exception as e:
  267. logger.debug("MQTT relay: failed to read energy from plug %s: %s", plug.id, e)
  268. continue
  269. if not energy:
  270. continue
  271. await mqtt_relay.on_smart_plug_energy(
  272. plug.id, plug.name, energy.get("power"), energy.get("today"), energy.get("total")
  273. )
  274. async def _capture_energy_snapshots(self):
  275. """Capture one energy snapshot row per plug with a usable lifetime counter."""
  276. from backend.app.core.database import async_session
  277. from backend.app.models.smart_plug import SmartPlug
  278. async with async_session() as db:
  279. plugs_result = await db.execute(select(SmartPlug).where(SmartPlug.enabled.is_(True)))
  280. plugs = list(plugs_result.scalars().all())
  281. if not plugs:
  282. return
  283. # Naive UTC: the column is naive, and asyncpg rejects an aware value
  284. # outright (SQLite quietly drops the offset, which is why this went
  285. # unnoticed — on Postgres the whole capture raised).
  286. now = utcnow_naive()
  287. # One price for every row of this tick: read from Home Assistant
  288. # when that's the source, so it is refreshed hourly (#1251).
  289. from backend.app.services.energy_price import current_price, new_snapshot
  290. price = await current_price(db, remember=True)
  291. captured = 0
  292. for plug in plugs:
  293. # An MQTT plug feeds the snapshots only with its lifetime counter
  294. # (#3582); its one legacy energy value may be a daily counter that
  295. # resets at midnight. Read through get_plug_energy, not the
  296. # service lookup, which would fall back to Tasmota on an IP-less plug.
  297. if plug.plug_type == "mqtt" and not mqtt_has_lifetime_counter(plug):
  298. continue
  299. try:
  300. if plug.plug_type == "mqtt":
  301. energy = await get_plug_energy(plug, db)
  302. else:
  303. service = await self.get_service_for_plug(plug, db)
  304. energy = await service.get_energy(plug)
  305. except Exception as e:
  306. logger.debug("Snapshot: failed to read energy from plug %s: %s", plug.id, e)
  307. continue
  308. if not energy:
  309. continue
  310. lifetime = energy.get("total")
  311. if lifetime is None:
  312. # The plug exposes no cumulative counter — a REST plug with only
  313. # rest_energy_path set, say. Nothing to snapshot, and its Today
  314. # comes straight from the device anyway.
  315. continue
  316. db.add(
  317. await new_snapshot(db, plug_id=plug.id, recorded_at=now, lifetime_kwh=float(lifetime), price=price)
  318. )
  319. captured += 1
  320. # Commits the price read above too, even with nothing captured.
  321. await db.commit()
  322. if captured:
  323. logger.info("Captured %d energy snapshot(s)", captured)
  324. async def _check_schedules(self):
  325. """Check all plugs for scheduled on/off times."""
  326. from backend.app.core.database import async_session
  327. from backend.app.models.smart_plug import SmartPlug
  328. current_time = datetime.now().strftime("%H:%M")
  329. async with async_session() as db:
  330. result = await db.execute(
  331. select(SmartPlug).where(
  332. SmartPlug.enabled.is_(True),
  333. SmartPlug.schedule_enabled.is_(True),
  334. )
  335. )
  336. plugs = result.scalars().all()
  337. for plug in plugs:
  338. # A schedule cannot switch a monitor-only MQTT plug (#3583).
  339. if is_monitor_only(plug):
  340. continue
  341. service = await self.get_service_for_plug(plug, db)
  342. # Check if we should turn on
  343. if plug.schedule_on_time == current_time:
  344. last_check = self._last_schedule_check.get(plug.id)
  345. if last_check != f"on:{current_time}":
  346. logger.info("Schedule: Turning on plug '%s' at %s", plug.name, current_time)
  347. success = await service.turn_on(plug)
  348. if success:
  349. plug.last_state = "ON"
  350. plug.last_checked = utcnow_naive()
  351. self._last_schedule_check[plug.id] = f"on:{current_time}"
  352. await publish_plug_state(
  353. plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id
  354. )
  355. await run_linked_scripts_after_automatic_switch(plug.printer_id, plug, "ON")
  356. # Check if we should turn off
  357. if plug.schedule_off_time == current_time:
  358. last_check = self._last_schedule_check.get(plug.id)
  359. if last_check != f"off:{current_time}":
  360. logger.info("Schedule: Turning off plug '%s' at %s", plug.name, current_time)
  361. success = await service.turn_off(plug)
  362. if success:
  363. plug.last_state = "OFF"
  364. plug.last_checked = utcnow_naive()
  365. self._last_schedule_check[plug.id] = f"off:{current_time}"
  366. await publish_plug_state(
  367. plug.id, plug.name, plug.printer_id, on=False, ha_entity_id=plug.ha_entity_id
  368. )
  369. # Mark printer offline if this plug feeds it (#2629)
  370. if plug.printer_id and plug.controls_printer_power:
  371. printer_manager.mark_printer_offline(plug.printer_id)
  372. await run_linked_scripts_after_automatic_switch(plug.printer_id, plug, "OFF")
  373. await db.commit()
  374. async def _get_plugs_for_printer(self, printer_id: int, db: AsyncSession) -> list["SmartPlug"]:
  375. """Get all smart plugs linked to a printer for automation control."""
  376. from backend.app.models.smart_plug import SmartPlug
  377. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  378. return list(result.scalars().all())
  379. async def on_print_start(self, printer_id: int, db: AsyncSession):
  380. """Called when a print starts - turn on all plugs linked to this printer."""
  381. plugs = await self._get_plugs_for_printer(printer_id, db)
  382. if not plugs:
  383. return
  384. for plug in plugs:
  385. if not plug.enabled:
  386. logger.debug("Smart plug '%s' is disabled, skipping auto-on", plug.name)
  387. continue
  388. # Cancel any pending off task FIRST — a re-print must abort a
  389. # scheduled auto-off regardless of the plug's auto_on setting
  390. # (#1890). Previously this lived behind the auto_on gate, so a plug
  391. # with auto_on disabled kept its pending off and cut power mid-print.
  392. self._cancel_pending_off(plug.id)
  393. if not plug.auto_on:
  394. logger.debug("Smart plug '%s' auto_on is disabled", plug.name)
  395. continue
  396. if is_monitor_only(plug):
  397. logger.debug("Smart plug '%s' is monitor-only, skipping auto-on", plug.name)
  398. continue
  399. # Turn on the plug
  400. logger.info("Print started on printer %s, turning on plug '%s'", printer_id, plug.name)
  401. try:
  402. service = await self.get_service_for_plug(plug, db)
  403. success = await service.turn_on(plug)
  404. if success:
  405. plug.last_state = "ON"
  406. plug.last_checked = utcnow_naive()
  407. plug.auto_off_executed = False # Reset flag when turning on
  408. await publish_plug_state(
  409. plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id
  410. )
  411. except Exception as e:
  412. logger.warning("Failed to turn on plug '%s' for printer %s: %s", plug.name, printer_id, e)
  413. await db.commit()
  414. async def on_print_complete(self, printer_id: int, status: str, db: AsyncSession):
  415. """Called when a print completes - schedule turn off for all plugs linked to this printer.
  416. Only triggers auto-off on successful completion (status='completed').
  417. Failed prints keep the printer powered on for user investigation.
  418. """
  419. # Only auto-off on successful completion, not on failures
  420. if status != "completed":
  421. logger.info(
  422. "Print on printer %s ended with status '%s', skipping auto-off to allow investigation",
  423. printer_id,
  424. status,
  425. )
  426. return
  427. plugs = await self._get_plugs_for_printer(printer_id, db)
  428. if not plugs:
  429. return
  430. for plug in plugs:
  431. if not plug.enabled:
  432. logger.debug("Smart plug '%s' is disabled, skipping auto-off", plug.name)
  433. continue
  434. if not plug.auto_off:
  435. logger.debug("Smart plug '%s' auto_off is disabled", plug.name)
  436. continue
  437. # Skip auto-off for HA script entities (scripts can only be triggered,
  438. # not turned off) and monitor-only MQTT plugs (#3583).
  439. if not can_turn_off(plug):
  440. logger.debug("Smart plug '%s' cannot be switched off, skipping auto-off", plug.name)
  441. continue
  442. logger.info(
  443. "Print completed successfully on printer %s, scheduling turn-off for plug '%s'",
  444. printer_id,
  445. plug.name,
  446. )
  447. self._schedule_off_per_mode(plug, printer_id)
  448. def _schedule_off_per_mode(self, plug: "SmartPlug", printer_id: int):
  449. """Schedule an auto-off using the plug's configured off strategy.
  450. Honours the per-plug ``off_delay_mode`` — ``time`` waits
  451. ``off_delay_minutes``; ``temperature`` waits until the nozzle drops
  452. below ``off_temp_threshold`` (#1890 — the queue/scheduler auto-off
  453. paths used to hardcode 50°C / 600s and ignore these settings). Both
  454. branches register a cancellable task in ``_pending_off``, so a re-print
  455. cancels the pending off via :meth:`on_print_start`.
  456. """
  457. if plug.off_delay_mode == "temperature":
  458. self._schedule_temp_based_off(plug, printer_id, plug.off_temp_threshold)
  459. else:
  460. # Default / "time": also the safe fallback for any unexpected value.
  461. self._schedule_delayed_off(plug, printer_id, plug.off_delay_minutes * 60)
  462. async def schedule_off_after_queue_job(self, printer_id: int, db: AsyncSession):
  463. """Schedule auto-off for a printer after a queue job that opted in.
  464. The print-queue "auto off after this job" toggle (`auto_off_after`) is
  465. a per-job override, independent of the plug's global ``auto_off`` flag —
  466. so unlike :meth:`on_print_complete` this does NOT gate on ``plug.auto_off``.
  467. It still honours ``enabled`` and skips HA-script entities (which can only
  468. be triggered, not turned off), and uses each plug's configured off
  469. strategy via :meth:`_schedule_off_per_mode`. Replaces three inline
  470. cooldown waits (50°C, 600s) that ignored plug settings,
  471. fired on the cooldown *timeout* regardless of print state, and could not
  472. be cancelled by a re-print (#1890).
  473. """
  474. plugs = await self._get_plugs_for_printer(printer_id, db)
  475. for plug in plugs:
  476. if not plug.enabled:
  477. logger.debug("Smart plug '%s' is disabled, skipping queue auto-off", plug.name)
  478. continue
  479. if not can_turn_off(plug):
  480. logger.debug("Smart plug '%s' cannot be switched off, skipping queue auto-off", plug.name)
  481. continue
  482. logger.info(
  483. "Queue job finished on printer %s, scheduling turn-off for plug '%s'",
  484. printer_id,
  485. plug.name,
  486. )
  487. self._schedule_off_per_mode(plug, printer_id)
  488. async def on_drying_complete(self, printer_id: int, db: AsyncSession):
  489. """Schedule turn-off for plugs flagged ``auto_off_after_drying`` when
  490. an AMS drying cycle finishes on this printer (#1349).
  491. Mirrors :meth:`on_print_complete` but uses the drying-specific
  492. toggle and delay. Iterates every plug linked to the printer and
  493. fires only on the ones the user has opted-in via the per-plug
  494. toggle. Always uses the time-delay branch — temperature-based
  495. cooldown is about the printer's hotend, which isn't meaningful
  496. after a drying cycle (AMS chamber is the thing that's hot, and
  497. Bambuddy doesn't track its temperature).
  498. """
  499. plugs = await self._get_plugs_for_printer(printer_id, db)
  500. if not plugs:
  501. return
  502. for plug in plugs:
  503. if not plug.enabled:
  504. logger.debug("Smart plug '%s' is disabled, skipping drying auto-off", plug.name)
  505. continue
  506. if not plug.auto_off_after_drying:
  507. logger.debug("Smart plug '%s' auto_off_after_drying is disabled, skipping", plug.name)
  508. continue
  509. # HA script entities can only be triggered, not turned off, and MQTT
  510. # plugs not switched at all — same guard the print-finish path uses.
  511. if not can_turn_off(plug):
  512. logger.debug("Smart plug '%s' cannot be switched off, skipping drying auto-off", plug.name)
  513. continue
  514. logger.info(
  515. "Drying completed on printer %s, scheduling turn-off for plug '%s' in %d min",
  516. printer_id,
  517. plug.name,
  518. plug.off_delay_after_drying_minutes,
  519. )
  520. self._schedule_delayed_off(plug, printer_id, plug.off_delay_after_drying_minutes * 60)
  521. def _schedule_delayed_off(self, plug: "SmartPlug", printer_id: int, delay_seconds: int):
  522. """Schedule turn-off after delay."""
  523. # Cancel any existing task for this plug
  524. self._cancel_pending_off(plug.id)
  525. logger.info("Scheduling turn-off for plug '%s' in %s seconds", plug.name, delay_seconds)
  526. # Mark as pending in database (survives restarts)
  527. spawn_background_task(self._mark_auto_off_pending(plug.id, True), name=f"plug-auto-off-pending-{plug.id}")
  528. task = asyncio.create_task(
  529. self._delayed_off(
  530. plug.id,
  531. plug.plug_type,
  532. plug.ip_address,
  533. plug.ha_entity_id,
  534. plug.username,
  535. plug.password,
  536. printer_id,
  537. delay_seconds,
  538. controls_printer_power=plug.controls_printer_power,
  539. plug_name=plug.name,
  540. rest_off_url=plug.rest_off_url if plug.plug_type == "rest" else None,
  541. rest_off_body=plug.rest_off_body if plug.plug_type == "rest" else None,
  542. rest_method=plug.rest_method if plug.plug_type == "rest" else None,
  543. rest_headers=plug.rest_headers if plug.plug_type == "rest" else None,
  544. )
  545. )
  546. self._pending_off[plug.id] = task
  547. async def _delayed_off(
  548. self,
  549. plug_id: int,
  550. plug_type: str,
  551. ip_address: str | None,
  552. ha_entity_id: str | None,
  553. username: str | None,
  554. password: str | None,
  555. printer_id: int,
  556. delay_seconds: int,
  557. *,
  558. controls_printer_power: bool = True,
  559. plug_name: str = "",
  560. rest_off_url: str | None = None,
  561. rest_off_body: str | None = None,
  562. rest_method: str | None = None,
  563. rest_headers: str | None = None,
  564. ):
  565. """Wait and turn off."""
  566. try:
  567. await asyncio.sleep(delay_seconds)
  568. # #1890: never cut power while a print is loaded / running. The
  569. # delay fires unconditionally after N minutes, so if the user
  570. # re-started (or reprinted) in the meantime, the printer is active
  571. # again — skip the off and clear the pending flag rather than
  572. # killing the print mid-way.
  573. if printer_manager.is_print_active(printer_id):
  574. logger.info(
  575. "Skipping auto-off for plug %s: printer %s is printing again (state=%s)",
  576. plug_id,
  577. printer_id,
  578. getattr(printer_manager.get_status(printer_id), "state", "unknown"),
  579. )
  580. await self._mark_auto_off_pending(plug_id, False)
  581. return
  582. # Create a minimal plug-like object for the service
  583. class PlugInfo:
  584. def __init__(self):
  585. self.plug_type = plug_type
  586. self.ip_address = ip_address
  587. self.ha_entity_id = ha_entity_id
  588. self.username = username
  589. self.password = password
  590. self.name = f"plug_{plug_id}"
  591. # REST fields
  592. self.rest_off_url = rest_off_url
  593. self.rest_off_body = rest_off_body
  594. self.rest_method = rest_method
  595. self.rest_headers = rest_headers
  596. self.controls_printer_power = controls_printer_power
  597. plug_info = PlugInfo()
  598. service = await self.get_service_for_plug(plug_info)
  599. success = await service.turn_off(plug_info)
  600. logger.info("Turned off plug %s after time delay", plug_id)
  601. # Mark auto_off_executed in database and update printer status
  602. if success:
  603. await self._mark_auto_off_executed(plug_id)
  604. await publish_plug_state(
  605. plug_id, plug_name or f"plug_{plug_id}", printer_id, on=False, ha_entity_id=ha_entity_id
  606. )
  607. # Mark the printer as offline immediately — but only when this
  608. # plug actually feeds the printer (#2629).
  609. if controls_printer_power:
  610. printer_manager.mark_printer_offline(printer_id)
  611. await run_linked_scripts_after_automatic_switch(printer_id, plug_info, "OFF")
  612. except asyncio.CancelledError:
  613. logger.debug("Delayed turn-off cancelled for plug %s", plug_id)
  614. finally:
  615. self._pending_off.pop(plug_id, None)
  616. def _schedule_temp_based_off(self, plug: "SmartPlug", printer_id: int, temp_threshold: int):
  617. """Monitor temperature and turn off when below threshold."""
  618. # Cancel any existing task for this plug
  619. self._cancel_pending_off(plug.id)
  620. logger.info("Scheduling temperature-based turn-off for plug '%s' (threshold: %s°C)", plug.name, temp_threshold)
  621. # Mark as pending in database (survives restarts)
  622. spawn_background_task(self._mark_auto_off_pending(plug.id, True), name=f"plug-auto-off-pending-{plug.id}")
  623. task = asyncio.create_task(
  624. self._temp_based_off(
  625. plug.id,
  626. plug.plug_type,
  627. plug.ip_address,
  628. plug.ha_entity_id,
  629. plug.username,
  630. plug.password,
  631. printer_id,
  632. temp_threshold,
  633. controls_printer_power=plug.controls_printer_power,
  634. plug_name=plug.name,
  635. rest_off_url=plug.rest_off_url if plug.plug_type == "rest" else None,
  636. rest_off_body=plug.rest_off_body if plug.plug_type == "rest" else None,
  637. rest_method=plug.rest_method if plug.plug_type == "rest" else None,
  638. rest_headers=plug.rest_headers if plug.plug_type == "rest" else None,
  639. )
  640. )
  641. self._pending_off[plug.id] = task
  642. async def _temp_based_off(
  643. self,
  644. plug_id: int,
  645. plug_type: str,
  646. ip_address: str | None,
  647. ha_entity_id: str | None,
  648. username: str | None,
  649. password: str | None,
  650. printer_id: int,
  651. temp_threshold: int,
  652. *,
  653. controls_printer_power: bool = True,
  654. plug_name: str = "",
  655. rest_off_url: str | None = None,
  656. rest_off_body: str | None = None,
  657. rest_method: str | None = None,
  658. rest_headers: str | None = None,
  659. ):
  660. """Poll temperature until below threshold, then turn off.
  661. For dual-extruder printers (H2 series), checks both nozzles.
  662. """
  663. try:
  664. check_interval = 10 # seconds
  665. max_wait = 3600 # 1 hour max
  666. elapsed = 0
  667. while elapsed < max_wait:
  668. status = printer_manager.get_status(printer_id)
  669. if status:
  670. temps = status.temperatures or {}
  671. nozzle_temp = temps.get("nozzle", 999)
  672. # Check second nozzle for dual-extruder printers (H2 series)
  673. nozzle_2_temp = temps.get("nozzle_2")
  674. # Get the maximum temperature across all nozzles
  675. max_nozzle_temp = nozzle_temp
  676. if nozzle_2_temp is not None:
  677. max_nozzle_temp = max(nozzle_temp, nozzle_2_temp)
  678. logger.info(
  679. f"Temp check plug {plug_id}: nozzle1={nozzle_temp}°C, "
  680. f"nozzle2={nozzle_2_temp}°C, max={max_nozzle_temp}°C, "
  681. f"threshold={temp_threshold}°C"
  682. )
  683. else:
  684. logger.info(
  685. "Temp check plug %s: nozzle=%s°C, threshold=%s°C", plug_id, nozzle_temp, temp_threshold
  686. )
  687. if max_nozzle_temp < temp_threshold:
  688. # #1890: the nozzle can dip below the threshold between
  689. # a finished print and a fresh one starting (e.g. a
  690. # touchscreen reprint during the PREPARE/heating phase).
  691. # Guard the turn-off so we never cut power on a loaded
  692. # print; keep polling until it's genuinely idle again.
  693. if printer_manager.is_print_active(printer_id):
  694. logger.info(
  695. "Deferring temp-based auto-off for plug %s: printer %s is printing again (state=%s)",
  696. plug_id,
  697. printer_id,
  698. getattr(printer_manager.get_status(printer_id), "state", "unknown"),
  699. )
  700. await asyncio.sleep(check_interval)
  701. elapsed += check_interval
  702. continue
  703. # All nozzles are below threshold, turn off
  704. class PlugInfo:
  705. def __init__(self):
  706. self.plug_type = plug_type
  707. self.ip_address = ip_address
  708. self.ha_entity_id = ha_entity_id
  709. self.username = username
  710. self.password = password
  711. self.name = f"plug_{plug_id}"
  712. # REST fields
  713. self.rest_off_url = rest_off_url
  714. self.rest_off_body = rest_off_body
  715. self.rest_method = rest_method
  716. self.rest_headers = rest_headers
  717. self.controls_printer_power = controls_printer_power
  718. plug_info = PlugInfo()
  719. service = await self.get_service_for_plug(plug_info)
  720. success = await service.turn_off(plug_info)
  721. logger.info(
  722. f"Turned off plug {plug_id} after nozzle temp dropped to "
  723. f"{max_nozzle_temp}°C (threshold: {temp_threshold}°C)"
  724. )
  725. # Mark auto_off_executed in database and update printer status
  726. if success:
  727. await self._mark_auto_off_executed(plug_id)
  728. await publish_plug_state(
  729. plug_id, plug_name or f"plug_{plug_id}", printer_id, on=False, ha_entity_id=ha_entity_id
  730. )
  731. # Mark the printer as offline immediately — but only
  732. # when this plug actually feeds the printer (#2629).
  733. if controls_printer_power:
  734. printer_manager.mark_printer_offline(printer_id)
  735. await run_linked_scripts_after_automatic_switch(printer_id, plug_info, "OFF")
  736. break
  737. await asyncio.sleep(check_interval)
  738. elapsed += check_interval
  739. if elapsed >= max_wait:
  740. logger.warning("Temperature-based turn-off timed out for plug %s after %ss", plug_id, max_wait)
  741. except asyncio.CancelledError:
  742. logger.debug("Temperature-based turn-off cancelled for plug %s", plug_id)
  743. finally:
  744. self._pending_off.pop(plug_id, None)
  745. async def _mark_auto_off_pending(self, plug_id: int, pending: bool):
  746. """Mark a plug as having a pending auto-off (survives restarts)."""
  747. try:
  748. from backend.app.core.database import async_session
  749. from backend.app.models.smart_plug import SmartPlug
  750. async with async_session() as db:
  751. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  752. plug = result.scalar_one_or_none()
  753. if plug:
  754. plug.auto_off_pending = pending
  755. plug.auto_off_pending_since = utcnow_naive() if pending else None
  756. await db.commit()
  757. logger.debug("Marked plug %s auto_off_pending=%s", plug_id, pending)
  758. except Exception as e:
  759. logger.warning("Failed to update plug %s pending state: %s", plug_id, e)
  760. async def _mark_auto_off_executed(self, plug_id: int):
  761. """Disable auto-off after it was executed (one-shot behavior unless persistent)."""
  762. try:
  763. from backend.app.core.database import async_session
  764. from backend.app.models.smart_plug import SmartPlug
  765. async with async_session() as db:
  766. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  767. plug = result.scalar_one_or_none()
  768. if plug:
  769. if not plug.auto_off_persistent:
  770. plug.auto_off = False # Disable auto-off (one-shot behavior)
  771. plug.auto_off_executed = False # Reset the flag
  772. plug.auto_off_pending = False # Clear pending state
  773. plug.auto_off_pending_since = None
  774. plug.last_state = "OFF"
  775. plug.last_checked = utcnow_naive()
  776. await db.commit()
  777. if plug.auto_off_persistent:
  778. logger.info("Auto-off executed for plug %s (persistent, stays enabled)", plug_id)
  779. else:
  780. logger.info("Auto-off executed and disabled for plug %s", plug_id)
  781. except Exception as e:
  782. logger.warning("Failed to update plug %s after auto-off: %s", plug_id, e)
  783. def _cancel_pending_off(self, plug_id: int):
  784. """Cancel any pending off task for this plug."""
  785. if plug_id in self._pending_off:
  786. logger.debug("Cancelling pending turn-off for plug %s", plug_id)
  787. self._pending_off[plug_id].cancel()
  788. del self._pending_off[plug_id]
  789. # Clear pending state in database
  790. spawn_background_task(self._mark_auto_off_pending(plug_id, False), name=f"plug-auto-off-pending-{plug_id}")
  791. def forget_plug(self, plug_id: int) -> None:
  792. """Cancel a deleted plug's pending turn-off.
  793. The task holds the plug's address and printer id, so it would still switch
  794. the outlet, and on SQLite read the next printer given the id. Nothing is
  795. written: the row is gone, and SQLite gives its id to the next plug.
  796. """
  797. task = self._pending_off.pop(plug_id, None)
  798. if task is not None:
  799. task.cancel()
  800. async def resume_pending_auto_offs(self):
  801. """Resume any pending auto-offs that were interrupted by a restart.
  802. Called on startup to check for plugs that had auto-off pending but
  803. never completed (e.g., due to service restart).
  804. """
  805. try:
  806. from backend.app.core.database import async_session
  807. from backend.app.models.smart_plug import SmartPlug
  808. async with async_session() as db:
  809. # Find all plugs with pending auto-off
  810. result = await db.execute(
  811. select(SmartPlug).where(
  812. SmartPlug.auto_off_pending.is_(True),
  813. SmartPlug.printer_id.isnot(None),
  814. )
  815. )
  816. pending_plugs = result.scalars().all()
  817. for plug in pending_plugs:
  818. # A pending off left on an MQTT plug by an earlier version
  819. # can never run (#3583): clear it.
  820. if is_monitor_only(plug):
  821. plug.auto_off_pending = False
  822. plug.auto_off_pending_since = None
  823. await db.commit()
  824. continue
  825. # Check how long it's been pending (timeout after 2 hours)
  826. if plug.auto_off_pending_since:
  827. pending_since = to_naive_utc(plug.auto_off_pending_since)
  828. elapsed = (utcnow_naive() - pending_since).total_seconds()
  829. if elapsed > 7200: # 2 hours
  830. logger.warning(
  831. f"Auto-off for plug '{plug.name}' was pending for {elapsed / 60:.0f} minutes, "
  832. f"clearing stale pending state"
  833. )
  834. plug.auto_off_pending = False
  835. plug.auto_off_pending_since = None
  836. await db.commit()
  837. continue
  838. logger.info("Resuming pending auto-off for plug '%s' (printer %s)", plug.name, plug.printer_id)
  839. # #1890: never resume a power-off onto a live print. If the
  840. # printer started a new print during the downtime, the stale
  841. # pending off must be dropped, not executed — same guard the
  842. # live off-executors use.
  843. if printer_manager.is_print_active(plug.printer_id):
  844. logger.info(
  845. "Not resuming auto-off for plug '%s': printer %s is printing (state=%s); clearing pending",
  846. plug.name,
  847. plug.printer_id,
  848. getattr(printer_manager.get_status(plug.printer_id), "state", "unknown"),
  849. )
  850. plug.auto_off_pending = False
  851. plug.auto_off_pending_since = None
  852. await db.commit()
  853. continue
  854. # Resume the appropriate off mode
  855. if plug.off_delay_mode == "temperature":
  856. self._schedule_temp_based_off(plug, plug.printer_id, plug.off_temp_threshold)
  857. else:
  858. # For time mode, just turn off immediately since delay already passed
  859. logger.info("Time-based auto-off was pending, turning off plug '%s' now", plug.name)
  860. service = await self.get_service_for_plug(plug, db)
  861. success = await service.turn_off(plug)
  862. if success:
  863. await self._mark_auto_off_executed(plug.id)
  864. await publish_plug_state(
  865. plug.id, plug.name, plug.printer_id, on=False, ha_entity_id=plug.ha_entity_id
  866. )
  867. if plug.controls_printer_power:
  868. printer_manager.mark_printer_offline(plug.printer_id)
  869. await run_linked_scripts_after_automatic_switch(plug.printer_id, plug, "OFF")
  870. if pending_plugs:
  871. logger.info("Resumed %s pending auto-off(s)", len(pending_plugs))
  872. except Exception as e:
  873. logger.warning("Failed to resume pending auto-offs: %s", e)
  874. # Global singleton
  875. smart_plug_manager = SmartPlugManager()