smart_plug_manager.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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 _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. # An MQTT plug feeds the snapshots only with its lifetime counter
  300. # (#3582); its one legacy energy value may be a daily counter that
  301. # resets at midnight. Read through get_plug_energy, not the
  302. # service lookup, which would fall back to Tasmota on an IP-less plug.
  303. if plug.plug_type == "mqtt" and not mqtt_has_lifetime_counter(plug):
  304. continue
  305. try:
  306. if plug.plug_type == "mqtt":
  307. energy = await get_plug_energy(plug, db)
  308. else:
  309. service = await self.get_service_for_plug(plug, db)
  310. energy = await service.get_energy(plug)
  311. except Exception as e:
  312. logger.debug("Snapshot: failed to read energy from plug %s: %s", plug.id, e)
  313. continue
  314. if not energy:
  315. continue
  316. lifetime = energy.get("total")
  317. if lifetime is None:
  318. # The plug exposes no cumulative counter — a REST plug with only
  319. # rest_energy_path set, say. Nothing to snapshot, and its Today
  320. # comes straight from the device anyway.
  321. continue
  322. db.add(
  323. await new_snapshot(db, plug_id=plug.id, recorded_at=now, lifetime_kwh=float(lifetime), price=price)
  324. )
  325. captured += 1
  326. # Commits the price read above too, even with nothing captured.
  327. await db.commit()
  328. if captured:
  329. logger.info("Captured %d energy snapshot(s)", captured)
  330. async def _check_schedules(self):
  331. """Check all plugs for scheduled on/off times."""
  332. from backend.app.core.database import async_session
  333. from backend.app.models.smart_plug import SmartPlug
  334. current_time = datetime.now().strftime("%H:%M")
  335. async with async_session() as db:
  336. result = await db.execute(
  337. select(SmartPlug).where(
  338. SmartPlug.enabled.is_(True),
  339. SmartPlug.schedule_enabled.is_(True),
  340. )
  341. )
  342. plugs = result.scalars().all()
  343. for plug in plugs:
  344. service = await self.get_service_for_plug(plug, db)
  345. # Check if we should turn on
  346. if plug.schedule_on_time == current_time:
  347. last_check = self._last_schedule_check.get(plug.id)
  348. if last_check != f"on:{current_time}":
  349. logger.info("Schedule: Turning on plug '%s' at %s", plug.name, current_time)
  350. success = await service.turn_on(plug)
  351. if success:
  352. plug.last_state = "ON"
  353. plug.last_checked = utcnow_naive()
  354. self._last_schedule_check[plug.id] = f"on:{current_time}"
  355. await publish_plug_state(
  356. plug.id, plug.name, plug.printer_id, on=True, ha_entity_id=plug.ha_entity_id
  357. )
  358. await run_linked_scripts_after_automatic_switch(plug.printer_id, plug, "ON")
  359. # Check if we should turn off
  360. if plug.schedule_off_time == current_time:
  361. last_check = self._last_schedule_check.get(plug.id)
  362. if last_check != f"off:{current_time}":
  363. logger.info("Schedule: Turning off plug '%s' at %s", plug.name, current_time)
  364. success = await service.turn_off(plug)
  365. if success:
  366. plug.last_state = "OFF"
  367. plug.last_checked = utcnow_naive()
  368. self._last_schedule_check[plug.id] = f"off:{current_time}"
  369. await publish_plug_state(
  370. plug.id, plug.name, plug.printer_id, on=False, ha_entity_id=plug.ha_entity_id
  371. )
  372. # Mark printer offline if this plug feeds it (#2629)
  373. if plug.printer_id and plug.controls_printer_power:
  374. printer_manager.mark_printer_offline(plug.printer_id)
  375. await run_linked_scripts_after_automatic_switch(plug.printer_id, plug, "OFF")
  376. await db.commit()
  377. async def _get_plugs_for_printer(self, printer_id: int, db: AsyncSession) -> list["SmartPlug"]:
  378. """Get all smart plugs linked to a printer for automation control."""
  379. from backend.app.models.smart_plug import SmartPlug
  380. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  381. return list(result.scalars().all())
  382. async def on_print_start(self, printer_id: int, db: AsyncSession):
  383. """Called when a print starts - turn on all plugs linked to this printer."""
  384. plugs = await self._get_plugs_for_printer(printer_id, db)
  385. if not plugs:
  386. return
  387. for plug in plugs:
  388. if not plug.enabled:
  389. logger.debug("Smart plug '%s' is disabled, skipping auto-on", plug.name)
  390. continue
  391. # Cancel any pending off task FIRST — a re-print must abort a
  392. # scheduled auto-off regardless of the plug's auto_on setting
  393. # (#1890). Previously this lived behind the auto_on gate, so a plug
  394. # with auto_on disabled kept its pending off and cut power mid-print.
  395. self._cancel_pending_off(plug.id)
  396. if not plug.auto_on:
  397. logger.debug("Smart plug '%s' auto_on is disabled", 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, not turned off)
  438. if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
  439. logger.debug("Smart plug '%s' is a HA script entity, skipping auto-off", plug.name)
  440. continue
  441. logger.info(
  442. "Print completed successfully on printer %s, scheduling turn-off for plug '%s'",
  443. printer_id,
  444. plug.name,
  445. )
  446. self._schedule_off_per_mode(plug, printer_id)
  447. def _schedule_off_per_mode(self, plug: "SmartPlug", printer_id: int):
  448. """Schedule an auto-off using the plug's configured off strategy.
  449. Honours the per-plug ``off_delay_mode`` — ``time`` waits
  450. ``off_delay_minutes``; ``temperature`` waits until the nozzle drops
  451. below ``off_temp_threshold``, or the bed below ``off_bed_temp_threshold``
  452. (``off_temp_source``, #3464) (#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 plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
  480. logger.debug("Smart plug '%s' is a HA script entity, 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 — same
  510. # guard the print-finish path uses.
  511. if plug.plug_type == "homeassistant" and plug.ha_entity_id and plug.ha_entity_id.startswith("script."):
  512. logger.debug("Smart plug '%s' is a HA script entity, 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(
  621. "Scheduling temperature-based turn-off for plug '%s' (waits for: %s, nozzle threshold: %s°C, "
  622. "bed threshold: %s°C)",
  623. plug.name,
  624. plug.off_temp_source,
  625. temp_threshold,
  626. plug.off_bed_temp_threshold,
  627. )
  628. # Mark as pending in database (survives restarts)
  629. spawn_background_task(self._mark_auto_off_pending(plug.id, True), name=f"plug-auto-off-pending-{plug.id}")
  630. task = asyncio.create_task(
  631. self._temp_based_off(
  632. plug.id,
  633. plug.plug_type,
  634. plug.ip_address,
  635. plug.ha_entity_id,
  636. plug.username,
  637. plug.password,
  638. printer_id,
  639. temp_threshold,
  640. temp_source=plug.off_temp_source,
  641. bed_temp_threshold=plug.off_bed_temp_threshold,
  642. controls_printer_power=plug.controls_printer_power,
  643. plug_name=plug.name,
  644. rest_off_url=plug.rest_off_url if plug.plug_type == "rest" else None,
  645. rest_off_body=plug.rest_off_body if plug.plug_type == "rest" else None,
  646. rest_method=plug.rest_method if plug.plug_type == "rest" else None,
  647. rest_headers=plug.rest_headers if plug.plug_type == "rest" else None,
  648. )
  649. )
  650. self._pending_off[plug.id] = task
  651. async def _temp_based_off(
  652. self,
  653. plug_id: int,
  654. plug_type: str,
  655. ip_address: str | None,
  656. ha_entity_id: str | None,
  657. username: str | None,
  658. password: str | None,
  659. printer_id: int,
  660. temp_threshold: int,
  661. *,
  662. temp_source: str = "nozzle",
  663. bed_temp_threshold: int = 35,
  664. controls_printer_power: bool = True,
  665. plug_name: str = "",
  666. rest_off_url: str | None = None,
  667. rest_off_body: str | None = None,
  668. rest_method: str | None = None,
  669. rest_headers: str | None = None,
  670. ):
  671. """Poll temperature until below threshold, then turn off.
  672. ``temp_source`` is what has to cool (#3464): the nozzle (both nozzles
  673. on dual-extruder H2 printers) below ``temp_threshold``, or the bed
  674. below ``bed_temp_threshold``.
  675. """
  676. try:
  677. check_interval = 10 # seconds
  678. max_wait = 3600 # 1 hour max
  679. elapsed = 0
  680. while elapsed < max_wait:
  681. status = printer_manager.get_status(printer_id)
  682. if status:
  683. cooled, reading = _cooled_down(
  684. status.temperatures or {}, temp_source, temp_threshold, bed_temp_threshold
  685. )
  686. logger.info("Temp check plug %s: %s", plug_id, reading)
  687. if cooled:
  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. # Cool enough, 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("Turned off plug %s after cooling down: %s", plug_id, reading)
  722. # Mark auto_off_executed in database and update printer status
  723. if success:
  724. await self._mark_auto_off_executed(plug_id)
  725. await publish_plug_state(
  726. plug_id, plug_name or f"plug_{plug_id}", printer_id, on=False, ha_entity_id=ha_entity_id
  727. )
  728. # Mark the printer as offline immediately — but only
  729. # when this plug actually feeds the printer (#2629).
  730. if controls_printer_power:
  731. printer_manager.mark_printer_offline(printer_id)
  732. await run_linked_scripts_after_automatic_switch(printer_id, plug_info, "OFF")
  733. break
  734. await asyncio.sleep(check_interval)
  735. elapsed += check_interval
  736. if elapsed >= max_wait:
  737. logger.warning("Temperature-based turn-off timed out for plug %s after %ss", plug_id, max_wait)
  738. except asyncio.CancelledError:
  739. logger.debug("Temperature-based turn-off cancelled for plug %s", plug_id)
  740. finally:
  741. self._pending_off.pop(plug_id, None)
  742. async def _mark_auto_off_pending(self, plug_id: int, pending: bool):
  743. """Mark a plug as having a pending auto-off (survives restarts)."""
  744. try:
  745. from backend.app.core.database import async_session
  746. from backend.app.models.smart_plug import SmartPlug
  747. async with async_session() as db:
  748. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  749. plug = result.scalar_one_or_none()
  750. if plug:
  751. plug.auto_off_pending = pending
  752. plug.auto_off_pending_since = utcnow_naive() if pending else None
  753. await db.commit()
  754. logger.debug("Marked plug %s auto_off_pending=%s", plug_id, pending)
  755. except Exception as e:
  756. logger.warning("Failed to update plug %s pending state: %s", plug_id, e)
  757. async def _mark_auto_off_executed(self, plug_id: int):
  758. """Disable auto-off after it was executed (one-shot behavior unless persistent)."""
  759. try:
  760. from backend.app.core.database import async_session
  761. from backend.app.models.smart_plug import SmartPlug
  762. async with async_session() as db:
  763. result = await db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  764. plug = result.scalar_one_or_none()
  765. if plug:
  766. if not plug.auto_off_persistent:
  767. plug.auto_off = False # Disable auto-off (one-shot behavior)
  768. plug.auto_off_executed = False # Reset the flag
  769. plug.auto_off_pending = False # Clear pending state
  770. plug.auto_off_pending_since = None
  771. plug.last_state = "OFF"
  772. plug.last_checked = utcnow_naive()
  773. await db.commit()
  774. if plug.auto_off_persistent:
  775. logger.info("Auto-off executed for plug %s (persistent, stays enabled)", plug_id)
  776. else:
  777. logger.info("Auto-off executed and disabled for plug %s", plug_id)
  778. except Exception as e:
  779. logger.warning("Failed to update plug %s after auto-off: %s", plug_id, e)
  780. def _cancel_pending_off(self, plug_id: int):
  781. """Cancel any pending off task for this plug."""
  782. if plug_id in self._pending_off:
  783. logger.debug("Cancelling pending turn-off for plug %s", plug_id)
  784. self._pending_off[plug_id].cancel()
  785. del self._pending_off[plug_id]
  786. # Clear pending state in database
  787. spawn_background_task(self._mark_auto_off_pending(plug_id, False), name=f"plug-auto-off-pending-{plug_id}")
  788. def forget_plug(self, plug_id: int) -> None:
  789. """Cancel a deleted plug's pending turn-off.
  790. The task holds the plug's address and printer id, so it would still switch
  791. the outlet, and on SQLite read the next printer given the id. Nothing is
  792. written: the row is gone, and SQLite gives its id to the next plug.
  793. """
  794. task = self._pending_off.pop(plug_id, None)
  795. if task is not None:
  796. task.cancel()
  797. async def resume_pending_auto_offs(self):
  798. """Resume any pending auto-offs that were interrupted by a restart.
  799. Called on startup to check for plugs that had auto-off pending but
  800. never completed (e.g., due to service restart).
  801. """
  802. try:
  803. from backend.app.core.database import async_session
  804. from backend.app.models.smart_plug import SmartPlug
  805. async with async_session() as db:
  806. # Find all plugs with pending auto-off
  807. result = await db.execute(
  808. select(SmartPlug).where(
  809. SmartPlug.auto_off_pending.is_(True),
  810. SmartPlug.printer_id.isnot(None),
  811. )
  812. )
  813. pending_plugs = result.scalars().all()
  814. for plug in pending_plugs:
  815. # Check how long it's been pending (timeout after 2 hours)
  816. if plug.auto_off_pending_since:
  817. pending_since = to_naive_utc(plug.auto_off_pending_since)
  818. elapsed = (utcnow_naive() - pending_since).total_seconds()
  819. if elapsed > 7200: # 2 hours
  820. logger.warning(
  821. f"Auto-off for plug '{plug.name}' was pending for {elapsed / 60:.0f} minutes, "
  822. f"clearing stale pending state"
  823. )
  824. plug.auto_off_pending = False
  825. plug.auto_off_pending_since = None
  826. await db.commit()
  827. continue
  828. logger.info("Resuming pending auto-off for plug '%s' (printer %s)", plug.name, plug.printer_id)
  829. # #1890: never resume a power-off onto a live print. If the
  830. # printer started a new print during the downtime, the stale
  831. # pending off must be dropped, not executed — same guard the
  832. # live off-executors use.
  833. if printer_manager.is_print_active(plug.printer_id):
  834. logger.info(
  835. "Not resuming auto-off for plug '%s': printer %s is printing (state=%s); clearing pending",
  836. plug.name,
  837. plug.printer_id,
  838. getattr(printer_manager.get_status(plug.printer_id), "state", "unknown"),
  839. )
  840. plug.auto_off_pending = False
  841. plug.auto_off_pending_since = None
  842. await db.commit()
  843. continue
  844. # Resume the appropriate off mode
  845. if plug.off_delay_mode == "temperature":
  846. self._schedule_temp_based_off(plug, plug.printer_id, plug.off_temp_threshold)
  847. else:
  848. # For time mode, just turn off immediately since delay already passed
  849. logger.info("Time-based auto-off was pending, turning off plug '%s' now", plug.name)
  850. service = await self.get_service_for_plug(plug, db)
  851. success = await service.turn_off(plug)
  852. if success:
  853. await self._mark_auto_off_executed(plug.id)
  854. await publish_plug_state(
  855. plug.id, plug.name, plug.printer_id, on=False, ha_entity_id=plug.ha_entity_id
  856. )
  857. if plug.controls_printer_power:
  858. printer_manager.mark_printer_offline(plug.printer_id)
  859. await run_linked_scripts_after_automatic_switch(plug.printer_id, plug, "OFF")
  860. if pending_plugs:
  861. logger.info("Resumed %s pending auto-off(s)", len(pending_plugs))
  862. except Exception as e:
  863. logger.warning("Failed to resume pending auto-offs: %s", e)
  864. # Global singleton
  865. smart_plug_manager = SmartPlugManager()