print_scheduler.py 50 KB

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