smart_plug_manager.py 46 KB

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