smart_plug_manager.py 47 KB

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