print_scheduler.py 150 KB

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