print_scheduler.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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
  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. # 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(f"Printer {item.printer_id} offline, attempting to power on via smart plug")
  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(f"Could not power on printer {item.printer_id} via smart plug")
  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(f"Skipped queue item {item.id} - previous print failed")
  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(f"Skipped queue item {item.id} - previous print failed")
  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(f"Model-based assignment: queue item {item.id} assigned to printer {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(f"Skipping printer {printer.id} ({printer.name}) - missing filaments: {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(f"Cannot compute AMS mapping: printer {printer_id} status unavailable")
  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(f"No filament requirements found for queue item {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(f"No filaments loaded on printer {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. used_g = filament_elem.get("used_g", "0")
  367. try:
  368. used_grams = float(used_g)
  369. if used_grams > 0 and filament_id:
  370. filaments.append(
  371. {
  372. "slot_id": int(filament_id),
  373. "type": filament_type,
  374. "color": filament_color,
  375. "used_grams": round(used_grams, 1),
  376. }
  377. )
  378. except (ValueError, TypeError):
  379. pass
  380. break
  381. else:
  382. # No plate_id - extract all filaments with used_g > 0
  383. for filament_elem in root.findall("./filament"):
  384. filament_id = filament_elem.get("id")
  385. filament_type = filament_elem.get("type", "")
  386. filament_color = filament_elem.get("color", "")
  387. used_g = filament_elem.get("used_g", "0")
  388. try:
  389. used_grams = float(used_g)
  390. if used_grams > 0 and filament_id:
  391. filaments.append(
  392. {
  393. "slot_id": int(filament_id),
  394. "type": filament_type,
  395. "color": filament_color,
  396. "used_grams": round(used_grams, 1),
  397. }
  398. )
  399. except (ValueError, TypeError):
  400. pass
  401. filaments.sort(key=lambda x: x["slot_id"])
  402. except Exception as e:
  403. logger.warning(f"Failed to parse filament requirements: {e}")
  404. return None
  405. return filaments if filaments else None
  406. def _build_loaded_filaments(self, status) -> list[dict]:
  407. """Build list of loaded filaments from printer status.
  408. Args:
  409. status: PrinterState from printer_manager
  410. Returns:
  411. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  412. """
  413. filaments = []
  414. # Parse AMS units from raw_data
  415. ams_data = status.raw_data.get("ams", [])
  416. for ams_unit in ams_data:
  417. ams_id = ams_unit.get("id", 0)
  418. trays = ams_unit.get("tray", [])
  419. is_ht = len(trays) == 1 # AMS-HT has single tray
  420. for tray in trays:
  421. tray_type = tray.get("tray_type")
  422. if tray_type:
  423. tray_id = tray.get("id", 0)
  424. tray_color = tray.get("tray_color", "")
  425. # Normalize color: remove alpha, add hash
  426. color = self._normalize_color(tray_color)
  427. # Calculate global tray ID
  428. global_tray_id = ams_id * 4 + tray_id
  429. filaments.append(
  430. {
  431. "type": tray_type,
  432. "color": color,
  433. "ams_id": ams_id,
  434. "tray_id": tray_id,
  435. "is_ht": is_ht,
  436. "is_external": False,
  437. "global_tray_id": global_tray_id,
  438. }
  439. )
  440. # Check external spool (vt_tray)
  441. vt_tray = status.raw_data.get("vt_tray")
  442. if vt_tray and vt_tray.get("tray_type"):
  443. color = self._normalize_color(vt_tray.get("tray_color", ""))
  444. filaments.append(
  445. {
  446. "type": vt_tray["tray_type"],
  447. "color": color,
  448. "ams_id": -1,
  449. "tray_id": 0,
  450. "is_ht": False,
  451. "is_external": True,
  452. "global_tray_id": 254,
  453. }
  454. )
  455. return filaments
  456. def _normalize_color(self, color: str | None) -> str:
  457. """Normalize color to #RRGGBB format."""
  458. if not color:
  459. return "#808080"
  460. hex_color = color.replace("#", "")[:6]
  461. return f"#{hex_color}"
  462. def _normalize_color_for_compare(self, color: str | None) -> str:
  463. """Normalize color for comparison (lowercase, no hash)."""
  464. if not color:
  465. return ""
  466. return color.replace("#", "").lower()[:6]
  467. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  468. """Check if two colors are visually similar within a threshold."""
  469. hex1 = self._normalize_color_for_compare(color1)
  470. hex2 = self._normalize_color_for_compare(color2)
  471. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  472. return False
  473. try:
  474. r1 = int(hex1[0:2], 16)
  475. g1 = int(hex1[2:4], 16)
  476. b1 = int(hex1[4:6], 16)
  477. r2 = int(hex2[0:2], 16)
  478. g2 = int(hex2[2:4], 16)
  479. b2 = int(hex2[4:6], 16)
  480. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  481. except ValueError:
  482. return False
  483. def _match_filaments_to_slots(self, required: list[dict], loaded: list[dict]) -> list[int] | None:
  484. """Match required filaments to loaded filaments and build AMS mapping.
  485. Priority: exact color match > similar color match > type-only match
  486. Args:
  487. required: List of required filaments with slot_id, type, color
  488. loaded: List of loaded filaments with type, color, global_tray_id
  489. Returns:
  490. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  491. """
  492. if not required:
  493. return None
  494. # Track used trays to avoid duplicate assignment
  495. used_tray_ids: set[int] = set()
  496. comparisons = []
  497. for req in required:
  498. req_type = (req.get("type") or "").upper()
  499. req_color = req.get("color", "")
  500. # Find best match: exact color > similar color > type-only
  501. exact_match = None
  502. similar_match = None
  503. type_only_match = None
  504. for f in loaded:
  505. if f["global_tray_id"] in used_tray_ids:
  506. continue
  507. f_type = (f.get("type") or "").upper()
  508. if f_type != req_type:
  509. continue
  510. # Type matches - check color
  511. f_color = f.get("color", "")
  512. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  513. exact_match = f
  514. break # Best possible match
  515. elif self._colors_are_similar(f_color, req_color):
  516. if not similar_match:
  517. similar_match = f
  518. elif not type_only_match:
  519. type_only_match = f
  520. match = exact_match or similar_match or type_only_match
  521. if match:
  522. used_tray_ids.add(match["global_tray_id"])
  523. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  524. else:
  525. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  526. # Build mapping array
  527. if not comparisons:
  528. return None
  529. max_slot_id = max(c["slot_id"] for c in comparisons)
  530. if max_slot_id <= 0:
  531. return None
  532. mapping = [-1] * max_slot_id
  533. for c in comparisons:
  534. slot_id = c["slot_id"]
  535. if slot_id and slot_id > 0:
  536. mapping[slot_id - 1] = c["global_tray_id"]
  537. return mapping
  538. def _is_printer_idle(self, printer_id: int) -> bool:
  539. """Check if a printer is connected and idle."""
  540. if not printer_manager.is_connected(printer_id):
  541. return False
  542. state = printer_manager.get_status(printer_id)
  543. if not state:
  544. return False
  545. # Printer is idle if state is IDLE, FINISH, FAILED, or unknown
  546. # FAILED means previous print failed, printer is ready for new print
  547. return state.state in ("IDLE", "FINISH", "FAILED", "unknown")
  548. async def _get_smart_plug(self, db: AsyncSession, printer_id: int) -> SmartPlug | None:
  549. """Get the smart plug associated with a printer."""
  550. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  551. return result.scalar_one_or_none()
  552. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  553. """Turn on smart plug and wait for printer to connect.
  554. Returns True if printer connected successfully within timeout.
  555. """
  556. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  557. service = await smart_plug_manager.get_service_for_plug(plug, db)
  558. # Check current plug state
  559. status = await service.get_status(plug)
  560. if not status.get("reachable"):
  561. logger.warning(f"Smart plug '{plug.name}' is not reachable")
  562. return False
  563. # Turn on if not already on
  564. if status.get("state") != "ON":
  565. success = await service.turn_on(plug)
  566. if not success:
  567. logger.warning(f"Failed to turn on smart plug '{plug.name}'")
  568. return False
  569. logger.info(f"Powered on smart plug '{plug.name}' for printer {printer_id}")
  570. # Get printer from database for connection
  571. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  572. printer = result.scalar_one_or_none()
  573. if not printer:
  574. logger.error(f"Printer {printer_id} not found in database")
  575. return False
  576. # Wait for printer to boot (give it some time before trying to connect)
  577. logger.info(f"Waiting 30s for printer {printer_id} to boot...")
  578. await asyncio.sleep(30)
  579. # Try to connect to the printer periodically
  580. elapsed = 30 # Already waited 30s
  581. while elapsed < self._power_on_wait_time:
  582. # Try to connect
  583. logger.info(f"Attempting to connect to printer {printer_id}...")
  584. try:
  585. connected = await printer_manager.connect_printer(printer)
  586. if connected:
  587. logger.info(f"Printer {printer_id} connected after {elapsed}s")
  588. # Give it a moment to stabilize and get status
  589. await asyncio.sleep(5)
  590. return True
  591. except Exception as e:
  592. logger.debug(f"Connection attempt failed: {e}")
  593. await asyncio.sleep(self._power_on_check_interval)
  594. elapsed += self._power_on_check_interval
  595. logger.debug(f"Waiting for printer {printer_id} to connect... ({elapsed}s)")
  596. logger.warning(f"Printer {printer_id} did not connect within {self._power_on_wait_time}s after power on")
  597. return False
  598. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  599. """Check if the previous print on this printer succeeded."""
  600. # Find the most recent completed queue item for this printer
  601. result = await db.execute(
  602. select(PrintQueueItem)
  603. .where(PrintQueueItem.printer_id == item.printer_id)
  604. .where(PrintQueueItem.id != item.id)
  605. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  606. .order_by(PrintQueueItem.completed_at.desc())
  607. .limit(1)
  608. )
  609. prev_item = result.scalar_one_or_none()
  610. # If no previous item, assume success (first in queue)
  611. if not prev_item:
  612. return True
  613. return prev_item.status == "completed"
  614. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  615. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  616. if not item.auto_off_after:
  617. return
  618. plug = await self._get_smart_plug(db, item.printer_id)
  619. if plug and plug.enabled:
  620. logger.info(f"Auto-off: Waiting for printer {item.printer_id} to cool down before power off...")
  621. # Wait for cooldown (up to 10 minutes)
  622. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  623. logger.info(f"Auto-off: Powering off printer {item.printer_id}")
  624. service = await smart_plug_manager.get_service_for_plug(plug, db)
  625. await service.turn_off(plug)
  626. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  627. """Get a human-readable name for a queue item."""
  628. if item.archive_id:
  629. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  630. archive = result.scalar_one_or_none()
  631. if archive:
  632. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  633. if item.library_file_id:
  634. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  635. library_file = result.scalar_one_or_none()
  636. if library_file:
  637. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  638. return f"Job #{item.id}"
  639. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  640. """Get printer by ID."""
  641. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  642. return result.scalar_one_or_none()
  643. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  644. """Upload file and start print for a queue item.
  645. Supports two sources:
  646. - archive_id: Print from an existing archive
  647. - library_file_id: Print from a library file (file manager)
  648. """
  649. logger.info(f"Starting queue item {item.id}")
  650. # Get printer first (needed for both paths)
  651. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  652. printer = result.scalar_one_or_none()
  653. if not printer:
  654. item.status = "failed"
  655. item.error_message = "Printer not found"
  656. item.completed_at = datetime.utcnow()
  657. await db.commit()
  658. logger.error(f"Queue item {item.id}: Printer {item.printer_id} not found")
  659. await self._power_off_if_needed(db, item)
  660. return
  661. # Check printer is connected
  662. if not printer_manager.is_connected(item.printer_id):
  663. item.status = "failed"
  664. item.error_message = "Printer not connected"
  665. item.completed_at = datetime.utcnow()
  666. await db.commit()
  667. logger.error(f"Queue item {item.id}: Printer {item.printer_id} not connected")
  668. await self._power_off_if_needed(db, item)
  669. return
  670. # Determine source: archive or library file
  671. archive = None
  672. library_file = None
  673. file_path = None
  674. filename = None
  675. if item.archive_id:
  676. # Print from archive
  677. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  678. archive = result.scalar_one_or_none()
  679. if not archive:
  680. item.status = "failed"
  681. item.error_message = "Archive not found"
  682. item.completed_at = datetime.utcnow()
  683. await db.commit()
  684. logger.error(f"Queue item {item.id}: Archive {item.archive_id} not found")
  685. await self._power_off_if_needed(db, item)
  686. return
  687. file_path = settings.base_dir / archive.file_path
  688. filename = archive.filename
  689. elif item.library_file_id:
  690. # Print from library file (file manager)
  691. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  692. library_file = result.scalar_one_or_none()
  693. if not library_file:
  694. item.status = "failed"
  695. item.error_message = "Library file not found"
  696. item.completed_at = datetime.utcnow()
  697. await db.commit()
  698. logger.error(f"Queue item {item.id}: Library file {item.library_file_id} not found")
  699. await self._power_off_if_needed(db, item)
  700. return
  701. # Library files store absolute paths
  702. from pathlib import Path
  703. lib_path = Path(library_file.file_path)
  704. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  705. filename = library_file.filename
  706. else:
  707. # Neither archive nor library file specified
  708. item.status = "failed"
  709. item.error_message = "No source file specified"
  710. item.completed_at = datetime.utcnow()
  711. await db.commit()
  712. logger.error(f"Queue item {item.id}: No archive_id or library_file_id specified")
  713. await self._power_off_if_needed(db, item)
  714. return
  715. # Check file exists on disk
  716. if not file_path.exists():
  717. item.status = "failed"
  718. item.error_message = "Source file not found on disk"
  719. item.completed_at = datetime.utcnow()
  720. await db.commit()
  721. logger.error(f"Queue item {item.id}: File not found: {file_path}")
  722. await self._power_off_if_needed(db, item)
  723. return
  724. # Upload file to printer via FTP
  725. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  726. base_name = filename
  727. if base_name.endswith(".gcode.3mf"):
  728. base_name = base_name[:-10] # Remove .gcode.3mf
  729. elif base_name.endswith(".3mf"):
  730. base_name = base_name[:-4] # Remove .3mf
  731. remote_filename = f"{base_name}.3mf"
  732. # Upload to root directory (not /cache/) - the start_print command references
  733. # files by name only (ftp://{filename}), so they must be in the root
  734. remote_path = f"/{remote_filename}"
  735. # Get FTP retry settings
  736. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  737. logger.info(
  738. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  739. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  740. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  741. )
  742. # Delete existing file if present (avoids 553 error on overwrite)
  743. try:
  744. logger.debug(f"Queue item {item.id}: Deleting existing file {remote_path} if present...")
  745. delete_result = await delete_file_async(
  746. printer.ip_address,
  747. printer.access_code,
  748. remote_path,
  749. socket_timeout=ftp_timeout,
  750. printer_model=printer.model,
  751. )
  752. logger.debug(f"Queue item {item.id}: Delete result: {delete_result}")
  753. except Exception as e:
  754. logger.debug(f"Queue item {item.id}: Delete failed (may not exist): {e}")
  755. try:
  756. if ftp_retry_enabled:
  757. uploaded = await with_ftp_retry(
  758. upload_file_async,
  759. printer.ip_address,
  760. printer.access_code,
  761. file_path,
  762. remote_path,
  763. socket_timeout=ftp_timeout,
  764. printer_model=printer.model,
  765. max_retries=ftp_retry_count,
  766. retry_delay=ftp_retry_delay,
  767. operation_name=f"Upload print to {printer.name}",
  768. )
  769. else:
  770. uploaded = await upload_file_async(
  771. printer.ip_address,
  772. printer.access_code,
  773. file_path,
  774. remote_path,
  775. socket_timeout=ftp_timeout,
  776. printer_model=printer.model,
  777. )
  778. except Exception as e:
  779. uploaded = False
  780. logger.error(f"Queue item {item.id}: FTP error: {e} (type: {type(e).__name__})")
  781. if not uploaded:
  782. error_msg = (
  783. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  784. "See server logs for detailed diagnostics."
  785. )
  786. item.status = "failed"
  787. item.error_message = error_msg
  788. item.completed_at = datetime.utcnow()
  789. await db.commit()
  790. logger.error(
  791. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  792. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  793. )
  794. # Send failure notification
  795. await notification_service.on_queue_job_failed(
  796. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  797. printer_id=printer.id,
  798. printer_name=printer.name,
  799. reason="Failed to upload file to printer",
  800. db=db,
  801. )
  802. await self._power_off_if_needed(db, item)
  803. return
  804. # Register as expected print so we don't create a duplicate archive
  805. # Only applicable for archive-based prints
  806. if archive:
  807. from backend.app.main import register_expected_print
  808. register_expected_print(item.printer_id, remote_filename, archive.id)
  809. # Parse AMS mapping if stored
  810. ams_mapping = None
  811. if item.ams_mapping:
  812. try:
  813. ams_mapping = json.loads(item.ams_mapping)
  814. except json.JSONDecodeError:
  815. logger.warning(f"Queue item {item.id}: Invalid AMS mapping JSON, ignoring")
  816. # Start the print with AMS mapping, plate_id and print options
  817. started = printer_manager.start_print(
  818. item.printer_id,
  819. remote_filename,
  820. plate_id=item.plate_id or 1,
  821. ams_mapping=ams_mapping,
  822. bed_levelling=item.bed_levelling,
  823. flow_cali=item.flow_cali,
  824. vibration_cali=item.vibration_cali,
  825. layer_inspect=item.layer_inspect,
  826. timelapse=item.timelapse,
  827. use_ams=item.use_ams,
  828. )
  829. if started:
  830. item.status = "printing"
  831. item.started_at = datetime.utcnow()
  832. await db.commit()
  833. logger.info(f"Queue item {item.id}: Print started - {filename}")
  834. # Get estimated time for notification
  835. estimated_time = None
  836. if archive and archive.print_time_seconds:
  837. estimated_time = archive.print_time_seconds
  838. elif library_file and library_file.print_time_seconds:
  839. estimated_time = library_file.print_time_seconds
  840. # Send job started notification
  841. await notification_service.on_queue_job_started(
  842. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  843. printer_id=printer.id,
  844. printer_name=printer.name,
  845. db=db,
  846. estimated_time=estimated_time,
  847. )
  848. # MQTT relay - publish queue job started
  849. try:
  850. from backend.app.services.mqtt_relay import mqtt_relay
  851. await mqtt_relay.on_queue_job_started(
  852. job_id=item.id,
  853. filename=filename,
  854. printer_id=printer.id,
  855. printer_name=printer.name,
  856. printer_serial=printer.serial_number,
  857. )
  858. except Exception:
  859. pass # Don't fail if MQTT fails
  860. else:
  861. item.status = "failed"
  862. item.error_message = "Failed to send print command"
  863. item.completed_at = datetime.utcnow()
  864. await db.commit()
  865. logger.error(f"Queue item {item.id}: Failed to start print")
  866. # Send failure notification
  867. await notification_service.on_queue_job_failed(
  868. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  869. printer_id=printer.id,
  870. printer_name=printer.name,
  871. reason="Failed to send print command",
  872. db=db,
  873. )
  874. await self._power_off_if_needed(db, item)
  875. # Global scheduler instance
  876. scheduler = PrintScheduler()