print_scheduler.py 191 KB

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