print_scheduler.py 56 KB

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