print_scheduler.py 57 KB

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