print_scheduler.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import zipfile
  6. from datetime import datetime, timezone
  7. from pathlib import Path
  8. import defusedxml.ElementTree as ET
  9. from sqlalchemy import func, select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.config import settings
  12. from backend.app.core.database import async_session
  13. from backend.app.models.archive import PrintArchive
  14. from backend.app.models.library import LibraryFile
  15. from backend.app.models.print_queue import PrintQueueItem
  16. from backend.app.models.printer import Printer
  17. from backend.app.models.smart_plug import SmartPlug
  18. from backend.app.services.bambu_ftp import delete_file_async, get_ftp_retry_settings, upload_file_async, with_ftp_retry
  19. from backend.app.services.notification_service import notification_service
  20. from backend.app.services.printer_manager import printer_manager
  21. from backend.app.services.smart_plug_manager import smart_plug_manager
  22. from backend.app.utils.printer_models import normalize_printer_model
  23. from backend.app.utils.threemf_tools import extract_nozzle_mapping_from_3mf
  24. logger = logging.getLogger(__name__)
  25. class PrintScheduler:
  26. """Background scheduler that processes the print queue."""
  27. def __init__(self):
  28. self._running = False
  29. self._check_interval = 30 # seconds
  30. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  31. self._power_on_check_interval = 10 # seconds between connection checks
  32. async def run(self):
  33. """Main loop - check queue every interval."""
  34. self._running = True
  35. logger.info("Print scheduler started")
  36. while self._running:
  37. try:
  38. await self.check_queue()
  39. except Exception as e:
  40. logger.error("Scheduler error: %s", e)
  41. await asyncio.sleep(self._check_interval)
  42. def stop(self):
  43. """Stop the scheduler."""
  44. self._running = False
  45. logger.info("Print scheduler stopped")
  46. async def check_queue(self):
  47. """Check for prints ready to start."""
  48. async with async_session() as db:
  49. # Get all pending items, ordered by printer and position
  50. result = await db.execute(
  51. select(PrintQueueItem)
  52. .where(PrintQueueItem.status == "pending")
  53. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  54. )
  55. items = list(result.scalars().all())
  56. if not items:
  57. return
  58. logger.info(
  59. "Queue check: found %d pending items: %s",
  60. len(items),
  61. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  62. )
  63. # Track busy printers to avoid assigning multiple items to same printer
  64. busy_printers: set[int] = set()
  65. for item in items:
  66. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  67. if item.scheduled_time and item.scheduled_time > datetime.now(timezone.utc):
  68. continue
  69. # Skip items that require manual start
  70. if item.manual_start:
  71. continue
  72. if item.printer_id:
  73. # Specific printer assignment (existing behavior)
  74. if item.printer_id in busy_printers:
  75. continue
  76. # Check if printer is idle
  77. printer_idle = self._is_printer_idle(item.printer_id)
  78. printer_connected = printer_manager.is_connected(item.printer_id)
  79. # If printer not connected, try to power on via smart plug
  80. if not printer_connected:
  81. plug = await self._get_smart_plug(db, item.printer_id)
  82. if plug and plug.auto_on and plug.enabled:
  83. logger.info("Printer %s offline, attempting to power on via smart plug", item.printer_id)
  84. powered_on = await self._power_on_and_wait(plug, item.printer_id, db)
  85. if powered_on:
  86. printer_connected = True
  87. printer_idle = self._is_printer_idle(item.printer_id)
  88. else:
  89. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  90. busy_printers.add(item.printer_id)
  91. continue
  92. else:
  93. # No plug or auto_on disabled
  94. busy_printers.add(item.printer_id)
  95. continue
  96. # Check if printer is idle (busy with another print)
  97. if not printer_idle:
  98. busy_printers.add(item.printer_id)
  99. continue
  100. # Check condition (previous print success)
  101. if item.require_previous_success:
  102. if not await self._check_previous_success(db, item):
  103. item.status = "skipped"
  104. item.error_message = "Previous print failed or was aborted"
  105. item.completed_at = datetime.now(timezone.utc)
  106. await db.commit()
  107. logger.info("Skipped queue item %s - previous print failed", item.id)
  108. # Send notification
  109. job_name = await self._get_job_name(db, item)
  110. printer = await self._get_printer(db, item.printer_id)
  111. await notification_service.on_queue_job_skipped(
  112. job_name=job_name,
  113. printer_id=item.printer_id,
  114. printer_name=printer.name if printer else "Unknown",
  115. reason="Previous print failed or was aborted",
  116. db=db,
  117. )
  118. continue
  119. # Compute AMS mapping if not already set
  120. if not item.ams_mapping:
  121. computed_mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item)
  122. if computed_mapping:
  123. item.ams_mapping = json.dumps(computed_mapping)
  124. logger.info(
  125. f"Queue item {item.id}: Computed AMS mapping for printer {item.printer_id}: {computed_mapping}"
  126. )
  127. await db.commit()
  128. # Start the print
  129. await self._start_print(db, item)
  130. busy_printers.add(item.printer_id)
  131. elif item.target_model:
  132. # Model-based assignment - find any idle printer of matching model
  133. # Parse required filament types if present
  134. required_types = None
  135. if item.required_filament_types:
  136. try:
  137. required_types = json.loads(item.required_filament_types)
  138. except json.JSONDecodeError:
  139. pass # Ignore malformed filament types; treat as no constraint
  140. # Parse filament overrides if present
  141. filament_overrides = None
  142. if item.filament_overrides:
  143. try:
  144. filament_overrides = json.loads(item.filament_overrides)
  145. except json.JSONDecodeError:
  146. pass
  147. # If overrides exist, use override types for validation instead
  148. effective_types = required_types
  149. if filament_overrides:
  150. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  151. if override_types:
  152. # Merge: keep original types for non-overridden slots, add override types
  153. effective_types = sorted(set(required_types or []) | set(override_types))
  154. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  155. db,
  156. item.target_model,
  157. busy_printers,
  158. effective_types,
  159. item.target_location,
  160. filament_overrides=filament_overrides,
  161. )
  162. # Update waiting_reason if changed and send notification when first waiting
  163. if item.waiting_reason != waiting_reason:
  164. was_waiting = item.waiting_reason is not None
  165. item.waiting_reason = waiting_reason
  166. await db.commit()
  167. # Send waiting notification only when transitioning to waiting state
  168. if waiting_reason and not was_waiting:
  169. job_name = await self._get_job_name(db, item)
  170. await notification_service.on_queue_job_waiting(
  171. job_name=job_name,
  172. target_model=item.target_model,
  173. waiting_reason=waiting_reason,
  174. db=db,
  175. )
  176. if printer_id:
  177. # Check condition (previous print success) before assigning
  178. if item.require_previous_success:
  179. if not await self._check_previous_success(db, item):
  180. item.status = "skipped"
  181. item.error_message = "Previous print failed or was aborted"
  182. item.completed_at = datetime.now(timezone.utc)
  183. await db.commit()
  184. logger.info("Skipped queue item %s - previous print failed", item.id)
  185. # Send notification
  186. job_name = await self._get_job_name(db, item)
  187. printer = await self._get_printer(db, printer_id)
  188. await notification_service.on_queue_job_skipped(
  189. job_name=job_name,
  190. printer_id=printer_id,
  191. printer_name=printer.name if printer else "Unknown",
  192. reason="Previous print failed or was aborted",
  193. db=db,
  194. )
  195. continue
  196. # Assign printer and start - clear waiting reason
  197. item.printer_id = printer_id
  198. item.waiting_reason = None
  199. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  200. # Send assignment notification
  201. job_name = await self._get_job_name(db, item)
  202. printer = await self._get_printer(db, printer_id)
  203. await notification_service.on_queue_job_assigned(
  204. job_name=job_name,
  205. printer_id=printer_id,
  206. printer_name=printer.name if printer else "Unknown",
  207. target_model=item.target_model,
  208. db=db,
  209. )
  210. # Compute AMS mapping for the assigned printer if not already set
  211. # This is critical for model-based jobs where mapping wasn't computed upfront
  212. if not item.ams_mapping:
  213. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  214. if computed_mapping:
  215. item.ams_mapping = json.dumps(computed_mapping)
  216. logger.info(
  217. f"Queue item {item.id}: Computed AMS mapping for printer {printer_id}: {computed_mapping}"
  218. )
  219. await db.commit()
  220. await self._start_print(db, item)
  221. busy_printers.add(printer_id)
  222. async def _find_idle_printer_for_model(
  223. self,
  224. db: AsyncSession,
  225. model: str,
  226. exclude_ids: set[int],
  227. required_filament_types: list[str] | None = None,
  228. target_location: str | None = None,
  229. filament_overrides: list[dict] | None = None,
  230. ) -> tuple[int | None, str | None]:
  231. """Find an idle, connected printer matching the model with compatible filaments.
  232. Args:
  233. db: Database session
  234. model: Printer model to match (e.g., "X1C", "P1S")
  235. exclude_ids: Printer IDs to exclude (already busy)
  236. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  237. If provided, only printers with all required types loaded will match.
  238. target_location: Optional location filter. If provided, only printers in this location are considered.
  239. Returns:
  240. Tuple of (printer_id, waiting_reason):
  241. - (printer_id, None) if a matching printer was found
  242. - (None, reason) if no printer is available, with explanation
  243. """
  244. # Normalize model name and use case-insensitive matching
  245. normalized_model = normalize_printer_model(model) or model
  246. query = (
  247. select(Printer)
  248. .where(func.lower(Printer.model) == normalized_model.lower())
  249. .where(Printer.is_active == True) # noqa: E712
  250. )
  251. # Add location filter if specified
  252. if target_location:
  253. query = query.where(Printer.location == target_location)
  254. result = await db.execute(query)
  255. printers = list(result.scalars().all())
  256. location_suffix = f" in {target_location}" if target_location else ""
  257. if not printers:
  258. return None, f"No active {normalized_model} printers{location_suffix} configured"
  259. # Track reasons for skipping printers
  260. printers_busy = []
  261. printers_offline = []
  262. printers_missing_filament = []
  263. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  264. for printer in printers:
  265. if printer.id in exclude_ids:
  266. printers_busy.append(printer.name)
  267. continue
  268. is_connected = printer_manager.is_connected(printer.id)
  269. is_idle = self._is_printer_idle(printer.id) if is_connected else False
  270. if not is_connected:
  271. printers_offline.append(printer.name)
  272. continue
  273. if not is_idle:
  274. printers_busy.append(printer.name)
  275. continue
  276. # Validate filament compatibility if required types are specified
  277. if required_filament_types:
  278. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  279. if missing:
  280. printers_missing_filament.append((printer.name, missing))
  281. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  282. continue
  283. # If filament overrides with colors, only consider printers that have at least one color match
  284. if filament_overrides:
  285. color_matches = self._count_override_color_matches(printer.id, filament_overrides)
  286. if color_matches > 0:
  287. candidates.append((printer.id, color_matches))
  288. else:
  289. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in filament_overrides]
  290. printers_missing_filament.append((printer.name, override_colors))
  291. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  292. continue
  293. else:
  294. # No overrides - take first available (existing behavior)
  295. return printer.id, None
  296. # If we have candidates from override matching, pick the one with most color matches
  297. if candidates:
  298. candidates.sort(key=lambda c: c[1], reverse=True)
  299. return candidates[0][0], None
  300. # Build waiting reason from what we found
  301. reasons = []
  302. if printers_missing_filament:
  303. # Filament mismatch is most actionable - show first
  304. names_and_missing = [f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament]
  305. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  306. if printers_busy:
  307. reasons.append(f"Busy: {', '.join(printers_busy)}")
  308. if printers_offline:
  309. reasons.append(f"Offline: {', '.join(printers_offline)}")
  310. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  311. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  312. """Get the list of required filament types that are not loaded on the printer.
  313. Args:
  314. printer_id: The printer ID
  315. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  316. Returns:
  317. List of missing filament types (empty if all are loaded)
  318. """
  319. status = printer_manager.get_status(printer_id)
  320. if not status:
  321. return required_types # Can't determine, assume all missing
  322. # Collect all filament types loaded on this printer (AMS units + external spool)
  323. loaded_types: set[str] = set()
  324. # Check AMS units (stored in raw_data["ams"])
  325. ams_data = status.raw_data.get("ams", [])
  326. if ams_data:
  327. for ams_unit in ams_data:
  328. for tray in ams_unit.get("tray", []):
  329. tray_type = tray.get("tray_type")
  330. if tray_type:
  331. loaded_types.add(tray_type.upper())
  332. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  333. for vt in status.raw_data.get("vt_tray") or []:
  334. vt_type = vt.get("tray_type")
  335. if vt_type:
  336. loaded_types.add(vt_type.upper())
  337. # Find which required types are missing (case-insensitive comparison)
  338. missing = []
  339. for req_type in required_types:
  340. if req_type.upper() not in loaded_types:
  341. missing.append(req_type)
  342. return missing
  343. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  344. """Count how many filament overrides have an exact color match on the printer.
  345. Used to prefer printers that already have the desired override colors loaded.
  346. """
  347. status = printer_manager.get_status(printer_id)
  348. if not status:
  349. return 0
  350. # Collect loaded filaments' type+color pairs
  351. loaded: set[tuple[str, str]] = set()
  352. for ams_unit in status.raw_data.get("ams", []):
  353. for tray in ams_unit.get("tray", []):
  354. tray_type = tray.get("tray_type")
  355. tray_color = tray.get("tray_color", "")
  356. if tray_type:
  357. color_norm = tray_color.replace("#", "").lower()[:6]
  358. loaded.add((tray_type.upper(), color_norm))
  359. for vt in status.raw_data.get("vt_tray") or []:
  360. vt_type = vt.get("tray_type")
  361. if vt_type:
  362. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  363. loaded.add((vt_type.upper(), color_norm))
  364. matches = 0
  365. for o in overrides:
  366. o_type = (o.get("type") or "").upper()
  367. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  368. if (o_type, o_color) in loaded:
  369. matches += 1
  370. return matches
  371. async def _compute_ams_mapping_for_printer(
  372. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  373. ) -> list[int] | None:
  374. """Compute AMS mapping for a printer based on filament requirements.
  375. Called when a queue item has no ams_mapping set — either for model-based
  376. items after printer assignment, or printer-specific items (e.g. from VP).
  377. Args:
  378. db: Database session
  379. printer_id: The assigned printer ID
  380. item: The queue item (contains archive_id or library_file_id)
  381. Returns:
  382. AMS mapping array or None if no mapping needed/possible
  383. """
  384. # Get printer status
  385. status = printer_manager.get_status(printer_id)
  386. if not status:
  387. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  388. return None
  389. # Get filament requirements from source file
  390. filament_reqs = await self._get_filament_requirements(db, item)
  391. if not filament_reqs:
  392. logger.debug("No filament requirements found for queue item %s", item.id)
  393. return None
  394. # Apply filament overrides if present
  395. if item.filament_overrides:
  396. try:
  397. overrides = json.loads(item.filament_overrides)
  398. override_map = {o["slot_id"]: o for o in overrides}
  399. for req in filament_reqs:
  400. if req["slot_id"] in override_map:
  401. override = override_map[req["slot_id"]]
  402. req["type"] = override["type"]
  403. req["color"] = override["color"]
  404. # Clear tray_info_idx so matching uses type+color instead of
  405. # the original 3MF's tray_info_idx (which would match the old filament)
  406. req["tray_info_idx"] = ""
  407. logger.debug(
  408. "Queue item %s: Override slot %d -> %s %s",
  409. item.id,
  410. req["slot_id"],
  411. override["type"],
  412. override["color"],
  413. )
  414. except (json.JSONDecodeError, KeyError, TypeError) as e:
  415. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  416. # Build loaded filaments from printer status
  417. loaded_filaments = self._build_loaded_filaments(status)
  418. if not loaded_filaments:
  419. logger.debug("No filaments loaded on printer %s", printer_id)
  420. return None
  421. # Compute mapping: match required filaments to available slots
  422. return self._match_filaments_to_slots(filament_reqs, loaded_filaments)
  423. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  424. """Extract filament requirements from the source 3MF file.
  425. Args:
  426. db: Database session
  427. item: Queue item with archive_id or library_file_id
  428. Returns:
  429. List of filament requirement dicts with slot_id, type, color, used_grams
  430. """
  431. file_path: Path | None = None
  432. if item.archive_id:
  433. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  434. archive = result.scalar_one_or_none()
  435. if archive:
  436. file_path = settings.base_dir / archive.file_path
  437. elif item.library_file_id:
  438. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  439. library_file = result.scalar_one_or_none()
  440. if library_file:
  441. lib_path = Path(library_file.file_path)
  442. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  443. if not file_path or not file_path.exists():
  444. return None
  445. filaments = []
  446. try:
  447. with zipfile.ZipFile(file_path, "r") as zf:
  448. if "Metadata/slice_info.config" not in zf.namelist():
  449. return None
  450. content = zf.read("Metadata/slice_info.config").decode()
  451. root = ET.fromstring(content)
  452. # Check if plate_id is specified - use that plate's filaments
  453. plate_id = item.plate_id
  454. if plate_id:
  455. for plate_elem in root.findall("./plate"):
  456. plate_index = None
  457. for meta in plate_elem.findall("metadata"):
  458. if meta.get("key") == "index":
  459. plate_index = int(meta.get("value", "0"))
  460. break
  461. if plate_index == plate_id:
  462. for filament_elem in plate_elem.findall("./filament"):
  463. filament_id = filament_elem.get("id")
  464. filament_type = filament_elem.get("type", "")
  465. filament_color = filament_elem.get("color", "")
  466. # tray_info_idx identifies the specific spool selected when slicing
  467. tray_info_idx = filament_elem.get("tray_info_idx", "")
  468. used_g = filament_elem.get("used_g", "0")
  469. try:
  470. used_grams = float(used_g)
  471. if used_grams > 0 and filament_id:
  472. filaments.append(
  473. {
  474. "slot_id": int(filament_id),
  475. "type": filament_type,
  476. "color": filament_color,
  477. "tray_info_idx": tray_info_idx,
  478. "used_grams": round(used_grams, 1),
  479. }
  480. )
  481. except (ValueError, TypeError):
  482. pass # Skip filament entry with unparseable usage data
  483. break
  484. else:
  485. # No plate_id - extract all filaments with used_g > 0
  486. for filament_elem in root.findall("./filament"):
  487. filament_id = filament_elem.get("id")
  488. filament_type = filament_elem.get("type", "")
  489. filament_color = filament_elem.get("color", "")
  490. # tray_info_idx identifies the specific spool selected when slicing
  491. tray_info_idx = filament_elem.get("tray_info_idx", "")
  492. used_g = filament_elem.get("used_g", "0")
  493. try:
  494. used_grams = float(used_g)
  495. if used_grams > 0 and filament_id:
  496. filaments.append(
  497. {
  498. "slot_id": int(filament_id),
  499. "type": filament_type,
  500. "color": filament_color,
  501. "tray_info_idx": tray_info_idx,
  502. "used_grams": round(used_grams, 1),
  503. }
  504. )
  505. except (ValueError, TypeError):
  506. pass # Skip filament entry with unparseable usage data
  507. filaments.sort(key=lambda x: x["slot_id"])
  508. # Enrich with nozzle mapping for dual-nozzle printers
  509. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  510. if nozzle_mapping:
  511. for filament in filaments:
  512. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  513. except Exception as e:
  514. logger.warning("Failed to parse filament requirements: %s", e)
  515. return None
  516. return filaments if filaments else None
  517. def _build_loaded_filaments(self, status) -> list[dict]:
  518. """Build list of loaded filaments from printer status.
  519. Args:
  520. status: PrinterState from printer_manager
  521. Returns:
  522. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  523. """
  524. filaments = []
  525. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  526. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  527. # Parse AMS units from raw_data
  528. ams_data = status.raw_data.get("ams", [])
  529. for ams_unit in ams_data:
  530. ams_id = int(ams_unit.get("id", 0))
  531. trays = ams_unit.get("tray", [])
  532. is_ht = len(trays) == 1 # AMS-HT has single tray
  533. for tray in trays:
  534. tray_type = tray.get("tray_type")
  535. if tray_type:
  536. tray_id = int(tray.get("id", 0))
  537. tray_color = tray.get("tray_color", "")
  538. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  539. tray_info_idx = tray.get("tray_info_idx", "")
  540. # Normalize color: remove alpha, add hash
  541. color = self._normalize_color(tray_color)
  542. # Calculate global tray ID
  543. # AMS-HT units have IDs starting at 128 with a single tray
  544. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  545. filaments.append(
  546. {
  547. "type": tray_type,
  548. "color": color,
  549. "tray_info_idx": tray_info_idx,
  550. "ams_id": ams_id,
  551. "tray_id": tray_id,
  552. "is_ht": is_ht,
  553. "is_external": False,
  554. "global_tray_id": global_tray_id,
  555. "extruder_id": ams_extruder_map.get(str(ams_id)),
  556. }
  557. )
  558. # Check external spool(s) (vt_tray is a list)
  559. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  560. if vt.get("tray_type"):
  561. color = self._normalize_color(vt.get("tray_color", ""))
  562. tray_id = int(vt.get("id", 254))
  563. filaments.append(
  564. {
  565. "type": vt["tray_type"],
  566. "color": color,
  567. "tray_info_idx": vt.get("tray_info_idx", ""),
  568. "ams_id": -1,
  569. "tray_id": idx,
  570. "is_ht": False,
  571. "is_external": True,
  572. "global_tray_id": tray_id,
  573. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  574. }
  575. )
  576. return filaments
  577. def _normalize_color(self, color: str | None) -> str:
  578. """Normalize color to #RRGGBB format."""
  579. if not color:
  580. return "#808080"
  581. hex_color = color.replace("#", "")[:6]
  582. return f"#{hex_color}"
  583. def _normalize_color_for_compare(self, color: str | None) -> str:
  584. """Normalize color for comparison (lowercase, no hash)."""
  585. if not color:
  586. return ""
  587. return color.replace("#", "").lower()[:6]
  588. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  589. """Check if two colors are visually similar within a threshold."""
  590. hex1 = self._normalize_color_for_compare(color1)
  591. hex2 = self._normalize_color_for_compare(color2)
  592. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  593. return False
  594. try:
  595. r1 = int(hex1[0:2], 16)
  596. g1 = int(hex1[2:4], 16)
  597. b1 = int(hex1[4:6], 16)
  598. r2 = int(hex2[0:2], 16)
  599. g2 = int(hex2[2:4], 16)
  600. b2 = int(hex2[4:6], 16)
  601. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  602. except ValueError:
  603. return False
  604. def _match_filaments_to_slots(self, required: list[dict], loaded: list[dict]) -> list[int] | None:
  605. """Match required filaments to loaded filaments and build AMS mapping.
  606. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  607. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  608. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  609. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  610. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  611. matching among those trays.
  612. Args:
  613. required: List of required filaments with slot_id, type, color, tray_info_idx
  614. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  615. Returns:
  616. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  617. """
  618. if not required:
  619. return None
  620. # Track used trays to avoid duplicate assignment
  621. used_tray_ids: set[int] = set()
  622. comparisons = []
  623. for req in required:
  624. req_type = (req.get("type") or "").upper()
  625. req_color = req.get("color", "")
  626. req_tray_info_idx = req.get("tray_info_idx", "")
  627. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  628. idx_match = None
  629. exact_match = None
  630. similar_match = None
  631. type_only_match = None
  632. # Get available trays (not already used)
  633. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  634. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  635. # Hard filter — cross-nozzle assignment causes print failures
  636. # ("position of left hotend is abnormal"), so never fall back.
  637. req_nozzle_id = req.get("nozzle_id")
  638. if req_nozzle_id is not None:
  639. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  640. # Check if tray_info_idx is unique among available trays
  641. if req_tray_info_idx:
  642. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  643. if len(idx_matches) == 1:
  644. # Unique tray_info_idx - use it as definitive match
  645. idx_match = idx_matches[0]
  646. logger.debug(
  647. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  648. f"-> tray {idx_match['global_tray_id']}"
  649. )
  650. elif len(idx_matches) > 1:
  651. # Multiple trays with same tray_info_idx - use color matching among them
  652. logger.debug(
  653. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  654. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  655. )
  656. # Use color matching within this subset
  657. for f in idx_matches:
  658. f_color = f.get("color", "")
  659. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  660. if not exact_match:
  661. exact_match = f
  662. elif self._colors_are_similar(f_color, req_color):
  663. if not similar_match:
  664. similar_match = f
  665. elif not type_only_match:
  666. type_only_match = f
  667. # If no idx_match yet, do standard type/color matching on all available trays
  668. if not idx_match and not exact_match and not similar_match and not type_only_match:
  669. for f in available:
  670. f_type = (f.get("type") or "").upper()
  671. if f_type != req_type:
  672. continue
  673. # Type matches - check color
  674. f_color = f.get("color", "")
  675. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  676. if not exact_match:
  677. exact_match = f
  678. elif self._colors_are_similar(f_color, req_color):
  679. if not similar_match:
  680. similar_match = f
  681. elif not type_only_match:
  682. type_only_match = f
  683. match = idx_match or exact_match or similar_match or type_only_match
  684. if match:
  685. used_tray_ids.add(match["global_tray_id"])
  686. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  687. else:
  688. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  689. # Build mapping array
  690. if not comparisons:
  691. return None
  692. max_slot_id = max(c["slot_id"] for c in comparisons)
  693. if max_slot_id <= 0:
  694. return None
  695. mapping = [-1] * max_slot_id
  696. for c in comparisons:
  697. slot_id = c["slot_id"]
  698. if slot_id and slot_id > 0:
  699. mapping[slot_id - 1] = c["global_tray_id"]
  700. return mapping
  701. def _is_printer_idle(self, printer_id: int) -> bool:
  702. """Check if a printer is connected and idle."""
  703. if not printer_manager.is_connected(printer_id):
  704. return False
  705. state = printer_manager.get_status(printer_id)
  706. if not state:
  707. return False
  708. # IDLE = ready for next print
  709. # FINISH/FAILED = ready only if user confirmed plate is cleared
  710. return state.state == "IDLE" or (
  711. state.state in ("FINISH", "FAILED") and printer_manager.is_plate_cleared(printer_id)
  712. )
  713. async def _get_smart_plug(self, db: AsyncSession, printer_id: int) -> SmartPlug | None:
  714. """Get the smart plug associated with a printer."""
  715. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  716. return result.scalar_one_or_none()
  717. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  718. """Turn on smart plug and wait for printer to connect.
  719. Returns True if printer connected successfully within timeout.
  720. """
  721. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  722. service = await smart_plug_manager.get_service_for_plug(plug, db)
  723. # Check current plug state
  724. status = await service.get_status(plug)
  725. if not status.get("reachable"):
  726. logger.warning("Smart plug '%s' is not reachable", plug.name)
  727. return False
  728. # Turn on if not already on
  729. if status.get("state") != "ON":
  730. success = await service.turn_on(plug)
  731. if not success:
  732. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  733. return False
  734. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  735. # Get printer from database for connection
  736. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  737. printer = result.scalar_one_or_none()
  738. if not printer:
  739. logger.error("Printer %s not found in database", printer_id)
  740. return False
  741. # Wait for printer to boot (give it some time before trying to connect)
  742. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  743. await asyncio.sleep(30)
  744. # Try to connect to the printer periodically
  745. elapsed = 30 # Already waited 30s
  746. while elapsed < self._power_on_wait_time:
  747. # Try to connect
  748. logger.info("Attempting to connect to printer %s...", printer_id)
  749. try:
  750. connected = await printer_manager.connect_printer(printer)
  751. if connected:
  752. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  753. # Give it a moment to stabilize and get status
  754. await asyncio.sleep(5)
  755. return True
  756. except Exception as e:
  757. logger.debug("Connection attempt failed: %s", e)
  758. await asyncio.sleep(self._power_on_check_interval)
  759. elapsed += self._power_on_check_interval
  760. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  761. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  762. return False
  763. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  764. """Check if the previous print on this printer succeeded."""
  765. # Find the most recent completed queue item for this printer
  766. result = await db.execute(
  767. select(PrintQueueItem)
  768. .where(PrintQueueItem.printer_id == item.printer_id)
  769. .where(PrintQueueItem.id != item.id)
  770. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  771. .order_by(PrintQueueItem.completed_at.desc())
  772. .limit(1)
  773. )
  774. prev_item = result.scalar_one_or_none()
  775. # If no previous item, assume success (first in queue)
  776. if not prev_item:
  777. return True
  778. return prev_item.status == "completed"
  779. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  780. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  781. if not item.auto_off_after:
  782. return
  783. plug = await self._get_smart_plug(db, item.printer_id)
  784. if plug and plug.enabled:
  785. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  786. # Wait for cooldown (up to 10 minutes)
  787. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  788. logger.info("Auto-off: Powering off printer %s", item.printer_id)
  789. service = await smart_plug_manager.get_service_for_plug(plug, db)
  790. await service.turn_off(plug)
  791. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  792. """Get a human-readable name for a queue item."""
  793. if item.archive_id:
  794. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  795. archive = result.scalar_one_or_none()
  796. if archive:
  797. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  798. if item.library_file_id:
  799. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  800. library_file = result.scalar_one_or_none()
  801. if library_file:
  802. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  803. return f"Job #{item.id}"
  804. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  805. """Get printer by ID."""
  806. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  807. return result.scalar_one_or_none()
  808. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  809. """Upload file and start print for a queue item.
  810. Supports two sources:
  811. - archive_id: Print from an existing archive
  812. - library_file_id: Print from a library file (file manager)
  813. """
  814. logger.info("Starting queue item %s", item.id)
  815. # Get printer first (needed for both paths)
  816. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  817. printer = result.scalar_one_or_none()
  818. if not printer:
  819. item.status = "failed"
  820. item.error_message = "Printer not found"
  821. item.completed_at = datetime.now(timezone.utc)
  822. await db.commit()
  823. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  824. await self._power_off_if_needed(db, item)
  825. return
  826. # Check printer is connected
  827. if not printer_manager.is_connected(item.printer_id):
  828. item.status = "failed"
  829. item.error_message = "Printer not connected"
  830. item.completed_at = datetime.now(timezone.utc)
  831. await db.commit()
  832. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  833. await self._power_off_if_needed(db, item)
  834. return
  835. # Determine source: archive or library file
  836. archive = None
  837. library_file = None
  838. file_path = None
  839. filename = None
  840. if item.archive_id:
  841. # Print from archive
  842. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  843. archive = result.scalar_one_or_none()
  844. if not archive:
  845. item.status = "failed"
  846. item.error_message = "Archive not found"
  847. item.completed_at = datetime.now(timezone.utc)
  848. await db.commit()
  849. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  850. await self._power_off_if_needed(db, item)
  851. return
  852. file_path = settings.base_dir / archive.file_path
  853. filename = archive.filename
  854. elif item.library_file_id:
  855. # Print from library file (file manager)
  856. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  857. library_file = result.scalar_one_or_none()
  858. if not library_file:
  859. item.status = "failed"
  860. item.error_message = "Library file not found"
  861. item.completed_at = datetime.now(timezone.utc)
  862. await db.commit()
  863. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  864. await self._power_off_if_needed(db, item)
  865. return
  866. # Library files store absolute paths
  867. lib_path = Path(library_file.file_path)
  868. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  869. filename = library_file.filename
  870. # Create archive from library file so usage tracking has access to the 3MF
  871. try:
  872. from backend.app.services.archive import ArchiveService
  873. archive_service = ArchiveService(db)
  874. archive = await archive_service.archive_print(
  875. printer_id=item.printer_id,
  876. source_file=file_path,
  877. original_filename=filename,
  878. )
  879. if archive:
  880. item.archive_id = archive.id
  881. await db.flush()
  882. logger.info(
  883. "Queue item %s: Created archive %s from library file %s",
  884. item.id,
  885. archive.id,
  886. item.library_file_id,
  887. )
  888. except Exception as e:
  889. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  890. else:
  891. # Neither archive nor library file specified
  892. item.status = "failed"
  893. item.error_message = "No source file specified"
  894. item.completed_at = datetime.now(timezone.utc)
  895. await db.commit()
  896. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  897. await self._power_off_if_needed(db, item)
  898. return
  899. # Check file exists on disk
  900. if not file_path.exists():
  901. item.status = "failed"
  902. item.error_message = "Source file not found on disk"
  903. item.completed_at = datetime.now(timezone.utc)
  904. await db.commit()
  905. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  906. await self._power_off_if_needed(db, item)
  907. return
  908. # Upload file to printer via FTP
  909. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  910. base_name = filename
  911. if base_name.endswith(".gcode.3mf"):
  912. base_name = base_name[:-10] # Remove .gcode.3mf
  913. elif base_name.endswith(".3mf"):
  914. base_name = base_name[:-4] # Remove .3mf
  915. remote_filename = f"{base_name}.3mf"
  916. # Upload to root directory (not /cache/) - the start_print command references
  917. # files by name only (ftp://{filename}), so they must be in the root
  918. remote_path = f"/{remote_filename}"
  919. # Get FTP retry settings
  920. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  921. logger.info(
  922. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  923. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  924. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  925. )
  926. # Delete existing file if present (avoids 553 error on overwrite)
  927. try:
  928. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  929. delete_result = await delete_file_async(
  930. printer.ip_address,
  931. printer.access_code,
  932. remote_path,
  933. socket_timeout=ftp_timeout,
  934. printer_model=printer.model,
  935. )
  936. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  937. except Exception as e:
  938. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  939. try:
  940. if ftp_retry_enabled:
  941. uploaded = await with_ftp_retry(
  942. upload_file_async,
  943. printer.ip_address,
  944. printer.access_code,
  945. file_path,
  946. remote_path,
  947. socket_timeout=ftp_timeout,
  948. printer_model=printer.model,
  949. max_retries=ftp_retry_count,
  950. retry_delay=ftp_retry_delay,
  951. operation_name=f"Upload print to {printer.name}",
  952. )
  953. else:
  954. uploaded = await upload_file_async(
  955. printer.ip_address,
  956. printer.access_code,
  957. file_path,
  958. remote_path,
  959. socket_timeout=ftp_timeout,
  960. printer_model=printer.model,
  961. )
  962. except Exception as e:
  963. uploaded = False
  964. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  965. if not uploaded:
  966. error_msg = (
  967. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  968. "See server logs for detailed diagnostics."
  969. )
  970. item.status = "failed"
  971. item.error_message = error_msg
  972. item.completed_at = datetime.now(timezone.utc)
  973. await db.commit()
  974. logger.error(
  975. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  976. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  977. )
  978. # Send failure notification
  979. await notification_service.on_queue_job_failed(
  980. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  981. printer_id=printer.id,
  982. printer_name=printer.name,
  983. reason="Failed to upload file to printer",
  984. db=db,
  985. )
  986. await self._power_off_if_needed(db, item)
  987. return
  988. # Parse AMS mapping if stored
  989. ams_mapping = None
  990. if item.ams_mapping:
  991. try:
  992. ams_mapping = json.loads(item.ams_mapping)
  993. except json.JSONDecodeError:
  994. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  995. # Register as expected print so we don't create a duplicate archive
  996. # Only applicable for archive-based prints
  997. if archive:
  998. from backend.app.main import register_expected_print
  999. register_expected_print(item.printer_id, remote_filename, archive.id, ams_mapping=ams_mapping)
  1000. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  1001. # This prevents phantom reprints if the backend crashes/restarts after the
  1002. # print command is sent but before the status update is committed.
  1003. # If we crash after this commit but before start_print(), the item will be
  1004. # in "printing" status without actually printing - but that's safer than
  1005. # accidentally reprinting the same file hours later.
  1006. item.status = "printing"
  1007. item.started_at = datetime.now(timezone.utc)
  1008. await db.commit()
  1009. # Consume the plate-cleared flag now that we're starting a print
  1010. printer_manager.consume_plate_cleared(item.printer_id)
  1011. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  1012. # Start the print with AMS mapping, plate_id and print options
  1013. started = printer_manager.start_print(
  1014. item.printer_id,
  1015. remote_filename,
  1016. plate_id=item.plate_id or 1,
  1017. ams_mapping=ams_mapping,
  1018. bed_levelling=item.bed_levelling,
  1019. flow_cali=item.flow_cali,
  1020. vibration_cali=item.vibration_cali,
  1021. layer_inspect=item.layer_inspect,
  1022. timelapse=item.timelapse,
  1023. use_ams=item.use_ams,
  1024. )
  1025. if started:
  1026. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  1027. # Get estimated time for notification
  1028. estimated_time = None
  1029. if archive and archive.print_time_seconds:
  1030. estimated_time = archive.print_time_seconds
  1031. elif library_file and library_file.print_time_seconds:
  1032. estimated_time = library_file.print_time_seconds
  1033. # Send job started notification
  1034. await notification_service.on_queue_job_started(
  1035. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1036. printer_id=printer.id,
  1037. printer_name=printer.name,
  1038. db=db,
  1039. estimated_time=estimated_time,
  1040. )
  1041. # MQTT relay - publish queue job started
  1042. try:
  1043. from backend.app.services.mqtt_relay import mqtt_relay
  1044. await mqtt_relay.on_queue_job_started(
  1045. job_id=item.id,
  1046. filename=filename,
  1047. printer_id=printer.id,
  1048. printer_name=printer.name,
  1049. printer_serial=printer.serial_number,
  1050. )
  1051. except Exception:
  1052. pass # Don't fail if MQTT fails
  1053. else:
  1054. # Clean up uploaded file from SD card to prevent phantom prints
  1055. try:
  1056. await delete_file_async(
  1057. printer.ip_address,
  1058. printer.access_code,
  1059. remote_path,
  1060. printer_model=printer.model,
  1061. )
  1062. except Exception:
  1063. pass # Best-effort — don't fail the error handler
  1064. # Print command failed - revert status
  1065. item.status = "failed"
  1066. item.error_message = "Failed to send print command to printer"
  1067. item.completed_at = datetime.now(timezone.utc)
  1068. await db.commit()
  1069. logger.error(
  1070. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  1071. f"printer_manager.start_print() returned False. "
  1072. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  1073. f"Check printer status and backend logs for details."
  1074. )
  1075. # Send failure notification
  1076. await notification_service.on_queue_job_failed(
  1077. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1078. printer_id=printer.id,
  1079. printer_name=printer.name,
  1080. reason="Failed to send print command to printer - check printer connection and status",
  1081. db=db,
  1082. )
  1083. await self._power_off_if_needed(db, item)
  1084. # Global scheduler instance
  1085. scheduler = PrintScheduler()