print_scheduler.py 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  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. # Get filament requirements from source file
  792. filament_reqs = await self._get_filament_requirements(db, item)
  793. if not filament_reqs:
  794. # When the 3MF can't be read but force-color overrides are present, build a
  795. # direct mapping from the overrides so the printer uses the correct AMS slot.
  796. if item.filament_overrides:
  797. try:
  798. overrides = json.loads(item.filament_overrides)
  799. force_overrides = [o for o in overrides if o.get("force_color_match")]
  800. if force_overrides:
  801. logger.info(
  802. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  803. "force-color override(s)",
  804. item.id,
  805. len(force_overrides),
  806. )
  807. return self._build_override_direct_mapping(force_overrides, status)
  808. except (json.JSONDecodeError, KeyError, TypeError) as e:
  809. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  810. logger.debug("No filament requirements found for queue item %s", item.id)
  811. return None
  812. # Apply filament overrides if present
  813. if item.filament_overrides:
  814. try:
  815. overrides = json.loads(item.filament_overrides)
  816. override_map = {o["slot_id"]: o for o in overrides}
  817. for req in filament_reqs:
  818. if req["slot_id"] in override_map:
  819. override = override_map[req["slot_id"]]
  820. req["type"] = override["type"]
  821. req["color"] = override["color"]
  822. # Clear tray_info_idx so matching uses type+color instead of
  823. # the original 3MF's tray_info_idx (which would match the old filament)
  824. req["tray_info_idx"] = ""
  825. logger.debug(
  826. "Queue item %s: Override slot %d -> %s %s",
  827. item.id,
  828. req["slot_id"],
  829. override["type"],
  830. override["color"],
  831. )
  832. except (json.JSONDecodeError, KeyError, TypeError) as e:
  833. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  834. # Build loaded filaments from printer status
  835. loaded_filaments = self._build_loaded_filaments(status)
  836. if not loaded_filaments:
  837. logger.debug("No filaments loaded on printer %s", printer_id)
  838. return None
  839. # Check if user prefers lowest remaining filament when multiple spools match
  840. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  841. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  842. # Without backup, the printer will not switch to a second spool when the
  843. # picked one runs out — so sorting toward the lowest leaves the print
  844. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  845. # today's behaviour intentionally.
  846. if prefer_lowest and status.ams_filament_backup is False:
  847. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  848. prefer_lowest = False
  849. # When the preference is on, surface Bambuddy's inventory-side
  850. # remaining for each slot that's bound to a tracked spool, so the
  851. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  852. # entirely when the preference is off — no behaviour change for
  853. # users who haven't opted in.
  854. inventory_remain_overrides: dict[int, float] | None = None
  855. if prefer_lowest:
  856. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  857. # Compute mapping: match required filaments to available slots
  858. return self._match_filaments_to_slots(
  859. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides
  860. )
  861. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  862. """Build an AMS mapping directly from force-color overrides without a 3MF.
  863. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  864. slice_info is missing or unreadable) but ``force_color_match`` overrides
  865. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  866. treated as the filament requirement for that slot and matched against the
  867. current AMS state of the printer.
  868. Returns the same format as ``_match_filaments_to_slots``, or None when
  869. the AMS has no loaded filaments.
  870. """
  871. loaded = self._build_loaded_filaments(status)
  872. if not loaded:
  873. return None
  874. reqs = [
  875. {
  876. "slot_id": o["slot_id"],
  877. "type": o.get("type", ""),
  878. "color": o.get("color", ""),
  879. "tray_info_idx": "",
  880. }
  881. for o in force_overrides
  882. ]
  883. return self._match_filaments_to_slots(reqs, loaded)
  884. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  885. """Resolve the queue item's source 3MF and parse the per-slot
  886. filament requirements out of it. Thin DB-resolver wrapper around
  887. ``filament_requirements.extract_filament_requirements`` so the VP
  888. queue-mode write path (#1188) can reuse the same parser at upload
  889. time.
  890. """
  891. from backend.app.services.filament_requirements import extract_filament_requirements
  892. file_path: Path | None = None
  893. if item.archive_id:
  894. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  895. archive = result.scalar_one_or_none()
  896. if archive:
  897. file_path = settings.base_dir / archive.file_path
  898. elif item.library_file_id:
  899. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  900. library_file = result.scalar_one_or_none()
  901. if library_file:
  902. lib_path = Path(library_file.file_path)
  903. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  904. if not file_path or not file_path.exists():
  905. return None
  906. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  907. return filaments if filaments else None
  908. def _build_loaded_filaments(self, status) -> list[dict]:
  909. """Build list of loaded filaments from printer status.
  910. Args:
  911. status: PrinterState from printer_manager
  912. Returns:
  913. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  914. """
  915. filaments = []
  916. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  917. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  918. # Parse AMS units from raw_data
  919. ams_data = status.raw_data.get("ams", [])
  920. for ams_unit in ams_data:
  921. ams_id = int(ams_unit.get("id", 0))
  922. trays = ams_unit.get("tray", [])
  923. is_ht = len(trays) == 1 # AMS-HT has single tray
  924. for tray in trays:
  925. tray_type = tray.get("tray_type")
  926. if tray_type:
  927. tray_id = int(tray.get("id", 0))
  928. tray_color = tray.get("tray_color", "")
  929. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  930. tray_info_idx = tray.get("tray_info_idx", "")
  931. # Normalize color: remove alpha, add hash
  932. color = self._normalize_color(tray_color)
  933. # Calculate global tray ID
  934. # AMS-HT units have IDs starting at 128 with a single tray
  935. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  936. filaments.append(
  937. {
  938. "type": tray_type,
  939. "color": color,
  940. "tray_info_idx": tray_info_idx,
  941. "ams_id": ams_id,
  942. "tray_id": tray_id,
  943. "is_ht": is_ht,
  944. "is_external": False,
  945. "global_tray_id": global_tray_id,
  946. "extruder_id": ams_extruder_map.get(str(ams_id)),
  947. "remain": tray.get("remain", -1),
  948. }
  949. )
  950. # Check external spool(s) (vt_tray is a list)
  951. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  952. if vt.get("tray_type"):
  953. color = self._normalize_color(vt.get("tray_color", ""))
  954. tray_id = int(vt.get("id", 254))
  955. filaments.append(
  956. {
  957. "type": vt["tray_type"],
  958. "color": color,
  959. "tray_info_idx": vt.get("tray_info_idx", ""),
  960. "ams_id": -1,
  961. "tray_id": idx,
  962. "is_ht": False,
  963. "is_external": True,
  964. "global_tray_id": tray_id,
  965. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  966. "remain": vt.get("remain", -1),
  967. }
  968. )
  969. return filaments
  970. def _normalize_color(self, color: str | None) -> str:
  971. """Normalize color to #RRGGBB format."""
  972. if not color:
  973. return "#808080"
  974. hex_color = color.replace("#", "")[:6]
  975. return f"#{hex_color}"
  976. def _normalize_color_for_compare(self, color: str | None) -> str:
  977. """Normalize color for comparison (lowercase, no hash)."""
  978. if not color:
  979. return ""
  980. return color.replace("#", "").lower()[:6]
  981. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  982. """Check if two colors are visually similar within a threshold."""
  983. hex1 = self._normalize_color_for_compare(color1)
  984. hex2 = self._normalize_color_for_compare(color2)
  985. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  986. return False
  987. try:
  988. r1 = int(hex1[0:2], 16)
  989. g1 = int(hex1[2:4], 16)
  990. b1 = int(hex1[4:6], 16)
  991. r2 = int(hex2[0:2], 16)
  992. g2 = int(hex2[2:4], 16)
  993. b2 = int(hex2[4:6], 16)
  994. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  995. except ValueError:
  996. return False
  997. async def _build_inventory_remain_overrides(
  998. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  999. ) -> dict[int, float]:
  1000. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  1001. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  1002. The MQTT ``remain`` field on a tray is the printer firmware's
  1003. RFID-decremented value, which has two limitations the "Prefer Lowest
  1004. Remaining Filament" feature has been ignoring (#1508):
  1005. - it's only meaningful for Bambu RFID spools; everything else reports
  1006. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  1007. compare equal and the sort collapses to AMS-slot order — the user
  1008. who's curating inventory weights gets the lower-slot pick instead
  1009. of the lower-remaining pick;
  1010. - even when set, it's the *printer's* counter, not Bambuddy's
  1011. ``label_weight - weight_used`` (internal mode) or Spoolman's
  1012. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  1013. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  1014. When the user has bound a spool to a slot, their own inventory
  1015. tracking is authoritative; this helper surfaces that value so the
  1016. sort can prefer it. Slots without a binding are absent from the
  1017. returned map — the caller then falls back to MQTT ``remain`` for
  1018. those, preserving the pre-#1508 behaviour for un-tracked spools.
  1019. Returns an empty map on any failure (no inventory bindings, DB
  1020. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  1021. is a preference, not a guarantee.
  1022. """
  1023. if not loaded:
  1024. return {}
  1025. # External / virtual-tray slots are tracked separately from AMS — skip
  1026. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  1027. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  1028. # match is fiddly and out of scope for this fix).
  1029. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  1030. if not tracked_slots:
  1031. return {}
  1032. is_spoolman = await self._is_spoolman_mode(db)
  1033. overrides: dict[int, float] = {}
  1034. if is_spoolman:
  1035. result = await db.execute(
  1036. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  1037. )
  1038. assignments = list(result.scalars().all())
  1039. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  1040. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  1041. for ams_id, tray_id, gtid in tracked_slots:
  1042. spoolman_id = by_slot.get((ams_id, tray_id))
  1043. if spoolman_id is None:
  1044. continue
  1045. grams = await _spoolman_remaining_grams(spoolman_id)
  1046. if grams is not None:
  1047. overrides[gtid] = grams
  1048. return overrides
  1049. # Internal inventory mode (default). selectinload matches the pattern
  1050. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  1051. # plus an eager-loaded relationship rather than an explicit join, so
  1052. # the row-attribute shape is exactly what those routes already rely on.
  1053. result = await db.execute(
  1054. select(SpoolAssignment)
  1055. .options(selectinload(SpoolAssignment.spool))
  1056. .where(SpoolAssignment.printer_id == printer_id)
  1057. )
  1058. assignments = list(result.scalars().all())
  1059. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  1060. for ams_id, tray_id, gtid in tracked_slots:
  1061. spool = by_slot.get((ams_id, tray_id))
  1062. if spool is None:
  1063. continue
  1064. label = float(spool.label_weight or 0)
  1065. used = float(spool.weight_used or 0)
  1066. overrides[gtid] = max(0.0, label - used)
  1067. return overrides
  1068. @staticmethod
  1069. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  1070. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  1071. here to avoid making this module import-dependent on that private
  1072. helper's signature."""
  1073. try:
  1074. from backend.app.api.routes.settings import get_setting
  1075. v = await get_setting(db, "spoolman_enabled")
  1076. return bool(v) and v.lower() == "true"
  1077. except Exception:
  1078. return False
  1079. @staticmethod
  1080. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  1081. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  1082. Three bands, matched to the emission order in ``_build_loaded_filaments``
  1083. so a tied sort produces the same physical-position order the pre-#1508
  1084. stable sort did (preserves the regression-free baseline):
  1085. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  1086. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  1087. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  1088. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  1089. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  1090. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  1091. """
  1092. if ams_id is None or ams_id < 0:
  1093. return 10_000
  1094. if ams_id >= 128:
  1095. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  1096. return ams_id * 4 + (tray_id or 0)
  1097. @staticmethod
  1098. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  1099. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  1100. Two-tier ordering: inventory-tracked spools always sort BEFORE
  1101. non-tracked spools (the user has told us they care about these
  1102. specifically), then ascending by remaining within each tier, then
  1103. ascending by AMS slot position as the deterministic tie-breaker.
  1104. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  1105. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  1106. because the tier flag dominates — which is what lets us mix grams
  1107. (inventory) and percent (MQTT) without a unit conversion.
  1108. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  1109. spools the printer DOES know something about sort ahead of those
  1110. it knows nothing about — preserves pre-#1508 behaviour for the
  1111. no-inventory-binding case.
  1112. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  1113. external on ties, matching the legacy emission-order stable sort.
  1114. """
  1115. gtid = f.get("global_tray_id")
  1116. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  1117. if overrides and gtid in overrides:
  1118. return (0, overrides[gtid], slot_order)
  1119. remain = f.get("remain", -1)
  1120. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  1121. def _match_filaments_to_slots(
  1122. self,
  1123. required: list[dict],
  1124. loaded: list[dict],
  1125. prefer_lowest: bool = False,
  1126. inventory_remain_overrides: dict[int, float] | None = None,
  1127. ) -> list[int] | None:
  1128. """Match required filaments to loaded filaments and build AMS mapping.
  1129. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  1130. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  1131. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  1132. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  1133. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  1134. matching among those trays.
  1135. Args:
  1136. required: List of required filaments with slot_id, type, color, tray_info_idx
  1137. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  1138. Returns:
  1139. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  1140. """
  1141. if not required:
  1142. return None
  1143. # Track used trays to avoid duplicate assignment
  1144. used_tray_ids: set[int] = set()
  1145. comparisons = []
  1146. for req in required:
  1147. req_type = (req.get("type") or "").upper()
  1148. req_color = req.get("color", "")
  1149. req_tray_info_idx = req.get("tray_info_idx", "")
  1150. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  1151. idx_match = None
  1152. exact_match = None
  1153. similar_match = None
  1154. type_only_match = None
  1155. # Get available trays (not already used)
  1156. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  1157. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  1158. # Hard filter — cross-nozzle assignment causes print failures
  1159. # ("position of left hotend is abnormal"), so never fall back.
  1160. req_nozzle_id = req.get("nozzle_id")
  1161. if req_nozzle_id is not None:
  1162. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  1163. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  1164. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  1165. # _prefer_lowest_sort_key for the full rationale.
  1166. if prefer_lowest:
  1167. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1168. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  1169. # One line per filament req so a bug report can be diagnosed
  1170. # without enabling debug logging: shows what the matcher saw
  1171. # (req shape + sorted candidate trays with their remain values
  1172. # and any inventory override that was applied). Mirrored by
  1173. # the picked-match log at the bottom of the loop.
  1174. logger.info(
  1175. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  1176. req.get("slot_id"),
  1177. req_type,
  1178. req_color,
  1179. req_tray_info_idx,
  1180. req_nozzle_id,
  1181. [
  1182. {
  1183. "gtid": f.get("global_tray_id"),
  1184. "type": f.get("type"),
  1185. "color": f.get("color"),
  1186. "tii": f.get("tray_info_idx"),
  1187. "remain": f.get("remain"),
  1188. "inv_g": (
  1189. inventory_remain_overrides.get(f.get("global_tray_id"))
  1190. if inventory_remain_overrides
  1191. else None
  1192. ),
  1193. }
  1194. for f in available
  1195. ],
  1196. )
  1197. # Check if tray_info_idx is unique among available trays
  1198. if req_tray_info_idx:
  1199. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  1200. if len(idx_matches) == 1:
  1201. # Unique tray_info_idx - use it as definitive match
  1202. idx_match = idx_matches[0]
  1203. logger.debug(
  1204. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  1205. f"-> tray {idx_match['global_tray_id']}"
  1206. )
  1207. elif len(idx_matches) > 1:
  1208. # Multiple trays with same tray_info_idx - use color matching among them
  1209. logger.debug(
  1210. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  1211. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  1212. )
  1213. if prefer_lowest:
  1214. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  1215. # Use color matching within this subset
  1216. for f in idx_matches:
  1217. f_color = f.get("color", "")
  1218. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1219. if not exact_match:
  1220. exact_match = f
  1221. elif self._colors_are_similar(f_color, req_color):
  1222. if not similar_match:
  1223. similar_match = f
  1224. elif not type_only_match:
  1225. type_only_match = f
  1226. # If no idx_match yet, do standard type/color matching on all available trays
  1227. if not idx_match and not exact_match and not similar_match and not type_only_match:
  1228. for f in available:
  1229. f_type = (f.get("type") or "").upper()
  1230. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  1231. continue
  1232. # Type matches - check color
  1233. f_color = f.get("color", "")
  1234. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  1235. if not exact_match:
  1236. exact_match = f
  1237. elif self._colors_are_similar(f_color, req_color):
  1238. if not similar_match:
  1239. similar_match = f
  1240. elif not type_only_match:
  1241. type_only_match = f
  1242. match = idx_match or exact_match or similar_match or type_only_match
  1243. if match:
  1244. used_tray_ids.add(match["global_tray_id"])
  1245. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  1246. else:
  1247. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  1248. if prefer_lowest:
  1249. # Pair with the "available (sorted)" log above so the reporter
  1250. # bundle shows BOTH what the matcher saw AND which match bucket
  1251. # won — fast triage when "Prefer Lowest Filament" picks the
  1252. # wrong slot (#1766).
  1253. if match:
  1254. bucket = (
  1255. "idx"
  1256. if idx_match is not None
  1257. else "exact_color"
  1258. if exact_match is not None
  1259. else "similar_color"
  1260. if similar_match is not None
  1261. else "type_only"
  1262. )
  1263. logger.info(
  1264. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  1265. match["global_tray_id"],
  1266. bucket,
  1267. req.get("slot_id"),
  1268. )
  1269. else:
  1270. logger.info(
  1271. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  1272. req.get("slot_id"),
  1273. req_type,
  1274. req_color,
  1275. req_tray_info_idx,
  1276. )
  1277. # Build mapping array
  1278. if not comparisons:
  1279. return None
  1280. max_slot_id = max(c["slot_id"] for c in comparisons)
  1281. if max_slot_id <= 0:
  1282. return None
  1283. mapping = [-1] * max_slot_id
  1284. for c in comparisons:
  1285. slot_id = c["slot_id"]
  1286. if slot_id and slot_id > 0:
  1287. mapping[slot_id - 1] = c["global_tray_id"]
  1288. return mapping
  1289. def _mark_printer_dispatched(
  1290. self,
  1291. printer_id: int,
  1292. pre_state: str | None,
  1293. pre_subtask_id: str | None,
  1294. ) -> None:
  1295. """Record that a print command was just sent to ``printer_id``.
  1296. Held until either the watchdog observes a state/subtask transition
  1297. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1298. """
  1299. if not pre_state:
  1300. # No pre_state means we can't detect a transition — fall back to a
  1301. # pure time-based hold using empty string as a sentinel that won't
  1302. # match any real printer state.
  1303. pre_state = ""
  1304. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1305. def _release_dispatch_hold(self, printer_id: int) -> None:
  1306. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1307. self._dispatch_holds.pop(printer_id, None)
  1308. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1309. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1310. Returns False (and clears the hold) once any of these are true:
  1311. - hard timeout (``_dispatch_max_hold``) has elapsed
  1312. - the printer has transitioned out of pre_state and we're past the
  1313. minimum cooldown
  1314. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1315. past the minimum cooldown
  1316. Otherwise the printer is held — caller should treat it as busy.
  1317. """
  1318. entry = self._dispatch_holds.get(printer_id)
  1319. if not entry:
  1320. return False
  1321. started_at, pre_state, pre_subtask_id = entry
  1322. elapsed = time.monotonic() - started_at
  1323. if elapsed >= self._dispatch_max_hold:
  1324. self._dispatch_holds.pop(printer_id, None)
  1325. return False
  1326. # Without a pre_state we can't detect a transition — fall back to the
  1327. # min cooldown alone, then drop the hold.
  1328. if not pre_state:
  1329. if elapsed >= self._dispatch_min_cooldown:
  1330. self._dispatch_holds.pop(printer_id, None)
  1331. return False
  1332. return True
  1333. status = printer_manager.get_status(printer_id)
  1334. current_state = getattr(status, "state", None) if status else None
  1335. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1336. transitioned = (current_state is not None and current_state != pre_state) or (
  1337. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1338. )
  1339. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1340. self._dispatch_holds.pop(printer_id, None)
  1341. return False
  1342. return True
  1343. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1344. """Check if a printer is connected and idle."""
  1345. if not printer_manager.is_connected(printer_id):
  1346. logger.debug("Printer %d: not connected", printer_id)
  1347. return False
  1348. state = printer_manager.get_status(printer_id)
  1349. if not state:
  1350. logger.debug("Printer %d: no status available", printer_id)
  1351. return False
  1352. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1353. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1354. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1355. # printer, it boots back into IDLE with no memory of the previous finish; without
  1356. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1357. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1358. logger.debug(
  1359. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1360. printer_id,
  1361. state.state,
  1362. )
  1363. return False
  1364. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1365. if not idle:
  1366. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1367. return idle
  1368. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1369. """Read a setting value from the database."""
  1370. result = await db.execute(select(Settings).where(Settings.key == key))
  1371. setting = result.scalar_one_or_none()
  1372. return setting.value if setting else None
  1373. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1374. """Read a boolean setting from the database."""
  1375. result = await db.execute(select(Settings).where(Settings.key == key))
  1376. setting = result.scalar_one_or_none()
  1377. if setting:
  1378. return setting.value.lower() == "true"
  1379. return default
  1380. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  1381. """Read an int setting; falls back to default on missing/unparseable rows."""
  1382. result = await db.execute(select(Settings).where(Settings.key == key))
  1383. setting = result.scalar_one_or_none()
  1384. if setting and setting.value:
  1385. try:
  1386. return int(setting.value)
  1387. except ValueError:
  1388. pass
  1389. return default
  1390. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1391. """Get drying presets (user-configured or built-in defaults)."""
  1392. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1393. setting = result.scalar_one_or_none()
  1394. if setting and setting.value:
  1395. try:
  1396. presets = json.loads(setting.value)
  1397. if isinstance(presets, dict) and presets:
  1398. return presets
  1399. except json.JSONDecodeError:
  1400. pass
  1401. return self.DEFAULT_DRYING_PRESETS
  1402. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  1403. """Per-filament humidity thresholds (#1605).
  1404. Returns the user-configured overrides map keyed by normalized filament
  1405. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  1406. unknown / unmapped types. Empty / unset → empty dict, in which case
  1407. callers fall back to ``ams_humidity_fair``.
  1408. """
  1409. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  1410. setting = result.scalar_one_or_none()
  1411. if not setting or not setting.value:
  1412. return {}
  1413. try:
  1414. data = json.loads(setting.value)
  1415. except json.JSONDecodeError:
  1416. return {}
  1417. if not isinstance(data, dict):
  1418. return {}
  1419. out: dict[str, int] = {}
  1420. for key, value in data.items():
  1421. try:
  1422. out[str(key).upper() if key != "default" else "default"] = int(value)
  1423. except (TypeError, ValueError):
  1424. continue
  1425. return out
  1426. @staticmethod
  1427. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  1428. """Resolve the effective humidity threshold for an AMS unit (#1605).
  1429. For mixed filament types loaded into one AMS, returns the most
  1430. restrictive (lowest) threshold across all loaded tray types — matches
  1431. the conservative-params strategy already used for drying temp/hours.
  1432. Empty / unloaded trays contribute no constraint. Unknown types use the
  1433. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  1434. when no per-type map is configured at all.
  1435. """
  1436. default = thresholds.get("default", fallback)
  1437. if not thresholds:
  1438. return fallback
  1439. candidates: list[int] = []
  1440. for tray in trays:
  1441. tray_type = str(tray.get("tray_type") or "").strip()
  1442. if not tray_type:
  1443. continue
  1444. base_type = tray_type.split()[0].upper()
  1445. candidates.append(thresholds.get(base_type, default))
  1446. if not candidates:
  1447. return default
  1448. return min(candidates)
  1449. def _get_conservative_drying_params(
  1450. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1451. ) -> tuple[int, int, str] | None:
  1452. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1453. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1454. """
  1455. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1456. hours_key = f"{temp_key}_hours"
  1457. min_temp = None
  1458. max_hours = None
  1459. filament_type = ""
  1460. for tray in trays:
  1461. tray_type = tray.get("tray_type", "")
  1462. if not tray_type:
  1463. continue
  1464. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1465. base_type = tray_type.split()[0].upper()
  1466. preset = presets.get(base_type)
  1467. if not preset:
  1468. continue
  1469. temp = preset.get(temp_key, 55)
  1470. hours = preset.get(hours_key, 12)
  1471. # Conservative: lowest temp, longest duration
  1472. if min_temp is None or temp < min_temp:
  1473. min_temp = temp
  1474. if max_hours is None or hours > max_hours:
  1475. max_hours = hours
  1476. if not filament_type:
  1477. filament_type = base_type
  1478. if min_temp is None:
  1479. return None
  1480. return (min_temp, max_hours or 12, filament_type)
  1481. async def _check_auto_drying(
  1482. self,
  1483. db: AsyncSession,
  1484. queue_items: list[PrintQueueItem],
  1485. busy_printers: set[int],
  1486. *,
  1487. require_plate_clear: bool = True,
  1488. ):
  1489. """Start drying on idle printers based on humidity.
  1490. Three modes (can all be enabled independently):
  1491. - queue_drying_enabled: Dry between scheduled queue prints
  1492. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1493. - print_drying_enabled: Also evaluate printers that are currently printing,
  1494. when model+firmware supports "Print While Drying" (gated by
  1495. supports_drying_while_printing). Drying temperature is capped at
  1496. max(40, preset_temp - 5) to protect spools mid-print.
  1497. """
  1498. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1499. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1500. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  1501. if not queue_drying_enabled and not ambient_drying_enabled:
  1502. # Stop active drying on all printers if both features disabled
  1503. if self._drying_in_progress:
  1504. for pid in list(self._drying_in_progress):
  1505. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1506. await self._stop_drying(pid)
  1507. return
  1508. # Update drying state from printer status (handles backend restart)
  1509. self._sync_drying_state()
  1510. # Find printers with scheduled items (for queue drying mode)
  1511. printers_with_scheduled: set[int] = set()
  1512. printers_with_items: set[int] = set()
  1513. for item in queue_items:
  1514. if item.printer_id:
  1515. printers_with_items.add(item.printer_id)
  1516. if item.scheduled_time and not item.manual_start:
  1517. printers_with_scheduled.add(item.printer_id)
  1518. # If only queue mode is on and no printers have scheduled items, stop drying
  1519. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  1520. # may still be eligible for mid-print drying regardless of queue state).
  1521. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  1522. for pid in list(self._drying_in_progress):
  1523. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1524. await self._stop_drying(pid)
  1525. return
  1526. # Get humidity threshold (global fallback)
  1527. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1528. setting = result.scalar_one_or_none()
  1529. global_humidity_threshold = int(setting.value) if setting else 60
  1530. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  1531. # to the global threshold for every AMS unit.
  1532. per_type_thresholds = await self._get_humidity_thresholds(db)
  1533. # Get drying presets
  1534. presets = await self._get_drying_presets(db)
  1535. # Determine if drying should be skipped for printers with pending items
  1536. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1537. # Get all active printers
  1538. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1539. for printer in all_printers.scalars():
  1540. pid = printer.id
  1541. # Resolve model+firmware up front — needed to decide whether this printer
  1542. # qualifies for mid-print drying (busy printer on capable hardware).
  1543. state = printer_manager.get_status(pid)
  1544. if not state:
  1545. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1546. continue
  1547. model = printer_manager.get_model(pid)
  1548. firmware = state.firmware_version
  1549. mid_print = (
  1550. pid in busy_printers and print_drying_enabled and supports_drying_while_printing(model, firmware)
  1551. )
  1552. if pid in busy_printers and not mid_print:
  1553. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1554. continue
  1555. if not mid_print:
  1556. # In queue-only mode, only dry printers that have scheduled prints
  1557. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1558. if self._drying_in_progress.get(pid):
  1559. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1560. await self._stop_drying(pid)
  1561. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1562. continue
  1563. # When block mode is on, don't START new drying on printers with pending items.
  1564. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1565. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1566. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1567. continue
  1568. if not printer_manager.is_connected(pid):
  1569. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1570. continue
  1571. if not mid_print and not self._is_printer_idle(pid, require_plate_clear):
  1572. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1573. continue
  1574. # Check drying capability. For mid-print path, supports_drying_while_printing
  1575. # was already verified when computing mid_print above.
  1576. if not mid_print and not supports_drying(model, firmware):
  1577. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1578. continue
  1579. # Check each AMS unit from raw_data
  1580. ams_list = state.raw_data.get("ams", [])
  1581. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1582. for ams_data in ams_list:
  1583. module_type = str(ams_data.get("module_type") or "")
  1584. ams_id = int(ams_data.get("id", 0))
  1585. # Only n3f/n3s support drying
  1586. if module_type not in ("n3f", "n3s"):
  1587. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1588. continue
  1589. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  1590. # Most-restrictive of all loaded tray types; falls back to the
  1591. # global threshold when no overrides are configured.
  1592. trays = ams_data.get("tray", []) or []
  1593. humidity_threshold = self.resolve_humidity_threshold(
  1594. trays, per_type_thresholds, global_humidity_threshold
  1595. )
  1596. dry_time = int(ams_data.get("dry_time") or 0)
  1597. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1598. humidity = None
  1599. h_raw = ams_data.get("humidity_raw")
  1600. if h_raw is not None:
  1601. try:
  1602. humidity = int(h_raw)
  1603. except (ValueError, TypeError):
  1604. pass
  1605. if humidity is None:
  1606. h_idx = ams_data.get("humidity")
  1607. if h_idx is not None:
  1608. try:
  1609. humidity = int(h_idx)
  1610. except (ValueError, TypeError):
  1611. pass
  1612. # Already drying — let it run to its configured duration (#1892).
  1613. #
  1614. # We deliberately do NOT stop drying from a humidity re-check here.
  1615. # Relative humidity drops steeply in heated air, so the AMS sensor
  1616. # reads ~15-20% within minutes of the dryer starting even while the
  1617. # filament is still saturated. A humidity-based early-stop therefore
  1618. # always fires at the minimum-time floor, truncating both user-started
  1619. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  1620. # The firmware stops when the configured duration elapses; scheduling
  1621. # stops (print takes priority, queue no longer needs drying) are
  1622. # handled separately via _stop_drying().
  1623. if dry_time > 0:
  1624. if pid not in self._drying_in_progress:
  1625. # Drying we didn't start (manual or from before restart) —
  1626. # track it so scheduling stops still apply; never auto-stop it.
  1627. self._drying_in_progress[pid] = time.monotonic()
  1628. logger.debug(
  1629. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  1630. pid,
  1631. ams_id,
  1632. dry_time,
  1633. humidity,
  1634. )
  1635. continue
  1636. # Humidity below threshold — no need to start drying
  1637. if humidity is None or humidity <= humidity_threshold:
  1638. logger.debug(
  1639. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1640. pid,
  1641. ams_id,
  1642. humidity,
  1643. humidity_threshold,
  1644. )
  1645. continue
  1646. # Check cannot-dry reasons (power constraints etc.)
  1647. sf_reasons = ams_data.get("dry_sf_reason", [])
  1648. if sf_reasons:
  1649. logger.debug(
  1650. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1651. pid,
  1652. ams_id,
  1653. sf_reasons,
  1654. )
  1655. continue
  1656. # Get conservative drying params for mixed filaments
  1657. params = self._get_conservative_drying_params(trays, module_type, presets)
  1658. if not params:
  1659. logger.debug(
  1660. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1661. )
  1662. continue
  1663. temp, duration_hours, filament_type = params
  1664. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  1665. # "drying temperature must not exceed the filament's softening temperature"
  1666. # for Print While Drying). Floor at 40 degC — below that the dryer is
  1667. # ineffective and firmware will reject anyway.
  1668. if mid_print:
  1669. temp = max(40, temp - 5)
  1670. # Start drying
  1671. logger.info(
  1672. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1673. "starting %s drying at %d°C for %dh%s",
  1674. pid,
  1675. ams_id,
  1676. humidity,
  1677. humidity_threshold,
  1678. filament_type,
  1679. temp,
  1680. duration_hours,
  1681. " (mid-print)" if mid_print else "",
  1682. )
  1683. success = printer_manager.send_drying_command(
  1684. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1685. )
  1686. if success:
  1687. self._drying_in_progress[pid] = time.monotonic()
  1688. def _sync_drying_state(self):
  1689. """Sync in-memory drying state with actual printer status.
  1690. Handles backend restart — if a printer is drying but we don't know about it,
  1691. update our state. If we think it's drying but it's not, clear it.
  1692. """
  1693. to_remove = []
  1694. for pid in self._drying_in_progress:
  1695. state = printer_manager.get_status(pid)
  1696. if not state:
  1697. to_remove.append(pid)
  1698. continue
  1699. # Check if any AMS unit is still drying
  1700. ams_list = state.raw_data.get("ams", [])
  1701. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1702. if not any_drying:
  1703. to_remove.append(pid)
  1704. for pid in to_remove:
  1705. self._drying_in_progress.pop(pid, None)
  1706. async def _stop_drying(self, printer_id: int):
  1707. """Stop all active drying on a printer (print takes priority)."""
  1708. state = printer_manager.get_status(printer_id)
  1709. if not state:
  1710. self._drying_in_progress.pop(printer_id, None)
  1711. return
  1712. ams_list = state.raw_data.get("ams", [])
  1713. for ams_data in ams_list:
  1714. dry_time = int(ams_data.get("dry_time") or 0)
  1715. if dry_time > 0:
  1716. ams_id = int(ams_data.get("id", 0))
  1717. logger.info(
  1718. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1719. printer_id,
  1720. ams_id,
  1721. )
  1722. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1723. self._drying_in_progress.pop(printer_id, None)
  1724. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  1725. """Get all smart plugs associated with a printer."""
  1726. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1727. return list(result.scalars().all())
  1728. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  1729. # chamber-temperature recommendations BambuStudio ships for the matching
  1730. # filament profile; users can override via Settings → Workflow → Preheat
  1731. # card. "default" applies when a loaded tray's normalised type isn't in
  1732. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  1733. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  1734. "PLA": 0,
  1735. "PETG": 0,
  1736. "PETG-CF": 40,
  1737. "ABS": 45,
  1738. "ASA": 45,
  1739. "PA": 50,
  1740. "PA-CF": 55,
  1741. "PC": 50,
  1742. "PC-FR": 50,
  1743. "TPU": 0,
  1744. "PVA": 0,
  1745. "default": 0,
  1746. }
  1747. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  1748. """Parse the user-configured filament→chamber-target map, falling back
  1749. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  1750. are uppercased and the 'default' fallback is always present in the
  1751. returned dict so the resolution loop can index it unconditionally."""
  1752. raw = await self._get_setting(db, "preheat_filament_targets")
  1753. if not raw:
  1754. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  1755. try:
  1756. parsed = json.loads(raw)
  1757. if not isinstance(parsed, dict):
  1758. raise ValueError("not an object")
  1759. except (json.JSONDecodeError, ValueError) as exc:
  1760. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  1761. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  1762. # Coerce values to int; drop unparseable rows so a stray string
  1763. # doesn't crash the loop.
  1764. out: dict[str, int] = {}
  1765. for key, value in parsed.items():
  1766. try:
  1767. out[str(key).upper()] = int(value)
  1768. except (TypeError, ValueError):
  1769. continue
  1770. if "DEFAULT" not in out:
  1771. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  1772. return out
  1773. @staticmethod
  1774. def _normalize_filament_type(tray_type: str) -> str:
  1775. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  1776. existing drying-preset normalisation (split-at-space, upper-case) so
  1777. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  1778. "PA-CF" (no space to split on)."""
  1779. return tray_type.split()[0].upper() if tray_type else ""
  1780. def _derive_chamber_target(
  1781. self,
  1782. printer: Printer,
  1783. targets: dict[str, int],
  1784. ) -> int:
  1785. """Look up the chamber target for each loaded AMS tray and return the
  1786. max. Returns 0 when no AMS data is available (e.g. external-spool
  1787. prints) or when every loaded slot maps to 0 — the chamber phase then
  1788. short-circuits in the main loop.
  1789. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  1790. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  1791. less slots have empty `tray_type` and contribute nothing."""
  1792. state = printer_manager.get_status(printer.id)
  1793. if state is None:
  1794. return 0
  1795. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  1796. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  1797. if isinstance(ams_list, dict):
  1798. ams_list = ams_list.get("ams") or []
  1799. if not isinstance(ams_list, list):
  1800. return 0
  1801. best = 0
  1802. for ams in ams_list:
  1803. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  1804. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  1805. if not normalised:
  1806. continue
  1807. target = targets.get(normalised, targets.get("DEFAULT", 0))
  1808. if target > best:
  1809. best = target
  1810. return best
  1811. async def _preheat_and_soak(
  1812. self,
  1813. db: AsyncSession,
  1814. item: PrintQueueItem,
  1815. printer: Printer,
  1816. archive: PrintArchive | None,
  1817. ) -> None:
  1818. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  1819. Resolution order:
  1820. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  1821. to the global `preheat_enabled` setting; 'on' forces the stage on
  1822. even if the global is off.
  1823. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  1824. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  1825. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  1826. phase + soak timer).
  1827. 3. Three hardware tiers branch the wait loop:
  1828. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  1829. send M141 to the resolved target, then wait for the chamber sensor
  1830. to reach it (or the max-wait timeout to elapse).
  1831. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  1832. no M141; the bed is the only heat source, so we wait for the chamber
  1833. sensor to rise via bed radiation OR fall through on timeout.
  1834. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  1835. temperature; the function just heats the bed and holds for the
  1836. configured soak duration.
  1837. The bed target comes from the archive's parsed metadata
  1838. (`bed_temperature`); if missing the preheat stage logs and returns
  1839. without dispatching anything, rather than guessing at a default that
  1840. might wreck filament setup.
  1841. Failures are logged but never re-raised — preheat is best-effort. A
  1842. printer that goes offline mid-soak, a refused gcode command, or a
  1843. missing temperature reading must not turn into a failed queue item; the
  1844. normal upload + start path runs immediately after this method returns.
  1845. """
  1846. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  1847. if override == "off":
  1848. return
  1849. if override == "inherit":
  1850. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  1851. if not enabled:
  1852. return
  1853. # override == "on" forces the stage on regardless of the global setting.
  1854. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  1855. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  1856. # Chamber target resolution:
  1857. # 1. Explicit per-item override beats everything (user knows best).
  1858. # 2. Otherwise derive from loaded AMS filament types via the per-
  1859. # filament target map. PLA-only print derives 0 → chamber phase
  1860. # auto-skips without the user touching anything.
  1861. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  1862. if explicit_target is not None and explicit_target > 0:
  1863. chamber_target = int(explicit_target)
  1864. chamber_source = "item-override"
  1865. elif explicit_target == 0:
  1866. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  1867. chamber_source = "item-override-zero"
  1868. else:
  1869. targets = await self._get_preheat_filament_targets(db)
  1870. chamber_target = self._derive_chamber_target(printer, targets)
  1871. chamber_source = "filament-map"
  1872. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  1873. if bed_target <= 0:
  1874. logger.info(
  1875. "Queue item %s: preheat skipped — archive has no bed_temperature metadata",
  1876. item.id,
  1877. )
  1878. return
  1879. client = printer_manager.get_client(printer.id)
  1880. if client is None:
  1881. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  1882. return
  1883. model = printer.model or ""
  1884. has_heater = supports_chamber_heater(model)
  1885. has_sensor = supports_chamber_temp(model)
  1886. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  1887. logger.info(
  1888. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  1889. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  1890. item.id,
  1891. bed_target,
  1892. chamber_target if do_chamber else 0,
  1893. chamber_source,
  1894. override,
  1895. model,
  1896. has_heater,
  1897. has_sensor,
  1898. max_wait,
  1899. soak_seconds,
  1900. )
  1901. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  1902. # cache the target locally so the polling reads below see consistent
  1903. # state (firmware MQTT echoes lag by ~1s).
  1904. try:
  1905. client.set_bed_temperature(bed_target)
  1906. except Exception as exc:
  1907. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  1908. return
  1909. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  1910. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  1911. # left it on, regardless of M141. Default cooling actively vents the
  1912. # chamber, so a `chamber_target > 0` print with the flap stuck in
  1913. # cooling never converges — the heater fights the open exhaust. We
  1914. # flip the flap BEFORE M141 to "heating" when the preheat wants
  1915. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  1916. # on an H2D that was previously running ABS would otherwise stay in
  1917. # heating mode and overheat PLA). The current-state read keeps the
  1918. # command idempotent — no MQTT chatter when the flap is already where
  1919. # we want it.
  1920. if supports_airduct(model):
  1921. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  1922. desired_id = 1 if desired_airduct == "heating" else 0
  1923. current_state = printer_manager.get_status(printer.id)
  1924. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  1925. if current_airduct != desired_id:
  1926. try:
  1927. client.set_airduct_mode(desired_airduct)
  1928. except Exception as exc:
  1929. logger.warning(
  1930. "Queue item %s: preheat airduct %s mode failed: %s",
  1931. item.id,
  1932. desired_airduct,
  1933. exc,
  1934. )
  1935. if do_chamber and has_heater:
  1936. try:
  1937. client.set_chamber_temperature(chamber_target)
  1938. except Exception as exc:
  1939. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  1940. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  1941. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  1942. # Poll every 3s — frequent enough for responsive logging without
  1943. # spamming the MQTT state stream. The "converged" predicate is:
  1944. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  1945. # AND
  1946. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  1947. BED_TOLERANCE = 2.0
  1948. CHAMBER_TOLERANCE = 2.0
  1949. POLL_INTERVAL = 3.0
  1950. deadline = asyncio.get_event_loop().time() + max_wait
  1951. while True:
  1952. state = printer_manager.get_status(printer.id)
  1953. if state is None:
  1954. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  1955. break
  1956. temps = state.temperatures or {}
  1957. bed_now = float(temps.get("bed", 0) or 0)
  1958. chamber_now = float(temps.get("chamber", 0) or 0)
  1959. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  1960. if not do_chamber:
  1961. chamber_ok = True # phase disabled or model has neither sensor nor heater
  1962. elif not has_sensor:
  1963. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  1964. else:
  1965. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  1966. if bed_ok and chamber_ok:
  1967. logger.info(
  1968. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  1969. item.id,
  1970. bed_now,
  1971. chamber_now,
  1972. )
  1973. break
  1974. if asyncio.get_event_loop().time() >= deadline:
  1975. logger.info(
  1976. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  1977. item.id,
  1978. bed_now,
  1979. bed_target,
  1980. chamber_now,
  1981. chamber_target if do_chamber else 0,
  1982. )
  1983. break
  1984. await asyncio.sleep(POLL_INTERVAL)
  1985. if soak_seconds > 0:
  1986. logger.info("Queue item %s: preheat soak — holding for %ds", item.id, soak_seconds)
  1987. await asyncio.sleep(soak_seconds)
  1988. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  1989. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1990. """Turn on smart plug and wait for printer to connect.
  1991. Returns True if printer connected successfully within timeout.
  1992. """
  1993. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1994. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1995. # Check current plug state
  1996. status = await service.get_status(plug)
  1997. if not status.get("reachable"):
  1998. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1999. return False
  2000. # Turn on if not already on
  2001. if status.get("state") != "ON":
  2002. success = await service.turn_on(plug)
  2003. if not success:
  2004. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  2005. return False
  2006. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  2007. # Get printer from database for connection
  2008. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2009. printer = result.scalar_one_or_none()
  2010. if not printer:
  2011. logger.error("Printer %s not found in database", printer_id)
  2012. return False
  2013. # Wait for printer to boot (give it some time before trying to connect)
  2014. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  2015. await asyncio.sleep(30)
  2016. # Try to connect to the printer periodically
  2017. elapsed = 30 # Already waited 30s
  2018. while elapsed < self._power_on_wait_time:
  2019. # Try to connect
  2020. logger.info("Attempting to connect to printer %s...", printer_id)
  2021. try:
  2022. connected = await printer_manager.connect_printer(printer)
  2023. if connected:
  2024. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  2025. # Give it a moment to stabilize and get status
  2026. await asyncio.sleep(5)
  2027. return True
  2028. except Exception as e:
  2029. logger.debug("Connection attempt failed: %s", e)
  2030. await asyncio.sleep(self._power_on_check_interval)
  2031. elapsed += self._power_on_check_interval
  2032. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  2033. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  2034. return False
  2035. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  2036. """Check if the previous print on this printer succeeded.
  2037. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  2038. deliberate action, not a failure, so subsequent items should still
  2039. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  2040. a skip isn't an actual print attempt, so it must not gate downstream
  2041. items — counting it as a failed predecessor was the cascade bug that
  2042. let a single cancellation block 18 items over 3 days for the reporter.
  2043. Only `failed` and `aborted` — real print-attempt failures — block.
  2044. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  2045. action — #1818) are also excluded from the lookback so the user can
  2046. clear the gate after fixing the physical issue without having to
  2047. re-queue every downstream job.
  2048. """
  2049. result = await db.execute(
  2050. select(PrintQueueItem)
  2051. .where(PrintQueueItem.printer_id == item.printer_id)
  2052. .where(PrintQueueItem.id != item.id)
  2053. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  2054. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  2055. .order_by(PrintQueueItem.completed_at.desc())
  2056. .limit(1)
  2057. )
  2058. prev_item = result.scalar_one_or_none()
  2059. # If no previous item, assume success (first in queue)
  2060. if not prev_item:
  2061. return True
  2062. return prev_item.status in ("completed", "cancelled")
  2063. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  2064. """Schedule power-off if the queue item enabled auto_off_after.
  2065. Delegates to the smart-plug manager so the off honours each plug's
  2066. configured strategy (time delay or temperature threshold), is cancelled
  2067. if the printer starts printing again, and never cuts power on a loaded
  2068. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  2069. powered off on the timeout regardless of print state.
  2070. """
  2071. if not item.auto_off_after:
  2072. return
  2073. try:
  2074. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  2075. except Exception as e:
  2076. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  2077. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  2078. """Get a human-readable name for a queue item."""
  2079. if item.archive_id:
  2080. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2081. archive = result.scalar_one_or_none()
  2082. if archive:
  2083. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2084. if item.library_file_id:
  2085. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2086. library_file = result.scalar_one_or_none()
  2087. if library_file:
  2088. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2089. return f"Job #{item.id}"
  2090. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  2091. """Get printer by ID."""
  2092. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2093. return result.scalar_one_or_none()
  2094. async def _block_on_filament_deficit(
  2095. self,
  2096. db: AsyncSession,
  2097. item: PrintQueueItem,
  2098. ) -> bool:
  2099. """Promote the item to manual_start when the assigned spool is short (#1496).
  2100. Returns True when this dispatch attempt was blocked, False when the
  2101. item is clear to start. A previously-flagged item whose spool has
  2102. since been swapped to one with enough material clears the flag here
  2103. so the next scheduler tick dispatches it.
  2104. """
  2105. # User has explicitly acknowledged the deficit ("Print Anyway") —
  2106. # don't re-flag, don't even compute. Without this short-circuit the
  2107. # scheduler bounces between "user said anyway" (route clears
  2108. # manual_start) and "scheduler re-blocked" (this method re-flags it
  2109. # on identical spool state) (#1698-followup).
  2110. if item.skip_filament_check:
  2111. # #1762 diagnostic: surface the short-circuit at INFO so a
  2112. # future "Print Anyway didn't work" report (e.g. issue #1762
  2113. # comment 3) has actionable evidence in the support bundle
  2114. # without needing DEBUG enabled.
  2115. logger.info(
  2116. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  2117. item.id,
  2118. )
  2119. return False
  2120. try:
  2121. deficit = await compute_deficit_for_queue_item(db, item)
  2122. except Exception as e:
  2123. # Never let a flaky deficit check wedge the queue — log and let
  2124. # dispatch proceed. The PrintModal-side check still runs on the
  2125. # manual paths.
  2126. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  2127. return False
  2128. if deficit:
  2129. item.filament_short = True
  2130. item.manual_start = True
  2131. await db.commit()
  2132. job_name = await self._get_job_name(db, item)
  2133. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  2134. logger.info(
  2135. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  2136. item.id,
  2137. len(deficit),
  2138. )
  2139. try:
  2140. await notification_service.on_queue_job_waiting(
  2141. job_name=job_name,
  2142. target_model=(printer.model if printer else "") or "",
  2143. waiting_reason="filament_short",
  2144. db=db,
  2145. )
  2146. except Exception as e:
  2147. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  2148. return True
  2149. # No deficit — clear any stale flag from a previous tick.
  2150. if item.filament_short:
  2151. item.filament_short = False
  2152. await db.commit()
  2153. return False
  2154. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  2155. """Hand the queue item's owner to printer_manager so the
  2156. print-complete callback can credit the user in PrintLogEntry (#1670).
  2157. No-ops when the item has no `created_by_id` or the referenced user
  2158. row is missing (e.g. user deleted between queue-add and dispatch —
  2159. in that case the print log row falls back to the existing un-credited
  2160. behaviour rather than crashing the dispatch).
  2161. """
  2162. if not item.created_by_id:
  2163. return
  2164. from backend.app.models.user import User
  2165. owner = await db.get(User, item.created_by_id)
  2166. if owner:
  2167. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  2168. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  2169. """Upload file and start print for a queue item.
  2170. Supports two sources:
  2171. - archive_id: Print from an existing archive
  2172. - library_file_id: Print from a library file (file manager)
  2173. """
  2174. logger.info("Starting queue item %s", item.id)
  2175. # Get printer first (needed for both paths)
  2176. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  2177. printer = result.scalar_one_or_none()
  2178. if not printer:
  2179. item.status = "failed"
  2180. item.error_message = "Printer not found"
  2181. item.completed_at = datetime.now(timezone.utc)
  2182. await db.commit()
  2183. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  2184. await self._power_off_if_needed(db, item)
  2185. return
  2186. # Check printer is connected
  2187. if not printer_manager.is_connected(item.printer_id):
  2188. item.status = "failed"
  2189. item.error_message = "Printer not connected"
  2190. item.completed_at = datetime.now(timezone.utc)
  2191. await db.commit()
  2192. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  2193. await self._power_off_if_needed(db, item)
  2194. return
  2195. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  2196. # `items` was taken at the top of check_queue, but the user can /cancel
  2197. # any pending row in the gap before we reach this point. Re-read the
  2198. # row and bail out cleanly instead of starting an FTP upload for a row
  2199. # that's already cancelled. The atomic CAS at the pending→printing
  2200. # transition (below, before start_print) is the load-bearing guard;
  2201. # this is the early-exit optimisation that avoids wasted FTP I/O.
  2202. await db.refresh(item)
  2203. if item.status != "pending":
  2204. logger.info(
  2205. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  2206. item.id,
  2207. item.status,
  2208. )
  2209. return
  2210. # Determine source: archive or library file
  2211. archive = None
  2212. library_file = None
  2213. file_path = None
  2214. filename = None
  2215. cleanup_disk_paths: list[Path] = []
  2216. if item.archive_id:
  2217. # Print from archive
  2218. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2219. archive = result.scalar_one_or_none()
  2220. if not archive:
  2221. item.status = "failed"
  2222. item.error_message = "Archive not found"
  2223. item.completed_at = datetime.now(timezone.utc)
  2224. await db.commit()
  2225. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  2226. await self._power_off_if_needed(db, item)
  2227. return
  2228. file_path = settings.base_dir / archive.file_path
  2229. filename = archive.filename
  2230. elif item.library_file_id:
  2231. # Print from library file (file manager)
  2232. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2233. library_file = result.scalar_one_or_none()
  2234. if not library_file:
  2235. item.status = "failed"
  2236. item.error_message = "Library file not found"
  2237. item.completed_at = datetime.now(timezone.utc)
  2238. await db.commit()
  2239. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  2240. await self._power_off_if_needed(db, item)
  2241. return
  2242. # Library files store absolute paths
  2243. lib_path = Path(library_file.file_path)
  2244. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  2245. filename = library_file.filename
  2246. # Create archive from library file so usage tracking has access to the 3MF
  2247. queue_item_id = item.id
  2248. try:
  2249. from backend.app.services.archive import ArchiveService
  2250. archive_service = ArchiveService(db)
  2251. archive = await archive_service.archive_print(
  2252. printer_id=item.printer_id,
  2253. source_file=file_path,
  2254. original_filename=filename,
  2255. created_by_id=item.created_by_id,
  2256. project_id=item.project_id,
  2257. )
  2258. if archive:
  2259. item.archive_id = archive.id
  2260. if item.cleanup_library_after_dispatch and not library_file.is_external:
  2261. item.library_file_id = None
  2262. cleanup_disk_paths.append(file_path)
  2263. if library_file.thumbnail_path:
  2264. thumb_path = Path(library_file.thumbnail_path)
  2265. if not thumb_path.is_absolute():
  2266. thumb_path = settings.base_dir / library_file.thumbnail_path
  2267. cleanup_disk_paths.append(thumb_path)
  2268. await db.delete(library_file)
  2269. file_path = settings.base_dir / archive.file_path
  2270. filename = archive.filename
  2271. # Commit, not flush — flush opens the SQLite write
  2272. # transaction (item.archive_id update + library_file
  2273. # delete) and would hold the WAL writer lock through the
  2274. # FTP upload below, causing "database is locked" cascades
  2275. # for sensor history + concurrent cancels (#1853).
  2276. await db.commit()
  2277. logger.info(
  2278. "Queue item %s: Created archive %s from library file %s",
  2279. item.id,
  2280. archive.id,
  2281. item.library_file_id,
  2282. )
  2283. except Exception as e:
  2284. logger.warning(
  2285. "Queue item %s: Failed to create archive from library file: %s",
  2286. queue_item_id,
  2287. e,
  2288. exc_info=True,
  2289. )
  2290. await db.rollback()
  2291. item = await db.get(PrintQueueItem, queue_item_id)
  2292. if item:
  2293. item.status = "failed"
  2294. item.error_message = "Failed to create archive from library file"
  2295. item.completed_at = datetime.now(timezone.utc)
  2296. await db.commit()
  2297. await self._power_off_if_needed(db, item)
  2298. return
  2299. if not archive:
  2300. item.status = "failed"
  2301. item.error_message = "Failed to create archive from library file"
  2302. item.completed_at = datetime.now(timezone.utc)
  2303. await db.commit()
  2304. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  2305. await self._power_off_if_needed(db, item)
  2306. return
  2307. else:
  2308. # Neither archive nor library file specified
  2309. item.status = "failed"
  2310. item.error_message = "No source file specified"
  2311. item.completed_at = datetime.now(timezone.utc)
  2312. await db.commit()
  2313. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  2314. await self._power_off_if_needed(db, item)
  2315. return
  2316. # Check file exists on disk
  2317. if not file_path.exists():
  2318. item.status = "failed"
  2319. item.error_message = "Source file not found on disk"
  2320. item.completed_at = datetime.now(timezone.utc)
  2321. await db.commit()
  2322. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  2323. await self._power_off_if_needed(db, item)
  2324. return
  2325. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  2326. # bed (and chamber, if applicable) is at temperature when the firmware
  2327. # starts the actual print routine. Best-effort: any failure logs and
  2328. # falls through to the normal upload+start path rather than turning a
  2329. # configuration issue into a failed queue item.
  2330. await self._preheat_and_soak(db, item, printer, archive)
  2331. # G-code injection for auto-print systems (#422)
  2332. injected_path = None
  2333. if item.gcode_injection:
  2334. try:
  2335. snippets_raw = await self._get_setting(db, "gcode_snippets")
  2336. if snippets_raw:
  2337. snippets = json.loads(snippets_raw)
  2338. model_snippets = snippets.get(printer.model, {})
  2339. start_gc = (model_snippets.get("start_gcode") or "").strip()
  2340. end_gc = (model_snippets.get("end_gcode") or "").strip()
  2341. if start_gc or end_gc:
  2342. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  2343. injected_path = inject_gcode_into_3mf(
  2344. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  2345. )
  2346. if injected_path:
  2347. file_path = injected_path
  2348. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  2349. else:
  2350. logger.warning(
  2351. "Queue item %s: G-code injection returned no result, using original", item.id
  2352. )
  2353. except Exception as e:
  2354. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  2355. # Upload to root directory (not /cache/) - the start_print command references
  2356. # files by name only (ftp://{filename}), so they must be in the root
  2357. remote_filename = derive_remote_filename(filename)
  2358. remote_path = f"/{remote_filename}"
  2359. # Get FTP retry settings
  2360. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2361. logger.info(
  2362. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  2363. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  2364. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  2365. )
  2366. # Delete existing file if present (avoids 553 error on overwrite)
  2367. try:
  2368. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  2369. delete_result = await delete_file_async(
  2370. printer.ip_address,
  2371. printer.access_code,
  2372. remote_path,
  2373. socket_timeout=ftp_timeout,
  2374. printer_model=printer.model,
  2375. )
  2376. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  2377. except Exception as e:
  2378. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  2379. # Dispatch toast — announce the upload start with the total byte
  2380. # count so the frontend can render an honest progress bar.
  2381. toast_uid = item.created_by_id
  2382. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  2383. try:
  2384. total_bytes = file_path.stat().st_size
  2385. except OSError:
  2386. total_bytes = 0
  2387. try:
  2388. await ws_manager.send_queue_item_uploading(
  2389. user_id=toast_uid,
  2390. queue_item_id=item.id,
  2391. printer_id=item.printer_id,
  2392. printer_name=printer.name,
  2393. file_name=toast_file_name,
  2394. total_bytes=total_bytes,
  2395. )
  2396. except Exception:
  2397. pass # toast is best-effort
  2398. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  2399. try:
  2400. if ftp_retry_enabled:
  2401. uploaded = await with_ftp_retry(
  2402. upload_file_async,
  2403. printer.ip_address,
  2404. printer.access_code,
  2405. file_path,
  2406. remote_path,
  2407. socket_timeout=ftp_timeout,
  2408. printer_model=printer.model,
  2409. progress_callback=progress_bridge,
  2410. max_retries=ftp_retry_count,
  2411. retry_delay=ftp_retry_delay,
  2412. operation_name=f"Upload print to {printer.name}",
  2413. )
  2414. else:
  2415. uploaded = await upload_file_async(
  2416. printer.ip_address,
  2417. printer.access_code,
  2418. file_path,
  2419. remote_path,
  2420. socket_timeout=ftp_timeout,
  2421. printer_model=printer.model,
  2422. progress_callback=progress_bridge,
  2423. )
  2424. except Exception as e:
  2425. uploaded = False
  2426. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  2427. # Clean up injected temp file after upload attempt
  2428. if injected_path and injected_path.exists():
  2429. injected_path.unlink(missing_ok=True)
  2430. if not uploaded:
  2431. error_msg = (
  2432. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  2433. "See server logs for detailed diagnostics."
  2434. )
  2435. item.status = "failed"
  2436. item.error_message = error_msg
  2437. item.completed_at = datetime.now(timezone.utc)
  2438. await db.commit()
  2439. logger.error(
  2440. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  2441. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  2442. )
  2443. # Send failure notification
  2444. await notification_service.on_queue_job_failed(
  2445. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2446. printer_id=printer.id,
  2447. printer_name=printer.name,
  2448. reason="Failed to upload file to printer",
  2449. db=db,
  2450. )
  2451. try:
  2452. await ws_manager.send_queue_item_failed(
  2453. user_id=toast_uid,
  2454. queue_item_id=item.id,
  2455. printer_id=item.printer_id,
  2456. reason="upload_failed",
  2457. )
  2458. except Exception:
  2459. pass
  2460. await self._power_off_if_needed(db, item)
  2461. return
  2462. # Parse AMS mapping if stored
  2463. ams_mapping = None
  2464. if item.ams_mapping:
  2465. try:
  2466. ams_mapping = json.loads(item.ams_mapping)
  2467. except json.JSONDecodeError:
  2468. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  2469. # Register as expected print so we don't create a duplicate archive
  2470. # Only applicable for archive-based prints
  2471. if archive:
  2472. from backend.app.main import register_expected_print
  2473. register_expected_print(
  2474. item.printer_id,
  2475. remote_filename,
  2476. archive.id,
  2477. ams_mapping=ams_mapping,
  2478. created_by_id=item.created_by_id,
  2479. plate_id=item.plate_id,
  2480. )
  2481. # Propagate the queue item's owner into printer_manager so the
  2482. # print-complete callback can credit the user in the PrintLogEntry
  2483. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  2484. # items) or when the user clicks the manual-start button.
  2485. await self._propagate_owner_to_printer_manager(db, item)
  2486. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  2487. # This prevents phantom reprints if the backend crashes/restarts after the
  2488. # print command is sent but before the status update is committed.
  2489. # If we crash after this commit but before start_print(), the item will be
  2490. # in "printing" status without actually printing - but that's safer than
  2491. # accidentally reprinting the same file hours later.
  2492. #
  2493. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  2494. # initial pending read at the top of check_queue and this point) flips
  2495. # the row to "cancelled" in a separate session. Without the WHERE
  2496. # status='pending' clause, the unconditional update here would silently
  2497. # overwrite that cancellation and we'd ship the MQTT start_print below
  2498. # — printer obeys, user sees "I pressed cancel and the print started".
  2499. # rowcount==0 means the user won the race; bail out, best-effort delete
  2500. # the file we just uploaded, do NOT send start_print.
  2501. now_utc = datetime.now(timezone.utc)
  2502. cas = await db.execute(
  2503. update(PrintQueueItem)
  2504. .where(PrintQueueItem.id == item.id)
  2505. .where(PrintQueueItem.status == "pending")
  2506. .values(status="printing", started_at=now_utc)
  2507. )
  2508. await db.commit()
  2509. if cas.rowcount == 0:
  2510. logger.info(
  2511. "Queue item %s no longer pending at print-command time "
  2512. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  2513. item.id,
  2514. )
  2515. try:
  2516. await delete_file_async(
  2517. printer.ip_address,
  2518. printer.access_code,
  2519. remote_path,
  2520. socket_timeout=ftp_timeout,
  2521. printer_model=printer.model,
  2522. )
  2523. except Exception as cleanup_err:
  2524. logger.debug(
  2525. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  2526. item.id,
  2527. cleanup_err,
  2528. )
  2529. try:
  2530. await ws_manager.send_queue_item_failed(
  2531. user_id=toast_uid,
  2532. queue_item_id=item.id,
  2533. printer_id=item.printer_id,
  2534. reason="cancelled_mid_dispatch",
  2535. )
  2536. except Exception:
  2537. pass
  2538. return
  2539. # Sync the in-memory item so subsequent code that reads item.status /
  2540. # item.started_at sees the values we just persisted.
  2541. item.status = "printing"
  2542. item.started_at = now_utc
  2543. for cleanup_path in cleanup_disk_paths:
  2544. try:
  2545. if cleanup_path.exists():
  2546. cleanup_path.unlink()
  2547. except OSError as cleanup_err:
  2548. logger.warning(
  2549. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  2550. json.dumps(
  2551. {
  2552. "queue_item_id": item.id,
  2553. "path": str(cleanup_path),
  2554. "error": str(cleanup_err),
  2555. },
  2556. sort_keys=True,
  2557. ),
  2558. )
  2559. # Clear the awaiting-plate-clear flag now that we're starting a new print
  2560. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  2561. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  2562. # Capture state before dispatch so the watchdog can detect whether the
  2563. # printer actually transitioned (#967). Also capture subtask_id so the
  2564. # watchdog can recognise "command landed but state hasn't flipped yet"
  2565. # on slow H2D transitions (#1078).
  2566. pre_status = printer_manager.get_status(item.printer_id)
  2567. pre_state = getattr(pre_status, "state", None) if pre_status else None
  2568. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  2569. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  2570. # #1721: respect the user's explicit timelapse choice. The #1397
  2571. # force-on at dispatch was removed because it caused per-layer nozzle
  2572. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  2573. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  2574. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  2575. # FINISH-state fallback — no need to force a video.
  2576. effective_timelapse = bool(item.timelapse)
  2577. # Start the print with AMS mapping, plate_id and print options.
  2578. # nozzle_mapping rides through verbatim — JSON string captured from
  2579. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  2580. # parses + injects it only for dual-nozzle models so a null on every
  2581. # other model is a transparent pass-through.
  2582. started = printer_manager.start_print(
  2583. item.printer_id,
  2584. remote_filename,
  2585. plate_id=item.plate_id or 1,
  2586. ams_mapping=ams_mapping,
  2587. bed_levelling=item.bed_levelling,
  2588. flow_cali=item.flow_cali,
  2589. vibration_cali=item.vibration_cali,
  2590. layer_inspect=item.layer_inspect,
  2591. timelapse=effective_timelapse,
  2592. use_ams=item.use_ams,
  2593. nozzle_offset_cali=item.nozzle_offset_cali,
  2594. nozzle_mapping=item.nozzle_mapping,
  2595. )
  2596. if started:
  2597. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  2598. # No dispatch-toast event here: the legacy bg-dispatch path kept
  2599. # status='processing' from upload start until the printer acked
  2600. # (or timed out). The frontend derives "Awaiting printer…" purely
  2601. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  2602. # event would push the status chip out of 'PROCESSING' prematurely
  2603. # — which is exactly what the screenshot at #1625-followup
  2604. # complained about.
  2605. # Register the local 3MF in the cover-cache so /cover skips FTP
  2606. # (#1166 follow-up). file_path was resolved earlier from either the
  2607. # archive or the library file row.
  2608. if file_path is not None:
  2609. cache_3mf_download(item.printer_id, remote_filename, file_path)
  2610. # Hold the printer against further dispatches until the watchdog
  2611. # confirms the printer transitioned (or until the hard timeout).
  2612. # Prevents multi-plate batches from triple-dispatching onto the
  2613. # same H2D Pro while it digests the first project_file (#1157).
  2614. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  2615. # Watchdog: if the printer never transitions out of pre_state AND
  2616. # never advances subtask_id, the MQTT publish was accepted locally but
  2617. # didn't reach the printer (half-broken session — same shape as
  2618. # #887/#936). Revert the queue item so the next dispatch can pick it
  2619. # up instead of leaving it stuck in "printing" (#967). subtask_id
  2620. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  2621. # that would otherwise cause the item to re-dispatch as a reprint
  2622. # of the just-finished job (#1078).
  2623. if pre_state:
  2624. spawn_background_task(
  2625. self._watchdog_print_start(
  2626. item.id,
  2627. item.printer_id,
  2628. pre_state,
  2629. pre_subtask_id,
  2630. pre_gcode_file,
  2631. created_by_id=toast_uid,
  2632. ),
  2633. name=f"watchdog-print-start-{item.id}",
  2634. )
  2635. # Get estimated time for notification
  2636. estimated_time = None
  2637. if archive and archive.print_time_seconds:
  2638. estimated_time = archive.print_time_seconds
  2639. elif library_file and library_file.print_time_seconds:
  2640. estimated_time = library_file.print_time_seconds
  2641. # Send job started notification
  2642. await notification_service.on_queue_job_started(
  2643. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2644. printer_id=printer.id,
  2645. printer_name=printer.name,
  2646. db=db,
  2647. estimated_time=estimated_time,
  2648. )
  2649. # MQTT relay - publish queue job started
  2650. try:
  2651. from backend.app.services.mqtt_relay import mqtt_relay
  2652. await mqtt_relay.on_queue_job_started(
  2653. job_id=item.id,
  2654. filename=filename,
  2655. printer_id=printer.id,
  2656. printer_name=printer.name,
  2657. printer_serial=printer.serial_number,
  2658. )
  2659. except Exception:
  2660. pass # Don't fail if MQTT fails
  2661. else:
  2662. # Clean up uploaded file from SD card to prevent phantom prints
  2663. try:
  2664. await delete_file_async(
  2665. printer.ip_address,
  2666. printer.access_code,
  2667. remote_path,
  2668. printer_model=printer.model,
  2669. )
  2670. except Exception:
  2671. pass # Best-effort — don't fail the error handler
  2672. # Print command failed - revert status
  2673. item.status = "failed"
  2674. item.error_message = "Failed to send print command to printer"
  2675. item.completed_at = datetime.now(timezone.utc)
  2676. await db.commit()
  2677. logger.error(
  2678. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  2679. f"printer_manager.start_print() returned False. "
  2680. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  2681. f"Check printer status and backend logs for details."
  2682. )
  2683. # Send failure notification
  2684. await notification_service.on_queue_job_failed(
  2685. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  2686. printer_id=printer.id,
  2687. printer_name=printer.name,
  2688. reason="Failed to send print command to printer - check printer connection and status",
  2689. db=db,
  2690. )
  2691. try:
  2692. await ws_manager.send_queue_item_failed(
  2693. user_id=toast_uid,
  2694. queue_item_id=item.id,
  2695. printer_id=item.printer_id,
  2696. reason="start_command_failed",
  2697. )
  2698. except Exception:
  2699. pass
  2700. await self._power_off_if_needed(db, item)
  2701. @staticmethod
  2702. async def _watchdog_print_start(
  2703. queue_item_id: int,
  2704. printer_id: int,
  2705. pre_state: str,
  2706. pre_subtask_id: str | None = None,
  2707. pre_gcode_file: str | None = None,
  2708. timeout: float = 90.0,
  2709. phase_b_timeout: float = 180.0,
  2710. poll_interval: float = 3.0,
  2711. created_by_id: int | None = None,
  2712. ) -> None:
  2713. """Revert a queue item if the printer never acknowledges the start command.
  2714. Bambuddy optimistically marks the queue item as "printing" right after the
  2715. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  2716. Phase A (up to ``timeout``): wait for either an active-state transition
  2717. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  2718. primary signal; subtask_id advance handles the H2D case where state can
  2719. sit at FINISH for ~50 s after the printer accepted ``project_file``
  2720. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  2721. was lost on a half-broken session (#887/#936) — revert and force
  2722. reconnect (the #967 recovery path).
  2723. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  2724. alone): keep watching for the active-state transition. subtask_id alone
  2725. proves the file landed but not that the printer started — and a printer
  2726. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  2727. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  2728. used to leave the queue item stuck in 'printing' forever because the
  2729. old watchdog returned success as soon as subtask_id advanced. If Phase
  2730. B times out, revert the queue item so the user can retry without
  2731. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  2732. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  2733. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  2734. transitions that also don't emit an early subtask_id tick.
  2735. """
  2736. last_status = None
  2737. landed_on_subtask = False
  2738. deadline = time.monotonic() + timeout
  2739. while time.monotonic() < deadline:
  2740. await asyncio.sleep(poll_interval)
  2741. status = printer_manager.get_status(printer_id)
  2742. if not status:
  2743. # Printer disconnected — don't mess with the DB. Drop the
  2744. # in-memory dispatch hold too so a fresh dispatch can retry
  2745. # once the printer comes back; the hard timeout would
  2746. # otherwise hold the printer unnecessarily.
  2747. scheduler._release_dispatch_hold(printer_id)
  2748. return
  2749. last_status = status
  2750. if status.state in _ACTIVE_PRINT_STATES:
  2751. # Printer is actively processing the job — release the
  2752. # post-dispatch hold so the next pending item for this printer
  2753. # can be evaluated normally. We do NOT accept arbitrary state
  2754. # transitions: a printer going FINISH -> IDLE (user dismissed
  2755. # the post-print prompt without accepting our project_file)
  2756. # would otherwise look like "command landed" and leave the
  2757. # queue item stuck in 'printing' forever (#1370).
  2758. scheduler._release_dispatch_hold(printer_id)
  2759. try:
  2760. await ws_manager.send_queue_item_acked(
  2761. user_id=created_by_id,
  2762. queue_item_id=queue_item_id,
  2763. printer_id=printer_id,
  2764. )
  2765. except Exception:
  2766. pass
  2767. return
  2768. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  2769. # Phase A exit — printer accepted the file (subtask_id flipped
  2770. # to our submission id). Don't return yet: the printer may
  2771. # have accepted the command but never actually start (e.g.
  2772. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  2773. # B watches for the active-state transition.
  2774. landed_on_subtask = True
  2775. break
  2776. if landed_on_subtask:
  2777. phase_b_deadline = time.monotonic() + phase_b_timeout
  2778. while time.monotonic() < phase_b_deadline:
  2779. await asyncio.sleep(poll_interval)
  2780. status = printer_manager.get_status(printer_id)
  2781. if not status:
  2782. scheduler._release_dispatch_hold(printer_id)
  2783. return
  2784. last_status = status
  2785. if status.state in _ACTIVE_PRINT_STATES:
  2786. scheduler._release_dispatch_hold(printer_id)
  2787. try:
  2788. await ws_manager.send_queue_item_acked(
  2789. user_id=created_by_id,
  2790. queue_item_id=queue_item_id,
  2791. printer_id=printer_id,
  2792. )
  2793. except Exception:
  2794. pass
  2795. return
  2796. # No active-state transition. Revert the item so the scheduler can retry.
  2797. # Drop the in-memory hold so the retry isn't blocked by it.
  2798. scheduler._release_dispatch_hold(printer_id)
  2799. # Three outcomes from the revert attempt, each routed differently:
  2800. # "reverted": row flipped from printing -> pending, run recovery
  2801. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  2802. # on_print_complete or user). Skip recovery entirely
  2803. # — the print clearly landed somewhere even if the
  2804. # watchdog didn't see the active-state transition.
  2805. # "revert_failed": SQLite contention exhausted retries. Still run
  2806. # recovery so the MQTT session gets a fresh client_id
  2807. # on the half-broken-session path.
  2808. async def _do_revert(db):
  2809. item = await db.get(PrintQueueItem, queue_item_id)
  2810. if not item or item.status != "printing":
  2811. return "already_moved_on"
  2812. item.status = "pending"
  2813. item.started_at = None
  2814. await db.commit()
  2815. return "reverted"
  2816. try:
  2817. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  2818. except Exception as e:
  2819. logger.warning(
  2820. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  2821. "scheduler may keep treating this item as in-flight",
  2822. queue_item_id,
  2823. printer_id,
  2824. e,
  2825. )
  2826. revert_outcome = "revert_failed"
  2827. if revert_outcome == "already_moved_on":
  2828. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  2829. # other path) already moved the item past 'printing', don't run the
  2830. # MQTT session-recovery logic below — a forced reconnect on a healthy
  2831. # session breaks ongoing prints on the same printer.
  2832. return
  2833. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  2834. if revert_outcome == "reverted":
  2835. if landed_on_subtask:
  2836. logger.warning(
  2837. "Queue item %s: printer %d accepted project_file (subtask_id "
  2838. "advanced) but never transitioned to an active state within "
  2839. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  2840. "for retry (#1678)",
  2841. queue_item_id,
  2842. printer_id,
  2843. total_timeout,
  2844. )
  2845. else:
  2846. logger.warning(
  2847. "Queue item %s: printer %d did not respond to print command within "
  2848. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  2849. "for retry (#967)",
  2850. queue_item_id,
  2851. printer_id,
  2852. timeout,
  2853. pre_state,
  2854. pre_subtask_id,
  2855. )
  2856. # Phase B was entered iff subtask_id advanced, which means the
  2857. # project_file landed on the printer. A forced reconnect at this point
  2858. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  2859. # skip the recovery entirely.
  2860. if landed_on_subtask:
  2861. return
  2862. # Phase A timeout path: if the printer's gcode_file changed since
  2863. # pre-dispatch, the project_file command landed and the printer is
  2864. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  2865. # If gcode_file is unchanged, the publish was silently swallowed
  2866. # (#887/#936) and force_reconnect recovery is what we want.
  2867. client = printer_manager.get_client(printer_id)
  2868. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  2869. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  2870. if publish_landed:
  2871. logger.warning(
  2872. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  2873. "received the command and is parsing slowly. Skipping forced "
  2874. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  2875. queue_item_id,
  2876. current_gcode_file,
  2877. pre_gcode_file,
  2878. )
  2879. elif client and hasattr(client, "force_reconnect_stale_session"):
  2880. client.force_reconnect_stale_session(
  2881. f"queue print command unacknowledged after {timeout:.0f}s "
  2882. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  2883. )
  2884. # Global scheduler instance
  2885. scheduler = PrintScheduler()