print_scheduler.py 99 KB

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