print_scheduler.py 159 KB

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