print_scheduler.py 172 KB

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