print_scheduler.py 84 KB

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