print_scheduler.py 199 KB

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