print_scheduler.py 50 KB

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