print_scheduler.py 154 KB

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