print_scheduler.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181
  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. # When the 3MF can't be read but force-color overrides are present, build a
  704. # direct mapping from the overrides so the printer uses the correct AMS slot.
  705. if item.filament_overrides:
  706. try:
  707. overrides = json.loads(item.filament_overrides)
  708. force_overrides = [o for o in overrides if o.get("force_color_match")]
  709. if force_overrides:
  710. logger.info(
  711. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  712. "force-color override(s)",
  713. item.id,
  714. len(force_overrides),
  715. )
  716. return self._build_override_direct_mapping(force_overrides, status)
  717. except (json.JSONDecodeError, KeyError, TypeError) as e:
  718. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  719. logger.debug("No filament requirements found for queue item %s", item.id)
  720. return None
  721. # Apply filament overrides if present
  722. if item.filament_overrides:
  723. try:
  724. overrides = json.loads(item.filament_overrides)
  725. override_map = {o["slot_id"]: o for o in overrides}
  726. for req in filament_reqs:
  727. if req["slot_id"] in override_map:
  728. override = override_map[req["slot_id"]]
  729. req["type"] = override["type"]
  730. req["color"] = override["color"]
  731. # Clear tray_info_idx so matching uses type+color instead of
  732. # the original 3MF's tray_info_idx (which would match the old filament)
  733. req["tray_info_idx"] = ""
  734. logger.debug(
  735. "Queue item %s: Override slot %d -> %s %s",
  736. item.id,
  737. req["slot_id"],
  738. override["type"],
  739. override["color"],
  740. )
  741. except (json.JSONDecodeError, KeyError, TypeError) as e:
  742. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  743. # Build loaded filaments from printer status
  744. loaded_filaments = self._build_loaded_filaments(status)
  745. if not loaded_filaments:
  746. logger.debug("No filaments loaded on printer %s", printer_id)
  747. return None
  748. # Check if user prefers lowest remaining filament when multiple spools match
  749. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  750. # Compute mapping: match required filaments to available slots
  751. return self._match_filaments_to_slots(filament_reqs, loaded_filaments, prefer_lowest)
  752. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  753. """Build an AMS mapping directly from force-color overrides without a 3MF.
  754. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  755. slice_info is missing or unreadable) but ``force_color_match`` overrides
  756. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  757. treated as the filament requirement for that slot and matched against the
  758. current AMS state of the printer.
  759. Returns the same format as ``_match_filaments_to_slots``, or None when
  760. the AMS has no loaded filaments.
  761. """
  762. loaded = self._build_loaded_filaments(status)
  763. if not loaded:
  764. return None
  765. reqs = [
  766. {
  767. "slot_id": o["slot_id"],
  768. "type": o.get("type", ""),
  769. "color": o.get("color", ""),
  770. "tray_info_idx": "",
  771. }
  772. for o in force_overrides
  773. ]
  774. return self._match_filaments_to_slots(reqs, loaded)
  775. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  776. """Resolve the queue item's source 3MF and parse the per-slot
  777. filament requirements out of it. Thin DB-resolver wrapper around
  778. ``filament_requirements.extract_filament_requirements`` so the VP
  779. queue-mode write path (#1188) can reuse the same parser at upload
  780. time.
  781. """
  782. from backend.app.services.filament_requirements import extract_filament_requirements
  783. file_path: Path | None = None
  784. if item.archive_id:
  785. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  786. archive = result.scalar_one_or_none()
  787. if archive:
  788. file_path = settings.base_dir / archive.file_path
  789. elif item.library_file_id:
  790. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  791. library_file = result.scalar_one_or_none()
  792. if library_file:
  793. lib_path = Path(library_file.file_path)
  794. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  795. if not file_path or not file_path.exists():
  796. return None
  797. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  798. return filaments if filaments else None
  799. def _build_loaded_filaments(self, status) -> list[dict]:
  800. """Build list of loaded filaments from printer status.
  801. Args:
  802. status: PrinterState from printer_manager
  803. Returns:
  804. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  805. """
  806. filaments = []
  807. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  808. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  809. # Parse AMS units from raw_data
  810. ams_data = status.raw_data.get("ams", [])
  811. for ams_unit in ams_data:
  812. ams_id = int(ams_unit.get("id", 0))
  813. trays = ams_unit.get("tray", [])
  814. is_ht = len(trays) == 1 # AMS-HT has single tray
  815. for tray in trays:
  816. tray_type = tray.get("tray_type")
  817. if tray_type:
  818. tray_id = int(tray.get("id", 0))
  819. tray_color = tray.get("tray_color", "")
  820. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  821. tray_info_idx = tray.get("tray_info_idx", "")
  822. # Normalize color: remove alpha, add hash
  823. color = self._normalize_color(tray_color)
  824. # Calculate global tray ID
  825. # AMS-HT units have IDs starting at 128 with a single tray
  826. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  827. filaments.append(
  828. {
  829. "type": tray_type,
  830. "color": color,
  831. "tray_info_idx": tray_info_idx,
  832. "ams_id": ams_id,
  833. "tray_id": tray_id,
  834. "is_ht": is_ht,
  835. "is_external": False,
  836. "global_tray_id": global_tray_id,
  837. "extruder_id": ams_extruder_map.get(str(ams_id)),
  838. "remain": tray.get("remain", -1),
  839. }
  840. )
  841. # Check external spool(s) (vt_tray is a list)
  842. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  843. if vt.get("tray_type"):
  844. color = self._normalize_color(vt.get("tray_color", ""))
  845. tray_id = int(vt.get("id", 254))
  846. filaments.append(
  847. {
  848. "type": vt["tray_type"],
  849. "color": color,
  850. "tray_info_idx": vt.get("tray_info_idx", ""),
  851. "ams_id": -1,
  852. "tray_id": idx,
  853. "is_ht": False,
  854. "is_external": True,
  855. "global_tray_id": tray_id,
  856. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  857. "remain": vt.get("remain", -1),
  858. }
  859. )
  860. return filaments
  861. def _normalize_color(self, color: str | None) -> str:
  862. """Normalize color to #RRGGBB format."""
  863. if not color:
  864. return "#808080"
  865. hex_color = color.replace("#", "")[:6]
  866. return f"#{hex_color}"
  867. def _normalize_color_for_compare(self, color: str | None) -> str:
  868. """Normalize color for comparison (lowercase, no hash)."""
  869. if not color:
  870. return ""
  871. return color.replace("#", "").lower()[:6]
  872. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  873. """Check if two colors are visually similar within a threshold."""
  874. hex1 = self._normalize_color_for_compare(color1)
  875. hex2 = self._normalize_color_for_compare(color2)
  876. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  877. return False
  878. try:
  879. r1 = int(hex1[0:2], 16)
  880. g1 = int(hex1[2:4], 16)
  881. b1 = int(hex1[4:6], 16)
  882. r2 = int(hex2[0:2], 16)
  883. g2 = int(hex2[2:4], 16)
  884. b2 = int(hex2[4:6], 16)
  885. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  886. except ValueError:
  887. return False
  888. def _match_filaments_to_slots(
  889. self, required: list[dict], loaded: list[dict], prefer_lowest: bool = False
  890. ) -> list[int] | None:
  891. """Match required filaments to loaded filaments and build AMS mapping.
  892. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  893. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  894. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  895. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  896. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  897. matching among those trays.
  898. Args:
  899. required: List of required filaments with slot_id, type, color, tray_info_idx
  900. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  901. Returns:
  902. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  903. """
  904. if not required:
  905. return None
  906. # Track used trays to avoid duplicate assignment
  907. used_tray_ids: set[int] = set()
  908. comparisons = []
  909. for req in required:
  910. req_type = (req.get("type") or "").upper()
  911. req_color = req.get("color", "")
  912. req_tray_info_idx = req.get("tray_info_idx", "")
  913. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  914. idx_match = None
  915. exact_match = None
  916. similar_match = None
  917. type_only_match = None
  918. # Get available trays (not already used)
  919. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  920. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  921. # Hard filter — cross-nozzle assignment causes print failures
  922. # ("position of left hotend is abnormal"), so never fall back.
  923. req_nozzle_id = req.get("nozzle_id")
  924. if req_nozzle_id is not None:
  925. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  926. # Sort by remaining filament (ascending) so lowest-remain spool wins .find()
  927. if prefer_lowest:
  928. available.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  929. # Check if tray_info_idx is unique among available trays
  930. if req_tray_info_idx:
  931. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  932. if len(idx_matches) == 1:
  933. # Unique tray_info_idx - use it as definitive match
  934. idx_match = idx_matches[0]
  935. logger.debug(
  936. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  937. f"-> tray {idx_match['global_tray_id']}"
  938. )
  939. elif len(idx_matches) > 1:
  940. # Multiple trays with same tray_info_idx - use color matching among them
  941. logger.debug(
  942. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  943. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  944. )
  945. if prefer_lowest:
  946. idx_matches.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  947. # Use color matching within this subset
  948. for f in idx_matches:
  949. f_color = f.get("color", "")
  950. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  951. if not exact_match:
  952. exact_match = f
  953. elif self._colors_are_similar(f_color, req_color):
  954. if not similar_match:
  955. similar_match = f
  956. elif not type_only_match:
  957. type_only_match = f
  958. # If no idx_match yet, do standard type/color matching on all available trays
  959. if not idx_match and not exact_match and not similar_match and not type_only_match:
  960. for f in available:
  961. f_type = (f.get("type") or "").upper()
  962. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  963. continue
  964. # Type matches - check color
  965. f_color = f.get("color", "")
  966. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  967. if not exact_match:
  968. exact_match = f
  969. elif self._colors_are_similar(f_color, req_color):
  970. if not similar_match:
  971. similar_match = f
  972. elif not type_only_match:
  973. type_only_match = f
  974. match = idx_match or exact_match or similar_match or type_only_match
  975. if match:
  976. used_tray_ids.add(match["global_tray_id"])
  977. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  978. else:
  979. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  980. # Build mapping array
  981. if not comparisons:
  982. return None
  983. max_slot_id = max(c["slot_id"] for c in comparisons)
  984. if max_slot_id <= 0:
  985. return None
  986. mapping = [-1] * max_slot_id
  987. for c in comparisons:
  988. slot_id = c["slot_id"]
  989. if slot_id and slot_id > 0:
  990. mapping[slot_id - 1] = c["global_tray_id"]
  991. return mapping
  992. def _mark_printer_dispatched(
  993. self,
  994. printer_id: int,
  995. pre_state: str | None,
  996. pre_subtask_id: str | None,
  997. ) -> None:
  998. """Record that a print command was just sent to ``printer_id``.
  999. Held until either the watchdog observes a state/subtask transition
  1000. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1001. """
  1002. if not pre_state:
  1003. # No pre_state means we can't detect a transition — fall back to a
  1004. # pure time-based hold using empty string as a sentinel that won't
  1005. # match any real printer state.
  1006. pre_state = ""
  1007. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1008. def _release_dispatch_hold(self, printer_id: int) -> None:
  1009. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1010. self._dispatch_holds.pop(printer_id, None)
  1011. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1012. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1013. Returns False (and clears the hold) once any of these are true:
  1014. - hard timeout (``_dispatch_max_hold``) has elapsed
  1015. - the printer has transitioned out of pre_state and we're past the
  1016. minimum cooldown
  1017. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1018. past the minimum cooldown
  1019. Otherwise the printer is held — caller should treat it as busy.
  1020. """
  1021. entry = self._dispatch_holds.get(printer_id)
  1022. if not entry:
  1023. return False
  1024. started_at, pre_state, pre_subtask_id = entry
  1025. elapsed = time.monotonic() - started_at
  1026. if elapsed >= self._dispatch_max_hold:
  1027. self._dispatch_holds.pop(printer_id, None)
  1028. return False
  1029. # Without a pre_state we can't detect a transition — fall back to the
  1030. # min cooldown alone, then drop the hold.
  1031. if not pre_state:
  1032. if elapsed >= self._dispatch_min_cooldown:
  1033. self._dispatch_holds.pop(printer_id, None)
  1034. return False
  1035. return True
  1036. status = printer_manager.get_status(printer_id)
  1037. current_state = getattr(status, "state", None) if status else None
  1038. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1039. transitioned = (current_state is not None and current_state != pre_state) or (
  1040. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1041. )
  1042. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1043. self._dispatch_holds.pop(printer_id, None)
  1044. return False
  1045. return True
  1046. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1047. """Check if a printer is connected and idle."""
  1048. if not printer_manager.is_connected(printer_id):
  1049. logger.debug("Printer %d: not connected", printer_id)
  1050. return False
  1051. state = printer_manager.get_status(printer_id)
  1052. if not state:
  1053. logger.debug("Printer %d: no status available", printer_id)
  1054. return False
  1055. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1056. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1057. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1058. # printer, it boots back into IDLE with no memory of the previous finish; without
  1059. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1060. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1061. logger.debug(
  1062. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1063. printer_id,
  1064. state.state,
  1065. )
  1066. return False
  1067. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1068. if not idle:
  1069. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1070. return idle
  1071. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1072. """Read a setting value from the database."""
  1073. result = await db.execute(select(Settings).where(Settings.key == key))
  1074. setting = result.scalar_one_or_none()
  1075. return setting.value if setting else None
  1076. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1077. """Read a boolean setting from the database."""
  1078. result = await db.execute(select(Settings).where(Settings.key == key))
  1079. setting = result.scalar_one_or_none()
  1080. if setting:
  1081. return setting.value.lower() == "true"
  1082. return default
  1083. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1084. """Get drying presets (user-configured or built-in defaults)."""
  1085. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1086. setting = result.scalar_one_or_none()
  1087. if setting and setting.value:
  1088. try:
  1089. presets = json.loads(setting.value)
  1090. if isinstance(presets, dict) and presets:
  1091. return presets
  1092. except json.JSONDecodeError:
  1093. pass
  1094. return self.DEFAULT_DRYING_PRESETS
  1095. def _get_conservative_drying_params(
  1096. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1097. ) -> tuple[int, int, str] | None:
  1098. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1099. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1100. """
  1101. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1102. hours_key = f"{temp_key}_hours"
  1103. min_temp = None
  1104. max_hours = None
  1105. filament_type = ""
  1106. for tray in trays:
  1107. tray_type = tray.get("tray_type", "")
  1108. if not tray_type:
  1109. continue
  1110. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1111. base_type = tray_type.split()[0].upper()
  1112. preset = presets.get(base_type)
  1113. if not preset:
  1114. continue
  1115. temp = preset.get(temp_key, 55)
  1116. hours = preset.get(hours_key, 12)
  1117. # Conservative: lowest temp, longest duration
  1118. if min_temp is None or temp < min_temp:
  1119. min_temp = temp
  1120. if max_hours is None or hours > max_hours:
  1121. max_hours = hours
  1122. if not filament_type:
  1123. filament_type = base_type
  1124. if min_temp is None:
  1125. return None
  1126. return (min_temp, max_hours or 12, filament_type)
  1127. async def _check_auto_drying(
  1128. self,
  1129. db: AsyncSession,
  1130. queue_items: list[PrintQueueItem],
  1131. busy_printers: set[int],
  1132. *,
  1133. require_plate_clear: bool = True,
  1134. ):
  1135. """Start drying on idle printers based on humidity.
  1136. Two modes (can both be enabled):
  1137. - queue_drying_enabled: Dry between scheduled queue prints
  1138. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1139. """
  1140. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1141. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1142. if not queue_drying_enabled and not ambient_drying_enabled:
  1143. # Stop active drying on all printers if both features disabled
  1144. if self._drying_in_progress:
  1145. for pid in list(self._drying_in_progress):
  1146. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1147. await self._stop_drying(pid)
  1148. return
  1149. # Update drying state from printer status (handles backend restart)
  1150. self._sync_drying_state()
  1151. # Find printers with scheduled items (for queue drying mode)
  1152. printers_with_scheduled: set[int] = set()
  1153. printers_with_items: set[int] = set()
  1154. for item in queue_items:
  1155. if item.printer_id:
  1156. printers_with_items.add(item.printer_id)
  1157. if item.scheduled_time and not item.manual_start:
  1158. printers_with_scheduled.add(item.printer_id)
  1159. # If only queue mode is on and no printers have scheduled items, stop drying
  1160. if not ambient_drying_enabled and not printers_with_scheduled:
  1161. for pid in list(self._drying_in_progress):
  1162. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1163. await self._stop_drying(pid)
  1164. return
  1165. # Get humidity threshold
  1166. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1167. setting = result.scalar_one_or_none()
  1168. humidity_threshold = int(setting.value) if setting else 60
  1169. # Get drying presets
  1170. presets = await self._get_drying_presets(db)
  1171. # Determine if drying should be skipped for printers with pending items
  1172. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1173. # Get all active printers
  1174. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1175. for printer in all_printers.scalars():
  1176. pid = printer.id
  1177. if pid in busy_printers:
  1178. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1179. continue
  1180. # In queue-only mode, only dry printers that have scheduled prints
  1181. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1182. if self._drying_in_progress.get(pid):
  1183. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1184. await self._stop_drying(pid)
  1185. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1186. continue
  1187. # When block mode is on, don't START new drying on printers with pending items.
  1188. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1189. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1190. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1191. continue
  1192. if not printer_manager.is_connected(pid):
  1193. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1194. continue
  1195. if not self._is_printer_idle(pid, require_plate_clear):
  1196. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1197. continue
  1198. # Check if this printer supports drying
  1199. state = printer_manager.get_status(pid)
  1200. if not state:
  1201. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1202. continue
  1203. model = printer_manager.get_model(pid)
  1204. firmware = state.firmware_version
  1205. if not supports_drying(model, firmware):
  1206. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1207. continue
  1208. # Check each AMS unit from raw_data
  1209. ams_list = state.raw_data.get("ams", [])
  1210. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1211. for ams_data in ams_list:
  1212. module_type = str(ams_data.get("module_type") or "")
  1213. ams_id = int(ams_data.get("id", 0))
  1214. # Only n3f/n3s support drying
  1215. if module_type not in ("n3f", "n3s"):
  1216. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1217. continue
  1218. dry_time = int(ams_data.get("dry_time") or 0)
  1219. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1220. humidity = None
  1221. h_raw = ams_data.get("humidity_raw")
  1222. if h_raw is not None:
  1223. try:
  1224. humidity = int(h_raw)
  1225. except (ValueError, TypeError):
  1226. pass
  1227. if humidity is None:
  1228. h_idx = ams_data.get("humidity")
  1229. if h_idx is not None:
  1230. try:
  1231. humidity = int(h_idx)
  1232. except (ValueError, TypeError):
  1233. pass
  1234. # Already drying — check if humidity dropped below threshold (with minimum drying time)
  1235. if dry_time > 0:
  1236. if pid not in self._drying_in_progress:
  1237. # Drying we didn't start (manual or from before restart) — track but don't stop
  1238. self._drying_in_progress[pid] = time.monotonic()
  1239. started_at = self._drying_in_progress[pid]
  1240. elapsed = time.monotonic() - started_at
  1241. if humidity is not None and humidity <= humidity_threshold and elapsed >= self._min_drying_seconds:
  1242. logger.info(
  1243. "Auto-drying: printer %d AMS %d — humidity %d%% <= threshold %d%% after %dm, stopping drying",
  1244. pid,
  1245. ams_id,
  1246. humidity,
  1247. humidity_threshold,
  1248. int(elapsed / 60),
  1249. )
  1250. printer_manager.send_drying_command(pid, ams_id, temp=0, duration=0, mode=0)
  1251. else:
  1252. logger.debug(
  1253. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%, elapsed %dm/%dm min)",
  1254. pid,
  1255. ams_id,
  1256. dry_time,
  1257. humidity,
  1258. int(elapsed / 60),
  1259. self._min_drying_seconds // 60,
  1260. )
  1261. continue
  1262. # Humidity below threshold — no need to start drying
  1263. if humidity is None or humidity <= humidity_threshold:
  1264. logger.debug(
  1265. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1266. pid,
  1267. ams_id,
  1268. humidity,
  1269. humidity_threshold,
  1270. )
  1271. continue
  1272. # Check cannot-dry reasons (power constraints etc.)
  1273. sf_reasons = ams_data.get("dry_sf_reason", [])
  1274. if sf_reasons:
  1275. logger.debug(
  1276. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1277. pid,
  1278. ams_id,
  1279. sf_reasons,
  1280. )
  1281. continue
  1282. # Get conservative drying params for mixed filaments
  1283. trays = ams_data.get("tray", [])
  1284. params = self._get_conservative_drying_params(trays, module_type, presets)
  1285. if not params:
  1286. logger.debug(
  1287. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1288. )
  1289. continue
  1290. temp, duration_hours, filament_type = params
  1291. # Start drying
  1292. logger.info(
  1293. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1294. "starting %s drying at %d°C for %dh",
  1295. pid,
  1296. ams_id,
  1297. humidity,
  1298. humidity_threshold,
  1299. filament_type,
  1300. temp,
  1301. duration_hours,
  1302. )
  1303. success = printer_manager.send_drying_command(
  1304. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1305. )
  1306. if success:
  1307. self._drying_in_progress[pid] = time.monotonic()
  1308. def _sync_drying_state(self):
  1309. """Sync in-memory drying state with actual printer status.
  1310. Handles backend restart — if a printer is drying but we don't know about it,
  1311. update our state. If we think it's drying but it's not, clear it.
  1312. """
  1313. to_remove = []
  1314. for pid in self._drying_in_progress:
  1315. state = printer_manager.get_status(pid)
  1316. if not state:
  1317. to_remove.append(pid)
  1318. continue
  1319. # Check if any AMS unit is still drying
  1320. ams_list = state.raw_data.get("ams", [])
  1321. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1322. if not any_drying:
  1323. to_remove.append(pid)
  1324. for pid in to_remove:
  1325. self._drying_in_progress.pop(pid, None)
  1326. async def _stop_drying(self, printer_id: int):
  1327. """Stop all active drying on a printer (print takes priority)."""
  1328. state = printer_manager.get_status(printer_id)
  1329. if not state:
  1330. self._drying_in_progress.pop(printer_id, None)
  1331. return
  1332. ams_list = state.raw_data.get("ams", [])
  1333. for ams_data in ams_list:
  1334. dry_time = int(ams_data.get("dry_time") or 0)
  1335. if dry_time > 0:
  1336. ams_id = int(ams_data.get("id", 0))
  1337. logger.info(
  1338. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1339. printer_id,
  1340. ams_id,
  1341. )
  1342. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1343. self._drying_in_progress.pop(printer_id, None)
  1344. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  1345. """Get all smart plugs associated with a printer."""
  1346. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1347. return list(result.scalars().all())
  1348. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1349. """Turn on smart plug and wait for printer to connect.
  1350. Returns True if printer connected successfully within timeout.
  1351. """
  1352. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1353. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1354. # Check current plug state
  1355. status = await service.get_status(plug)
  1356. if not status.get("reachable"):
  1357. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1358. return False
  1359. # Turn on if not already on
  1360. if status.get("state") != "ON":
  1361. success = await service.turn_on(plug)
  1362. if not success:
  1363. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  1364. return False
  1365. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  1366. # Get printer from database for connection
  1367. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1368. printer = result.scalar_one_or_none()
  1369. if not printer:
  1370. logger.error("Printer %s not found in database", printer_id)
  1371. return False
  1372. # Wait for printer to boot (give it some time before trying to connect)
  1373. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  1374. await asyncio.sleep(30)
  1375. # Try to connect to the printer periodically
  1376. elapsed = 30 # Already waited 30s
  1377. while elapsed < self._power_on_wait_time:
  1378. # Try to connect
  1379. logger.info("Attempting to connect to printer %s...", printer_id)
  1380. try:
  1381. connected = await printer_manager.connect_printer(printer)
  1382. if connected:
  1383. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  1384. # Give it a moment to stabilize and get status
  1385. await asyncio.sleep(5)
  1386. return True
  1387. except Exception as e:
  1388. logger.debug("Connection attempt failed: %s", e)
  1389. await asyncio.sleep(self._power_on_check_interval)
  1390. elapsed += self._power_on_check_interval
  1391. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  1392. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  1393. return False
  1394. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  1395. """Check if the previous print on this printer succeeded."""
  1396. # Find the most recent completed queue item for this printer
  1397. result = await db.execute(
  1398. select(PrintQueueItem)
  1399. .where(PrintQueueItem.printer_id == item.printer_id)
  1400. .where(PrintQueueItem.id != item.id)
  1401. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  1402. .order_by(PrintQueueItem.completed_at.desc())
  1403. .limit(1)
  1404. )
  1405. prev_item = result.scalar_one_or_none()
  1406. # If no previous item, assume success (first in queue)
  1407. if not prev_item:
  1408. return True
  1409. return prev_item.status == "completed"
  1410. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  1411. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  1412. if not item.auto_off_after:
  1413. return
  1414. plugs = await self._get_smart_plugs(db, item.printer_id)
  1415. plug_ids = [p.id for p in plugs if p.enabled]
  1416. if plug_ids:
  1417. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  1418. # Wait for cooldown (up to 10 minutes)
  1419. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  1420. # Re-fetch plugs in a fresh session after the long cooldown wait
  1421. async with async_session() as new_db:
  1422. for plug_id in plug_ids:
  1423. try:
  1424. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1425. plug = result.scalar_one_or_none()
  1426. if plug and plug.enabled:
  1427. logger.info("Auto-off: Powering off plug '%s' for printer %s", plug.name, item.printer_id)
  1428. service = await smart_plug_manager.get_service_for_plug(plug, new_db)
  1429. await service.turn_off(plug)
  1430. except Exception as e:
  1431. logger.warning(
  1432. "Auto-off: Failed to power off plug %s for printer %s: %s", plug_id, item.printer_id, e
  1433. )
  1434. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  1435. """Get a human-readable name for a queue item."""
  1436. if item.archive_id:
  1437. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1438. archive = result.scalar_one_or_none()
  1439. if archive:
  1440. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1441. if item.library_file_id:
  1442. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1443. library_file = result.scalar_one_or_none()
  1444. if library_file:
  1445. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1446. return f"Job #{item.id}"
  1447. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  1448. """Get printer by ID."""
  1449. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1450. return result.scalar_one_or_none()
  1451. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  1452. """Upload file and start print for a queue item.
  1453. Supports two sources:
  1454. - archive_id: Print from an existing archive
  1455. - library_file_id: Print from a library file (file manager)
  1456. """
  1457. logger.info("Starting queue item %s", item.id)
  1458. # Get printer first (needed for both paths)
  1459. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  1460. printer = result.scalar_one_or_none()
  1461. if not printer:
  1462. item.status = "failed"
  1463. item.error_message = "Printer not found"
  1464. item.completed_at = datetime.now(timezone.utc)
  1465. await db.commit()
  1466. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  1467. await self._power_off_if_needed(db, item)
  1468. return
  1469. # Check printer is connected
  1470. if not printer_manager.is_connected(item.printer_id):
  1471. item.status = "failed"
  1472. item.error_message = "Printer not connected"
  1473. item.completed_at = datetime.now(timezone.utc)
  1474. await db.commit()
  1475. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  1476. await self._power_off_if_needed(db, item)
  1477. return
  1478. # Determine source: archive or library file
  1479. archive = None
  1480. library_file = None
  1481. file_path = None
  1482. filename = None
  1483. if item.archive_id:
  1484. # Print from archive
  1485. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1486. archive = result.scalar_one_or_none()
  1487. if not archive:
  1488. item.status = "failed"
  1489. item.error_message = "Archive not found"
  1490. item.completed_at = datetime.now(timezone.utc)
  1491. await db.commit()
  1492. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  1493. await self._power_off_if_needed(db, item)
  1494. return
  1495. file_path = settings.base_dir / archive.file_path
  1496. filename = archive.filename
  1497. elif item.library_file_id:
  1498. # Print from library file (file manager)
  1499. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1500. library_file = result.scalar_one_or_none()
  1501. if not library_file:
  1502. item.status = "failed"
  1503. item.error_message = "Library file not found"
  1504. item.completed_at = datetime.now(timezone.utc)
  1505. await db.commit()
  1506. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  1507. await self._power_off_if_needed(db, item)
  1508. return
  1509. # Library files store absolute paths
  1510. lib_path = Path(library_file.file_path)
  1511. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1512. filename = library_file.filename
  1513. # Create archive from library file so usage tracking has access to the 3MF
  1514. try:
  1515. from backend.app.services.archive import ArchiveService
  1516. archive_service = ArchiveService(db)
  1517. archive = await archive_service.archive_print(
  1518. printer_id=item.printer_id,
  1519. source_file=file_path,
  1520. original_filename=filename,
  1521. created_by_id=item.created_by_id,
  1522. project_id=item.project_id,
  1523. )
  1524. if archive:
  1525. item.archive_id = archive.id
  1526. await db.flush()
  1527. logger.info(
  1528. "Queue item %s: Created archive %s from library file %s",
  1529. item.id,
  1530. archive.id,
  1531. item.library_file_id,
  1532. )
  1533. except Exception as e:
  1534. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  1535. else:
  1536. # Neither archive nor library file specified
  1537. item.status = "failed"
  1538. item.error_message = "No source file specified"
  1539. item.completed_at = datetime.now(timezone.utc)
  1540. await db.commit()
  1541. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  1542. await self._power_off_if_needed(db, item)
  1543. return
  1544. # Check file exists on disk
  1545. if not file_path.exists():
  1546. item.status = "failed"
  1547. item.error_message = "Source file not found on disk"
  1548. item.completed_at = datetime.now(timezone.utc)
  1549. await db.commit()
  1550. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  1551. await self._power_off_if_needed(db, item)
  1552. return
  1553. # G-code injection for auto-print systems (#422)
  1554. injected_path = None
  1555. if item.gcode_injection:
  1556. try:
  1557. snippets_raw = await self._get_setting(db, "gcode_snippets")
  1558. if snippets_raw:
  1559. snippets = json.loads(snippets_raw)
  1560. model_snippets = snippets.get(printer.model, {})
  1561. start_gc = (model_snippets.get("start_gcode") or "").strip()
  1562. end_gc = (model_snippets.get("end_gcode") or "").strip()
  1563. if start_gc or end_gc:
  1564. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  1565. injected_path = inject_gcode_into_3mf(
  1566. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  1567. )
  1568. if injected_path:
  1569. file_path = injected_path
  1570. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  1571. else:
  1572. logger.warning(
  1573. "Queue item %s: G-code injection returned no result, using original", item.id
  1574. )
  1575. except Exception as e:
  1576. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  1577. # Upload file to printer via FTP
  1578. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1579. base_name = filename
  1580. if base_name.endswith(".gcode.3mf"):
  1581. base_name = base_name[:-10] # Remove .gcode.3mf
  1582. elif base_name.endswith(".3mf"):
  1583. base_name = base_name[:-4] # Remove .3mf
  1584. remote_filename = f"{base_name}.3mf"
  1585. # Sanitize: firmware parses ftp://{filename} as a URL, spaces break it
  1586. remote_filename = remote_filename.replace(" ", "_")
  1587. # Upload to root directory (not /cache/) - the start_print command references
  1588. # files by name only (ftp://{filename}), so they must be in the root
  1589. remote_path = f"/{remote_filename}"
  1590. # Get FTP retry settings
  1591. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1592. logger.info(
  1593. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  1594. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1595. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1596. )
  1597. # Delete existing file if present (avoids 553 error on overwrite)
  1598. try:
  1599. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  1600. delete_result = await delete_file_async(
  1601. printer.ip_address,
  1602. printer.access_code,
  1603. remote_path,
  1604. socket_timeout=ftp_timeout,
  1605. printer_model=printer.model,
  1606. )
  1607. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  1608. except Exception as e:
  1609. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  1610. try:
  1611. if ftp_retry_enabled:
  1612. uploaded = await with_ftp_retry(
  1613. upload_file_async,
  1614. printer.ip_address,
  1615. printer.access_code,
  1616. file_path,
  1617. remote_path,
  1618. socket_timeout=ftp_timeout,
  1619. printer_model=printer.model,
  1620. max_retries=ftp_retry_count,
  1621. retry_delay=ftp_retry_delay,
  1622. operation_name=f"Upload print to {printer.name}",
  1623. )
  1624. else:
  1625. uploaded = await upload_file_async(
  1626. printer.ip_address,
  1627. printer.access_code,
  1628. file_path,
  1629. remote_path,
  1630. socket_timeout=ftp_timeout,
  1631. printer_model=printer.model,
  1632. )
  1633. except Exception as e:
  1634. uploaded = False
  1635. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  1636. # Clean up injected temp file after upload attempt
  1637. if injected_path and injected_path.exists():
  1638. injected_path.unlink(missing_ok=True)
  1639. if not uploaded:
  1640. error_msg = (
  1641. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1642. "See server logs for detailed diagnostics."
  1643. )
  1644. item.status = "failed"
  1645. item.error_message = error_msg
  1646. item.completed_at = datetime.now(timezone.utc)
  1647. await db.commit()
  1648. logger.error(
  1649. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  1650. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  1651. )
  1652. # Send failure notification
  1653. await notification_service.on_queue_job_failed(
  1654. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1655. printer_id=printer.id,
  1656. printer_name=printer.name,
  1657. reason="Failed to upload file to printer",
  1658. db=db,
  1659. )
  1660. await self._power_off_if_needed(db, item)
  1661. return
  1662. # Parse AMS mapping if stored
  1663. ams_mapping = None
  1664. if item.ams_mapping:
  1665. try:
  1666. ams_mapping = json.loads(item.ams_mapping)
  1667. except json.JSONDecodeError:
  1668. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  1669. # Register as expected print so we don't create a duplicate archive
  1670. # Only applicable for archive-based prints
  1671. if archive:
  1672. from backend.app.main import register_expected_print
  1673. register_expected_print(
  1674. item.printer_id,
  1675. remote_filename,
  1676. archive.id,
  1677. ams_mapping=ams_mapping,
  1678. created_by_id=item.created_by_id,
  1679. )
  1680. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  1681. # This prevents phantom reprints if the backend crashes/restarts after the
  1682. # print command is sent but before the status update is committed.
  1683. # If we crash after this commit but before start_print(), the item will be
  1684. # in "printing" status without actually printing - but that's safer than
  1685. # accidentally reprinting the same file hours later.
  1686. item.status = "printing"
  1687. item.started_at = datetime.now(timezone.utc)
  1688. await db.commit()
  1689. # Clear the awaiting-plate-clear flag now that we're starting a new print
  1690. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  1691. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  1692. # Capture state before dispatch so the watchdog can detect whether the
  1693. # printer actually transitioned (#967). Also capture subtask_id so the
  1694. # watchdog can recognise "command landed but state hasn't flipped yet"
  1695. # on slow H2D transitions (#1078).
  1696. pre_status = printer_manager.get_status(item.printer_id)
  1697. pre_state = getattr(pre_status, "state", None) if pre_status else None
  1698. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  1699. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  1700. # Start the print with AMS mapping, plate_id and print options
  1701. started = printer_manager.start_print(
  1702. item.printer_id,
  1703. remote_filename,
  1704. plate_id=item.plate_id or 1,
  1705. ams_mapping=ams_mapping,
  1706. bed_levelling=item.bed_levelling,
  1707. flow_cali=item.flow_cali,
  1708. vibration_cali=item.vibration_cali,
  1709. layer_inspect=item.layer_inspect,
  1710. timelapse=item.timelapse,
  1711. use_ams=item.use_ams,
  1712. )
  1713. if started:
  1714. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  1715. # Register the local 3MF in the cover-cache so /cover skips FTP
  1716. # (#1166 follow-up). file_path was resolved earlier from either the
  1717. # archive or the library file row.
  1718. if file_path is not None:
  1719. cache_3mf_download(item.printer_id, remote_filename, file_path)
  1720. # Hold the printer against further dispatches until the watchdog
  1721. # confirms the printer transitioned (or until the hard timeout).
  1722. # Prevents multi-plate batches from triple-dispatching onto the
  1723. # same H2D Pro while it digests the first project_file (#1157).
  1724. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  1725. # Watchdog: if the printer never transitions out of pre_state AND
  1726. # never advances subtask_id, the MQTT publish was accepted locally but
  1727. # didn't reach the printer (half-broken session — same shape as
  1728. # #887/#936). Revert the queue item so the next dispatch can pick it
  1729. # up instead of leaving it stuck in "printing" (#967). subtask_id
  1730. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  1731. # that would otherwise cause the item to re-dispatch as a reprint
  1732. # of the just-finished job (#1078).
  1733. if pre_state:
  1734. asyncio.create_task(
  1735. self._watchdog_print_start(
  1736. item.id,
  1737. item.printer_id,
  1738. pre_state,
  1739. pre_subtask_id,
  1740. pre_gcode_file,
  1741. )
  1742. )
  1743. # Get estimated time for notification
  1744. estimated_time = None
  1745. if archive and archive.print_time_seconds:
  1746. estimated_time = archive.print_time_seconds
  1747. elif library_file and library_file.print_time_seconds:
  1748. estimated_time = library_file.print_time_seconds
  1749. # Send job started notification
  1750. await notification_service.on_queue_job_started(
  1751. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1752. printer_id=printer.id,
  1753. printer_name=printer.name,
  1754. db=db,
  1755. estimated_time=estimated_time,
  1756. )
  1757. # MQTT relay - publish queue job started
  1758. try:
  1759. from backend.app.services.mqtt_relay import mqtt_relay
  1760. await mqtt_relay.on_queue_job_started(
  1761. job_id=item.id,
  1762. filename=filename,
  1763. printer_id=printer.id,
  1764. printer_name=printer.name,
  1765. printer_serial=printer.serial_number,
  1766. )
  1767. except Exception:
  1768. pass # Don't fail if MQTT fails
  1769. else:
  1770. # Clean up uploaded file from SD card to prevent phantom prints
  1771. try:
  1772. await delete_file_async(
  1773. printer.ip_address,
  1774. printer.access_code,
  1775. remote_path,
  1776. printer_model=printer.model,
  1777. )
  1778. except Exception:
  1779. pass # Best-effort — don't fail the error handler
  1780. # Print command failed - revert status
  1781. item.status = "failed"
  1782. item.error_message = "Failed to send print command to printer"
  1783. item.completed_at = datetime.now(timezone.utc)
  1784. await db.commit()
  1785. logger.error(
  1786. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  1787. f"printer_manager.start_print() returned False. "
  1788. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  1789. f"Check printer status and backend logs for details."
  1790. )
  1791. # Send failure notification
  1792. await notification_service.on_queue_job_failed(
  1793. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1794. printer_id=printer.id,
  1795. printer_name=printer.name,
  1796. reason="Failed to send print command to printer - check printer connection and status",
  1797. db=db,
  1798. )
  1799. await self._power_off_if_needed(db, item)
  1800. @staticmethod
  1801. async def _watchdog_print_start(
  1802. queue_item_id: int,
  1803. printer_id: int,
  1804. pre_state: str,
  1805. pre_subtask_id: str | None = None,
  1806. pre_gcode_file: str | None = None,
  1807. timeout: float = 90.0,
  1808. poll_interval: float = 3.0,
  1809. ) -> None:
  1810. """Revert a queue item if the printer never acknowledges the start command.
  1811. Bambuddy optimistically marks the queue item as "printing" right after the
  1812. MQTT project_file publish succeeds locally. If the printer drops/ignores the
  1813. command (half-broken MQTT session — #887/#936), the state never transitions
  1814. and the item would otherwise stay stuck in "printing" forever (#967).
  1815. Exit paths (printer picked up the job — no revert):
  1816. - gcode_state changed from pre_state, OR
  1817. - subtask_id advanced past pre_subtask_id — the printer echoes our
  1818. per-dispatch identity back on push_status, so a subtask_id change is
  1819. a definitive "command landed" signal even while state is still FINISH.
  1820. H2D can sit at FINISH for ~50 s after accepting project_file before
  1821. transitioning to PREPARE, which used to trip the state-only watchdog
  1822. and caused the scheduler to revert + re-dispatch the item; the next
  1823. successful dispatch then looked like a reprint of the just-finished
  1824. job (#1078).
  1825. Timeout raised from 45 s → 90 s as belt-and-braces for slow transitions
  1826. that also don't emit an early subtask_id tick.
  1827. """
  1828. deadline = time.monotonic() + timeout
  1829. last_status = None
  1830. while time.monotonic() < deadline:
  1831. await asyncio.sleep(poll_interval)
  1832. status = printer_manager.get_status(printer_id)
  1833. if not status:
  1834. # Printer disconnected — don't mess with the DB. Drop the
  1835. # in-memory dispatch hold too so a fresh dispatch can retry
  1836. # once the printer comes back; the hard timeout would
  1837. # otherwise hold the printer unnecessarily.
  1838. scheduler._release_dispatch_hold(printer_id)
  1839. return
  1840. last_status = status
  1841. if status.state in _ACTIVE_PRINT_STATES:
  1842. # Printer is actively processing the job — release the
  1843. # post-dispatch hold so the next pending item for this printer
  1844. # can be evaluated normally. We do NOT accept arbitrary state
  1845. # transitions: a printer going FINISH -> IDLE (user dismissed
  1846. # the post-print prompt without accepting our project_file)
  1847. # would otherwise look like "command landed" and leave the
  1848. # queue item stuck in 'printing' forever (#1370).
  1849. scheduler._release_dispatch_hold(printer_id)
  1850. return
  1851. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  1852. # Printer picked up the job (subtask_id advanced). H2D can
  1853. # sit at FINISH for ~50 s after accepting project_file
  1854. # before transitioning to PREPARE, but the subtask_id flips
  1855. # to our submission_id almost immediately (#1078).
  1856. scheduler._release_dispatch_hold(printer_id)
  1857. return
  1858. # No transition. Revert the item so the scheduler can retry.
  1859. # Drop the in-memory hold so the retry isn't blocked by it.
  1860. scheduler._release_dispatch_hold(printer_id)
  1861. # Three outcomes from the revert attempt, each routed differently:
  1862. # "reverted": row flipped from printing -> pending, run recovery
  1863. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  1864. # on_print_complete or user). Skip recovery entirely
  1865. # — the print clearly landed somewhere even if the
  1866. # watchdog didn't see the active-state transition.
  1867. # "revert_failed": SQLite contention exhausted retries. Still run
  1868. # recovery so the MQTT session gets a fresh client_id
  1869. # on the half-broken-session path.
  1870. async def _do_revert(db):
  1871. item = await db.get(PrintQueueItem, queue_item_id)
  1872. if not item or item.status != "printing":
  1873. return "already_moved_on"
  1874. item.status = "pending"
  1875. item.started_at = None
  1876. await db.commit()
  1877. return "reverted"
  1878. try:
  1879. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  1880. except Exception as e:
  1881. logger.warning(
  1882. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  1883. "scheduler may keep treating this item as in-flight",
  1884. queue_item_id,
  1885. printer_id,
  1886. e,
  1887. )
  1888. revert_outcome = "revert_failed"
  1889. if revert_outcome == "already_moved_on":
  1890. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  1891. # other path) already moved the item past 'printing', don't run the
  1892. # MQTT session-recovery logic below — a forced reconnect on a healthy
  1893. # session breaks ongoing prints on the same printer.
  1894. return
  1895. if revert_outcome == "reverted":
  1896. logger.warning(
  1897. "Queue item %s: printer %d did not respond to print command within "
  1898. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  1899. "for retry (#967)",
  1900. queue_item_id,
  1901. printer_id,
  1902. timeout,
  1903. pre_state,
  1904. pre_subtask_id,
  1905. )
  1906. # Same #1150 / #887/#936 discriminator as background_dispatch: if the
  1907. # printer's gcode_file changed since pre-dispatch, the project_file
  1908. # command landed and the printer is parsing — a forced reconnect
  1909. # mid-parse triggers 0500_4003. If gcode_file is unchanged, the
  1910. # publish was silently swallowed (#887/#936) and the original
  1911. # force_reconnect recovery is what we want.
  1912. client = printer_manager.get_client(printer_id)
  1913. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  1914. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  1915. if publish_landed:
  1916. logger.warning(
  1917. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  1918. "received the command and is parsing slowly. Skipping forced "
  1919. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  1920. queue_item_id,
  1921. current_gcode_file,
  1922. pre_gcode_file,
  1923. )
  1924. elif client and hasattr(client, "force_reconnect_stale_session"):
  1925. client.force_reconnect_stale_session(
  1926. f"queue print command unacknowledged after {timeout:.0f}s "
  1927. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  1928. )
  1929. # Global scheduler instance
  1930. scheduler = PrintScheduler()