print_scheduler.py 50 KB

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