print_scheduler.py 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637
  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 sqlalchemy.orm import selectinload
  11. from backend.app.core.config import settings
  12. from backend.app.core.database import async_session, run_with_retry
  13. from backend.app.core.tasks import spawn_background_task
  14. from backend.app.models.archive import PrintArchive
  15. from backend.app.models.library import LibraryFile
  16. from backend.app.models.print_queue import PrintQueueItem
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.settings import Settings
  19. from backend.app.models.smart_plug import SmartPlug
  20. from backend.app.models.spool_assignment import SpoolAssignment
  21. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  22. from backend.app.services.bambu_ftp import (
  23. cache_3mf_download,
  24. delete_file_async,
  25. get_ftp_retry_settings,
  26. upload_file_async,
  27. with_ftp_retry,
  28. )
  29. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  30. from backend.app.services.notification_service import notification_service
  31. from backend.app.services.printer_manager import printer_manager, supports_drying
  32. from backend.app.services.smart_plug_manager import smart_plug_manager
  33. from backend.app.utils.filename import derive_remote_filename
  34. from backend.app.utils.printer_models import normalize_printer_model
  35. logger = logging.getLogger(__name__)
  36. # Bambu firmware states that mean the project_file has actually been accepted
  37. # and the printer is now processing / running / paused mid-print. Used by the
  38. # dispatch watchdog (#1370): a transition into one of these states means the
  39. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  40. # a post-print prompt) is NOT a valid "command landed" signal even though the
  41. # state value did change. SLICING is included because some firmwares park
  42. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  43. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  44. # Filament type equivalence groups — types within the same group are
  45. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  46. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  47. ["PA-CF", "PA12-CF", "PAHT-CF"],
  48. ]
  49. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  50. for _group in _FILAMENT_TYPE_GROUPS:
  51. _canonical = _group[0].upper()
  52. for _t in _group:
  53. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  54. def _canonical_filament_type(ftype: str) -> str:
  55. """Return canonical type for equivalence matching."""
  56. upper = ftype.upper()
  57. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  58. class PrintScheduler:
  59. """Background scheduler that processes the print queue."""
  60. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  61. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  62. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  63. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  64. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  65. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  66. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  67. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  68. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  69. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  70. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  71. }
  72. def __init__(self):
  73. self._running = False
  74. self._check_interval = 30 # seconds
  75. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  76. self._power_on_check_interval = 10 # seconds between connection checks
  77. self._min_drying_seconds = 1800 # 30 minutes minimum before humidity re-check can stop drying
  78. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  79. self._drying_in_progress: dict[int, float] = {}
  80. # Defensive in-memory dispatch hold (#1157): a printer that just received
  81. # a project_file command must not get a second dispatch until either it
  82. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  83. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  84. # during that window the DB busy_printers seed is empirically unreliable
  85. # (multi-plate batches double-/triple-dispatched onto the same printer
  86. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  87. # or revert.
  88. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  89. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  90. # Minimum cooldown between dispatches to the same printer (covers the
  91. # H2D's project_file digestion window).
  92. self._dispatch_min_cooldown = 60.0
  93. # Hard timeout — drop the hold even if we never observed a transition,
  94. # so a lost MQTT session can't lock a printer out of the queue forever.
  95. # Matches the watchdog timeout (90 s) plus a safety margin so the
  96. # watchdog runs first on the unhappy path.
  97. self._dispatch_max_hold = 180.0
  98. async def run(self):
  99. """Main loop - check queue every interval."""
  100. self._running = True
  101. logger.info("Print scheduler started")
  102. while self._running:
  103. try:
  104. await self.check_queue()
  105. except Exception as e:
  106. logger.error("Scheduler error: %s", e)
  107. await asyncio.sleep(self._check_interval)
  108. def stop(self):
  109. """Stop the scheduler."""
  110. self._running = False
  111. logger.info("Print scheduler stopped")
  112. async def check_queue(self):
  113. """Check for prints ready to start."""
  114. async with async_session() as db:
  115. # Check if shortest-job-first scheduling is enabled
  116. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  117. # Get all pending items, ordered by printer and position (or SJF order)
  118. if sjf_enabled:
  119. # SJF: group by printer (and target_model for model-based jobs),
  120. # then items already jumped get top priority (starvation guard),
  121. # then sort by print_time ascending. Items with no print time go last.
  122. result = await db.execute(
  123. select(PrintQueueItem)
  124. .where(PrintQueueItem.status == "pending")
  125. .order_by(
  126. PrintQueueItem.printer_id,
  127. PrintQueueItem.target_model,
  128. PrintQueueItem.been_jumped.desc(),
  129. PrintQueueItem.print_time_seconds.asc().nullslast(),
  130. PrintQueueItem.position,
  131. )
  132. )
  133. else:
  134. result = await db.execute(
  135. select(PrintQueueItem)
  136. .where(PrintQueueItem.status == "pending")
  137. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  138. )
  139. items = list(result.scalars().all())
  140. # Read plate-clear setting once per queue check
  141. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=True)
  142. if not items:
  143. # No pending items — still check auto-drying on idle printers
  144. await self._check_auto_drying(db, [], set(), require_plate_clear=require_plate_clear)
  145. return
  146. logger.info(
  147. "Queue check: found %d pending items: %s",
  148. len(items),
  149. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  150. )
  151. # Seed busy_printers with printers that already have an item in 'printing'
  152. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  153. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  154. # lag several seconds behind the print command, so the next check_queue
  155. # tick still sees IDLE and would double-dispatch onto the same printer.
  156. # Without this guard, two pending items targeting the same printer
  157. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  158. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  159. busy_result = await db.execute(
  160. select(PrintQueueItem.printer_id)
  161. .where(PrintQueueItem.status == "printing")
  162. .where(PrintQueueItem.printer_id.is_not(None))
  163. )
  164. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  165. # Defense-in-depth (#1157): augment busy_printers with any printer
  166. # still in its post-dispatch hold window. Empirically, the DB seed
  167. # above can miss in-flight items in a multi-plate batch — same-file
  168. # plates were being dispatched 30 s apart while the H2D was still
  169. # digesting the first project_file. The hold is keyed in-memory and
  170. # released by the watchdog on the success path, so it adds a layer
  171. # that doesn't depend on DB row visibility or completion-callback
  172. # timing.
  173. for held_printer_id in list(self._dispatch_holds.keys()):
  174. if self._printer_in_dispatch_hold(held_printer_id):
  175. busy_printers.add(held_printer_id)
  176. # Log skip reasons once per queue check (not per item)
  177. skip_reasons: dict[str, int] = {}
  178. for item in items:
  179. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  180. if item.scheduled_time:
  181. sched = item.scheduled_time
  182. if sched.tzinfo is None:
  183. sched = sched.replace(tzinfo=timezone.utc)
  184. if sched > datetime.now(timezone.utc):
  185. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  186. continue
  187. # Skip items that require manual start
  188. if item.manual_start:
  189. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  190. continue
  191. if item.printer_id:
  192. # Specific printer assignment (existing behavior)
  193. if item.printer_id in busy_printers:
  194. continue
  195. # Check if printer is idle
  196. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  197. printer_connected = printer_manager.is_connected(item.printer_id)
  198. # If printer not connected, try to power on via smart plug
  199. if not printer_connected:
  200. plugs = await self._get_smart_plugs(db, item.printer_id)
  201. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  202. if auto_on_plugs:
  203. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  204. # Power on using the first auto_on plug (the printer power plug)
  205. powered_on = await self._power_on_and_wait(auto_on_plugs[0], item.printer_id, db)
  206. if powered_on:
  207. # Also turn on any remaining auto_on plugs (e.g., filter)
  208. for extra_plug in auto_on_plugs[1:]:
  209. try:
  210. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  211. await service.turn_on(extra_plug)
  212. logger.info(
  213. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  214. )
  215. except Exception as e:
  216. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  217. printer_connected = True
  218. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  219. else:
  220. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  221. busy_printers.add(item.printer_id)
  222. continue
  223. else:
  224. # No plug or auto_on disabled
  225. busy_printers.add(item.printer_id)
  226. continue
  227. # Check if printer is idle (busy with another print)
  228. if not printer_idle:
  229. # If printer is drying (not truly busy), handle based on queue_drying_block
  230. if self._drying_in_progress.get(item.printer_id):
  231. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  232. if block_for_drying:
  233. # Drying blocks queue — skip this printer
  234. busy_printers.add(item.printer_id)
  235. continue
  236. else:
  237. # Print takes priority — stop drying
  238. await self._stop_drying(item.printer_id)
  239. # Re-check idle after stopping drying
  240. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  241. if not printer_idle:
  242. busy_printers.add(item.printer_id)
  243. continue
  244. else:
  245. busy_printers.add(item.printer_id)
  246. continue
  247. # Check condition (previous print success)
  248. if item.require_previous_success:
  249. if not await self._check_previous_success(db, item):
  250. item.status = "skipped"
  251. item.error_message = "Previous print failed or was aborted"
  252. item.completed_at = datetime.now(timezone.utc)
  253. await db.commit()
  254. logger.info("Skipped queue item %s - previous print failed", item.id)
  255. # Send notification
  256. job_name = await self._get_job_name(db, item)
  257. printer = await self._get_printer(db, item.printer_id)
  258. await notification_service.on_queue_job_skipped(
  259. job_name=job_name,
  260. printer_id=item.printer_id,
  261. printer_name=printer.name if printer else "Unknown",
  262. reason="Previous print failed or was aborted",
  263. db=db,
  264. )
  265. continue
  266. # Compute AMS mapping if not already set
  267. if not item.ams_mapping:
  268. computed_mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item)
  269. if computed_mapping:
  270. item.ams_mapping = json.dumps(computed_mapping)
  271. logger.info(
  272. f"Queue item {item.id}: Computed AMS mapping for printer {item.printer_id}: {computed_mapping}"
  273. )
  274. await db.commit()
  275. # Filament-deficit pre-dispatch check (#1496). If the
  276. # assigned spool can't satisfy any required slot grams,
  277. # promote the item to manual_start so the user must
  278. # acknowledge via the ▶ button (which re-checks live).
  279. if await self._block_on_filament_deficit(db, item):
  280. continue
  281. # Start the print
  282. await self._start_print(db, item)
  283. busy_printers.add(item.printer_id)
  284. # SJF starvation guard: mark items that were jumped
  285. if sjf_enabled and item.print_time_seconds is not None:
  286. for other in items:
  287. if (
  288. other.id != item.id
  289. and other.status == "pending"
  290. and other.printer_id == item.printer_id
  291. and not other.been_jumped
  292. and other.position < item.position
  293. and (
  294. other.print_time_seconds is None
  295. or other.print_time_seconds > item.print_time_seconds
  296. )
  297. ):
  298. other.been_jumped = True
  299. await db.commit()
  300. elif item.target_model:
  301. # Model-based assignment - find any idle printer of matching model
  302. # Parse required filament types if present
  303. required_types = None
  304. if item.required_filament_types:
  305. try:
  306. required_types = json.loads(item.required_filament_types)
  307. except json.JSONDecodeError:
  308. pass # Ignore malformed filament types; treat as no constraint
  309. # Parse filament overrides if present
  310. filament_overrides = None
  311. if item.filament_overrides:
  312. try:
  313. filament_overrides = json.loads(item.filament_overrides)
  314. except json.JSONDecodeError:
  315. pass
  316. # If overrides exist, use override types for validation instead
  317. effective_types = required_types
  318. if filament_overrides:
  319. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  320. if override_types:
  321. # Merge: keep original types for non-overridden slots, add override types
  322. effective_types = sorted(set(required_types or []) | set(override_types))
  323. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  324. db,
  325. item.target_model,
  326. busy_printers,
  327. effective_types,
  328. item.target_location,
  329. filament_overrides=filament_overrides,
  330. require_plate_clear=require_plate_clear,
  331. )
  332. # Update waiting_reason if changed and send notification when first waiting
  333. if item.waiting_reason != waiting_reason:
  334. was_waiting = item.waiting_reason is not None
  335. item.waiting_reason = waiting_reason
  336. await db.commit()
  337. # Send waiting notification only when transitioning to waiting state
  338. # and the reason requires user action (not just "all printers busy")
  339. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  340. job_name = await self._get_job_name(db, item)
  341. await notification_service.on_queue_job_waiting(
  342. job_name=job_name,
  343. target_model=item.target_model,
  344. waiting_reason=waiting_reason,
  345. db=db,
  346. )
  347. if printer_id:
  348. # Check condition (previous print success) before assigning
  349. if item.require_previous_success:
  350. if not await self._check_previous_success(db, item):
  351. item.status = "skipped"
  352. item.error_message = "Previous print failed or was aborted"
  353. item.completed_at = datetime.now(timezone.utc)
  354. await db.commit()
  355. logger.info("Skipped queue item %s - previous print failed", item.id)
  356. # Send notification
  357. job_name = await self._get_job_name(db, item)
  358. printer = await self._get_printer(db, printer_id)
  359. await notification_service.on_queue_job_skipped(
  360. job_name=job_name,
  361. printer_id=printer_id,
  362. printer_name=printer.name if printer else "Unknown",
  363. reason="Previous print failed or was aborted",
  364. db=db,
  365. )
  366. continue
  367. # Assign printer and start - clear waiting reason
  368. item.printer_id = printer_id
  369. item.waiting_reason = None
  370. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  371. # Send assignment notification
  372. job_name = await self._get_job_name(db, item)
  373. printer = await self._get_printer(db, printer_id)
  374. await notification_service.on_queue_job_assigned(
  375. job_name=job_name,
  376. printer_id=printer_id,
  377. printer_name=printer.name if printer else "Unknown",
  378. target_model=item.target_model,
  379. db=db,
  380. )
  381. # Compute AMS mapping for the assigned printer if not already set
  382. # This is critical for model-based jobs where mapping wasn't computed upfront
  383. if not item.ams_mapping:
  384. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  385. if computed_mapping:
  386. item.ams_mapping = json.dumps(computed_mapping)
  387. logger.info(
  388. f"Queue item {item.id}: Computed AMS mapping for printer {printer_id}: {computed_mapping}"
  389. )
  390. await db.commit()
  391. # Filament-deficit pre-dispatch check (#1496).
  392. if await self._block_on_filament_deficit(db, item):
  393. continue
  394. await self._start_print(db, item)
  395. busy_printers.add(printer_id)
  396. # SJF starvation guard: mark model-based items that were jumped
  397. if sjf_enabled and item.print_time_seconds is not None:
  398. for other in items:
  399. if (
  400. other.id != item.id
  401. and other.status == "pending"
  402. and other.printer_id is None
  403. and other.target_model
  404. and other.target_model.upper() == item.target_model.upper()
  405. and not other.been_jumped
  406. and other.position < item.position
  407. and (
  408. other.print_time_seconds is None
  409. or other.print_time_seconds > item.print_time_seconds
  410. )
  411. ):
  412. other.been_jumped = True
  413. await db.commit()
  414. # Log summary of skip reasons (helps diagnose why queue items aren't starting)
  415. if skip_reasons:
  416. logger.info("Queue skip summary: %s", skip_reasons)
  417. if busy_printers:
  418. # Log why each printer was busy (first time it was checked)
  419. for pid in busy_printers:
  420. state = printer_manager.get_status(pid)
  421. connected = printer_manager.is_connected(pid)
  422. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  423. state_name = state.state if state else "NO_STATUS"
  424. logger.info(
  425. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  426. pid,
  427. connected,
  428. state_name,
  429. awaiting,
  430. )
  431. # Auto-drying: start drying on idle printers that have no pending queue items
  432. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  433. async def _find_idle_printer_for_model(
  434. self,
  435. db: AsyncSession,
  436. model: str,
  437. exclude_ids: set[int],
  438. required_filament_types: list[str] | None = None,
  439. target_location: str | None = None,
  440. filament_overrides: list[dict] | None = None,
  441. require_plate_clear: bool = True,
  442. ) -> tuple[int | None, str | None]:
  443. """Find an idle, connected printer matching the model with compatible filaments.
  444. Args:
  445. db: Database session
  446. model: Printer model to match (e.g., "X1C", "P1S")
  447. exclude_ids: Printer IDs to exclude (already busy)
  448. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  449. If provided, only printers with all required types loaded will match.
  450. target_location: Optional location filter. If provided, only printers in this location are considered.
  451. filament_overrides: Optional list of override dicts. Each entry may include
  452. ``force_color_match: true`` to require an exact type+color match
  453. on the printer for that slot. Without the flag the existing
  454. colour-preference logic applies.
  455. Returns:
  456. Tuple of (printer_id, waiting_reason):
  457. - (printer_id, None) if a matching printer was found
  458. - (None, reason) if no printer is available, with explanation
  459. """
  460. # Normalize model name and use case-insensitive matching
  461. normalized_model = normalize_printer_model(model) or model
  462. query = (
  463. select(Printer)
  464. .where(func.lower(Printer.model) == normalized_model.lower())
  465. .where(Printer.is_active == True) # noqa: E712
  466. )
  467. # Add location filter if specified
  468. if target_location:
  469. query = query.where(Printer.location == target_location)
  470. result = await db.execute(query)
  471. printers = list(result.scalars().all())
  472. location_suffix = f" in {target_location}" if target_location else ""
  473. if not printers:
  474. return None, f"No active {normalized_model} printers{location_suffix} configured"
  475. # Separate force-matched overrides from preference-only overrides
  476. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  477. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  478. # Track reasons for skipping printers
  479. printers_busy = []
  480. printers_offline = []
  481. printers_missing_filament: list[tuple[str, list[str]]] = []
  482. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  483. for printer in printers:
  484. if printer.id in exclude_ids:
  485. # Printer is already claimed by another job in this scheduling run.
  486. # For force-color jobs, still check if the color would match — if not,
  487. # report it as a color mismatch rather than plain "Busy" so the user
  488. # knows the job needs a filament change, not just to wait for availability.
  489. if force_overrides and not pref_overrides:
  490. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  491. if missing_colors:
  492. printers_missing_filament.append((printer.name, missing_colors))
  493. continue
  494. printers_busy.append(printer.name)
  495. continue
  496. is_connected = printer_manager.is_connected(printer.id)
  497. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  498. if not is_connected:
  499. printers_offline.append(printer.name)
  500. continue
  501. if not is_idle:
  502. # Printer is currently printing. For force-color jobs, check whether the
  503. # loaded color would satisfy the requirement — if not, surface it as a
  504. # color-mismatch reason rather than plain "Busy" so the user understands
  505. # that the job is waiting for a filament change, not just printer availability.
  506. if force_overrides and not pref_overrides:
  507. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  508. if missing_colors:
  509. printers_missing_filament.append((printer.name, missing_colors))
  510. logger.debug(
  511. "Printer %s (%s) is busy but also has wrong force-color: %s",
  512. printer.id,
  513. printer.name,
  514. missing_colors,
  515. )
  516. continue
  517. printers_busy.append(printer.name)
  518. continue
  519. # Validate filament compatibility if required types are specified
  520. if required_filament_types:
  521. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  522. if missing:
  523. # When force_overrides are present, enrich missing entries with color info
  524. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  525. if force_overrides:
  526. force_color_map = {
  527. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  528. for o in force_overrides
  529. }
  530. missing_enriched = [
  531. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  532. for t in missing
  533. ]
  534. printers_missing_filament.append((printer.name, missing_enriched))
  535. else:
  536. printers_missing_filament.append((printer.name, missing))
  537. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  538. continue
  539. # Force color match: ALL flagged slots must have an exact type+color match
  540. if force_overrides:
  541. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  542. if missing_colors:
  543. printers_missing_filament.append((printer.name, missing_colors))
  544. logger.debug(
  545. "Skipping printer %s (%s) - missing force-matched colors: %s",
  546. printer.id,
  547. printer.name,
  548. missing_colors,
  549. )
  550. continue
  551. # If preference-only overrides exist, rank by color matches (existing behaviour)
  552. if pref_overrides:
  553. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  554. if color_matches > 0:
  555. candidates.append((printer.id, color_matches))
  556. else:
  557. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  558. printers_missing_filament.append((printer.name, override_colors))
  559. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  560. continue
  561. elif force_overrides:
  562. # Passed all force checks — immediately eligible (no preference ordering needed)
  563. return printer.id, None
  564. else:
  565. # No overrides at all - take first available (existing behavior)
  566. return printer.id, None
  567. # If we have candidates from preference override matching, pick the one with most color matches
  568. if candidates:
  569. candidates.sort(key=lambda c: c[1], reverse=True)
  570. return candidates[0][0], None
  571. # Build waiting reason from what we found
  572. reasons = []
  573. if printers_missing_filament:
  574. # Filament/color mismatch is most actionable - show first
  575. if force_overrides and not pref_overrides:
  576. # All mismatches are force-color failures — use descriptive message only;
  577. # but only if there are no busy printers that DO have the matching color.
  578. # If a printer has the right color but is busy, surface "Busy" instead so
  579. # the user knows the job will start automatically once that printer is free.
  580. if not printers_busy:
  581. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  582. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  583. # else: fall through — printers_busy will be appended below
  584. else:
  585. names_and_missing = [
  586. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  587. ]
  588. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  589. if printers_busy:
  590. reasons.append(f"Busy: {', '.join(printers_busy)}")
  591. if printers_offline:
  592. reasons.append(f"Offline: {', '.join(printers_offline)}")
  593. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  594. @staticmethod
  595. def _is_busy_only(waiting_reason: str) -> bool:
  596. """Check if the waiting reason only contains 'Busy' entries.
  597. When all matching printers are simply busy printing, the queued job
  598. will start automatically once a printer finishes — no user action
  599. is required, so we skip the notification.
  600. """
  601. parts = [p.strip() for p in waiting_reason.split(" | ")]
  602. return all(p.startswith("Busy:") for p in parts)
  603. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  604. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  605. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  606. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  607. with an exact type+color match.
  608. Returns:
  609. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  610. """
  611. status = printer_manager.get_status(printer_id)
  612. if not status:
  613. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  614. # Build set of loaded type+colour pairs from AMS and external spool
  615. loaded: set[tuple[str, str]] = set()
  616. for ams_unit in status.raw_data.get("ams", []):
  617. for tray in ams_unit.get("tray", []):
  618. tray_type = tray.get("tray_type")
  619. tray_color = tray.get("tray_color", "")
  620. if tray_type:
  621. color_norm = tray_color.replace("#", "").lower()[:6]
  622. loaded.add((_canonical_filament_type(tray_type), color_norm))
  623. for vt in status.raw_data.get("vt_tray") or []:
  624. vt_type = vt.get("tray_type")
  625. if vt_type:
  626. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  627. loaded.add((_canonical_filament_type(vt_type), color_norm))
  628. missing = []
  629. for o in force_overrides:
  630. o_type = _canonical_filament_type(o.get("type") or "")
  631. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  632. if (o_type, o_color) not in loaded:
  633. color_label = o.get("color_name") or o.get("color", "?")
  634. missing.append(f"{o_type} ({color_label})")
  635. return missing
  636. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  637. """Get the list of required filament types that are not loaded on the printer.
  638. Args:
  639. printer_id: The printer ID
  640. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  641. Returns:
  642. List of missing filament types (empty if all are loaded)
  643. """
  644. status = printer_manager.get_status(printer_id)
  645. if not status:
  646. return required_types # Can't determine, assume all missing
  647. # Collect all filament types loaded on this printer (AMS units + external spool)
  648. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  649. loaded_types: set[str] = set()
  650. # Check AMS units (stored in raw_data["ams"])
  651. ams_data = status.raw_data.get("ams", [])
  652. if ams_data:
  653. for ams_unit in ams_data:
  654. for tray in ams_unit.get("tray", []):
  655. tray_type = tray.get("tray_type")
  656. if tray_type:
  657. loaded_types.add(_canonical_filament_type(tray_type))
  658. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  659. for vt in status.raw_data.get("vt_tray") or []:
  660. vt_type = vt.get("tray_type")
  661. if vt_type:
  662. loaded_types.add(_canonical_filament_type(vt_type))
  663. # Find which required types are missing (using canonical type for equivalence)
  664. missing = []
  665. for req_type in required_types:
  666. if _canonical_filament_type(req_type) not in loaded_types:
  667. missing.append(req_type)
  668. return missing
  669. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  670. """Count how many filament overrides have an exact color match on the printer.
  671. Used to prefer printers that already have the desired override colors loaded.
  672. """
  673. status = printer_manager.get_status(printer_id)
  674. if not status:
  675. return 0
  676. # Collect loaded filaments' type+color pairs
  677. loaded: set[tuple[str, str]] = set()
  678. for ams_unit in status.raw_data.get("ams", []):
  679. for tray in ams_unit.get("tray", []):
  680. tray_type = tray.get("tray_type")
  681. tray_color = tray.get("tray_color", "")
  682. if tray_type:
  683. color_norm = tray_color.replace("#", "").lower()[:6]
  684. loaded.add((tray_type.upper(), color_norm))
  685. for vt in status.raw_data.get("vt_tray") or []:
  686. vt_type = vt.get("tray_type")
  687. if vt_type:
  688. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  689. loaded.add((vt_type.upper(), color_norm))
  690. matches = 0
  691. for o in overrides:
  692. o_type = (o.get("type") or "").upper()
  693. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  694. if (o_type, o_color) in loaded:
  695. matches += 1
  696. return matches
  697. async def _compute_ams_mapping_for_printer(
  698. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  699. ) -> list[int] | None:
  700. """Compute AMS mapping for a printer based on filament requirements.
  701. Called when a queue item has no ams_mapping set — either for model-based
  702. items after printer assignment, or printer-specific items (e.g. from VP).
  703. Args:
  704. db: Database session
  705. printer_id: The assigned printer ID
  706. item: The queue item (contains archive_id or library_file_id)
  707. Returns:
  708. AMS mapping array or None if no mapping needed/possible
  709. """
  710. # Get printer status
  711. status = printer_manager.get_status(printer_id)
  712. if not status:
  713. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  714. return None
  715. # Get filament requirements from source file
  716. filament_reqs = await self._get_filament_requirements(db, item)
  717. if not filament_reqs:
  718. # When the 3MF can't be read but force-color overrides are present, build a
  719. # direct mapping from the overrides so the printer uses the correct AMS slot.
  720. if item.filament_overrides:
  721. try:
  722. overrides = json.loads(item.filament_overrides)
  723. force_overrides = [o for o in overrides if o.get("force_color_match")]
  724. if force_overrides:
  725. logger.info(
  726. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  727. "force-color override(s)",
  728. item.id,
  729. len(force_overrides),
  730. )
  731. return self._build_override_direct_mapping(force_overrides, status)
  732. except (json.JSONDecodeError, KeyError, TypeError) as e:
  733. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  734. logger.debug("No filament requirements found for queue item %s", item.id)
  735. return None
  736. # Apply filament overrides if present
  737. if item.filament_overrides:
  738. try:
  739. overrides = json.loads(item.filament_overrides)
  740. override_map = {o["slot_id"]: o for o in overrides}
  741. for req in filament_reqs:
  742. if req["slot_id"] in override_map:
  743. override = override_map[req["slot_id"]]
  744. req["type"] = override["type"]
  745. req["color"] = override["color"]
  746. # Clear tray_info_idx so matching uses type+color instead of
  747. # the original 3MF's tray_info_idx (which would match the old filament)
  748. req["tray_info_idx"] = ""
  749. logger.debug(
  750. "Queue item %s: Override slot %d -> %s %s",
  751. item.id,
  752. req["slot_id"],
  753. override["type"],
  754. override["color"],
  755. )
  756. except (json.JSONDecodeError, KeyError, TypeError) as e:
  757. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  758. # Build loaded filaments from printer status
  759. loaded_filaments = self._build_loaded_filaments(status)
  760. if not loaded_filaments:
  761. logger.debug("No filaments loaded on printer %s", printer_id)
  762. return None
  763. # Check if user prefers lowest remaining filament when multiple spools match
  764. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  765. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  766. # Without backup, the printer will not switch to a second spool when the
  767. # picked one runs out — so sorting toward the lowest leaves the print
  768. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  769. # today's behaviour intentionally.
  770. if prefer_lowest and status.ams_filament_backup is False:
  771. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  772. prefer_lowest = False
  773. # When the preference is on, surface Bambuddy's inventory-side
  774. # remaining for each slot that's bound to a tracked spool, so the
  775. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  776. # entirely when the preference is off — no behaviour change for
  777. # users who haven't opted in.
  778. inventory_remain_overrides: dict[int, float] | None = None
  779. if prefer_lowest:
  780. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  781. # Compute mapping: match required filaments to available slots
  782. return self._match_filaments_to_slots(
  783. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides
  784. )
  785. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  786. """Build an AMS mapping directly from force-color overrides without a 3MF.
  787. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  788. slice_info is missing or unreadable) but ``force_color_match`` overrides
  789. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  790. treated as the filament requirement for that slot and matched against the
  791. current AMS state of the printer.
  792. Returns the same format as ``_match_filaments_to_slots``, or None when
  793. the AMS has no loaded filaments.
  794. """
  795. loaded = self._build_loaded_filaments(status)
  796. if not loaded:
  797. return None
  798. reqs = [
  799. {
  800. "slot_id": o["slot_id"],
  801. "type": o.get("type", ""),
  802. "color": o.get("color", ""),
  803. "tray_info_idx": "",
  804. }
  805. for o in force_overrides
  806. ]
  807. return self._match_filaments_to_slots(reqs, loaded)
  808. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  809. """Resolve the queue item's source 3MF and parse the per-slot
  810. filament requirements out of it. Thin DB-resolver wrapper around
  811. ``filament_requirements.extract_filament_requirements`` so the VP
  812. queue-mode write path (#1188) can reuse the same parser at upload
  813. time.
  814. """
  815. from backend.app.services.filament_requirements import extract_filament_requirements
  816. file_path: Path | None = None
  817. if item.archive_id:
  818. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  819. archive = result.scalar_one_or_none()
  820. if archive:
  821. file_path = settings.base_dir / archive.file_path
  822. elif item.library_file_id:
  823. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  824. library_file = result.scalar_one_or_none()
  825. if library_file:
  826. lib_path = Path(library_file.file_path)
  827. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  828. if not file_path or not file_path.exists():
  829. return None
  830. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  831. return filaments if filaments else None
  832. def _build_loaded_filaments(self, status) -> list[dict]:
  833. """Build list of loaded filaments from printer status.
  834. Args:
  835. status: PrinterState from printer_manager
  836. Returns:
  837. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  838. """
  839. filaments = []
  840. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  841. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  842. # Parse AMS units from raw_data
  843. ams_data = status.raw_data.get("ams", [])
  844. for ams_unit in ams_data:
  845. ams_id = int(ams_unit.get("id", 0))
  846. trays = ams_unit.get("tray", [])
  847. is_ht = len(trays) == 1 # AMS-HT has single tray
  848. for tray in trays:
  849. tray_type = tray.get("tray_type")
  850. if tray_type:
  851. tray_id = int(tray.get("id", 0))
  852. tray_color = tray.get("tray_color", "")
  853. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  854. tray_info_idx = tray.get("tray_info_idx", "")
  855. # Normalize color: remove alpha, add hash
  856. color = self._normalize_color(tray_color)
  857. # Calculate global tray ID
  858. # AMS-HT units have IDs starting at 128 with a single tray
  859. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  860. filaments.append(
  861. {
  862. "type": tray_type,
  863. "color": color,
  864. "tray_info_idx": tray_info_idx,
  865. "ams_id": ams_id,
  866. "tray_id": tray_id,
  867. "is_ht": is_ht,
  868. "is_external": False,
  869. "global_tray_id": global_tray_id,
  870. "extruder_id": ams_extruder_map.get(str(ams_id)),
  871. "remain": tray.get("remain", -1),
  872. }
  873. )
  874. # Check external spool(s) (vt_tray is a list)
  875. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  876. if vt.get("tray_type"):
  877. color = self._normalize_color(vt.get("tray_color", ""))
  878. tray_id = int(vt.get("id", 254))
  879. filaments.append(
  880. {
  881. "type": vt["tray_type"],
  882. "color": color,
  883. "tray_info_idx": vt.get("tray_info_idx", ""),
  884. "ams_id": -1,
  885. "tray_id": idx,
  886. "is_ht": False,
  887. "is_external": True,
  888. "global_tray_id": tray_id,
  889. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  890. "remain": vt.get("remain", -1),
  891. }
  892. )
  893. return filaments
  894. def _normalize_color(self, color: str | None) -> str:
  895. """Normalize color to #RRGGBB format."""
  896. if not color:
  897. return "#808080"
  898. hex_color = color.replace("#", "")[:6]
  899. return f"#{hex_color}"
  900. def _normalize_color_for_compare(self, color: str | None) -> str:
  901. """Normalize color for comparison (lowercase, no hash)."""
  902. if not color:
  903. return ""
  904. return color.replace("#", "").lower()[:6]
  905. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  906. """Check if two colors are visually similar within a threshold."""
  907. hex1 = self._normalize_color_for_compare(color1)
  908. hex2 = self._normalize_color_for_compare(color2)
  909. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  910. return False
  911. try:
  912. r1 = int(hex1[0:2], 16)
  913. g1 = int(hex1[2:4], 16)
  914. b1 = int(hex1[4:6], 16)
  915. r2 = int(hex2[0:2], 16)
  916. g2 = int(hex2[2:4], 16)
  917. b2 = int(hex2[4:6], 16)
  918. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  919. except ValueError:
  920. return False
  921. async def _build_inventory_remain_overrides(
  922. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  923. ) -> dict[int, float]:
  924. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  925. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  926. The MQTT ``remain`` field on a tray is the printer firmware's
  927. RFID-decremented value, which has two limitations the "Prefer Lowest
  928. Remaining Filament" feature has been ignoring (#1508):
  929. - it's only meaningful for Bambu RFID spools; everything else reports
  930. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  931. compare equal and the sort collapses to AMS-slot order — the user
  932. who's curating inventory weights gets the lower-slot pick instead
  933. of the lower-remaining pick;
  934. - even when set, it's the *printer's* counter, not Bambuddy's
  935. ``label_weight - weight_used`` (internal mode) or Spoolman's
  936. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  937. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  938. When the user has bound a spool to a slot, their own inventory
  939. tracking is authoritative; this helper surfaces that value so the
  940. sort can prefer it. Slots without a binding are absent from the
  941. returned map — the caller then falls back to MQTT ``remain`` for
  942. those, preserving the pre-#1508 behaviour for un-tracked spools.
  943. Returns an empty map on any failure (no inventory bindings, DB
  944. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  945. is a preference, not a guarantee.
  946. """
  947. if not loaded:
  948. return {}
  949. # External / virtual-tray slots are tracked separately from AMS — skip
  950. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  951. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  952. # match is fiddly and out of scope for this fix).
  953. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  954. if not tracked_slots:
  955. return {}
  956. is_spoolman = await self._is_spoolman_mode(db)
  957. overrides: dict[int, float] = {}
  958. if is_spoolman:
  959. result = await db.execute(
  960. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  961. )
  962. assignments = list(result.scalars().all())
  963. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  964. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  965. for ams_id, tray_id, gtid in tracked_slots:
  966. spoolman_id = by_slot.get((ams_id, tray_id))
  967. if spoolman_id is None:
  968. continue
  969. grams = await _spoolman_remaining_grams(spoolman_id)
  970. if grams is not None:
  971. overrides[gtid] = grams
  972. return overrides
  973. # Internal inventory mode (default). selectinload matches the pattern
  974. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  975. # plus an eager-loaded relationship rather than an explicit join, so
  976. # the row-attribute shape is exactly what those routes already rely on.
  977. result = await db.execute(
  978. select(SpoolAssignment)
  979. .options(selectinload(SpoolAssignment.spool))
  980. .where(SpoolAssignment.printer_id == printer_id)
  981. )
  982. assignments = list(result.scalars().all())
  983. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  984. for ams_id, tray_id, gtid in tracked_slots:
  985. spool = by_slot.get((ams_id, tray_id))
  986. if spool is None:
  987. continue
  988. label = float(spool.label_weight or 0)
  989. used = float(spool.weight_used or 0)
  990. overrides[gtid] = max(0.0, label - used)
  991. return overrides
  992. @staticmethod
  993. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  994. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  995. here to avoid making this module import-dependent on that private
  996. helper's signature."""
  997. try:
  998. from backend.app.api.routes.settings import get_setting
  999. v = await get_setting(db, "spoolman_enabled")
  1000. return bool(v) and v.lower() == "true"
  1001. except Exception:
  1002. return False
  1003. @staticmethod
  1004. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  1005. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  1006. Three bands, matched to the emission order in ``_build_loaded_filaments``
  1007. so a tied sort produces the same physical-position order the pre-#1508
  1008. stable sort did (preserves the regression-free baseline):
  1009. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  1010. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  1011. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  1012. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  1013. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  1014. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  1015. """
  1016. if ams_id is None or ams_id < 0:
  1017. return 10_000
  1018. if ams_id >= 128:
  1019. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  1020. return ams_id * 4 + (tray_id or 0)
  1021. @staticmethod
  1022. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  1023. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  1024. Two-tier ordering: inventory-tracked spools always sort BEFORE
  1025. non-tracked spools (the user has told us they care about these
  1026. specifically), then ascending by remaining within each tier, then
  1027. ascending by AMS slot position as the deterministic tie-breaker.
  1028. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  1029. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  1030. because the tier flag dominates — which is what lets us mix grams
  1031. (inventory) and percent (MQTT) without a unit conversion.
  1032. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  1033. spools the printer DOES know something about sort ahead of those
  1034. it knows nothing about — preserves pre-#1508 behaviour for the
  1035. no-inventory-binding case.
  1036. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  1037. external on ties, matching the legacy emission-order stable sort.
  1038. """
  1039. gtid = f.get("global_tray_id")
  1040. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  1041. if overrides and gtid in overrides:
  1042. return (0, overrides[gtid], slot_order)
  1043. remain = f.get("remain", -1)
  1044. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  1045. def _match_filaments_to_slots(
  1046. self,
  1047. required: list[dict],
  1048. loaded: list[dict],
  1049. prefer_lowest: bool = False,
  1050. inventory_remain_overrides: dict[int, float] | None = None,
  1051. ) -> list[int] | None:
  1052. """Match required filaments to loaded filaments and build AMS mapping.
  1053. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  1054. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  1055. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  1056. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  1057. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  1058. matching among those trays.
  1059. Args:
  1060. required: List of required filaments with slot_id, type, color, tray_info_idx
  1061. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  1062. Returns:
  1063. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  1064. """
  1065. if not required:
  1066. return None
  1067. # Track used trays to avoid duplicate assignment
  1068. used_tray_ids: set[int] = set()
  1069. comparisons = []
  1070. for req in required:
  1071. req_type = (req.get("type") or "").upper()
  1072. req_color = req.get("color", "")
  1073. req_tray_info_idx = req.get("tray_info_idx", "")
  1074. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  1075. idx_match = None
  1076. exact_match = None
  1077. similar_match = None
  1078. type_only_match = None
  1079. # Get available trays (not already used)
  1080. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  1081. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  1082. # Hard filter — cross-nozzle assignment causes print failures
  1083. # ("position of left hotend is abnormal"), so never fall back.
  1084. req_nozzle_id = req.get("nozzle_id")
  1085. if req_nozzle_id is not None:
  1086. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  1087. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  1088. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  1089. # _prefer_lowest_sort_key for the full rationale.
  1090. if prefer_lowest:
  1091. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1092. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  1093. # One line per filament req so a bug report can be diagnosed
  1094. # without enabling debug logging: shows what the matcher saw
  1095. # (req shape + sorted candidate trays with their remain values
  1096. # and any inventory override that was applied). Mirrored by
  1097. # the picked-match log at the bottom of the loop.
  1098. logger.info(
  1099. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  1100. req.get("slot_id"),
  1101. req_type,
  1102. req_color,
  1103. req_tray_info_idx,
  1104. req_nozzle_id,
  1105. [
  1106. {
  1107. "gtid": f.get("global_tray_id"),
  1108. "type": f.get("type"),
  1109. "color": f.get("color"),
  1110. "tii": f.get("tray_info_idx"),
  1111. "remain": f.get("remain"),
  1112. "inv_g": (
  1113. inventory_remain_overrides.get(f.get("global_tray_id"))
  1114. if inventory_remain_overrides
  1115. else None
  1116. ),
  1117. }
  1118. for f in available
  1119. ],
  1120. )
  1121. # Check if tray_info_idx is unique among available trays
  1122. if req_tray_info_idx:
  1123. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  1124. if len(idx_matches) == 1:
  1125. # Unique tray_info_idx - use it as definitive match
  1126. idx_match = idx_matches[0]
  1127. logger.debug(
  1128. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  1129. f"-> tray {idx_match['global_tray_id']}"
  1130. )
  1131. elif len(idx_matches) > 1:
  1132. # Multiple trays with same tray_info_idx - use color matching among them
  1133. logger.debug(
  1134. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  1135. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  1136. )
  1137. if prefer_lowest:
  1138. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1139. # Use color matching within this subset
  1140. for f in idx_matches:
  1141. f_color = f.get("color", "")
  1142. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1143. if not exact_match:
  1144. exact_match = f
  1145. elif self._colors_are_similar(f_color, req_color):
  1146. if not similar_match:
  1147. similar_match = f
  1148. elif not type_only_match:
  1149. type_only_match = f
  1150. # If no idx_match yet, do standard type/color matching on all available trays
  1151. if not idx_match and not exact_match and not similar_match and not type_only_match:
  1152. for f in available:
  1153. f_type = (f.get("type") or "").upper()
  1154. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  1155. continue
  1156. # Type matches - check color
  1157. f_color = f.get("color", "")
  1158. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1159. if not exact_match:
  1160. exact_match = f
  1161. elif self._colors_are_similar(f_color, req_color):
  1162. if not similar_match:
  1163. similar_match = f
  1164. elif not type_only_match:
  1165. type_only_match = f
  1166. match = idx_match or exact_match or similar_match or type_only_match
  1167. if match:
  1168. used_tray_ids.add(match["global_tray_id"])
  1169. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  1170. else:
  1171. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  1172. if prefer_lowest:
  1173. # Pair with the "available (sorted)" log above so the reporter
  1174. # bundle shows BOTH what the matcher saw AND which match bucket
  1175. # won — fast triage when "Prefer Lowest Filament" picks the
  1176. # wrong slot (#1766).
  1177. if match:
  1178. bucket = (
  1179. "idx"
  1180. if idx_match is not None
  1181. else "exact_color"
  1182. if exact_match is not None
  1183. else "similar_color"
  1184. if similar_match is not None
  1185. else "type_only"
  1186. )
  1187. logger.info(
  1188. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  1189. match["global_tray_id"],
  1190. bucket,
  1191. req.get("slot_id"),
  1192. )
  1193. else:
  1194. logger.info(
  1195. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  1196. req.get("slot_id"),
  1197. req_type,
  1198. req_color,
  1199. req_tray_info_idx,
  1200. )
  1201. # Build mapping array
  1202. if not comparisons:
  1203. return None
  1204. max_slot_id = max(c["slot_id"] for c in comparisons)
  1205. if max_slot_id <= 0:
  1206. return None
  1207. mapping = [-1] * max_slot_id
  1208. for c in comparisons:
  1209. slot_id = c["slot_id"]
  1210. if slot_id and slot_id > 0:
  1211. mapping[slot_id - 1] = c["global_tray_id"]
  1212. return mapping
  1213. def _mark_printer_dispatched(
  1214. self,
  1215. printer_id: int,
  1216. pre_state: str | None,
  1217. pre_subtask_id: str | None,
  1218. ) -> None:
  1219. """Record that a print command was just sent to ``printer_id``.
  1220. Held until either the watchdog observes a state/subtask transition
  1221. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1222. """
  1223. if not pre_state:
  1224. # No pre_state means we can't detect a transition — fall back to a
  1225. # pure time-based hold using empty string as a sentinel that won't
  1226. # match any real printer state.
  1227. pre_state = ""
  1228. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1229. def _release_dispatch_hold(self, printer_id: int) -> None:
  1230. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1231. self._dispatch_holds.pop(printer_id, None)
  1232. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1233. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1234. Returns False (and clears the hold) once any of these are true:
  1235. - hard timeout (``_dispatch_max_hold``) has elapsed
  1236. - the printer has transitioned out of pre_state and we're past the
  1237. minimum cooldown
  1238. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1239. past the minimum cooldown
  1240. Otherwise the printer is held — caller should treat it as busy.
  1241. """
  1242. entry = self._dispatch_holds.get(printer_id)
  1243. if not entry:
  1244. return False
  1245. started_at, pre_state, pre_subtask_id = entry
  1246. elapsed = time.monotonic() - started_at
  1247. if elapsed >= self._dispatch_max_hold:
  1248. self._dispatch_holds.pop(printer_id, None)
  1249. return False
  1250. # Without a pre_state we can't detect a transition — fall back to the
  1251. # min cooldown alone, then drop the hold.
  1252. if not pre_state:
  1253. if elapsed >= self._dispatch_min_cooldown:
  1254. self._dispatch_holds.pop(printer_id, None)
  1255. return False
  1256. return True
  1257. status = printer_manager.get_status(printer_id)
  1258. current_state = getattr(status, "state", None) if status else None
  1259. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1260. transitioned = (current_state is not None and current_state != pre_state) or (
  1261. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1262. )
  1263. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1264. self._dispatch_holds.pop(printer_id, None)
  1265. return False
  1266. return True
  1267. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1268. """Check if a printer is connected and idle."""
  1269. if not printer_manager.is_connected(printer_id):
  1270. logger.debug("Printer %d: not connected", printer_id)
  1271. return False
  1272. state = printer_manager.get_status(printer_id)
  1273. if not state:
  1274. logger.debug("Printer %d: no status available", printer_id)
  1275. return False
  1276. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1277. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1278. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1279. # printer, it boots back into IDLE with no memory of the previous finish; without
  1280. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1281. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1282. logger.debug(
  1283. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1284. printer_id,
  1285. state.state,
  1286. )
  1287. return False
  1288. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1289. if not idle:
  1290. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1291. return idle
  1292. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1293. """Read a setting value from the database."""
  1294. result = await db.execute(select(Settings).where(Settings.key == key))
  1295. setting = result.scalar_one_or_none()
  1296. return setting.value if setting else None
  1297. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1298. """Read a boolean setting from the database."""
  1299. result = await db.execute(select(Settings).where(Settings.key == key))
  1300. setting = result.scalar_one_or_none()
  1301. if setting:
  1302. return setting.value.lower() == "true"
  1303. return default
  1304. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1305. """Get drying presets (user-configured or built-in defaults)."""
  1306. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1307. setting = result.scalar_one_or_none()
  1308. if setting and setting.value:
  1309. try:
  1310. presets = json.loads(setting.value)
  1311. if isinstance(presets, dict) and presets:
  1312. return presets
  1313. except json.JSONDecodeError:
  1314. pass
  1315. return self.DEFAULT_DRYING_PRESETS
  1316. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  1317. """Per-filament humidity thresholds (#1605).
  1318. Returns the user-configured overrides map keyed by normalized filament
  1319. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  1320. unknown / unmapped types. Empty / unset → empty dict, in which case
  1321. callers fall back to ``ams_humidity_fair``.
  1322. """
  1323. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  1324. setting = result.scalar_one_or_none()
  1325. if not setting or not setting.value:
  1326. return {}
  1327. try:
  1328. data = json.loads(setting.value)
  1329. except json.JSONDecodeError:
  1330. return {}
  1331. if not isinstance(data, dict):
  1332. return {}
  1333. out: dict[str, int] = {}
  1334. for key, value in data.items():
  1335. try:
  1336. out[str(key).upper() if key != "default" else "default"] = int(value)
  1337. except (TypeError, ValueError):
  1338. continue
  1339. return out
  1340. @staticmethod
  1341. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  1342. """Resolve the effective humidity threshold for an AMS unit (#1605).
  1343. For mixed filament types loaded into one AMS, returns the most
  1344. restrictive (lowest) threshold across all loaded tray types — matches
  1345. the conservative-params strategy already used for drying temp/hours.
  1346. Empty / unloaded trays contribute no constraint. Unknown types use the
  1347. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  1348. when no per-type map is configured at all.
  1349. """
  1350. default = thresholds.get("default", fallback)
  1351. if not thresholds:
  1352. return fallback
  1353. candidates: list[int] = []
  1354. for tray in trays:
  1355. tray_type = str(tray.get("tray_type") or "").strip()
  1356. if not tray_type:
  1357. continue
  1358. base_type = tray_type.split()[0].upper()
  1359. candidates.append(thresholds.get(base_type, default))
  1360. if not candidates:
  1361. return default
  1362. return min(candidates)
  1363. def _get_conservative_drying_params(
  1364. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1365. ) -> tuple[int, int, str] | None:
  1366. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1367. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1368. """
  1369. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1370. hours_key = f"{temp_key}_hours"
  1371. min_temp = None
  1372. max_hours = None
  1373. filament_type = ""
  1374. for tray in trays:
  1375. tray_type = tray.get("tray_type", "")
  1376. if not tray_type:
  1377. continue
  1378. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1379. base_type = tray_type.split()[0].upper()
  1380. preset = presets.get(base_type)
  1381. if not preset:
  1382. continue
  1383. temp = preset.get(temp_key, 55)
  1384. hours = preset.get(hours_key, 12)
  1385. # Conservative: lowest temp, longest duration
  1386. if min_temp is None or temp < min_temp:
  1387. min_temp = temp
  1388. if max_hours is None or hours > max_hours:
  1389. max_hours = hours
  1390. if not filament_type:
  1391. filament_type = base_type
  1392. if min_temp is None:
  1393. return None
  1394. return (min_temp, max_hours or 12, filament_type)
  1395. async def _check_auto_drying(
  1396. self,
  1397. db: AsyncSession,
  1398. queue_items: list[PrintQueueItem],
  1399. busy_printers: set[int],
  1400. *,
  1401. require_plate_clear: bool = True,
  1402. ):
  1403. """Start drying on idle printers based on humidity.
  1404. Two modes (can both be enabled):
  1405. - queue_drying_enabled: Dry between scheduled queue prints
  1406. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1407. """
  1408. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1409. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1410. if not queue_drying_enabled and not ambient_drying_enabled:
  1411. # Stop active drying on all printers if both features disabled
  1412. if self._drying_in_progress:
  1413. for pid in list(self._drying_in_progress):
  1414. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1415. await self._stop_drying(pid)
  1416. return
  1417. # Update drying state from printer status (handles backend restart)
  1418. self._sync_drying_state()
  1419. # Find printers with scheduled items (for queue drying mode)
  1420. printers_with_scheduled: set[int] = set()
  1421. printers_with_items: set[int] = set()
  1422. for item in queue_items:
  1423. if item.printer_id:
  1424. printers_with_items.add(item.printer_id)
  1425. if item.scheduled_time and not item.manual_start:
  1426. printers_with_scheduled.add(item.printer_id)
  1427. # If only queue mode is on and no printers have scheduled items, stop drying
  1428. if not ambient_drying_enabled and not printers_with_scheduled:
  1429. for pid in list(self._drying_in_progress):
  1430. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1431. await self._stop_drying(pid)
  1432. return
  1433. # Get humidity threshold (global fallback)
  1434. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1435. setting = result.scalar_one_or_none()
  1436. global_humidity_threshold = int(setting.value) if setting else 60
  1437. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  1438. # to the global threshold for every AMS unit.
  1439. per_type_thresholds = await self._get_humidity_thresholds(db)
  1440. # Get drying presets
  1441. presets = await self._get_drying_presets(db)
  1442. # Determine if drying should be skipped for printers with pending items
  1443. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1444. # Get all active printers
  1445. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1446. for printer in all_printers.scalars():
  1447. pid = printer.id
  1448. if pid in busy_printers:
  1449. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1450. continue
  1451. # In queue-only mode, only dry printers that have scheduled prints
  1452. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1453. if self._drying_in_progress.get(pid):
  1454. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1455. await self._stop_drying(pid)
  1456. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1457. continue
  1458. # When block mode is on, don't START new drying on printers with pending items.
  1459. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1460. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1461. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1462. continue
  1463. if not printer_manager.is_connected(pid):
  1464. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1465. continue
  1466. if not self._is_printer_idle(pid, require_plate_clear):
  1467. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1468. continue
  1469. # Check if this printer supports drying
  1470. state = printer_manager.get_status(pid)
  1471. if not state:
  1472. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1473. continue
  1474. model = printer_manager.get_model(pid)
  1475. firmware = state.firmware_version
  1476. if not supports_drying(model, firmware):
  1477. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1478. continue
  1479. # Check each AMS unit from raw_data
  1480. ams_list = state.raw_data.get("ams", [])
  1481. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1482. for ams_data in ams_list:
  1483. module_type = str(ams_data.get("module_type") or "")
  1484. ams_id = int(ams_data.get("id", 0))
  1485. # Only n3f/n3s support drying
  1486. if module_type not in ("n3f", "n3s"):
  1487. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1488. continue
  1489. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  1490. # Most-restrictive of all loaded tray types; falls back to the
  1491. # global threshold when no overrides are configured.
  1492. trays = ams_data.get("tray", []) or []
  1493. humidity_threshold = self.resolve_humidity_threshold(
  1494. trays, per_type_thresholds, global_humidity_threshold
  1495. )
  1496. dry_time = int(ams_data.get("dry_time") or 0)
  1497. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1498. humidity = None
  1499. h_raw = ams_data.get("humidity_raw")
  1500. if h_raw is not None:
  1501. try:
  1502. humidity = int(h_raw)
  1503. except (ValueError, TypeError):
  1504. pass
  1505. if humidity is None:
  1506. h_idx = ams_data.get("humidity")
  1507. if h_idx is not None:
  1508. try:
  1509. humidity = int(h_idx)
  1510. except (ValueError, TypeError):
  1511. pass
  1512. # Already drying — check if humidity dropped below threshold (with minimum drying time)
  1513. if dry_time > 0:
  1514. if pid not in self._drying_in_progress:
  1515. # Drying we didn't start (manual or from before restart) — track but don't stop
  1516. self._drying_in_progress[pid] = time.monotonic()
  1517. started_at = self._drying_in_progress[pid]
  1518. elapsed = time.monotonic() - started_at
  1519. if humidity is not None and humidity <= humidity_threshold and elapsed >= self._min_drying_seconds:
  1520. logger.info(
  1521. "Auto-drying: printer %d AMS %d — humidity %d%% <= threshold %d%% after %dm, stopping drying",
  1522. pid,
  1523. ams_id,
  1524. humidity,
  1525. humidity_threshold,
  1526. int(elapsed / 60),
  1527. )
  1528. printer_manager.send_drying_command(pid, ams_id, temp=0, duration=0, mode=0)
  1529. else:
  1530. logger.debug(
  1531. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%, elapsed %dm/%dm min)",
  1532. pid,
  1533. ams_id,
  1534. dry_time,
  1535. humidity,
  1536. int(elapsed / 60),
  1537. self._min_drying_seconds // 60,
  1538. )
  1539. continue
  1540. # Humidity below threshold — no need to start drying
  1541. if humidity is None or humidity <= humidity_threshold:
  1542. logger.debug(
  1543. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1544. pid,
  1545. ams_id,
  1546. humidity,
  1547. humidity_threshold,
  1548. )
  1549. continue
  1550. # Check cannot-dry reasons (power constraints etc.)
  1551. sf_reasons = ams_data.get("dry_sf_reason", [])
  1552. if sf_reasons:
  1553. logger.debug(
  1554. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1555. pid,
  1556. ams_id,
  1557. sf_reasons,
  1558. )
  1559. continue
  1560. # Get conservative drying params for mixed filaments
  1561. params = self._get_conservative_drying_params(trays, module_type, presets)
  1562. if not params:
  1563. logger.debug(
  1564. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1565. )
  1566. continue
  1567. temp, duration_hours, filament_type = params
  1568. # Start drying
  1569. logger.info(
  1570. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1571. "starting %s drying at %d°C for %dh",
  1572. pid,
  1573. ams_id,
  1574. humidity,
  1575. humidity_threshold,
  1576. filament_type,
  1577. temp,
  1578. duration_hours,
  1579. )
  1580. success = printer_manager.send_drying_command(
  1581. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1582. )
  1583. if success:
  1584. self._drying_in_progress[pid] = time.monotonic()
  1585. def _sync_drying_state(self):
  1586. """Sync in-memory drying state with actual printer status.
  1587. Handles backend restart — if a printer is drying but we don't know about it,
  1588. update our state. If we think it's drying but it's not, clear it.
  1589. """
  1590. to_remove = []
  1591. for pid in self._drying_in_progress:
  1592. state = printer_manager.get_status(pid)
  1593. if not state:
  1594. to_remove.append(pid)
  1595. continue
  1596. # Check if any AMS unit is still drying
  1597. ams_list = state.raw_data.get("ams", [])
  1598. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1599. if not any_drying:
  1600. to_remove.append(pid)
  1601. for pid in to_remove:
  1602. self._drying_in_progress.pop(pid, None)
  1603. async def _stop_drying(self, printer_id: int):
  1604. """Stop all active drying on a printer (print takes priority)."""
  1605. state = printer_manager.get_status(printer_id)
  1606. if not state:
  1607. self._drying_in_progress.pop(printer_id, None)
  1608. return
  1609. ams_list = state.raw_data.get("ams", [])
  1610. for ams_data in ams_list:
  1611. dry_time = int(ams_data.get("dry_time") or 0)
  1612. if dry_time > 0:
  1613. ams_id = int(ams_data.get("id", 0))
  1614. logger.info(
  1615. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1616. printer_id,
  1617. ams_id,
  1618. )
  1619. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1620. self._drying_in_progress.pop(printer_id, None)
  1621. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  1622. """Get all smart plugs associated with a printer."""
  1623. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1624. return list(result.scalars().all())
  1625. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1626. """Turn on smart plug and wait for printer to connect.
  1627. Returns True if printer connected successfully within timeout.
  1628. """
  1629. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1630. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1631. # Check current plug state
  1632. status = await service.get_status(plug)
  1633. if not status.get("reachable"):
  1634. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1635. return False
  1636. # Turn on if not already on
  1637. if status.get("state") != "ON":
  1638. success = await service.turn_on(plug)
  1639. if not success:
  1640. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  1641. return False
  1642. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  1643. # Get printer from database for connection
  1644. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1645. printer = result.scalar_one_or_none()
  1646. if not printer:
  1647. logger.error("Printer %s not found in database", printer_id)
  1648. return False
  1649. # Wait for printer to boot (give it some time before trying to connect)
  1650. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  1651. await asyncio.sleep(30)
  1652. # Try to connect to the printer periodically
  1653. elapsed = 30 # Already waited 30s
  1654. while elapsed < self._power_on_wait_time:
  1655. # Try to connect
  1656. logger.info("Attempting to connect to printer %s...", printer_id)
  1657. try:
  1658. connected = await printer_manager.connect_printer(printer)
  1659. if connected:
  1660. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  1661. # Give it a moment to stabilize and get status
  1662. await asyncio.sleep(5)
  1663. return True
  1664. except Exception as e:
  1665. logger.debug("Connection attempt failed: %s", e)
  1666. await asyncio.sleep(self._power_on_check_interval)
  1667. elapsed += self._power_on_check_interval
  1668. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  1669. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  1670. return False
  1671. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  1672. """Check if the previous print on this printer succeeded.
  1673. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  1674. deliberate action, not a failure, so subsequent items should still
  1675. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  1676. a skip isn't an actual print attempt, so it must not gate downstream
  1677. items — counting it as a failed predecessor was the cascade bug that
  1678. let a single cancellation block 18 items over 3 days for the reporter.
  1679. Only `failed` and `aborted` — real print-attempt failures — block.
  1680. """
  1681. result = await db.execute(
  1682. select(PrintQueueItem)
  1683. .where(PrintQueueItem.printer_id == item.printer_id)
  1684. .where(PrintQueueItem.id != item.id)
  1685. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  1686. .order_by(PrintQueueItem.completed_at.desc())
  1687. .limit(1)
  1688. )
  1689. prev_item = result.scalar_one_or_none()
  1690. # If no previous item, assume success (first in queue)
  1691. if not prev_item:
  1692. return True
  1693. return prev_item.status in ("completed", "cancelled")
  1694. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  1695. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  1696. if not item.auto_off_after:
  1697. return
  1698. plugs = await self._get_smart_plugs(db, item.printer_id)
  1699. plug_ids = [p.id for p in plugs if p.enabled]
  1700. if plug_ids:
  1701. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  1702. # Wait for cooldown (up to 10 minutes)
  1703. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  1704. # Re-fetch plugs in a fresh session after the long cooldown wait
  1705. async with async_session() as new_db:
  1706. for plug_id in plug_ids:
  1707. try:
  1708. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1709. plug = result.scalar_one_or_none()
  1710. if plug and plug.enabled:
  1711. logger.info("Auto-off: Powering off plug '%s' for printer %s", plug.name, item.printer_id)
  1712. service = await smart_plug_manager.get_service_for_plug(plug, new_db)
  1713. await service.turn_off(plug)
  1714. except Exception as e:
  1715. logger.warning(
  1716. "Auto-off: Failed to power off plug %s for printer %s: %s", plug_id, item.printer_id, e
  1717. )
  1718. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  1719. """Get a human-readable name for a queue item."""
  1720. if item.archive_id:
  1721. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1722. archive = result.scalar_one_or_none()
  1723. if archive:
  1724. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1725. if item.library_file_id:
  1726. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1727. library_file = result.scalar_one_or_none()
  1728. if library_file:
  1729. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1730. return f"Job #{item.id}"
  1731. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  1732. """Get printer by ID."""
  1733. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1734. return result.scalar_one_or_none()
  1735. async def _block_on_filament_deficit(
  1736. self,
  1737. db: AsyncSession,
  1738. item: PrintQueueItem,
  1739. ) -> bool:
  1740. """Promote the item to manual_start when the assigned spool is short (#1496).
  1741. Returns True when this dispatch attempt was blocked, False when the
  1742. item is clear to start. A previously-flagged item whose spool has
  1743. since been swapped to one with enough material clears the flag here
  1744. so the next scheduler tick dispatches it.
  1745. """
  1746. # User has explicitly acknowledged the deficit ("Print Anyway") —
  1747. # don't re-flag, don't even compute. Without this short-circuit the
  1748. # scheduler bounces between "user said anyway" (route clears
  1749. # manual_start) and "scheduler re-blocked" (this method re-flags it
  1750. # on identical spool state) (#1698-followup).
  1751. if item.skip_filament_check:
  1752. # #1762 diagnostic: surface the short-circuit at INFO so a
  1753. # future "Print Anyway didn't work" report (e.g. issue #1762
  1754. # comment 3) has actionable evidence in the support bundle
  1755. # without needing DEBUG enabled.
  1756. logger.info(
  1757. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  1758. item.id,
  1759. )
  1760. return False
  1761. try:
  1762. deficit = await compute_deficit_for_queue_item(db, item)
  1763. except Exception as e:
  1764. # Never let a flaky deficit check wedge the queue — log and let
  1765. # dispatch proceed. The PrintModal-side check still runs on the
  1766. # manual paths.
  1767. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  1768. return False
  1769. if deficit:
  1770. item.filament_short = True
  1771. item.manual_start = True
  1772. await db.commit()
  1773. job_name = await self._get_job_name(db, item)
  1774. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  1775. logger.info(
  1776. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  1777. item.id,
  1778. len(deficit),
  1779. )
  1780. try:
  1781. await notification_service.on_queue_job_waiting(
  1782. job_name=job_name,
  1783. target_model=(printer.model if printer else "") or "",
  1784. waiting_reason="filament_short",
  1785. db=db,
  1786. )
  1787. except Exception as e:
  1788. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  1789. return True
  1790. # No deficit — clear any stale flag from a previous tick.
  1791. if item.filament_short:
  1792. item.filament_short = False
  1793. await db.commit()
  1794. return False
  1795. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  1796. """Hand the queue item's owner to printer_manager so the
  1797. print-complete callback can credit the user in PrintLogEntry (#1670).
  1798. No-ops when the item has no `created_by_id` or the referenced user
  1799. row is missing (e.g. user deleted between queue-add and dispatch —
  1800. in that case the print log row falls back to the existing un-credited
  1801. behaviour rather than crashing the dispatch).
  1802. """
  1803. if not item.created_by_id:
  1804. return
  1805. from backend.app.models.user import User
  1806. owner = await db.get(User, item.created_by_id)
  1807. if owner:
  1808. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  1809. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  1810. """Upload file and start print for a queue item.
  1811. Supports two sources:
  1812. - archive_id: Print from an existing archive
  1813. - library_file_id: Print from a library file (file manager)
  1814. """
  1815. logger.info("Starting queue item %s", item.id)
  1816. # Get printer first (needed for both paths)
  1817. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  1818. printer = result.scalar_one_or_none()
  1819. if not printer:
  1820. item.status = "failed"
  1821. item.error_message = "Printer not found"
  1822. item.completed_at = datetime.now(timezone.utc)
  1823. await db.commit()
  1824. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  1825. await self._power_off_if_needed(db, item)
  1826. return
  1827. # Check printer is connected
  1828. if not printer_manager.is_connected(item.printer_id):
  1829. item.status = "failed"
  1830. item.error_message = "Printer not connected"
  1831. item.completed_at = datetime.now(timezone.utc)
  1832. await db.commit()
  1833. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  1834. await self._power_off_if_needed(db, item)
  1835. return
  1836. # Determine source: archive or library file
  1837. archive = None
  1838. library_file = None
  1839. file_path = None
  1840. filename = None
  1841. if item.archive_id:
  1842. # Print from archive
  1843. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1844. archive = result.scalar_one_or_none()
  1845. if not archive:
  1846. item.status = "failed"
  1847. item.error_message = "Archive not found"
  1848. item.completed_at = datetime.now(timezone.utc)
  1849. await db.commit()
  1850. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  1851. await self._power_off_if_needed(db, item)
  1852. return
  1853. file_path = settings.base_dir / archive.file_path
  1854. filename = archive.filename
  1855. elif item.library_file_id:
  1856. # Print from library file (file manager)
  1857. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1858. library_file = result.scalar_one_or_none()
  1859. if not library_file:
  1860. item.status = "failed"
  1861. item.error_message = "Library file not found"
  1862. item.completed_at = datetime.now(timezone.utc)
  1863. await db.commit()
  1864. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  1865. await self._power_off_if_needed(db, item)
  1866. return
  1867. # Library files store absolute paths
  1868. lib_path = Path(library_file.file_path)
  1869. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1870. filename = library_file.filename
  1871. # Create archive from library file so usage tracking has access to the 3MF
  1872. try:
  1873. from backend.app.services.archive import ArchiveService
  1874. archive_service = ArchiveService(db)
  1875. archive = await archive_service.archive_print(
  1876. printer_id=item.printer_id,
  1877. source_file=file_path,
  1878. original_filename=filename,
  1879. created_by_id=item.created_by_id,
  1880. project_id=item.project_id,
  1881. )
  1882. if archive:
  1883. item.archive_id = archive.id
  1884. await db.flush()
  1885. logger.info(
  1886. "Queue item %s: Created archive %s from library file %s",
  1887. item.id,
  1888. archive.id,
  1889. item.library_file_id,
  1890. )
  1891. except Exception as e:
  1892. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  1893. else:
  1894. # Neither archive nor library file specified
  1895. item.status = "failed"
  1896. item.error_message = "No source file specified"
  1897. item.completed_at = datetime.now(timezone.utc)
  1898. await db.commit()
  1899. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  1900. await self._power_off_if_needed(db, item)
  1901. return
  1902. # Check file exists on disk
  1903. if not file_path.exists():
  1904. item.status = "failed"
  1905. item.error_message = "Source file not found on disk"
  1906. item.completed_at = datetime.now(timezone.utc)
  1907. await db.commit()
  1908. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  1909. await self._power_off_if_needed(db, item)
  1910. return
  1911. # G-code injection for auto-print systems (#422)
  1912. injected_path = None
  1913. if item.gcode_injection:
  1914. try:
  1915. snippets_raw = await self._get_setting(db, "gcode_snippets")
  1916. if snippets_raw:
  1917. snippets = json.loads(snippets_raw)
  1918. model_snippets = snippets.get(printer.model, {})
  1919. start_gc = (model_snippets.get("start_gcode") or "").strip()
  1920. end_gc = (model_snippets.get("end_gcode") or "").strip()
  1921. if start_gc or end_gc:
  1922. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  1923. injected_path = inject_gcode_into_3mf(
  1924. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  1925. )
  1926. if injected_path:
  1927. file_path = injected_path
  1928. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  1929. else:
  1930. logger.warning(
  1931. "Queue item %s: G-code injection returned no result, using original", item.id
  1932. )
  1933. except Exception as e:
  1934. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  1935. # Upload to root directory (not /cache/) - the start_print command references
  1936. # files by name only (ftp://{filename}), so they must be in the root
  1937. remote_filename = derive_remote_filename(filename)
  1938. remote_path = f"/{remote_filename}"
  1939. # Get FTP retry settings
  1940. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1941. logger.info(
  1942. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  1943. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1944. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1945. )
  1946. # Delete existing file if present (avoids 553 error on overwrite)
  1947. try:
  1948. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  1949. delete_result = await delete_file_async(
  1950. printer.ip_address,
  1951. printer.access_code,
  1952. remote_path,
  1953. socket_timeout=ftp_timeout,
  1954. printer_model=printer.model,
  1955. )
  1956. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  1957. except Exception as e:
  1958. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  1959. try:
  1960. if ftp_retry_enabled:
  1961. uploaded = await with_ftp_retry(
  1962. upload_file_async,
  1963. printer.ip_address,
  1964. printer.access_code,
  1965. file_path,
  1966. remote_path,
  1967. socket_timeout=ftp_timeout,
  1968. printer_model=printer.model,
  1969. max_retries=ftp_retry_count,
  1970. retry_delay=ftp_retry_delay,
  1971. operation_name=f"Upload print to {printer.name}",
  1972. )
  1973. else:
  1974. uploaded = await upload_file_async(
  1975. printer.ip_address,
  1976. printer.access_code,
  1977. file_path,
  1978. remote_path,
  1979. socket_timeout=ftp_timeout,
  1980. printer_model=printer.model,
  1981. )
  1982. except Exception as e:
  1983. uploaded = False
  1984. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  1985. # Clean up injected temp file after upload attempt
  1986. if injected_path and injected_path.exists():
  1987. injected_path.unlink(missing_ok=True)
  1988. if not uploaded:
  1989. error_msg = (
  1990. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1991. "See server logs for detailed diagnostics."
  1992. )
  1993. item.status = "failed"
  1994. item.error_message = error_msg
  1995. item.completed_at = datetime.now(timezone.utc)
  1996. await db.commit()
  1997. logger.error(
  1998. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  1999. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  2000. )
  2001. # Send failure notification
  2002. await notification_service.on_queue_job_failed(
  2003. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2004. printer_id=printer.id,
  2005. printer_name=printer.name,
  2006. reason="Failed to upload file to printer",
  2007. db=db,
  2008. )
  2009. await self._power_off_if_needed(db, item)
  2010. return
  2011. # Parse AMS mapping if stored
  2012. ams_mapping = None
  2013. if item.ams_mapping:
  2014. try:
  2015. ams_mapping = json.loads(item.ams_mapping)
  2016. except json.JSONDecodeError:
  2017. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  2018. # Register as expected print so we don't create a duplicate archive
  2019. # Only applicable for archive-based prints
  2020. if archive:
  2021. from backend.app.main import register_expected_print
  2022. register_expected_print(
  2023. item.printer_id,
  2024. remote_filename,
  2025. archive.id,
  2026. ams_mapping=ams_mapping,
  2027. created_by_id=item.created_by_id,
  2028. plate_id=item.plate_id,
  2029. )
  2030. # Propagate the queue item's owner into printer_manager so the
  2031. # print-complete callback can credit the user in the PrintLogEntry
  2032. # (#1670). The dispatch path in `background_dispatch.py` does the
  2033. # equivalent for archive/library "Print" flows; the queue path was
  2034. # missing this hop, which left the print log's User column blank
  2035. # for any print started from the queue. `created_by_id` is set
  2036. # either at queue-add time (UI-added items) or when the user
  2037. # clicks the manual-start button (#1670 fix in print_queue.py).
  2038. await self._propagate_owner_to_printer_manager(db, item)
  2039. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  2040. # This prevents phantom reprints if the backend crashes/restarts after the
  2041. # print command is sent but before the status update is committed.
  2042. # If we crash after this commit but before start_print(), the item will be
  2043. # in "printing" status without actually printing - but that's safer than
  2044. # accidentally reprinting the same file hours later.
  2045. item.status = "printing"
  2046. item.started_at = datetime.now(timezone.utc)
  2047. await db.commit()
  2048. # Clear the awaiting-plate-clear flag now that we're starting a new print
  2049. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  2050. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  2051. # Capture state before dispatch so the watchdog can detect whether the
  2052. # printer actually transitioned (#967). Also capture subtask_id so the
  2053. # watchdog can recognise "command landed but state hasn't flipped yet"
  2054. # on slow H2D transitions (#1078).
  2055. pre_status = printer_manager.get_status(item.printer_id)
  2056. pre_state = getattr(pre_status, "state", None) if pre_status else None
  2057. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  2058. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  2059. # #1721: respect the user's explicit timelapse choice. The #1397
  2060. # force-on at dispatch was removed because it caused per-layer nozzle
  2061. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  2062. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  2063. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  2064. # FINISH-state fallback — no need to force a video.
  2065. effective_timelapse = bool(item.timelapse)
  2066. # Start the print with AMS mapping, plate_id and print options.
  2067. # nozzle_mapping rides through verbatim — JSON string captured from
  2068. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  2069. # parses + injects it only for dual-nozzle models so a null on every
  2070. # other model is a transparent pass-through.
  2071. started = printer_manager.start_print(
  2072. item.printer_id,
  2073. remote_filename,
  2074. plate_id=item.plate_id or 1,
  2075. ams_mapping=ams_mapping,
  2076. bed_levelling=item.bed_levelling,
  2077. flow_cali=item.flow_cali,
  2078. vibration_cali=item.vibration_cali,
  2079. layer_inspect=item.layer_inspect,
  2080. timelapse=effective_timelapse,
  2081. use_ams=item.use_ams,
  2082. nozzle_offset_cali=item.nozzle_offset_cali,
  2083. nozzle_mapping=item.nozzle_mapping,
  2084. )
  2085. if started:
  2086. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  2087. # Register the local 3MF in the cover-cache so /cover skips FTP
  2088. # (#1166 follow-up). file_path was resolved earlier from either the
  2089. # archive or the library file row.
  2090. if file_path is not None:
  2091. cache_3mf_download(item.printer_id, remote_filename, file_path)
  2092. # Hold the printer against further dispatches until the watchdog
  2093. # confirms the printer transitioned (or until the hard timeout).
  2094. # Prevents multi-plate batches from triple-dispatching onto the
  2095. # same H2D Pro while it digests the first project_file (#1157).
  2096. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  2097. # Watchdog: if the printer never transitions out of pre_state AND
  2098. # never advances subtask_id, the MQTT publish was accepted locally but
  2099. # didn't reach the printer (half-broken session — same shape as
  2100. # #887/#936). Revert the queue item so the next dispatch can pick it
  2101. # up instead of leaving it stuck in "printing" (#967). subtask_id
  2102. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  2103. # that would otherwise cause the item to re-dispatch as a reprint
  2104. # of the just-finished job (#1078).
  2105. if pre_state:
  2106. spawn_background_task(
  2107. self._watchdog_print_start(
  2108. item.id,
  2109. item.printer_id,
  2110. pre_state,
  2111. pre_subtask_id,
  2112. pre_gcode_file,
  2113. ),
  2114. name=f"watchdog-print-start-{item.id}",
  2115. )
  2116. # Get estimated time for notification
  2117. estimated_time = None
  2118. if archive and archive.print_time_seconds:
  2119. estimated_time = archive.print_time_seconds
  2120. elif library_file and library_file.print_time_seconds:
  2121. estimated_time = library_file.print_time_seconds
  2122. # Send job started notification
  2123. await notification_service.on_queue_job_started(
  2124. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2125. printer_id=printer.id,
  2126. printer_name=printer.name,
  2127. db=db,
  2128. estimated_time=estimated_time,
  2129. )
  2130. # MQTT relay - publish queue job started
  2131. try:
  2132. from backend.app.services.mqtt_relay import mqtt_relay
  2133. await mqtt_relay.on_queue_job_started(
  2134. job_id=item.id,
  2135. filename=filename,
  2136. printer_id=printer.id,
  2137. printer_name=printer.name,
  2138. printer_serial=printer.serial_number,
  2139. )
  2140. except Exception:
  2141. pass # Don't fail if MQTT fails
  2142. else:
  2143. # Clean up uploaded file from SD card to prevent phantom prints
  2144. try:
  2145. await delete_file_async(
  2146. printer.ip_address,
  2147. printer.access_code,
  2148. remote_path,
  2149. printer_model=printer.model,
  2150. )
  2151. except Exception:
  2152. pass # Best-effort — don't fail the error handler
  2153. # Print command failed - revert status
  2154. item.status = "failed"
  2155. item.error_message = "Failed to send print command to printer"
  2156. item.completed_at = datetime.now(timezone.utc)
  2157. await db.commit()
  2158. logger.error(
  2159. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  2160. f"printer_manager.start_print() returned False. "
  2161. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  2162. f"Check printer status and backend logs for details."
  2163. )
  2164. # Send failure notification
  2165. await notification_service.on_queue_job_failed(
  2166. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2167. printer_id=printer.id,
  2168. printer_name=printer.name,
  2169. reason="Failed to send print command to printer - check printer connection and status",
  2170. db=db,
  2171. )
  2172. await self._power_off_if_needed(db, item)
  2173. @staticmethod
  2174. async def _watchdog_print_start(
  2175. queue_item_id: int,
  2176. printer_id: int,
  2177. pre_state: str,
  2178. pre_subtask_id: str | None = None,
  2179. pre_gcode_file: str | None = None,
  2180. timeout: float = 90.0,
  2181. phase_b_timeout: float = 180.0,
  2182. poll_interval: float = 3.0,
  2183. ) -> None:
  2184. """Revert a queue item if the printer never acknowledges the start command.
  2185. Bambuddy optimistically marks the queue item as "printing" right after the
  2186. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  2187. Phase A (up to ``timeout``): wait for either an active-state transition
  2188. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  2189. primary signal; subtask_id advance handles the H2D case where state can
  2190. sit at FINISH for ~50 s after the printer accepted ``project_file``
  2191. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  2192. was lost on a half-broken session (#887/#936) — revert and force
  2193. reconnect (the #967 recovery path).
  2194. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  2195. alone): keep watching for the active-state transition. subtask_id alone
  2196. proves the file landed but not that the printer started — and a printer
  2197. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  2198. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  2199. used to leave the queue item stuck in 'printing' forever because the
  2200. old watchdog returned success as soon as subtask_id advanced. If Phase
  2201. B times out, revert the queue item so the user can retry without
  2202. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  2203. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  2204. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  2205. transitions that also don't emit an early subtask_id tick.
  2206. """
  2207. last_status = None
  2208. landed_on_subtask = False
  2209. deadline = time.monotonic() + timeout
  2210. while time.monotonic() < deadline:
  2211. await asyncio.sleep(poll_interval)
  2212. status = printer_manager.get_status(printer_id)
  2213. if not status:
  2214. # Printer disconnected — don't mess with the DB. Drop the
  2215. # in-memory dispatch hold too so a fresh dispatch can retry
  2216. # once the printer comes back; the hard timeout would
  2217. # otherwise hold the printer unnecessarily.
  2218. scheduler._release_dispatch_hold(printer_id)
  2219. return
  2220. last_status = status
  2221. if status.state in _ACTIVE_PRINT_STATES:
  2222. # Printer is actively processing the job — release the
  2223. # post-dispatch hold so the next pending item for this printer
  2224. # can be evaluated normally. We do NOT accept arbitrary state
  2225. # transitions: a printer going FINISH -> IDLE (user dismissed
  2226. # the post-print prompt without accepting our project_file)
  2227. # would otherwise look like "command landed" and leave the
  2228. # queue item stuck in 'printing' forever (#1370).
  2229. scheduler._release_dispatch_hold(printer_id)
  2230. return
  2231. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  2232. # Phase A exit — printer accepted the file (subtask_id flipped
  2233. # to our submission id). Don't return yet: the printer may
  2234. # have accepted the command but never actually start (e.g.
  2235. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  2236. # B watches for the active-state transition.
  2237. landed_on_subtask = True
  2238. break
  2239. if landed_on_subtask:
  2240. phase_b_deadline = time.monotonic() + phase_b_timeout
  2241. while time.monotonic() < phase_b_deadline:
  2242. await asyncio.sleep(poll_interval)
  2243. status = printer_manager.get_status(printer_id)
  2244. if not status:
  2245. scheduler._release_dispatch_hold(printer_id)
  2246. return
  2247. last_status = status
  2248. if status.state in _ACTIVE_PRINT_STATES:
  2249. scheduler._release_dispatch_hold(printer_id)
  2250. return
  2251. # No active-state transition. Revert the item so the scheduler can retry.
  2252. # Drop the in-memory hold so the retry isn't blocked by it.
  2253. scheduler._release_dispatch_hold(printer_id)
  2254. # Three outcomes from the revert attempt, each routed differently:
  2255. # "reverted": row flipped from printing -> pending, run recovery
  2256. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  2257. # on_print_complete or user). Skip recovery entirely
  2258. # — the print clearly landed somewhere even if the
  2259. # watchdog didn't see the active-state transition.
  2260. # "revert_failed": SQLite contention exhausted retries. Still run
  2261. # recovery so the MQTT session gets a fresh client_id
  2262. # on the half-broken-session path.
  2263. async def _do_revert(db):
  2264. item = await db.get(PrintQueueItem, queue_item_id)
  2265. if not item or item.status != "printing":
  2266. return "already_moved_on"
  2267. item.status = "pending"
  2268. item.started_at = None
  2269. await db.commit()
  2270. return "reverted"
  2271. try:
  2272. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  2273. except Exception as e:
  2274. logger.warning(
  2275. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  2276. "scheduler may keep treating this item as in-flight",
  2277. queue_item_id,
  2278. printer_id,
  2279. e,
  2280. )
  2281. revert_outcome = "revert_failed"
  2282. if revert_outcome == "already_moved_on":
  2283. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  2284. # other path) already moved the item past 'printing', don't run the
  2285. # MQTT session-recovery logic below — a forced reconnect on a healthy
  2286. # session breaks ongoing prints on the same printer.
  2287. return
  2288. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  2289. if revert_outcome == "reverted":
  2290. if landed_on_subtask:
  2291. logger.warning(
  2292. "Queue item %s: printer %d accepted project_file (subtask_id "
  2293. "advanced) but never transitioned to an active state within "
  2294. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  2295. "for retry (#1678)",
  2296. queue_item_id,
  2297. printer_id,
  2298. total_timeout,
  2299. )
  2300. else:
  2301. logger.warning(
  2302. "Queue item %s: printer %d did not respond to print command within "
  2303. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  2304. "for retry (#967)",
  2305. queue_item_id,
  2306. printer_id,
  2307. timeout,
  2308. pre_state,
  2309. pre_subtask_id,
  2310. )
  2311. # Phase B was entered iff subtask_id advanced, which means the
  2312. # project_file landed on the printer. A forced reconnect at this point
  2313. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  2314. # skip the recovery entirely.
  2315. if landed_on_subtask:
  2316. return
  2317. # Phase A timeout path — same #1150 / #887/#936 discriminator as
  2318. # background_dispatch: if the printer's gcode_file changed since
  2319. # pre-dispatch, the project_file command landed and the printer is
  2320. # parsing — a forced reconnect mid-parse triggers 0500_4003. If
  2321. # gcode_file is unchanged, the publish was silently swallowed
  2322. # (#887/#936) and the original force_reconnect recovery is what we
  2323. # want.
  2324. client = printer_manager.get_client(printer_id)
  2325. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  2326. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  2327. if publish_landed:
  2328. logger.warning(
  2329. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  2330. "received the command and is parsing slowly. Skipping forced "
  2331. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  2332. queue_item_id,
  2333. current_gcode_file,
  2334. pre_gcode_file,
  2335. )
  2336. elif client and hasattr(client, "force_reconnect_stale_session"):
  2337. client.force_reconnect_stale_session(
  2338. f"queue print command unacknowledged after {timeout:.0f}s "
  2339. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  2340. )
  2341. # Global scheduler instance
  2342. scheduler = PrintScheduler()