print_scheduler.py 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import zipfile
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. import defusedxml.ElementTree as ET
  10. from sqlalchemy import func, select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import async_session
  14. from backend.app.models.archive import PrintArchive
  15. from backend.app.models.library import LibraryFile
  16. from backend.app.models.print_queue import PrintQueueItem
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.settings import Settings
  19. from backend.app.models.smart_plug import SmartPlug
  20. from backend.app.services.bambu_ftp import delete_file_async, get_ftp_retry_settings, upload_file_async, with_ftp_retry
  21. from backend.app.services.notification_service import notification_service
  22. from backend.app.services.printer_manager import printer_manager, supports_drying
  23. from backend.app.services.smart_plug_manager import smart_plug_manager
  24. from backend.app.utils.printer_models import normalize_printer_model
  25. from backend.app.utils.threemf_tools import extract_nozzle_mapping_from_3mf
  26. logger = logging.getLogger(__name__)
  27. # Filament type equivalence groups — types within the same group are
  28. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  29. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  30. ["PA-CF", "PA12-CF", "PAHT-CF"],
  31. ]
  32. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  33. for _group in _FILAMENT_TYPE_GROUPS:
  34. _canonical = _group[0].upper()
  35. for _t in _group:
  36. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  37. def _canonical_filament_type(ftype: str) -> str:
  38. """Return canonical type for equivalence matching."""
  39. upper = ftype.upper()
  40. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  41. class PrintScheduler:
  42. """Background scheduler that processes the print queue."""
  43. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  44. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  45. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  46. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  47. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  48. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  49. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  50. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  51. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  52. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  53. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  54. }
  55. def __init__(self):
  56. self._running = False
  57. self._check_interval = 30 # seconds
  58. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  59. self._power_on_check_interval = 10 # seconds between connection checks
  60. self._min_drying_seconds = 1800 # 30 minutes minimum before humidity re-check can stop drying
  61. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  62. self._drying_in_progress: dict[int, float] = {}
  63. async def run(self):
  64. """Main loop - check queue every interval."""
  65. self._running = True
  66. logger.info("Print scheduler started")
  67. while self._running:
  68. try:
  69. await self.check_queue()
  70. except Exception as e:
  71. logger.error("Scheduler error: %s", e)
  72. await asyncio.sleep(self._check_interval)
  73. def stop(self):
  74. """Stop the scheduler."""
  75. self._running = False
  76. logger.info("Print scheduler stopped")
  77. async def check_queue(self):
  78. """Check for prints ready to start."""
  79. async with async_session() as db:
  80. # Check if shortest-job-first scheduling is enabled
  81. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  82. # Get all pending items, ordered by printer and position (or SJF order)
  83. if sjf_enabled:
  84. # SJF: group by printer (and target_model for model-based jobs),
  85. # then items already jumped get top priority (starvation guard),
  86. # then sort by print_time ascending. Items with no print time go last.
  87. result = await db.execute(
  88. select(PrintQueueItem)
  89. .where(PrintQueueItem.status == "pending")
  90. .order_by(
  91. PrintQueueItem.printer_id,
  92. PrintQueueItem.target_model,
  93. PrintQueueItem.been_jumped.desc(),
  94. PrintQueueItem.print_time_seconds.asc().nullslast(),
  95. PrintQueueItem.position,
  96. )
  97. )
  98. else:
  99. result = await db.execute(
  100. select(PrintQueueItem)
  101. .where(PrintQueueItem.status == "pending")
  102. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  103. )
  104. items = list(result.scalars().all())
  105. # Read plate-clear setting once per queue check
  106. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=True)
  107. if not items:
  108. # No pending items — still check auto-drying on idle printers
  109. await self._check_auto_drying(db, [], set(), require_plate_clear=require_plate_clear)
  110. return
  111. logger.info(
  112. "Queue check: found %d pending items: %s",
  113. len(items),
  114. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  115. )
  116. # Track busy printers to avoid assigning multiple items to same printer
  117. busy_printers: set[int] = set()
  118. # Log skip reasons once per queue check (not per item)
  119. skip_reasons: dict[str, int] = {}
  120. for item in items:
  121. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  122. if item.scheduled_time:
  123. sched = item.scheduled_time
  124. if sched.tzinfo is None:
  125. sched = sched.replace(tzinfo=timezone.utc)
  126. if sched > datetime.now(timezone.utc):
  127. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  128. continue
  129. # Skip items that require manual start
  130. if item.manual_start:
  131. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  132. continue
  133. if item.printer_id:
  134. # Specific printer assignment (existing behavior)
  135. if item.printer_id in busy_printers:
  136. continue
  137. # Check if printer is idle
  138. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  139. printer_connected = printer_manager.is_connected(item.printer_id)
  140. # If printer not connected, try to power on via smart plug
  141. if not printer_connected:
  142. plug = await self._get_smart_plug(db, item.printer_id)
  143. if plug and plug.auto_on and plug.enabled:
  144. logger.info("Printer %s offline, attempting to power on via smart plug", item.printer_id)
  145. powered_on = await self._power_on_and_wait(plug, item.printer_id, db)
  146. if powered_on:
  147. printer_connected = True
  148. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  149. else:
  150. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  151. busy_printers.add(item.printer_id)
  152. continue
  153. else:
  154. # No plug or auto_on disabled
  155. busy_printers.add(item.printer_id)
  156. continue
  157. # Check if printer is idle (busy with another print)
  158. if not printer_idle:
  159. # If printer is drying (not truly busy), handle based on queue_drying_block
  160. if self._drying_in_progress.get(item.printer_id):
  161. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  162. if block_for_drying:
  163. # Drying blocks queue — skip this printer
  164. busy_printers.add(item.printer_id)
  165. continue
  166. else:
  167. # Print takes priority — stop drying
  168. await self._stop_drying(item.printer_id)
  169. # Re-check idle after stopping drying
  170. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  171. if not printer_idle:
  172. busy_printers.add(item.printer_id)
  173. continue
  174. else:
  175. busy_printers.add(item.printer_id)
  176. continue
  177. # Check condition (previous print success)
  178. if item.require_previous_success:
  179. if not await self._check_previous_success(db, item):
  180. item.status = "skipped"
  181. item.error_message = "Previous print failed or was aborted"
  182. item.completed_at = datetime.now(timezone.utc)
  183. await db.commit()
  184. logger.info("Skipped queue item %s - previous print failed", item.id)
  185. # Send notification
  186. job_name = await self._get_job_name(db, item)
  187. printer = await self._get_printer(db, item.printer_id)
  188. await notification_service.on_queue_job_skipped(
  189. job_name=job_name,
  190. printer_id=item.printer_id,
  191. printer_name=printer.name if printer else "Unknown",
  192. reason="Previous print failed or was aborted",
  193. db=db,
  194. )
  195. continue
  196. # Compute AMS mapping if not already set
  197. if not item.ams_mapping:
  198. computed_mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item)
  199. if computed_mapping:
  200. item.ams_mapping = json.dumps(computed_mapping)
  201. logger.info(
  202. f"Queue item {item.id}: Computed AMS mapping for printer {item.printer_id}: {computed_mapping}"
  203. )
  204. await db.commit()
  205. # Start the print
  206. await self._start_print(db, item)
  207. busy_printers.add(item.printer_id)
  208. # SJF starvation guard: mark items that were jumped
  209. if sjf_enabled and item.print_time_seconds is not None:
  210. for other in items:
  211. if (
  212. other.id != item.id
  213. and other.status == "pending"
  214. and other.printer_id == item.printer_id
  215. and not other.been_jumped
  216. and other.position < item.position
  217. and (
  218. other.print_time_seconds is None
  219. or other.print_time_seconds > item.print_time_seconds
  220. )
  221. ):
  222. other.been_jumped = True
  223. await db.commit()
  224. elif item.target_model:
  225. # Model-based assignment - find any idle printer of matching model
  226. # Parse required filament types if present
  227. required_types = None
  228. if item.required_filament_types:
  229. try:
  230. required_types = json.loads(item.required_filament_types)
  231. except json.JSONDecodeError:
  232. pass # Ignore malformed filament types; treat as no constraint
  233. # Parse filament overrides if present
  234. filament_overrides = None
  235. if item.filament_overrides:
  236. try:
  237. filament_overrides = json.loads(item.filament_overrides)
  238. except json.JSONDecodeError:
  239. pass
  240. # If overrides exist, use override types for validation instead
  241. effective_types = required_types
  242. if filament_overrides:
  243. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  244. if override_types:
  245. # Merge: keep original types for non-overridden slots, add override types
  246. effective_types = sorted(set(required_types or []) | set(override_types))
  247. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  248. db,
  249. item.target_model,
  250. busy_printers,
  251. effective_types,
  252. item.target_location,
  253. filament_overrides=filament_overrides,
  254. require_plate_clear=require_plate_clear,
  255. )
  256. # Update waiting_reason if changed and send notification when first waiting
  257. if item.waiting_reason != waiting_reason:
  258. was_waiting = item.waiting_reason is not None
  259. item.waiting_reason = waiting_reason
  260. await db.commit()
  261. # Send waiting notification only when transitioning to waiting state
  262. # and the reason requires user action (not just "all printers busy")
  263. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  264. job_name = await self._get_job_name(db, item)
  265. await notification_service.on_queue_job_waiting(
  266. job_name=job_name,
  267. target_model=item.target_model,
  268. waiting_reason=waiting_reason,
  269. db=db,
  270. )
  271. if printer_id:
  272. # Check condition (previous print success) before assigning
  273. if item.require_previous_success:
  274. if not await self._check_previous_success(db, item):
  275. item.status = "skipped"
  276. item.error_message = "Previous print failed or was aborted"
  277. item.completed_at = datetime.now(timezone.utc)
  278. await db.commit()
  279. logger.info("Skipped queue item %s - previous print failed", item.id)
  280. # Send notification
  281. job_name = await self._get_job_name(db, item)
  282. printer = await self._get_printer(db, printer_id)
  283. await notification_service.on_queue_job_skipped(
  284. job_name=job_name,
  285. printer_id=printer_id,
  286. printer_name=printer.name if printer else "Unknown",
  287. reason="Previous print failed or was aborted",
  288. db=db,
  289. )
  290. continue
  291. # Assign printer and start - clear waiting reason
  292. item.printer_id = printer_id
  293. item.waiting_reason = None
  294. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  295. # Send assignment notification
  296. job_name = await self._get_job_name(db, item)
  297. printer = await self._get_printer(db, printer_id)
  298. await notification_service.on_queue_job_assigned(
  299. job_name=job_name,
  300. printer_id=printer_id,
  301. printer_name=printer.name if printer else "Unknown",
  302. target_model=item.target_model,
  303. db=db,
  304. )
  305. # Compute AMS mapping for the assigned printer if not already set
  306. # This is critical for model-based jobs where mapping wasn't computed upfront
  307. if not item.ams_mapping:
  308. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  309. if computed_mapping:
  310. item.ams_mapping = json.dumps(computed_mapping)
  311. logger.info(
  312. f"Queue item {item.id}: Computed AMS mapping for printer {printer_id}: {computed_mapping}"
  313. )
  314. await db.commit()
  315. await self._start_print(db, item)
  316. busy_printers.add(printer_id)
  317. # SJF starvation guard: mark model-based items that were jumped
  318. if sjf_enabled and item.print_time_seconds is not None:
  319. for other in items:
  320. if (
  321. other.id != item.id
  322. and other.status == "pending"
  323. and other.printer_id is None
  324. and other.target_model
  325. and other.target_model.upper() == item.target_model.upper()
  326. and not other.been_jumped
  327. and other.position < item.position
  328. and (
  329. other.print_time_seconds is None
  330. or other.print_time_seconds > item.print_time_seconds
  331. )
  332. ):
  333. other.been_jumped = True
  334. await db.commit()
  335. # Log summary of skip reasons (helps diagnose why queue items aren't starting)
  336. if skip_reasons:
  337. logger.info("Queue skip summary: %s", skip_reasons)
  338. if busy_printers:
  339. # Log why each printer was busy (first time it was checked)
  340. for pid in busy_printers:
  341. state = printer_manager.get_status(pid)
  342. connected = printer_manager.is_connected(pid)
  343. plate_cleared = printer_manager.is_plate_cleared(pid)
  344. state_name = state.state if state else "NO_STATUS"
  345. logger.info(
  346. "Queue: printer %d not available — connected=%s, state=%s, plate_cleared=%s",
  347. pid,
  348. connected,
  349. state_name,
  350. plate_cleared,
  351. )
  352. # Auto-drying: start drying on idle printers that have no pending queue items
  353. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  354. async def _find_idle_printer_for_model(
  355. self,
  356. db: AsyncSession,
  357. model: str,
  358. exclude_ids: set[int],
  359. required_filament_types: list[str] | None = None,
  360. target_location: str | None = None,
  361. filament_overrides: list[dict] | None = None,
  362. require_plate_clear: bool = True,
  363. ) -> tuple[int | None, str | None]:
  364. """Find an idle, connected printer matching the model with compatible filaments.
  365. Args:
  366. db: Database session
  367. model: Printer model to match (e.g., "X1C", "P1S")
  368. exclude_ids: Printer IDs to exclude (already busy)
  369. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  370. If provided, only printers with all required types loaded will match.
  371. target_location: Optional location filter. If provided, only printers in this location are considered.
  372. filament_overrides: Optional list of override dicts. Each entry may include
  373. ``force_color_match: true`` to require an exact type+color match
  374. on the printer for that slot. Without the flag the existing
  375. colour-preference logic applies.
  376. Returns:
  377. Tuple of (printer_id, waiting_reason):
  378. - (printer_id, None) if a matching printer was found
  379. - (None, reason) if no printer is available, with explanation
  380. """
  381. # Normalize model name and use case-insensitive matching
  382. normalized_model = normalize_printer_model(model) or model
  383. query = (
  384. select(Printer)
  385. .where(func.lower(Printer.model) == normalized_model.lower())
  386. .where(Printer.is_active == True) # noqa: E712
  387. )
  388. # Add location filter if specified
  389. if target_location:
  390. query = query.where(Printer.location == target_location)
  391. result = await db.execute(query)
  392. printers = list(result.scalars().all())
  393. location_suffix = f" in {target_location}" if target_location else ""
  394. if not printers:
  395. return None, f"No active {normalized_model} printers{location_suffix} configured"
  396. # Separate force-matched overrides from preference-only overrides
  397. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  398. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  399. # Track reasons for skipping printers
  400. printers_busy = []
  401. printers_offline = []
  402. printers_missing_filament: list[tuple[str, list[str]]] = []
  403. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  404. for printer in printers:
  405. if printer.id in exclude_ids:
  406. # Printer is already claimed by another job in this scheduling run.
  407. # For force-color jobs, still check if the color would match — if not,
  408. # report it as a color mismatch rather than plain "Busy" so the user
  409. # knows the job needs a filament change, not just to wait for availability.
  410. if force_overrides and not pref_overrides:
  411. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  412. if missing_colors:
  413. printers_missing_filament.append((printer.name, missing_colors))
  414. continue
  415. printers_busy.append(printer.name)
  416. continue
  417. is_connected = printer_manager.is_connected(printer.id)
  418. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  419. if not is_connected:
  420. printers_offline.append(printer.name)
  421. continue
  422. if not is_idle:
  423. # Printer is currently printing. For force-color jobs, check whether the
  424. # loaded color would satisfy the requirement — if not, surface it as a
  425. # color-mismatch reason rather than plain "Busy" so the user understands
  426. # that the job is waiting for a filament change, not just printer availability.
  427. if force_overrides and not pref_overrides:
  428. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  429. if missing_colors:
  430. printers_missing_filament.append((printer.name, missing_colors))
  431. logger.debug(
  432. "Printer %s (%s) is busy but also has wrong force-color: %s",
  433. printer.id,
  434. printer.name,
  435. missing_colors,
  436. )
  437. continue
  438. printers_busy.append(printer.name)
  439. continue
  440. # Validate filament compatibility if required types are specified
  441. if required_filament_types:
  442. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  443. if missing:
  444. # When force_overrides are present, enrich missing entries with color info
  445. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  446. if force_overrides:
  447. force_color_map = {
  448. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  449. for o in force_overrides
  450. }
  451. missing_enriched = [
  452. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  453. for t in missing
  454. ]
  455. printers_missing_filament.append((printer.name, missing_enriched))
  456. else:
  457. printers_missing_filament.append((printer.name, missing))
  458. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  459. continue
  460. # Force color match: ALL flagged slots must have an exact type+color match
  461. if force_overrides:
  462. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  463. if missing_colors:
  464. printers_missing_filament.append((printer.name, missing_colors))
  465. logger.debug(
  466. "Skipping printer %s (%s) - missing force-matched colors: %s",
  467. printer.id,
  468. printer.name,
  469. missing_colors,
  470. )
  471. continue
  472. # If preference-only overrides exist, rank by color matches (existing behaviour)
  473. if pref_overrides:
  474. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  475. if color_matches > 0:
  476. candidates.append((printer.id, color_matches))
  477. else:
  478. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  479. printers_missing_filament.append((printer.name, override_colors))
  480. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  481. continue
  482. elif force_overrides:
  483. # Passed all force checks — immediately eligible (no preference ordering needed)
  484. return printer.id, None
  485. else:
  486. # No overrides at all - take first available (existing behavior)
  487. return printer.id, None
  488. # If we have candidates from preference override matching, pick the one with most color matches
  489. if candidates:
  490. candidates.sort(key=lambda c: c[1], reverse=True)
  491. return candidates[0][0], None
  492. # Build waiting reason from what we found
  493. reasons = []
  494. if printers_missing_filament:
  495. # Filament/color mismatch is most actionable - show first
  496. if force_overrides and not pref_overrides:
  497. # All mismatches are force-color failures — use descriptive message only;
  498. # but only if there are no busy printers that DO have the matching color.
  499. # If a printer has the right color but is busy, surface "Busy" instead so
  500. # the user knows the job will start automatically once that printer is free.
  501. if not printers_busy:
  502. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  503. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  504. # else: fall through — printers_busy will be appended below
  505. else:
  506. names_and_missing = [
  507. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  508. ]
  509. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  510. if printers_busy:
  511. reasons.append(f"Busy: {', '.join(printers_busy)}")
  512. if printers_offline:
  513. reasons.append(f"Offline: {', '.join(printers_offline)}")
  514. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  515. @staticmethod
  516. def _is_busy_only(waiting_reason: str) -> bool:
  517. """Check if the waiting reason only contains 'Busy' entries.
  518. When all matching printers are simply busy printing, the queued job
  519. will start automatically once a printer finishes — no user action
  520. is required, so we skip the notification.
  521. """
  522. parts = [p.strip() for p in waiting_reason.split(" | ")]
  523. return all(p.startswith("Busy:") for p in parts)
  524. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  525. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  526. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  527. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  528. with an exact type+color match.
  529. Returns:
  530. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  531. """
  532. status = printer_manager.get_status(printer_id)
  533. if not status:
  534. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  535. # Build set of loaded type+colour pairs from AMS and external spool
  536. loaded: set[tuple[str, str]] = set()
  537. for ams_unit in status.raw_data.get("ams", []):
  538. for tray in ams_unit.get("tray", []):
  539. tray_type = tray.get("tray_type")
  540. tray_color = tray.get("tray_color", "")
  541. if tray_type:
  542. color_norm = tray_color.replace("#", "").lower()[:6]
  543. loaded.add((_canonical_filament_type(tray_type), color_norm))
  544. for vt in status.raw_data.get("vt_tray") or []:
  545. vt_type = vt.get("tray_type")
  546. if vt_type:
  547. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  548. loaded.add((_canonical_filament_type(vt_type), color_norm))
  549. missing = []
  550. for o in force_overrides:
  551. o_type = _canonical_filament_type(o.get("type") or "")
  552. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  553. if (o_type, o_color) not in loaded:
  554. color_label = o.get("color_name") or o.get("color", "?")
  555. missing.append(f"{o_type} ({color_label})")
  556. return missing
  557. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  558. """Get the list of required filament types that are not loaded on the printer.
  559. Args:
  560. printer_id: The printer ID
  561. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  562. Returns:
  563. List of missing filament types (empty if all are loaded)
  564. """
  565. status = printer_manager.get_status(printer_id)
  566. if not status:
  567. return required_types # Can't determine, assume all missing
  568. # Collect all filament types loaded on this printer (AMS units + external spool)
  569. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  570. loaded_types: set[str] = set()
  571. # Check AMS units (stored in raw_data["ams"])
  572. ams_data = status.raw_data.get("ams", [])
  573. if ams_data:
  574. for ams_unit in ams_data:
  575. for tray in ams_unit.get("tray", []):
  576. tray_type = tray.get("tray_type")
  577. if tray_type:
  578. loaded_types.add(_canonical_filament_type(tray_type))
  579. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  580. for vt in status.raw_data.get("vt_tray") or []:
  581. vt_type = vt.get("tray_type")
  582. if vt_type:
  583. loaded_types.add(_canonical_filament_type(vt_type))
  584. # Find which required types are missing (using canonical type for equivalence)
  585. missing = []
  586. for req_type in required_types:
  587. if _canonical_filament_type(req_type) not in loaded_types:
  588. missing.append(req_type)
  589. return missing
  590. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  591. """Count how many filament overrides have an exact color match on the printer.
  592. Used to prefer printers that already have the desired override colors loaded.
  593. """
  594. status = printer_manager.get_status(printer_id)
  595. if not status:
  596. return 0
  597. # Collect loaded filaments' type+color pairs
  598. loaded: set[tuple[str, str]] = set()
  599. for ams_unit in status.raw_data.get("ams", []):
  600. for tray in ams_unit.get("tray", []):
  601. tray_type = tray.get("tray_type")
  602. tray_color = tray.get("tray_color", "")
  603. if tray_type:
  604. color_norm = tray_color.replace("#", "").lower()[:6]
  605. loaded.add((tray_type.upper(), color_norm))
  606. for vt in status.raw_data.get("vt_tray") or []:
  607. vt_type = vt.get("tray_type")
  608. if vt_type:
  609. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  610. loaded.add((vt_type.upper(), color_norm))
  611. matches = 0
  612. for o in overrides:
  613. o_type = (o.get("type") or "").upper()
  614. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  615. if (o_type, o_color) in loaded:
  616. matches += 1
  617. return matches
  618. async def _compute_ams_mapping_for_printer(
  619. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  620. ) -> list[int] | None:
  621. """Compute AMS mapping for a printer based on filament requirements.
  622. Called when a queue item has no ams_mapping set — either for model-based
  623. items after printer assignment, or printer-specific items (e.g. from VP).
  624. Args:
  625. db: Database session
  626. printer_id: The assigned printer ID
  627. item: The queue item (contains archive_id or library_file_id)
  628. Returns:
  629. AMS mapping array or None if no mapping needed/possible
  630. """
  631. # Get printer status
  632. status = printer_manager.get_status(printer_id)
  633. if not status:
  634. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  635. return None
  636. # Get filament requirements from source file
  637. filament_reqs = await self._get_filament_requirements(db, item)
  638. if not filament_reqs:
  639. logger.debug("No filament requirements found for queue item %s", item.id)
  640. return None
  641. # Apply filament overrides if present
  642. if item.filament_overrides:
  643. try:
  644. overrides = json.loads(item.filament_overrides)
  645. override_map = {o["slot_id"]: o for o in overrides}
  646. for req in filament_reqs:
  647. if req["slot_id"] in override_map:
  648. override = override_map[req["slot_id"]]
  649. req["type"] = override["type"]
  650. req["color"] = override["color"]
  651. # Clear tray_info_idx so matching uses type+color instead of
  652. # the original 3MF's tray_info_idx (which would match the old filament)
  653. req["tray_info_idx"] = ""
  654. logger.debug(
  655. "Queue item %s: Override slot %d -> %s %s",
  656. item.id,
  657. req["slot_id"],
  658. override["type"],
  659. override["color"],
  660. )
  661. except (json.JSONDecodeError, KeyError, TypeError) as e:
  662. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  663. # Build loaded filaments from printer status
  664. loaded_filaments = self._build_loaded_filaments(status)
  665. if not loaded_filaments:
  666. logger.debug("No filaments loaded on printer %s", printer_id)
  667. return None
  668. # Check if user prefers lowest remaining filament when multiple spools match
  669. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  670. # Compute mapping: match required filaments to available slots
  671. return self._match_filaments_to_slots(filament_reqs, loaded_filaments, prefer_lowest)
  672. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  673. """Extract filament requirements from the source 3MF file.
  674. Args:
  675. db: Database session
  676. item: Queue item with archive_id or library_file_id
  677. Returns:
  678. List of filament requirement dicts with slot_id, type, color, used_grams
  679. """
  680. file_path: Path | None = None
  681. if item.archive_id:
  682. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  683. archive = result.scalar_one_or_none()
  684. if archive:
  685. file_path = settings.base_dir / archive.file_path
  686. elif item.library_file_id:
  687. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  688. library_file = result.scalar_one_or_none()
  689. if library_file:
  690. lib_path = Path(library_file.file_path)
  691. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  692. if not file_path or not file_path.exists():
  693. return None
  694. filaments = []
  695. try:
  696. with zipfile.ZipFile(file_path, "r") as zf:
  697. if "Metadata/slice_info.config" not in zf.namelist():
  698. return None
  699. content = zf.read("Metadata/slice_info.config").decode()
  700. root = ET.fromstring(content)
  701. # Check if plate_id is specified - use that plate's filaments
  702. plate_id = item.plate_id
  703. if plate_id:
  704. for plate_elem in root.findall("./plate"):
  705. plate_index = None
  706. for meta in plate_elem.findall("metadata"):
  707. if meta.get("key") == "index":
  708. plate_index = int(meta.get("value", "0"))
  709. break
  710. if plate_index == plate_id:
  711. for filament_elem in plate_elem.findall("./filament"):
  712. filament_id = filament_elem.get("id")
  713. filament_type = filament_elem.get("type", "")
  714. filament_color = filament_elem.get("color", "")
  715. # tray_info_idx identifies the specific spool selected when slicing
  716. tray_info_idx = filament_elem.get("tray_info_idx", "")
  717. used_g = filament_elem.get("used_g", "0")
  718. try:
  719. used_grams = float(used_g)
  720. if used_grams > 0 and filament_id:
  721. filaments.append(
  722. {
  723. "slot_id": int(filament_id),
  724. "type": filament_type,
  725. "color": filament_color,
  726. "tray_info_idx": tray_info_idx,
  727. "used_grams": round(used_grams, 1),
  728. }
  729. )
  730. except (ValueError, TypeError):
  731. pass # Skip filament entry with unparseable usage data
  732. break
  733. else:
  734. # No plate_id - extract all filaments with used_g > 0
  735. for filament_elem in root.findall("./filament"):
  736. filament_id = filament_elem.get("id")
  737. filament_type = filament_elem.get("type", "")
  738. filament_color = filament_elem.get("color", "")
  739. # tray_info_idx identifies the specific spool selected when slicing
  740. tray_info_idx = filament_elem.get("tray_info_idx", "")
  741. used_g = filament_elem.get("used_g", "0")
  742. try:
  743. used_grams = float(used_g)
  744. if used_grams > 0 and filament_id:
  745. filaments.append(
  746. {
  747. "slot_id": int(filament_id),
  748. "type": filament_type,
  749. "color": filament_color,
  750. "tray_info_idx": tray_info_idx,
  751. "used_grams": round(used_grams, 1),
  752. }
  753. )
  754. except (ValueError, TypeError):
  755. pass # Skip filament entry with unparseable usage data
  756. filaments.sort(key=lambda x: x["slot_id"])
  757. # Enrich with nozzle mapping for dual-nozzle printers
  758. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  759. if nozzle_mapping:
  760. for filament in filaments:
  761. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  762. except Exception as e:
  763. logger.warning("Failed to parse filament requirements: %s", e)
  764. return None
  765. return filaments if filaments else None
  766. def _build_loaded_filaments(self, status) -> list[dict]:
  767. """Build list of loaded filaments from printer status.
  768. Args:
  769. status: PrinterState from printer_manager
  770. Returns:
  771. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  772. """
  773. filaments = []
  774. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  775. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  776. # Parse AMS units from raw_data
  777. ams_data = status.raw_data.get("ams", [])
  778. for ams_unit in ams_data:
  779. ams_id = int(ams_unit.get("id", 0))
  780. trays = ams_unit.get("tray", [])
  781. is_ht = len(trays) == 1 # AMS-HT has single tray
  782. for tray in trays:
  783. tray_type = tray.get("tray_type")
  784. if tray_type:
  785. tray_id = int(tray.get("id", 0))
  786. tray_color = tray.get("tray_color", "")
  787. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  788. tray_info_idx = tray.get("tray_info_idx", "")
  789. # Normalize color: remove alpha, add hash
  790. color = self._normalize_color(tray_color)
  791. # Calculate global tray ID
  792. # AMS-HT units have IDs starting at 128 with a single tray
  793. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  794. filaments.append(
  795. {
  796. "type": tray_type,
  797. "color": color,
  798. "tray_info_idx": tray_info_idx,
  799. "ams_id": ams_id,
  800. "tray_id": tray_id,
  801. "is_ht": is_ht,
  802. "is_external": False,
  803. "global_tray_id": global_tray_id,
  804. "extruder_id": ams_extruder_map.get(str(ams_id)),
  805. "remain": tray.get("remain", -1),
  806. }
  807. )
  808. # Check external spool(s) (vt_tray is a list)
  809. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  810. if vt.get("tray_type"):
  811. color = self._normalize_color(vt.get("tray_color", ""))
  812. tray_id = int(vt.get("id", 254))
  813. filaments.append(
  814. {
  815. "type": vt["tray_type"],
  816. "color": color,
  817. "tray_info_idx": vt.get("tray_info_idx", ""),
  818. "ams_id": -1,
  819. "tray_id": idx,
  820. "is_ht": False,
  821. "is_external": True,
  822. "global_tray_id": tray_id,
  823. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  824. "remain": vt.get("remain", -1),
  825. }
  826. )
  827. return filaments
  828. def _normalize_color(self, color: str | None) -> str:
  829. """Normalize color to #RRGGBB format."""
  830. if not color:
  831. return "#808080"
  832. hex_color = color.replace("#", "")[:6]
  833. return f"#{hex_color}"
  834. def _normalize_color_for_compare(self, color: str | None) -> str:
  835. """Normalize color for comparison (lowercase, no hash)."""
  836. if not color:
  837. return ""
  838. return color.replace("#", "").lower()[:6]
  839. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  840. """Check if two colors are visually similar within a threshold."""
  841. hex1 = self._normalize_color_for_compare(color1)
  842. hex2 = self._normalize_color_for_compare(color2)
  843. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  844. return False
  845. try:
  846. r1 = int(hex1[0:2], 16)
  847. g1 = int(hex1[2:4], 16)
  848. b1 = int(hex1[4:6], 16)
  849. r2 = int(hex2[0:2], 16)
  850. g2 = int(hex2[2:4], 16)
  851. b2 = int(hex2[4:6], 16)
  852. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  853. except ValueError:
  854. return False
  855. def _match_filaments_to_slots(
  856. self, required: list[dict], loaded: list[dict], prefer_lowest: bool = False
  857. ) -> list[int] | None:
  858. """Match required filaments to loaded filaments and build AMS mapping.
  859. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  860. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  861. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  862. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  863. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  864. matching among those trays.
  865. Args:
  866. required: List of required filaments with slot_id, type, color, tray_info_idx
  867. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  868. Returns:
  869. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  870. """
  871. if not required:
  872. return None
  873. # Track used trays to avoid duplicate assignment
  874. used_tray_ids: set[int] = set()
  875. comparisons = []
  876. for req in required:
  877. req_type = (req.get("type") or "").upper()
  878. req_color = req.get("color", "")
  879. req_tray_info_idx = req.get("tray_info_idx", "")
  880. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  881. idx_match = None
  882. exact_match = None
  883. similar_match = None
  884. type_only_match = None
  885. # Get available trays (not already used)
  886. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  887. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  888. # Hard filter — cross-nozzle assignment causes print failures
  889. # ("position of left hotend is abnormal"), so never fall back.
  890. req_nozzle_id = req.get("nozzle_id")
  891. if req_nozzle_id is not None:
  892. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  893. # Sort by remaining filament (ascending) so lowest-remain spool wins .find()
  894. if prefer_lowest:
  895. available.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  896. # Check if tray_info_idx is unique among available trays
  897. if req_tray_info_idx:
  898. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  899. if len(idx_matches) == 1:
  900. # Unique tray_info_idx - use it as definitive match
  901. idx_match = idx_matches[0]
  902. logger.debug(
  903. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  904. f"-> tray {idx_match['global_tray_id']}"
  905. )
  906. elif len(idx_matches) > 1:
  907. # Multiple trays with same tray_info_idx - use color matching among them
  908. logger.debug(
  909. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  910. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  911. )
  912. if prefer_lowest:
  913. idx_matches.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  914. # Use color matching within this subset
  915. for f in idx_matches:
  916. f_color = f.get("color", "")
  917. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  918. if not exact_match:
  919. exact_match = f
  920. elif self._colors_are_similar(f_color, req_color):
  921. if not similar_match:
  922. similar_match = f
  923. elif not type_only_match:
  924. type_only_match = f
  925. # If no idx_match yet, do standard type/color matching on all available trays
  926. if not idx_match and not exact_match and not similar_match and not type_only_match:
  927. for f in available:
  928. f_type = (f.get("type") or "").upper()
  929. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  930. continue
  931. # Type matches - check color
  932. f_color = f.get("color", "")
  933. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  934. if not exact_match:
  935. exact_match = f
  936. elif self._colors_are_similar(f_color, req_color):
  937. if not similar_match:
  938. similar_match = f
  939. elif not type_only_match:
  940. type_only_match = f
  941. match = idx_match or exact_match or similar_match or type_only_match
  942. if match:
  943. used_tray_ids.add(match["global_tray_id"])
  944. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  945. else:
  946. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  947. # Build mapping array
  948. if not comparisons:
  949. return None
  950. max_slot_id = max(c["slot_id"] for c in comparisons)
  951. if max_slot_id <= 0:
  952. return None
  953. mapping = [-1] * max_slot_id
  954. for c in comparisons:
  955. slot_id = c["slot_id"]
  956. if slot_id and slot_id > 0:
  957. mapping[slot_id - 1] = c["global_tray_id"]
  958. return mapping
  959. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  960. """Check if a printer is connected and idle."""
  961. if not printer_manager.is_connected(printer_id):
  962. logger.debug("Printer %d: not connected", printer_id)
  963. return False
  964. state = printer_manager.get_status(printer_id)
  965. if not state:
  966. logger.debug("Printer %d: no status available", printer_id)
  967. return False
  968. # IDLE = ready for next print
  969. # FINISH/FAILED = ready if plate-clear not required, or user confirmed plate is cleared
  970. idle = state.state == "IDLE" or (
  971. state.state in ("FINISH", "FAILED")
  972. and (not require_plate_clear or printer_manager.is_plate_cleared(printer_id))
  973. )
  974. if not idle:
  975. logger.debug(
  976. "Printer %d: not idle — state=%s, plate_cleared=%s",
  977. printer_id,
  978. state.state,
  979. printer_manager.is_plate_cleared(printer_id),
  980. )
  981. return idle
  982. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  983. """Read a setting value from the database."""
  984. result = await db.execute(select(Settings).where(Settings.key == key))
  985. setting = result.scalar_one_or_none()
  986. return setting.value if setting else None
  987. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  988. """Read a boolean setting from the database."""
  989. result = await db.execute(select(Settings).where(Settings.key == key))
  990. setting = result.scalar_one_or_none()
  991. if setting:
  992. return setting.value.lower() == "true"
  993. return default
  994. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  995. """Get drying presets (user-configured or built-in defaults)."""
  996. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  997. setting = result.scalar_one_or_none()
  998. if setting and setting.value:
  999. try:
  1000. presets = json.loads(setting.value)
  1001. if isinstance(presets, dict) and presets:
  1002. return presets
  1003. except json.JSONDecodeError:
  1004. pass
  1005. return self.DEFAULT_DRYING_PRESETS
  1006. def _get_conservative_drying_params(
  1007. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1008. ) -> tuple[int, int, str] | None:
  1009. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1010. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1011. """
  1012. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1013. hours_key = f"{temp_key}_hours"
  1014. min_temp = None
  1015. max_hours = None
  1016. filament_type = ""
  1017. for tray in trays:
  1018. tray_type = tray.get("tray_type", "")
  1019. if not tray_type:
  1020. continue
  1021. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1022. base_type = tray_type.split()[0].upper()
  1023. preset = presets.get(base_type)
  1024. if not preset:
  1025. continue
  1026. temp = preset.get(temp_key, 55)
  1027. hours = preset.get(hours_key, 12)
  1028. # Conservative: lowest temp, longest duration
  1029. if min_temp is None or temp < min_temp:
  1030. min_temp = temp
  1031. if max_hours is None or hours > max_hours:
  1032. max_hours = hours
  1033. if not filament_type:
  1034. filament_type = base_type
  1035. if min_temp is None:
  1036. return None
  1037. return (min_temp, max_hours or 12, filament_type)
  1038. async def _check_auto_drying(
  1039. self,
  1040. db: AsyncSession,
  1041. queue_items: list[PrintQueueItem],
  1042. busy_printers: set[int],
  1043. *,
  1044. require_plate_clear: bool = True,
  1045. ):
  1046. """Start drying on idle printers based on humidity.
  1047. Two modes (can both be enabled):
  1048. - queue_drying_enabled: Dry between scheduled queue prints
  1049. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1050. """
  1051. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1052. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1053. if not queue_drying_enabled and not ambient_drying_enabled:
  1054. # Stop active drying on all printers if both features disabled
  1055. if self._drying_in_progress:
  1056. for pid in list(self._drying_in_progress):
  1057. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1058. await self._stop_drying(pid)
  1059. return
  1060. # Update drying state from printer status (handles backend restart)
  1061. self._sync_drying_state()
  1062. # Find printers with scheduled items (for queue drying mode)
  1063. printers_with_scheduled: set[int] = set()
  1064. printers_with_items: set[int] = set()
  1065. for item in queue_items:
  1066. if item.printer_id:
  1067. printers_with_items.add(item.printer_id)
  1068. if item.scheduled_time and not item.manual_start:
  1069. printers_with_scheduled.add(item.printer_id)
  1070. # If only queue mode is on and no printers have scheduled items, stop drying
  1071. if not ambient_drying_enabled and not printers_with_scheduled:
  1072. for pid in list(self._drying_in_progress):
  1073. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1074. await self._stop_drying(pid)
  1075. return
  1076. # Get humidity threshold
  1077. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1078. setting = result.scalar_one_or_none()
  1079. humidity_threshold = int(setting.value) if setting else 60
  1080. # Get drying presets
  1081. presets = await self._get_drying_presets(db)
  1082. # Determine if drying should be skipped for printers with pending items
  1083. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1084. # Get all active printers
  1085. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1086. for printer in all_printers.scalars():
  1087. pid = printer.id
  1088. if pid in busy_printers:
  1089. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1090. continue
  1091. # In queue-only mode, only dry printers that have scheduled prints
  1092. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1093. if self._drying_in_progress.get(pid):
  1094. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1095. await self._stop_drying(pid)
  1096. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1097. continue
  1098. # When block mode is on, don't START new drying on printers with pending items.
  1099. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1100. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1101. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1102. continue
  1103. if not printer_manager.is_connected(pid):
  1104. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1105. continue
  1106. if not self._is_printer_idle(pid, require_plate_clear):
  1107. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1108. continue
  1109. # Check if this printer supports drying
  1110. state = printer_manager.get_status(pid)
  1111. if not state:
  1112. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1113. continue
  1114. model = printer_manager.get_model(pid)
  1115. firmware = state.firmware_version
  1116. if not supports_drying(model, firmware):
  1117. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1118. continue
  1119. # Check each AMS unit from raw_data
  1120. ams_list = state.raw_data.get("ams", [])
  1121. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1122. for ams_data in ams_list:
  1123. module_type = str(ams_data.get("module_type") or "")
  1124. ams_id = int(ams_data.get("id", 0))
  1125. # Only n3f/n3s support drying
  1126. if module_type not in ("n3f", "n3s"):
  1127. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1128. continue
  1129. dry_time = int(ams_data.get("dry_time") or 0)
  1130. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1131. humidity = None
  1132. h_raw = ams_data.get("humidity_raw")
  1133. if h_raw is not None:
  1134. try:
  1135. humidity = int(h_raw)
  1136. except (ValueError, TypeError):
  1137. pass
  1138. if humidity is None:
  1139. h_idx = ams_data.get("humidity")
  1140. if h_idx is not None:
  1141. try:
  1142. humidity = int(h_idx)
  1143. except (ValueError, TypeError):
  1144. pass
  1145. # Already drying — check if humidity dropped below threshold (with minimum drying time)
  1146. if dry_time > 0:
  1147. if pid not in self._drying_in_progress:
  1148. # Drying we didn't start (manual or from before restart) — track but don't stop
  1149. self._drying_in_progress[pid] = time.monotonic()
  1150. started_at = self._drying_in_progress[pid]
  1151. elapsed = time.monotonic() - started_at
  1152. if humidity is not None and humidity <= humidity_threshold and elapsed >= self._min_drying_seconds:
  1153. logger.info(
  1154. "Auto-drying: printer %d AMS %d — humidity %d%% <= threshold %d%% after %dm, stopping drying",
  1155. pid,
  1156. ams_id,
  1157. humidity,
  1158. humidity_threshold,
  1159. int(elapsed / 60),
  1160. )
  1161. printer_manager.send_drying_command(pid, ams_id, temp=0, duration=0, mode=0)
  1162. else:
  1163. logger.debug(
  1164. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%, elapsed %dm/%dm min)",
  1165. pid,
  1166. ams_id,
  1167. dry_time,
  1168. humidity,
  1169. int(elapsed / 60),
  1170. self._min_drying_seconds // 60,
  1171. )
  1172. continue
  1173. # Humidity below threshold — no need to start drying
  1174. if humidity is None or humidity <= humidity_threshold:
  1175. logger.debug(
  1176. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1177. pid,
  1178. ams_id,
  1179. humidity,
  1180. humidity_threshold,
  1181. )
  1182. continue
  1183. # Check cannot-dry reasons (power constraints etc.)
  1184. sf_reasons = ams_data.get("dry_sf_reason", [])
  1185. if sf_reasons:
  1186. logger.debug(
  1187. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1188. pid,
  1189. ams_id,
  1190. sf_reasons,
  1191. )
  1192. continue
  1193. # Get conservative drying params for mixed filaments
  1194. trays = ams_data.get("tray", [])
  1195. params = self._get_conservative_drying_params(trays, module_type, presets)
  1196. if not params:
  1197. logger.debug(
  1198. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1199. )
  1200. continue
  1201. temp, duration_hours, filament_type = params
  1202. # Start drying
  1203. logger.info(
  1204. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1205. "starting %s drying at %d°C for %dh",
  1206. pid,
  1207. ams_id,
  1208. humidity,
  1209. humidity_threshold,
  1210. filament_type,
  1211. temp,
  1212. duration_hours,
  1213. )
  1214. success = printer_manager.send_drying_command(
  1215. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1216. )
  1217. if success:
  1218. self._drying_in_progress[pid] = time.monotonic()
  1219. def _sync_drying_state(self):
  1220. """Sync in-memory drying state with actual printer status.
  1221. Handles backend restart — if a printer is drying but we don't know about it,
  1222. update our state. If we think it's drying but it's not, clear it.
  1223. """
  1224. to_remove = []
  1225. for pid in self._drying_in_progress:
  1226. state = printer_manager.get_status(pid)
  1227. if not state:
  1228. to_remove.append(pid)
  1229. continue
  1230. # Check if any AMS unit is still drying
  1231. ams_list = state.raw_data.get("ams", [])
  1232. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1233. if not any_drying:
  1234. to_remove.append(pid)
  1235. for pid in to_remove:
  1236. self._drying_in_progress.pop(pid, None)
  1237. async def _stop_drying(self, printer_id: int):
  1238. """Stop all active drying on a printer (print takes priority)."""
  1239. state = printer_manager.get_status(printer_id)
  1240. if not state:
  1241. self._drying_in_progress.pop(printer_id, None)
  1242. return
  1243. ams_list = state.raw_data.get("ams", [])
  1244. for ams_data in ams_list:
  1245. dry_time = int(ams_data.get("dry_time") or 0)
  1246. if dry_time > 0:
  1247. ams_id = int(ams_data.get("id", 0))
  1248. logger.info(
  1249. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1250. printer_id,
  1251. ams_id,
  1252. )
  1253. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1254. self._drying_in_progress.pop(printer_id, None)
  1255. async def _get_smart_plug(self, db: AsyncSession, printer_id: int) -> SmartPlug | None:
  1256. """Get the smart plug associated with a printer."""
  1257. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1258. return result.scalar_one_or_none()
  1259. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1260. """Turn on smart plug and wait for printer to connect.
  1261. Returns True if printer connected successfully within timeout.
  1262. """
  1263. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1264. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1265. # Check current plug state
  1266. status = await service.get_status(plug)
  1267. if not status.get("reachable"):
  1268. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1269. return False
  1270. # Turn on if not already on
  1271. if status.get("state") != "ON":
  1272. success = await service.turn_on(plug)
  1273. if not success:
  1274. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  1275. return False
  1276. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  1277. # Get printer from database for connection
  1278. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1279. printer = result.scalar_one_or_none()
  1280. if not printer:
  1281. logger.error("Printer %s not found in database", printer_id)
  1282. return False
  1283. # Wait for printer to boot (give it some time before trying to connect)
  1284. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  1285. await asyncio.sleep(30)
  1286. # Try to connect to the printer periodically
  1287. elapsed = 30 # Already waited 30s
  1288. while elapsed < self._power_on_wait_time:
  1289. # Try to connect
  1290. logger.info("Attempting to connect to printer %s...", printer_id)
  1291. try:
  1292. connected = await printer_manager.connect_printer(printer)
  1293. if connected:
  1294. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  1295. # Give it a moment to stabilize and get status
  1296. await asyncio.sleep(5)
  1297. return True
  1298. except Exception as e:
  1299. logger.debug("Connection attempt failed: %s", e)
  1300. await asyncio.sleep(self._power_on_check_interval)
  1301. elapsed += self._power_on_check_interval
  1302. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  1303. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  1304. return False
  1305. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  1306. """Check if the previous print on this printer succeeded."""
  1307. # Find the most recent completed queue item for this printer
  1308. result = await db.execute(
  1309. select(PrintQueueItem)
  1310. .where(PrintQueueItem.printer_id == item.printer_id)
  1311. .where(PrintQueueItem.id != item.id)
  1312. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  1313. .order_by(PrintQueueItem.completed_at.desc())
  1314. .limit(1)
  1315. )
  1316. prev_item = result.scalar_one_or_none()
  1317. # If no previous item, assume success (first in queue)
  1318. if not prev_item:
  1319. return True
  1320. return prev_item.status == "completed"
  1321. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  1322. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  1323. if not item.auto_off_after:
  1324. return
  1325. plug = await self._get_smart_plug(db, item.printer_id)
  1326. if plug and plug.enabled:
  1327. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  1328. # Wait for cooldown (up to 10 minutes)
  1329. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  1330. logger.info("Auto-off: Powering off printer %s", item.printer_id)
  1331. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1332. await service.turn_off(plug)
  1333. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  1334. """Get a human-readable name for a queue item."""
  1335. if item.archive_id:
  1336. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1337. archive = result.scalar_one_or_none()
  1338. if archive:
  1339. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1340. if item.library_file_id:
  1341. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1342. library_file = result.scalar_one_or_none()
  1343. if library_file:
  1344. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1345. return f"Job #{item.id}"
  1346. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  1347. """Get printer by ID."""
  1348. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1349. return result.scalar_one_or_none()
  1350. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  1351. """Upload file and start print for a queue item.
  1352. Supports two sources:
  1353. - archive_id: Print from an existing archive
  1354. - library_file_id: Print from a library file (file manager)
  1355. """
  1356. logger.info("Starting queue item %s", item.id)
  1357. # Get printer first (needed for both paths)
  1358. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  1359. printer = result.scalar_one_or_none()
  1360. if not printer:
  1361. item.status = "failed"
  1362. item.error_message = "Printer not found"
  1363. item.completed_at = datetime.now(timezone.utc)
  1364. await db.commit()
  1365. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  1366. await self._power_off_if_needed(db, item)
  1367. return
  1368. # Check printer is connected
  1369. if not printer_manager.is_connected(item.printer_id):
  1370. item.status = "failed"
  1371. item.error_message = "Printer not connected"
  1372. item.completed_at = datetime.now(timezone.utc)
  1373. await db.commit()
  1374. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  1375. await self._power_off_if_needed(db, item)
  1376. return
  1377. # Determine source: archive or library file
  1378. archive = None
  1379. library_file = None
  1380. file_path = None
  1381. filename = None
  1382. if item.archive_id:
  1383. # Print from archive
  1384. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1385. archive = result.scalar_one_or_none()
  1386. if not archive:
  1387. item.status = "failed"
  1388. item.error_message = "Archive not found"
  1389. item.completed_at = datetime.now(timezone.utc)
  1390. await db.commit()
  1391. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  1392. await self._power_off_if_needed(db, item)
  1393. return
  1394. file_path = settings.base_dir / archive.file_path
  1395. filename = archive.filename
  1396. elif item.library_file_id:
  1397. # Print from library file (file manager)
  1398. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1399. library_file = result.scalar_one_or_none()
  1400. if not library_file:
  1401. item.status = "failed"
  1402. item.error_message = "Library file not found"
  1403. item.completed_at = datetime.now(timezone.utc)
  1404. await db.commit()
  1405. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  1406. await self._power_off_if_needed(db, item)
  1407. return
  1408. # Library files store absolute paths
  1409. lib_path = Path(library_file.file_path)
  1410. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1411. filename = library_file.filename
  1412. # Create archive from library file so usage tracking has access to the 3MF
  1413. try:
  1414. from backend.app.services.archive import ArchiveService
  1415. archive_service = ArchiveService(db)
  1416. archive = await archive_service.archive_print(
  1417. printer_id=item.printer_id,
  1418. source_file=file_path,
  1419. original_filename=filename,
  1420. created_by_id=item.created_by_id,
  1421. )
  1422. if archive:
  1423. item.archive_id = archive.id
  1424. await db.flush()
  1425. logger.info(
  1426. "Queue item %s: Created archive %s from library file %s",
  1427. item.id,
  1428. archive.id,
  1429. item.library_file_id,
  1430. )
  1431. except Exception as e:
  1432. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  1433. else:
  1434. # Neither archive nor library file specified
  1435. item.status = "failed"
  1436. item.error_message = "No source file specified"
  1437. item.completed_at = datetime.now(timezone.utc)
  1438. await db.commit()
  1439. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  1440. await self._power_off_if_needed(db, item)
  1441. return
  1442. # Check file exists on disk
  1443. if not file_path.exists():
  1444. item.status = "failed"
  1445. item.error_message = "Source file not found on disk"
  1446. item.completed_at = datetime.now(timezone.utc)
  1447. await db.commit()
  1448. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  1449. await self._power_off_if_needed(db, item)
  1450. return
  1451. # G-code injection for auto-print systems (#422)
  1452. injected_path = None
  1453. if item.gcode_injection:
  1454. try:
  1455. snippets_raw = await self._get_setting(db, "gcode_snippets")
  1456. if snippets_raw:
  1457. snippets = json.loads(snippets_raw)
  1458. model_snippets = snippets.get(printer.model, {})
  1459. start_gc = (model_snippets.get("start_gcode") or "").strip()
  1460. end_gc = (model_snippets.get("end_gcode") or "").strip()
  1461. if start_gc or end_gc:
  1462. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  1463. injected_path = inject_gcode_into_3mf(
  1464. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  1465. )
  1466. if injected_path:
  1467. file_path = injected_path
  1468. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  1469. else:
  1470. logger.warning(
  1471. "Queue item %s: G-code injection returned no result, using original", item.id
  1472. )
  1473. except Exception as e:
  1474. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  1475. # Upload file to printer via FTP
  1476. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1477. base_name = filename
  1478. if base_name.endswith(".gcode.3mf"):
  1479. base_name = base_name[:-10] # Remove .gcode.3mf
  1480. elif base_name.endswith(".3mf"):
  1481. base_name = base_name[:-4] # Remove .3mf
  1482. remote_filename = f"{base_name}.3mf"
  1483. # Sanitize: firmware parses ftp://{filename} as a URL, spaces break it
  1484. remote_filename = remote_filename.replace(" ", "_")
  1485. # Upload to root directory (not /cache/) - the start_print command references
  1486. # files by name only (ftp://{filename}), so they must be in the root
  1487. remote_path = f"/{remote_filename}"
  1488. # Get FTP retry settings
  1489. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1490. logger.info(
  1491. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  1492. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1493. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1494. )
  1495. # Delete existing file if present (avoids 553 error on overwrite)
  1496. try:
  1497. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  1498. delete_result = await delete_file_async(
  1499. printer.ip_address,
  1500. printer.access_code,
  1501. remote_path,
  1502. socket_timeout=ftp_timeout,
  1503. printer_model=printer.model,
  1504. )
  1505. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  1506. except Exception as e:
  1507. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  1508. try:
  1509. if ftp_retry_enabled:
  1510. uploaded = await with_ftp_retry(
  1511. upload_file_async,
  1512. printer.ip_address,
  1513. printer.access_code,
  1514. file_path,
  1515. remote_path,
  1516. socket_timeout=ftp_timeout,
  1517. printer_model=printer.model,
  1518. max_retries=ftp_retry_count,
  1519. retry_delay=ftp_retry_delay,
  1520. operation_name=f"Upload print to {printer.name}",
  1521. )
  1522. else:
  1523. uploaded = await upload_file_async(
  1524. printer.ip_address,
  1525. printer.access_code,
  1526. file_path,
  1527. remote_path,
  1528. socket_timeout=ftp_timeout,
  1529. printer_model=printer.model,
  1530. )
  1531. except Exception as e:
  1532. uploaded = False
  1533. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  1534. # Clean up injected temp file after upload attempt
  1535. if injected_path and injected_path.exists():
  1536. injected_path.unlink(missing_ok=True)
  1537. if not uploaded:
  1538. error_msg = (
  1539. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1540. "See server logs for detailed diagnostics."
  1541. )
  1542. item.status = "failed"
  1543. item.error_message = error_msg
  1544. item.completed_at = datetime.now(timezone.utc)
  1545. await db.commit()
  1546. logger.error(
  1547. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  1548. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  1549. )
  1550. # Send failure notification
  1551. await notification_service.on_queue_job_failed(
  1552. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1553. printer_id=printer.id,
  1554. printer_name=printer.name,
  1555. reason="Failed to upload file to printer",
  1556. db=db,
  1557. )
  1558. await self._power_off_if_needed(db, item)
  1559. return
  1560. # Parse AMS mapping if stored
  1561. ams_mapping = None
  1562. if item.ams_mapping:
  1563. try:
  1564. ams_mapping = json.loads(item.ams_mapping)
  1565. except json.JSONDecodeError:
  1566. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  1567. # Register as expected print so we don't create a duplicate archive
  1568. # Only applicable for archive-based prints
  1569. if archive:
  1570. from backend.app.main import register_expected_print
  1571. register_expected_print(
  1572. item.printer_id,
  1573. remote_filename,
  1574. archive.id,
  1575. ams_mapping=ams_mapping,
  1576. created_by_id=item.created_by_id,
  1577. )
  1578. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  1579. # This prevents phantom reprints if the backend crashes/restarts after the
  1580. # print command is sent but before the status update is committed.
  1581. # If we crash after this commit but before start_print(), the item will be
  1582. # in "printing" status without actually printing - but that's safer than
  1583. # accidentally reprinting the same file hours later.
  1584. item.status = "printing"
  1585. item.started_at = datetime.now(timezone.utc)
  1586. await db.commit()
  1587. # Consume the plate-cleared flag now that we're starting a print
  1588. printer_manager.consume_plate_cleared(item.printer_id)
  1589. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  1590. # Start the print with AMS mapping, plate_id and print options
  1591. started = printer_manager.start_print(
  1592. item.printer_id,
  1593. remote_filename,
  1594. plate_id=item.plate_id or 1,
  1595. ams_mapping=ams_mapping,
  1596. bed_levelling=item.bed_levelling,
  1597. flow_cali=item.flow_cali,
  1598. vibration_cali=item.vibration_cali,
  1599. layer_inspect=item.layer_inspect,
  1600. timelapse=item.timelapse,
  1601. use_ams=item.use_ams,
  1602. )
  1603. if started:
  1604. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  1605. # Get estimated time for notification
  1606. estimated_time = None
  1607. if archive and archive.print_time_seconds:
  1608. estimated_time = archive.print_time_seconds
  1609. elif library_file and library_file.print_time_seconds:
  1610. estimated_time = library_file.print_time_seconds
  1611. # Send job started notification
  1612. await notification_service.on_queue_job_started(
  1613. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1614. printer_id=printer.id,
  1615. printer_name=printer.name,
  1616. db=db,
  1617. estimated_time=estimated_time,
  1618. )
  1619. # MQTT relay - publish queue job started
  1620. try:
  1621. from backend.app.services.mqtt_relay import mqtt_relay
  1622. await mqtt_relay.on_queue_job_started(
  1623. job_id=item.id,
  1624. filename=filename,
  1625. printer_id=printer.id,
  1626. printer_name=printer.name,
  1627. printer_serial=printer.serial_number,
  1628. )
  1629. except Exception:
  1630. pass # Don't fail if MQTT fails
  1631. else:
  1632. # Clean up uploaded file from SD card to prevent phantom prints
  1633. try:
  1634. await delete_file_async(
  1635. printer.ip_address,
  1636. printer.access_code,
  1637. remote_path,
  1638. printer_model=printer.model,
  1639. )
  1640. except Exception:
  1641. pass # Best-effort — don't fail the error handler
  1642. # Print command failed - revert status
  1643. item.status = "failed"
  1644. item.error_message = "Failed to send print command to printer"
  1645. item.completed_at = datetime.now(timezone.utc)
  1646. await db.commit()
  1647. logger.error(
  1648. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  1649. f"printer_manager.start_print() returned False. "
  1650. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  1651. f"Check printer status and backend logs for details."
  1652. )
  1653. # Send failure notification
  1654. await notification_service.on_queue_job_failed(
  1655. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1656. printer_id=printer.id,
  1657. printer_name=printer.name,
  1658. reason="Failed to send print command to printer - check printer connection and status",
  1659. db=db,
  1660. )
  1661. await self._power_off_if_needed(db, item)
  1662. # Global scheduler instance
  1663. scheduler = PrintScheduler()