print_scheduler.py 203 KB

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