print_scheduler.py 102 KB

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