print_scheduler.py 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134
  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 fastapi import HTTPException
  9. from sqlalchemy import func, select, update
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from sqlalchemy.orm import selectinload
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import async_session, run_with_retry
  14. from backend.app.core.tasks import spawn_background_task
  15. from backend.app.core.websocket import ws_manager
  16. from backend.app.models.archive import PrintArchive
  17. from backend.app.models.library import LibraryFile
  18. from backend.app.models.print_queue import PrintQueueItem
  19. from backend.app.models.printer import Printer
  20. from backend.app.models.settings import Settings
  21. from backend.app.models.smart_plug import SmartPlug
  22. from backend.app.models.spool_assignment import SpoolAssignment
  23. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  24. from backend.app.services.bambu_ftp import (
  25. UploadCancelled,
  26. cache_3mf_download,
  27. delete_file_async,
  28. get_ftp_retry_settings,
  29. upload_file_async,
  30. with_ftp_retry,
  31. )
  32. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  33. from backend.app.services.finance_budget import (
  34. create_budget_reservation,
  35. release_budget_reservation,
  36. validate_print_budget,
  37. )
  38. from backend.app.services.notification_service import notification_service
  39. from backend.app.services.printer_manager import (
  40. printer_manager,
  41. supports_airduct,
  42. supports_chamber_heater,
  43. supports_chamber_temp,
  44. supports_drying,
  45. supports_drying_while_printing,
  46. )
  47. from backend.app.services.smart_plug_manager import smart_plug_manager
  48. from backend.app.utils.filename import derive_remote_filename
  49. from backend.app.utils.printer_models import is_gcode_compatible, normalize_printer_model
  50. logger = logging.getLogger(__name__)
  51. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  52. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  53. # byte gate) from before the scheduler unification. Time gate keeps small
  54. # files from going silent (a single 8 KB chunk fires once and that's it);
  55. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  56. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  57. # sub-200 ms files.
  58. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  59. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  60. class _UploadProgressBridge:
  61. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  62. ``upload_file_async`` runs the FTP transfer in an executor thread and
  63. invokes its ``progress_callback`` from that thread, so the callback
  64. body cannot ``await`` directly. This bridge captures the asyncio loop
  65. at construction (on the scheduler thread) and uses
  66. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  67. matches the legacy background_dispatch.py path 1:1 so the toast feels
  68. identical to the pre-#1625 experience.
  69. Failures inside the emit are swallowed — progress is a UX nicety, the
  70. upload itself must not fail because of a WS hiccup.
  71. """
  72. def __init__(self, user_id: int | None, queue_item_id: int):
  73. self._user_id = user_id
  74. self._queue_item_id = queue_item_id
  75. try:
  76. self._loop = asyncio.get_running_loop()
  77. except RuntimeError:
  78. self._loop = None
  79. self._last_emit_bytes = 0
  80. self._last_emit_monotonic = 0.0
  81. self._has_emitted = False
  82. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  83. if self._loop is None or total_bytes <= 0:
  84. return
  85. now = time.monotonic()
  86. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  87. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  88. # the four matter most: first-call so the user sees something even
  89. # for sub-chunk-size files; uploaded >= total so the bar locks at
  90. # 100% even when the throttle would otherwise eat it.
  91. should_emit = (
  92. not self._has_emitted
  93. or bytes_transferred >= total_bytes
  94. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  95. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  96. )
  97. if not should_emit:
  98. return
  99. self._has_emitted = True
  100. self._last_emit_bytes = bytes_transferred
  101. self._last_emit_monotonic = now
  102. try:
  103. asyncio.run_coroutine_threadsafe(
  104. ws_manager.send_queue_item_upload_progress(
  105. user_id=self._user_id,
  106. queue_item_id=self._queue_item_id,
  107. bytes_transferred=bytes_transferred,
  108. total_bytes=total_bytes,
  109. ),
  110. self._loop,
  111. )
  112. except Exception:
  113. pass # progress is best-effort, never block the upload
  114. # Bambu firmware states that mean the project_file has actually been accepted
  115. # and the printer is now processing / running / paused mid-print. Used by the
  116. # dispatch watchdog (#1370): a transition into one of these states means the
  117. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  118. # a post-print prompt) is NOT a valid "command landed" signal even though the
  119. # state value did change. SLICING is included because some firmwares park
  120. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  121. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  122. # How many times the start-watchdog may revert an item to 'pending' before it
  123. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  124. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  125. # both never recovers and starves the other printers of dispatch slots. Three
  126. # is chosen to clear the transient causes the watchdog already recovers from —
  127. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  128. # force-reconnect on the very next attempt — while still bounding the loop.
  129. DISPATCH_MAX_ATTEMPTS = 3
  130. # Filament type equivalence groups — types within the same group are
  131. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  132. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  133. ["PA-CF", "PA12-CF", "PAHT-CF"],
  134. ]
  135. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  136. for _group in _FILAMENT_TYPE_GROUPS:
  137. _canonical = _group[0].upper()
  138. for _t in _group:
  139. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  140. def _canonical_filament_type(ftype: str) -> str:
  141. """Return canonical type for equivalence matching."""
  142. upper = ftype.upper()
  143. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  144. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  145. """True if ``mapping`` is a non-empty list whose every entry is the
  146. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  147. Such a mapping is a bug artifact: a frontend status-load race can serialize
  148. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  149. recomputed from live status at dispatch rather than trusted, otherwise it
  150. reaches the print command and is silently downgraded to external-spool mode.
  151. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  152. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  153. explicit external selection (``>= 254``) is NOT unresolved either — those
  154. keep their meaning.
  155. """
  156. if not isinstance(mapping, list) or not mapping:
  157. return False
  158. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  159. def _installed_nozzle_diameters(status) -> list[float]:
  160. """Parse the installed nozzle diameters from a PrinterState (#1899).
  161. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  162. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  163. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  164. told us its nozzle hardware" — callers must treat that as unknown, not as a
  165. mismatch, so we never block a print on missing data.
  166. """
  167. diameters: list[float] = []
  168. for nozzle in getattr(status, "nozzles", None) or []:
  169. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  170. try:
  171. value = float(raw)
  172. except (TypeError, ValueError):
  173. continue
  174. if value > 0:
  175. diameters.append(value)
  176. return diameters
  177. def _nozzle_mismatch_message(sliced_nozzle: float | None, installed: list[float]) -> str | None:
  178. """Return an actionable error message when the sliced nozzle can't be
  179. printed on any installed nozzle, else None (#1899).
  180. Fail-safe: returns None whenever we lack the data to judge — no sliced
  181. diameter, or the printer reported no nozzles — so a print is only ever
  182. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  183. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  184. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  185. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  186. """
  187. if not sliced_nozzle or not installed:
  188. return None
  189. if any(abs(d - sliced_nozzle) < 0.05 for d in installed):
  190. return None
  191. installed_str = " / ".join(f"{d:g}mm" for d in installed)
  192. return (
  193. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  194. f"{installed_str} installed. Re-slice for the installed nozzle, or "
  195. f"install the matching nozzle before printing."
  196. )
  197. class PrintScheduler:
  198. """Background scheduler that processes the print queue."""
  199. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  200. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  201. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  202. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  203. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  204. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  205. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  206. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  207. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  208. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  209. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  210. }
  211. def __init__(self):
  212. self._running = False
  213. self._check_interval = 30 # seconds
  214. # After a pass that actually dispatched something, loop again almost
  215. # immediately instead of sleeping the full interval (#2555). A dispatch
  216. # changes printer state — a batch launch fans out over several passes as
  217. # printers free up, a wedged head-of-line job reverts to pending, an
  218. # upload slot opens — and the next batch of ready work should not have to
  219. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  220. # pending items are behind printers that are genuinely busy printing),
  221. # there is nothing to react to, so we fall back to the normal interval;
  222. # that also means this can never tight-loop, since fast ticks only
  223. # continue while dispatches keep happening and the queue is draining.
  224. self._fast_check_interval = 3 # seconds
  225. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  226. self._power_on_check_interval = 10 # seconds between connection checks
  227. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  228. self._drying_in_progress: dict[int, float] = {}
  229. # Defensive in-memory dispatch hold (#1157): a printer that just received
  230. # a project_file command must not get a second dispatch until either it
  231. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  232. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  233. # during that window the DB busy_printers seed is empirically unreliable
  234. # (multi-plate batches double-/triple-dispatched onto the same printer
  235. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  236. # or revert.
  237. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  238. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  239. # Minimum cooldown between dispatches to the same printer (covers the
  240. # H2D's project_file digestion window).
  241. self._dispatch_min_cooldown = 60.0
  242. # Hard timeout — drop the hold even if we never observed a transition,
  243. # so a lost MQTT session can't lock a printer out of the queue forever.
  244. # Matches the watchdog timeout (90 s) plus a safety margin so the
  245. # watchdog runs first on the unhappy path.
  246. self._dispatch_max_hold = 180.0
  247. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  248. # an earlier pass and is still running. `_start_print` flips the row
  249. # pending -> printing only *after* the upload completes, so until then
  250. # the row stays `pending`: each tick, check_queue excludes these
  251. # item_ids from re-selection and their printers from new dispatch /
  252. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  253. # freed slots refill on the next fast tick. check_queue is the sole,
  254. # sequential caller and the prune done-callbacks run in the same
  255. # event-loop thread, so this dict needs no lock.
  256. # item_id -> (task, printer_id)
  257. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  258. # Expected prints registered by `_start_print` that have not yet had a
  259. # print command sent. Populated at registration, dropped once
  260. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  261. # other exit. Same threading argument as `_inflight` above: one
  262. # sequential caller, callbacks on the same loop, so no lock.
  263. # item_id -> (printer_id, remote_filename, archive_id)
  264. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  265. # Budget reservations created for a dispatch whose print command has
  266. # not been confirmed yet. `_dispatch_one` releases these on every
  267. # unsuccessful exit; a successful start removes the item id and leaves
  268. # the reservation for finance_billing to consume with the archive.
  269. self._unconfirmed_budget_reservations: set[int] = set()
  270. async def run(self):
  271. """Main loop - check queue every interval."""
  272. self._running = True
  273. logger.info("Print scheduler started")
  274. await self._clear_stale_dispatch_claims(at_startup=True)
  275. while self._running:
  276. dispatched = False
  277. try:
  278. # No-op while any upload is in flight; on a quiet tick it releases
  279. # a claim whose best-effort clear failed (e.g. the database was
  280. # briefly unreachable), instead of leaving the row wedged until
  281. # the next restart.
  282. await self._clear_stale_dispatch_claims()
  283. dispatched = await self.check_queue()
  284. except Exception as e:
  285. logger.error("Scheduler error: %s", e)
  286. # Re-check quickly after a productive pass so a draining batch does
  287. # not stall behind the idle interval; otherwise sleep normally (#2555).
  288. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  289. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  290. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  291. A claim is only ever held by a live dispatch coroutine, so when this
  292. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  293. is stale. At startup that is trivially true — no coroutine survives a
  294. restart. It is equally true on any later tick where no upload is running,
  295. which is what makes this safe to repeat rather than only run once.
  296. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  297. the database is briefly unreachable at exactly the moment dispatch ends,
  298. the claim survives and the row is wedged out of the selection query. That
  299. used to last until the next restart (#2702 follow-up, seen when
  300. PostgreSQL refused a connection mid-dispatch).
  301. ``_inflight`` is populated when the task is spawned, before the coroutine
  302. claims its row, and pruned by a done-callback that cannot run before the
  303. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  304. race window and needs no age threshold. A size-derived upload deadline
  305. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  306. """
  307. if self._inflight:
  308. return
  309. try:
  310. async with async_session() as db:
  311. res = await db.execute(
  312. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  313. )
  314. await db.commit()
  315. if res.rowcount:
  316. logger.info(
  317. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  318. res.rowcount,
  319. " at startup" if at_startup else "",
  320. )
  321. except Exception as exc:
  322. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  323. def stop(self):
  324. """Stop the scheduler."""
  325. self._running = False
  326. logger.info("Print scheduler stopped")
  327. async def check_queue(self) -> bool:
  328. """Check for prints ready to start.
  329. Returns True if this pass dispatched at least one item, so the caller
  330. can loop again quickly instead of sleeping the full interval (#2555).
  331. """
  332. async with async_session() as db:
  333. # Check if shortest-job-first scheduling is enabled
  334. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  335. # Get all pending items, ordered by printer and position (or SJF order)
  336. if sjf_enabled:
  337. # SJF: group by printer (and target_model for model-based jobs),
  338. # then items already jumped get top priority (starvation guard),
  339. # then sort by print_time ascending. Items with no print time go last.
  340. result = await db.execute(
  341. select(PrintQueueItem)
  342. .where(PrintQueueItem.status == "pending")
  343. # Never re-select a row a dispatch worker has already claimed
  344. # (#2615) — belt-and-suspenders with the _inflight exclusion
  345. # below, and the guard that lets an orphaned claim be ignored
  346. # until startup reconciliation clears it.
  347. .where(PrintQueueItem.dispatching_at.is_(None))
  348. # archive/library_file are read by the cross-model gate
  349. # (#2578); eager-load once per pass instead of a lazy-load
  350. # (which would raise in async) per item.
  351. .options(
  352. selectinload(PrintQueueItem.archive),
  353. selectinload(PrintQueueItem.library_file),
  354. )
  355. .order_by(
  356. PrintQueueItem.printer_id,
  357. PrintQueueItem.target_model,
  358. PrintQueueItem.been_jumped.desc(),
  359. PrintQueueItem.print_time_seconds.asc().nullslast(),
  360. PrintQueueItem.position,
  361. )
  362. )
  363. else:
  364. result = await db.execute(
  365. select(PrintQueueItem)
  366. .where(PrintQueueItem.status == "pending")
  367. # Skip rows already claimed by a dispatch worker (#2615).
  368. .where(PrintQueueItem.dispatching_at.is_(None))
  369. .options(
  370. selectinload(PrintQueueItem.archive),
  371. selectinload(PrintQueueItem.library_file),
  372. )
  373. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  374. )
  375. items = list(result.scalars().all())
  376. # Drop rows whose upload is still in flight from an earlier pass
  377. # (#2602). They stay `pending` until the upload finishes, so without
  378. # this a fast tick would re-select and re-dispatch the same row.
  379. # Belt-and-suspenders with the printer exclusion below.
  380. if self._inflight:
  381. inflight_ids = set(self._inflight)
  382. items = [it for it in items if it.id not in inflight_ids]
  383. # Read plate-clear setting once per queue check. Default MUST be
  384. # False to match the schema (SettingsSchema.require_plate_clear
  385. # defaults False) and the frontend (toggle + card badge both treat a
  386. # missing value as off). When no settings row exists, a True default
  387. # here re-enabled the plate-clear gate the UI showed as disabled,
  388. # blocking dispatch to FINISH-state printers forever with no UI path
  389. # to clear it (#1865).
  390. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  391. if not items:
  392. # No dispatchable pending items — still check auto-drying on idle
  393. # printers, but keep any printer with an upload still in flight
  394. # from an earlier pass out of it (#2602): its print is imminent,
  395. # so it must not be auto-dried in the gap before the row flips to
  396. # printing. Report the pass as productive while uploads run so the
  397. # loop stays on the fast interval.
  398. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  399. await self._check_auto_drying(db, [], inflight_printers, require_plate_clear=require_plate_clear)
  400. return bool(self._inflight)
  401. logger.info(
  402. "Queue check: found %d pending items: %s",
  403. len(items),
  404. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  405. )
  406. # Seed busy_printers with printers that already have an item in 'printing'
  407. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  408. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  409. # lag several seconds behind the print command, so the next check_queue
  410. # tick still sees IDLE and would double-dispatch onto the same printer.
  411. # Without this guard, two pending items targeting the same printer
  412. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  413. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  414. busy_result = await db.execute(
  415. select(PrintQueueItem.printer_id)
  416. .where(PrintQueueItem.status == "printing")
  417. .where(PrintQueueItem.printer_id.is_not(None))
  418. )
  419. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  420. # Defense-in-depth (#1157): augment busy_printers with any printer
  421. # still in its post-dispatch hold window. Empirically, the DB seed
  422. # above can miss in-flight items in a multi-plate batch — same-file
  423. # plates were being dispatched 30 s apart while the H2D was still
  424. # digesting the first project_file. The hold is keyed in-memory and
  425. # released by the watchdog on the success path, so it adds a layer
  426. # that doesn't depend on DB row visibility or completion-callback
  427. # timing.
  428. for held_printer_id in list(self._dispatch_holds.keys()):
  429. if self._printer_in_dispatch_hold(held_printer_id):
  430. busy_printers.add(held_printer_id)
  431. # Exclude printers whose upload is still in flight from an earlier
  432. # pass (#2602). The row is `pending` until the upload finishes and
  433. # the printing-state seed / dispatch hold above only arm once the
  434. # upload completes, so this is what holds the printer (and, via
  435. # busy_printers, its auto-drying) out of the pass during the upload.
  436. for _task, inflight_pid in self._inflight.values():
  437. if inflight_pid is not None:
  438. busy_printers.add(inflight_pid)
  439. # Log skip reasons once per queue check (not per item)
  440. skip_reasons: dict[str, int] = {}
  441. # Items selected for dispatch in this pass, one per printer. The
  442. # loop below only *decides* — the uploads happen afterwards, in
  443. # parallel (#2555). See _dispatch_selected().
  444. dispatch_ids: list[int] = []
  445. # Library rows queued with `cleanup_library_after_dispatch` (the
  446. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  447. # that prints them: the row is deleted and the 3MF is unlinked from
  448. # disk. That was safe only because dispatch was serial. Run two of
  449. # them against the same row at once and the second DELETE matches no
  450. # row (StaleDataError), and the winner's unlink can pull the file out
  451. # from under the loser's in-flight upload.
  452. #
  453. # Only the cleanup flag mutates the row. An ordinary library print
  454. # just reads it, so the common fan-out — one file, many printers,
  455. # which is exactly the reporter's workload — still goes out fully in
  456. # parallel. Narrow the guard to the mutating case; do not serialise
  457. # the case the whole fix exists for.
  458. dispatch_libs: set[int] = set()
  459. consumed_libs: set[int] = set()
  460. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  461. """True if dispatching `candidate` now would race another item's cleanup."""
  462. lib_id = candidate.library_file_id
  463. if lib_id is None:
  464. return False
  465. if candidate.cleanup_library_after_dispatch:
  466. # We would delete a row someone else in this pass is reading.
  467. return lib_id in dispatch_libs
  468. # Someone else in this pass will delete the row out from under us.
  469. return lib_id in consumed_libs
  470. def _claim_library_row(candidate: PrintQueueItem) -> None:
  471. lib_id = candidate.library_file_id
  472. if lib_id is None:
  473. return
  474. dispatch_libs.add(lib_id)
  475. if candidate.cleanup_library_after_dispatch:
  476. consumed_libs.add(lib_id)
  477. for item in items:
  478. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  479. if item.scheduled_time:
  480. sched = item.scheduled_time
  481. if sched.tzinfo is None:
  482. sched = sched.replace(tzinfo=timezone.utc)
  483. if sched > datetime.now(timezone.utc):
  484. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  485. continue
  486. # Skip items that require manual start
  487. if item.manual_start:
  488. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  489. continue
  490. if item.printer_id:
  491. # Specific printer assignment (existing behavior)
  492. if item.printer_id in busy_printers:
  493. continue
  494. # Check if printer is idle
  495. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  496. printer_connected = printer_manager.is_connected(item.printer_id)
  497. # If printer not connected, try to power on via smart plug
  498. if not printer_connected:
  499. plugs = await self._get_smart_plugs(db, item.printer_id)
  500. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  501. if auto_on_plugs:
  502. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  503. # Power on using the plug that actually feeds the printer, and
  504. # wait for it to boot on that one only (#2629).
  505. primary_plug = self._pick_power_plug(auto_on_plugs)
  506. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  507. if powered_on:
  508. # Also turn on any remaining auto_on plugs (e.g., filter)
  509. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  510. try:
  511. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  512. await service.turn_on(extra_plug)
  513. logger.info(
  514. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  515. )
  516. except Exception as e:
  517. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  518. printer_connected = True
  519. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  520. else:
  521. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  522. busy_printers.add(item.printer_id)
  523. continue
  524. else:
  525. # No plug or auto_on disabled
  526. busy_printers.add(item.printer_id)
  527. continue
  528. # Check if printer is idle (busy with another print)
  529. if not printer_idle:
  530. # If printer is drying (not truly busy), handle based on queue_drying_block
  531. if self._drying_in_progress.get(item.printer_id):
  532. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  533. if block_for_drying:
  534. # Drying blocks queue — skip this printer
  535. busy_printers.add(item.printer_id)
  536. continue
  537. else:
  538. # Print takes priority — stop drying
  539. await self._stop_drying(item.printer_id)
  540. # Re-check idle after stopping drying
  541. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  542. if not printer_idle:
  543. busy_printers.add(item.printer_id)
  544. continue
  545. else:
  546. busy_printers.add(item.printer_id)
  547. continue
  548. # Check condition (previous print success)
  549. if item.require_previous_success:
  550. if not await self._check_previous_success(db, item):
  551. item.status = "skipped"
  552. item.error_message = "Previous print failed or was aborted"
  553. item.completed_at = datetime.now(timezone.utc)
  554. await db.commit()
  555. logger.info("Skipped queue item %s - previous print failed", item.id)
  556. # Send notification
  557. job_name = await self._get_job_name(db, item)
  558. printer = await self._get_printer(db, item.printer_id)
  559. await notification_service.on_queue_job_skipped(
  560. job_name=job_name,
  561. printer_id=item.printer_id,
  562. printer_name=printer.name if printer else "Unknown",
  563. reason="Previous print failed or was aborted",
  564. db=db,
  565. )
  566. continue
  567. # Resolve the AMS mapping when it's missing OR unresolved
  568. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  569. # frontend status-load race can persist [-1] (#2589) — and
  570. # must be recomputed from live trays rather than trusted.
  571. await self._ensure_ams_mapping(db, item.printer_id, item)
  572. # Filament-deficit pre-dispatch check (#1496). If the
  573. # assigned spool can't satisfy any required slot grams,
  574. # promote the item to manual_start so the user must
  575. # acknowledge via the ▶ button (which re-checks live).
  576. if await self._block_on_filament_deficit(db, item):
  577. continue
  578. # Hold this item back for the next pass rather than racing
  579. # another dispatch over the same transient library row. The
  580. # printer is still marked busy so a later item does not jump
  581. # its place in this printer's queue.
  582. if _library_row_conflict(item):
  583. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  584. busy_printers.add(item.printer_id)
  585. continue
  586. # Queue the dispatch instead of running it here — see
  587. # _dispatch_selected(). busy_printers still gets the printer
  588. # immediately, so nothing else in this pass can target it.
  589. _claim_library_row(item)
  590. dispatch_ids.append(item.id)
  591. busy_printers.add(item.printer_id)
  592. # SJF starvation guard: mark items that were jumped
  593. if sjf_enabled and item.print_time_seconds is not None:
  594. for other in items:
  595. if (
  596. other.id != item.id
  597. and other.status == "pending"
  598. and other.printer_id == item.printer_id
  599. and not other.been_jumped
  600. and other.position < item.position
  601. and (
  602. other.print_time_seconds is None
  603. or other.print_time_seconds > item.print_time_seconds
  604. )
  605. ):
  606. other.been_jumped = True
  607. await db.commit()
  608. elif item.target_model:
  609. # Model-based assignment - find any idle printer of matching model
  610. # Parse required filament types if present
  611. required_types = None
  612. if item.required_filament_types:
  613. try:
  614. required_types = json.loads(item.required_filament_types)
  615. except json.JSONDecodeError:
  616. pass # Ignore malformed filament types; treat as no constraint
  617. # Parse filament overrides if present
  618. filament_overrides = None
  619. if item.filament_overrides:
  620. try:
  621. filament_overrides = json.loads(item.filament_overrides)
  622. except json.JSONDecodeError:
  623. pass
  624. # If overrides exist, use override types for validation instead
  625. effective_types = required_types
  626. if filament_overrides:
  627. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  628. if override_types:
  629. # Merge: keep original types for non-overridden slots, add override types
  630. effective_types = sorted(set(required_types or []) | set(override_types))
  631. # Cross-model safety gate (#2578): never hand a 3MF sliced
  632. # for an incompatible model to a printer, no matter how the
  633. # row got into the DB (old rows, direct API writes). Held
  634. # as pending with an actionable waiting_reason — the user
  635. # fixes it by editing the item's target model.
  636. sliced_for = None
  637. if item.archive:
  638. sliced_for = item.archive.sliced_for_model
  639. elif item.library_file and item.library_file.file_metadata:
  640. sliced_for = item.library_file.file_metadata.get("sliced_for_model")
  641. if not is_gcode_compatible(sliced_for, item.target_model):
  642. printer_id = None
  643. waiting_reason = (
  644. f"File was sliced for {sliced_for}, which is not compatible with "
  645. f"{item.target_model} — edit the item and fix its target model"
  646. )
  647. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  648. else:
  649. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  650. db,
  651. item.target_model,
  652. busy_printers,
  653. effective_types,
  654. item.target_location,
  655. filament_overrides=filament_overrides,
  656. require_plate_clear=require_plate_clear,
  657. )
  658. # Update waiting_reason if changed and send notification when first waiting
  659. if item.waiting_reason != waiting_reason:
  660. was_waiting = item.waiting_reason is not None
  661. item.waiting_reason = waiting_reason
  662. await db.commit()
  663. # Send waiting notification only when transitioning to waiting state
  664. # and the reason requires user action (not just "all printers busy")
  665. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  666. job_name = await self._get_job_name(db, item)
  667. await notification_service.on_queue_job_waiting(
  668. job_name=job_name,
  669. target_model=item.target_model,
  670. waiting_reason=waiting_reason,
  671. db=db,
  672. )
  673. if printer_id:
  674. # Before claiming the printer: hold back rather than race
  675. # another dispatch over the same transient library row.
  676. # Checked here so a held item does not get a printer
  677. # assigned and then sit on it. See _library_row_conflict().
  678. #
  679. # No busy_printers.add() here, unlike the fixed-printer
  680. # branch above: that one protects its printer's own queue
  681. # ordering, but this item was never assigned to `printer_id`
  682. # — the matcher merely offered it. Marking it busy would
  683. # strand an idle printer for the rest of the pass.
  684. if _library_row_conflict(item):
  685. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  686. continue
  687. # Check condition (previous print success) before assigning
  688. if item.require_previous_success:
  689. if not await self._check_previous_success(db, item):
  690. item.status = "skipped"
  691. item.error_message = "Previous print failed or was aborted"
  692. item.completed_at = datetime.now(timezone.utc)
  693. await db.commit()
  694. logger.info("Skipped queue item %s - previous print failed", item.id)
  695. # Send notification
  696. job_name = await self._get_job_name(db, item)
  697. printer = await self._get_printer(db, printer_id)
  698. await notification_service.on_queue_job_skipped(
  699. job_name=job_name,
  700. printer_id=printer_id,
  701. printer_name=printer.name if printer else "Unknown",
  702. reason="Previous print failed or was aborted",
  703. db=db,
  704. )
  705. continue
  706. # Assign printer and start - clear waiting reason
  707. item.printer_id = printer_id
  708. item.waiting_reason = None
  709. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  710. # Send assignment notification
  711. job_name = await self._get_job_name(db, item)
  712. printer = await self._get_printer(db, printer_id)
  713. await notification_service.on_queue_job_assigned(
  714. job_name=job_name,
  715. printer_id=printer_id,
  716. printer_name=printer.name if printer else "Unknown",
  717. target_model=item.target_model,
  718. db=db,
  719. )
  720. # Resolve the AMS mapping for the assigned printer when it's
  721. # missing OR unresolved (all -1). Critical for model-based
  722. # jobs where mapping wasn't computed upfront, and it also
  723. # self-heals a bogus stored [-1] (#2589).
  724. await self._ensure_ams_mapping(db, printer_id, item)
  725. # Filament-deficit pre-dispatch check (#1496).
  726. if await self._block_on_filament_deficit(db, item):
  727. continue
  728. _claim_library_row(item)
  729. dispatch_ids.append(item.id)
  730. busy_printers.add(printer_id)
  731. # SJF starvation guard: mark model-based items that were jumped
  732. if sjf_enabled and item.print_time_seconds is not None:
  733. for other in items:
  734. if (
  735. other.id != item.id
  736. and other.status == "pending"
  737. and other.printer_id is None
  738. and other.target_model
  739. and other.target_model.upper() == item.target_model.upper()
  740. and not other.been_jumped
  741. and other.position < item.position
  742. and (
  743. other.print_time_seconds is None
  744. or other.print_time_seconds > item.print_time_seconds
  745. )
  746. ):
  747. other.been_jumped = True
  748. await db.commit()
  749. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  750. # as long as the slowest upload takes (minutes on a big 3MF), and a
  751. # skip summary that only lands after the transfers have finished is
  752. # useless for working out why an item did not go out.
  753. if skip_reasons:
  754. logger.info("Queue skip summary: %s", skip_reasons)
  755. if busy_printers:
  756. # Log why each printer was busy (first time it was checked)
  757. for pid in busy_printers:
  758. state = printer_manager.get_status(pid)
  759. connected = printer_manager.is_connected(pid)
  760. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  761. state_name = state.state if state else "NO_STATUS"
  762. logger.info(
  763. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  764. pid,
  765. connected,
  766. state_name,
  767. awaiting,
  768. )
  769. # Read the concurrency limit BEFORE the commit below, not inside
  770. # _dispatch_selected(). A SELECT on this session after the commit
  771. # implicitly opens a fresh transaction that nothing then closes, and
  772. # it would stay open for the whole dispatch — minutes of "idle in
  773. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  774. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  775. # checkpointed while every dispatch is writing to it.
  776. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  777. # Selection is done; every decision above is recorded on `db`
  778. # (model-based printer assignment, computed ams_mapping). Flush it
  779. # before the dispatch tasks open their own sessions, or they will
  780. # read a row that still says printer_id=None. This also releases the
  781. # connection back to the pool for the duration of the dispatch.
  782. await db.commit()
  783. if dispatch_ids:
  784. item_printers = {it.id: it.printer_id for it in items}
  785. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  786. # Auto-drying: start drying on idle printers that have no pending queue items
  787. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  788. # Keep the loop on the fast interval while any upload is in flight so
  789. # a slot freed mid-tick refills within seconds rather than after the
  790. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  791. # deferred because the pool was full) also counts as productive.
  792. return bool(dispatch_ids) or bool(self._inflight)
  793. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  794. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  795. Dispatch used to happen inline in the selection loop: ``await
  796. _start_print(db, item)`` per item in turn. Since ``_start_print``
  797. performs the FTP upload, that serialized every printer behind every
  798. other printer's transfer even though the printers are independent
  799. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  800. gather was awaited before ``check_queue`` returned, so the run loop
  801. stayed blocked until the *slowest* upload in the batch finished — a
  802. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  803. 93-printer farm even as other printers came free (#2602).
  804. Each upload now runs as an independent background task tracked in
  805. ``self._inflight``. check_queue excludes in-flight item_ids (still
  806. `pending` until their upload completes) and their printers from the
  807. next pass's selection, and this method launches at most
  808. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  809. the next fast tick instead of waiting out the whole batch. The bound
  810. exists because the printers are independent but the host is not: each
  811. in-flight upload holds a thread in the FTP pool, a TLS session and a
  812. file handle.
  813. The no-overlapping-dispatch invariant the batch-await used to provide
  814. is now carried by the in-flight exclusion in check_queue. Everything
  815. else — the pending->printing CAS, the busy-printer guard (#2598), the
  816. per-printer hold, and each item's independent failure handling — still
  817. lives in ``_start_print`` and runs per task exactly as before.
  818. Synchronous on purpose: it registers every launched task into
  819. ``self._inflight`` before returning, so the next (sequential) tick sees
  820. an accurate in-flight count with no interleaving await.
  821. """
  822. free = limit - len(self._inflight)
  823. if free <= 0:
  824. logger.info(
  825. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  826. len(self._inflight),
  827. limit,
  828. len(item_ids),
  829. item_ids,
  830. )
  831. return
  832. to_launch = item_ids[:free]
  833. deferred = item_ids[free:]
  834. logger.info(
  835. "Launching %d upload(s) (pool %d/%d in flight)%s",
  836. len(to_launch),
  837. len(self._inflight),
  838. limit,
  839. f" — deferring {deferred} to a later tick" if deferred else "",
  840. )
  841. for item_id in to_launch:
  842. task = spawn_background_task(self._dispatch_one(item_id), name=f"queue-upload-{item_id}")
  843. self._inflight[item_id] = (task, item_printers.get(item_id))
  844. # Prune on completion so the freed slot is refillable next tick.
  845. # spawn_background_task already logs any uncaught exception; this
  846. # only reclaims the pool slot (fires on success, failure, or cancel).
  847. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  848. async def _dispatch_one(self, item_id: int) -> None:
  849. """Upload + start one queue item in its own session (pool worker, #2602).
  850. Its own session: pool workers run concurrently and an AsyncSession is
  851. not safe to share across tasks; it also keeps a slow upload from pinning
  852. the scheduler's session (and, on SQLite, its transaction) open for the
  853. transfer's duration.
  854. """
  855. async with async_session() as item_db:
  856. # Claim the row for dispatch BEFORE reading the printer snapshot or
  857. # touching any slow I/O (#2615). The claim is an atomic CAS on
  858. # (status='pending', dispatching_at IS NULL); while it's held the edit
  859. # routes reject reassignment (409), so printer_id can't change out from
  860. # under the in-flight upload and split the queue row from the
  861. # archive/expected-print/physical command.
  862. if not await self._claim_for_dispatch(item_db, item_id):
  863. logger.info(
  864. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  865. item_id,
  866. )
  867. return
  868. try:
  869. item = await item_db.get(PrintQueueItem, item_id)
  870. if not item:
  871. logger.info("Queue item %s vanished after claim — skipping", item_id)
  872. return
  873. await self._start_print(item_db, item)
  874. finally:
  875. # Undo an expected-print registration whose print command never
  876. # went out. One choke point covers every way `_start_print` can
  877. # end without sending: a raised exception (a DB failure mid-
  878. # dispatch is the reported case), an early return, a cancel
  879. # winning the #1853 CAS, or `start_print()` returning False.
  880. # A confirmed send removes the entry itself, so this is a no-op
  881. # on the happy path.
  882. self._rollback_unconfirmed_expected_print(item_id)
  883. # Mirror the pre-#1625 background-dispatch lifecycle: a
  884. # reservation survives only after start_print() accepted the
  885. # command. Failure, cancellation, deferral, and exceptions all
  886. # release it here.
  887. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_db, item_id))
  888. # Release the claim on every exit. Once dispatch has finished the
  889. # row's status carries the lock (printing/failed/cancelled are all
  890. # != pending), so the token is only needed for the duration of the
  891. # upload. A row left pending (e.g. busy-printer deferral) becomes
  892. # dispatchable again on the next tick.
  893. await self._clear_dispatch_claim(item_db, item_id)
  894. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  895. """Drop an expectation for a print command that was never sent.
  896. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  897. where the interesting exception is usually the one already propagating.
  898. """
  899. pending = self._unconfirmed_expected_print.pop(item_id, None)
  900. if pending is None:
  901. return
  902. printer_id, remote_filename, archive_id = pending
  903. try:
  904. from backend.app.main import unregister_expected_print
  905. unregister_expected_print(printer_id, remote_filename, archive_id)
  906. except Exception:
  907. logger.warning(
  908. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  909. item_id,
  910. printer_id,
  911. remote_filename,
  912. archive_id,
  913. exc_info=True,
  914. )
  915. async def _release_unconfirmed_budget_reservation(self, db: AsyncSession, item_id: int) -> None:
  916. """Release a queue reservation when dispatch ended before MQTT send."""
  917. if item_id not in self._unconfirmed_budget_reservations:
  918. return
  919. for attempt in range(1, 4):
  920. try:
  921. await db.rollback()
  922. await release_budget_reservation(
  923. db,
  924. source_type="print_queue",
  925. source_id=item_id,
  926. status="released",
  927. )
  928. await db.commit()
  929. self._unconfirmed_budget_reservations.discard(item_id)
  930. return
  931. except Exception as exc:
  932. try:
  933. await db.rollback()
  934. except Exception:
  935. pass
  936. if attempt == 3:
  937. logger.error(
  938. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  939. item_id,
  940. attempt,
  941. exc,
  942. )
  943. return
  944. await asyncio.sleep(0.5 * attempt)
  945. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  946. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  947. Returns True if this call won the claim, False if the row was already
  948. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  949. the load-bearing guard against reassign-during-dispatch (#2615)."""
  950. res = await db.execute(
  951. update(PrintQueueItem)
  952. .where(PrintQueueItem.id == item_id)
  953. .where(PrintQueueItem.status == "pending")
  954. .where(PrintQueueItem.dispatching_at.is_(None))
  955. .values(dispatching_at=datetime.now(timezone.utc))
  956. )
  957. await db.commit()
  958. return res.rowcount > 0
  959. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  960. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  961. mask the dispatch outcome.
  962. Retried, because the failure mode in practice is transient and narrow: a
  963. database that is momentarily unreachable — PostgreSQL out of connection
  964. slots is the observed case — refuses this write for a second or two while
  965. the dispatch that just ended is still holding the row out of the selection
  966. query. One attempt was enough to wedge the item; a couple of spaced
  967. attempts clear it. Each attempt rolls back first, since a failed write
  968. leaves the session needing it before it can be reused.
  969. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  970. on the next quiet tick.
  971. """
  972. for attempt in range(1, 4):
  973. try:
  974. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  975. await db.commit()
  976. return
  977. except Exception as exc:
  978. try:
  979. await db.rollback()
  980. except Exception:
  981. pass
  982. if attempt == 3:
  983. logger.warning(
  984. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  985. "— a later quiet tick will release it",
  986. item_id,
  987. attempt,
  988. exc,
  989. )
  990. return
  991. await asyncio.sleep(0.5 * attempt)
  992. async def _find_idle_printer_for_model(
  993. self,
  994. db: AsyncSession,
  995. model: str,
  996. exclude_ids: set[int],
  997. required_filament_types: list[str] | None = None,
  998. target_location: str | None = None,
  999. filament_overrides: list[dict] | None = None,
  1000. require_plate_clear: bool = True,
  1001. ) -> tuple[int | None, str | None]:
  1002. """Find an idle, connected printer matching the model with compatible filaments.
  1003. Args:
  1004. db: Database session
  1005. model: Printer model to match (e.g., "X1C", "P1S")
  1006. exclude_ids: Printer IDs to exclude (already busy)
  1007. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  1008. If provided, only printers with all required types loaded will match.
  1009. target_location: Optional location filter. If provided, only printers in this location are considered.
  1010. filament_overrides: Optional list of override dicts. Each entry may include
  1011. ``force_color_match: true`` to require an exact type+color match
  1012. on the printer for that slot. Without the flag the existing
  1013. colour-preference logic applies.
  1014. Returns:
  1015. Tuple of (printer_id, waiting_reason):
  1016. - (printer_id, None) if a matching printer was found
  1017. - (None, reason) if no printer is available, with explanation
  1018. """
  1019. # Normalize model name and use case-insensitive matching
  1020. normalized_model = normalize_printer_model(model) or model
  1021. query = (
  1022. select(Printer)
  1023. .where(func.lower(Printer.model) == normalized_model.lower())
  1024. .where(Printer.is_active == True) # noqa: E712
  1025. )
  1026. # Add location filter if specified
  1027. if target_location:
  1028. query = query.where(Printer.location == target_location)
  1029. result = await db.execute(query)
  1030. printers = list(result.scalars().all())
  1031. location_suffix = f" in {target_location}" if target_location else ""
  1032. if not printers:
  1033. return None, f"No active {normalized_model} printers{location_suffix} configured"
  1034. # Separate force-matched overrides from preference-only overrides
  1035. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  1036. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  1037. # Track reasons for skipping printers
  1038. printers_busy = []
  1039. printers_offline = []
  1040. printers_missing_filament: list[tuple[str, list[str]]] = []
  1041. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  1042. for printer in printers:
  1043. if printer.id in exclude_ids:
  1044. # Printer is already claimed by another job in this scheduling run.
  1045. # For force-color jobs, still check if the color would match — if not,
  1046. # report it as a color mismatch rather than plain "Busy" so the user
  1047. # knows the job needs a filament change, not just to wait for availability.
  1048. if force_overrides and not pref_overrides:
  1049. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1050. if missing_colors:
  1051. printers_missing_filament.append((printer.name, missing_colors))
  1052. continue
  1053. printers_busy.append(printer.name)
  1054. continue
  1055. is_connected = printer_manager.is_connected(printer.id)
  1056. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  1057. if not is_connected:
  1058. printers_offline.append(printer.name)
  1059. continue
  1060. if not is_idle:
  1061. # Printer is currently printing. For force-color jobs, check whether the
  1062. # loaded color would satisfy the requirement — if not, surface it as a
  1063. # color-mismatch reason rather than plain "Busy" so the user understands
  1064. # that the job is waiting for a filament change, not just printer availability.
  1065. if force_overrides and not pref_overrides:
  1066. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1067. if missing_colors:
  1068. printers_missing_filament.append((printer.name, missing_colors))
  1069. logger.debug(
  1070. "Printer %s (%s) is busy but also has wrong force-color: %s",
  1071. printer.id,
  1072. printer.name,
  1073. missing_colors,
  1074. )
  1075. continue
  1076. printers_busy.append(printer.name)
  1077. continue
  1078. # Validate filament compatibility if required types are specified
  1079. if required_filament_types:
  1080. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  1081. if missing:
  1082. # When force_overrides are present, enrich missing entries with color info
  1083. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  1084. if force_overrides:
  1085. force_color_map = {
  1086. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  1087. for o in force_overrides
  1088. }
  1089. missing_enriched = [
  1090. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  1091. for t in missing
  1092. ]
  1093. printers_missing_filament.append((printer.name, missing_enriched))
  1094. else:
  1095. printers_missing_filament.append((printer.name, missing))
  1096. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  1097. continue
  1098. # Force color match: ALL flagged slots must have an exact type+color match
  1099. if force_overrides:
  1100. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1101. if missing_colors:
  1102. printers_missing_filament.append((printer.name, missing_colors))
  1103. logger.debug(
  1104. "Skipping printer %s (%s) - missing force-matched colors: %s",
  1105. printer.id,
  1106. printer.name,
  1107. missing_colors,
  1108. )
  1109. continue
  1110. # If preference-only overrides exist, rank by color matches (existing behaviour)
  1111. if pref_overrides:
  1112. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  1113. if color_matches > 0:
  1114. candidates.append((printer.id, color_matches))
  1115. else:
  1116. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  1117. printers_missing_filament.append((printer.name, override_colors))
  1118. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  1119. continue
  1120. elif force_overrides:
  1121. # Passed all force checks — immediately eligible (no preference ordering needed)
  1122. return printer.id, None
  1123. else:
  1124. # No overrides at all - take first available (existing behavior)
  1125. return printer.id, None
  1126. # If we have candidates from preference override matching, pick the one with most color matches
  1127. if candidates:
  1128. candidates.sort(key=lambda c: c[1], reverse=True)
  1129. return candidates[0][0], None
  1130. # Build waiting reason from what we found
  1131. reasons = []
  1132. if printers_missing_filament:
  1133. # Filament/color mismatch is most actionable - show first
  1134. if force_overrides and not pref_overrides:
  1135. # All mismatches are force-color failures — use descriptive message only;
  1136. # but only if there are no busy printers that DO have the matching color.
  1137. # If a printer has the right color but is busy, surface "Busy" instead so
  1138. # the user knows the job will start automatically once that printer is free.
  1139. if not printers_busy:
  1140. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  1141. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  1142. # else: fall through — printers_busy will be appended below
  1143. else:
  1144. names_and_missing = [
  1145. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  1146. ]
  1147. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  1148. if printers_busy:
  1149. reasons.append(f"Busy: {', '.join(printers_busy)}")
  1150. if printers_offline:
  1151. reasons.append(f"Offline: {', '.join(printers_offline)}")
  1152. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  1153. @staticmethod
  1154. def _is_busy_only(waiting_reason: str) -> bool:
  1155. """Check if the waiting reason only contains 'Busy' entries.
  1156. When all matching printers are simply busy printing, the queued job
  1157. will start automatically once a printer finishes — no user action
  1158. is required, so we skip the notification.
  1159. """
  1160. parts = [p.strip() for p in waiting_reason.split(" | ")]
  1161. return all(p.startswith("Busy:") for p in parts)
  1162. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  1163. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  1164. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  1165. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  1166. with an exact type+color match.
  1167. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  1168. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  1169. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  1170. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  1171. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  1172. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  1173. setups are unaffected.
  1174. Returns:
  1175. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  1176. """
  1177. status = printer_manager.get_status(printer_id)
  1178. if not status:
  1179. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  1180. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  1181. loaded: list[tuple[str, str, str]] = []
  1182. for ams_unit in status.raw_data.get("ams", []):
  1183. for tray in ams_unit.get("tray", []):
  1184. tray_type = tray.get("tray_type")
  1185. if tray_type:
  1186. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1187. loaded.append(
  1188. (_canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or "")
  1189. )
  1190. for vt in status.raw_data.get("vt_tray") or []:
  1191. vt_type = vt.get("tray_type")
  1192. if vt_type:
  1193. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1194. loaded.append((_canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  1195. missing = []
  1196. for o in force_overrides:
  1197. o_type = _canonical_filament_type(o.get("type") or "")
  1198. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1199. o_idx = o.get("tray_info_idx") or ""
  1200. satisfied = any(
  1201. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  1202. for t_type, t_color, t_idx in loaded
  1203. )
  1204. if not satisfied:
  1205. color_label = o.get("color_name") or o.get("color", "?")
  1206. missing.append(f"{o_type} ({color_label})")
  1207. return missing
  1208. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  1209. """Get the list of required filament types that are not loaded on the printer.
  1210. Args:
  1211. printer_id: The printer ID
  1212. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  1213. Returns:
  1214. List of missing filament types (empty if all are loaded)
  1215. """
  1216. status = printer_manager.get_status(printer_id)
  1217. if not status:
  1218. return required_types # Can't determine, assume all missing
  1219. # Collect all filament types loaded on this printer (AMS units + external spool)
  1220. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  1221. loaded_types: set[str] = set()
  1222. # Check AMS units (stored in raw_data["ams"])
  1223. ams_data = status.raw_data.get("ams", [])
  1224. if ams_data:
  1225. for ams_unit in ams_data:
  1226. for tray in ams_unit.get("tray", []):
  1227. tray_type = tray.get("tray_type")
  1228. if tray_type:
  1229. loaded_types.add(_canonical_filament_type(tray_type))
  1230. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  1231. for vt in status.raw_data.get("vt_tray") or []:
  1232. vt_type = vt.get("tray_type")
  1233. if vt_type:
  1234. loaded_types.add(_canonical_filament_type(vt_type))
  1235. # Find which required types are missing (using canonical type for equivalence)
  1236. missing = []
  1237. for req_type in required_types:
  1238. if _canonical_filament_type(req_type) not in loaded_types:
  1239. missing.append(req_type)
  1240. return missing
  1241. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  1242. """Count how many filament overrides have an exact color match on the printer.
  1243. Used to prefer printers that already have the desired override colors loaded.
  1244. """
  1245. status = printer_manager.get_status(printer_id)
  1246. if not status:
  1247. return 0
  1248. # Collect loaded filaments' type+color pairs
  1249. loaded: set[tuple[str, str]] = set()
  1250. for ams_unit in status.raw_data.get("ams", []):
  1251. for tray in ams_unit.get("tray", []):
  1252. tray_type = tray.get("tray_type")
  1253. tray_color = tray.get("tray_color", "")
  1254. if tray_type:
  1255. color_norm = tray_color.replace("#", "").lower()[:6]
  1256. loaded.add((tray_type.upper(), color_norm))
  1257. for vt in status.raw_data.get("vt_tray") or []:
  1258. vt_type = vt.get("tray_type")
  1259. if vt_type:
  1260. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1261. loaded.add((vt_type.upper(), color_norm))
  1262. matches = 0
  1263. for o in overrides:
  1264. o_type = (o.get("type") or "").upper()
  1265. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1266. if (o_type, o_color) in loaded:
  1267. matches += 1
  1268. return matches
  1269. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> None:
  1270. """Ensure the queue item carries a usable AMS mapping before dispatch.
  1271. Recomputes from live printer status when the stored mapping is missing OR
  1272. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  1273. frontend status-load race can serialize [-1] before the printer's AMS
  1274. trays are known (#2589) — and must not be trusted: downstream it would be
  1275. silently downgraded to external-spool mode and print against an empty
  1276. feed. A resolved mapping (including manual overrides, or a partially
  1277. padded one) is left untouched.
  1278. When recompute cannot resolve it either (no compatible tray loaded), the
  1279. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  1280. external selection; the print command then keeps use_ams=True and the
  1281. firmware surfaces a clear AMS-mapping error instead of silently printing
  1282. to the empty external feed.
  1283. """
  1284. stored_mapping: list | None = None
  1285. if item.ams_mapping:
  1286. try:
  1287. stored_mapping = json.loads(item.ams_mapping)
  1288. except (json.JSONDecodeError, TypeError):
  1289. stored_mapping = None
  1290. # Already resolved (present and not all-unresolved) — keep as-is so a
  1291. # user's manual mapping is never overwritten.
  1292. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  1293. return
  1294. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  1295. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  1296. item.ams_mapping = json.dumps(computed_mapping)
  1297. logger.info(
  1298. "Queue item %s: Computed AMS mapping for printer %s: %s",
  1299. item.id,
  1300. printer_id,
  1301. computed_mapping,
  1302. )
  1303. await db.commit()
  1304. elif _mapping_is_all_unresolved(stored_mapping):
  1305. logger.warning(
  1306. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  1307. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  1308. item.id,
  1309. stored_mapping,
  1310. printer_id,
  1311. )
  1312. item.ams_mapping = None
  1313. await db.commit()
  1314. async def _compute_ams_mapping_for_printer(
  1315. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  1316. ) -> list[int] | None:
  1317. """Compute AMS mapping for a printer based on filament requirements.
  1318. Called when a queue item has no ams_mapping set — either for model-based
  1319. items after printer assignment, or printer-specific items (e.g. from VP).
  1320. Args:
  1321. db: Database session
  1322. printer_id: The assigned printer ID
  1323. item: The queue item (contains archive_id or library_file_id)
  1324. Returns:
  1325. AMS mapping array or None if no mapping needed/possible
  1326. """
  1327. # Get printer status
  1328. status = printer_manager.get_status(printer_id)
  1329. if not status:
  1330. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  1331. return None
  1332. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  1333. # either extruder, so the per-nozzle hard filter below must NOT apply.
  1334. # Otherwise a print on one nozzle can't use a spool physically loaded in
  1335. # an AMS on the *other* nozzle, and the matcher falls through to a
  1336. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  1337. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  1338. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  1339. # Get filament requirements from source file
  1340. filament_reqs = await self._get_filament_requirements(db, item)
  1341. if not filament_reqs:
  1342. # When the 3MF can't be read but force-color overrides are present, build a
  1343. # direct mapping from the overrides so the printer uses the correct AMS slot.
  1344. if item.filament_overrides:
  1345. try:
  1346. overrides = json.loads(item.filament_overrides)
  1347. force_overrides = [o for o in overrides if o.get("force_color_match")]
  1348. if force_overrides:
  1349. logger.info(
  1350. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  1351. "force-color override(s)",
  1352. item.id,
  1353. len(force_overrides),
  1354. )
  1355. return self._build_override_direct_mapping(force_overrides, status)
  1356. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1357. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  1358. logger.debug("No filament requirements found for queue item %s", item.id)
  1359. return None
  1360. # Apply filament overrides if present
  1361. if item.filament_overrides:
  1362. try:
  1363. overrides = json.loads(item.filament_overrides)
  1364. override_map = {o["slot_id"]: o for o in overrides}
  1365. for req in filament_reqs:
  1366. if req["slot_id"] in override_map:
  1367. override = override_map[req["slot_id"]]
  1368. req["type"] = override["type"]
  1369. req["color"] = override["color"]
  1370. # A manual/preference override SWAPS the slot's filament, so the
  1371. # 3MF's original tray_info_idx now points at the old spool and must
  1372. # be cleared — matching then falls back to type+colour. A
  1373. # force_color_match override is not a swap: it carries the 3MF's
  1374. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  1375. # it here too, letting the matcher pin the correct variant slot on a
  1376. # printer holding two same-colour spools of different variants (#2650).
  1377. # If that variant isn't loaded the matcher falls back to type+colour,
  1378. # so an eligible printer never fails to map.
  1379. req["tray_info_idx"] = (
  1380. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  1381. )
  1382. logger.debug(
  1383. "Queue item %s: Override slot %d -> %s %s",
  1384. item.id,
  1385. req["slot_id"],
  1386. override["type"],
  1387. override["color"],
  1388. )
  1389. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1390. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  1391. # Build loaded filaments from printer status
  1392. loaded_filaments = self._build_loaded_filaments(status)
  1393. if not loaded_filaments:
  1394. logger.debug("No filaments loaded on printer %s", printer_id)
  1395. return None
  1396. # Check if user prefers lowest remaining filament when multiple spools match
  1397. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  1398. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  1399. # Without backup, the printer will not switch to a second spool when the
  1400. # picked one runs out — so sorting toward the lowest leaves the print
  1401. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  1402. # today's behaviour intentionally.
  1403. if prefer_lowest and status.ams_filament_backup is False:
  1404. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  1405. prefer_lowest = False
  1406. # When the preference is on, surface Bambuddy's inventory-side
  1407. # remaining for each slot that's bound to a tracked spool, so the
  1408. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  1409. # entirely when the preference is off — no behaviour change for
  1410. # users who haven't opted in.
  1411. inventory_remain_overrides: dict[int, float] | None = None
  1412. if prefer_lowest:
  1413. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  1414. # Compute mapping: match required filaments to available slots
  1415. return self._match_filaments_to_slots(
  1416. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  1417. )
  1418. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  1419. """Build an AMS mapping directly from force-color overrides without a 3MF.
  1420. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  1421. slice_info is missing or unreadable) but ``force_color_match`` overrides
  1422. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  1423. treated as the filament requirement for that slot and matched against the
  1424. current AMS state of the printer.
  1425. Returns the same format as ``_match_filaments_to_slots``, or None when
  1426. the AMS has no loaded filaments.
  1427. """
  1428. loaded = self._build_loaded_filaments(status)
  1429. if not loaded:
  1430. return None
  1431. reqs = [
  1432. {
  1433. "slot_id": o["slot_id"],
  1434. "type": o.get("type", ""),
  1435. "color": o.get("color", ""),
  1436. # These are all force_color_match overrides, so the idx (when the
  1437. # 3MF carried one) is the intended variant, not a stale swap —
  1438. # keep it so the matcher pins the right variant slot, falling back
  1439. # to type+colour when it isn't loaded (#2650).
  1440. "tray_info_idx": o.get("tray_info_idx", ""),
  1441. }
  1442. for o in force_overrides
  1443. ]
  1444. return self._match_filaments_to_slots(reqs, loaded)
  1445. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  1446. """Resolve the queue item's source 3MF and parse the per-slot
  1447. filament requirements out of it. Thin DB-resolver wrapper around
  1448. ``filament_requirements.extract_filament_requirements`` so the VP
  1449. queue-mode write path (#1188) can reuse the same parser at upload
  1450. time.
  1451. """
  1452. from backend.app.services.filament_requirements import extract_filament_requirements
  1453. file_path: Path | None = None
  1454. if item.archive_id:
  1455. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1456. archive = result.scalar_one_or_none()
  1457. if archive:
  1458. file_path = settings.base_dir / archive.file_path
  1459. elif item.library_file_id:
  1460. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1461. library_file = result.scalar_one_or_none()
  1462. if library_file:
  1463. lib_path = Path(library_file.file_path)
  1464. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1465. if not file_path or not file_path.exists():
  1466. return None
  1467. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  1468. return filaments if filaments else None
  1469. def _build_loaded_filaments(self, status) -> list[dict]:
  1470. """Build list of loaded filaments from printer status.
  1471. Args:
  1472. status: PrinterState from printer_manager
  1473. Returns:
  1474. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  1475. """
  1476. filaments = []
  1477. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  1478. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  1479. # Parse AMS units from raw_data
  1480. ams_data = status.raw_data.get("ams", [])
  1481. for ams_unit in ams_data:
  1482. ams_id = int(ams_unit.get("id", 0))
  1483. trays = ams_unit.get("tray", [])
  1484. is_ht = len(trays) == 1 # AMS-HT has single tray
  1485. for tray in trays:
  1486. tray_type = tray.get("tray_type")
  1487. if tray_type:
  1488. tray_id = int(tray.get("id", 0))
  1489. tray_color = tray.get("tray_color", "")
  1490. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  1491. tray_info_idx = tray.get("tray_info_idx", "")
  1492. # Normalize color: remove alpha, add hash
  1493. color = self._normalize_color(tray_color)
  1494. # Calculate global tray ID
  1495. # AMS-HT units have IDs starting at 128 with a single tray
  1496. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  1497. filaments.append(
  1498. {
  1499. "type": tray_type,
  1500. "color": color,
  1501. "tray_info_idx": tray_info_idx,
  1502. "ams_id": ams_id,
  1503. "tray_id": tray_id,
  1504. "is_ht": is_ht,
  1505. "is_external": False,
  1506. "global_tray_id": global_tray_id,
  1507. "extruder_id": ams_extruder_map.get(str(ams_id)),
  1508. "remain": tray.get("remain", -1),
  1509. }
  1510. )
  1511. # Check external spool(s) (vt_tray is a list)
  1512. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  1513. if vt.get("tray_type"):
  1514. color = self._normalize_color(vt.get("tray_color", ""))
  1515. tray_id = int(vt.get("id", 254))
  1516. filaments.append(
  1517. {
  1518. "type": vt["tray_type"],
  1519. "color": color,
  1520. "tray_info_idx": vt.get("tray_info_idx", ""),
  1521. "ams_id": -1,
  1522. "tray_id": idx,
  1523. "is_ht": False,
  1524. "is_external": True,
  1525. "global_tray_id": tray_id,
  1526. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  1527. "remain": vt.get("remain", -1),
  1528. }
  1529. )
  1530. return filaments
  1531. def _normalize_color(self, color: str | None) -> str:
  1532. """Normalize color to #RRGGBB format."""
  1533. if not color:
  1534. return "#808080"
  1535. hex_color = color.replace("#", "")[:6]
  1536. return f"#{hex_color}"
  1537. def _normalize_color_for_compare(self, color: str | None) -> str:
  1538. """Normalize color for comparison (lowercase, no hash)."""
  1539. if not color:
  1540. return ""
  1541. return color.replace("#", "").lower()[:6]
  1542. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  1543. """Check if two colors are visually similar within a threshold."""
  1544. hex1 = self._normalize_color_for_compare(color1)
  1545. hex2 = self._normalize_color_for_compare(color2)
  1546. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  1547. return False
  1548. try:
  1549. r1 = int(hex1[0:2], 16)
  1550. g1 = int(hex1[2:4], 16)
  1551. b1 = int(hex1[4:6], 16)
  1552. r2 = int(hex2[0:2], 16)
  1553. g2 = int(hex2[2:4], 16)
  1554. b2 = int(hex2[4:6], 16)
  1555. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  1556. except ValueError:
  1557. return False
  1558. async def _build_inventory_remain_overrides(
  1559. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  1560. ) -> dict[int, float]:
  1561. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  1562. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  1563. The MQTT ``remain`` field on a tray is the printer firmware's
  1564. RFID-decremented value, which has two limitations the "Prefer Lowest
  1565. Remaining Filament" feature has been ignoring (#1508):
  1566. - it's only meaningful for Bambu RFID spools; everything else reports
  1567. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  1568. compare equal and the sort collapses to AMS-slot order — the user
  1569. who's curating inventory weights gets the lower-slot pick instead
  1570. of the lower-remaining pick;
  1571. - even when set, it's the *printer's* counter, not Bambuddy's
  1572. ``label_weight - weight_used`` (internal mode) or Spoolman's
  1573. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  1574. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  1575. When the user has bound a spool to a slot, their own inventory
  1576. tracking is authoritative; this helper surfaces that value so the
  1577. sort can prefer it. Slots without a binding are absent from the
  1578. returned map — the caller then falls back to MQTT ``remain`` for
  1579. those, preserving the pre-#1508 behaviour for un-tracked spools.
  1580. Returns an empty map on any failure (no inventory bindings, DB
  1581. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  1582. is a preference, not a guarantee.
  1583. """
  1584. if not loaded:
  1585. return {}
  1586. # External / virtual-tray slots are tracked separately from AMS — skip
  1587. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  1588. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  1589. # match is fiddly and out of scope for this fix).
  1590. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  1591. if not tracked_slots:
  1592. return {}
  1593. is_spoolman = await self._is_spoolman_mode(db)
  1594. overrides: dict[int, float] = {}
  1595. if is_spoolman:
  1596. result = await db.execute(
  1597. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  1598. )
  1599. assignments = list(result.scalars().all())
  1600. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  1601. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  1602. for ams_id, tray_id, gtid in tracked_slots:
  1603. spoolman_id = by_slot.get((ams_id, tray_id))
  1604. if spoolman_id is None:
  1605. continue
  1606. grams = await _spoolman_remaining_grams(spoolman_id)
  1607. if grams is not None:
  1608. overrides[gtid] = grams
  1609. return overrides
  1610. # Internal inventory mode (default). selectinload matches the pattern
  1611. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  1612. # plus an eager-loaded relationship rather than an explicit join, so
  1613. # the row-attribute shape is exactly what those routes already rely on.
  1614. result = await db.execute(
  1615. select(SpoolAssignment)
  1616. .options(selectinload(SpoolAssignment.spool))
  1617. .where(SpoolAssignment.printer_id == printer_id)
  1618. )
  1619. assignments = list(result.scalars().all())
  1620. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  1621. for ams_id, tray_id, gtid in tracked_slots:
  1622. spool = by_slot.get((ams_id, tray_id))
  1623. if spool is None:
  1624. continue
  1625. label = float(spool.label_weight or 0)
  1626. used = float(spool.weight_used or 0)
  1627. overrides[gtid] = max(0.0, label - used)
  1628. return overrides
  1629. @staticmethod
  1630. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  1631. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  1632. here to avoid making this module import-dependent on that private
  1633. helper's signature."""
  1634. try:
  1635. from backend.app.api.routes.settings import get_setting
  1636. v = await get_setting(db, "spoolman_enabled")
  1637. return bool(v) and v.lower() == "true"
  1638. except Exception:
  1639. return False
  1640. @staticmethod
  1641. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  1642. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  1643. Three bands, matched to the emission order in ``_build_loaded_filaments``
  1644. so a tied sort produces the same physical-position order the pre-#1508
  1645. stable sort did (preserves the regression-free baseline):
  1646. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  1647. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  1648. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  1649. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  1650. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  1651. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  1652. """
  1653. if ams_id is None or ams_id < 0:
  1654. return 10_000
  1655. if ams_id >= 128:
  1656. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  1657. return ams_id * 4 + (tray_id or 0)
  1658. @staticmethod
  1659. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  1660. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  1661. Two-tier ordering: inventory-tracked spools always sort BEFORE
  1662. non-tracked spools (the user has told us they care about these
  1663. specifically), then ascending by remaining within each tier, then
  1664. ascending by AMS slot position as the deterministic tie-breaker.
  1665. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  1666. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  1667. because the tier flag dominates — which is what lets us mix grams
  1668. (inventory) and percent (MQTT) without a unit conversion.
  1669. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  1670. spools the printer DOES know something about sort ahead of those
  1671. it knows nothing about — preserves pre-#1508 behaviour for the
  1672. no-inventory-binding case.
  1673. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  1674. external on ties, matching the legacy emission-order stable sort.
  1675. """
  1676. gtid = f.get("global_tray_id")
  1677. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  1678. if overrides and gtid in overrides:
  1679. return (0, overrides[gtid], slot_order)
  1680. remain = f.get("remain", -1)
  1681. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  1682. def _match_filaments_to_slots(
  1683. self,
  1684. required: list[dict],
  1685. loaded: list[dict],
  1686. prefer_lowest: bool = False,
  1687. inventory_remain_overrides: dict[int, float] | None = None,
  1688. fts_installed: bool = False,
  1689. ) -> list[int] | None:
  1690. """Match required filaments to loaded filaments and build AMS mapping.
  1691. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  1692. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  1693. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  1694. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  1695. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  1696. matching among those trays.
  1697. Args:
  1698. required: List of required filaments with slot_id, type, color, tray_info_idx
  1699. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  1700. Returns:
  1701. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  1702. """
  1703. if not required:
  1704. return None
  1705. # Track used trays to avoid duplicate assignment
  1706. used_tray_ids: set[int] = set()
  1707. comparisons = []
  1708. for req in required:
  1709. req_type = (req.get("type") or "").upper()
  1710. req_color = req.get("color", "")
  1711. req_tray_info_idx = req.get("tray_info_idx", "")
  1712. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  1713. idx_match = None
  1714. exact_match = None
  1715. similar_match = None
  1716. type_only_match = None
  1717. # Get available trays (not already used)
  1718. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  1719. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  1720. # Hard filter — cross-nozzle assignment causes print failures
  1721. # ("position of left hotend is abnormal"), so never fall back.
  1722. # Skipped when an FTS is installed: it routes any AMS slot to either
  1723. # extruder, so restricting to one nozzle would wrongly exclude the
  1724. # correct spool sitting in the other nozzle's AMS (#2186).
  1725. req_nozzle_id = req.get("nozzle_id")
  1726. if req_nozzle_id is not None and not fts_installed:
  1727. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  1728. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  1729. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  1730. # _prefer_lowest_sort_key for the full rationale.
  1731. if prefer_lowest:
  1732. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1733. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  1734. # One line per filament req so a bug report can be diagnosed
  1735. # without enabling debug logging: shows what the matcher saw
  1736. # (req shape + sorted candidate trays with their remain values
  1737. # and any inventory override that was applied). Mirrored by
  1738. # the picked-match log at the bottom of the loop.
  1739. logger.info(
  1740. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  1741. req.get("slot_id"),
  1742. req_type,
  1743. req_color,
  1744. req_tray_info_idx,
  1745. req_nozzle_id,
  1746. [
  1747. {
  1748. "gtid": f.get("global_tray_id"),
  1749. "type": f.get("type"),
  1750. "color": f.get("color"),
  1751. "tii": f.get("tray_info_idx"),
  1752. "remain": f.get("remain"),
  1753. "inv_g": (
  1754. inventory_remain_overrides.get(f.get("global_tray_id"))
  1755. if inventory_remain_overrides
  1756. else None
  1757. ),
  1758. }
  1759. for f in available
  1760. ],
  1761. )
  1762. # Check if tray_info_idx is unique among available trays
  1763. if req_tray_info_idx:
  1764. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  1765. if len(idx_matches) == 1:
  1766. # Unique tray_info_idx - use it as definitive match
  1767. idx_match = idx_matches[0]
  1768. logger.debug(
  1769. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  1770. f"-> tray {idx_match['global_tray_id']}"
  1771. )
  1772. elif len(idx_matches) > 1:
  1773. # Multiple trays with same tray_info_idx - use color matching among them
  1774. logger.debug(
  1775. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  1776. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  1777. )
  1778. if prefer_lowest:
  1779. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1780. # Use color matching within this subset
  1781. for f in idx_matches:
  1782. f_color = f.get("color", "")
  1783. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1784. if not exact_match:
  1785. exact_match = f
  1786. elif self._colors_are_similar(f_color, req_color):
  1787. if not similar_match:
  1788. similar_match = f
  1789. elif not type_only_match:
  1790. type_only_match = f
  1791. # If no idx_match yet, do standard type/color matching on all available trays
  1792. if not idx_match and not exact_match and not similar_match and not type_only_match:
  1793. for f in available:
  1794. f_type = (f.get("type") or "").upper()
  1795. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  1796. continue
  1797. # Type matches - check color
  1798. f_color = f.get("color", "")
  1799. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1800. if not exact_match:
  1801. exact_match = f
  1802. elif self._colors_are_similar(f_color, req_color):
  1803. if not similar_match:
  1804. similar_match = f
  1805. elif not type_only_match:
  1806. type_only_match = f
  1807. match = idx_match or exact_match or similar_match or type_only_match
  1808. if match:
  1809. used_tray_ids.add(match["global_tray_id"])
  1810. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  1811. else:
  1812. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  1813. if prefer_lowest:
  1814. # Pair with the "available (sorted)" log above so the reporter
  1815. # bundle shows BOTH what the matcher saw AND which match bucket
  1816. # won — fast triage when "Prefer Lowest Filament" picks the
  1817. # wrong slot (#1766).
  1818. if match:
  1819. bucket = (
  1820. "idx"
  1821. if idx_match is not None
  1822. else "exact_color"
  1823. if exact_match is not None
  1824. else "similar_color"
  1825. if similar_match is not None
  1826. else "type_only"
  1827. )
  1828. logger.info(
  1829. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  1830. match["global_tray_id"],
  1831. bucket,
  1832. req.get("slot_id"),
  1833. )
  1834. else:
  1835. logger.info(
  1836. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  1837. req.get("slot_id"),
  1838. req_type,
  1839. req_color,
  1840. req_tray_info_idx,
  1841. )
  1842. # Build mapping array
  1843. if not comparisons:
  1844. return None
  1845. max_slot_id = max(c["slot_id"] for c in comparisons)
  1846. if max_slot_id <= 0:
  1847. return None
  1848. mapping = [-1] * max_slot_id
  1849. for c in comparisons:
  1850. slot_id = c["slot_id"]
  1851. if slot_id and slot_id > 0:
  1852. mapping[slot_id - 1] = c["global_tray_id"]
  1853. return mapping
  1854. def _mark_printer_dispatched(
  1855. self,
  1856. printer_id: int,
  1857. pre_state: str | None,
  1858. pre_subtask_id: str | None,
  1859. ) -> None:
  1860. """Record that a print command was just sent to ``printer_id``.
  1861. Held until either the watchdog observes a state/subtask transition
  1862. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1863. """
  1864. if not pre_state:
  1865. # No pre_state means we can't detect a transition — fall back to a
  1866. # pure time-based hold using empty string as a sentinel that won't
  1867. # match any real printer state.
  1868. pre_state = ""
  1869. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1870. def _release_dispatch_hold(self, printer_id: int) -> None:
  1871. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1872. self._dispatch_holds.pop(printer_id, None)
  1873. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1874. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1875. Returns False (and clears the hold) once any of these are true:
  1876. - hard timeout (``_dispatch_max_hold``) has elapsed
  1877. - the printer has transitioned out of pre_state and we're past the
  1878. minimum cooldown
  1879. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1880. past the minimum cooldown
  1881. Otherwise the printer is held — caller should treat it as busy.
  1882. """
  1883. entry = self._dispatch_holds.get(printer_id)
  1884. if not entry:
  1885. return False
  1886. started_at, pre_state, pre_subtask_id = entry
  1887. elapsed = time.monotonic() - started_at
  1888. if elapsed >= self._dispatch_max_hold:
  1889. self._dispatch_holds.pop(printer_id, None)
  1890. return False
  1891. # Without a pre_state we can't detect a transition — fall back to the
  1892. # min cooldown alone, then drop the hold.
  1893. if not pre_state:
  1894. if elapsed >= self._dispatch_min_cooldown:
  1895. self._dispatch_holds.pop(printer_id, None)
  1896. return False
  1897. return True
  1898. status = printer_manager.get_status(printer_id)
  1899. current_state = getattr(status, "state", None) if status else None
  1900. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1901. transitioned = (current_state is not None and current_state != pre_state) or (
  1902. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1903. )
  1904. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1905. self._dispatch_holds.pop(printer_id, None)
  1906. return False
  1907. return True
  1908. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1909. """Check if a printer is connected and idle."""
  1910. if not printer_manager.is_connected(printer_id):
  1911. logger.debug("Printer %d: not connected", printer_id)
  1912. return False
  1913. state = printer_manager.get_status(printer_id)
  1914. if not state:
  1915. logger.debug("Printer %d: no status available", printer_id)
  1916. return False
  1917. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1918. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1919. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1920. # printer, it boots back into IDLE with no memory of the previous finish; without
  1921. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1922. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1923. logger.debug(
  1924. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1925. printer_id,
  1926. state.state,
  1927. )
  1928. return False
  1929. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1930. if not idle:
  1931. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1932. return idle
  1933. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1934. """Read a setting value from the database."""
  1935. result = await db.execute(select(Settings).where(Settings.key == key))
  1936. setting = result.scalar_one_or_none()
  1937. return setting.value if setting else None
  1938. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1939. """Read a boolean setting from the database."""
  1940. result = await db.execute(select(Settings).where(Settings.key == key))
  1941. setting = result.scalar_one_or_none()
  1942. if setting:
  1943. return setting.value.lower() == "true"
  1944. return default
  1945. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  1946. """Read an int setting; falls back to default on missing/unparseable rows."""
  1947. result = await db.execute(select(Settings).where(Settings.key == key))
  1948. setting = result.scalar_one_or_none()
  1949. if setting and setting.value:
  1950. try:
  1951. return int(setting.value)
  1952. except ValueError:
  1953. pass
  1954. return default
  1955. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1956. """Get drying presets (user-configured or built-in defaults)."""
  1957. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1958. setting = result.scalar_one_or_none()
  1959. if setting and setting.value:
  1960. try:
  1961. presets = json.loads(setting.value)
  1962. if isinstance(presets, dict) and presets:
  1963. return presets
  1964. except json.JSONDecodeError:
  1965. pass
  1966. return self.DEFAULT_DRYING_PRESETS
  1967. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  1968. """Per-filament humidity thresholds (#1605).
  1969. Returns the user-configured overrides map keyed by normalized filament
  1970. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  1971. unknown / unmapped types. Empty / unset → empty dict, in which case
  1972. callers fall back to ``ams_humidity_fair``.
  1973. """
  1974. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  1975. setting = result.scalar_one_or_none()
  1976. if not setting or not setting.value:
  1977. return {}
  1978. try:
  1979. data = json.loads(setting.value)
  1980. except json.JSONDecodeError:
  1981. return {}
  1982. if not isinstance(data, dict):
  1983. return {}
  1984. out: dict[str, int] = {}
  1985. for key, value in data.items():
  1986. try:
  1987. out[str(key).upper() if key != "default" else "default"] = int(value)
  1988. except (TypeError, ValueError):
  1989. continue
  1990. return out
  1991. @staticmethod
  1992. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  1993. """Resolve the effective humidity threshold for an AMS unit (#1605).
  1994. For mixed filament types loaded into one AMS, returns the most
  1995. restrictive (lowest) threshold across all loaded tray types — matches
  1996. the conservative-params strategy already used for drying temp/hours.
  1997. Empty / unloaded trays contribute no constraint. Unknown types use the
  1998. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  1999. when no per-type map is configured at all.
  2000. """
  2001. default = thresholds.get("default", fallback)
  2002. if not thresholds:
  2003. return fallback
  2004. candidates: list[int] = []
  2005. for tray in trays:
  2006. tray_type = str(tray.get("tray_type") or "").strip()
  2007. if not tray_type:
  2008. continue
  2009. base_type = tray_type.split()[0].upper()
  2010. candidates.append(thresholds.get(base_type, default))
  2011. if not candidates:
  2012. return default
  2013. return min(candidates)
  2014. def _get_conservative_drying_params(
  2015. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  2016. ) -> tuple[int, int, str] | None:
  2017. """Get the most conservative drying params for mixed filament types in an AMS unit.
  2018. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  2019. """
  2020. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  2021. hours_key = f"{temp_key}_hours"
  2022. min_temp = None
  2023. max_hours = None
  2024. filament_type = ""
  2025. for tray in trays:
  2026. tray_type = tray.get("tray_type", "")
  2027. if not tray_type:
  2028. continue
  2029. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  2030. base_type = tray_type.split()[0].upper()
  2031. preset = presets.get(base_type)
  2032. if not preset:
  2033. continue
  2034. temp = preset.get(temp_key, 55)
  2035. hours = preset.get(hours_key, 12)
  2036. # Conservative: lowest temp, longest duration
  2037. if min_temp is None or temp < min_temp:
  2038. min_temp = temp
  2039. if max_hours is None or hours > max_hours:
  2040. max_hours = hours
  2041. if not filament_type:
  2042. filament_type = base_type
  2043. if min_temp is None:
  2044. return None
  2045. return (min_temp, max_hours or 12, filament_type)
  2046. async def _check_auto_drying(
  2047. self,
  2048. db: AsyncSession,
  2049. queue_items: list[PrintQueueItem],
  2050. busy_printers: set[int],
  2051. *,
  2052. require_plate_clear: bool = True,
  2053. ):
  2054. """Start drying on idle printers based on humidity.
  2055. Three modes (can all be enabled independently):
  2056. - queue_drying_enabled: Dry between scheduled queue prints
  2057. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  2058. - print_drying_enabled: Also evaluate printers that are currently printing,
  2059. when model+firmware supports "Print While Drying" (gated by
  2060. supports_drying_while_printing). Drying temperature is capped at
  2061. max(40, preset_temp - 5) to protect spools mid-print.
  2062. """
  2063. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  2064. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  2065. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  2066. if not queue_drying_enabled and not ambient_drying_enabled:
  2067. # Stop active drying on all printers if both features disabled
  2068. if self._drying_in_progress:
  2069. for pid in list(self._drying_in_progress):
  2070. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  2071. await self._stop_drying(pid)
  2072. return
  2073. # Update drying state from printer status (handles backend restart)
  2074. self._sync_drying_state()
  2075. # Find printers with scheduled items (for queue drying mode)
  2076. printers_with_scheduled: set[int] = set()
  2077. printers_with_items: set[int] = set()
  2078. for item in queue_items:
  2079. if item.printer_id:
  2080. printers_with_items.add(item.printer_id)
  2081. if item.scheduled_time and not item.manual_start:
  2082. printers_with_scheduled.add(item.printer_id)
  2083. # If only queue mode is on and no printers have scheduled items, stop drying
  2084. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  2085. # may still be eligible for mid-print drying regardless of queue state).
  2086. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  2087. for pid in list(self._drying_in_progress):
  2088. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  2089. await self._stop_drying(pid)
  2090. return
  2091. # Get humidity threshold (global fallback)
  2092. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  2093. setting = result.scalar_one_or_none()
  2094. global_humidity_threshold = int(setting.value) if setting else 60
  2095. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  2096. # to the global threshold for every AMS unit.
  2097. per_type_thresholds = await self._get_humidity_thresholds(db)
  2098. # Get drying presets
  2099. presets = await self._get_drying_presets(db)
  2100. # Determine if drying should be skipped for printers with pending items
  2101. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  2102. # Get all active printers
  2103. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2104. for printer in all_printers.scalars():
  2105. pid = printer.id
  2106. # Resolve model+firmware up front — needed to decide whether this printer
  2107. # qualifies for mid-print drying (busy printer on capable hardware).
  2108. state = printer_manager.get_status(pid)
  2109. if not state:
  2110. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  2111. continue
  2112. model = printer_manager.get_model(pid)
  2113. firmware = state.firmware_version
  2114. mid_print = (
  2115. pid in busy_printers and print_drying_enabled and supports_drying_while_printing(model, firmware)
  2116. )
  2117. if pid in busy_printers and not mid_print:
  2118. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  2119. continue
  2120. if not mid_print:
  2121. # In queue-only mode, only dry printers that have scheduled prints
  2122. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  2123. if self._drying_in_progress.get(pid):
  2124. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  2125. await self._stop_drying(pid)
  2126. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  2127. continue
  2128. # When block mode is on, don't START new drying on printers with pending items.
  2129. # But allow already-drying printers through so humidity auto-stop logic still runs.
  2130. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  2131. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  2132. continue
  2133. if not printer_manager.is_connected(pid):
  2134. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  2135. continue
  2136. if not mid_print and not self._is_printer_idle(pid, require_plate_clear):
  2137. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  2138. continue
  2139. # Check drying capability. For mid-print path, supports_drying_while_printing
  2140. # was already verified when computing mid_print above.
  2141. if not mid_print and not supports_drying(model, firmware):
  2142. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  2143. continue
  2144. # Check each AMS unit from raw_data
  2145. ams_list = state.raw_data.get("ams", [])
  2146. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  2147. for ams_data in ams_list:
  2148. module_type = str(ams_data.get("module_type") or "")
  2149. ams_id = int(ams_data.get("id", 0))
  2150. # Only n3f/n3s support drying
  2151. if module_type not in ("n3f", "n3s"):
  2152. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  2153. continue
  2154. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  2155. # Most-restrictive of all loaded tray types; falls back to the
  2156. # global threshold when no overrides are configured.
  2157. trays = ams_data.get("tray", []) or []
  2158. humidity_threshold = self.resolve_humidity_threshold(
  2159. trays, per_type_thresholds, global_humidity_threshold
  2160. )
  2161. dry_time = int(ams_data.get("dry_time") or 0)
  2162. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  2163. humidity = None
  2164. h_raw = ams_data.get("humidity_raw")
  2165. if h_raw is not None:
  2166. try:
  2167. humidity = int(h_raw)
  2168. except (ValueError, TypeError):
  2169. pass
  2170. if humidity is None:
  2171. h_idx = ams_data.get("humidity")
  2172. if h_idx is not None:
  2173. try:
  2174. humidity = int(h_idx)
  2175. except (ValueError, TypeError):
  2176. pass
  2177. # Already drying — let it run to its configured duration (#1892).
  2178. #
  2179. # We deliberately do NOT stop drying from a humidity re-check here.
  2180. # Relative humidity drops steeply in heated air, so the AMS sensor
  2181. # reads ~15-20% within minutes of the dryer starting even while the
  2182. # filament is still saturated. A humidity-based early-stop therefore
  2183. # always fires at the minimum-time floor, truncating both user-started
  2184. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  2185. # The firmware stops when the configured duration elapses; scheduling
  2186. # stops (print takes priority, queue no longer needs drying) are
  2187. # handled separately via _stop_drying().
  2188. if dry_time > 0:
  2189. if pid not in self._drying_in_progress:
  2190. # Drying we didn't start (manual or from before restart) —
  2191. # track it so scheduling stops still apply; never auto-stop it.
  2192. self._drying_in_progress[pid] = time.monotonic()
  2193. logger.debug(
  2194. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  2195. pid,
  2196. ams_id,
  2197. dry_time,
  2198. humidity,
  2199. )
  2200. continue
  2201. # Humidity below threshold — no need to start drying
  2202. if humidity is None or humidity <= humidity_threshold:
  2203. logger.debug(
  2204. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  2205. pid,
  2206. ams_id,
  2207. humidity,
  2208. humidity_threshold,
  2209. )
  2210. continue
  2211. # Check cannot-dry reasons (power constraints etc.)
  2212. sf_reasons = ams_data.get("dry_sf_reason", [])
  2213. if sf_reasons:
  2214. logger.debug(
  2215. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  2216. pid,
  2217. ams_id,
  2218. sf_reasons,
  2219. )
  2220. continue
  2221. # Get conservative drying params for mixed filaments
  2222. params = self._get_conservative_drying_params(trays, module_type, presets)
  2223. if not params:
  2224. logger.debug(
  2225. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  2226. )
  2227. continue
  2228. temp, duration_hours, filament_type = params
  2229. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  2230. # "drying temperature must not exceed the filament's softening temperature"
  2231. # for Print While Drying). Floor at 40 degC — below that the dryer is
  2232. # ineffective and firmware will reject anyway.
  2233. if mid_print:
  2234. temp = max(40, temp - 5)
  2235. # Start drying
  2236. logger.info(
  2237. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  2238. "starting %s drying at %d°C for %dh%s",
  2239. pid,
  2240. ams_id,
  2241. humidity,
  2242. humidity_threshold,
  2243. filament_type,
  2244. temp,
  2245. duration_hours,
  2246. " (mid-print)" if mid_print else "",
  2247. )
  2248. success = printer_manager.send_drying_command(
  2249. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  2250. )
  2251. if success:
  2252. self._drying_in_progress[pid] = time.monotonic()
  2253. def _sync_drying_state(self):
  2254. """Sync in-memory drying state with actual printer status.
  2255. Handles backend restart — if a printer is drying but we don't know about it,
  2256. update our state. If we think it's drying but it's not, clear it.
  2257. """
  2258. to_remove = []
  2259. for pid in self._drying_in_progress:
  2260. state = printer_manager.get_status(pid)
  2261. if not state:
  2262. to_remove.append(pid)
  2263. continue
  2264. # Check if any AMS unit is still drying
  2265. ams_list = state.raw_data.get("ams", [])
  2266. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  2267. if not any_drying:
  2268. to_remove.append(pid)
  2269. for pid in to_remove:
  2270. self._drying_in_progress.pop(pid, None)
  2271. async def _stop_drying(self, printer_id: int):
  2272. """Stop all active drying on a printer (print takes priority)."""
  2273. state = printer_manager.get_status(printer_id)
  2274. if not state:
  2275. self._drying_in_progress.pop(printer_id, None)
  2276. return
  2277. ams_list = state.raw_data.get("ams", [])
  2278. for ams_data in ams_list:
  2279. dry_time = int(ams_data.get("dry_time") or 0)
  2280. if dry_time > 0:
  2281. ams_id = int(ams_data.get("id", 0))
  2282. logger.info(
  2283. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  2284. printer_id,
  2285. ams_id,
  2286. )
  2287. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  2288. self._drying_in_progress.pop(printer_id, None)
  2289. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  2290. """Get all smart plugs associated with a printer."""
  2291. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2292. return list(result.scalars().all())
  2293. @staticmethod
  2294. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  2295. """Pick the plug to power-cycle a printer back online with (#2629).
  2296. Only a plug flagged ``controls_printer_power`` can actually bring the
  2297. printer back; waiting for a boot on an accessory (filter fan, lights)
  2298. just burns the power-on timeout and fails the dispatch. Falls back to
  2299. the first plug when none is flagged, which is the pre-#2629 behaviour.
  2300. Callers must pass a non-empty list.
  2301. """
  2302. for plug in auto_on_plugs:
  2303. if plug.controls_printer_power:
  2304. return plug
  2305. return auto_on_plugs[0]
  2306. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  2307. # chamber-temperature recommendations BambuStudio ships for the matching
  2308. # filament profile; users can override via Settings → Workflow → Preheat
  2309. # card. "default" applies when a loaded tray's normalised type isn't in
  2310. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  2311. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  2312. "PLA": 0,
  2313. "PETG": 0,
  2314. "PETG-CF": 40,
  2315. "ABS": 45,
  2316. "ASA": 45,
  2317. "PA": 50,
  2318. "PA-CF": 55,
  2319. "PC": 50,
  2320. "PC-FR": 50,
  2321. "TPU": 0,
  2322. "PVA": 0,
  2323. "default": 0,
  2324. }
  2325. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  2326. """Parse the user-configured filament→chamber-target map, falling back
  2327. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  2328. are uppercased and the 'default' fallback is always present in the
  2329. returned dict so the resolution loop can index it unconditionally."""
  2330. raw = await self._get_setting(db, "preheat_filament_targets")
  2331. if not raw:
  2332. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2333. try:
  2334. parsed = json.loads(raw)
  2335. if not isinstance(parsed, dict):
  2336. raise ValueError("not an object")
  2337. except (json.JSONDecodeError, ValueError) as exc:
  2338. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  2339. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  2340. # Coerce values to int; drop unparseable rows so a stray string
  2341. # doesn't crash the loop.
  2342. out: dict[str, int] = {}
  2343. for key, value in parsed.items():
  2344. try:
  2345. out[str(key).upper()] = int(value)
  2346. except (TypeError, ValueError):
  2347. continue
  2348. if "DEFAULT" not in out:
  2349. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  2350. return out
  2351. @staticmethod
  2352. def _normalize_filament_type(tray_type: str) -> str:
  2353. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  2354. existing drying-preset normalisation (split-at-space, upper-case) so
  2355. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  2356. "PA-CF" (no space to split on)."""
  2357. return tray_type.split()[0].upper() if tray_type else ""
  2358. def _derive_chamber_target(
  2359. self,
  2360. printer: Printer,
  2361. targets: dict[str, int],
  2362. ) -> int:
  2363. """Look up the chamber target for each loaded AMS tray and return the
  2364. max. Returns 0 when no AMS data is available (e.g. external-spool
  2365. prints) or when every loaded slot maps to 0 — the chamber phase then
  2366. short-circuits in the main loop.
  2367. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  2368. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  2369. less slots have empty `tray_type` and contribute nothing."""
  2370. state = printer_manager.get_status(printer.id)
  2371. if state is None:
  2372. return 0
  2373. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  2374. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  2375. if isinstance(ams_list, dict):
  2376. ams_list = ams_list.get("ams") or []
  2377. if not isinstance(ams_list, list):
  2378. return 0
  2379. best = 0
  2380. for ams in ams_list:
  2381. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  2382. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  2383. if not normalised:
  2384. continue
  2385. target = targets.get(normalised, targets.get("DEFAULT", 0))
  2386. if target > best:
  2387. best = target
  2388. return best
  2389. async def _preheat_and_soak(
  2390. self,
  2391. db: AsyncSession,
  2392. item: PrintQueueItem,
  2393. printer: Printer,
  2394. archive: PrintArchive | None,
  2395. ) -> None:
  2396. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  2397. Resolution order:
  2398. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  2399. to the global `preheat_enabled` setting; 'on' forces the stage on
  2400. even if the global is off.
  2401. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  2402. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  2403. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  2404. phase + soak timer).
  2405. 3. Three hardware tiers branch the wait loop:
  2406. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  2407. send M141 to the resolved target, then wait for the chamber sensor
  2408. to reach it (or the max-wait timeout to elapse).
  2409. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  2410. no M141; the bed is the only heat source, so we wait for the chamber
  2411. sensor to rise via bed radiation OR fall through on timeout.
  2412. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  2413. temperature; the function just heats the bed and holds for the
  2414. configured soak duration.
  2415. The bed target comes from the archive's parsed metadata
  2416. (`bed_temperature`); if missing the preheat stage logs and returns
  2417. without dispatching anything, rather than guessing at a default that
  2418. might wreck filament setup.
  2419. Failures are logged but never re-raised — preheat is best-effort. A
  2420. printer that goes offline mid-soak, a refused gcode command, or a
  2421. missing temperature reading must not turn into a failed queue item; the
  2422. normal upload + start path runs immediately after this method returns.
  2423. """
  2424. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  2425. if override == "off":
  2426. return
  2427. if override == "inherit":
  2428. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  2429. if not enabled:
  2430. return
  2431. # override == "on" forces the stage on regardless of the global setting.
  2432. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  2433. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  2434. # Chamber target resolution:
  2435. # 1. Explicit per-item override beats everything (user knows best).
  2436. # 2. Otherwise derive from loaded AMS filament types via the per-
  2437. # filament target map. PLA-only print derives 0 → chamber phase
  2438. # auto-skips without the user touching anything.
  2439. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  2440. if explicit_target is not None and explicit_target > 0:
  2441. chamber_target = int(explicit_target)
  2442. chamber_source = "item-override"
  2443. elif explicit_target == 0:
  2444. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  2445. chamber_source = "item-override-zero"
  2446. else:
  2447. targets = await self._get_preheat_filament_targets(db)
  2448. chamber_target = self._derive_chamber_target(printer, targets)
  2449. chamber_source = "filament-map"
  2450. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  2451. if bed_target <= 0:
  2452. logger.info(
  2453. "Queue item %s: preheat skipped — archive has no bed_temperature metadata",
  2454. item.id,
  2455. )
  2456. return
  2457. client = printer_manager.get_client(printer.id)
  2458. if client is None:
  2459. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  2460. return
  2461. model = printer.model or ""
  2462. has_heater = supports_chamber_heater(model)
  2463. has_sensor = supports_chamber_temp(model)
  2464. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  2465. logger.info(
  2466. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  2467. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  2468. item.id,
  2469. bed_target,
  2470. chamber_target if do_chamber else 0,
  2471. chamber_source,
  2472. override,
  2473. model,
  2474. has_heater,
  2475. has_sensor,
  2476. max_wait,
  2477. soak_seconds,
  2478. )
  2479. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  2480. # cache the target locally so the polling reads below see consistent
  2481. # state (firmware MQTT echoes lag by ~1s).
  2482. try:
  2483. client.set_bed_temperature(bed_target)
  2484. except Exception as exc:
  2485. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  2486. return
  2487. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  2488. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  2489. # left it on, regardless of M141. Default cooling actively vents the
  2490. # chamber, so a `chamber_target > 0` print with the flap stuck in
  2491. # cooling never converges — the heater fights the open exhaust. We
  2492. # flip the flap BEFORE M141 to "heating" when the preheat wants
  2493. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  2494. # on an H2D that was previously running ABS would otherwise stay in
  2495. # heating mode and overheat PLA). The current-state read keeps the
  2496. # command idempotent — no MQTT chatter when the flap is already where
  2497. # we want it.
  2498. if supports_airduct(model):
  2499. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  2500. desired_id = 1 if desired_airduct == "heating" else 0
  2501. current_state = printer_manager.get_status(printer.id)
  2502. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  2503. if current_airduct != desired_id:
  2504. try:
  2505. client.set_airduct_mode(desired_airduct)
  2506. except Exception as exc:
  2507. logger.warning(
  2508. "Queue item %s: preheat airduct %s mode failed: %s",
  2509. item.id,
  2510. desired_airduct,
  2511. exc,
  2512. )
  2513. if do_chamber and has_heater:
  2514. try:
  2515. client.set_chamber_temperature(chamber_target)
  2516. except Exception as exc:
  2517. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  2518. # Release the pooled DB connection before the (potentially many-minute)
  2519. # heat-soak wait below (#2572). Every setting this method needs is read
  2520. # above; the wait/soak loop only polls printer_manager state and sleeps —
  2521. # it never touches the DB. Without this the caller's transaction sat
  2522. # "idle in transaction" for the whole soak, pinning one pooled connection
  2523. # per preheating printer. expire_on_commit=False keeps item/printer
  2524. # readable afterwards; there are no pending writes to lose here.
  2525. await db.commit()
  2526. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  2527. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  2528. # Poll every 3s — frequent enough for responsive logging without
  2529. # spamming the MQTT state stream. The "converged" predicate is:
  2530. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  2531. # AND
  2532. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  2533. BED_TOLERANCE = 2.0
  2534. CHAMBER_TOLERANCE = 2.0
  2535. POLL_INTERVAL = 3.0
  2536. deadline = asyncio.get_event_loop().time() + max_wait
  2537. while True:
  2538. state = printer_manager.get_status(printer.id)
  2539. if state is None:
  2540. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  2541. break
  2542. temps = state.temperatures or {}
  2543. bed_now = float(temps.get("bed", 0) or 0)
  2544. chamber_now = float(temps.get("chamber", 0) or 0)
  2545. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  2546. if not do_chamber:
  2547. chamber_ok = True # phase disabled or model has neither sensor nor heater
  2548. elif not has_sensor:
  2549. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  2550. else:
  2551. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  2552. if bed_ok and chamber_ok:
  2553. logger.info(
  2554. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  2555. item.id,
  2556. bed_now,
  2557. chamber_now,
  2558. )
  2559. break
  2560. if asyncio.get_event_loop().time() >= deadline:
  2561. logger.info(
  2562. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  2563. item.id,
  2564. bed_now,
  2565. bed_target,
  2566. chamber_now,
  2567. chamber_target if do_chamber else 0,
  2568. )
  2569. break
  2570. await asyncio.sleep(POLL_INTERVAL)
  2571. if soak_seconds > 0:
  2572. logger.info("Queue item %s: preheat soak — holding for %ds", item.id, soak_seconds)
  2573. await asyncio.sleep(soak_seconds)
  2574. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  2575. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  2576. """Turn on smart plug and wait for printer to connect.
  2577. Returns True if printer connected successfully within timeout.
  2578. """
  2579. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  2580. service = await smart_plug_manager.get_service_for_plug(plug, db)
  2581. # Check current plug state
  2582. status = await service.get_status(plug)
  2583. if not status.get("reachable"):
  2584. logger.warning("Smart plug '%s' is not reachable", plug.name)
  2585. return False
  2586. # Turn on if not already on
  2587. if status.get("state") != "ON":
  2588. success = await service.turn_on(plug)
  2589. if not success:
  2590. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  2591. return False
  2592. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  2593. # Get printer from database for connection
  2594. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2595. printer = result.scalar_one_or_none()
  2596. if not printer:
  2597. logger.error("Printer %s not found in database", printer_id)
  2598. return False
  2599. # Wait for printer to boot (give it some time before trying to connect)
  2600. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  2601. await asyncio.sleep(30)
  2602. # Try to connect to the printer periodically
  2603. elapsed = 30 # Already waited 30s
  2604. while elapsed < self._power_on_wait_time:
  2605. # Try to connect
  2606. logger.info("Attempting to connect to printer %s...", printer_id)
  2607. try:
  2608. connected = await printer_manager.connect_printer(printer)
  2609. if connected:
  2610. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  2611. # Give it a moment to stabilize and get status
  2612. await asyncio.sleep(5)
  2613. return True
  2614. except Exception as e:
  2615. logger.debug("Connection attempt failed: %s", e)
  2616. await asyncio.sleep(self._power_on_check_interval)
  2617. elapsed += self._power_on_check_interval
  2618. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  2619. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  2620. return False
  2621. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  2622. """Check if the previous print on this printer succeeded.
  2623. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  2624. deliberate action, not a failure, so subsequent items should still
  2625. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  2626. a skip isn't an actual print attempt, so it must not gate downstream
  2627. items — counting it as a failed predecessor was the cascade bug that
  2628. let a single cancellation block 18 items over 3 days for the reporter.
  2629. Only `failed` and `aborted` — real print-attempt failures — block.
  2630. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  2631. action — #1818) are also excluded from the lookback so the user can
  2632. clear the gate after fixing the physical issue without having to
  2633. re-queue every downstream job.
  2634. """
  2635. result = await db.execute(
  2636. select(PrintQueueItem)
  2637. .where(PrintQueueItem.printer_id == item.printer_id)
  2638. .where(PrintQueueItem.id != item.id)
  2639. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  2640. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  2641. .order_by(PrintQueueItem.completed_at.desc())
  2642. .limit(1)
  2643. )
  2644. prev_item = result.scalar_one_or_none()
  2645. # If no previous item, assume success (first in queue)
  2646. if not prev_item:
  2647. return True
  2648. return prev_item.status in ("completed", "cancelled")
  2649. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  2650. """Schedule power-off if the queue item enabled auto_off_after.
  2651. Delegates to the smart-plug manager so the off honours each plug's
  2652. configured strategy (time delay or temperature threshold), is cancelled
  2653. if the printer starts printing again, and never cuts power on a loaded
  2654. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  2655. powered off on the timeout regardless of print state.
  2656. """
  2657. if not item.auto_off_after:
  2658. return
  2659. try:
  2660. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  2661. except Exception as e:
  2662. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  2663. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  2664. """Get a human-readable name for a queue item."""
  2665. if item.archive_id:
  2666. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2667. archive = result.scalar_one_or_none()
  2668. if archive:
  2669. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2670. if item.library_file_id:
  2671. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2672. library_file = result.scalar_one_or_none()
  2673. if library_file:
  2674. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2675. return f"Job #{item.id}"
  2676. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  2677. """Get printer by ID."""
  2678. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2679. return result.scalar_one_or_none()
  2680. async def _notify_dispatch_gave_up(
  2681. self,
  2682. queue_item_id: int,
  2683. printer_id: int,
  2684. created_by_id: int | None,
  2685. ) -> None:
  2686. """Tell the user the queue item was failed after exhausting its dispatch retries.
  2687. Called from the watchdog, which is a background task with no session of
  2688. its own — hence the fresh one here. Best-effort throughout: the row is
  2689. already marked failed and that is the load-bearing part; a notification
  2690. provider being down must not resurrect the retry loop we just stopped.
  2691. """
  2692. try:
  2693. async with async_session() as db:
  2694. item = await db.get(PrintQueueItem, queue_item_id)
  2695. if not item:
  2696. return
  2697. job_name = await self._get_job_name(db, item)
  2698. printer = await self._get_printer(db, printer_id)
  2699. await notification_service.on_queue_job_failed(
  2700. job_name=job_name,
  2701. printer_id=printer_id,
  2702. printer_name=printer.name if printer else "Unknown",
  2703. reason="Printer accepted the file but never started printing",
  2704. db=db,
  2705. )
  2706. except Exception as e:
  2707. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  2708. try:
  2709. await ws_manager.send_queue_item_failed(
  2710. user_id=created_by_id,
  2711. queue_item_id=queue_item_id,
  2712. printer_id=printer_id,
  2713. reason="never_started",
  2714. )
  2715. except Exception:
  2716. pass # toast is best-effort
  2717. async def _block_on_filament_deficit(
  2718. self,
  2719. db: AsyncSession,
  2720. item: PrintQueueItem,
  2721. ) -> bool:
  2722. """Promote the item to manual_start when the assigned spool is short (#1496).
  2723. Returns True when this dispatch attempt was blocked, False when the
  2724. item is clear to start. A previously-flagged item whose spool has
  2725. since been swapped to one with enough material clears the flag here
  2726. so the next scheduler tick dispatches it.
  2727. """
  2728. # User has explicitly acknowledged the deficit ("Print Anyway") —
  2729. # don't re-flag, don't even compute. Without this short-circuit the
  2730. # scheduler bounces between "user said anyway" (route clears
  2731. # manual_start) and "scheduler re-blocked" (this method re-flags it
  2732. # on identical spool state) (#1698-followup).
  2733. if item.skip_filament_check:
  2734. # #1762 diagnostic: surface the short-circuit at INFO so a
  2735. # future "Print Anyway didn't work" report (e.g. issue #1762
  2736. # comment 3) has actionable evidence in the support bundle
  2737. # without needing DEBUG enabled.
  2738. logger.info(
  2739. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  2740. item.id,
  2741. )
  2742. return False
  2743. try:
  2744. deficit = await compute_deficit_for_queue_item(db, item)
  2745. except Exception as e:
  2746. # Never let a flaky deficit check wedge the queue — log and let
  2747. # dispatch proceed. The PrintModal-side check still runs on the
  2748. # manual paths.
  2749. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  2750. return False
  2751. if deficit:
  2752. item.filament_short = True
  2753. item.manual_start = True
  2754. await db.commit()
  2755. job_name = await self._get_job_name(db, item)
  2756. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  2757. logger.info(
  2758. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  2759. item.id,
  2760. len(deficit),
  2761. )
  2762. try:
  2763. await notification_service.on_queue_job_waiting(
  2764. job_name=job_name,
  2765. target_model=(printer.model if printer else "") or "",
  2766. waiting_reason="filament_short",
  2767. db=db,
  2768. )
  2769. except Exception as e:
  2770. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  2771. return True
  2772. # No deficit — clear any stale flag from a previous tick.
  2773. if item.filament_short:
  2774. item.filament_short = False
  2775. await db.commit()
  2776. return False
  2777. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  2778. """Hand the queue item's owner to printer_manager so the
  2779. print-complete callback can credit the user in PrintLogEntry (#1670).
  2780. No-ops when the item has no `created_by_id` or the referenced user
  2781. row is missing (e.g. user deleted between queue-add and dispatch —
  2782. in that case the print log row falls back to the existing un-credited
  2783. behaviour rather than crashing the dispatch).
  2784. """
  2785. if not item.created_by_id:
  2786. return
  2787. from backend.app.models.user import User
  2788. owner = await db.get(User, item.created_by_id)
  2789. if owner:
  2790. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  2791. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  2792. """Upload file and start print for a queue item.
  2793. Supports two sources:
  2794. - archive_id: Print from an existing archive
  2795. - library_file_id: Print from a library file (file manager)
  2796. """
  2797. logger.info("Starting queue item %s", item.id)
  2798. # Also covers a reservation left active by a process interruption
  2799. # during an earlier attempt. `_dispatch_one` releases this marker on
  2800. # every exit unless start_print() confirms that the command was sent.
  2801. self._unconfirmed_budget_reservations.add(item.id)
  2802. try:
  2803. from backend.app.models.user import User
  2804. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  2805. await validate_print_budget(
  2806. db,
  2807. cost_center_id=item.cost_center_id,
  2808. estimated_cost=item.estimated_cost,
  2809. current_user=queue_user,
  2810. exclude_queue_item_id=item.id,
  2811. exclude_reservation_source_type="print_queue",
  2812. exclude_reservation_source_id=item.id,
  2813. )
  2814. budget_reservation = await create_budget_reservation(
  2815. db,
  2816. cost_center_id=item.cost_center_id,
  2817. estimated_cost=item.estimated_cost,
  2818. current_user=queue_user,
  2819. source_type="print_queue",
  2820. source_id=item.id,
  2821. print_archive_id=item.archive_id,
  2822. exclude_queue_item_id=item.id,
  2823. )
  2824. await db.commit()
  2825. except HTTPException as exc:
  2826. item.status = "failed"
  2827. item.error_message = str(exc.detail)
  2828. item.completed_at = datetime.now(timezone.utc)
  2829. await db.commit()
  2830. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  2831. await self._power_off_if_needed(db, item)
  2832. return
  2833. # Get printer first (needed for both paths)
  2834. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  2835. printer = result.scalar_one_or_none()
  2836. if not printer:
  2837. item.status = "failed"
  2838. item.error_message = "Printer not found"
  2839. item.completed_at = datetime.now(timezone.utc)
  2840. await db.commit()
  2841. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  2842. await self._power_off_if_needed(db, item)
  2843. return
  2844. # Check printer is connected
  2845. if not printer_manager.is_connected(item.printer_id):
  2846. item.status = "failed"
  2847. item.error_message = "Printer not connected"
  2848. item.completed_at = datetime.now(timezone.utc)
  2849. await db.commit()
  2850. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  2851. await self._power_off_if_needed(db, item)
  2852. return
  2853. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  2854. # `items` was taken at the top of check_queue, but the user can /cancel
  2855. # any pending row in the gap before we reach this point. Re-read the
  2856. # row and bail out cleanly instead of starting an FTP upload for a row
  2857. # that's already cancelled. The atomic CAS at the pending→printing
  2858. # transition (below, before start_print) is the load-bearing guard;
  2859. # this is the early-exit optimisation that avoids wasted FTP I/O.
  2860. await db.refresh(item)
  2861. if item.status != "pending":
  2862. logger.info(
  2863. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  2864. item.id,
  2865. item.status,
  2866. )
  2867. return
  2868. # Busy-printer guard (#2598). check_queue gates dispatch on
  2869. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  2870. # keep reporting FINISH for tens of seconds *after* it accepted a
  2871. # project_file (see the watchdog's phase-B note). A watchdog revert
  2872. # (#2555) also releases the dispatch hold, so a re-selected item can
  2873. # reach here while its printer has actually started printing. Uploading
  2874. # and dispatching then collides with the live job — the firmware answers
  2875. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  2876. # live state right before the expensive FTP upload: if the printer is
  2877. # busy, leave the item pending and let a later tick dispatch it once the
  2878. # printer is genuinely idle. No wasted upload, no collision.
  2879. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  2880. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  2881. logger.info(
  2882. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  2883. "leaving item pending for a later tick (#2598)",
  2884. item.id,
  2885. item.printer_id,
  2886. pre_dispatch_state,
  2887. )
  2888. return
  2889. # Determine source: archive or library file
  2890. archive = None
  2891. library_file = None
  2892. file_path = None
  2893. filename = None
  2894. cleanup_disk_paths: list[Path] = []
  2895. if item.archive_id:
  2896. # Print from archive
  2897. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2898. archive = result.scalar_one_or_none()
  2899. if not archive:
  2900. item.status = "failed"
  2901. item.error_message = "Archive not found"
  2902. item.completed_at = datetime.now(timezone.utc)
  2903. await db.commit()
  2904. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  2905. await self._power_off_if_needed(db, item)
  2906. return
  2907. # Persist the queue item's selected plate onto the archive so Print
  2908. # History can show the actual plate after cancel/fail/complete (#2603).
  2909. # Only when the archive doesn't already carry one, so a reprint of a
  2910. # plate-specific archive isn't relabelled by a differently-plated
  2911. # queue row.
  2912. if archive.plate_id is None and item.plate_id is not None:
  2913. archive.plate_id = item.plate_id
  2914. file_path = settings.base_dir / archive.file_path
  2915. filename = archive.filename
  2916. elif item.library_file_id:
  2917. # Print from library file (file manager)
  2918. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2919. library_file = result.scalar_one_or_none()
  2920. if not library_file:
  2921. item.status = "failed"
  2922. item.error_message = "Library file not found"
  2923. item.completed_at = datetime.now(timezone.utc)
  2924. await db.commit()
  2925. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  2926. await self._power_off_if_needed(db, item)
  2927. return
  2928. # Library files store absolute paths
  2929. lib_path = Path(library_file.file_path)
  2930. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  2931. filename = library_file.filename
  2932. # Create archive from library file so usage tracking has access to the 3MF
  2933. queue_item_id = item.id
  2934. try:
  2935. from backend.app.services.archive import ArchiveService
  2936. archive_service = ArchiveService(db)
  2937. archive = await archive_service.archive_print(
  2938. printer_id=item.printer_id,
  2939. source_file=file_path,
  2940. original_filename=filename,
  2941. created_by_id=item.created_by_id,
  2942. project_id=item.project_id,
  2943. cost_center_id=item.cost_center_id,
  2944. library_file_id=item.library_file_id, # per-file project progress (#1897)
  2945. plate_id=item.plate_id, # selected plate → Print History (#2603)
  2946. )
  2947. if archive:
  2948. item.archive_id = archive.id
  2949. if budget_reservation is not None:
  2950. budget_reservation.print_archive_id = archive.id
  2951. if item.cleanup_library_after_dispatch and not library_file.is_external:
  2952. item.library_file_id = None
  2953. cleanup_disk_paths.append(file_path)
  2954. if library_file.thumbnail_path:
  2955. thumb_path = Path(library_file.thumbnail_path)
  2956. if not thumb_path.is_absolute():
  2957. thumb_path = settings.base_dir / library_file.thumbnail_path
  2958. cleanup_disk_paths.append(thumb_path)
  2959. await db.delete(library_file)
  2960. file_path = settings.base_dir / archive.file_path
  2961. filename = archive.filename
  2962. # Commit, not flush — flush opens the SQLite write
  2963. # transaction (item.archive_id update + library_file
  2964. # delete) and would hold the WAL writer lock through the
  2965. # FTP upload below, causing "database is locked" cascades
  2966. # for sensor history + concurrent cancels (#1853).
  2967. await db.commit()
  2968. logger.info(
  2969. "Queue item %s: Created archive %s from library file %s",
  2970. item.id,
  2971. archive.id,
  2972. item.library_file_id,
  2973. )
  2974. except Exception as e:
  2975. logger.warning(
  2976. "Queue item %s: Failed to create archive from library file: %s",
  2977. queue_item_id,
  2978. e,
  2979. exc_info=True,
  2980. )
  2981. await db.rollback()
  2982. item = await db.get(PrintQueueItem, queue_item_id)
  2983. if item:
  2984. item.status = "failed"
  2985. item.error_message = "Failed to create archive from library file"
  2986. item.completed_at = datetime.now(timezone.utc)
  2987. await db.commit()
  2988. await self._power_off_if_needed(db, item)
  2989. return
  2990. if not archive:
  2991. item.status = "failed"
  2992. item.error_message = "Failed to create archive from library file"
  2993. item.completed_at = datetime.now(timezone.utc)
  2994. await db.commit()
  2995. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  2996. await self._power_off_if_needed(db, item)
  2997. return
  2998. else:
  2999. # Neither archive nor library file specified
  3000. item.status = "failed"
  3001. item.error_message = "No source file specified"
  3002. item.completed_at = datetime.now(timezone.utc)
  3003. await db.commit()
  3004. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  3005. await self._power_off_if_needed(db, item)
  3006. return
  3007. # Check file exists on disk
  3008. if not file_path.exists():
  3009. item.status = "failed"
  3010. item.error_message = "Source file not found on disk"
  3011. item.completed_at = datetime.now(timezone.utc)
  3012. await db.commit()
  3013. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  3014. await self._power_off_if_needed(db, item)
  3015. return
  3016. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  3017. # size dispatched to a printer with a different nozzle installed is
  3018. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  3019. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  3020. # gives the user no idea what went wrong. Catch it here, before we spend
  3021. # time preheating and uploading, and fail with an actionable message.
  3022. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  3023. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  3024. # the printer hasn't reported its nozzles yet, we fall through and let the
  3025. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  3026. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  3027. # as one of the two hotends is a 0.6.
  3028. sliced_nozzle = archive.nozzle_diameter if archive else None
  3029. if sliced_nozzle:
  3030. installed = _installed_nozzle_diameters(printer_manager.get_status(item.printer_id))
  3031. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed)
  3032. if mismatch_msg:
  3033. item.status = "failed"
  3034. item.error_message = mismatch_msg
  3035. item.completed_at = datetime.now(timezone.utc)
  3036. await db.commit()
  3037. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  3038. await notification_service.on_queue_job_failed(
  3039. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3040. printer_id=printer.id,
  3041. printer_name=printer.name,
  3042. reason=mismatch_msg,
  3043. db=db,
  3044. )
  3045. try:
  3046. await ws_manager.send_queue_item_failed(
  3047. user_id=item.created_by_id,
  3048. queue_item_id=item.id,
  3049. printer_id=item.printer_id,
  3050. reason="nozzle_mismatch",
  3051. )
  3052. except Exception:
  3053. pass
  3054. await self._power_off_if_needed(db, item)
  3055. return
  3056. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  3057. # bed (and chamber, if applicable) is at temperature when the firmware
  3058. # starts the actual print routine. Best-effort: any failure logs and
  3059. # falls through to the normal upload+start path rather than turning a
  3060. # configuration issue into a failed queue item.
  3061. await self._preheat_and_soak(db, item, printer, archive)
  3062. # G-code injection for auto-print systems (#422)
  3063. injected_path = None
  3064. if item.gcode_injection:
  3065. try:
  3066. snippets_raw = await self._get_setting(db, "gcode_snippets")
  3067. if snippets_raw:
  3068. snippets = json.loads(snippets_raw)
  3069. model_snippets = snippets.get(printer.model, {})
  3070. start_gc = (model_snippets.get("start_gcode") or "").strip()
  3071. end_gc = (model_snippets.get("end_gcode") or "").strip()
  3072. if start_gc or end_gc:
  3073. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  3074. injected_path = inject_gcode_into_3mf(
  3075. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  3076. )
  3077. if injected_path:
  3078. file_path = injected_path
  3079. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  3080. else:
  3081. logger.warning(
  3082. "Queue item %s: G-code injection returned no result, using original", item.id
  3083. )
  3084. except Exception as e:
  3085. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  3086. # Upload to root directory (not /cache/) - the start_print command references
  3087. # files by name only (ftp://{filename}), so they must be in the root
  3088. remote_filename = derive_remote_filename(filename)
  3089. remote_path = f"/{remote_filename}"
  3090. # Get FTP retry settings
  3091. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3092. logger.info(
  3093. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  3094. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  3095. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  3096. )
  3097. # Release the pooled DB connection before the FTP delete/upload (#2572).
  3098. # Every read this method needs (printer, archive/library, preheat) is
  3099. # done, and the library-file branch already committed its archive
  3100. # creation. Without this the transaction opened by the first SELECT above
  3101. # stays "idle in transaction" for the entire upload — multiple seconds
  3102. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  3103. # a farm dispatching many jobs at once then exhausts the pool. This was
  3104. # correlated to an exact idle-in-transaction session on a 93-printer farm
  3105. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  3106. # readable; the status writes below (upload-failure path and the
  3107. # pending->printing CAS) transparently open a fresh transaction.
  3108. await db.commit()
  3109. # Delete existing file if present (avoids 553 error on overwrite)
  3110. try:
  3111. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  3112. delete_result = await delete_file_async(
  3113. printer.ip_address,
  3114. printer.access_code,
  3115. remote_path,
  3116. socket_timeout=ftp_timeout,
  3117. printer_model=printer.model,
  3118. )
  3119. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  3120. except Exception as e:
  3121. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  3122. # Dispatch toast — announce the upload start with the total byte
  3123. # count so the frontend can render an honest progress bar.
  3124. toast_uid = item.created_by_id
  3125. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3126. try:
  3127. total_bytes = file_path.stat().st_size
  3128. except OSError:
  3129. total_bytes = 0
  3130. try:
  3131. await ws_manager.send_queue_item_uploading(
  3132. user_id=toast_uid,
  3133. queue_item_id=item.id,
  3134. printer_id=item.printer_id,
  3135. printer_name=printer.name,
  3136. file_name=toast_file_name,
  3137. total_bytes=total_bytes,
  3138. )
  3139. except Exception:
  3140. pass # toast is best-effort
  3141. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  3142. # A deadline expiry gets its own message: "check your SD card" is the
  3143. # wrong advice for a link that was simply too slow to finish (#2529).
  3144. upload_error: str | None = None
  3145. try:
  3146. if ftp_retry_enabled:
  3147. uploaded = await with_ftp_retry(
  3148. upload_file_async,
  3149. printer.ip_address,
  3150. printer.access_code,
  3151. file_path,
  3152. remote_path,
  3153. socket_timeout=ftp_timeout,
  3154. printer_model=printer.model,
  3155. progress_callback=progress_bridge,
  3156. max_retries=ftp_retry_count,
  3157. retry_delay=ftp_retry_delay,
  3158. operation_name=f"Upload print to {printer.name}",
  3159. )
  3160. else:
  3161. uploaded = await upload_file_async(
  3162. printer.ip_address,
  3163. printer.access_code,
  3164. file_path,
  3165. remote_path,
  3166. socket_timeout=ftp_timeout,
  3167. printer_model=printer.model,
  3168. progress_callback=progress_bridge,
  3169. )
  3170. except UploadCancelled as e:
  3171. uploaded = False
  3172. upload_error = (
  3173. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  3174. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  3175. )
  3176. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  3177. except Exception as e:
  3178. uploaded = False
  3179. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  3180. # Clean up injected temp file after upload attempt
  3181. if injected_path and injected_path.exists():
  3182. injected_path.unlink(missing_ok=True)
  3183. if not uploaded:
  3184. error_msg = upload_error or (
  3185. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  3186. "See server logs for detailed diagnostics."
  3187. )
  3188. item.status = "failed"
  3189. item.error_message = error_msg
  3190. item.completed_at = datetime.now(timezone.utc)
  3191. await db.commit()
  3192. logger.error(
  3193. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  3194. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  3195. )
  3196. # Send failure notification
  3197. await notification_service.on_queue_job_failed(
  3198. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3199. printer_id=printer.id,
  3200. printer_name=printer.name,
  3201. reason="Failed to upload file to printer",
  3202. db=db,
  3203. )
  3204. try:
  3205. await ws_manager.send_queue_item_failed(
  3206. user_id=toast_uid,
  3207. queue_item_id=item.id,
  3208. printer_id=item.printer_id,
  3209. reason="upload_failed",
  3210. )
  3211. except Exception:
  3212. pass
  3213. await self._power_off_if_needed(db, item)
  3214. return
  3215. # Parse AMS mapping if stored
  3216. ams_mapping = None
  3217. if item.ams_mapping:
  3218. try:
  3219. ams_mapping = json.loads(item.ams_mapping)
  3220. except json.JSONDecodeError:
  3221. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  3222. # Register as expected print so we don't create a duplicate archive
  3223. # Only applicable for archive-based prints
  3224. if archive:
  3225. from backend.app.main import register_expected_print
  3226. register_expected_print(
  3227. item.printer_id,
  3228. remote_filename,
  3229. archive.id,
  3230. ams_mapping=ams_mapping,
  3231. created_by_id=item.created_by_id,
  3232. cost_center_id=item.cost_center_id,
  3233. plate_id=item.plate_id,
  3234. )
  3235. # Registration happens before the print command by necessity (the
  3236. # printer can report the print before the send returns), so record
  3237. # what to undo if we never get as far as sending. `_dispatch_one`
  3238. # rolls back anything still pending here on every exit — exception,
  3239. # early return, or cancel winning the CAS below.
  3240. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  3241. # Propagate the queue item's owner into printer_manager so the
  3242. # print-complete callback can credit the user in the PrintLogEntry
  3243. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  3244. # items) or when the user clicks the manual-start button.
  3245. await self._propagate_owner_to_printer_manager(db, item)
  3246. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  3247. # This prevents phantom reprints if the backend crashes/restarts after the
  3248. # print command is sent but before the status update is committed.
  3249. # If we crash after this commit but before start_print(), the item will be
  3250. # in "printing" status without actually printing - but that's safer than
  3251. # accidentally reprinting the same file hours later.
  3252. #
  3253. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  3254. # initial pending read at the top of check_queue and this point) flips
  3255. # the row to "cancelled" in a separate session. Without the WHERE
  3256. # status='pending' clause, the unconditional update here would silently
  3257. # overwrite that cancellation and we'd ship the MQTT start_print below
  3258. # — printer obeys, user sees "I pressed cancel and the print started".
  3259. # rowcount==0 means the user won the race; bail out, best-effort delete
  3260. # the file we just uploaded, do NOT send start_print.
  3261. now_utc = datetime.now(timezone.utc)
  3262. cas = await db.execute(
  3263. update(PrintQueueItem)
  3264. .where(PrintQueueItem.id == item.id)
  3265. .where(PrintQueueItem.status == "pending")
  3266. .values(status="printing", started_at=now_utc)
  3267. )
  3268. await db.commit()
  3269. if cas.rowcount == 0:
  3270. logger.info(
  3271. "Queue item %s no longer pending at print-command time "
  3272. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  3273. item.id,
  3274. )
  3275. try:
  3276. await delete_file_async(
  3277. printer.ip_address,
  3278. printer.access_code,
  3279. remote_path,
  3280. socket_timeout=ftp_timeout,
  3281. printer_model=printer.model,
  3282. )
  3283. except Exception as cleanup_err:
  3284. logger.debug(
  3285. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  3286. item.id,
  3287. cleanup_err,
  3288. )
  3289. try:
  3290. await ws_manager.send_queue_item_failed(
  3291. user_id=toast_uid,
  3292. queue_item_id=item.id,
  3293. printer_id=item.printer_id,
  3294. reason="cancelled_mid_dispatch",
  3295. )
  3296. except Exception:
  3297. pass
  3298. return
  3299. # Sync the in-memory item so subsequent code that reads item.status /
  3300. # item.started_at sees the values we just persisted.
  3301. item.status = "printing"
  3302. item.started_at = now_utc
  3303. for cleanup_path in cleanup_disk_paths:
  3304. try:
  3305. if cleanup_path.exists():
  3306. cleanup_path.unlink()
  3307. except OSError as cleanup_err:
  3308. logger.warning(
  3309. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  3310. json.dumps(
  3311. {
  3312. "queue_item_id": item.id,
  3313. "path": str(cleanup_path),
  3314. "error": str(cleanup_err),
  3315. },
  3316. sort_keys=True,
  3317. ),
  3318. )
  3319. # Clear the awaiting-plate-clear flag now that we're starting a new print
  3320. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  3321. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  3322. # Capture state before dispatch so the watchdog can detect whether the
  3323. # printer actually transitioned (#967). Also capture subtask_id so the
  3324. # watchdog can recognise "command landed but state hasn't flipped yet"
  3325. # on slow H2D transitions (#1078).
  3326. pre_status = printer_manager.get_status(item.printer_id)
  3327. pre_state = getattr(pre_status, "state", None) if pre_status else None
  3328. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  3329. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  3330. # #1721: respect the user's explicit timelapse choice. The #1397
  3331. # force-on at dispatch was removed because it caused per-layer nozzle
  3332. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  3333. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  3334. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  3335. # FINISH-state fallback — no need to force a video.
  3336. effective_timelapse = bool(item.timelapse)
  3337. # Start the print with AMS mapping, plate_id and print options.
  3338. # nozzle_mapping rides through verbatim — JSON string captured from
  3339. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  3340. # parses + injects it only for dual-nozzle models so a null on every
  3341. # other model is a transparent pass-through.
  3342. started = printer_manager.start_print(
  3343. item.printer_id,
  3344. remote_filename,
  3345. plate_id=item.plate_id or 1,
  3346. ams_mapping=ams_mapping,
  3347. bed_levelling=item.bed_levelling,
  3348. flow_cali=item.flow_cali,
  3349. vibration_cali=item.vibration_cali,
  3350. layer_inspect=item.layer_inspect,
  3351. timelapse=effective_timelapse,
  3352. use_ams=item.use_ams,
  3353. nozzle_offset_cali=item.nozzle_offset_cali,
  3354. nozzle_mapping=item.nozzle_mapping,
  3355. )
  3356. if started:
  3357. # The command is away, so the expectation is now legitimate and must
  3358. # survive. Anything still in this dict when _dispatch_one exits gets
  3359. # rolled back.
  3360. self._unconfirmed_expected_print.pop(item.id, None)
  3361. self._unconfirmed_budget_reservations.discard(item.id)
  3362. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  3363. # No dispatch-toast event here: the legacy bg-dispatch path kept
  3364. # status='processing' from upload start until the printer acked
  3365. # (or timed out). The frontend derives "Awaiting printer…" purely
  3366. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  3367. # event would push the status chip out of 'PROCESSING' prematurely
  3368. # — which is exactly what the screenshot at #1625-followup
  3369. # complained about.
  3370. # Register the local 3MF in the cover-cache so /cover skips FTP
  3371. # (#1166 follow-up). file_path was resolved earlier from either the
  3372. # archive or the library file row.
  3373. if file_path is not None:
  3374. cache_3mf_download(item.printer_id, remote_filename, file_path)
  3375. # Hold the printer against further dispatches until the watchdog
  3376. # confirms the printer transitioned (or until the hard timeout).
  3377. # Prevents multi-plate batches from triple-dispatching onto the
  3378. # same H2D Pro while it digests the first project_file (#1157).
  3379. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  3380. # Watchdog: if the printer never transitions out of pre_state AND
  3381. # never advances subtask_id, the MQTT publish was accepted locally but
  3382. # didn't reach the printer (half-broken session — same shape as
  3383. # #887/#936). Revert the queue item so the next dispatch can pick it
  3384. # up instead of leaving it stuck in "printing" (#967). subtask_id
  3385. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  3386. # that would otherwise cause the item to re-dispatch as a reprint
  3387. # of the just-finished job (#1078).
  3388. if pre_state:
  3389. spawn_background_task(
  3390. self._watchdog_print_start(
  3391. item.id,
  3392. item.printer_id,
  3393. pre_state,
  3394. pre_subtask_id,
  3395. pre_gcode_file,
  3396. created_by_id=toast_uid,
  3397. ),
  3398. name=f"watchdog-print-start-{item.id}",
  3399. )
  3400. # Get estimated time for notification.
  3401. #
  3402. # This used to fall back to `library_file.print_time_seconds`, a column
  3403. # LibraryFile does not have — the print time it knows about lives in
  3404. # `file_metadata`. So a library print whose archive carried no parseable
  3405. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  3406. # AttributeError right here, *after* the printer had already been sent
  3407. # the job: the started-notification never fired, and the exception
  3408. # unwound the whole queue pass, so every other printer still waiting to
  3409. # be dispatched on that tick silently missed its turn.
  3410. #
  3411. # The queue item caches the print time at creation ("Cached from
  3412. # archive/library"), which is the value this was reaching for.
  3413. estimated_time = None
  3414. if archive and archive.print_time_seconds:
  3415. estimated_time = archive.print_time_seconds
  3416. elif item.print_time_seconds:
  3417. estimated_time = item.print_time_seconds
  3418. # Send job started notification
  3419. await notification_service.on_queue_job_started(
  3420. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3421. printer_id=printer.id,
  3422. printer_name=printer.name,
  3423. db=db,
  3424. estimated_time=estimated_time,
  3425. )
  3426. # MQTT relay - publish queue job started
  3427. try:
  3428. from backend.app.services.mqtt_relay import mqtt_relay
  3429. await mqtt_relay.on_queue_job_started(
  3430. job_id=item.id,
  3431. filename=filename,
  3432. printer_id=printer.id,
  3433. printer_name=printer.name,
  3434. printer_serial=printer.serial_number,
  3435. )
  3436. except Exception:
  3437. pass # Don't fail if MQTT fails
  3438. else:
  3439. # Clean up uploaded file from SD card to prevent phantom prints
  3440. try:
  3441. await delete_file_async(
  3442. printer.ip_address,
  3443. printer.access_code,
  3444. remote_path,
  3445. printer_model=printer.model,
  3446. )
  3447. except Exception:
  3448. pass # Best-effort — don't fail the error handler
  3449. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  3450. # state can flip from idle to active in the window between the
  3451. # pre-dispatch check above and this publish (the FTP upload takes
  3452. # seconds); start_print() then refuses to send project_file to the
  3453. # now-busy printer and returns False. Failing the item here would be
  3454. # wrong — the printer is fine, it is simply busy — so revert to
  3455. # pending and let a later tick dispatch it once the printer is idle,
  3456. # exactly like the pre-dispatch guard. Only a start_print() False on
  3457. # an idle/unknown printer is a genuine command failure.
  3458. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  3459. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  3460. logger.info(
  3461. "Queue item %s: printer %s became busy (state=%s) before the start "
  3462. "command was sent — deferring, reverting item to pending (#2598)",
  3463. item.id,
  3464. item.printer_id,
  3465. post_dispatch_state,
  3466. )
  3467. item.status = "pending"
  3468. item.started_at = None
  3469. await db.commit()
  3470. return
  3471. # Print command failed - revert status
  3472. item.status = "failed"
  3473. item.error_message = "Failed to send print command to printer"
  3474. item.completed_at = datetime.now(timezone.utc)
  3475. await db.commit()
  3476. logger.error(
  3477. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  3478. f"printer_manager.start_print() returned False. "
  3479. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  3480. f"Check printer status and backend logs for details."
  3481. )
  3482. # Send failure notification
  3483. await notification_service.on_queue_job_failed(
  3484. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3485. printer_id=printer.id,
  3486. printer_name=printer.name,
  3487. reason="Failed to send print command to printer - check printer connection and status",
  3488. db=db,
  3489. )
  3490. try:
  3491. await ws_manager.send_queue_item_failed(
  3492. user_id=toast_uid,
  3493. queue_item_id=item.id,
  3494. printer_id=item.printer_id,
  3495. reason="start_command_failed",
  3496. )
  3497. except Exception:
  3498. pass
  3499. await self._power_off_if_needed(db, item)
  3500. @staticmethod
  3501. async def _watchdog_print_start(
  3502. queue_item_id: int,
  3503. printer_id: int,
  3504. pre_state: str,
  3505. pre_subtask_id: str | None = None,
  3506. pre_gcode_file: str | None = None,
  3507. timeout: float = 90.0,
  3508. phase_b_timeout: float = 180.0,
  3509. poll_interval: float = 3.0,
  3510. created_by_id: int | None = None,
  3511. ) -> None:
  3512. """Revert a queue item if the printer never acknowledges the start command.
  3513. Bambuddy optimistically marks the queue item as "printing" right after the
  3514. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  3515. Phase A (up to ``timeout``): wait for either an active-state transition
  3516. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  3517. primary signal; subtask_id advance handles the H2D case where state can
  3518. sit at FINISH for ~50 s after the printer accepted ``project_file``
  3519. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  3520. was lost on a half-broken session (#887/#936) — revert and force
  3521. reconnect (the #967 recovery path).
  3522. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  3523. alone): keep watching for the active-state transition. subtask_id alone
  3524. proves the file landed but not that the printer started — and a printer
  3525. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  3526. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  3527. used to leave the queue item stuck in 'printing' forever because the
  3528. old watchdog returned success as soon as subtask_id advanced. If Phase
  3529. B times out, revert the queue item so the user can retry without
  3530. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  3531. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  3532. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  3533. transitions that also don't emit an early subtask_id tick.
  3534. """
  3535. last_status = None
  3536. landed_on_subtask = False
  3537. deadline = time.monotonic() + timeout
  3538. while time.monotonic() < deadline:
  3539. await asyncio.sleep(poll_interval)
  3540. status = printer_manager.get_status(printer_id)
  3541. if not status:
  3542. # Printer disconnected — don't mess with the DB. Drop the
  3543. # in-memory dispatch hold too so a fresh dispatch can retry
  3544. # once the printer comes back; the hard timeout would
  3545. # otherwise hold the printer unnecessarily.
  3546. scheduler._release_dispatch_hold(printer_id)
  3547. return
  3548. last_status = status
  3549. if status.state in _ACTIVE_PRINT_STATES:
  3550. # Printer is actively processing the job — release the
  3551. # post-dispatch hold so the next pending item for this printer
  3552. # can be evaluated normally. We do NOT accept arbitrary state
  3553. # transitions: a printer going FINISH -> IDLE (user dismissed
  3554. # the post-print prompt without accepting our project_file)
  3555. # would otherwise look like "command landed" and leave the
  3556. # queue item stuck in 'printing' forever (#1370).
  3557. scheduler._release_dispatch_hold(printer_id)
  3558. try:
  3559. await ws_manager.send_queue_item_acked(
  3560. user_id=created_by_id,
  3561. queue_item_id=queue_item_id,
  3562. printer_id=printer_id,
  3563. )
  3564. except Exception:
  3565. pass
  3566. return
  3567. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  3568. # Phase A exit — printer accepted the file (subtask_id flipped
  3569. # to our submission id). Don't return yet: the printer may
  3570. # have accepted the command but never actually start (e.g.
  3571. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  3572. # B watches for the active-state transition.
  3573. landed_on_subtask = True
  3574. break
  3575. if landed_on_subtask:
  3576. phase_b_deadline = time.monotonic() + phase_b_timeout
  3577. while time.monotonic() < phase_b_deadline:
  3578. await asyncio.sleep(poll_interval)
  3579. status = printer_manager.get_status(printer_id)
  3580. if not status:
  3581. scheduler._release_dispatch_hold(printer_id)
  3582. return
  3583. last_status = status
  3584. if status.state in _ACTIVE_PRINT_STATES:
  3585. scheduler._release_dispatch_hold(printer_id)
  3586. try:
  3587. await ws_manager.send_queue_item_acked(
  3588. user_id=created_by_id,
  3589. queue_item_id=queue_item_id,
  3590. printer_id=printer_id,
  3591. )
  3592. except Exception:
  3593. pass
  3594. return
  3595. # No active-state transition. Revert the item so the scheduler can retry.
  3596. # Drop the in-memory hold so the retry isn't blocked by it.
  3597. scheduler._release_dispatch_hold(printer_id)
  3598. # Four outcomes from the revert attempt, each routed differently:
  3599. # "reverted": row flipped from printing -> pending, run recovery
  3600. # "gave_up": same, but the retry budget is spent — row failed
  3601. # rather than pending, so it stops going round again
  3602. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  3603. # on_print_complete or user). Skip recovery entirely
  3604. # — the print clearly landed somewhere even if the
  3605. # watchdog didn't see the active-state transition.
  3606. # "revert_failed": SQLite contention exhausted retries. Still run
  3607. # recovery so the MQTT session gets a fresh client_id
  3608. # on the half-broken-session path.
  3609. #
  3610. # The retry budget (#2555): reverting to 'pending' hands the item straight
  3611. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  3612. # the watchdog again. For a printer that is genuinely wedged that loop never
  3613. # ends — the reporter had one printer "since this morning still not launch"
  3614. # — and each lap also consumes an upload slot that the other printers in the
  3615. # farm are waiting on. Retrying is right; retrying forever is not.
  3616. async def _do_revert(db):
  3617. item = await db.get(PrintQueueItem, queue_item_id)
  3618. if not item or item.status != "printing":
  3619. return "already_moved_on"
  3620. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  3621. item.started_at = None
  3622. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  3623. item.status = "failed"
  3624. item.error_message = (
  3625. f"The printer accepted the file but never started printing, after "
  3626. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  3627. f"prompt or error, confirm its SD card is readable, and start the job again."
  3628. )
  3629. item.completed_at = datetime.now(timezone.utc)
  3630. await release_budget_reservation(
  3631. db,
  3632. source_type="print_queue",
  3633. source_id=item.id,
  3634. status="released",
  3635. )
  3636. await db.commit()
  3637. return "gave_up"
  3638. item.status = "pending"
  3639. await db.commit()
  3640. return "reverted"
  3641. try:
  3642. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  3643. except Exception as e:
  3644. logger.warning(
  3645. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  3646. "scheduler may keep treating this item as in-flight",
  3647. queue_item_id,
  3648. printer_id,
  3649. e,
  3650. )
  3651. revert_outcome = "revert_failed"
  3652. if revert_outcome == "already_moved_on":
  3653. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  3654. # other path) already moved the item past 'printing', don't run the
  3655. # MQTT session-recovery logic below — a forced reconnect on a healthy
  3656. # session breaks ongoing prints on the same printer.
  3657. return
  3658. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  3659. if revert_outcome == "gave_up":
  3660. logger.error(
  3661. "Queue item %s: printer %d never started the print after %d dispatch "
  3662. "attempts (last one waited %.0fs) — marking the item failed instead of "
  3663. "re-uploading it again (#2555)",
  3664. queue_item_id,
  3665. printer_id,
  3666. DISPATCH_MAX_ATTEMPTS,
  3667. total_timeout,
  3668. )
  3669. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  3670. elif revert_outcome == "reverted":
  3671. if landed_on_subtask:
  3672. logger.warning(
  3673. "Queue item %s: printer %d accepted project_file (subtask_id "
  3674. "advanced) but never transitioned to an active state within "
  3675. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  3676. "for retry (#1678)",
  3677. queue_item_id,
  3678. printer_id,
  3679. total_timeout,
  3680. )
  3681. else:
  3682. logger.warning(
  3683. "Queue item %s: printer %d did not respond to print command within "
  3684. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  3685. "for retry (#967)",
  3686. queue_item_id,
  3687. printer_id,
  3688. timeout,
  3689. pre_state,
  3690. pre_subtask_id,
  3691. )
  3692. # Phase B was entered iff subtask_id advanced, which means the
  3693. # project_file landed on the printer. A forced reconnect at this point
  3694. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  3695. # skip the recovery entirely.
  3696. if landed_on_subtask:
  3697. return
  3698. # Phase A timeout path: if the printer's gcode_file changed since
  3699. # pre-dispatch, the project_file command landed and the printer is
  3700. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  3701. # If gcode_file is unchanged, the publish was silently swallowed
  3702. # (#887/#936) and force_reconnect recovery is what we want.
  3703. client = printer_manager.get_client(printer_id)
  3704. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  3705. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  3706. if publish_landed:
  3707. logger.warning(
  3708. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  3709. "received the command and is parsing slowly. Skipping forced "
  3710. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  3711. queue_item_id,
  3712. current_gcode_file,
  3713. pre_gcode_file,
  3714. )
  3715. elif client and hasattr(client, "force_reconnect_stale_session"):
  3716. client.force_reconnect_stale_session(
  3717. f"queue print command unacknowledged after {timeout:.0f}s "
  3718. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  3719. )
  3720. # Global scheduler instance
  3721. scheduler = PrintScheduler()