print_scheduler.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import logging
  4. from datetime import datetime
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.config import settings
  8. from backend.app.core.database import async_session
  9. from backend.app.models.archive import PrintArchive
  10. from backend.app.models.library import LibraryFile
  11. from backend.app.models.print_queue import PrintQueueItem
  12. from backend.app.models.printer import Printer
  13. from backend.app.models.smart_plug import SmartPlug
  14. from backend.app.services.bambu_ftp import delete_file_async, get_ftp_retry_settings, upload_file_async, with_ftp_retry
  15. from backend.app.services.notification_service import notification_service
  16. from backend.app.services.printer_manager import printer_manager
  17. from backend.app.services.tasmota import tasmota_service
  18. logger = logging.getLogger(__name__)
  19. class PrintScheduler:
  20. """Background scheduler that processes the print queue."""
  21. def __init__(self):
  22. self._running = False
  23. self._check_interval = 30 # seconds
  24. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  25. self._power_on_check_interval = 10 # seconds between connection checks
  26. async def run(self):
  27. """Main loop - check queue every interval."""
  28. self._running = True
  29. logger.info("Print scheduler started")
  30. while self._running:
  31. try:
  32. await self.check_queue()
  33. except Exception as e:
  34. logger.error(f"Scheduler error: {e}")
  35. await asyncio.sleep(self._check_interval)
  36. def stop(self):
  37. """Stop the scheduler."""
  38. self._running = False
  39. logger.info("Print scheduler stopped")
  40. async def check_queue(self):
  41. """Check for prints ready to start."""
  42. async with async_session() as db:
  43. # Get all pending items, ordered by printer and position
  44. result = await db.execute(
  45. select(PrintQueueItem)
  46. .where(PrintQueueItem.status == "pending")
  47. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  48. )
  49. items = list(result.scalars().all())
  50. if not items:
  51. return
  52. # Track busy printers to avoid assigning multiple items to same printer
  53. busy_printers: set[int] = set()
  54. for item in items:
  55. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  56. if item.scheduled_time and item.scheduled_time > datetime.utcnow():
  57. continue
  58. # Skip items that require manual start
  59. if item.manual_start:
  60. continue
  61. if item.printer_id:
  62. # Specific printer assignment (existing behavior)
  63. if item.printer_id in busy_printers:
  64. continue
  65. # Check if printer is idle
  66. printer_idle = self._is_printer_idle(item.printer_id)
  67. printer_connected = printer_manager.is_connected(item.printer_id)
  68. # If printer not connected, try to power on via smart plug
  69. if not printer_connected:
  70. plug = await self._get_smart_plug(db, item.printer_id)
  71. if plug and plug.auto_on and plug.enabled:
  72. logger.info(f"Printer {item.printer_id} offline, attempting to power on via smart plug")
  73. powered_on = await self._power_on_and_wait(plug, item.printer_id, db)
  74. if powered_on:
  75. printer_connected = True
  76. printer_idle = self._is_printer_idle(item.printer_id)
  77. else:
  78. logger.warning(f"Could not power on printer {item.printer_id} via smart plug")
  79. busy_printers.add(item.printer_id)
  80. continue
  81. else:
  82. # No plug or auto_on disabled
  83. busy_printers.add(item.printer_id)
  84. continue
  85. # Check if printer is idle (busy with another print)
  86. if not printer_idle:
  87. busy_printers.add(item.printer_id)
  88. continue
  89. # Check condition (previous print success)
  90. if item.require_previous_success:
  91. if not await self._check_previous_success(db, item):
  92. item.status = "skipped"
  93. item.error_message = "Previous print failed or was aborted"
  94. item.completed_at = datetime.now()
  95. await db.commit()
  96. logger.info(f"Skipped queue item {item.id} - previous print failed")
  97. # Send notification
  98. job_name = await self._get_job_name(db, item)
  99. printer = await self._get_printer(db, item.printer_id)
  100. await notification_service.on_queue_job_skipped(
  101. job_name=job_name,
  102. printer_id=item.printer_id,
  103. printer_name=printer.name if printer else "Unknown",
  104. reason="Previous print failed or was aborted",
  105. db=db,
  106. )
  107. continue
  108. # Start the print
  109. await self._start_print(db, item)
  110. busy_printers.add(item.printer_id)
  111. elif item.target_model:
  112. # Model-based assignment - find any idle printer of matching model
  113. # Parse required filament types if present
  114. required_types = None
  115. if item.required_filament_types:
  116. try:
  117. import json
  118. required_types = json.loads(item.required_filament_types)
  119. except json.JSONDecodeError:
  120. pass
  121. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  122. db, item.target_model, busy_printers, required_types
  123. )
  124. # Update waiting_reason if changed and send notification when first waiting
  125. if item.waiting_reason != waiting_reason:
  126. was_waiting = item.waiting_reason is not None
  127. item.waiting_reason = waiting_reason
  128. await db.commit()
  129. # Send waiting notification only when transitioning to waiting state
  130. if waiting_reason and not was_waiting:
  131. job_name = await self._get_job_name(db, item)
  132. await notification_service.on_queue_job_waiting(
  133. job_name=job_name,
  134. target_model=item.target_model,
  135. waiting_reason=waiting_reason,
  136. db=db,
  137. )
  138. if printer_id:
  139. # Check condition (previous print success) before assigning
  140. if item.require_previous_success:
  141. if not await self._check_previous_success(db, item):
  142. item.status = "skipped"
  143. item.error_message = "Previous print failed or was aborted"
  144. item.completed_at = datetime.now()
  145. await db.commit()
  146. logger.info(f"Skipped queue item {item.id} - previous print failed")
  147. # Send notification
  148. job_name = await self._get_job_name(db, item)
  149. printer = await self._get_printer(db, printer_id)
  150. await notification_service.on_queue_job_skipped(
  151. job_name=job_name,
  152. printer_id=printer_id,
  153. printer_name=printer.name if printer else "Unknown",
  154. reason="Previous print failed or was aborted",
  155. db=db,
  156. )
  157. continue
  158. # Assign printer and start - clear waiting reason
  159. item.printer_id = printer_id
  160. item.waiting_reason = None
  161. logger.info(f"Model-based assignment: queue item {item.id} assigned to printer {printer_id}")
  162. # Send assignment 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_assigned(
  166. job_name=job_name,
  167. printer_id=printer_id,
  168. printer_name=printer.name if printer else "Unknown",
  169. target_model=item.target_model,
  170. db=db,
  171. )
  172. await self._start_print(db, item)
  173. busy_printers.add(printer_id)
  174. async def _find_idle_printer_for_model(
  175. self,
  176. db: AsyncSession,
  177. model: str,
  178. exclude_ids: set[int],
  179. required_filament_types: list[str] | None = None,
  180. ) -> tuple[int | None, str | None]:
  181. """Find an idle, connected printer matching the model with compatible filaments.
  182. Args:
  183. db: Database session
  184. model: Printer model to match (e.g., "X1C", "P1S")
  185. exclude_ids: Printer IDs to exclude (already busy)
  186. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  187. If provided, only printers with all required types loaded will match.
  188. Returns:
  189. Tuple of (printer_id, waiting_reason):
  190. - (printer_id, None) if a matching printer was found
  191. - (None, reason) if no printer is available, with explanation
  192. """
  193. result = await db.execute(
  194. select(Printer).where(Printer.model == model).where(Printer.is_active == True) # noqa: E712
  195. )
  196. printers = list(result.scalars().all())
  197. if not printers:
  198. return None, f"No active {model} printers configured"
  199. # Track reasons for skipping printers
  200. printers_busy = []
  201. printers_offline = []
  202. printers_missing_filament = []
  203. for printer in printers:
  204. if printer.id in exclude_ids:
  205. printers_busy.append(printer.name)
  206. continue
  207. is_connected = printer_manager.is_connected(printer.id)
  208. is_idle = self._is_printer_idle(printer.id) if is_connected else False
  209. if not is_connected:
  210. printers_offline.append(printer.name)
  211. continue
  212. if not is_idle:
  213. printers_busy.append(printer.name)
  214. continue
  215. # Validate filament compatibility if required types are specified
  216. if required_filament_types:
  217. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  218. if missing:
  219. printers_missing_filament.append((printer.name, missing))
  220. logger.debug(f"Skipping printer {printer.id} ({printer.name}) - missing filaments: {missing}")
  221. continue
  222. # Found a matching printer - clear waiting reason
  223. return printer.id, None
  224. # Build waiting reason from what we found
  225. reasons = []
  226. if printers_missing_filament:
  227. # Filament mismatch is most actionable - show first
  228. names_and_missing = [f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament]
  229. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  230. if printers_busy:
  231. reasons.append(f"Busy: {', '.join(printers_busy)}")
  232. if printers_offline:
  233. reasons.append(f"Offline: {', '.join(printers_offline)}")
  234. return None, " | ".join(reasons) if reasons else f"No available {model} printers"
  235. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  236. """Get the list of required filament types that are not loaded on the printer.
  237. Args:
  238. printer_id: The printer ID
  239. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  240. Returns:
  241. List of missing filament types (empty if all are loaded)
  242. """
  243. status = printer_manager.get_status(printer_id)
  244. if not status:
  245. return required_types # Can't determine, assume all missing
  246. # Collect all filament types loaded on this printer (AMS units + external spool)
  247. loaded_types: set[str] = set()
  248. # Check AMS units (stored in raw_data["ams"])
  249. ams_data = status.raw_data.get("ams", [])
  250. if ams_data:
  251. for ams_unit in ams_data:
  252. for tray in ams_unit.get("tray", []):
  253. tray_type = tray.get("tray_type")
  254. if tray_type:
  255. loaded_types.add(tray_type.upper())
  256. # Check external spool (virtual tray, stored in raw_data["vt_tray"])
  257. vt_tray = status.raw_data.get("vt_tray")
  258. if vt_tray:
  259. vt_type = vt_tray.get("tray_type")
  260. if vt_type:
  261. loaded_types.add(vt_type.upper())
  262. # Find which required types are missing (case-insensitive comparison)
  263. missing = []
  264. for req_type in required_types:
  265. if req_type.upper() not in loaded_types:
  266. missing.append(req_type)
  267. return missing
  268. def _is_printer_idle(self, printer_id: int) -> bool:
  269. """Check if a printer is connected and idle."""
  270. if not printer_manager.is_connected(printer_id):
  271. return False
  272. state = printer_manager.get_status(printer_id)
  273. if not state:
  274. return False
  275. # Printer is idle if state is IDLE, FINISH, FAILED, or unknown
  276. # FAILED means previous print failed, printer is ready for new print
  277. return state.state in ("IDLE", "FINISH", "FAILED", "unknown")
  278. async def _get_smart_plug(self, db: AsyncSession, printer_id: int) -> SmartPlug | None:
  279. """Get the smart plug associated with a printer."""
  280. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  281. return result.scalar_one_or_none()
  282. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  283. """Turn on smart plug and wait for printer to connect.
  284. Returns True if printer connected successfully within timeout.
  285. """
  286. # Check current plug state
  287. status = await tasmota_service.get_status(plug)
  288. if not status.get("reachable"):
  289. logger.warning(f"Smart plug '{plug.name}' is not reachable")
  290. return False
  291. # Turn on if not already on
  292. if status.get("state") != "ON":
  293. success = await tasmota_service.turn_on(plug)
  294. if not success:
  295. logger.warning(f"Failed to turn on smart plug '{plug.name}'")
  296. return False
  297. logger.info(f"Powered on smart plug '{plug.name}' for printer {printer_id}")
  298. # Get printer from database for connection
  299. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  300. printer = result.scalar_one_or_none()
  301. if not printer:
  302. logger.error(f"Printer {printer_id} not found in database")
  303. return False
  304. # Wait for printer to boot (give it some time before trying to connect)
  305. logger.info(f"Waiting 30s for printer {printer_id} to boot...")
  306. await asyncio.sleep(30)
  307. # Try to connect to the printer periodically
  308. elapsed = 30 # Already waited 30s
  309. while elapsed < self._power_on_wait_time:
  310. # Try to connect
  311. logger.info(f"Attempting to connect to printer {printer_id}...")
  312. try:
  313. connected = await printer_manager.connect_printer(printer)
  314. if connected:
  315. logger.info(f"Printer {printer_id} connected after {elapsed}s")
  316. # Give it a moment to stabilize and get status
  317. await asyncio.sleep(5)
  318. return True
  319. except Exception as e:
  320. logger.debug(f"Connection attempt failed: {e}")
  321. await asyncio.sleep(self._power_on_check_interval)
  322. elapsed += self._power_on_check_interval
  323. logger.debug(f"Waiting for printer {printer_id} to connect... ({elapsed}s)")
  324. logger.warning(f"Printer {printer_id} did not connect within {self._power_on_wait_time}s after power on")
  325. return False
  326. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  327. """Check if the previous print on this printer succeeded."""
  328. # Find the most recent completed queue item for this printer
  329. result = await db.execute(
  330. select(PrintQueueItem)
  331. .where(PrintQueueItem.printer_id == item.printer_id)
  332. .where(PrintQueueItem.id != item.id)
  333. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  334. .order_by(PrintQueueItem.completed_at.desc())
  335. .limit(1)
  336. )
  337. prev_item = result.scalar_one_or_none()
  338. # If no previous item, assume success (first in queue)
  339. if not prev_item:
  340. return True
  341. return prev_item.status == "completed"
  342. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  343. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  344. if not item.auto_off_after:
  345. return
  346. plug = await self._get_smart_plug(db, item.printer_id)
  347. if plug and plug.enabled:
  348. logger.info(f"Auto-off: Waiting for printer {item.printer_id} to cool down before power off...")
  349. # Wait for cooldown (up to 10 minutes)
  350. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  351. logger.info(f"Auto-off: Powering off printer {item.printer_id}")
  352. await tasmota_service.turn_off(plug)
  353. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  354. """Get a human-readable name for a queue item."""
  355. if item.archive_id:
  356. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  357. archive = result.scalar_one_or_none()
  358. if archive:
  359. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  360. if item.library_file_id:
  361. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  362. library_file = result.scalar_one_or_none()
  363. if library_file:
  364. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  365. return f"Job #{item.id}"
  366. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  367. """Get printer by ID."""
  368. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  369. return result.scalar_one_or_none()
  370. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  371. """Upload file and start print for a queue item.
  372. Supports two sources:
  373. - archive_id: Print from an existing archive
  374. - library_file_id: Print from a library file (file manager)
  375. """
  376. logger.info(f"Starting queue item {item.id}")
  377. # Get printer first (needed for both paths)
  378. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  379. printer = result.scalar_one_or_none()
  380. if not printer:
  381. item.status = "failed"
  382. item.error_message = "Printer not found"
  383. item.completed_at = datetime.utcnow()
  384. await db.commit()
  385. logger.error(f"Queue item {item.id}: Printer {item.printer_id} not found")
  386. await self._power_off_if_needed(db, item)
  387. return
  388. # Check printer is connected
  389. if not printer_manager.is_connected(item.printer_id):
  390. item.status = "failed"
  391. item.error_message = "Printer not connected"
  392. item.completed_at = datetime.utcnow()
  393. await db.commit()
  394. logger.error(f"Queue item {item.id}: Printer {item.printer_id} not connected")
  395. await self._power_off_if_needed(db, item)
  396. return
  397. # Determine source: archive or library file
  398. archive = None
  399. library_file = None
  400. file_path = None
  401. filename = None
  402. if item.archive_id:
  403. # Print from archive
  404. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  405. archive = result.scalar_one_or_none()
  406. if not archive:
  407. item.status = "failed"
  408. item.error_message = "Archive not found"
  409. item.completed_at = datetime.utcnow()
  410. await db.commit()
  411. logger.error(f"Queue item {item.id}: Archive {item.archive_id} not found")
  412. await self._power_off_if_needed(db, item)
  413. return
  414. file_path = settings.base_dir / archive.file_path
  415. filename = archive.filename
  416. elif item.library_file_id:
  417. # Print from library file (file manager)
  418. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  419. library_file = result.scalar_one_or_none()
  420. if not library_file:
  421. item.status = "failed"
  422. item.error_message = "Library file not found"
  423. item.completed_at = datetime.utcnow()
  424. await db.commit()
  425. logger.error(f"Queue item {item.id}: Library file {item.library_file_id} not found")
  426. await self._power_off_if_needed(db, item)
  427. return
  428. # Library files store absolute paths
  429. from pathlib import Path
  430. lib_path = Path(library_file.file_path)
  431. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  432. filename = library_file.filename
  433. else:
  434. # Neither archive nor library file specified
  435. item.status = "failed"
  436. item.error_message = "No source file specified"
  437. item.completed_at = datetime.utcnow()
  438. await db.commit()
  439. logger.error(f"Queue item {item.id}: No archive_id or library_file_id specified")
  440. await self._power_off_if_needed(db, item)
  441. return
  442. # Check file exists on disk
  443. if not file_path.exists():
  444. item.status = "failed"
  445. item.error_message = "Source file not found on disk"
  446. item.completed_at = datetime.utcnow()
  447. await db.commit()
  448. logger.error(f"Queue item {item.id}: File not found: {file_path}")
  449. await self._power_off_if_needed(db, item)
  450. return
  451. # Upload file to printer via FTP
  452. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  453. base_name = filename
  454. if base_name.endswith(".gcode.3mf"):
  455. base_name = base_name[:-10] # Remove .gcode.3mf
  456. elif base_name.endswith(".3mf"):
  457. base_name = base_name[:-4] # Remove .3mf
  458. remote_filename = f"{base_name}.3mf"
  459. # Upload to root directory (not /cache/) - the start_print command references
  460. # files by name only (ftp://{filename}), so they must be in the root
  461. remote_path = f"/{remote_filename}"
  462. # Get FTP retry settings
  463. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  464. # Delete existing file if present (avoids 553 error on overwrite)
  465. try:
  466. await delete_file_async(
  467. printer.ip_address,
  468. printer.access_code,
  469. remote_path,
  470. socket_timeout=ftp_timeout,
  471. printer_model=printer.model,
  472. )
  473. except Exception:
  474. pass # File may not exist, that's fine
  475. try:
  476. if ftp_retry_enabled:
  477. uploaded = await with_ftp_retry(
  478. upload_file_async,
  479. printer.ip_address,
  480. printer.access_code,
  481. file_path,
  482. remote_path,
  483. socket_timeout=ftp_timeout,
  484. printer_model=printer.model,
  485. max_retries=ftp_retry_count,
  486. retry_delay=ftp_retry_delay,
  487. operation_name=f"Upload print to {printer.name}",
  488. )
  489. else:
  490. uploaded = await upload_file_async(
  491. printer.ip_address,
  492. printer.access_code,
  493. file_path,
  494. remote_path,
  495. socket_timeout=ftp_timeout,
  496. printer_model=printer.model,
  497. )
  498. except Exception as e:
  499. uploaded = False
  500. logger.error(f"Queue item {item.id}: FTP error: {e}")
  501. if not uploaded:
  502. item.status = "failed"
  503. item.error_message = "Failed to upload file to printer"
  504. item.completed_at = datetime.utcnow()
  505. await db.commit()
  506. logger.error(f"Queue item {item.id}: FTP upload failed")
  507. # Send failure notification
  508. await notification_service.on_queue_job_failed(
  509. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  510. printer_id=printer.id,
  511. printer_name=printer.name,
  512. reason="Failed to upload file to printer",
  513. db=db,
  514. )
  515. await self._power_off_if_needed(db, item)
  516. return
  517. # Register as expected print so we don't create a duplicate archive
  518. # Only applicable for archive-based prints
  519. if archive:
  520. from backend.app.main import register_expected_print
  521. register_expected_print(item.printer_id, remote_filename, archive.id)
  522. # Parse AMS mapping if stored
  523. ams_mapping = None
  524. if item.ams_mapping:
  525. try:
  526. import json
  527. ams_mapping = json.loads(item.ams_mapping)
  528. except json.JSONDecodeError:
  529. logger.warning(f"Queue item {item.id}: Invalid AMS mapping JSON, ignoring")
  530. # Start the print with AMS mapping, plate_id and print options
  531. started = printer_manager.start_print(
  532. item.printer_id,
  533. remote_filename,
  534. plate_id=item.plate_id or 1,
  535. ams_mapping=ams_mapping,
  536. bed_levelling=item.bed_levelling,
  537. flow_cali=item.flow_cali,
  538. vibration_cali=item.vibration_cali,
  539. layer_inspect=item.layer_inspect,
  540. timelapse=item.timelapse,
  541. use_ams=item.use_ams,
  542. )
  543. if started:
  544. item.status = "printing"
  545. item.started_at = datetime.utcnow()
  546. await db.commit()
  547. logger.info(f"Queue item {item.id}: Print started - {filename}")
  548. # Get estimated time for notification
  549. estimated_time = None
  550. if archive and archive.print_time_seconds:
  551. estimated_time = archive.print_time_seconds
  552. elif library_file and library_file.print_time_seconds:
  553. estimated_time = library_file.print_time_seconds
  554. # Send job started notification
  555. await notification_service.on_queue_job_started(
  556. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  557. printer_id=printer.id,
  558. printer_name=printer.name,
  559. db=db,
  560. estimated_time=estimated_time,
  561. )
  562. # MQTT relay - publish queue job started
  563. try:
  564. from backend.app.services.mqtt_relay import mqtt_relay
  565. await mqtt_relay.on_queue_job_started(
  566. job_id=item.id,
  567. filename=filename,
  568. printer_id=printer.id,
  569. printer_name=printer.name,
  570. printer_serial=printer.serial_number,
  571. )
  572. except Exception:
  573. pass # Don't fail if MQTT fails
  574. else:
  575. item.status = "failed"
  576. item.error_message = "Failed to send print command"
  577. item.completed_at = datetime.utcnow()
  578. await db.commit()
  579. logger.error(f"Queue item {item.id}: Failed to start print")
  580. # Send failure notification
  581. await notification_service.on_queue_job_failed(
  582. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  583. printer_id=printer.id,
  584. printer_name=printer.name,
  585. reason="Failed to send print command",
  586. db=db,
  587. )
  588. await self._power_off_if_needed(db, item)
  589. # Global scheduler instance
  590. scheduler = PrintScheduler()