print_scheduler.py 136 KB

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