print_scheduler.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import zipfile
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. import defusedxml.ElementTree as ET
  10. from sqlalchemy import func, select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import async_session
  14. from backend.app.models.archive import PrintArchive
  15. from backend.app.models.library import LibraryFile
  16. from backend.app.models.print_queue import PrintQueueItem
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.settings import Settings
  19. from backend.app.models.smart_plug import SmartPlug
  20. from backend.app.services.bambu_ftp import delete_file_async, get_ftp_retry_settings, upload_file_async, with_ftp_retry
  21. from backend.app.services.notification_service import notification_service
  22. from backend.app.services.printer_manager import printer_manager, supports_drying
  23. from backend.app.services.smart_plug_manager import smart_plug_manager
  24. from backend.app.utils.printer_models import normalize_printer_model
  25. from backend.app.utils.threemf_tools import extract_nozzle_mapping_from_3mf
  26. logger = logging.getLogger(__name__)
  27. # Filament type equivalence groups — types within the same group are
  28. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  29. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  30. ["PA-CF", "PA12-CF", "PAHT-CF"],
  31. ]
  32. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  33. for _group in _FILAMENT_TYPE_GROUPS:
  34. _canonical = _group[0].upper()
  35. for _t in _group:
  36. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  37. def _canonical_filament_type(ftype: str) -> str:
  38. """Return canonical type for equivalence matching."""
  39. upper = ftype.upper()
  40. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  41. class PrintScheduler:
  42. """Background scheduler that processes the print queue."""
  43. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  44. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  45. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  46. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  47. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  48. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  49. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  50. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  51. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  52. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  53. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  54. }
  55. def __init__(self):
  56. self._running = False
  57. self._check_interval = 30 # seconds
  58. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  59. self._power_on_check_interval = 10 # seconds between connection checks
  60. self._min_drying_seconds = 1800 # 30 minutes minimum before humidity re-check can stop drying
  61. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  62. self._drying_in_progress: dict[int, float] = {}
  63. async def run(self):
  64. """Main loop - check queue every interval."""
  65. self._running = True
  66. logger.info("Print scheduler started")
  67. while self._running:
  68. try:
  69. await self.check_queue()
  70. except Exception as e:
  71. logger.error("Scheduler error: %s", e)
  72. await asyncio.sleep(self._check_interval)
  73. def stop(self):
  74. """Stop the scheduler."""
  75. self._running = False
  76. logger.info("Print scheduler stopped")
  77. async def check_queue(self):
  78. """Check for prints ready to start."""
  79. async with async_session() as db:
  80. # Get all pending items, ordered by printer and position
  81. result = await db.execute(
  82. select(PrintQueueItem)
  83. .where(PrintQueueItem.status == "pending")
  84. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  85. )
  86. items = list(result.scalars().all())
  87. if not items:
  88. # No pending items — still check auto-drying on idle printers
  89. await self._check_auto_drying(db, [], set())
  90. return
  91. logger.info(
  92. "Queue check: found %d pending items: %s",
  93. len(items),
  94. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  95. )
  96. # Track busy printers to avoid assigning multiple items to same printer
  97. busy_printers: set[int] = set()
  98. # Log skip reasons once per queue check (not per item)
  99. skip_reasons: dict[str, int] = {}
  100. for item in items:
  101. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  102. if item.scheduled_time:
  103. sched = item.scheduled_time
  104. if sched.tzinfo is None:
  105. sched = sched.replace(tzinfo=timezone.utc)
  106. if sched > datetime.now(timezone.utc):
  107. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  108. continue
  109. # Skip items that require manual start
  110. if item.manual_start:
  111. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  112. continue
  113. if item.printer_id:
  114. # Specific printer assignment (existing behavior)
  115. if item.printer_id in busy_printers:
  116. continue
  117. # Check if printer is idle
  118. printer_idle = self._is_printer_idle(item.printer_id)
  119. printer_connected = printer_manager.is_connected(item.printer_id)
  120. # If printer not connected, try to power on via smart plug
  121. if not printer_connected:
  122. plug = await self._get_smart_plug(db, item.printer_id)
  123. if plug and plug.auto_on and plug.enabled:
  124. logger.info("Printer %s offline, attempting to power on via smart plug", item.printer_id)
  125. powered_on = await self._power_on_and_wait(plug, item.printer_id, db)
  126. if powered_on:
  127. printer_connected = True
  128. printer_idle = self._is_printer_idle(item.printer_id)
  129. else:
  130. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  131. busy_printers.add(item.printer_id)
  132. continue
  133. else:
  134. # No plug or auto_on disabled
  135. busy_printers.add(item.printer_id)
  136. continue
  137. # Check if printer is idle (busy with another print)
  138. if not printer_idle:
  139. # If printer is drying (not truly busy), handle based on queue_drying_block
  140. if self._drying_in_progress.get(item.printer_id):
  141. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  142. if block_for_drying:
  143. # Drying blocks queue — skip this printer
  144. busy_printers.add(item.printer_id)
  145. continue
  146. else:
  147. # Print takes priority — stop drying
  148. await self._stop_drying(item.printer_id)
  149. # Re-check idle after stopping drying
  150. printer_idle = self._is_printer_idle(item.printer_id)
  151. if not printer_idle:
  152. busy_printers.add(item.printer_id)
  153. continue
  154. else:
  155. busy_printers.add(item.printer_id)
  156. continue
  157. # Check condition (previous print success)
  158. if item.require_previous_success:
  159. if not await self._check_previous_success(db, item):
  160. item.status = "skipped"
  161. item.error_message = "Previous print failed or was aborted"
  162. item.completed_at = datetime.now(timezone.utc)
  163. await db.commit()
  164. logger.info("Skipped queue item %s - previous print failed", item.id)
  165. # Send notification
  166. job_name = await self._get_job_name(db, item)
  167. printer = await self._get_printer(db, item.printer_id)
  168. await notification_service.on_queue_job_skipped(
  169. job_name=job_name,
  170. printer_id=item.printer_id,
  171. printer_name=printer.name if printer else "Unknown",
  172. reason="Previous print failed or was aborted",
  173. db=db,
  174. )
  175. continue
  176. # Compute AMS mapping if not already set
  177. if not item.ams_mapping:
  178. computed_mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item)
  179. if computed_mapping:
  180. item.ams_mapping = json.dumps(computed_mapping)
  181. logger.info(
  182. f"Queue item {item.id}: Computed AMS mapping for printer {item.printer_id}: {computed_mapping}"
  183. )
  184. await db.commit()
  185. # Start the print
  186. await self._start_print(db, item)
  187. busy_printers.add(item.printer_id)
  188. elif item.target_model:
  189. # Model-based assignment - find any idle printer of matching model
  190. # Parse required filament types if present
  191. required_types = None
  192. if item.required_filament_types:
  193. try:
  194. required_types = json.loads(item.required_filament_types)
  195. except json.JSONDecodeError:
  196. pass # Ignore malformed filament types; treat as no constraint
  197. # Parse filament overrides if present
  198. filament_overrides = None
  199. if item.filament_overrides:
  200. try:
  201. filament_overrides = json.loads(item.filament_overrides)
  202. except json.JSONDecodeError:
  203. pass
  204. # If overrides exist, use override types for validation instead
  205. effective_types = required_types
  206. if filament_overrides:
  207. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  208. if override_types:
  209. # Merge: keep original types for non-overridden slots, add override types
  210. effective_types = sorted(set(required_types or []) | set(override_types))
  211. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  212. db,
  213. item.target_model,
  214. busy_printers,
  215. effective_types,
  216. item.target_location,
  217. filament_overrides=filament_overrides,
  218. )
  219. # Update waiting_reason if changed and send notification when first waiting
  220. if item.waiting_reason != waiting_reason:
  221. was_waiting = item.waiting_reason is not None
  222. item.waiting_reason = waiting_reason
  223. await db.commit()
  224. # Send waiting notification only when transitioning to waiting state
  225. # and the reason requires user action (not just "all printers busy")
  226. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  227. job_name = await self._get_job_name(db, item)
  228. await notification_service.on_queue_job_waiting(
  229. job_name=job_name,
  230. target_model=item.target_model,
  231. waiting_reason=waiting_reason,
  232. db=db,
  233. )
  234. if printer_id:
  235. # Check condition (previous print success) before assigning
  236. if item.require_previous_success:
  237. if not await self._check_previous_success(db, item):
  238. item.status = "skipped"
  239. item.error_message = "Previous print failed or was aborted"
  240. item.completed_at = datetime.now(timezone.utc)
  241. await db.commit()
  242. logger.info("Skipped queue item %s - previous print failed", item.id)
  243. # Send notification
  244. job_name = await self._get_job_name(db, item)
  245. printer = await self._get_printer(db, printer_id)
  246. await notification_service.on_queue_job_skipped(
  247. job_name=job_name,
  248. printer_id=printer_id,
  249. printer_name=printer.name if printer else "Unknown",
  250. reason="Previous print failed or was aborted",
  251. db=db,
  252. )
  253. continue
  254. # Assign printer and start - clear waiting reason
  255. item.printer_id = printer_id
  256. item.waiting_reason = None
  257. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  258. # Send assignment notification
  259. job_name = await self._get_job_name(db, item)
  260. printer = await self._get_printer(db, printer_id)
  261. await notification_service.on_queue_job_assigned(
  262. job_name=job_name,
  263. printer_id=printer_id,
  264. printer_name=printer.name if printer else "Unknown",
  265. target_model=item.target_model,
  266. db=db,
  267. )
  268. # Compute AMS mapping for the assigned printer if not already set
  269. # This is critical for model-based jobs where mapping wasn't computed upfront
  270. if not item.ams_mapping:
  271. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  272. if computed_mapping:
  273. item.ams_mapping = json.dumps(computed_mapping)
  274. logger.info(
  275. f"Queue item {item.id}: Computed AMS mapping for printer {printer_id}: {computed_mapping}"
  276. )
  277. await db.commit()
  278. await self._start_print(db, item)
  279. busy_printers.add(printer_id)
  280. # Log summary of skip reasons (helps diagnose why queue items aren't starting)
  281. if skip_reasons:
  282. logger.info("Queue skip summary: %s", skip_reasons)
  283. if busy_printers:
  284. # Log why each printer was busy (first time it was checked)
  285. for pid in busy_printers:
  286. state = printer_manager.get_status(pid)
  287. connected = printer_manager.is_connected(pid)
  288. plate_cleared = printer_manager.is_plate_cleared(pid)
  289. state_name = state.state if state else "NO_STATUS"
  290. logger.info(
  291. "Queue: printer %d not available — connected=%s, state=%s, plate_cleared=%s",
  292. pid,
  293. connected,
  294. state_name,
  295. plate_cleared,
  296. )
  297. # Auto-drying: start drying on idle printers that have no pending queue items
  298. await self._check_auto_drying(db, items, busy_printers)
  299. async def _find_idle_printer_for_model(
  300. self,
  301. db: AsyncSession,
  302. model: str,
  303. exclude_ids: set[int],
  304. required_filament_types: list[str] | None = None,
  305. target_location: str | None = None,
  306. filament_overrides: list[dict] | None = None,
  307. ) -> tuple[int | None, str | None]:
  308. """Find an idle, connected printer matching the model with compatible filaments.
  309. Args:
  310. db: Database session
  311. model: Printer model to match (e.g., "X1C", "P1S")
  312. exclude_ids: Printer IDs to exclude (already busy)
  313. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  314. If provided, only printers with all required types loaded will match.
  315. target_location: Optional location filter. If provided, only printers in this location are considered.
  316. filament_overrides: Optional list of override dicts. Each entry may include
  317. ``force_color_match: true`` to require an exact type+color match
  318. on the printer for that slot. Without the flag the existing
  319. colour-preference logic applies.
  320. Returns:
  321. Tuple of (printer_id, waiting_reason):
  322. - (printer_id, None) if a matching printer was found
  323. - (None, reason) if no printer is available, with explanation
  324. """
  325. # Normalize model name and use case-insensitive matching
  326. normalized_model = normalize_printer_model(model) or model
  327. query = (
  328. select(Printer)
  329. .where(func.lower(Printer.model) == normalized_model.lower())
  330. .where(Printer.is_active == True) # noqa: E712
  331. )
  332. # Add location filter if specified
  333. if target_location:
  334. query = query.where(Printer.location == target_location)
  335. result = await db.execute(query)
  336. printers = list(result.scalars().all())
  337. location_suffix = f" in {target_location}" if target_location else ""
  338. if not printers:
  339. return None, f"No active {normalized_model} printers{location_suffix} configured"
  340. # Separate force-matched overrides from preference-only overrides
  341. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  342. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  343. # Track reasons for skipping printers
  344. printers_busy = []
  345. printers_offline = []
  346. printers_missing_filament: list[tuple[str, list[str]]] = []
  347. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  348. for printer in printers:
  349. if printer.id in exclude_ids:
  350. # Printer is already claimed by another job in this scheduling run.
  351. # For force-color jobs, still check if the color would match — if not,
  352. # report it as a color mismatch rather than plain "Busy" so the user
  353. # knows the job needs a filament change, not just to wait for availability.
  354. if force_overrides and not pref_overrides:
  355. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  356. if missing_colors:
  357. printers_missing_filament.append((printer.name, missing_colors))
  358. continue
  359. printers_busy.append(printer.name)
  360. continue
  361. is_connected = printer_manager.is_connected(printer.id)
  362. is_idle = self._is_printer_idle(printer.id) if is_connected else False
  363. if not is_connected:
  364. printers_offline.append(printer.name)
  365. continue
  366. if not is_idle:
  367. # Printer is currently printing. For force-color jobs, check whether the
  368. # loaded color would satisfy the requirement — if not, surface it as a
  369. # color-mismatch reason rather than plain "Busy" so the user understands
  370. # that the job is waiting for a filament change, not just printer availability.
  371. if force_overrides and not pref_overrides:
  372. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  373. if missing_colors:
  374. printers_missing_filament.append((printer.name, missing_colors))
  375. logger.debug(
  376. "Printer %s (%s) is busy but also has wrong force-color: %s",
  377. printer.id,
  378. printer.name,
  379. missing_colors,
  380. )
  381. continue
  382. printers_busy.append(printer.name)
  383. continue
  384. # Validate filament compatibility if required types are specified
  385. if required_filament_types:
  386. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  387. if missing:
  388. # When force_overrides are present, enrich missing entries with color info
  389. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  390. if force_overrides:
  391. force_color_map = {
  392. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  393. for o in force_overrides
  394. }
  395. missing_enriched = [
  396. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  397. for t in missing
  398. ]
  399. printers_missing_filament.append((printer.name, missing_enriched))
  400. else:
  401. printers_missing_filament.append((printer.name, missing))
  402. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  403. continue
  404. # Force color match: ALL flagged slots must have an exact type+color match
  405. if force_overrides:
  406. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  407. if missing_colors:
  408. printers_missing_filament.append((printer.name, missing_colors))
  409. logger.debug(
  410. "Skipping printer %s (%s) - missing force-matched colors: %s",
  411. printer.id,
  412. printer.name,
  413. missing_colors,
  414. )
  415. continue
  416. # If preference-only overrides exist, rank by color matches (existing behaviour)
  417. if pref_overrides:
  418. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  419. if color_matches > 0:
  420. candidates.append((printer.id, color_matches))
  421. else:
  422. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  423. printers_missing_filament.append((printer.name, override_colors))
  424. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  425. continue
  426. elif force_overrides:
  427. # Passed all force checks — immediately eligible (no preference ordering needed)
  428. return printer.id, None
  429. else:
  430. # No overrides at all - take first available (existing behavior)
  431. return printer.id, None
  432. # If we have candidates from preference override matching, pick the one with most color matches
  433. if candidates:
  434. candidates.sort(key=lambda c: c[1], reverse=True)
  435. return candidates[0][0], None
  436. # Build waiting reason from what we found
  437. reasons = []
  438. if printers_missing_filament:
  439. # Filament/color mismatch is most actionable - show first
  440. if force_overrides and not pref_overrides:
  441. # All mismatches are force-color failures — use descriptive message only;
  442. # but only if there are no busy printers that DO have the matching color.
  443. # If a printer has the right color but is busy, surface "Busy" instead so
  444. # the user knows the job will start automatically once that printer is free.
  445. if not printers_busy:
  446. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  447. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  448. # else: fall through — printers_busy will be appended below
  449. else:
  450. names_and_missing = [
  451. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  452. ]
  453. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  454. if printers_busy:
  455. reasons.append(f"Busy: {', '.join(printers_busy)}")
  456. if printers_offline:
  457. reasons.append(f"Offline: {', '.join(printers_offline)}")
  458. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  459. @staticmethod
  460. def _is_busy_only(waiting_reason: str) -> bool:
  461. """Check if the waiting reason only contains 'Busy' entries.
  462. When all matching printers are simply busy printing, the queued job
  463. will start automatically once a printer finishes — no user action
  464. is required, so we skip the notification.
  465. """
  466. parts = [p.strip() for p in waiting_reason.split(" | ")]
  467. return all(p.startswith("Busy:") for p in parts)
  468. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  469. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  470. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  471. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  472. with an exact type+color match.
  473. Returns:
  474. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  475. """
  476. status = printer_manager.get_status(printer_id)
  477. if not status:
  478. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  479. # Build set of loaded type+colour pairs from AMS and external spool
  480. loaded: set[tuple[str, str]] = set()
  481. for ams_unit in status.raw_data.get("ams", []):
  482. for tray in ams_unit.get("tray", []):
  483. tray_type = tray.get("tray_type")
  484. tray_color = tray.get("tray_color", "")
  485. if tray_type:
  486. color_norm = tray_color.replace("#", "").lower()[:6]
  487. loaded.add((_canonical_filament_type(tray_type), color_norm))
  488. for vt in status.raw_data.get("vt_tray") or []:
  489. vt_type = vt.get("tray_type")
  490. if vt_type:
  491. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  492. loaded.add((_canonical_filament_type(vt_type), color_norm))
  493. missing = []
  494. for o in force_overrides:
  495. o_type = _canonical_filament_type(o.get("type") or "")
  496. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  497. if (o_type, o_color) not in loaded:
  498. color_label = o.get("color_name") or o.get("color", "?")
  499. missing.append(f"{o_type} ({color_label})")
  500. return missing
  501. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  502. """Get the list of required filament types that are not loaded on the printer.
  503. Args:
  504. printer_id: The printer ID
  505. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  506. Returns:
  507. List of missing filament types (empty if all are loaded)
  508. """
  509. status = printer_manager.get_status(printer_id)
  510. if not status:
  511. return required_types # Can't determine, assume all missing
  512. # Collect all filament types loaded on this printer (AMS units + external spool)
  513. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  514. loaded_types: set[str] = set()
  515. # Check AMS units (stored in raw_data["ams"])
  516. ams_data = status.raw_data.get("ams", [])
  517. if ams_data:
  518. for ams_unit in ams_data:
  519. for tray in ams_unit.get("tray", []):
  520. tray_type = tray.get("tray_type")
  521. if tray_type:
  522. loaded_types.add(_canonical_filament_type(tray_type))
  523. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  524. for vt in status.raw_data.get("vt_tray") or []:
  525. vt_type = vt.get("tray_type")
  526. if vt_type:
  527. loaded_types.add(_canonical_filament_type(vt_type))
  528. # Find which required types are missing (using canonical type for equivalence)
  529. missing = []
  530. for req_type in required_types:
  531. if _canonical_filament_type(req_type) not in loaded_types:
  532. missing.append(req_type)
  533. return missing
  534. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  535. """Count how many filament overrides have an exact color match on the printer.
  536. Used to prefer printers that already have the desired override colors loaded.
  537. """
  538. status = printer_manager.get_status(printer_id)
  539. if not status:
  540. return 0
  541. # Collect loaded filaments' type+color pairs
  542. loaded: set[tuple[str, str]] = set()
  543. for ams_unit in status.raw_data.get("ams", []):
  544. for tray in ams_unit.get("tray", []):
  545. tray_type = tray.get("tray_type")
  546. tray_color = tray.get("tray_color", "")
  547. if tray_type:
  548. color_norm = tray_color.replace("#", "").lower()[:6]
  549. loaded.add((tray_type.upper(), color_norm))
  550. for vt in status.raw_data.get("vt_tray") or []:
  551. vt_type = vt.get("tray_type")
  552. if vt_type:
  553. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  554. loaded.add((vt_type.upper(), color_norm))
  555. matches = 0
  556. for o in overrides:
  557. o_type = (o.get("type") or "").upper()
  558. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  559. if (o_type, o_color) in loaded:
  560. matches += 1
  561. return matches
  562. async def _compute_ams_mapping_for_printer(
  563. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  564. ) -> list[int] | None:
  565. """Compute AMS mapping for a printer based on filament requirements.
  566. Called when a queue item has no ams_mapping set — either for model-based
  567. items after printer assignment, or printer-specific items (e.g. from VP).
  568. Args:
  569. db: Database session
  570. printer_id: The assigned printer ID
  571. item: The queue item (contains archive_id or library_file_id)
  572. Returns:
  573. AMS mapping array or None if no mapping needed/possible
  574. """
  575. # Get printer status
  576. status = printer_manager.get_status(printer_id)
  577. if not status:
  578. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  579. return None
  580. # Get filament requirements from source file
  581. filament_reqs = await self._get_filament_requirements(db, item)
  582. if not filament_reqs:
  583. logger.debug("No filament requirements found for queue item %s", item.id)
  584. return None
  585. # Apply filament overrides if present
  586. if item.filament_overrides:
  587. try:
  588. overrides = json.loads(item.filament_overrides)
  589. override_map = {o["slot_id"]: o for o in overrides}
  590. for req in filament_reqs:
  591. if req["slot_id"] in override_map:
  592. override = override_map[req["slot_id"]]
  593. req["type"] = override["type"]
  594. req["color"] = override["color"]
  595. # Clear tray_info_idx so matching uses type+color instead of
  596. # the original 3MF's tray_info_idx (which would match the old filament)
  597. req["tray_info_idx"] = ""
  598. logger.debug(
  599. "Queue item %s: Override slot %d -> %s %s",
  600. item.id,
  601. req["slot_id"],
  602. override["type"],
  603. override["color"],
  604. )
  605. except (json.JSONDecodeError, KeyError, TypeError) as e:
  606. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  607. # Build loaded filaments from printer status
  608. loaded_filaments = self._build_loaded_filaments(status)
  609. if not loaded_filaments:
  610. logger.debug("No filaments loaded on printer %s", printer_id)
  611. return None
  612. # Compute mapping: match required filaments to available slots
  613. return self._match_filaments_to_slots(filament_reqs, loaded_filaments)
  614. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  615. """Extract filament requirements from the source 3MF file.
  616. Args:
  617. db: Database session
  618. item: Queue item with archive_id or library_file_id
  619. Returns:
  620. List of filament requirement dicts with slot_id, type, color, used_grams
  621. """
  622. file_path: Path | None = None
  623. if item.archive_id:
  624. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  625. archive = result.scalar_one_or_none()
  626. if archive:
  627. file_path = settings.base_dir / archive.file_path
  628. elif item.library_file_id:
  629. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  630. library_file = result.scalar_one_or_none()
  631. if library_file:
  632. lib_path = Path(library_file.file_path)
  633. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  634. if not file_path or not file_path.exists():
  635. return None
  636. filaments = []
  637. try:
  638. with zipfile.ZipFile(file_path, "r") as zf:
  639. if "Metadata/slice_info.config" not in zf.namelist():
  640. return None
  641. content = zf.read("Metadata/slice_info.config").decode()
  642. root = ET.fromstring(content)
  643. # Check if plate_id is specified - use that plate's filaments
  644. plate_id = item.plate_id
  645. if plate_id:
  646. for plate_elem in root.findall("./plate"):
  647. plate_index = None
  648. for meta in plate_elem.findall("metadata"):
  649. if meta.get("key") == "index":
  650. plate_index = int(meta.get("value", "0"))
  651. break
  652. if plate_index == plate_id:
  653. for filament_elem in plate_elem.findall("./filament"):
  654. filament_id = filament_elem.get("id")
  655. filament_type = filament_elem.get("type", "")
  656. filament_color = filament_elem.get("color", "")
  657. # tray_info_idx identifies the specific spool selected when slicing
  658. tray_info_idx = filament_elem.get("tray_info_idx", "")
  659. used_g = filament_elem.get("used_g", "0")
  660. try:
  661. used_grams = float(used_g)
  662. if used_grams > 0 and filament_id:
  663. filaments.append(
  664. {
  665. "slot_id": int(filament_id),
  666. "type": filament_type,
  667. "color": filament_color,
  668. "tray_info_idx": tray_info_idx,
  669. "used_grams": round(used_grams, 1),
  670. }
  671. )
  672. except (ValueError, TypeError):
  673. pass # Skip filament entry with unparseable usage data
  674. break
  675. else:
  676. # No plate_id - extract all filaments with used_g > 0
  677. for filament_elem in root.findall("./filament"):
  678. filament_id = filament_elem.get("id")
  679. filament_type = filament_elem.get("type", "")
  680. filament_color = filament_elem.get("color", "")
  681. # tray_info_idx identifies the specific spool selected when slicing
  682. tray_info_idx = filament_elem.get("tray_info_idx", "")
  683. used_g = filament_elem.get("used_g", "0")
  684. try:
  685. used_grams = float(used_g)
  686. if used_grams > 0 and filament_id:
  687. filaments.append(
  688. {
  689. "slot_id": int(filament_id),
  690. "type": filament_type,
  691. "color": filament_color,
  692. "tray_info_idx": tray_info_idx,
  693. "used_grams": round(used_grams, 1),
  694. }
  695. )
  696. except (ValueError, TypeError):
  697. pass # Skip filament entry with unparseable usage data
  698. filaments.sort(key=lambda x: x["slot_id"])
  699. # Enrich with nozzle mapping for dual-nozzle printers
  700. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  701. if nozzle_mapping:
  702. for filament in filaments:
  703. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  704. except Exception as e:
  705. logger.warning("Failed to parse filament requirements: %s", e)
  706. return None
  707. return filaments if filaments else None
  708. def _build_loaded_filaments(self, status) -> list[dict]:
  709. """Build list of loaded filaments from printer status.
  710. Args:
  711. status: PrinterState from printer_manager
  712. Returns:
  713. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  714. """
  715. filaments = []
  716. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  717. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  718. # Parse AMS units from raw_data
  719. ams_data = status.raw_data.get("ams", [])
  720. for ams_unit in ams_data:
  721. ams_id = int(ams_unit.get("id", 0))
  722. trays = ams_unit.get("tray", [])
  723. is_ht = len(trays) == 1 # AMS-HT has single tray
  724. for tray in trays:
  725. tray_type = tray.get("tray_type")
  726. if tray_type:
  727. tray_id = int(tray.get("id", 0))
  728. tray_color = tray.get("tray_color", "")
  729. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  730. tray_info_idx = tray.get("tray_info_idx", "")
  731. # Normalize color: remove alpha, add hash
  732. color = self._normalize_color(tray_color)
  733. # Calculate global tray ID
  734. # AMS-HT units have IDs starting at 128 with a single tray
  735. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  736. filaments.append(
  737. {
  738. "type": tray_type,
  739. "color": color,
  740. "tray_info_idx": tray_info_idx,
  741. "ams_id": ams_id,
  742. "tray_id": tray_id,
  743. "is_ht": is_ht,
  744. "is_external": False,
  745. "global_tray_id": global_tray_id,
  746. "extruder_id": ams_extruder_map.get(str(ams_id)),
  747. }
  748. )
  749. # Check external spool(s) (vt_tray is a list)
  750. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  751. if vt.get("tray_type"):
  752. color = self._normalize_color(vt.get("tray_color", ""))
  753. tray_id = int(vt.get("id", 254))
  754. filaments.append(
  755. {
  756. "type": vt["tray_type"],
  757. "color": color,
  758. "tray_info_idx": vt.get("tray_info_idx", ""),
  759. "ams_id": -1,
  760. "tray_id": idx,
  761. "is_ht": False,
  762. "is_external": True,
  763. "global_tray_id": tray_id,
  764. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  765. }
  766. )
  767. return filaments
  768. def _normalize_color(self, color: str | None) -> str:
  769. """Normalize color to #RRGGBB format."""
  770. if not color:
  771. return "#808080"
  772. hex_color = color.replace("#", "")[:6]
  773. return f"#{hex_color}"
  774. def _normalize_color_for_compare(self, color: str | None) -> str:
  775. """Normalize color for comparison (lowercase, no hash)."""
  776. if not color:
  777. return ""
  778. return color.replace("#", "").lower()[:6]
  779. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  780. """Check if two colors are visually similar within a threshold."""
  781. hex1 = self._normalize_color_for_compare(color1)
  782. hex2 = self._normalize_color_for_compare(color2)
  783. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  784. return False
  785. try:
  786. r1 = int(hex1[0:2], 16)
  787. g1 = int(hex1[2:4], 16)
  788. b1 = int(hex1[4:6], 16)
  789. r2 = int(hex2[0:2], 16)
  790. g2 = int(hex2[2:4], 16)
  791. b2 = int(hex2[4:6], 16)
  792. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  793. except ValueError:
  794. return False
  795. def _match_filaments_to_slots(self, required: list[dict], loaded: list[dict]) -> list[int] | None:
  796. """Match required filaments to loaded filaments and build AMS mapping.
  797. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  798. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  799. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  800. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  801. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  802. matching among those trays.
  803. Args:
  804. required: List of required filaments with slot_id, type, color, tray_info_idx
  805. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  806. Returns:
  807. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  808. """
  809. if not required:
  810. return None
  811. # Track used trays to avoid duplicate assignment
  812. used_tray_ids: set[int] = set()
  813. comparisons = []
  814. for req in required:
  815. req_type = (req.get("type") or "").upper()
  816. req_color = req.get("color", "")
  817. req_tray_info_idx = req.get("tray_info_idx", "")
  818. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  819. idx_match = None
  820. exact_match = None
  821. similar_match = None
  822. type_only_match = None
  823. # Get available trays (not already used)
  824. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  825. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  826. # Hard filter — cross-nozzle assignment causes print failures
  827. # ("position of left hotend is abnormal"), so never fall back.
  828. req_nozzle_id = req.get("nozzle_id")
  829. if req_nozzle_id is not None:
  830. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  831. # Check if tray_info_idx is unique among available trays
  832. if req_tray_info_idx:
  833. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  834. if len(idx_matches) == 1:
  835. # Unique tray_info_idx - use it as definitive match
  836. idx_match = idx_matches[0]
  837. logger.debug(
  838. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  839. f"-> tray {idx_match['global_tray_id']}"
  840. )
  841. elif len(idx_matches) > 1:
  842. # Multiple trays with same tray_info_idx - use color matching among them
  843. logger.debug(
  844. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  845. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  846. )
  847. # Use color matching within this subset
  848. for f in idx_matches:
  849. f_color = f.get("color", "")
  850. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  851. if not exact_match:
  852. exact_match = f
  853. elif self._colors_are_similar(f_color, req_color):
  854. if not similar_match:
  855. similar_match = f
  856. elif not type_only_match:
  857. type_only_match = f
  858. # If no idx_match yet, do standard type/color matching on all available trays
  859. if not idx_match and not exact_match and not similar_match and not type_only_match:
  860. for f in available:
  861. f_type = (f.get("type") or "").upper()
  862. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  863. continue
  864. # Type matches - check color
  865. f_color = f.get("color", "")
  866. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  867. if not exact_match:
  868. exact_match = f
  869. elif self._colors_are_similar(f_color, req_color):
  870. if not similar_match:
  871. similar_match = f
  872. elif not type_only_match:
  873. type_only_match = f
  874. match = idx_match or exact_match or similar_match or type_only_match
  875. if match:
  876. used_tray_ids.add(match["global_tray_id"])
  877. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  878. else:
  879. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  880. # Build mapping array
  881. if not comparisons:
  882. return None
  883. max_slot_id = max(c["slot_id"] for c in comparisons)
  884. if max_slot_id <= 0:
  885. return None
  886. mapping = [-1] * max_slot_id
  887. for c in comparisons:
  888. slot_id = c["slot_id"]
  889. if slot_id and slot_id > 0:
  890. mapping[slot_id - 1] = c["global_tray_id"]
  891. return mapping
  892. def _is_printer_idle(self, printer_id: int) -> bool:
  893. """Check if a printer is connected and idle."""
  894. if not printer_manager.is_connected(printer_id):
  895. logger.debug("Printer %d: not connected", printer_id)
  896. return False
  897. state = printer_manager.get_status(printer_id)
  898. if not state:
  899. logger.debug("Printer %d: no status available", printer_id)
  900. return False
  901. # IDLE = ready for next print
  902. # FINISH/FAILED = ready only if user confirmed plate is cleared
  903. idle = state.state == "IDLE" or (
  904. state.state in ("FINISH", "FAILED") and printer_manager.is_plate_cleared(printer_id)
  905. )
  906. if not idle:
  907. logger.debug(
  908. "Printer %d: not idle — state=%s, plate_cleared=%s",
  909. printer_id,
  910. state.state,
  911. printer_manager.is_plate_cleared(printer_id),
  912. )
  913. return idle
  914. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  915. """Read a boolean setting from the database."""
  916. result = await db.execute(select(Settings).where(Settings.key == key))
  917. setting = result.scalar_one_or_none()
  918. if setting:
  919. return setting.value.lower() == "true"
  920. return default
  921. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  922. """Get drying presets (user-configured or built-in defaults)."""
  923. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  924. setting = result.scalar_one_or_none()
  925. if setting and setting.value:
  926. try:
  927. presets = json.loads(setting.value)
  928. if isinstance(presets, dict) and presets:
  929. return presets
  930. except json.JSONDecodeError:
  931. pass
  932. return self.DEFAULT_DRYING_PRESETS
  933. def _get_conservative_drying_params(
  934. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  935. ) -> tuple[int, int, str] | None:
  936. """Get the most conservative drying params for mixed filament types in an AMS unit.
  937. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  938. """
  939. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  940. hours_key = f"{temp_key}_hours"
  941. min_temp = None
  942. max_hours = None
  943. filament_type = ""
  944. for tray in trays:
  945. tray_type = tray.get("tray_type", "")
  946. if not tray_type:
  947. continue
  948. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  949. base_type = tray_type.split()[0].upper()
  950. preset = presets.get(base_type)
  951. if not preset:
  952. continue
  953. temp = preset.get(temp_key, 55)
  954. hours = preset.get(hours_key, 12)
  955. # Conservative: lowest temp, longest duration
  956. if min_temp is None or temp < min_temp:
  957. min_temp = temp
  958. if max_hours is None or hours > max_hours:
  959. max_hours = hours
  960. if not filament_type:
  961. filament_type = base_type
  962. if min_temp is None:
  963. return None
  964. return (min_temp, max_hours or 12, filament_type)
  965. async def _check_auto_drying(self, db: AsyncSession, queue_items: list[PrintQueueItem], busy_printers: set[int]):
  966. """Start drying on idle printers based on humidity.
  967. Two modes (can both be enabled):
  968. - queue_drying_enabled: Dry between scheduled queue prints
  969. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  970. """
  971. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  972. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  973. if not queue_drying_enabled and not ambient_drying_enabled:
  974. # Stop active drying on all printers if both features disabled
  975. if self._drying_in_progress:
  976. for pid in list(self._drying_in_progress):
  977. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  978. await self._stop_drying(pid)
  979. return
  980. # Update drying state from printer status (handles backend restart)
  981. self._sync_drying_state()
  982. # Find printers with scheduled items (for queue drying mode)
  983. printers_with_scheduled: set[int] = set()
  984. printers_with_items: set[int] = set()
  985. for item in queue_items:
  986. if item.printer_id:
  987. printers_with_items.add(item.printer_id)
  988. if item.scheduled_time and not item.manual_start:
  989. printers_with_scheduled.add(item.printer_id)
  990. # If only queue mode is on and no printers have scheduled items, stop drying
  991. if not ambient_drying_enabled and not printers_with_scheduled:
  992. for pid in list(self._drying_in_progress):
  993. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  994. await self._stop_drying(pid)
  995. return
  996. # Get humidity threshold
  997. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  998. setting = result.scalar_one_or_none()
  999. humidity_threshold = int(setting.value) if setting else 60
  1000. # Get drying presets
  1001. presets = await self._get_drying_presets(db)
  1002. # Determine if drying should be skipped for printers with pending items
  1003. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1004. # Get all active printers
  1005. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1006. for printer in all_printers.scalars():
  1007. pid = printer.id
  1008. if pid in busy_printers:
  1009. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1010. continue
  1011. # In queue-only mode, only dry printers that have scheduled prints
  1012. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1013. if self._drying_in_progress.get(pid):
  1014. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1015. await self._stop_drying(pid)
  1016. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1017. continue
  1018. # When block mode is on, don't START new drying on printers with pending items.
  1019. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1020. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1021. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1022. continue
  1023. if not printer_manager.is_connected(pid):
  1024. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1025. continue
  1026. if not self._is_printer_idle(pid):
  1027. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1028. continue
  1029. # Check if this printer supports drying
  1030. state = printer_manager.get_status(pid)
  1031. if not state:
  1032. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1033. continue
  1034. model = printer_manager.get_model(pid)
  1035. firmware = state.firmware_version
  1036. if not supports_drying(model, firmware):
  1037. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1038. continue
  1039. # Check each AMS unit from raw_data
  1040. ams_list = state.raw_data.get("ams", [])
  1041. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1042. for ams_data in ams_list:
  1043. module_type = str(ams_data.get("module_type") or "")
  1044. ams_id = int(ams_data.get("id", 0))
  1045. # Only n3f/n3s support drying
  1046. if module_type not in ("n3f", "n3s"):
  1047. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1048. continue
  1049. dry_time = int(ams_data.get("dry_time") or 0)
  1050. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1051. humidity = None
  1052. h_raw = ams_data.get("humidity_raw")
  1053. if h_raw is not None:
  1054. try:
  1055. humidity = int(h_raw)
  1056. except (ValueError, TypeError):
  1057. pass
  1058. if humidity is None:
  1059. h_idx = ams_data.get("humidity")
  1060. if h_idx is not None:
  1061. try:
  1062. humidity = int(h_idx)
  1063. except (ValueError, TypeError):
  1064. pass
  1065. # Already drying — check if humidity dropped below threshold (with minimum drying time)
  1066. if dry_time > 0:
  1067. if pid not in self._drying_in_progress:
  1068. # Drying we didn't start (manual or from before restart) — track but don't stop
  1069. self._drying_in_progress[pid] = time.monotonic()
  1070. started_at = self._drying_in_progress[pid]
  1071. elapsed = time.monotonic() - started_at
  1072. if humidity is not None and humidity <= humidity_threshold and elapsed >= self._min_drying_seconds:
  1073. logger.info(
  1074. "Auto-drying: printer %d AMS %d — humidity %d%% <= threshold %d%% after %dm, stopping drying",
  1075. pid,
  1076. ams_id,
  1077. humidity,
  1078. humidity_threshold,
  1079. int(elapsed / 60),
  1080. )
  1081. printer_manager.send_drying_command(pid, ams_id, temp=0, duration=0, mode=0)
  1082. else:
  1083. logger.debug(
  1084. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%, elapsed %dm/%dm min)",
  1085. pid,
  1086. ams_id,
  1087. dry_time,
  1088. humidity,
  1089. int(elapsed / 60),
  1090. self._min_drying_seconds // 60,
  1091. )
  1092. continue
  1093. # Humidity below threshold — no need to start drying
  1094. if humidity is None or humidity <= humidity_threshold:
  1095. logger.debug(
  1096. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1097. pid,
  1098. ams_id,
  1099. humidity,
  1100. humidity_threshold,
  1101. )
  1102. continue
  1103. # Check cannot-dry reasons (power constraints etc.)
  1104. sf_reasons = ams_data.get("dry_sf_reason", [])
  1105. if sf_reasons:
  1106. logger.debug(
  1107. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1108. pid,
  1109. ams_id,
  1110. sf_reasons,
  1111. )
  1112. continue
  1113. # Get conservative drying params for mixed filaments
  1114. trays = ams_data.get("tray", [])
  1115. params = self._get_conservative_drying_params(trays, module_type, presets)
  1116. if not params:
  1117. logger.debug(
  1118. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1119. )
  1120. continue
  1121. temp, duration_hours, filament_type = params
  1122. # Start drying
  1123. logger.info(
  1124. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1125. "starting %s drying at %d°C for %dh",
  1126. pid,
  1127. ams_id,
  1128. humidity,
  1129. humidity_threshold,
  1130. filament_type,
  1131. temp,
  1132. duration_hours,
  1133. )
  1134. success = printer_manager.send_drying_command(
  1135. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1136. )
  1137. if success:
  1138. self._drying_in_progress[pid] = time.monotonic()
  1139. def _sync_drying_state(self):
  1140. """Sync in-memory drying state with actual printer status.
  1141. Handles backend restart — if a printer is drying but we don't know about it,
  1142. update our state. If we think it's drying but it's not, clear it.
  1143. """
  1144. to_remove = []
  1145. for pid in self._drying_in_progress:
  1146. state = printer_manager.get_status(pid)
  1147. if not state:
  1148. to_remove.append(pid)
  1149. continue
  1150. # Check if any AMS unit is still drying
  1151. ams_list = state.raw_data.get("ams", [])
  1152. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1153. if not any_drying:
  1154. to_remove.append(pid)
  1155. for pid in to_remove:
  1156. self._drying_in_progress.pop(pid, None)
  1157. async def _stop_drying(self, printer_id: int):
  1158. """Stop all active drying on a printer (print takes priority)."""
  1159. state = printer_manager.get_status(printer_id)
  1160. if not state:
  1161. self._drying_in_progress.pop(printer_id, None)
  1162. return
  1163. ams_list = state.raw_data.get("ams", [])
  1164. for ams_data in ams_list:
  1165. dry_time = int(ams_data.get("dry_time") or 0)
  1166. if dry_time > 0:
  1167. ams_id = int(ams_data.get("id", 0))
  1168. logger.info(
  1169. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1170. printer_id,
  1171. ams_id,
  1172. )
  1173. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1174. self._drying_in_progress.pop(printer_id, None)
  1175. async def _get_smart_plug(self, db: AsyncSession, printer_id: int) -> SmartPlug | None:
  1176. """Get the smart plug associated with a printer."""
  1177. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1178. return result.scalar_one_or_none()
  1179. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1180. """Turn on smart plug and wait for printer to connect.
  1181. Returns True if printer connected successfully within timeout.
  1182. """
  1183. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1184. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1185. # Check current plug state
  1186. status = await service.get_status(plug)
  1187. if not status.get("reachable"):
  1188. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1189. return False
  1190. # Turn on if not already on
  1191. if status.get("state") != "ON":
  1192. success = await service.turn_on(plug)
  1193. if not success:
  1194. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  1195. return False
  1196. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  1197. # Get printer from database for connection
  1198. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1199. printer = result.scalar_one_or_none()
  1200. if not printer:
  1201. logger.error("Printer %s not found in database", printer_id)
  1202. return False
  1203. # Wait for printer to boot (give it some time before trying to connect)
  1204. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  1205. await asyncio.sleep(30)
  1206. # Try to connect to the printer periodically
  1207. elapsed = 30 # Already waited 30s
  1208. while elapsed < self._power_on_wait_time:
  1209. # Try to connect
  1210. logger.info("Attempting to connect to printer %s...", printer_id)
  1211. try:
  1212. connected = await printer_manager.connect_printer(printer)
  1213. if connected:
  1214. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  1215. # Give it a moment to stabilize and get status
  1216. await asyncio.sleep(5)
  1217. return True
  1218. except Exception as e:
  1219. logger.debug("Connection attempt failed: %s", e)
  1220. await asyncio.sleep(self._power_on_check_interval)
  1221. elapsed += self._power_on_check_interval
  1222. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  1223. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  1224. return False
  1225. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  1226. """Check if the previous print on this printer succeeded."""
  1227. # Find the most recent completed queue item for this printer
  1228. result = await db.execute(
  1229. select(PrintQueueItem)
  1230. .where(PrintQueueItem.printer_id == item.printer_id)
  1231. .where(PrintQueueItem.id != item.id)
  1232. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  1233. .order_by(PrintQueueItem.completed_at.desc())
  1234. .limit(1)
  1235. )
  1236. prev_item = result.scalar_one_or_none()
  1237. # If no previous item, assume success (first in queue)
  1238. if not prev_item:
  1239. return True
  1240. return prev_item.status == "completed"
  1241. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  1242. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  1243. if not item.auto_off_after:
  1244. return
  1245. plug = await self._get_smart_plug(db, item.printer_id)
  1246. if plug and plug.enabled:
  1247. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  1248. # Wait for cooldown (up to 10 minutes)
  1249. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  1250. logger.info("Auto-off: Powering off printer %s", item.printer_id)
  1251. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1252. await service.turn_off(plug)
  1253. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  1254. """Get a human-readable name for a queue item."""
  1255. if item.archive_id:
  1256. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1257. archive = result.scalar_one_or_none()
  1258. if archive:
  1259. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1260. if item.library_file_id:
  1261. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1262. library_file = result.scalar_one_or_none()
  1263. if library_file:
  1264. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1265. return f"Job #{item.id}"
  1266. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  1267. """Get printer by ID."""
  1268. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1269. return result.scalar_one_or_none()
  1270. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  1271. """Upload file and start print for a queue item.
  1272. Supports two sources:
  1273. - archive_id: Print from an existing archive
  1274. - library_file_id: Print from a library file (file manager)
  1275. """
  1276. logger.info("Starting queue item %s", item.id)
  1277. # Get printer first (needed for both paths)
  1278. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  1279. printer = result.scalar_one_or_none()
  1280. if not printer:
  1281. item.status = "failed"
  1282. item.error_message = "Printer not found"
  1283. item.completed_at = datetime.now(timezone.utc)
  1284. await db.commit()
  1285. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  1286. await self._power_off_if_needed(db, item)
  1287. return
  1288. # Check printer is connected
  1289. if not printer_manager.is_connected(item.printer_id):
  1290. item.status = "failed"
  1291. item.error_message = "Printer not connected"
  1292. item.completed_at = datetime.now(timezone.utc)
  1293. await db.commit()
  1294. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  1295. await self._power_off_if_needed(db, item)
  1296. return
  1297. # Determine source: archive or library file
  1298. archive = None
  1299. library_file = None
  1300. file_path = None
  1301. filename = None
  1302. if item.archive_id:
  1303. # Print from archive
  1304. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1305. archive = result.scalar_one_or_none()
  1306. if not archive:
  1307. item.status = "failed"
  1308. item.error_message = "Archive not found"
  1309. item.completed_at = datetime.now(timezone.utc)
  1310. await db.commit()
  1311. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  1312. await self._power_off_if_needed(db, item)
  1313. return
  1314. file_path = settings.base_dir / archive.file_path
  1315. filename = archive.filename
  1316. elif item.library_file_id:
  1317. # Print from library file (file manager)
  1318. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1319. library_file = result.scalar_one_or_none()
  1320. if not library_file:
  1321. item.status = "failed"
  1322. item.error_message = "Library file not found"
  1323. item.completed_at = datetime.now(timezone.utc)
  1324. await db.commit()
  1325. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  1326. await self._power_off_if_needed(db, item)
  1327. return
  1328. # Library files store absolute paths
  1329. lib_path = Path(library_file.file_path)
  1330. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1331. filename = library_file.filename
  1332. # Create archive from library file so usage tracking has access to the 3MF
  1333. try:
  1334. from backend.app.services.archive import ArchiveService
  1335. archive_service = ArchiveService(db)
  1336. archive = await archive_service.archive_print(
  1337. printer_id=item.printer_id,
  1338. source_file=file_path,
  1339. original_filename=filename,
  1340. created_by_id=item.created_by_id,
  1341. )
  1342. if archive:
  1343. item.archive_id = archive.id
  1344. await db.flush()
  1345. logger.info(
  1346. "Queue item %s: Created archive %s from library file %s",
  1347. item.id,
  1348. archive.id,
  1349. item.library_file_id,
  1350. )
  1351. except Exception as e:
  1352. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  1353. else:
  1354. # Neither archive nor library file specified
  1355. item.status = "failed"
  1356. item.error_message = "No source file specified"
  1357. item.completed_at = datetime.now(timezone.utc)
  1358. await db.commit()
  1359. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  1360. await self._power_off_if_needed(db, item)
  1361. return
  1362. # Check file exists on disk
  1363. if not file_path.exists():
  1364. item.status = "failed"
  1365. item.error_message = "Source file not found on disk"
  1366. item.completed_at = datetime.now(timezone.utc)
  1367. await db.commit()
  1368. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  1369. await self._power_off_if_needed(db, item)
  1370. return
  1371. # Upload file to printer via FTP
  1372. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1373. base_name = filename
  1374. if base_name.endswith(".gcode.3mf"):
  1375. base_name = base_name[:-10] # Remove .gcode.3mf
  1376. elif base_name.endswith(".3mf"):
  1377. base_name = base_name[:-4] # Remove .3mf
  1378. remote_filename = f"{base_name}.3mf"
  1379. # Upload to root directory (not /cache/) - the start_print command references
  1380. # files by name only (ftp://{filename}), so they must be in the root
  1381. remote_path = f"/{remote_filename}"
  1382. # Get FTP retry settings
  1383. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1384. logger.info(
  1385. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  1386. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1387. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1388. )
  1389. # Delete existing file if present (avoids 553 error on overwrite)
  1390. try:
  1391. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  1392. delete_result = await delete_file_async(
  1393. printer.ip_address,
  1394. printer.access_code,
  1395. remote_path,
  1396. socket_timeout=ftp_timeout,
  1397. printer_model=printer.model,
  1398. )
  1399. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  1400. except Exception as e:
  1401. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  1402. try:
  1403. if ftp_retry_enabled:
  1404. uploaded = await with_ftp_retry(
  1405. upload_file_async,
  1406. printer.ip_address,
  1407. printer.access_code,
  1408. file_path,
  1409. remote_path,
  1410. socket_timeout=ftp_timeout,
  1411. printer_model=printer.model,
  1412. max_retries=ftp_retry_count,
  1413. retry_delay=ftp_retry_delay,
  1414. operation_name=f"Upload print to {printer.name}",
  1415. )
  1416. else:
  1417. uploaded = await upload_file_async(
  1418. printer.ip_address,
  1419. printer.access_code,
  1420. file_path,
  1421. remote_path,
  1422. socket_timeout=ftp_timeout,
  1423. printer_model=printer.model,
  1424. )
  1425. except Exception as e:
  1426. uploaded = False
  1427. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  1428. if not uploaded:
  1429. error_msg = (
  1430. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1431. "See server logs for detailed diagnostics."
  1432. )
  1433. item.status = "failed"
  1434. item.error_message = error_msg
  1435. item.completed_at = datetime.now(timezone.utc)
  1436. await db.commit()
  1437. logger.error(
  1438. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  1439. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  1440. )
  1441. # Send failure notification
  1442. await notification_service.on_queue_job_failed(
  1443. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1444. printer_id=printer.id,
  1445. printer_name=printer.name,
  1446. reason="Failed to upload file to printer",
  1447. db=db,
  1448. )
  1449. await self._power_off_if_needed(db, item)
  1450. return
  1451. # Parse AMS mapping if stored
  1452. ams_mapping = None
  1453. if item.ams_mapping:
  1454. try:
  1455. ams_mapping = json.loads(item.ams_mapping)
  1456. except json.JSONDecodeError:
  1457. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  1458. # Register as expected print so we don't create a duplicate archive
  1459. # Only applicable for archive-based prints
  1460. if archive:
  1461. from backend.app.main import register_expected_print
  1462. register_expected_print(
  1463. item.printer_id,
  1464. remote_filename,
  1465. archive.id,
  1466. ams_mapping=ams_mapping,
  1467. created_by_id=item.created_by_id,
  1468. )
  1469. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  1470. # This prevents phantom reprints if the backend crashes/restarts after the
  1471. # print command is sent but before the status update is committed.
  1472. # If we crash after this commit but before start_print(), the item will be
  1473. # in "printing" status without actually printing - but that's safer than
  1474. # accidentally reprinting the same file hours later.
  1475. item.status = "printing"
  1476. item.started_at = datetime.now(timezone.utc)
  1477. await db.commit()
  1478. # Consume the plate-cleared flag now that we're starting a print
  1479. printer_manager.consume_plate_cleared(item.printer_id)
  1480. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  1481. # Start the print with AMS mapping, plate_id and print options
  1482. started = printer_manager.start_print(
  1483. item.printer_id,
  1484. remote_filename,
  1485. plate_id=item.plate_id or 1,
  1486. ams_mapping=ams_mapping,
  1487. bed_levelling=item.bed_levelling,
  1488. flow_cali=item.flow_cali,
  1489. vibration_cali=item.vibration_cali,
  1490. layer_inspect=item.layer_inspect,
  1491. timelapse=item.timelapse,
  1492. use_ams=item.use_ams,
  1493. )
  1494. if started:
  1495. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  1496. # Get estimated time for notification
  1497. estimated_time = None
  1498. if archive and archive.print_time_seconds:
  1499. estimated_time = archive.print_time_seconds
  1500. elif library_file and library_file.print_time_seconds:
  1501. estimated_time = library_file.print_time_seconds
  1502. # Send job started notification
  1503. await notification_service.on_queue_job_started(
  1504. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1505. printer_id=printer.id,
  1506. printer_name=printer.name,
  1507. db=db,
  1508. estimated_time=estimated_time,
  1509. )
  1510. # MQTT relay - publish queue job started
  1511. try:
  1512. from backend.app.services.mqtt_relay import mqtt_relay
  1513. await mqtt_relay.on_queue_job_started(
  1514. job_id=item.id,
  1515. filename=filename,
  1516. printer_id=printer.id,
  1517. printer_name=printer.name,
  1518. printer_serial=printer.serial_number,
  1519. )
  1520. except Exception:
  1521. pass # Don't fail if MQTT fails
  1522. else:
  1523. # Clean up uploaded file from SD card to prevent phantom prints
  1524. try:
  1525. await delete_file_async(
  1526. printer.ip_address,
  1527. printer.access_code,
  1528. remote_path,
  1529. printer_model=printer.model,
  1530. )
  1531. except Exception:
  1532. pass # Best-effort — don't fail the error handler
  1533. # Print command failed - revert status
  1534. item.status = "failed"
  1535. item.error_message = "Failed to send print command to printer"
  1536. item.completed_at = datetime.now(timezone.utc)
  1537. await db.commit()
  1538. logger.error(
  1539. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  1540. f"printer_manager.start_print() returned False. "
  1541. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  1542. f"Check printer status and backend logs for details."
  1543. )
  1544. # Send failure notification
  1545. await notification_service.on_queue_job_failed(
  1546. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1547. printer_id=printer.id,
  1548. printer_name=printer.name,
  1549. reason="Failed to send print command to printer - check printer connection and status",
  1550. db=db,
  1551. )
  1552. await self._power_off_if_needed(db, item)
  1553. # Global scheduler instance
  1554. scheduler = PrintScheduler()