print_scheduler.py 82 KB

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