print_scheduler.py 353 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. from collections import deque
  8. from dataclasses import dataclass
  9. from datetime import datetime, timedelta, timezone
  10. from pathlib import Path
  11. from fastapi import HTTPException
  12. from sqlalchemy import delete, false, func, or_, select, true, update
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from sqlalchemy.orm import selectinload
  15. from backend.app.core.config import settings
  16. from backend.app.core.database import async_session, run_with_retry
  17. from backend.app.core.tasks import spawn_background_task
  18. from backend.app.core.websocket import ws_manager
  19. from backend.app.models.archive import PrintArchive
  20. from backend.app.models.library import LibraryFile
  21. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  22. from backend.app.models.printer import Printer
  23. from backend.app.models.scheduled_drying import ScheduledDrying
  24. from backend.app.models.settings import Settings
  25. from backend.app.models.smart_plug import SmartPlug
  26. from backend.app.models.spool_assignment import SpoolAssignment
  27. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  28. from backend.app.services import drying_preflight, print_dispatch_context
  29. from backend.app.services.bambu_ftp import (
  30. UploadCancelled,
  31. cache_3mf_download,
  32. delete_file_async,
  33. ftps_handshake_cooloff_deadline,
  34. get_ftp_retry_settings,
  35. upload_file_async,
  36. with_ftp_retry,
  37. )
  38. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  39. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  40. from backend.app.services.finance_budget import (
  41. create_budget_reservation,
  42. release_budget_reservation,
  43. validate_print_budget,
  44. )
  45. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  46. from backend.app.services.notification_service import notification_service
  47. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  48. from backend.app.services.printer_manager import (
  49. printer_manager,
  50. supports_airduct,
  51. supports_chamber_heater,
  52. supports_chamber_temp,
  53. supports_drying,
  54. supports_drying_while_printing,
  55. )
  56. from backend.app.services.smart_plug_manager import smart_plug_manager
  57. from backend.app.utils.color_utils import perceptual_color_distance
  58. from backend.app.utils.filament_types import canonical_filament_type
  59. from backend.app.utils.filename import derive_remote_filename
  60. from backend.app.utils.local_time import utcnow_naive
  61. from backend.app.utils.printer_models import (
  62. is_gcode_compatible,
  63. is_nozzle_rack_model,
  64. normalize_printer_model,
  65. )
  66. from backend.app.utils.threemf_tools import (
  67. extract_rack_plan_from_3mf,
  68. extract_slot_extruders_from_3mf,
  69. )
  70. logger = logging.getLogger(__name__)
  71. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  72. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  73. # byte gate) from before the scheduler unification. Time gate keeps small
  74. # files from going silent (a single 8 KB chunk fires once and that's it);
  75. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  76. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  77. # sub-200 ms files.
  78. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  79. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  80. # How far back chamber temperature samples are retained. 2h comfortably spans
  81. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  82. # before the next print.
  83. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  84. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  85. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  86. # who clear plates promptly will want far less than this; it is deliberately
  87. # the cautious end, since the cost of it being too short is only a re-soak.
  88. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  89. # Max acceptable gap between two consecutive chamber samples before we treat
  90. # the older one as belonging to a separate observation run (printer went
  91. # offline and came back). Above ~30s cadence with a safety margin.
  92. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  93. # How long the chamber must read below target before we accept that it really
  94. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  95. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  96. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  97. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  98. # sub-target readings are therefore a door opening or noise, not lost soak,
  99. # and a plate swap (exactly when keep-warm is running) produces one. Six
  100. # minutes clears the longest such artifact observed (~5 min once bracketed by
  101. # its neighbouring samples) and still sits far below the 23-minute floor for
  102. # real cooling.
  103. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  104. # How often the preheat stage re-checks that the item it is heating for still
  105. # wants to be printed. Cancelling only writes `status` to the database — it
  106. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  107. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  108. # and the printer stays in `busy_printers`, blocking every other queued item
  109. # behind a print that is not happening.
  110. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  111. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  112. _AIRDUCT_MODE_COOLING = 0
  113. _AIRDUCT_MODE_HEATING = 1
  114. # How long a queue row may stay 'printing' while its printer sits in a terminal
  115. # state before the scheduler closes it itself (#2829).
  116. #
  117. # A real completion arrives within seconds of the printer going terminal, so
  118. # five minutes is far outside the normal path — this only ever sees a row whose
  119. # completion was refused or never delivered. It is the whole cost of the
  120. # failure to the user, though: a stranded row blocks every later job for that
  121. # printer, so it should not be raised without reason.
  122. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  123. # gcode_state values that mean the print is over, mapped to the queue status
  124. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  125. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  126. # which the queue calls cancelled) so a recovered row cannot disagree with one
  127. # closed by the normal path.
  128. _TERMINAL_STATE_QUEUE_STATUS = {
  129. "FINISH": "completed",
  130. "FAILED": "failed",
  131. "IDLE": "cancelled",
  132. }
  133. def _terminal_queue_status(state) -> str | None:
  134. """Queue status implied by *state*, or None if the print is not over.
  135. None for a disconnected printer as well as a busy one: a printer we are not
  136. talking to has a stale ``state`` field that proves nothing about what it is
  137. doing now.
  138. """
  139. if state is None or not getattr(state, "connected", False):
  140. return None
  141. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  142. @dataclass
  143. class _KeepWarmEntry:
  144. """Per-printer keep-warm state.
  145. - ``started``: monotonic time when keep-warm first fired for this printer.
  146. Used by the max-duration timeout.
  147. - ``held_target``: last bed target we successfully published. On release
  148. we only send bed-off when firmware still reports this value, so a user
  149. or subsequent print that changed the target isn't clobbered.
  150. - ``expired``: latched True when the max-duration timeout fires. Prevents
  151. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  152. release sweep drops the entry entirely once the printer leaves the
  153. candidate set.
  154. """
  155. started: float
  156. held_target: int
  157. expired: bool = False
  158. # Auto-drying re-arm guards (#2770).
  159. #
  160. # An AMS reports HIGHER relative humidity while it is warm than once it has
  161. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  162. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  163. # threshold set inside that band therefore cannot be satisfied while the box is
  164. # hot, and the firmware is free to end a cycle whenever it decides the filament
  165. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  166. # the threshold and arms another cycle. The reporter's log has five 12-hour
  167. # cycles armed inside four hours, one of them six seconds after the previous
  168. # ended.
  169. #
  170. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  171. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  172. # manual or firmware-run dry is untouched.
  173. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  174. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  175. # How long a finished scheduled drying row is kept before it is pruned.
  176. SCHEDULED_DRYING_RETENTION_DAYS = 7
  177. # How often that prune actually runs. The check itself is called on every queue
  178. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  179. # write transaction, which SQLite serialises against every other writer. Rows
  180. # only become prunable a week after they finish, so anything short of hourly is
  181. # paying that cost for nothing.
  182. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  183. class _UploadProgressBridge:
  184. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  185. ``upload_file_async`` runs the FTP transfer in an executor thread and
  186. invokes its ``progress_callback`` from that thread, so the callback
  187. body cannot ``await`` directly. This bridge captures the asyncio loop
  188. at construction (on the scheduler thread) and uses
  189. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  190. matches the legacy background_dispatch.py path 1:1 so the toast feels
  191. identical to the pre-#1625 experience.
  192. Failures inside the emit are swallowed — progress is a UX nicety, the
  193. upload itself must not fail because of a WS hiccup.
  194. """
  195. def __init__(self, user_id: int | None, queue_item_id: int):
  196. self._user_id = user_id
  197. self._queue_item_id = queue_item_id
  198. try:
  199. self._loop = asyncio.get_running_loop()
  200. except RuntimeError:
  201. self._loop = None
  202. self._last_emit_bytes = 0
  203. self._last_emit_monotonic = 0.0
  204. self._has_emitted = False
  205. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  206. if self._loop is None or total_bytes <= 0:
  207. return
  208. now = time.monotonic()
  209. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  210. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  211. # the four matter most: first-call so the user sees something even
  212. # for sub-chunk-size files; uploaded >= total so the bar locks at
  213. # 100% even when the throttle would otherwise eat it.
  214. should_emit = (
  215. not self._has_emitted
  216. or bytes_transferred >= total_bytes
  217. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  218. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  219. )
  220. if not should_emit:
  221. return
  222. self._has_emitted = True
  223. self._last_emit_bytes = bytes_transferred
  224. self._last_emit_monotonic = now
  225. try:
  226. asyncio.run_coroutine_threadsafe(
  227. ws_manager.send_queue_item_upload_progress(
  228. user_id=self._user_id,
  229. queue_item_id=self._queue_item_id,
  230. bytes_transferred=bytes_transferred,
  231. total_bytes=total_bytes,
  232. ),
  233. self._loop,
  234. )
  235. except Exception:
  236. pass # progress is best-effort, never block the upload
  237. # Bambu firmware states that mean the project_file has actually been accepted
  238. # and the printer is now processing / running / paused mid-print. Used by the
  239. # dispatch watchdog (#1370): a transition into one of these states means the
  240. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  241. # a post-print prompt) is NOT a valid "command landed" signal even though the
  242. # state value did change. SLICING is included because some firmwares park
  243. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  244. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  245. # How many times the start-watchdog may revert an item to 'pending' before it
  246. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  247. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  248. # both never recovers and starves the other printers of dispatch slots. Three
  249. # is chosen to clear the transient causes the watchdog already recovers from —
  250. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  251. # force-reconnect on the very next attempt — while still bounding the loop.
  252. DISPATCH_MAX_ATTEMPTS = 3
  253. @dataclass(slots=True)
  254. class _ModelCandidate:
  255. """One (file, printer model) pair the model-based matcher may try.
  256. Model-based assignment used to have exactly one of these per item, held
  257. directly in the item's own columns. Cross-model queue items (#671) have
  258. several, held in ``print_queue_variants``. Both shapes are normalised into
  259. this so the matching, the cross-model gate and the waiting-reason handling
  260. are written once and an item without variants provably takes the same path
  261. it took before variants existed.
  262. ``variant`` is None for the item's own columns and set for a real variant
  263. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  264. item once that candidate wins.
  265. """
  266. target_model: str | None
  267. sliced_for: str | None
  268. required_filament_types: str | None
  269. filament_overrides: str | None
  270. variant: "PrintQueueVariant | None" = None
  271. def _sliced_for_model(archive, library_file) -> str | None:
  272. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  273. if archive is not None:
  274. return archive.sliced_for_model
  275. if library_file is not None and library_file.file_metadata:
  276. return library_file.file_metadata.get("sliced_for_model")
  277. return None
  278. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  279. """The filament a candidate needs, as ``(types, overrides)``.
  280. Both columns are JSON text written by the slicer step. Malformed content is
  281. treated as no constraint rather than as an error: a job whose overrides
  282. cannot be parsed still prints, it just gets no filament-based narrowing.
  283. Overrides carry their own types, so the returned type list is the union of
  284. the two — an override on one slot must not drop the requirements of the
  285. slots it says nothing about.
  286. Shared by the matcher and by the smart-plug wake step so both ask a printer
  287. for the same filament (#2876). Waking a printer the matcher would then
  288. reject on colour is the bug this exists to prevent.
  289. """
  290. required_types = None
  291. if candidate.required_filament_types:
  292. try:
  293. required_types = json.loads(candidate.required_filament_types)
  294. except json.JSONDecodeError:
  295. pass
  296. filament_overrides = None
  297. if candidate.filament_overrides:
  298. try:
  299. filament_overrides = json.loads(candidate.filament_overrides)
  300. except json.JSONDecodeError:
  301. pass
  302. effective_types = required_types
  303. if filament_overrides:
  304. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  305. if override_types:
  306. effective_types = sorted(set(required_types or []) | set(override_types))
  307. return effective_types, filament_overrides
  308. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  309. """Candidate files for ``item``, best first.
  310. An item with no variant rows yields exactly one candidate built from its own
  311. columns — the pre-#671 behaviour, unchanged.
  312. Variants come back least-attempted first, ties broken by the user's
  313. ``position``. On the first pass every count is zero, so this is purely the
  314. user's priority order. After a start-watchdog bounce the printer that failed
  315. drops behind, so the next lap tries the other machine rather than spending the
  316. item's whole retry budget on the one that is wedged. Once every candidate has
  317. been tried equally often they cycle again, which keeps the item-level
  318. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  319. still gives up, it just does not give up without trying them.
  320. """
  321. if not item.variants:
  322. if not item.archive_id and not item.library_file_id:
  323. # Nothing to print at all. Dispatching would fail deep in the upload
  324. # on "No archive_id or library_file_id"; the caller holds the item
  325. # with an explanation instead.
  326. return []
  327. return [
  328. _ModelCandidate(
  329. target_model=item.target_model,
  330. sliced_for=_sliced_for_model(item.archive, item.library_file),
  331. required_filament_types=item.required_filament_types,
  332. filament_overrides=item.filament_overrides,
  333. )
  334. ]
  335. # Drop candidates whose file is gone or in the trash. Both are reachable and
  336. # neither is covered by the schema: library deletes are soft (the row lives
  337. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  338. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  339. # fires there and a hard delete leaves the variant row pointing at nothing.
  340. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  341. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  342. return [
  343. _ModelCandidate(
  344. target_model=v.target_model,
  345. sliced_for=_sliced_for_model(None, v.library_file),
  346. required_filament_types=v.required_filament_types,
  347. filament_overrides=v.filament_overrides,
  348. variant=v,
  349. )
  350. for v in ordered
  351. ]
  352. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  353. """Fold one waiting reason per candidate into a single line for the item.
  354. A cross-model item produces a reason per candidate, and pasting them
  355. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  356. — on which machine?). Each reason is prefixed with its model, except in the
  357. single-candidate case where the item already displays its target model and
  358. the prefix would be noise.
  359. Identical reasons collapse rather than repeat, so three idle-less models
  360. read as one clause.
  361. When *every* candidate is merely busy the parts are joined with the ``" | "``
  362. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  363. unprefixed. That case must keep testing busy-only: a fleet that is simply
  364. printing needs no user action, and labelling the clauses would turn each pass
  365. over a two-model item into a "job waiting" notification.
  366. """
  367. reasons = [(model, reason) for model, reason in per_model if reason]
  368. if not reasons:
  369. return None
  370. if len(reasons) == 1:
  371. return reasons[0][1]
  372. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  373. if len(distinct) == 1:
  374. return distinct[0]
  375. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  376. return " | ".join(distinct)
  377. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  378. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  379. """Human label for the models an item is waiting on ("H2S or H2C").
  380. Notifications take a single target model. For a cross-model item the item's
  381. own ``target_model`` is whichever variant happens to be first, which reads as
  382. a lie once it is the H2C that actually runs — so name all of them.
  383. """
  384. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  385. if not models:
  386. return None
  387. return " or ".join(models)
  388. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  389. """True if ``mapping`` is a non-empty list whose every entry is the
  390. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  391. Such a mapping is a bug artifact: a frontend status-load race can serialize
  392. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  393. recomputed from live status at dispatch rather than trusted, otherwise it
  394. reaches the print command and is silently downgraded to external-spool mode.
  395. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  396. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  397. explicit external selection (``>= 254``) is NOT unresolved either — those
  398. keep their meaning.
  399. """
  400. if not isinstance(mapping, list) or not mapping:
  401. return False
  402. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  403. def _mqtt_commands_rejected(status) -> bool:
  404. """True when the printer is currently reporting that it refused a command.
  405. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  406. a control command it could not verify. Queries still answer, so the printer
  407. looks connected and idle while project_file, gcode_line and
  408. ams_change_filament are all dropped — no amount of waiting or re-uploading
  409. changes that (#2732).
  410. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  411. ``print_error`` path builds HMSError differently), so this is safe to call on
  412. every watchdog poll.
  413. """
  414. for err in getattr(status, "hms_errors", None) or []:
  415. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  416. return True
  417. return False
  418. def _drying_ams_ids(status) -> list[int]:
  419. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  420. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  421. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  422. started (#2758) — it is a diagnostic, not a gate.
  423. Deliberately not used to block or stop drying before dispatch. This printer
  424. class supports drying concurrently with an active print
  425. (``supports_drying_while_printing``), so drying is not incompatible with
  426. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  427. while two AMS units were drying, one of them without its external PSU. Until
  428. it is known whether the blocker is drying itself or the power budget
  429. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  430. hardware is perfectly happy to continue.
  431. """
  432. ids: list[int] = []
  433. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  434. if not isinstance(unit, dict):
  435. continue
  436. try:
  437. if int(unit.get("dry_time") or 0) > 0:
  438. ids.append(int(unit.get("id", 0)))
  439. except (TypeError, ValueError):
  440. continue
  441. return ids
  442. def _parse_diameter(raw) -> float | None:
  443. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  444. try:
  445. value = float(raw)
  446. except (TypeError, ValueError):
  447. return None
  448. return value if value > 0 else None
  449. def _nozzle_info_by_id(status) -> dict[int, dict]:
  450. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  451. The field name is historical: on the H2 series ``nozzle_info`` carries an
  452. entry for *every* nozzle the printer knows about — the L/R hotends under
  453. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  454. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  455. :func:`_installed_nozzle_diameters` each take the half they need.
  456. """
  457. by_id: dict[int, dict] = {}
  458. for entry in getattr(status, "nozzle_rack", None) or []:
  459. if not isinstance(entry, dict):
  460. continue
  461. try:
  462. by_id[int(entry.get("id"))] = entry
  463. except (TypeError, ValueError):
  464. continue
  465. return by_id
  466. # What the firmware puts in a nozzle's serial number when the carriage or dock
  467. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  468. # its nozzle back in the rack (#2885).
  469. _EMPTY_NOZZLE_SERIAL = "N/A"
  470. def _nozzle_is_mounted(entry: dict | None) -> bool:
  471. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  472. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  473. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  474. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  475. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  476. the dock. So the diameter is not a presence signal (#2885).
  477. Emptiness has to be stated, not merely unstated. The serial must be the
  478. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  479. absent — an empty serial only means the printer didn't say, and a firmware
  480. that reports neither field normalises to exactly that. Treating "didn't
  481. say" as "empty" would silently switch the #1899 guard off on any such
  482. machine, so everything we cannot positively call empty counts as mounted.
  483. """
  484. if entry is None:
  485. return True
  486. serial = str(entry.get("serial_number") or "").strip().upper()
  487. if serial != _EMPTY_NOZZLE_SERIAL:
  488. return True
  489. try:
  490. max_temp = float(entry.get("max_temp") or 0)
  491. except (TypeError, ValueError):
  492. return True
  493. return max_temp > 0
  494. def _installed_nozzle_diameters(status) -> list[float]:
  495. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  496. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  497. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  498. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  499. told us its nozzle hardware" — callers must treat that as unknown, not as a
  500. mismatch, so we never block a print on missing data.
  501. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  502. though ``nozzles`` still carries a diameter for it: that value is stale, and
  503. counting it would let a slice match a nozzle the machine does not have
  504. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  505. """
  506. info = _nozzle_info_by_id(status)
  507. diameters: list[float] = []
  508. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  509. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  510. try:
  511. value = float(raw)
  512. except (TypeError, ValueError):
  513. continue
  514. if value > 0 and _nozzle_is_mounted(info.get(index)):
  515. diameters.append(value)
  516. return diameters
  517. def _rack_nozzle_diameters(status) -> list[float]:
  518. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  519. Keyed off the nozzle ids themselves rather than the printer model: only a
  520. rack machine ever reports ids 16-21, so there is no model registry to keep
  521. in sync. An empty dock is simply absent from the payload — measured on an
  522. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  523. present — so appearing here already means "a nozzle is in that dock".
  524. ``stat`` is deliberately not interpreted: its values aren't known, and
  525. reading it wrongly could hide a nozzle the printer would happily fetch.
  526. """
  527. diameters: list[float] = []
  528. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  529. if nozzle_id not in _RACK_NOZZLE_IDS:
  530. continue
  531. # PrinterState spells it "diameter"; the REST schema renames it to
  532. # "nozzle_diameter". Accept either so a caller holding the serialised
  533. # shape gets the same answer.
  534. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  535. if value is not None:
  536. diameters.append(value)
  537. return diameters
  538. def _format_diameters(diameters: list[float]) -> str:
  539. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  540. Deduplicated because a loaded rack holds several nozzles of the same size,
  541. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  542. short form doesn't. Matching still runs over the full list.
  543. """
  544. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  545. def _nozzle_mismatch_message(
  546. sliced_nozzle: float | None,
  547. installed: list[float],
  548. rack: list[float] | None = None,
  549. ) -> str | None:
  550. """Return an actionable error message when the sliced nozzle can't be
  551. printed on any nozzle the machine can reach, else None (#1899).
  552. Fail-safe: returns None whenever we lack the data to judge — no sliced
  553. diameter, or the printer reported no nozzles — so a print is only ever
  554. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  555. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  556. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  557. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  558. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  559. as reachable: the printer fetches one as part of starting the print, so a
  560. slice that matches a docked nozzle is not a mismatch. Without this the
  561. guard blocked every job whose nozzle happened not to be on a hotend at
  562. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  563. diameter already mounted could ever print, and the user had to fetch the
  564. nozzle by hand on the printer's own UI first (#2885).
  565. """
  566. reachable = [*installed, *(rack or [])]
  567. if not sliced_nozzle or not reachable:
  568. return None
  569. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  570. return None
  571. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  572. if rack:
  573. where += f" and {_format_diameters(rack)} in the nozzle rack"
  574. return (
  575. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  576. f"{where}. Re-slice for an available nozzle, or fit the matching "
  577. f"nozzle before printing."
  578. )
  579. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  580. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  581. Shared by the required and loaded sides, which name their extruder
  582. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  583. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  584. 1 the left/deputy — and both are absent on single-nozzle printers, where
  585. naming a nozzle would be noise.
  586. """
  587. parts = [(entry.get("type") or "filament").upper()]
  588. if entry.get("color"):
  589. parts.append(str(entry["color"]))
  590. nozzle = entry.get(nozzle_key)
  591. if nozzle == 0:
  592. parts.append("(right nozzle)")
  593. elif nozzle == 1:
  594. parts.append("(left nozzle)")
  595. return " ".join(parts)
  596. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  597. """Explain that nothing loaded matches what the file needs (#2771).
  598. Only ever built for a printer with no AMS, where the loaded list is short
  599. enough to quote in full and there is no "load another spool and hit Resume"
  600. recovery — the external spool holder is all there is, so the user needs to
  601. be told which filament to put on it.
  602. """
  603. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  604. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  605. return (
  606. f"No filament loaded on this printer matches the file. It needs {want}; "
  607. f"the printer has {have} and no AMS. Load the required filament on the "
  608. f"external spool holder, or send this job to a printer that has it."
  609. )
  610. class PrintScheduler:
  611. """Background scheduler that processes the print queue."""
  612. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  613. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  614. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  615. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  616. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  617. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  618. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  619. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  620. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  621. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  622. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  623. }
  624. def __init__(self):
  625. self._running = False
  626. self._check_interval = 30 # seconds
  627. # After a pass that actually dispatched something, loop again almost
  628. # immediately instead of sleeping the full interval (#2555). A dispatch
  629. # changes printer state — a batch launch fans out over several passes as
  630. # printers free up, a wedged head-of-line job reverts to pending, an
  631. # upload slot opens — and the next batch of ready work should not have to
  632. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  633. # pending items are behind printers that are genuinely busy printing),
  634. # there is nothing to react to, so we fall back to the normal interval;
  635. # that also means this can never tight-loop, since fast ticks only
  636. # continue while dispatches keep happening and the queue is draining.
  637. self._fast_check_interval = 3 # seconds
  638. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  639. self._power_on_check_interval = 10 # seconds between connection checks
  640. # Printers whose class-target power-on failed, mapped to the monotonic
  641. # time their cool-off expires (#2786).
  642. #
  643. # Without this, one printer with an unreachable plug starves every
  644. # sibling of its model forever: the wake step walks candidates in id
  645. # order, spends the pass's single attempt on the same broken printer
  646. # every time, and the healthy one two slots down is never reached. It
  647. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  648. # which delays the whole queue, not just this job.
  649. #
  650. # Entries expire on read rather than being cleared on success: a printer
  651. # inside its cool-off is skipped before the power-on is reached, so a
  652. # live entry can never be overwritten by a success anyway. A printer
  653. # that comes back by any other route stops being a wake candidate the
  654. # moment it connects.
  655. self._wake_failures: dict[int, float] = {}
  656. self._wake_failure_cooloff = 600 # seconds
  657. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  658. self._drying_in_progress: dict[int, float] = {}
  659. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  660. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  661. # cycle and the humidity finally coming down, so the normal steady
  662. # state is an empty dict. Fields:
  663. # running — a cycle we armed is (or should be) on the firmware
  664. # ended_at — monotonic when we observed that cycle end
  665. # unproductive — consecutive armed cycles that ended with the reading
  666. # still above the threshold
  667. # suspended — we have stopped arming this unit and said so
  668. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  669. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  670. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  671. # Auto-drying's stop-all branches must not stop or untrack these printers;
  672. # both features share _drying_in_progress.
  673. self._scheduled_drying_printer_ids: set[int] = set()
  674. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  675. # the first pass after a restart reaps anything left behind.
  676. self._last_scheduled_drying_prune: float | None = None
  677. # Defensive in-memory dispatch hold (#1157): a printer that just received
  678. # a project_file command must not get a second dispatch until either it
  679. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  680. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  681. # during that window the DB busy_printers seed is empirically unreliable
  682. # (multi-plate batches double-/triple-dispatched onto the same printer
  683. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  684. # or revert.
  685. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  686. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  687. # Minimum cooldown between dispatches to the same printer (covers the
  688. # H2D's project_file digestion window).
  689. self._dispatch_min_cooldown = 60.0
  690. # Hard timeout — drop the hold even if we never observed a transition,
  691. # so a lost MQTT session can't lock a printer out of the queue forever.
  692. # Matches the watchdog timeout (90 s) plus a safety margin so the
  693. # watchdog runs first on the unhappy path.
  694. self._dispatch_max_hold = 180.0
  695. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  696. # an earlier pass and is still running. `_start_print` flips the row
  697. # pending -> printing only *after* the upload completes, so until then
  698. # the row stays `pending`: each tick, check_queue excludes these
  699. # item_ids from re-selection and their printers from new dispatch /
  700. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  701. # freed slots refill on the next fast tick. check_queue is the sole,
  702. # sequential caller and the prune done-callbacks run in the same
  703. # event-loop thread, so this dict needs no lock.
  704. # item_id -> (task, printer_id)
  705. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  706. # Expected prints registered by `_start_print` that have not yet had a
  707. # print command sent. Populated at registration, dropped once
  708. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  709. # other exit. Same threading argument as `_inflight` above: one
  710. # sequential caller, callbacks on the same loop, so no lock.
  711. # item_id -> (printer_id, remote_filename, archive_id)
  712. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  713. # Budget reservations created for a dispatch whose print command has
  714. # not been confirmed yet. `_dispatch_one` releases these on every
  715. # unsuccessful exit; a successful start removes the item id and leaves
  716. # the reservation for finance_billing to consume with the archive.
  717. self._unconfirmed_budget_reservations: set[int] = set()
  718. # Chamber temperature history for smart soak-time reduction.
  719. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  720. # Entries older than _chamber_history_ttl are pruned on write.
  721. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  722. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  723. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  724. # Populated on engagement in `_apply_keep_warm`, cleared by
  725. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  726. # when a gate setting toggles off mid-hold — the release publishes
  727. # bed → 0 first).
  728. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  729. # Preheat rollback registry: printer_id -> subset of
  730. # {"bed", "chamber", "airduct"} listing which preheat commands
  731. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  732. # every entry still present at exit unless the print successfully
  733. # started, so a failed upload / cancel / exception never leaves the
  734. # printer heating for a job that isn't happening.
  735. self._preheat_pin: dict[int, set[str]] = {}
  736. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  737. # rollback can tell its own target from one someone else has since
  738. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  739. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  740. self._preheat_pin_bed: dict[int, int] = {}
  741. # Item ids whose in-flight dispatch has been cancelled or deleted while
  742. # its preheat was still holding at temperature. Set by
  743. # `notify_dispatch_cancelled` from the queue routes, consumed by
  744. # `_preheat_sleep`, and cleared when the dispatch exits.
  745. self._cancelled_dispatches: set[int] = set()
  746. # printer_id -> monotonic time it was first seen terminal while one of
  747. # its queue rows was still 'printing'. Reset by any non-terminal
  748. # observation, so it measures an unbroken run rather than a total.
  749. # In-memory on purpose: a restart re-arms the grace period, which only
  750. # delays a recovery that is already the exceptional path (#2829).
  751. self._terminal_since: dict[int, float] = {}
  752. async def run(self):
  753. """Main loop - check queue every interval."""
  754. self._running = True
  755. logger.info("Print scheduler started")
  756. await self._clear_stale_dispatch_claims(at_startup=True)
  757. while self._running:
  758. dispatched = False
  759. try:
  760. self._sample_chamber_temps()
  761. # No-op while any upload is in flight; on a quiet tick it releases
  762. # a claim whose best-effort clear failed (e.g. the database was
  763. # briefly unreachable), instead of leaving the row wedged until
  764. # the next restart.
  765. await self._clear_stale_dispatch_claims()
  766. await self._close_stranded_printing_items()
  767. dispatched = await self.check_queue()
  768. except Exception as e:
  769. logger.error("Scheduler error: %s", e)
  770. # Re-check quickly after a productive pass so a draining batch does
  771. # not stall behind the idle interval; otherwise sleep normally (#2555).
  772. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  773. async def _close_stranded_printing_items(self) -> None:
  774. """Close a ``printing`` row the completion event never closed (#2829).
  775. ``on_print_complete`` refuses to close a row when the completion's
  776. subtask name disagrees with the file the row was dispatched with, so a
  777. completion meant for something else (the printer's own
  778. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  779. The refusal has no way back, though: nothing else ever closes the row,
  780. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  781. one bad comparison wedges that printer's queue until a human presses
  782. cancel. That is what #2829's reporters hit, and the guard's own
  783. docstring already called stranding the worse of the two failures.
  784. This is the way back. When a row has been ``printing`` while its
  785. printer sat in a terminal state for the whole grace period, the print
  786. is over however the event was read, and the row is closed with the
  787. status the printer's own state implies.
  788. Deliberately conservative:
  789. * Only a connected printer counts. A disconnected one has a stale
  790. ``state`` and proves nothing.
  791. * The clock is reset by any non-terminal observation, so this cannot
  792. fire on a printer that is merely between stages.
  793. * The grace period is far longer than the gap between a printer
  794. finishing and its completion arriving, so the normal path always
  795. wins the race and this only ever sees genuine strandings.
  796. What it does *not* do is replay the completion's side effects --
  797. notifications, billing, auto-off. It restores the queue, which is the
  798. harm being undone; the archive was updated by the normal path
  799. regardless, since only the queue block refuses. A recovery that
  800. silently re-fired notifications minutes late would be its own bug.
  801. """
  802. try:
  803. async with async_session() as db:
  804. result = await db.execute(
  805. select(PrintQueueItem)
  806. .where(PrintQueueItem.status == "printing")
  807. .where(PrintQueueItem.printer_id.is_not(None))
  808. )
  809. items = list(result.scalars().all())
  810. if not items:
  811. self._terminal_since.clear()
  812. return
  813. now = time.monotonic()
  814. seen_printers: set[int] = set()
  815. closed = False
  816. for item in items:
  817. printer_id = item.printer_id
  818. seen_printers.add(printer_id)
  819. state = printer_manager.get_status(printer_id)
  820. status = _terminal_queue_status(state)
  821. if status is None:
  822. self._terminal_since.pop(printer_id, None)
  823. continue
  824. since = self._terminal_since.setdefault(printer_id, now)
  825. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  826. continue
  827. item.status = status
  828. item.completed_at = datetime.now(timezone.utc)
  829. closed = True
  830. logger.warning(
  831. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  832. "closing it as %s. Its completion event was never matched to it, which blocks "
  833. "every later job for this printer (#2829).",
  834. item.id,
  835. printer_id,
  836. getattr(state, "state", None),
  837. now - since,
  838. status,
  839. )
  840. if closed:
  841. await db.commit()
  842. for printer_id in list(self._terminal_since):
  843. if printer_id not in seen_printers:
  844. del self._terminal_since[printer_id]
  845. except Exception as e:
  846. # Best-effort, same as the claim sweep beside it: a recovery path
  847. # that can itself break the scheduler loop is worse than the strand.
  848. logger.error("Stranded-item sweep failed: %s", e)
  849. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  850. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  851. A claim is only ever held by a live dispatch coroutine, so when this
  852. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  853. is stale. At startup that is trivially true — no coroutine survives a
  854. restart. It is equally true on any later tick where no upload is running,
  855. which is what makes this safe to repeat rather than only run once.
  856. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  857. the database is briefly unreachable at exactly the moment dispatch ends,
  858. the claim survives and the row is wedged out of the selection query. That
  859. used to last until the next restart (#2702 follow-up, seen when
  860. PostgreSQL refused a connection mid-dispatch).
  861. ``_inflight`` is populated when the task is spawned, before the coroutine
  862. claims its row, and pruned by a done-callback that cannot run before the
  863. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  864. race window and needs no age threshold. A size-derived upload deadline
  865. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  866. """
  867. if self._inflight:
  868. return
  869. try:
  870. async with async_session() as db:
  871. res = await db.execute(
  872. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  873. )
  874. await db.commit()
  875. if res.rowcount:
  876. logger.info(
  877. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  878. res.rowcount,
  879. " at startup" if at_startup else "",
  880. )
  881. except Exception as exc:
  882. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  883. def stop(self):
  884. """Stop the scheduler."""
  885. self._running = False
  886. logger.info("Print scheduler stopped")
  887. async def check_queue(self) -> bool:
  888. """Check for prints ready to start.
  889. Returns True if this pass dispatched at least one item, so the caller
  890. can loop again quickly instead of sleeping the full interval (#2555).
  891. """
  892. async with async_session() as db:
  893. # Check if shortest-job-first scheduling is enabled
  894. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  895. # Get all pending items, ordered by printer and position (or SJF order)
  896. if sjf_enabled:
  897. # SJF: group by printer (and target_model for model-based jobs),
  898. # then items already jumped get top priority (starvation guard),
  899. # then sort by print_time ascending. Items with no print time go last.
  900. result = await db.execute(
  901. select(PrintQueueItem)
  902. .where(PrintQueueItem.status == "pending")
  903. # Never re-select a row a dispatch worker has already claimed
  904. # (#2615) — belt-and-suspenders with the _inflight exclusion
  905. # below, and the guard that lets an orphaned claim be ignored
  906. # until startup reconciliation clears it.
  907. .where(PrintQueueItem.dispatching_at.is_(None))
  908. # archive/library_file are read by the cross-model gate
  909. # (#2578); eager-load once per pass instead of a lazy-load
  910. # (which would raise in async) per item.
  911. .options(
  912. selectinload(PrintQueueItem.archive),
  913. selectinload(PrintQueueItem.library_file),
  914. # Cross-model candidates (#671), plus each candidate's file
  915. # for the same cross-model gate. Lazy-loading either would
  916. # raise in async.
  917. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  918. )
  919. .order_by(
  920. PrintQueueItem.printer_id,
  921. PrintQueueItem.target_model,
  922. PrintQueueItem.been_jumped.desc(),
  923. PrintQueueItem.print_time_seconds.asc().nullslast(),
  924. PrintQueueItem.position,
  925. )
  926. )
  927. else:
  928. result = await db.execute(
  929. select(PrintQueueItem)
  930. .where(PrintQueueItem.status == "pending")
  931. # Skip rows already claimed by a dispatch worker (#2615).
  932. .where(PrintQueueItem.dispatching_at.is_(None))
  933. .options(
  934. selectinload(PrintQueueItem.archive),
  935. selectinload(PrintQueueItem.library_file),
  936. # Cross-model candidates (#671), plus each candidate's file
  937. # for the same cross-model gate. Lazy-loading either would
  938. # raise in async.
  939. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  940. )
  941. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  942. )
  943. items = list(result.scalars().all())
  944. # Drop rows whose upload is still in flight from an earlier pass
  945. # (#2602). They stay `pending` until the upload finishes, so without
  946. # this a fast tick would re-select and re-dispatch the same row.
  947. # Belt-and-suspenders with the printer exclusion below.
  948. if self._inflight:
  949. inflight_ids = set(self._inflight)
  950. items = [it for it in items if it.id not in inflight_ids]
  951. # Read plate-clear setting once per queue check. Default MUST be
  952. # False to match the schema (SettingsSchema.require_plate_clear
  953. # defaults False) and the frontend (toggle + card badge both treat a
  954. # missing value as off). When no settings row exists, a True default
  955. # here re-enabled the plate-clear gate the UI showed as disabled,
  956. # blocking dispatch to FINISH-state printers forever with no UI path
  957. # to clear it (#1865).
  958. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  959. # Dispatch and track scheduled drying runs (#2638)
  960. await self._check_scheduled_dryings(db)
  961. if not items:
  962. # No dispatchable pending items — still check auto-drying on idle
  963. # printers, but keep any printer with an upload still in flight
  964. # from an earlier pass out of it (#2602): its print is imminent,
  965. # so it must not be auto-dried in the gap before the row flips to
  966. # printing. Report the pass as productive while uploads run so the
  967. # loop stays on the fast interval.
  968. #
  969. # Also release any keep-warm holds that got orphaned by the queue
  970. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  971. # this early return, so call it directly with an empty candidate
  972. # set. Without this, a printer whose queued item was cancelled or
  973. # deleted would keep its bed at target until the max-duration
  974. # timeout expired.
  975. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  976. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  977. await self._check_auto_drying(db, [], inflight_printers)
  978. return bool(self._inflight)
  979. logger.info(
  980. "Queue check: found %d pending items: %s",
  981. len(items),
  982. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  983. )
  984. # Seed busy_printers with printers that already have an item in 'printing'
  985. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  986. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  987. # lag several seconds behind the print command, so the next check_queue
  988. # tick still sees IDLE and would double-dispatch onto the same printer.
  989. # Without this guard, two pending items targeting the same printer
  990. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  991. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  992. busy_result = await db.execute(
  993. select(PrintQueueItem.printer_id)
  994. .where(PrintQueueItem.status == "printing")
  995. .where(PrintQueueItem.printer_id.is_not(None))
  996. )
  997. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  998. # Defense-in-depth (#1157): augment busy_printers with any printer
  999. # still in its post-dispatch hold window. Empirically, the DB seed
  1000. # above can miss in-flight items in a multi-plate batch — same-file
  1001. # plates were being dispatched 30 s apart while the H2D was still
  1002. # digesting the first project_file. The hold is keyed in-memory and
  1003. # released by the watchdog on the success path, so it adds a layer
  1004. # that doesn't depend on DB row visibility or completion-callback
  1005. # timing.
  1006. for held_printer_id in list(self._dispatch_holds.keys()):
  1007. if self._printer_in_dispatch_hold(held_printer_id):
  1008. busy_printers.add(held_printer_id)
  1009. # Exclude printers whose upload is still in flight from an earlier
  1010. # pass (#2602). The row is `pending` until the upload finishes and
  1011. # the printing-state seed / dispatch hold above only arm once the
  1012. # upload completes, so this is what holds the printer (and, via
  1013. # busy_printers, its auto-drying) out of the pass during the upload.
  1014. for _task, inflight_pid in self._inflight.values():
  1015. if inflight_pid is not None:
  1016. busy_printers.add(inflight_pid)
  1017. # Snapshot taken here, before the item loop adds anything (#2801).
  1018. #
  1019. # The three sources above all mean the same thing: a print on this
  1020. # printer is running or imminent. Everything the loop adds below
  1021. # means only "the queue could not dispatch to it this pass", which
  1022. # is a different statement -- a printer waiting on a plate-clear
  1023. # acknowledgment, an offline printer, one with no matching file.
  1024. #
  1025. # Auto-drying must only see the first kind. Reading the whole set
  1026. # as "is currently printing" is what put a plate-held printer down
  1027. # the mid-print path: it capped the drying temperature, logged the
  1028. # cycle as (mid-print), and skipped the very gate that was supposed
  1029. # to hold it. The interlock block below already documents the same
  1030. # hazard and works around it by staying out of busy_printers; this
  1031. # generalises that workaround instead of repeating it per case.
  1032. dispatching_printers: set[int] = set(busy_printers)
  1033. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1034. # enclosure door left open, say. The fixed-printer branch turns
  1035. # this into a waiting_reason the user can act on; the model-based
  1036. # branch hides these printers from the matcher so an "Any <model>"
  1037. # job runs on a sibling instead of queueing behind the held one.
  1038. #
  1039. # Deliberately NOT merged into busy_printers, even though that set
  1040. # already means "unavailable this pass". _check_auto_drying reads
  1041. # it as "is currently printing" and would put an idle-but-held
  1042. # printer down the mid-print drying path, which caps the drying
  1043. # temperature and skips the queue-only gating. A held printer is
  1044. # idle; it should dry exactly as it did before.
  1045. #
  1046. # Only sensors we actually read and found alerting appear here; see
  1047. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1048. # holds nothing.
  1049. interlocked: dict[int, str] = {}
  1050. try:
  1051. interlocked = await ha_sensor_manager.blocked_printers(db)
  1052. except Exception as e:
  1053. # Never let the interlock stop the queue running. A broken
  1054. # lookup means no holds, not no dispatches.
  1055. logger.warning("Home Assistant interlock check failed: %s", e)
  1056. interlocked = {}
  1057. # Printers a smart plug can bring back, read once for the whole pass
  1058. # (#2786). Used by the model-based branch both to word "Offline" in
  1059. # the waiting reason and to decide what the wake step may switch on.
  1060. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1061. # At most one power-on per queue check. Each one blocks this loop
  1062. # for the boot wait, so a queue of ten class-targeted jobs must not
  1063. # switch on ten printers inside a single pass — the next pass wakes
  1064. # the next one (#2786).
  1065. power_on_attempted = False
  1066. # Log skip reasons once per queue check (not per item)
  1067. skip_reasons: dict[str, int] = {}
  1068. # Items selected for dispatch in this pass, one per printer. The
  1069. # loop below only *decides* — the uploads happen afterwards, in
  1070. # parallel (#2555). See _dispatch_selected().
  1071. dispatch_ids: list[int] = []
  1072. # Library rows queued with `cleanup_library_after_dispatch` (the
  1073. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1074. # that prints them: the row is deleted and the 3MF is unlinked from
  1075. # disk. That was safe only because dispatch was serial. Run two of
  1076. # them against the same row at once and the second DELETE matches no
  1077. # row (StaleDataError), and the winner's unlink can pull the file out
  1078. # from under the loser's in-flight upload.
  1079. #
  1080. # Only the cleanup flag mutates the row. An ordinary library print
  1081. # just reads it, so the common fan-out — one file, many printers,
  1082. # which is exactly the reporter's workload — still goes out fully in
  1083. # parallel. Narrow the guard to the mutating case; do not serialise
  1084. # the case the whole fix exists for.
  1085. dispatch_libs: set[int] = set()
  1086. consumed_libs: set[int] = set()
  1087. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1088. """True if dispatching `candidate` now would race another item's cleanup."""
  1089. lib_id = candidate.library_file_id
  1090. if lib_id is None:
  1091. return False
  1092. if candidate.cleanup_library_after_dispatch:
  1093. # We would delete a row someone else in this pass is reading.
  1094. return lib_id in dispatch_libs
  1095. # Someone else in this pass will delete the row out from under us.
  1096. return lib_id in consumed_libs
  1097. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1098. lib_id = candidate.library_file_id
  1099. if lib_id is None:
  1100. return
  1101. dispatch_libs.add(lib_id)
  1102. if candidate.cleanup_library_after_dispatch:
  1103. consumed_libs.add(lib_id)
  1104. for item in items:
  1105. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1106. if item.scheduled_time:
  1107. sched = item.scheduled_time
  1108. if sched.tzinfo is None:
  1109. sched = sched.replace(tzinfo=timezone.utc)
  1110. if sched > datetime.now(timezone.utc):
  1111. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1112. continue
  1113. # Skip items that require manual start
  1114. if item.manual_start:
  1115. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1116. continue
  1117. if item.printer_id:
  1118. # Held by a sensor interlock (#1148). Checked before the
  1119. # busy_printers test that would otherwise swallow it
  1120. # silently — "waiting for a printer" and "waiting for you
  1121. # to shut the enclosure" need to read differently, and only
  1122. # one of them is something the user can fix.
  1123. #
  1124. # The interlock is the only thing that writes a
  1125. # waiting_reason on this branch — the model-based branch
  1126. # nulls it at the moment it assigns a printer — so any
  1127. # reason still standing once the hold lifts is stale and is
  1128. # cleared here. Doing it at dispatch instead would leave a
  1129. # shut door reading "Waiting on Enclosure Door" for as long
  1130. # as the printer stayed busy with something else.
  1131. interlock_reason = interlocked.get(item.printer_id)
  1132. reason = f"Waiting on {interlock_reason}" if interlock_reason else None
  1133. if item.waiting_reason != reason:
  1134. item.waiting_reason = reason
  1135. await db.commit()
  1136. if interlock_reason:
  1137. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1138. continue
  1139. # Specific printer assignment (existing behavior)
  1140. if item.printer_id in busy_printers:
  1141. continue
  1142. # Check if printer is idle
  1143. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1144. printer_connected = printer_manager.is_connected(item.printer_id)
  1145. # If printer not connected, try to power on via smart plug
  1146. if not printer_connected:
  1147. plugs = await self._get_smart_plugs(db, item.printer_id)
  1148. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1149. if auto_on_plugs:
  1150. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1151. # Power on using the plug that actually feeds the printer, and
  1152. # wait for it to boot on that one only (#2629).
  1153. primary_plug = self._pick_power_plug(auto_on_plugs)
  1154. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1155. if powered_on:
  1156. # Also turn on any remaining auto_on plugs (e.g., filter)
  1157. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1158. try:
  1159. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1160. await service.turn_on(extra_plug)
  1161. logger.info(
  1162. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1163. )
  1164. except Exception as e:
  1165. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1166. printer_connected = True
  1167. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1168. else:
  1169. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1170. busy_printers.add(item.printer_id)
  1171. continue
  1172. else:
  1173. # No plug or auto_on disabled
  1174. busy_printers.add(item.printer_id)
  1175. continue
  1176. # Check if printer is idle (busy with another print)
  1177. if not printer_idle:
  1178. busy_printers.add(item.printer_id)
  1179. continue
  1180. # Drying blocks the queue, if the user asked it to. A hold
  1181. # is a skip like any other, so it belongs here with the
  1182. # rest of the availability checks.
  1183. if self._drying_in_progress.get(item.printer_id) and await self._get_bool_setting(
  1184. db, "queue_drying_block"
  1185. ):
  1186. busy_printers.add(item.printer_id)
  1187. continue
  1188. # Check condition (previous print success)
  1189. if item.require_previous_success:
  1190. if not await self._check_previous_success(db, item):
  1191. item.status = "skipped"
  1192. item.error_message = "Previous print failed or was aborted"
  1193. item.completed_at = datetime.now(timezone.utc)
  1194. await db.commit()
  1195. logger.info("Skipped queue item %s - previous print failed", item.id)
  1196. # Send notification
  1197. job_name = await self._get_job_name(db, item)
  1198. printer = await self._get_printer(db, item.printer_id)
  1199. await notification_service.on_queue_job_skipped(
  1200. job_name=job_name,
  1201. printer_id=item.printer_id,
  1202. printer_name=printer.name if printer else "Unknown",
  1203. reason="Previous print failed or was aborted",
  1204. db=db,
  1205. )
  1206. continue
  1207. # Resolve the AMS mapping when it's missing OR unresolved
  1208. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1209. # frontend status-load race can persist [-1] (#2589) — and
  1210. # must be recomputed from live trays rather than trusted.
  1211. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1212. if unmappable:
  1213. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1214. continue
  1215. # Filament-deficit pre-dispatch check (#1496). If the
  1216. # assigned spool can't satisfy any required slot grams,
  1217. # promote the item to manual_start so the user must
  1218. # acknowledge via the ▶ button (which re-checks live).
  1219. if await self._block_on_filament_deficit(db, item):
  1220. continue
  1221. # Hold this item back for the next pass rather than racing
  1222. # another dispatch over the same transient library row. The
  1223. # printer is still marked busy so a later item does not jump
  1224. # its place in this printer's queue.
  1225. if _library_row_conflict(item):
  1226. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1227. busy_printers.add(item.printer_id)
  1228. continue
  1229. # Print takes priority: stop a cycle Bambuddy armed, now
  1230. # that this item is definitely going out.
  1231. #
  1232. # Placement is the whole point (#2801). This used to sit up
  1233. # with the availability checks, inside the not-idle branch
  1234. # -- so it fired only on the passes where the print was NOT
  1235. # going to start, and never on the ones where it was.
  1236. # Drying is not one of the things `_is_printer_idle` looks
  1237. # at, so a stop could never have unblocked that printer
  1238. # anyway; the cycle was spent for nothing, auto-drying
  1239. # re-armed on the next tick, and a plate left
  1240. # unacknowledged turned that into a loop on the scheduler
  1241. # interval. Every skip between there and here -- a failed
  1242. # previous print, an unmappable item, a filament deficit, a
  1243. # contested library row -- is another way to lose a cycle
  1244. # for a print that never happens, which is why this waits
  1245. # until the decision is actually made.
  1246. if self._drying_in_progress.get(
  1247. item.printer_id
  1248. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1249. await self._stop_drying(item.printer_id)
  1250. # Queue the dispatch instead of running it here — see
  1251. # _dispatch_selected(). busy_printers still gets the printer
  1252. # immediately, so nothing else in this pass can target it.
  1253. _claim_library_row(item)
  1254. dispatch_ids.append(item.id)
  1255. busy_printers.add(item.printer_id)
  1256. # SJF starvation guard: mark items that were jumped
  1257. if sjf_enabled and item.print_time_seconds is not None:
  1258. for other in items:
  1259. if (
  1260. other.id != item.id
  1261. and other.status == "pending"
  1262. and other.printer_id == item.printer_id
  1263. and not other.been_jumped
  1264. and other.position < item.position
  1265. and (
  1266. other.print_time_seconds is None
  1267. or other.print_time_seconds > item.print_time_seconds
  1268. )
  1269. ):
  1270. other.been_jumped = True
  1271. await db.commit()
  1272. elif item.target_model or item.variants:
  1273. # Model-based assignment - find any idle printer of matching model.
  1274. # A plain model-based item has exactly one candidate, built from
  1275. # its own columns. A cross-model item (#671) has one per sliced
  1276. # variant and takes the first that matches, walking them in the
  1277. # user's priority order so the pick is reproducible when more
  1278. # than one printer is free in the same pass.
  1279. candidates = _candidates_for(item)
  1280. printer_id = None
  1281. chosen: _ModelCandidate | None = None
  1282. per_model_reasons: list[tuple[str | None, str]] = []
  1283. # Candidates that cleared the cross-model gate below. The
  1284. # smart-plug wake step may only consider these — waking a
  1285. # printer for a file that can never legally run on it is
  1286. # worse than not waking at all (#2786).
  1287. wakeable_candidates: list[_ModelCandidate] = []
  1288. if not candidates:
  1289. # Every candidate file has been deleted or trashed out from
  1290. # under this item. Hold it with something the user can act
  1291. # on rather than letting it look dispatchable forever.
  1292. per_model_reasons.append(
  1293. (
  1294. item.target_model,
  1295. "Every file for this job has been deleted — add a file back or remove the item",
  1296. )
  1297. )
  1298. for candidate in candidates:
  1299. effective_types, filament_overrides = _filament_constraints(candidate)
  1300. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1301. # for an incompatible model to a printer, no matter how the
  1302. # row got into the DB (old rows, direct API writes). Held
  1303. # as pending with an actionable waiting_reason — the user
  1304. # fixes it by editing the item's target model.
  1305. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  1306. per_model_reasons.append(
  1307. (
  1308. candidate.target_model,
  1309. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  1310. f"{candidate.target_model} — edit the item and fix its target model",
  1311. )
  1312. )
  1313. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  1314. continue
  1315. wakeable_candidates.append(candidate)
  1316. match_id, match_reason = await self._find_idle_printer_for_model(
  1317. db,
  1318. candidate.target_model,
  1319. # Sensor-held printers are unavailable to the
  1320. # matcher but stay out of busy_printers itself
  1321. # (#1148) — see where `interlocked` is built.
  1322. busy_printers | interlocked.keys(),
  1323. effective_types,
  1324. item.target_location,
  1325. filament_overrides=filament_overrides,
  1326. require_plate_clear=require_plate_clear,
  1327. wakeable_ids=wakeable_printer_ids,
  1328. )
  1329. if match_id:
  1330. printer_id = match_id
  1331. chosen = candidate
  1332. break
  1333. per_model_reasons.append((candidate.target_model, match_reason or ""))
  1334. # Nothing is available and nothing has been woken this pass:
  1335. # switch one matching printer on. Assignment is left to the
  1336. # next pass, which sees the booted printer's live state
  1337. # instead of guessing at it seconds after connect (#2786).
  1338. if printer_id is None and not power_on_attempted and wakeable_candidates:
  1339. woken_id, attempted_id = await self._wake_printer_for_model(
  1340. db,
  1341. wakeable_candidates,
  1342. item.target_location,
  1343. busy_printers | interlocked.keys(),
  1344. wakeable_printer_ids,
  1345. require_plate_clear,
  1346. )
  1347. # An attempt spends the pass's one wake whether or not
  1348. # it worked: it has already blocked the queue loop for
  1349. # the boot wait. A failed printer is held out of later
  1350. # passes by its own cool-off, deliberately NOT by
  1351. # busy_printers — it is off, not busy, and labelling it
  1352. # busy would both misdescribe it in every later item's
  1353. # waiting reason and suppress the notification, since
  1354. # an all-busy reason is treated as needing no action.
  1355. power_on_attempted = attempted_id is not None
  1356. if woken_id is not None:
  1357. # Hold this item back rather than dispatching onto a
  1358. # printer whose AMS has not reported yet.
  1359. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  1360. continue
  1361. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  1362. # Fold the winning variant's file and settings onto the item
  1363. # before anything else looks at them — the guards below and
  1364. # every step of the dispatch read the item's own columns.
  1365. if chosen is not None:
  1366. self._resolve_variant(item, chosen)
  1367. # Update waiting_reason if changed and send notification when first waiting
  1368. if item.waiting_reason != waiting_reason:
  1369. was_waiting = item.waiting_reason is not None
  1370. item.waiting_reason = waiting_reason
  1371. await db.commit()
  1372. # Send waiting notification only when transitioning to waiting state
  1373. # and the reason requires user action (not just "all printers busy")
  1374. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  1375. job_name = await self._get_job_name(db, item)
  1376. await notification_service.on_queue_job_waiting(
  1377. job_name=job_name,
  1378. target_model=_candidate_model_label(candidates) or item.target_model,
  1379. waiting_reason=waiting_reason,
  1380. db=db,
  1381. )
  1382. if printer_id:
  1383. # Before claiming the printer: hold back rather than race
  1384. # another dispatch over the same transient library row.
  1385. # Checked here so a held item does not get a printer
  1386. # assigned and then sit on it. See _library_row_conflict().
  1387. #
  1388. # No busy_printers.add() here, unlike the fixed-printer
  1389. # branch above: that one protects its printer's own queue
  1390. # ordering, but this item was never assigned to `printer_id`
  1391. # — the matcher merely offered it. Marking it busy would
  1392. # strand an idle printer for the rest of the pass.
  1393. if _library_row_conflict(item):
  1394. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1395. continue
  1396. # Check condition (previous print success) before assigning
  1397. if item.require_previous_success:
  1398. if not await self._check_previous_success(db, item):
  1399. item.status = "skipped"
  1400. item.error_message = "Previous print failed or was aborted"
  1401. item.completed_at = datetime.now(timezone.utc)
  1402. await db.commit()
  1403. logger.info("Skipped queue item %s - previous print failed", item.id)
  1404. # Send notification
  1405. job_name = await self._get_job_name(db, item)
  1406. printer = await self._get_printer(db, printer_id)
  1407. await notification_service.on_queue_job_skipped(
  1408. job_name=job_name,
  1409. printer_id=printer_id,
  1410. printer_name=printer.name if printer else "Unknown",
  1411. reason="Previous print failed or was aborted",
  1412. db=db,
  1413. )
  1414. continue
  1415. # Assign printer and start - clear waiting reason
  1416. item.printer_id = printer_id
  1417. item.waiting_reason = None
  1418. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  1419. # Send assignment notification
  1420. job_name = await self._get_job_name(db, item)
  1421. printer = await self._get_printer(db, printer_id)
  1422. await notification_service.on_queue_job_assigned(
  1423. job_name=job_name,
  1424. printer_id=printer_id,
  1425. printer_name=printer.name if printer else "Unknown",
  1426. target_model=item.target_model,
  1427. db=db,
  1428. )
  1429. # Resolve the AMS mapping for the assigned printer when it's
  1430. # missing OR unresolved (all -1). Critical for model-based
  1431. # jobs where mapping wasn't computed upfront, and it also
  1432. # self-heals a bogus stored [-1] (#2589).
  1433. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  1434. if unmappable:
  1435. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  1436. continue
  1437. # Filament-deficit pre-dispatch check (#1496).
  1438. if await self._block_on_filament_deficit(db, item):
  1439. continue
  1440. _claim_library_row(item)
  1441. dispatch_ids.append(item.id)
  1442. busy_printers.add(printer_id)
  1443. # SJF starvation guard: mark model-based items that were jumped
  1444. if sjf_enabled and item.print_time_seconds is not None:
  1445. for other in items:
  1446. if (
  1447. other.id != item.id
  1448. and other.status == "pending"
  1449. and other.printer_id is None
  1450. and other.target_model
  1451. and other.target_model.upper() == item.target_model.upper()
  1452. and not other.been_jumped
  1453. and other.position < item.position
  1454. and (
  1455. other.print_time_seconds is None
  1456. or other.print_time_seconds > item.print_time_seconds
  1457. )
  1458. ):
  1459. other.been_jumped = True
  1460. await db.commit()
  1461. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  1462. # as long as the slowest upload takes (minutes on a big 3MF), and a
  1463. # skip summary that only lands after the transfers have finished is
  1464. # useless for working out why an item did not go out.
  1465. if skip_reasons:
  1466. logger.info("Queue skip summary: %s", skip_reasons)
  1467. if busy_printers:
  1468. # Log why each printer was busy (first time it was checked)
  1469. for pid in busy_printers:
  1470. state = printer_manager.get_status(pid)
  1471. connected = printer_manager.is_connected(pid)
  1472. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  1473. state_name = state.state if state else "NO_STATUS"
  1474. logger.info(
  1475. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  1476. pid,
  1477. connected,
  1478. state_name,
  1479. awaiting,
  1480. )
  1481. # Keep-warm is a comfort feature; dispatch is not. It sits between
  1482. # selection and `_launch_uploads`, so anything raising here would
  1483. # discard this tick's selections — computed AMS mappings and all —
  1484. # and, on a persistent fault, stop the queue dispatching entirely.
  1485. # Same reasoning as the deficit check's guard below: never let an
  1486. # auxiliary check wedge the queue. The bed simply stays wherever it
  1487. # was, and the next tick tries again.
  1488. try:
  1489. await self._apply_keep_warm(db, items, dispatch_ids, busy_printers, require_plate_clear)
  1490. except Exception as e:
  1491. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  1492. # Read the concurrency limit BEFORE the commit below, not inside
  1493. # _dispatch_selected(). A SELECT on this session after the commit
  1494. # implicitly opens a fresh transaction that nothing then closes, and
  1495. # it would stay open for the whole dispatch — minutes of "idle in
  1496. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  1497. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  1498. # checkpointed while every dispatch is writing to it.
  1499. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  1500. # Selection is done; every decision above is recorded on `db`
  1501. # (model-based printer assignment, computed ams_mapping). Flush it
  1502. # before the dispatch tasks open their own sessions, or they will
  1503. # read a row that still says printer_id=None. This also releases the
  1504. # connection back to the pool for the duration of the dispatch.
  1505. await db.commit()
  1506. if dispatch_ids:
  1507. item_printers = {it.id: it.printer_id for it in items}
  1508. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  1509. # Auto-drying: start drying on idle printers that have no pending queue items
  1510. await self._check_auto_drying(db, items, dispatching_printers)
  1511. # Keep the loop on the fast interval while any upload is in flight so
  1512. # a slot freed mid-tick refills within seconds rather than after the
  1513. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  1514. # deferred because the pool was full) also counts as productive.
  1515. return bool(dispatch_ids) or bool(self._inflight)
  1516. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  1517. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  1518. Dispatch used to happen inline in the selection loop: ``await
  1519. _start_print(db, item)`` per item in turn. Since ``_start_print``
  1520. performs the FTP upload, that serialized every printer behind every
  1521. other printer's transfer even though the printers are independent
  1522. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  1523. gather was awaited before ``check_queue`` returned, so the run loop
  1524. stayed blocked until the *slowest* upload in the batch finished — a
  1525. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  1526. 93-printer farm even as other printers came free (#2602).
  1527. Each upload now runs as an independent background task tracked in
  1528. ``self._inflight``. check_queue excludes in-flight item_ids (still
  1529. `pending` until their upload completes) and their printers from the
  1530. next pass's selection, and this method launches at most
  1531. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  1532. the next fast tick instead of waiting out the whole batch. The bound
  1533. exists because the printers are independent but the host is not: each
  1534. in-flight upload holds a thread in the FTP pool, a TLS session and a
  1535. file handle.
  1536. The no-overlapping-dispatch invariant the batch-await used to provide
  1537. is now carried by the in-flight exclusion in check_queue. Everything
  1538. else — the pending->printing CAS, the busy-printer guard (#2598), the
  1539. per-printer hold, and each item's independent failure handling — still
  1540. lives in ``_start_print`` and runs per task exactly as before.
  1541. Synchronous on purpose: it registers every launched task into
  1542. ``self._inflight`` before returning, so the next (sequential) tick sees
  1543. an accurate in-flight count with no interleaving await.
  1544. """
  1545. free = limit - len(self._inflight)
  1546. if free <= 0:
  1547. logger.info(
  1548. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  1549. len(self._inflight),
  1550. limit,
  1551. len(item_ids),
  1552. item_ids,
  1553. )
  1554. return
  1555. to_launch = item_ids[:free]
  1556. deferred = item_ids[free:]
  1557. logger.info(
  1558. "Launching %d upload(s) (pool %d/%d in flight)%s",
  1559. len(to_launch),
  1560. len(self._inflight),
  1561. limit,
  1562. f" — deferring {deferred} to a later tick" if deferred else "",
  1563. )
  1564. for item_id in to_launch:
  1565. task = spawn_background_task(
  1566. self._dispatch_one(item_id, item_printers.get(item_id)),
  1567. name=f"queue-upload-{item_id}",
  1568. )
  1569. self._inflight[item_id] = (task, item_printers.get(item_id))
  1570. # Prune on completion so the freed slot is refillable next tick.
  1571. # spawn_background_task already logs any uncaught exception; this
  1572. # only reclaims the pool slot (fires on success, failure, or cancel).
  1573. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  1574. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  1575. """Upload + start one queue item in its own session (pool worker, #2602).
  1576. Its own session: pool workers run concurrently and an AsyncSession is
  1577. not safe to share across tasks; it also keeps a slow upload from pinning
  1578. the scheduler's session (and, on SQLite, its transaction) open for the
  1579. transfer's duration.
  1580. ``selected_printer_id`` is the printer this item was selected for, taken
  1581. from the same snapshot the caller used. It exists so the preheat pin can
  1582. be unwound on the paths that never reach the ``finally`` below — see the
  1583. claim failure a few lines down. Optional so the direct-call tests keep
  1584. working; when it is absent those paths simply behave as they did before.
  1585. """
  1586. async with async_session() as item_db:
  1587. # Claim the row for dispatch BEFORE reading the printer snapshot or
  1588. # touching any slow I/O (#2615). The claim is an atomic CAS on
  1589. # (status='pending', dispatching_at IS NULL); while it's held the edit
  1590. # routes reject reassignment (409), so printer_id can't change out from
  1591. # under the in-flight upload and split the queue row from the
  1592. # archive/expected-print/physical command.
  1593. if not await self._claim_for_dispatch(item_db, item_id):
  1594. logger.info(
  1595. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  1596. item_id,
  1597. )
  1598. # This return is outside the try/finally below, so the rollback
  1599. # has to happen here. Selecting this item already handed any
  1600. # keep-warm hold on its printer over to the preheat pin
  1601. # (`_sweep_keep_warm`), on the promise that this dispatch would
  1602. # unwind it. Bailing without doing so leaves the bed hot with
  1603. # nothing tracking it: the keep-warm entry is gone, so the
  1604. # max-duration cap no longer applies, and if this was the
  1605. # printer's last pending item nothing else will ever turn it
  1606. # off. Reachable whenever a cancel or delete lands between
  1607. # selection and the claim.
  1608. if selected_printer_id is not None:
  1609. self._rollback_preheat_pin(item_id, selected_printer_id)
  1610. return
  1611. # Seeded from the caller's snapshot so the `item vanished` return
  1612. # below still unwinds the pin; overwritten with the row's own
  1613. # printer_id as soon as we have it.
  1614. item_printer_id: int | None = selected_printer_id
  1615. try:
  1616. item = await item_db.get(PrintQueueItem, item_id)
  1617. if not item:
  1618. logger.info("Queue item %s vanished after claim — skipping", item_id)
  1619. return
  1620. item_printer_id = item.printer_id
  1621. await self._start_print(item_db, item)
  1622. finally:
  1623. # Undo an expected-print registration whose print command never
  1624. # went out. One choke point covers every way `_start_print` can
  1625. # end without sending: a raised exception (a DB failure mid-
  1626. # dispatch is the reported case), an early return, a cancel
  1627. # winning the #1853 CAS, or `start_print()` returning False.
  1628. # A confirmed send removes the entry itself, so this is a no-op
  1629. # on the happy path.
  1630. self._rollback_unconfirmed_expected_print(item_id)
  1631. # Mirror the pre-#1625 background-dispatch lifecycle: a
  1632. # reservation survives only after start_print() accepted the
  1633. # command. Failure, cancellation, deferral, and exceptions all
  1634. # release it here.
  1635. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  1636. # Unwind preheat state (bed/chamber/airduct) if the
  1637. # dispatch aborted before the print's own gcode took over.
  1638. # `_start_print` clears the pin on successful `start_print()`;
  1639. # anything still present here is by definition an aborted
  1640. # dispatch and gets rolled back so the printer isn't left
  1641. # heating for a job that isn't happening.
  1642. if item_printer_id is not None:
  1643. self._rollback_preheat_pin(item_id, item_printer_id)
  1644. # The cancellation flag only has meaning while this dispatch is
  1645. # running; drop it so the set cannot grow without bound and a
  1646. # re-queued item never inherits a stale cancellation.
  1647. self._cancelled_dispatches.discard(item_id)
  1648. # Release the claim on every exit. Once dispatch has finished the
  1649. # row's status carries the lock (printing/failed/cancelled are all
  1650. # != pending), so the token is only needed for the duration of the
  1651. # upload. A row left pending (e.g. busy-printer deferral) becomes
  1652. # dispatchable again on the next tick.
  1653. await self._clear_dispatch_claim(item_db, item_id)
  1654. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  1655. """Drop an expectation for a print command that was never sent.
  1656. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  1657. where the interesting exception is usually the one already propagating.
  1658. """
  1659. pending = self._unconfirmed_expected_print.pop(item_id, None)
  1660. if pending is None:
  1661. return
  1662. printer_id, remote_filename, archive_id = pending
  1663. try:
  1664. from backend.app.main import unregister_expected_print
  1665. unregister_expected_print(printer_id, remote_filename, archive_id)
  1666. except Exception:
  1667. logger.warning(
  1668. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  1669. item_id,
  1670. printer_id,
  1671. remote_filename,
  1672. archive_id,
  1673. exc_info=True,
  1674. )
  1675. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  1676. """Release a queue reservation without touching the dispatch session."""
  1677. if item_id not in self._unconfirmed_budget_reservations:
  1678. return
  1679. for attempt in range(1, 4):
  1680. async with async_session() as cleanup_db:
  1681. try:
  1682. await release_budget_reservation(
  1683. cleanup_db,
  1684. source_type="print_queue",
  1685. source_id=item_id,
  1686. status="released",
  1687. )
  1688. await cleanup_db.commit()
  1689. self._unconfirmed_budget_reservations.discard(item_id)
  1690. return
  1691. except Exception as exc:
  1692. try:
  1693. await cleanup_db.rollback()
  1694. except Exception:
  1695. pass
  1696. if attempt == 3:
  1697. logger.error(
  1698. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  1699. item_id,
  1700. attempt,
  1701. exc,
  1702. )
  1703. return
  1704. await asyncio.sleep(0.5 * attempt)
  1705. @staticmethod
  1706. def _reported_bed_target(printer_id: int) -> int | None:
  1707. """The bed target firmware currently reports, or None if it can't be read.
  1708. None means "no evidence", not "zero" — callers must not treat it as a
  1709. temperature. Deliberately total: this feeds cleanup paths that run in a
  1710. ``finally``, where a malformed status must not become the exception the
  1711. caller sees.
  1712. """
  1713. try:
  1714. state = printer_manager.get_status(printer_id)
  1715. if state is None:
  1716. return None
  1717. temps = state.temperatures
  1718. if not isinstance(temps, dict):
  1719. return None
  1720. return int(float(temps.get("bed_target", 0) or 0))
  1721. except (TypeError, ValueError, AttributeError):
  1722. return None
  1723. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  1724. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  1725. Turns the bed heater off, the chamber heater off, and opens the
  1726. airduct flap back to cooling — for whichever of those preheat
  1727. actually applied. `_start_print` clears the pin on successful
  1728. `start_print()`; anything still present when `_dispatch_one` exits
  1729. is by definition an aborted dispatch and gets rolled back here.
  1730. The bed is the one action that can be declined: if firmware has since
  1731. been given a target other than the one we pinned, it belongs to someone
  1732. else and is left alone. See the comment at that branch.
  1733. Also called directly from `_dispatch_one`'s claim-failure return, which
  1734. never reaches the ``finally``.
  1735. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  1736. """
  1737. pin = self._preheat_pin.pop(printer_id, set())
  1738. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  1739. if not pin:
  1740. return
  1741. client = printer_manager.get_client(printer_id)
  1742. if client is None:
  1743. logger.info(
  1744. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  1745. item_id,
  1746. printer_id,
  1747. )
  1748. return
  1749. if "bed" in pin:
  1750. # Only undo our own target. If firmware reports something else, the
  1751. # user or another writer owns the bed now and zeroing it would
  1752. # clobber their choice -- the same guard `_release_keep_warm`
  1753. # applies to a keep-warm hold.
  1754. #
  1755. # Every uncertain case switches the bed off rather than leaving it:
  1756. # no recorded target (a pin written before this bookkeeping, or a
  1757. # setter that raised after pinning) and an unreadable status both
  1758. # fall through. A bed left hot with no owner is the worse failure,
  1759. # and this runs in a `finally` where raising would mask the real
  1760. # exception.
  1761. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  1762. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  1763. logger.info(
  1764. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  1765. item_id,
  1766. printer_id,
  1767. cur_bed_target,
  1768. pinned_bed,
  1769. )
  1770. else:
  1771. try:
  1772. client.set_bed_temperature(0)
  1773. except Exception as exc:
  1774. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  1775. if "chamber" in pin:
  1776. try:
  1777. client.set_chamber_temperature(0)
  1778. except Exception as exc:
  1779. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  1780. if "airduct" in pin:
  1781. try:
  1782. client.set_airduct_mode("cooling")
  1783. except Exception as exc:
  1784. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  1785. logger.info(
  1786. "Dispatch item %s (printer %d): preheat rollback → %s",
  1787. item_id,
  1788. printer_id,
  1789. sorted(pin),
  1790. )
  1791. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  1792. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  1793. Returns True if this call won the claim, False if the row was already
  1794. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  1795. the load-bearing guard against reassign-during-dispatch (#2615)."""
  1796. res = await db.execute(
  1797. update(PrintQueueItem)
  1798. .where(PrintQueueItem.id == item_id)
  1799. .where(PrintQueueItem.status == "pending")
  1800. .where(PrintQueueItem.dispatching_at.is_(None))
  1801. .values(dispatching_at=datetime.now(timezone.utc))
  1802. )
  1803. await db.commit()
  1804. return res.rowcount > 0
  1805. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  1806. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  1807. mask the dispatch outcome.
  1808. Retried, because the failure mode in practice is transient and narrow: a
  1809. database that is momentarily unreachable — PostgreSQL out of connection
  1810. slots is the observed case — refuses this write for a second or two while
  1811. the dispatch that just ended is still holding the row out of the selection
  1812. query. One attempt was enough to wedge the item; a couple of spaced
  1813. attempts clear it. Each attempt rolls back first, since a failed write
  1814. leaves the session needing it before it can be reused.
  1815. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  1816. on the next quiet tick.
  1817. """
  1818. for attempt in range(1, 4):
  1819. try:
  1820. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  1821. await db.commit()
  1822. return
  1823. except Exception as exc:
  1824. try:
  1825. await db.rollback()
  1826. except Exception:
  1827. pass
  1828. if attempt == 3:
  1829. logger.warning(
  1830. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  1831. "— a later quiet tick will release it",
  1832. item_id,
  1833. attempt,
  1834. exc,
  1835. )
  1836. return
  1837. await asyncio.sleep(0.5 * attempt)
  1838. async def _printers_for_model(
  1839. self,
  1840. db: AsyncSession,
  1841. model: str,
  1842. target_location: str | None = None,
  1843. ) -> list[Printer]:
  1844. """Active printers of *model*, optionally narrowed to one location.
  1845. Shared by the matcher and by the smart-plug wake step (#2786) so both
  1846. answer "which printers can this job run on" from one query — a job can
  1847. only be woken onto a printer the matcher would also have considered.
  1848. """
  1849. normalized_model = normalize_printer_model(model) or model
  1850. query = (
  1851. select(Printer)
  1852. .where(func.lower(Printer.model) == normalized_model.lower())
  1853. .where(Printer.is_active == True) # noqa: E712
  1854. )
  1855. if target_location:
  1856. query = query.where(Printer.location == target_location)
  1857. result = await db.execute(query)
  1858. return list(result.scalars().all())
  1859. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  1860. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  1861. Read once per queue check rather than per printer: it decides both
  1862. whether the wake step has anything to do and how an offline printer is
  1863. worded in the waiting reason — "Offline" and "offline with no Auto On
  1864. plug" are different problems, and the second is the one the user has to
  1865. fix themselves (#2786).
  1866. """
  1867. result = await db.execute(
  1868. select(SmartPlug.printer_id)
  1869. .where(SmartPlug.printer_id.is_not(None))
  1870. .where(SmartPlug.enabled == True) # noqa: E712
  1871. .where(SmartPlug.auto_on == True) # noqa: E712
  1872. )
  1873. return {pid for (pid,) in result.all() if pid is not None}
  1874. def _wake_recently_failed(self, printer_id: int) -> bool:
  1875. """True while this printer's failed power-on is still cooling off (#2786)."""
  1876. deadline = self._wake_failures.get(printer_id)
  1877. if deadline is None:
  1878. return False
  1879. if time.monotonic() >= deadline:
  1880. del self._wake_failures[printer_id]
  1881. return False
  1882. return True
  1883. async def _wake_printer_for_model(
  1884. self,
  1885. db: AsyncSession,
  1886. candidates: list[_ModelCandidate],
  1887. target_location: str | None,
  1888. exclude_ids: set[int],
  1889. wakeable_ids: set[int],
  1890. require_plate_clear: bool,
  1891. ) -> tuple[int | None, int | None]:
  1892. """Power on one offline printer a model-based item could run on (#2786).
  1893. The fixed-printer branch has powered a printer on since smart plugs
  1894. existed. The model-based branch never could: its matcher drops an
  1895. offline printer into the "Offline:" waiting reason and nothing looks at
  1896. its plugs, so a class-targeted job with every matching printer switched
  1897. off sat pending forever. The reporter's log is the controlled
  1898. experiment — the same item, same plug, same Auto On setting, dispatched
  1899. the moment they edited it onto a specific printer.
  1900. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  1901. power-on was actually tried, so the caller can tell "nothing here was
  1902. wakeable" (both None — cheap, other items may still find something)
  1903. from "we tried and it did not come up" (only ``attempted_id`` — the
  1904. boot timeout has already been spent).
  1905. A printer whose last known trays cannot satisfy the job is passed over
  1906. rather than woken (#2876): the colours are readable while it is off, so
  1907. switching a farm on one machine at a time to discover them wakes
  1908. printers that could never have taken the job.
  1909. Deliberately does NOT go on to match the job once a printer is up: AMS
  1910. trays arrive with the first status push after connect, so a filament
  1911. check against a printer that booted seconds ago can reject the printer
  1912. we just woke. The next queue pass matches it with live state.
  1913. At most one printer per pass. Each wake blocks the queue loop for the
  1914. boot wait, and a queue of ten class-targeted jobs must not switch on
  1915. ten printers inside one check.
  1916. """
  1917. for candidate in candidates:
  1918. if not candidate.target_model:
  1919. continue
  1920. required_types, filament_overrides = _filament_constraints(candidate)
  1921. printers = await self._printers_for_model(db, candidate.target_model, target_location)
  1922. for printer in sorted(printers, key=lambda p: p.id):
  1923. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  1924. continue
  1925. if printer_manager.is_connected(printer.id):
  1926. continue
  1927. if self._wake_recently_failed(printer.id):
  1928. # Its plug did not bring it back a moment ago. Move on to a
  1929. # sibling instead of spending this pass — and every pass —
  1930. # on the same printer.
  1931. continue
  1932. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  1933. # Waking this one buys nothing: it would boot into IDLE and
  1934. # then be held by the plate-clear gate, which is exactly
  1935. # what the reporter's log shows happening for 80 minutes
  1936. # after a fixed-printer wake. The flag is Bambuddy-side and
  1937. # persisted, so it is readable while the printer is off.
  1938. logger.info(
  1939. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  1940. printer.id,
  1941. candidate.target_model,
  1942. )
  1943. continue
  1944. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  1945. if shortfall:
  1946. logger.info(
  1947. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  1948. printer.id,
  1949. candidate.target_model,
  1950. ", ".join(shortfall),
  1951. )
  1952. continue
  1953. plugs = await self._get_smart_plugs(db, printer.id)
  1954. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1955. if not auto_on_plugs:
  1956. # wakeable_ids said otherwise — the plug changed under us
  1957. # mid-pass. Nothing to do but move on.
  1958. continue
  1959. logger.info(
  1960. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  1961. candidate.target_model,
  1962. printer.id,
  1963. )
  1964. primary_plug = self._pick_power_plug(auto_on_plugs)
  1965. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  1966. logger.warning(
  1967. "Could not power on printer %s via smart plug; not trying it again for %ss",
  1968. printer.id,
  1969. self._wake_failure_cooloff,
  1970. )
  1971. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  1972. return None, printer.id
  1973. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1974. try:
  1975. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1976. await service.turn_on(extra_plug)
  1977. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  1978. except Exception as e:
  1979. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1980. return printer.id, printer.id
  1981. return None, None
  1982. async def _find_idle_printer_for_model(
  1983. self,
  1984. db: AsyncSession,
  1985. model: str,
  1986. exclude_ids: set[int],
  1987. required_filament_types: list[str] | None = None,
  1988. target_location: str | None = None,
  1989. filament_overrides: list[dict] | None = None,
  1990. require_plate_clear: bool = True,
  1991. wakeable_ids: set[int] | None = None,
  1992. ) -> tuple[int | None, str | None]:
  1993. """Find an idle, connected printer matching the model with compatible filaments.
  1994. Args:
  1995. db: Database session
  1996. model: Printer model to match (e.g., "X1C", "P1S")
  1997. exclude_ids: Printer IDs to exclude (already busy)
  1998. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  1999. If provided, only printers with all required types loaded will match.
  2000. target_location: Optional location filter. If provided, only printers in this location are considered.
  2001. filament_overrides: Optional list of override dicts. Each entry may include
  2002. ``force_color_match: true`` to require an exact type+color match
  2003. on the printer for that slot. Without the flag the existing
  2004. colour-preference logic applies.
  2005. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2006. offline printer is worded: one Bambuddy will switch on reads
  2007. differently from one the user has to go and switch on themselves.
  2008. Returns:
  2009. Tuple of (printer_id, waiting_reason):
  2010. - (printer_id, None) if a matching printer was found
  2011. - (None, reason) if no printer is available, with explanation
  2012. """
  2013. normalized_model = normalize_printer_model(model) or model
  2014. printers = await self._printers_for_model(db, model, target_location)
  2015. location_suffix = f" in {target_location}" if target_location else ""
  2016. if not printers:
  2017. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2018. # Separate force-matched overrides from preference-only overrides
  2019. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2020. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2021. # Track reasons for skipping printers
  2022. printers_busy = []
  2023. printers_offline = []
  2024. printers_offline_no_plug = []
  2025. printers_missing_filament: list[tuple[str, list[str]]] = []
  2026. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2027. for printer in printers:
  2028. if printer.id in exclude_ids:
  2029. # Printer is already claimed by another job in this scheduling run.
  2030. # For force-color jobs, still check if the color would match — if not,
  2031. # report it as a color mismatch rather than plain "Busy" so the user
  2032. # knows the job needs a filament change, not just to wait for availability.
  2033. if force_overrides and not pref_overrides:
  2034. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2035. if missing_colors:
  2036. printers_missing_filament.append((printer.name, missing_colors))
  2037. continue
  2038. printers_busy.append(printer.name)
  2039. continue
  2040. is_connected = printer_manager.is_connected(printer.id)
  2041. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2042. if not is_connected:
  2043. # An offline printer whose last known filament cannot run this
  2044. # job is reported as needing filament rather than as offline
  2045. # (#2876). It is also the printer the smart-plug step will now
  2046. # decline to switch on, and "Offline:" on its own would leave
  2047. # that decision looking like nothing happening at all.
  2048. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2049. if shortfall:
  2050. printers_missing_filament.append((printer.name, shortfall))
  2051. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2052. printers_offline_no_plug.append(printer.name)
  2053. else:
  2054. printers_offline.append(printer.name)
  2055. continue
  2056. if not is_idle:
  2057. # Printer is currently printing. For force-color jobs, check whether the
  2058. # loaded color would satisfy the requirement — if not, surface it as a
  2059. # color-mismatch reason rather than plain "Busy" so the user understands
  2060. # that the job is waiting for a filament change, not just printer availability.
  2061. if force_overrides and not pref_overrides:
  2062. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2063. if missing_colors:
  2064. printers_missing_filament.append((printer.name, missing_colors))
  2065. logger.debug(
  2066. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2067. printer.id,
  2068. printer.name,
  2069. missing_colors,
  2070. )
  2071. continue
  2072. printers_busy.append(printer.name)
  2073. continue
  2074. # Validate filament compatibility if required types are specified
  2075. if required_filament_types:
  2076. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  2077. if missing:
  2078. # When force_overrides are present, enrich missing entries with color info
  2079. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  2080. if force_overrides:
  2081. force_color_map = {
  2082. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  2083. for o in force_overrides
  2084. }
  2085. missing_enriched = [
  2086. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2087. for t in missing
  2088. ]
  2089. printers_missing_filament.append((printer.name, missing_enriched))
  2090. else:
  2091. printers_missing_filament.append((printer.name, missing))
  2092. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  2093. continue
  2094. # Force color match: ALL flagged slots must have an exact type+color match
  2095. if force_overrides:
  2096. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2097. if missing_colors:
  2098. printers_missing_filament.append((printer.name, missing_colors))
  2099. logger.debug(
  2100. "Skipping printer %s (%s) - missing force-matched colors: %s",
  2101. printer.id,
  2102. printer.name,
  2103. missing_colors,
  2104. )
  2105. continue
  2106. # If preference-only overrides exist, rank by color matches (existing behaviour)
  2107. if pref_overrides:
  2108. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  2109. if color_matches > 0:
  2110. candidates.append((printer.id, color_matches))
  2111. else:
  2112. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  2113. printers_missing_filament.append((printer.name, override_colors))
  2114. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  2115. continue
  2116. elif force_overrides:
  2117. # Passed all force checks — immediately eligible (no preference ordering needed)
  2118. return printer.id, None
  2119. else:
  2120. # No overrides at all - take first available (existing behavior)
  2121. return printer.id, None
  2122. # If we have candidates from preference override matching, pick the one with most color matches
  2123. if candidates:
  2124. candidates.sort(key=lambda c: c[1], reverse=True)
  2125. return candidates[0][0], None
  2126. # Build waiting reason from what we found
  2127. reasons = []
  2128. if printers_missing_filament:
  2129. # Filament/color mismatch is most actionable - show first
  2130. if force_overrides and not pref_overrides:
  2131. # All mismatches are force-color failures — use descriptive message only;
  2132. # but only if there are no busy printers that DO have the matching color.
  2133. # If a printer has the right color but is busy, surface "Busy" instead so
  2134. # the user knows the job will start automatically once that printer is free.
  2135. # Same for a printer that is merely offline: Bambuddy switches that one on
  2136. # by itself, so the job is not actually waiting on anybody to change a
  2137. # spool (#2876 — offline printers reach this list now that a switched-off
  2138. # printer's own filament is read).
  2139. if not printers_busy and not printers_offline:
  2140. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  2141. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  2142. # else: fall through — the self-resolving entries are appended below
  2143. else:
  2144. names_and_missing = [
  2145. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  2146. ]
  2147. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  2148. if printers_busy:
  2149. reasons.append(f"Busy: {', '.join(printers_busy)}")
  2150. if printers_offline:
  2151. reasons.append(f"Offline: {', '.join(printers_offline)}")
  2152. if printers_offline_no_plug:
  2153. # Named separately because it is the one entry on this list the
  2154. # user has to act on: no enabled Auto On plug means Bambuddy will
  2155. # never power this printer on for the queue (#2786).
  2156. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  2157. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  2158. @staticmethod
  2159. def _is_busy_only(waiting_reason: str) -> bool:
  2160. """Check if the waiting reason only contains 'Busy' entries.
  2161. When all matching printers are simply busy printing, the queued job
  2162. will start automatically once a printer finishes — no user action
  2163. is required, so we skip the notification.
  2164. """
  2165. parts = [p.strip() for p in waiting_reason.split(" | ")]
  2166. return all(p.startswith("Busy:") for p in parts)
  2167. def _get_missing_force_color_slots(
  2168. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  2169. ) -> list[str]:
  2170. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  2171. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  2172. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  2173. with an exact type+color match.
  2174. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  2175. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  2176. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  2177. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  2178. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  2179. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  2180. setups are unaffected.
  2181. Returns:
  2182. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  2183. """
  2184. if raw_data is None:
  2185. status = printer_manager.get_status(printer_id)
  2186. if not status:
  2187. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  2188. raw_data = status.raw_data
  2189. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  2190. loaded: list[tuple[str, str, str]] = []
  2191. for ams_unit in raw_data.get("ams", []):
  2192. for tray in ams_unit.get("tray", []):
  2193. tray_type = tray.get("tray_type")
  2194. if tray_type:
  2195. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2196. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  2197. for vt in raw_data.get("vt_tray") or []:
  2198. vt_type = vt.get("tray_type")
  2199. if vt_type:
  2200. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2201. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  2202. missing = []
  2203. for o in force_overrides:
  2204. o_type = canonical_filament_type(o.get("type") or "")
  2205. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2206. o_idx = o.get("tray_info_idx") or ""
  2207. satisfied = any(
  2208. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  2209. for t_type, t_color, t_idx in loaded
  2210. )
  2211. if not satisfied:
  2212. color_label = o.get("color_name") or o.get("color", "?")
  2213. missing.append(f"{o_type} ({color_label})")
  2214. return missing
  2215. def _get_missing_filament_types(
  2216. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  2217. ) -> list[str]:
  2218. """Get the list of required filament types that are not loaded on the printer.
  2219. Args:
  2220. printer_id: The printer ID
  2221. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  2222. Returns:
  2223. List of missing filament types (empty if all are loaded)
  2224. """
  2225. if raw_data is None:
  2226. status = printer_manager.get_status(printer_id)
  2227. if not status:
  2228. return required_types # Can't determine, assume all missing
  2229. raw_data = status.raw_data
  2230. # Collect all filament types loaded on this printer (AMS units + external spool)
  2231. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  2232. loaded_types: set[str] = set()
  2233. # Check AMS units (stored in raw_data["ams"])
  2234. ams_data = raw_data.get("ams", [])
  2235. if ams_data:
  2236. for ams_unit in ams_data:
  2237. for tray in ams_unit.get("tray", []):
  2238. tray_type = tray.get("tray_type")
  2239. if tray_type:
  2240. loaded_types.add(canonical_filament_type(tray_type))
  2241. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  2242. for vt in raw_data.get("vt_tray") or []:
  2243. vt_type = vt.get("tray_type")
  2244. if vt_type:
  2245. loaded_types.add(canonical_filament_type(vt_type))
  2246. # Find which required types are missing (using canonical type for equivalence)
  2247. missing = []
  2248. for req_type in required_types:
  2249. if canonical_filament_type(req_type) not in loaded_types:
  2250. missing.append(req_type)
  2251. return missing
  2252. def _count_override_color_matches(
  2253. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  2254. ) -> int:
  2255. """Count how many filament overrides have an exact color match on the printer.
  2256. Used to prefer printers that already have the desired override colors loaded.
  2257. """
  2258. if raw_data is None:
  2259. status = printer_manager.get_status(printer_id)
  2260. if not status:
  2261. return 0
  2262. raw_data = status.raw_data
  2263. # Collect loaded filaments' type+color pairs
  2264. loaded: set[tuple[str, str]] = set()
  2265. for ams_unit in raw_data.get("ams", []):
  2266. for tray in ams_unit.get("tray", []):
  2267. tray_type = tray.get("tray_type")
  2268. # `or ""`, not a dict default: a slot can carry the key with a
  2269. # null value, and this now runs against switched-off printers
  2270. # too, where nobody is watching for the AttributeError.
  2271. tray_color = tray.get("tray_color") or ""
  2272. if tray_type:
  2273. color_norm = tray_color.replace("#", "").lower()[:6]
  2274. loaded.add((tray_type.upper(), color_norm))
  2275. for vt in raw_data.get("vt_tray") or []:
  2276. vt_type = vt.get("tray_type")
  2277. if vt_type:
  2278. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2279. loaded.add((vt_type.upper(), color_norm))
  2280. matches = 0
  2281. for o in overrides:
  2282. o_type = (o.get("type") or "").upper()
  2283. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2284. if (o_type, o_color) in loaded:
  2285. matches += 1
  2286. return matches
  2287. @staticmethod
  2288. def _tray_reading(printer_id: int) -> dict:
  2289. """The best tray reading available for a printer that is not printing.
  2290. Live status first: a printer keeps its last status after the power
  2291. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  2292. leaves ``raw_data`` alone. The manager's own record is the fallback,
  2293. for when the client itself has been dropped and taken its status with
  2294. it — which is what every power-on attempt does.
  2295. An empty result means "we have never heard", not "nothing is loaded":
  2296. the two are indistinguishable from here, and only the second would be
  2297. safe to act on.
  2298. """
  2299. status = printer_manager.get_status(printer_id)
  2300. raw = (status.raw_data if status else None) or {}
  2301. for ams_unit in raw.get("ams") or []:
  2302. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  2303. return raw
  2304. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  2305. return raw
  2306. return printer_manager.last_known_trays(printer_id)
  2307. def _cached_filament_shortfall(
  2308. self,
  2309. printer_id: int,
  2310. required_types: list[str] | None,
  2311. filament_overrides: list[dict] | None,
  2312. ) -> list[str]:
  2313. """What a switched-off printer's last known filament cannot provide (#2876).
  2314. The smart-plug wake step used to consider only the model, so a job for a
  2315. colour loaded on the last printer in ID order switched on every earlier
  2316. one in turn, evaluated it, rejected it on colour and left it running.
  2317. Bambuddy knew those colours the whole time. This asks the same three
  2318. questions the matcher asks a live printer — required types, forced
  2319. colours, preferred colours — of the trays it last reported, and returns
  2320. the answers in the same shape the "Waiting for filament" reason uses.
  2321. Empty means the printer may still be able to take the job.
  2322. Fails open, and deliberately: with no tray reading (never connected
  2323. since Bambuddy started, or the cache dropped by a reconnect) this
  2324. returns nothing to report and the printer is treated as it was before.
  2325. A farm restarted while its printers were off must not conclude that
  2326. none of them can print.
  2327. """
  2328. if not required_types and not filament_overrides:
  2329. return []
  2330. raw_data = self._tray_reading(printer_id)
  2331. if not raw_data:
  2332. return []
  2333. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2334. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2335. if required_types:
  2336. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  2337. if missing:
  2338. # Same enrichment the live path applies: a bare "PLA" is not
  2339. # much help when what is missing is a particular PLA.
  2340. force_color_map = {
  2341. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  2342. }
  2343. return [
  2344. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2345. for t in missing
  2346. ]
  2347. if force_overrides:
  2348. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  2349. if missing_colors:
  2350. return missing_colors
  2351. # Preference overrides read as a preference but the matcher treats zero
  2352. # matches as a skip, so a printer with none of the wanted colours is
  2353. # rejected there too. Waking it would only produce that same rejection.
  2354. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  2355. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  2356. return []
  2357. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  2358. """Fold the winning candidate's file and settings onto the queue row (#671).
  2359. This is the whole trick that keeps cross-model items cheap: the many-to-many
  2360. never escapes the selection loop. By the time the pass commits, the row
  2361. looks exactly like an ordinary single-file model-based item, so the upload,
  2362. archive creation, expected-print registration, print history and reprint
  2363. paths need no knowledge that variants exist.
  2364. No-ops for a non-variant candidate, which is already the item's own columns.
  2365. Safe to run and re-run: the item's file columns are only ever *read* when it
  2366. has no variants, so an item that gets resolved and then skipped (library-row
  2367. conflict, previous-print gate) is simply resolved again on the next pass.
  2368. """
  2369. variant = candidate.variant
  2370. if variant is None:
  2371. return
  2372. item.library_file_id = variant.library_file_id
  2373. item.library_file = variant.library_file
  2374. # The dispatcher checks archive_id first and would print that instead of
  2375. # the file we just picked. Creation refuses to combine the two, so this
  2376. # only ever fires on a hand-written row — clear it rather than silently
  2377. # dispatch something the matcher never considered.
  2378. item.archive_id = None
  2379. item.archive = None
  2380. item.target_model = variant.target_model
  2381. item.plate_id = variant.plate_id
  2382. item.ams_mapping = variant.ams_mapping
  2383. item.nozzle_mapping = variant.nozzle_mapping
  2384. item.nozzle_rack_choice = variant.nozzle_rack_choice
  2385. item.filament_overrides = variant.filament_overrides
  2386. item.required_filament_types = variant.required_filament_types
  2387. if variant.print_time_seconds is not None:
  2388. # The row carried the shortest candidate's estimate so SJF could order
  2389. # it before a printer was known; now that one is chosen, record what is
  2390. # actually going to run so history and the ETA agree with reality.
  2391. item.print_time_seconds = variant.print_time_seconds
  2392. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  2393. """Ensure the queue item carries a usable AMS mapping before dispatch.
  2394. Recomputes from live printer status when the stored mapping is missing OR
  2395. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  2396. frontend status-load race can serialize [-1] before the printer's AMS
  2397. trays are known (#2589) — and must not be trusted: downstream it would be
  2398. silently downgraded to external-spool mode and print against an empty
  2399. feed. A resolved mapping (including manual overrides, or a partially
  2400. padded one) is left untouched.
  2401. When recompute cannot resolve it either (no compatible tray loaded), the
  2402. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  2403. external selection; the print command then keeps use_ams=True and the
  2404. firmware surfaces a clear AMS-mapping error instead of silently printing
  2405. to the empty external feed.
  2406. Returns an actionable message when that firmware error is the only
  2407. possible outcome — the matcher ran, matched nothing, and the printer has
  2408. no AMS to load a different spool into (#2771). The caller fails the item
  2409. on it instead of spending an upload on a print that cannot start.
  2410. Returns None everywhere else, including every case where we simply lack
  2411. the data to judge, so dispatch is only ever blocked on a positive
  2412. finding.
  2413. """
  2414. stored_mapping: list | None = None
  2415. if item.ams_mapping:
  2416. try:
  2417. stored_mapping = json.loads(item.ams_mapping)
  2418. except (json.JSONDecodeError, TypeError):
  2419. stored_mapping = None
  2420. # Already resolved (present and not all-unresolved) — keep as-is so a
  2421. # user's manual mapping is never overwritten.
  2422. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  2423. return None
  2424. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  2425. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  2426. item.ams_mapping = json.dumps(computed_mapping)
  2427. logger.info(
  2428. "Queue item %s: Computed AMS mapping for printer %s: %s",
  2429. item.id,
  2430. printer_id,
  2431. computed_mapping,
  2432. )
  2433. await db.commit()
  2434. return None
  2435. if _mapping_is_all_unresolved(stored_mapping):
  2436. logger.warning(
  2437. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  2438. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  2439. item.id,
  2440. stored_mapping,
  2441. printer_id,
  2442. )
  2443. item.ams_mapping = None
  2444. await db.commit()
  2445. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  2446. async def _unmappable_without_ams_message(
  2447. self,
  2448. db: AsyncSession,
  2449. printer_id: int,
  2450. item: PrintQueueItem,
  2451. computed_mapping: list[int] | None,
  2452. ) -> str | None:
  2453. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  2454. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  2455. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  2456. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  2457. uploaded several megabytes and burned its dispatch retries. With an AMS
  2458. attached that error is worth reaching: the user can load the right spool
  2459. and press Resume, so this returns None and today's behaviour stands. With
  2460. no AMS there is nothing to resume into — the external spool holder is the
  2461. whole inventory — so the useful answer is to say which filament is
  2462. missing and stop.
  2463. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  2464. every branch that lacks the evidence to be sure returns None.
  2465. """
  2466. # None means the matcher never ran (no requirements parsed from the 3MF,
  2467. # or nothing loaded at all) rather than "ran and matched nothing". Those
  2468. # dispatch as they always have.
  2469. if not _mapping_is_all_unresolved(computed_mapping):
  2470. return None
  2471. status = printer_manager.get_status(printer_id)
  2472. if status is None:
  2473. return None
  2474. # "No AMS" has to be a fact the printer stated, not the absence of a
  2475. # statement. `raw_data["ams"]` is written only once an AMS push has been
  2476. # handled and is preserved across partial pushes thereafter, so a missing
  2477. # key means we have not heard yet — most likely a reconnect, where the
  2478. # trays of a fully loaded AMS would be invisible for a few seconds. An
  2479. # empty list is the positive report of a printer with no AMS.
  2480. ams_units = status.raw_data.get("ams")
  2481. if not isinstance(ams_units, list) or ams_units:
  2482. return None
  2483. required = await self._get_filament_requirements(db, item)
  2484. loaded = self._build_loaded_filaments(status)
  2485. if not required or not loaded:
  2486. # Both were non-empty moments ago or the matcher could not have run.
  2487. # If the picture changed under us, say nothing rather than fail an
  2488. # item on stale evidence.
  2489. return None
  2490. self._apply_filament_overrides(item, required)
  2491. return _unmatched_filament_message(required, loaded)
  2492. async def _fail_unmappable_item(
  2493. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  2494. ) -> None:
  2495. """Fail a queue item whose filament mapping cannot resolve (#2771).
  2496. This replaces a failure, not a success: without it the item is uploaded,
  2497. rejected by the firmware with 0700_8012, retried twice more and failed
  2498. anyway with "never started the print after N dispatch attempts". So this
  2499. applies on the model-based path too, even though it means an "Any <model>"
  2500. job stops at the first printer offered rather than trying its siblings —
  2501. deferring instead would need the check to move inside
  2502. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  2503. re-assigns the same printer on the next tick.
  2504. """
  2505. item.status = "failed"
  2506. item.error_message = message
  2507. item.completed_at = datetime.now(timezone.utc)
  2508. item.waiting_reason = None
  2509. await db.commit()
  2510. logger.warning(
  2511. "Queue item %s: no usable AMS mapping on printer %s — %s",
  2512. item.id,
  2513. printer_id,
  2514. message,
  2515. )
  2516. job_name = await self._get_job_name(db, item)
  2517. printer = await self._get_printer(db, printer_id)
  2518. await notification_service.on_queue_job_failed(
  2519. job_name=job_name,
  2520. printer_id=printer_id,
  2521. printer_name=printer.name if printer else "Unknown",
  2522. reason=message,
  2523. db=db,
  2524. )
  2525. try:
  2526. await ws_manager.send_queue_item_failed(
  2527. user_id=item.created_by_id,
  2528. queue_item_id=item.id,
  2529. printer_id=printer_id,
  2530. reason="filament_unmappable",
  2531. )
  2532. except Exception:
  2533. pass
  2534. async def _compute_ams_mapping_for_printer(
  2535. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  2536. ) -> list[int] | None:
  2537. """Compute AMS mapping for a printer based on filament requirements.
  2538. Called when a queue item has no ams_mapping set — either for model-based
  2539. items after printer assignment, or printer-specific items (e.g. from VP).
  2540. Args:
  2541. db: Database session
  2542. printer_id: The assigned printer ID
  2543. item: The queue item (contains archive_id or library_file_id)
  2544. Returns:
  2545. AMS mapping array or None if no mapping needed/possible
  2546. """
  2547. # Get printer status
  2548. status = printer_manager.get_status(printer_id)
  2549. if not status:
  2550. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  2551. return None
  2552. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  2553. # either extruder, so the per-nozzle hard filter below must NOT apply.
  2554. # Otherwise a print on one nozzle can't use a spool physically loaded in
  2555. # an AMS on the *other* nozzle, and the matcher falls through to a
  2556. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  2557. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  2558. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  2559. # Get filament requirements from source file
  2560. filament_reqs = await self._get_filament_requirements(db, item)
  2561. if not filament_reqs:
  2562. # When the 3MF can't be read but force-color overrides are present, build a
  2563. # direct mapping from the overrides so the printer uses the correct AMS slot.
  2564. if item.filament_overrides:
  2565. try:
  2566. overrides = json.loads(item.filament_overrides)
  2567. force_overrides = [o for o in overrides if o.get("force_color_match")]
  2568. if force_overrides:
  2569. logger.info(
  2570. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  2571. "force-color override(s)",
  2572. item.id,
  2573. len(force_overrides),
  2574. )
  2575. return self._build_override_direct_mapping(force_overrides, status)
  2576. except (json.JSONDecodeError, KeyError, TypeError) as e:
  2577. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  2578. logger.debug("No filament requirements found for queue item %s", item.id)
  2579. return None
  2580. self._apply_filament_overrides(item, filament_reqs)
  2581. # Build loaded filaments from printer status
  2582. loaded_filaments = self._build_loaded_filaments(status)
  2583. if not loaded_filaments:
  2584. logger.debug("No filaments loaded on printer %s", printer_id)
  2585. return None
  2586. # Check if user prefers lowest remaining filament when multiple spools match
  2587. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  2588. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  2589. # Without backup, the printer will not switch to a second spool when the
  2590. # picked one runs out — so sorting toward the lowest leaves the print
  2591. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  2592. # today's behaviour intentionally.
  2593. if prefer_lowest and status.ams_filament_backup is False:
  2594. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  2595. prefer_lowest = False
  2596. # When the preference is on, surface Bambuddy's inventory-side
  2597. # remaining for each slot that's bound to a tracked spool, so the
  2598. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  2599. # entirely when the preference is off — no behaviour change for
  2600. # users who haven't opted in.
  2601. inventory_remain_overrides: dict[int, float] | None = None
  2602. if prefer_lowest:
  2603. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  2604. # Compute mapping: match required filaments to available slots
  2605. return self._match_filaments_to_slots(
  2606. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  2607. )
  2608. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  2609. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  2610. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  2611. diagnosis (#2771) describes the filament the matcher actually looked
  2612. for, not the one the 3MF was sliced with — naming the pre-override
  2613. filament in a user-facing error would send the user to load the wrong
  2614. spool.
  2615. """
  2616. if not item.filament_overrides:
  2617. return
  2618. try:
  2619. overrides = json.loads(item.filament_overrides)
  2620. override_map = {o["slot_id"]: o for o in overrides}
  2621. for req in filament_reqs:
  2622. if req["slot_id"] in override_map:
  2623. override = override_map[req["slot_id"]]
  2624. req["type"] = override["type"]
  2625. req["color"] = override["color"]
  2626. # A manual/preference override SWAPS the slot's filament, so the
  2627. # 3MF's original tray_info_idx now points at the old spool and must
  2628. # be cleared — matching then falls back to type+colour. A
  2629. # force_color_match override is not a swap: it carries the 3MF's
  2630. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  2631. # it here too, letting the matcher pin the correct variant slot on a
  2632. # printer holding two same-colour spools of different variants (#2650).
  2633. # If that variant isn't loaded the matcher falls back to type+colour,
  2634. # so an eligible printer never fails to map.
  2635. req["tray_info_idx"] = (
  2636. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  2637. )
  2638. logger.debug(
  2639. "Queue item %s: Override slot %d -> %s %s",
  2640. item.id,
  2641. req["slot_id"],
  2642. override["type"],
  2643. override["color"],
  2644. )
  2645. except (json.JSONDecodeError, KeyError, TypeError) as e:
  2646. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  2647. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  2648. """Build an AMS mapping directly from force-color overrides without a 3MF.
  2649. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  2650. slice_info is missing or unreadable) but ``force_color_match`` overrides
  2651. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  2652. treated as the filament requirement for that slot and matched against the
  2653. current AMS state of the printer.
  2654. Returns the same format as ``_match_filaments_to_slots``, or None when
  2655. the AMS has no loaded filaments.
  2656. """
  2657. loaded = self._build_loaded_filaments(status)
  2658. if not loaded:
  2659. return None
  2660. reqs = [
  2661. {
  2662. "slot_id": o["slot_id"],
  2663. "type": o.get("type", ""),
  2664. "color": o.get("color", ""),
  2665. # These are all force_color_match overrides, so the idx (when the
  2666. # 3MF carried one) is the intended variant, not a stale swap —
  2667. # keep it so the matcher pins the right variant slot, falling back
  2668. # to type+colour when it isn't loaded (#2650).
  2669. "tray_info_idx": o.get("tray_info_idx", ""),
  2670. }
  2671. for o in force_overrides
  2672. ]
  2673. return self._match_filaments_to_slots(reqs, loaded)
  2674. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  2675. """Resolve the queue item's source 3MF and parse the per-slot
  2676. filament requirements out of it. Thin DB-resolver wrapper around
  2677. ``filament_requirements.extract_filament_requirements`` so the VP
  2678. queue-mode write path (#1188) can reuse the same parser at upload
  2679. time.
  2680. """
  2681. from backend.app.services.filament_requirements import extract_filament_requirements
  2682. file_path: Path | None = None
  2683. if item.archive_id:
  2684. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2685. archive = result.scalar_one_or_none()
  2686. if archive:
  2687. file_path = settings.base_dir / archive.file_path
  2688. elif item.library_file_id:
  2689. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2690. library_file = result.scalar_one_or_none()
  2691. if library_file:
  2692. lib_path = Path(library_file.file_path)
  2693. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  2694. if not file_path or not file_path.exists():
  2695. return None
  2696. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  2697. return filaments if filaments else None
  2698. def _build_loaded_filaments(self, status) -> list[dict]:
  2699. """Build list of loaded filaments from printer status.
  2700. Args:
  2701. status: PrinterState from printer_manager
  2702. Returns:
  2703. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  2704. """
  2705. filaments = []
  2706. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  2707. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  2708. # Dual-nozzle detection, used below to route external spools to an
  2709. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  2710. # which was corrected for #1257 while this copy kept the old signal.
  2711. #
  2712. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  2713. # printer with zero AMS units reports an empty map — and every external
  2714. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  2715. # `_match_filaments_to_slots` rejects outright because `None` equals
  2716. # neither 0 nor 1. On an X2D feeding from external spools only that left
  2717. # nothing to match, the mapping came back all -1, and the print went out
  2718. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  2719. # "Failed to get AMS mapping table".
  2720. #
  2721. # `nozzles` is always a two-entry list (the state seeds it with two empty
  2722. # NozzleInfo stubs), so its length proves nothing; only a populated
  2723. # diameter on the second entry means real hardware. The other two signals
  2724. # are fallbacks for firmware revisions that surface one but not the
  2725. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  2726. # and so is more than one `vt_tray` entry, since single-nozzle printers
  2727. # expose exactly one external feed.
  2728. nozzles = getattr(status, "nozzles", None) or []
  2729. vt_trays = status.raw_data.get("vt_tray") or []
  2730. is_dual_nozzle = bool(
  2731. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  2732. or ams_extruder_map
  2733. # isinstance, because a dict here would count its ~30 keys as trays.
  2734. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  2735. # so this is unreachable — but the loop below would raise on a dict
  2736. # and that is the pre-existing behaviour to keep, not to paper over.
  2737. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  2738. )
  2739. # Parse AMS units from raw_data
  2740. ams_data = status.raw_data.get("ams", [])
  2741. for ams_unit in ams_data:
  2742. ams_id = int(ams_unit.get("id", 0))
  2743. trays = ams_unit.get("tray", [])
  2744. is_ht = len(trays) == 1 # AMS-HT has single tray
  2745. for tray in trays:
  2746. tray_type = tray.get("tray_type")
  2747. if tray_type:
  2748. tray_id = int(tray.get("id", 0))
  2749. tray_color = tray.get("tray_color", "")
  2750. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  2751. tray_info_idx = tray.get("tray_info_idx", "")
  2752. # Normalize color: remove alpha, add hash
  2753. color = self._normalize_color(tray_color)
  2754. # Calculate global tray ID
  2755. # AMS-HT units have IDs starting at 128 with a single tray
  2756. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  2757. filaments.append(
  2758. {
  2759. "type": tray_type,
  2760. "color": color,
  2761. "tray_info_idx": tray_info_idx,
  2762. "ams_id": ams_id,
  2763. "tray_id": tray_id,
  2764. "is_ht": is_ht,
  2765. "is_external": False,
  2766. "global_tray_id": global_tray_id,
  2767. "extruder_id": ams_extruder_map.get(str(ams_id)),
  2768. "remain": tray.get("remain", -1),
  2769. }
  2770. )
  2771. # Check external spool(s) (vt_tray is a list)
  2772. for idx, vt in enumerate(vt_trays):
  2773. if vt.get("tray_type"):
  2774. color = self._normalize_color(vt.get("tray_color", ""))
  2775. tray_id = int(vt.get("id", 254))
  2776. filaments.append(
  2777. {
  2778. "type": vt["tray_type"],
  2779. "color": color,
  2780. "tray_info_idx": vt.get("tray_info_idx", ""),
  2781. "ams_id": -1,
  2782. "tray_id": idx,
  2783. "is_ht": False,
  2784. "is_external": True,
  2785. "global_tray_id": tray_id,
  2786. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  2787. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  2788. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  2789. "remain": vt.get("remain", -1),
  2790. }
  2791. )
  2792. return filaments
  2793. def _normalize_color(self, color: str | None) -> str:
  2794. """Normalize color to #RRGGBB format."""
  2795. if not color:
  2796. return "#808080"
  2797. hex_color = color.replace("#", "")[:6]
  2798. return f"#{hex_color}"
  2799. def _normalize_color_for_compare(self, color: str | None) -> str:
  2800. """Normalize color for comparison (lowercase, no hash)."""
  2801. if not color:
  2802. return ""
  2803. return color.replace("#", "").lower()[:6]
  2804. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  2805. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  2806. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  2807. stays the per-channel box that shipped — this only decides which of
  2808. several eligible spools is closest, so nothing becomes usable or
  2809. unusable because of it.
  2810. It ranks by how far apart the colours *look*, not how far apart their
  2811. numbers are. RGB distance overweights blue badly enough to invert the
  2812. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  2813. the nearer of two eligible spools by RGB and the further by a factor of
  2814. four once measured perceptually.
  2815. Alpha is ignored, deliberately: the alpha a slicer writes for a
  2816. transparent filament is not a colour the user chose, and counting it
  2817. would stop a transparent filament matching itself.
  2818. """
  2819. return perceptual_color_distance(color1, color2)
  2820. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  2821. """Check if two colors are visually similar within a threshold."""
  2822. hex1 = self._normalize_color_for_compare(color1)
  2823. hex2 = self._normalize_color_for_compare(color2)
  2824. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  2825. return False
  2826. try:
  2827. r1 = int(hex1[0:2], 16)
  2828. g1 = int(hex1[2:4], 16)
  2829. b1 = int(hex1[4:6], 16)
  2830. r2 = int(hex2[0:2], 16)
  2831. g2 = int(hex2[2:4], 16)
  2832. b2 = int(hex2[4:6], 16)
  2833. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  2834. except ValueError:
  2835. return False
  2836. async def _build_inventory_remain_overrides(
  2837. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  2838. ) -> dict[int, float]:
  2839. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  2840. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  2841. The MQTT ``remain`` field on a tray is the printer firmware's
  2842. RFID-decremented value, which has two limitations the "Prefer Lowest
  2843. Remaining Filament" feature has been ignoring (#1508):
  2844. - it's only meaningful for Bambu RFID spools; everything else reports
  2845. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  2846. compare equal and the sort collapses to AMS-slot order — the user
  2847. who's curating inventory weights gets the lower-slot pick instead
  2848. of the lower-remaining pick;
  2849. - even when set, it's the *printer's* counter, not Bambuddy's
  2850. ``label_weight - weight_used`` (internal mode) or Spoolman's
  2851. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  2852. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  2853. When the user has bound a spool to a slot, their own inventory
  2854. tracking is authoritative; this helper surfaces that value so the
  2855. sort can prefer it. Slots without a binding are absent from the
  2856. returned map — the caller then falls back to MQTT ``remain`` for
  2857. those, preserving the pre-#1508 behaviour for un-tracked spools.
  2858. Returns an empty map on any failure (no inventory bindings, DB
  2859. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  2860. is a preference, not a guarantee.
  2861. """
  2862. if not loaded:
  2863. return {}
  2864. # External / virtual-tray slots are tracked separately from AMS — skip
  2865. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  2866. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  2867. # match is fiddly and out of scope for this fix).
  2868. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  2869. if not tracked_slots:
  2870. return {}
  2871. is_spoolman = await self._is_spoolman_mode(db)
  2872. overrides: dict[int, float] = {}
  2873. if is_spoolman:
  2874. result = await db.execute(
  2875. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2876. )
  2877. assignments = list(result.scalars().all())
  2878. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  2879. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  2880. for ams_id, tray_id, gtid in tracked_slots:
  2881. spoolman_id = by_slot.get((ams_id, tray_id))
  2882. if spoolman_id is None:
  2883. continue
  2884. grams = await _spoolman_remaining_grams(spoolman_id)
  2885. if grams is not None:
  2886. overrides[gtid] = grams
  2887. return overrides
  2888. # Internal inventory mode (default). selectinload matches the pattern
  2889. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  2890. # plus an eager-loaded relationship rather than an explicit join, so
  2891. # the row-attribute shape is exactly what those routes already rely on.
  2892. result = await db.execute(
  2893. select(SpoolAssignment)
  2894. .options(selectinload(SpoolAssignment.spool))
  2895. .where(SpoolAssignment.printer_id == printer_id)
  2896. )
  2897. assignments = list(result.scalars().all())
  2898. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  2899. for ams_id, tray_id, gtid in tracked_slots:
  2900. spool = by_slot.get((ams_id, tray_id))
  2901. if spool is None:
  2902. continue
  2903. label = float(spool.label_weight or 0)
  2904. used = float(spool.weight_used or 0)
  2905. overrides[gtid] = max(0.0, label - used)
  2906. return overrides
  2907. @staticmethod
  2908. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  2909. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  2910. here to avoid making this module import-dependent on that private
  2911. helper's signature."""
  2912. try:
  2913. from backend.app.api.routes.settings import get_setting
  2914. v = await get_setting(db, "spoolman_enabled")
  2915. return bool(v) and v.lower() == "true"
  2916. except Exception:
  2917. return False
  2918. @staticmethod
  2919. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  2920. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  2921. Three bands, matched to the emission order in ``_build_loaded_filaments``
  2922. so a tied sort produces the same physical-position order the pre-#1508
  2923. stable sort did (preserves the regression-free baseline):
  2924. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  2925. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  2926. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  2927. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  2928. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  2929. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  2930. """
  2931. if ams_id is None or ams_id < 0:
  2932. return 10_000
  2933. if ams_id >= 128:
  2934. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  2935. return ams_id * 4 + (tray_id or 0)
  2936. @staticmethod
  2937. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  2938. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  2939. Two-tier ordering: inventory-tracked spools always sort BEFORE
  2940. non-tracked spools (the user has told us they care about these
  2941. specifically), then ascending by remaining within each tier, then
  2942. ascending by AMS slot position as the deterministic tie-breaker.
  2943. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  2944. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  2945. because the tier flag dominates — which is what lets us mix grams
  2946. (inventory) and percent (MQTT) without a unit conversion.
  2947. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  2948. spools the printer DOES know something about sort ahead of those
  2949. it knows nothing about — preserves pre-#1508 behaviour for the
  2950. no-inventory-binding case.
  2951. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  2952. external on ties, matching the legacy emission-order stable sort.
  2953. """
  2954. gtid = f.get("global_tray_id")
  2955. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  2956. if overrides and gtid in overrides:
  2957. return (0, overrides[gtid], slot_order)
  2958. remain = f.get("remain", -1)
  2959. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  2960. def _match_filaments_to_slots(
  2961. self,
  2962. required: list[dict],
  2963. loaded: list[dict],
  2964. prefer_lowest: bool = False,
  2965. inventory_remain_overrides: dict[int, float] | None = None,
  2966. fts_installed: bool = False,
  2967. ) -> list[int] | None:
  2968. """Match required filaments to loaded filaments and build AMS mapping.
  2969. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  2970. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  2971. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  2972. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  2973. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  2974. matching among those trays.
  2975. Args:
  2976. required: List of required filaments with slot_id, type, color, tray_info_idx
  2977. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  2978. Returns:
  2979. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  2980. """
  2981. if not required:
  2982. return None
  2983. # Track used trays to avoid duplicate assignment
  2984. used_tray_ids: set[int] = set()
  2985. comparisons = []
  2986. for req in required:
  2987. req_type = (req.get("type") or "").upper()
  2988. req_color = req.get("color", "")
  2989. req_tray_info_idx = req.get("tray_info_idx", "")
  2990. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  2991. idx_match = None
  2992. exact_match = None
  2993. similar_match = None
  2994. similar_distance = float("inf")
  2995. type_only_match = None
  2996. # Get available trays (not already used)
  2997. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  2998. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  2999. # Hard filter — cross-nozzle assignment causes print failures
  3000. # ("position of left hotend is abnormal"), so never fall back.
  3001. # Skipped when an FTS is installed: it routes any AMS slot to either
  3002. # extruder, so restricting to one nozzle would wrongly exclude the
  3003. # correct spool sitting in the other nozzle's AMS (#2186).
  3004. req_nozzle_id = req.get("nozzle_id")
  3005. if req_nozzle_id is not None and not fts_installed:
  3006. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  3007. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  3008. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  3009. # _prefer_lowest_sort_key for the full rationale.
  3010. if prefer_lowest:
  3011. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  3012. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  3013. # One line per filament req so a bug report can be diagnosed
  3014. # without enabling debug logging: shows what the matcher saw
  3015. # (req shape + sorted candidate trays with their remain values
  3016. # and any inventory override that was applied). Mirrored by
  3017. # the picked-match log at the bottom of the loop.
  3018. logger.info(
  3019. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  3020. req.get("slot_id"),
  3021. req_type,
  3022. req_color,
  3023. req_tray_info_idx,
  3024. req_nozzle_id,
  3025. [
  3026. {
  3027. "gtid": f.get("global_tray_id"),
  3028. "type": f.get("type"),
  3029. "color": f.get("color"),
  3030. "tii": f.get("tray_info_idx"),
  3031. "remain": f.get("remain"),
  3032. "inv_g": (
  3033. inventory_remain_overrides.get(f.get("global_tray_id"))
  3034. if inventory_remain_overrides
  3035. else None
  3036. ),
  3037. }
  3038. for f in available
  3039. ],
  3040. )
  3041. # Check if tray_info_idx is unique among available trays
  3042. if req_tray_info_idx:
  3043. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  3044. if len(idx_matches) == 1:
  3045. # Unique tray_info_idx - use it as definitive match
  3046. idx_match = idx_matches[0]
  3047. logger.debug(
  3048. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  3049. f"-> tray {idx_match['global_tray_id']}"
  3050. )
  3051. elif len(idx_matches) > 1:
  3052. # Multiple trays with same tray_info_idx - use color matching among them
  3053. logger.debug(
  3054. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  3055. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  3056. )
  3057. if prefer_lowest:
  3058. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  3059. # Use color matching within this subset
  3060. for f in idx_matches:
  3061. f_color = f.get("color", "")
  3062. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  3063. if not exact_match:
  3064. exact_match = f
  3065. elif self._colors_are_similar(f_color, req_color):
  3066. distance = self._color_distance(f_color, req_color)
  3067. if distance is not None and distance < similar_distance:
  3068. similar_match = f
  3069. similar_distance = distance
  3070. elif not type_only_match:
  3071. type_only_match = f
  3072. # If no idx_match yet, do standard type/color matching on all available trays
  3073. if not idx_match and not exact_match and not similar_match and not type_only_match:
  3074. for f in available:
  3075. f_type = (f.get("type") or "").upper()
  3076. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  3077. continue
  3078. # Type matches - check color
  3079. f_color = f.get("color", "")
  3080. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  3081. if not exact_match:
  3082. exact_match = f
  3083. elif self._colors_are_similar(f_color, req_color):
  3084. # Nearest wins, not first-in-tray-order. `available` is
  3085. # already in the caller's order (slot order, or the
  3086. # prefer-lowest sort), and `<` keeps the earliest of
  3087. # equally close spools — so that order survives as the
  3088. # tie-break (#2804).
  3089. distance = self._color_distance(f_color, req_color)
  3090. if distance is not None and distance < similar_distance:
  3091. similar_match = f
  3092. similar_distance = distance
  3093. elif not type_only_match:
  3094. type_only_match = f
  3095. match = idx_match or exact_match or similar_match or type_only_match
  3096. if match:
  3097. used_tray_ids.add(match["global_tray_id"])
  3098. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  3099. else:
  3100. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  3101. # Which bucket won, always — not only under Prefer Lowest (#2804).
  3102. # "Why did it pick that spool" is the question every wrong-filament
  3103. # report starts with, and a `similar_color` win is now a ranked
  3104. # choice among several eligible spools rather than whichever tray
  3105. # came first, so it is worth being able to see after the fact.
  3106. # Pairs with the "available (sorted)" log above when Prefer Lowest
  3107. # is on (#1766).
  3108. if match:
  3109. bucket = (
  3110. "idx"
  3111. if idx_match is not None
  3112. else "exact_color"
  3113. if exact_match is not None
  3114. else "similar_color"
  3115. if similar_match is not None
  3116. else "type_only"
  3117. )
  3118. logger.info(
  3119. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  3120. match["global_tray_id"],
  3121. bucket,
  3122. req.get("slot_id"),
  3123. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  3124. )
  3125. else:
  3126. logger.info(
  3127. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  3128. req.get("slot_id"),
  3129. req_type,
  3130. req_color,
  3131. req_tray_info_idx,
  3132. )
  3133. # Build mapping array
  3134. if not comparisons:
  3135. return None
  3136. max_slot_id = max(c["slot_id"] for c in comparisons)
  3137. if max_slot_id <= 0:
  3138. return None
  3139. mapping = [-1] * max_slot_id
  3140. for c in comparisons:
  3141. slot_id = c["slot_id"]
  3142. if slot_id and slot_id > 0:
  3143. mapping[slot_id - 1] = c["global_tray_id"]
  3144. return mapping
  3145. def _mark_printer_dispatched(
  3146. self,
  3147. printer_id: int,
  3148. pre_state: str | None,
  3149. pre_subtask_id: str | None,
  3150. ) -> None:
  3151. """Record that a print command was just sent to ``printer_id``.
  3152. Held until either the watchdog observes a state/subtask transition
  3153. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  3154. """
  3155. if not pre_state:
  3156. # No pre_state means we can't detect a transition — fall back to a
  3157. # pure time-based hold using empty string as a sentinel that won't
  3158. # match any real printer state.
  3159. pre_state = ""
  3160. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  3161. def _release_dispatch_hold(self, printer_id: int) -> None:
  3162. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  3163. self._dispatch_holds.pop(printer_id, None)
  3164. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  3165. """True if ``printer_id`` is still inside its post-dispatch hold window.
  3166. Returns False (and clears the hold) once any of these are true:
  3167. - hard timeout (``_dispatch_max_hold``) has elapsed
  3168. - the printer has transitioned out of pre_state and we're past the
  3169. minimum cooldown
  3170. - the printer's subtask_id has advanced past pre_subtask_id and we're
  3171. past the minimum cooldown
  3172. Otherwise the printer is held — caller should treat it as busy.
  3173. """
  3174. entry = self._dispatch_holds.get(printer_id)
  3175. if not entry:
  3176. return False
  3177. started_at, pre_state, pre_subtask_id = entry
  3178. elapsed = time.monotonic() - started_at
  3179. if elapsed >= self._dispatch_max_hold:
  3180. self._dispatch_holds.pop(printer_id, None)
  3181. return False
  3182. # Without a pre_state we can't detect a transition — fall back to the
  3183. # min cooldown alone, then drop the hold.
  3184. if not pre_state:
  3185. if elapsed >= self._dispatch_min_cooldown:
  3186. self._dispatch_holds.pop(printer_id, None)
  3187. return False
  3188. return True
  3189. status = printer_manager.get_status(printer_id)
  3190. current_state = getattr(status, "state", None) if status else None
  3191. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  3192. transitioned = (current_state is not None and current_state != pre_state) or (
  3193. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  3194. )
  3195. if transitioned and elapsed >= self._dispatch_min_cooldown:
  3196. self._dispatch_holds.pop(printer_id, None)
  3197. return False
  3198. return True
  3199. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  3200. """Check if a printer is connected and idle."""
  3201. if not printer_manager.is_connected(printer_id):
  3202. logger.debug("Printer %d: not connected", printer_id)
  3203. return False
  3204. state = printer_manager.get_status(printer_id)
  3205. if not state:
  3206. logger.debug("Printer %d: no status available", printer_id)
  3207. return False
  3208. # Plate-clear gate: if the printer finished/failed a previous print and the user
  3209. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  3210. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  3211. # printer, it boots back into IDLE with no memory of the previous finish; without
  3212. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  3213. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  3214. logger.debug(
  3215. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  3216. printer_id,
  3217. state.state,
  3218. )
  3219. return False
  3220. idle = state.state in ("IDLE", "FINISH", "FAILED")
  3221. if not idle:
  3222. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  3223. return idle
  3224. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  3225. """Read a setting value from the database."""
  3226. result = await db.execute(select(Settings).where(Settings.key == key))
  3227. setting = result.scalar_one_or_none()
  3228. return setting.value if setting else None
  3229. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  3230. """Read a boolean setting from the database."""
  3231. result = await db.execute(select(Settings).where(Settings.key == key))
  3232. setting = result.scalar_one_or_none()
  3233. if setting:
  3234. return setting.value.lower() == "true"
  3235. return default
  3236. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  3237. """Read an int setting; falls back to default on missing/unparseable rows."""
  3238. result = await db.execute(select(Settings).where(Settings.key == key))
  3239. setting = result.scalar_one_or_none()
  3240. if setting and setting.value:
  3241. try:
  3242. return int(setting.value)
  3243. except ValueError:
  3244. pass
  3245. return default
  3246. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  3247. """Get drying presets (user-configured or built-in defaults)."""
  3248. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  3249. setting = result.scalar_one_or_none()
  3250. if setting and setting.value:
  3251. try:
  3252. presets = json.loads(setting.value)
  3253. if isinstance(presets, dict) and presets:
  3254. return presets
  3255. except json.JSONDecodeError:
  3256. pass
  3257. return self.DEFAULT_DRYING_PRESETS
  3258. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  3259. """Per-filament humidity thresholds (#1605).
  3260. Returns the user-configured overrides map keyed by normalized filament
  3261. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  3262. unknown / unmapped types. Empty / unset → empty dict, in which case
  3263. callers fall back to ``ams_humidity_fair``.
  3264. """
  3265. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  3266. setting = result.scalar_one_or_none()
  3267. if not setting or not setting.value:
  3268. return {}
  3269. try:
  3270. data = json.loads(setting.value)
  3271. except json.JSONDecodeError:
  3272. return {}
  3273. if not isinstance(data, dict):
  3274. return {}
  3275. out: dict[str, int] = {}
  3276. for key, value in data.items():
  3277. try:
  3278. out[str(key).upper() if key != "default" else "default"] = int(value)
  3279. except (TypeError, ValueError):
  3280. continue
  3281. return out
  3282. @staticmethod
  3283. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  3284. """Resolve the effective humidity threshold for an AMS unit (#1605).
  3285. For mixed filament types loaded into one AMS, returns the most
  3286. restrictive (lowest) threshold across all loaded tray types — matches
  3287. the conservative-params strategy already used for drying temp/hours.
  3288. Empty / unloaded trays contribute no constraint. Unknown types use the
  3289. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  3290. when no per-type map is configured at all.
  3291. """
  3292. default = thresholds.get("default", fallback)
  3293. if not thresholds:
  3294. return fallback
  3295. candidates: list[int] = []
  3296. for tray in trays:
  3297. tray_type = str(tray.get("tray_type") or "").strip()
  3298. if not tray_type:
  3299. continue
  3300. base_type = tray_type.split()[0].upper()
  3301. candidates.append(thresholds.get(base_type, default))
  3302. if not candidates:
  3303. return default
  3304. return min(candidates)
  3305. def _get_conservative_drying_params(
  3306. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  3307. ) -> tuple[int, int, str] | None:
  3308. """Get the most conservative drying params for mixed filament types in an AMS unit.
  3309. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  3310. """
  3311. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  3312. hours_key = f"{temp_key}_hours"
  3313. min_temp = None
  3314. max_hours = None
  3315. filament_type = ""
  3316. for tray in trays:
  3317. tray_type = tray.get("tray_type", "")
  3318. if not tray_type:
  3319. continue
  3320. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  3321. base_type = tray_type.split()[0].upper()
  3322. preset = presets.get(base_type)
  3323. if not preset:
  3324. continue
  3325. temp = preset.get(temp_key, 55)
  3326. hours = preset.get(hours_key, 12)
  3327. # Conservative: lowest temp, longest duration
  3328. if min_temp is None or temp < min_temp:
  3329. min_temp = temp
  3330. if max_hours is None or hours > max_hours:
  3331. max_hours = hours
  3332. if not filament_type:
  3333. filament_type = base_type
  3334. if min_temp is None:
  3335. return None
  3336. return (min_temp, max_hours or 12, filament_type)
  3337. async def _check_auto_drying(
  3338. self,
  3339. db: AsyncSession,
  3340. queue_items: list[PrintQueueItem],
  3341. dispatching_printers: set[int],
  3342. ):
  3343. """Start drying on idle printers based on humidity.
  3344. Three modes (can all be enabled independently):
  3345. - queue_drying_enabled: Dry between scheduled queue prints
  3346. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  3347. - print_drying_enabled: Also evaluate printers that are currently printing,
  3348. when model+firmware supports "Print While Drying" (gated by
  3349. supports_drying_while_printing). Drying temperature is capped at
  3350. max(40, preset_temp - 5) to protect spools mid-print.
  3351. """
  3352. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  3353. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  3354. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  3355. if not queue_drying_enabled and not ambient_drying_enabled:
  3356. # Stop active drying on all printers if both features disabled
  3357. if self._drying_in_progress:
  3358. for pid in list(self._drying_in_progress):
  3359. if pid in self._scheduled_drying_printer_ids:
  3360. continue
  3361. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  3362. await self._stop_drying(pid)
  3363. return
  3364. # Update drying state from printer status (handles backend restart)
  3365. self._sync_drying_state()
  3366. # Find printers with scheduled items (for queue drying mode)
  3367. printers_with_scheduled: set[int] = set()
  3368. printers_with_items: set[int] = set()
  3369. for item in queue_items:
  3370. if item.printer_id:
  3371. printers_with_items.add(item.printer_id)
  3372. if item.scheduled_time and not item.manual_start:
  3373. printers_with_scheduled.add(item.printer_id)
  3374. # If only queue mode is on and no printers have scheduled items, stop drying
  3375. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  3376. # may still be eligible for mid-print drying regardless of queue state).
  3377. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  3378. for pid in list(self._drying_in_progress):
  3379. if pid in self._scheduled_drying_printer_ids:
  3380. continue
  3381. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  3382. await self._stop_drying(pid)
  3383. return
  3384. # Get humidity threshold (global fallback)
  3385. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  3386. setting = result.scalar_one_or_none()
  3387. global_humidity_threshold = int(setting.value) if setting else 60
  3388. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  3389. # to the global threshold for every AMS unit.
  3390. per_type_thresholds = await self._get_humidity_thresholds(db)
  3391. # Get drying presets
  3392. presets = await self._get_drying_presets(db)
  3393. # Determine if drying should be skipped for printers with pending items
  3394. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  3395. # Get all active printers
  3396. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  3397. for printer in all_printers.scalars():
  3398. pid = printer.id
  3399. # Resolve model+firmware up front — needed to decide whether this printer
  3400. # qualifies for mid-print drying (busy printer on capable hardware).
  3401. state = printer_manager.get_status(pid)
  3402. if not state:
  3403. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  3404. continue
  3405. model = printer_manager.get_model(pid)
  3406. firmware = state.firmware_version
  3407. # "Mid-print" has to mean the printer is actually printing (#2801).
  3408. # It used to be inferred from the dispatch set, which also holds
  3409. # printers that merely could not be dispatched to -- so a printer
  3410. # sitting in FINISH behind an unacknowledged plate was treated as
  3411. # printing, had its drying temperature capped by the mid-print
  3412. # spool protection, and was logged as (mid-print) while idle.
  3413. is_printing = state.state in _ACTIVE_PRINT_STATES
  3414. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  3415. # A printer whose print is running or imminent is left alone unless
  3416. # it can dry through it. `dispatching_printers` is deliberately the
  3417. # narrow set: running, held post-dispatch, or mid-upload.
  3418. if (is_printing or pid in dispatching_printers) and not mid_print:
  3419. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  3420. continue
  3421. if not mid_print:
  3422. # In queue-only mode, only dry printers that have scheduled prints
  3423. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  3424. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  3425. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  3426. await self._stop_drying(pid)
  3427. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  3428. continue
  3429. # When block mode is on, don't START new drying on printers with pending items.
  3430. # But allow already-drying printers through so humidity auto-stop logic still runs.
  3431. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  3432. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  3433. continue
  3434. if not printer_manager.is_connected(pid):
  3435. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  3436. continue
  3437. # Plate-clear is deliberately ignored here (#2801). It answers
  3438. # "is the bed ready for the next job", which says nothing about
  3439. # whether the AMS may heat -- and the gap between a finished print
  3440. # and the acknowledgment is exactly when drying is most useful,
  3441. # because the printer is free and nobody is waiting on it. Leaving
  3442. # the plate unacknowledged is also how people hold the queue by
  3443. # hand, and that hold should not cost them their drying.
  3444. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  3445. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  3446. continue
  3447. # Check drying capability. For mid-print path, supports_drying_while_printing
  3448. # was already verified when computing mid_print above.
  3449. if not mid_print and not supports_drying(model, firmware):
  3450. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  3451. continue
  3452. # Check each AMS unit from raw_data
  3453. ams_list = state.raw_data.get("ams", [])
  3454. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  3455. for ams_data in ams_list:
  3456. module_type = str(ams_data.get("module_type") or "")
  3457. ams_id = int(ams_data.get("id", 0))
  3458. # Only n3f/n3s support drying
  3459. if module_type not in ("n3f", "n3s"):
  3460. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  3461. continue
  3462. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  3463. # Most-restrictive of all loaded tray types; falls back to the
  3464. # global threshold when no overrides are configured.
  3465. trays = ams_data.get("tray", []) or []
  3466. humidity_threshold = self.resolve_humidity_threshold(
  3467. trays, per_type_thresholds, global_humidity_threshold
  3468. )
  3469. dry_time = int(ams_data.get("dry_time") or 0)
  3470. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  3471. humidity = None
  3472. h_raw = ams_data.get("humidity_raw")
  3473. if h_raw is not None:
  3474. try:
  3475. humidity = int(h_raw)
  3476. except (ValueError, TypeError):
  3477. pass
  3478. if humidity is None:
  3479. h_idx = ams_data.get("humidity")
  3480. if h_idx is not None:
  3481. try:
  3482. humidity = int(h_idx)
  3483. except (ValueError, TypeError):
  3484. pass
  3485. unit_key = (pid, ams_id)
  3486. unit_state = self._auto_dry_units.get(unit_key)
  3487. # Already drying — let it run to its configured duration (#1892).
  3488. #
  3489. # We deliberately do NOT stop drying from a humidity re-check here.
  3490. # Relative humidity drops steeply in heated air, so the AMS sensor
  3491. # reads ~15-20% within minutes of the dryer starting even while the
  3492. # filament is still saturated. A humidity-based early-stop therefore
  3493. # always fires at the minimum-time floor, truncating both user-started
  3494. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  3495. # The firmware stops when the configured duration elapses; scheduling
  3496. # stops (print takes priority, queue no longer needs drying) are
  3497. # handled separately via _stop_drying().
  3498. if dry_time > 0:
  3499. if pid not in self._drying_in_progress:
  3500. # Drying we didn't start (manual or from before restart) —
  3501. # track it so scheduling stops still apply; never auto-stop it.
  3502. self._drying_in_progress[pid] = time.monotonic()
  3503. if unit_state is not None:
  3504. unit_state["running"] = True
  3505. logger.debug(
  3506. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  3507. pid,
  3508. ams_id,
  3509. dry_time,
  3510. humidity,
  3511. )
  3512. continue
  3513. # Nothing is drying. Close out a cycle we armed ourselves and
  3514. # judge whether it achieved anything (#2770).
  3515. #
  3516. # "Achieved anything" is measured against the LOWEST reading any
  3517. # cycle on this unit has ended at, not against the threshold and
  3518. # not against the previous cycle. A spool that is genuinely wet
  3519. # in a humid room comes down slowly — 40, 37, 35 — and must be
  3520. # allowed to keep going for as long as it is still coming down,
  3521. # however far it still is from the threshold. What must not
  3522. # continue is a cycle that ends exactly where the last one did,
  3523. # which is the reporter's signature: 15, 15, 16, 15, forever.
  3524. # Comparing against the running minimum rather than the previous
  3525. # end is what stops a sensor oscillating by one point between two
  3526. # values from reading as progress every other cycle.
  3527. if unit_state is not None and unit_state.pop("running", False):
  3528. unit_state["ended_at"] = time.monotonic()
  3529. if humidity is not None and humidity > humidity_threshold:
  3530. best = unit_state.get("best_end_humidity")
  3531. if isinstance(best, int) and humidity < best:
  3532. # Still coming down. Keep going, however far the
  3533. # threshold still is.
  3534. unproductive = 0
  3535. else:
  3536. unproductive = int(unit_state.get("unproductive", 0)) + 1
  3537. if not isinstance(best, int) or humidity < best:
  3538. unit_state["best_end_humidity"] = humidity
  3539. unit_state["unproductive"] = unproductive
  3540. logger.info(
  3541. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  3542. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  3543. pid,
  3544. ams_id,
  3545. humidity,
  3546. humidity_threshold,
  3547. unit_state.get("best_end_humidity"),
  3548. unproductive,
  3549. )
  3550. # A cycle that ended at or below the threshold needs no
  3551. # counter reset here: the branch below drops the whole entry.
  3552. # Humidity below threshold — no need to start drying. This is
  3553. # also the only thing that lifts a suspension: the reading we
  3554. # gave up on has come down, so auto-drying works again and the
  3555. # unit goes back to having no history at all.
  3556. if humidity is None or humidity <= humidity_threshold:
  3557. if unit_state is not None and unit_state.get("suspended"):
  3558. logger.info(
  3559. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  3560. "threshold, resuming automatic drying",
  3561. pid,
  3562. ams_id,
  3563. humidity,
  3564. humidity_threshold,
  3565. )
  3566. # Clear the judgement, keep the clock (#2801). Dropping the
  3567. # whole entry also dropped `ended_at`, and with it the
  3568. # 30-minute cooldown -- so a reading that dips to the
  3569. # threshold as the AMS cools and comes back above it once
  3570. # warm wiped its own history and re-armed immediately. That
  3571. # oscillation is the very thing #2770's cooldown exists to
  3572. # ride out, and it is worst at exactly the margin that makes
  3573. # a unit dry repeatedly: a point or two above the threshold.
  3574. if unit_state is not None:
  3575. unit_state.pop("suspended", None)
  3576. unit_state.pop("unproductive", None)
  3577. unit_state.pop("best_end_humidity", None)
  3578. logger.debug(
  3579. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  3580. pid,
  3581. ams_id,
  3582. humidity,
  3583. humidity_threshold,
  3584. )
  3585. continue
  3586. if unit_state is not None:
  3587. if unit_state.get("suspended"):
  3588. logger.debug(
  3589. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  3590. "above the %d%% threshold",
  3591. pid,
  3592. ams_id,
  3593. int(unit_state.get("unproductive", 0)),
  3594. humidity_threshold,
  3595. )
  3596. continue
  3597. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  3598. unit_state["suspended"] = True
  3599. logger.warning(
  3600. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  3601. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  3602. "higher while it is warm, so a threshold in that range can never be reached and "
  3603. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  3604. pid,
  3605. ams_id,
  3606. int(unit_state.get("unproductive", 0)),
  3607. humidity,
  3608. humidity_threshold,
  3609. )
  3610. await self._notify_auto_drying_suspended(
  3611. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  3612. )
  3613. continue
  3614. ended_at = unit_state.get("ended_at")
  3615. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  3616. logger.debug(
  3617. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  3618. "cycle before the humidity reading is worth acting on",
  3619. pid,
  3620. ams_id,
  3621. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  3622. )
  3623. continue
  3624. # Check cannot-dry reasons (power constraints etc.)
  3625. sf_reasons = ams_data.get("dry_sf_reason", [])
  3626. if sf_reasons:
  3627. logger.debug(
  3628. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  3629. pid,
  3630. ams_id,
  3631. sf_reasons,
  3632. )
  3633. continue
  3634. # Get conservative drying params for mixed filaments
  3635. params = self._get_conservative_drying_params(trays, module_type, presets)
  3636. if not params:
  3637. logger.debug(
  3638. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  3639. )
  3640. continue
  3641. temp, duration_hours, filament_type = params
  3642. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  3643. # "drying temperature must not exceed the filament's softening temperature"
  3644. # for Print While Drying). Floor at 40 degC — below that the dryer is
  3645. # ineffective and firmware will reject anyway.
  3646. if mid_print:
  3647. temp = max(40, temp - 5)
  3648. # Start drying
  3649. logger.info(
  3650. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  3651. "starting %s drying at %d°C for %dh%s",
  3652. pid,
  3653. ams_id,
  3654. humidity,
  3655. humidity_threshold,
  3656. filament_type,
  3657. temp,
  3658. duration_hours,
  3659. " (mid-print)" if mid_print else "",
  3660. )
  3661. success = printer_manager.send_drying_command(
  3662. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  3663. )
  3664. if success:
  3665. self._drying_in_progress[pid] = time.monotonic()
  3666. armed = self._auto_dry_units.setdefault(
  3667. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  3668. )
  3669. armed["running"] = True
  3670. async def _notify_auto_drying_suspended(
  3671. self,
  3672. db: AsyncSession,
  3673. printer: Printer,
  3674. ams_id: int,
  3675. humidity: int,
  3676. threshold: int,
  3677. cycles: int,
  3678. ) -> None:
  3679. """Tell the user auto-drying has given up on one AMS unit (#2770).
  3680. Fires once per suspension — the caller sets ``suspended`` before calling
  3681. and every later pass short-circuits on it — because the whole point is
  3682. that Bambuddy has stopped acting. Somebody whose printer sits in another
  3683. building needs that to reach them, and the hourly humidity alarm they
  3684. are already getting says the opposite of what happened here.
  3685. Never raises: a notification provider being down must not stop the
  3686. suspension itself from taking effect.
  3687. """
  3688. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  3689. try:
  3690. await notification_service.on_ams_drying_suspended(
  3691. printer.id,
  3692. printer.name,
  3693. ams_label,
  3694. float(humidity),
  3695. float(threshold),
  3696. cycles,
  3697. db,
  3698. )
  3699. except Exception as e:
  3700. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  3701. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  3702. """Stop judging the drying cycle currently on this AMS unit (#2770).
  3703. The unproductive-cycle counter exists to notice that *drying* is not
  3704. moving the humidity reading. A cycle that ended because somebody sent a
  3705. stop says nothing about that — it was cut short before it had a chance —
  3706. so counting it would suspend auto-drying for a reason that has nothing to
  3707. do with the loop the counter is there to break.
  3708. Two callers, both of them a stop Bambuddy is responsible for: the
  3709. print-takes-priority stop below, and the manual Stop button. Left
  3710. uncalled, an install that dries between queue jobs would suspend its own
  3711. auto-drying after two prints interrupted a dry — exactly the install
  3712. queue-drying exists for.
  3713. The rest of the unit's history is kept: the cooldown before re-arming
  3714. still applies, and an earlier count still stands.
  3715. """
  3716. state = self._auto_dry_units.get((printer_id, ams_id))
  3717. if state is not None:
  3718. state.pop("running", None)
  3719. state["ended_at"] = time.monotonic()
  3720. def _sync_drying_state(self):
  3721. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  3722. One direction only: it prunes, it never adds. A printer drying without an
  3723. entry here — because the user started the cycle from Studio, the printer's
  3724. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  3725. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  3726. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  3727. That is deliberate for now rather than an oversight: populating this from
  3728. telemetry would hand the scheduler authority to stop drying a user started
  3729. by hand. It also means the backend-restart case this used to claim to
  3730. handle is not handled.
  3731. """
  3732. to_remove = []
  3733. for pid in self._drying_in_progress:
  3734. state = printer_manager.get_status(pid)
  3735. if not state:
  3736. to_remove.append(pid)
  3737. continue
  3738. # Check if any AMS unit is still drying
  3739. ams_list = state.raw_data.get("ams", [])
  3740. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  3741. if not any_drying:
  3742. to_remove.append(pid)
  3743. for pid in to_remove:
  3744. self._drying_in_progress.pop(pid, None)
  3745. # A printer that has gone away entirely takes its per-AMS auto-drying
  3746. # history with it (#2770), so a printer deleted and re-added does not
  3747. # inherit a suspension it never earned.
  3748. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  3749. self._auto_dry_units.pop(key, None)
  3750. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  3751. """True when a running cycle can be left alone while the next print runs.
  3752. Some hardware dries happily through a print and #2758 settled that we
  3753. should not tear those cycles down: the X2D there was refusing to
  3754. *start* a job, which is a different problem, and stopping drying before
  3755. every dispatch would throw away cycles the printer was content to run.
  3756. Where the model cannot do it, or the user has not enabled it, the print
  3757. takes priority and the cycle stops -- which is what the queue_drying_block
  3758. setting has always promised in its off position.
  3759. """
  3760. if not await self._get_bool_setting(db, "print_drying_enabled"):
  3761. return False
  3762. status = printer_manager.get_status(printer_id)
  3763. return supports_drying_while_printing(
  3764. printer_manager.get_model(printer_id),
  3765. status.firmware_version if status else None,
  3766. )
  3767. async def _stop_drying(self, printer_id: int):
  3768. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  3769. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  3770. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  3771. enough to kill a cycle the user had started by hand on a *different*
  3772. unit of the same printer (#2801). That contradicted the contract
  3773. ``_sync_drying_state`` already documents -- the entry gate deliberately
  3774. only knows about cycles Bambuddy began, so the action must not reach
  3775. past them either.
  3776. """
  3777. state = printer_manager.get_status(printer_id)
  3778. if not state:
  3779. self._drying_in_progress.pop(printer_id, None)
  3780. return
  3781. ams_list = state.raw_data.get("ams", [])
  3782. for ams_data in ams_list:
  3783. dry_time = int(ams_data.get("dry_time") or 0)
  3784. if dry_time > 0:
  3785. ams_id = int(ams_data.get("id", 0))
  3786. if (printer_id, ams_id) not in self._auto_dry_units:
  3787. logger.debug(
  3788. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  3789. printer_id,
  3790. ams_id,
  3791. )
  3792. continue
  3793. logger.info(
  3794. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  3795. printer_id,
  3796. ams_id,
  3797. )
  3798. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  3799. self.forget_auto_dry_cycle(printer_id, ams_id)
  3800. self._drying_in_progress.pop(printer_id, None)
  3801. # Scheduled manual drying (#2638) -----------------------------------
  3802. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  3803. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  3804. async def _check_scheduled_dryings(self, db: AsyncSession):
  3805. """Dispatch due scheduled drying runs and track running ones."""
  3806. now = utcnow_naive()
  3807. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  3808. # Monotonic, so a clock adjustment cannot park the prune for hours.
  3809. since_prune = time.monotonic()
  3810. if (
  3811. self._last_scheduled_drying_prune is None
  3812. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  3813. ):
  3814. self._last_scheduled_drying_prune = since_prune
  3815. await db.execute(
  3816. delete(ScheduledDrying).where(
  3817. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  3818. ScheduledDrying.completed_at.is_not(None),
  3819. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  3820. )
  3821. )
  3822. # Same order as the list route: with two rows due on one printer the
  3823. # earliest scheduled wins rather than whatever the DB hands back first.
  3824. result = await db.execute(
  3825. select(ScheduledDrying)
  3826. .where(ScheduledDrying.status.in_(("pending", "running")))
  3827. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  3828. )
  3829. rows = list(result.scalars().all())
  3830. # Rebuild from the DB every tick so route-side cancels and completions
  3831. # show up. Auto-drying's stop-all branches check this set before
  3832. # stopping anything (#2638).
  3833. # Kept from the previous pass so a run that ended between passes — a
  3834. # cancel through the route, say — can still be released below.
  3835. previously_running = self._scheduled_drying_printer_ids
  3836. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  3837. running_printer_ids = set(self._scheduled_drying_printer_ids)
  3838. # Model and firmware come from the printer row, not the live state.
  3839. printer_ids = {row.printer_id for row in rows}
  3840. printers_by_id: dict[int, Printer] = {}
  3841. if printer_ids:
  3842. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  3843. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  3844. for row in rows:
  3845. if row.status == "running":
  3846. self._update_running_scheduled_drying(row, now)
  3847. continue
  3848. if row.start_after is not None and row.start_after > now:
  3849. continue
  3850. state = printer_manager.get_status(row.printer_id)
  3851. if not state:
  3852. row.waiting_reason = "printer_offline"
  3853. continue
  3854. # Same preflight the immediate endpoint runs. Without it the publish
  3855. # succeeds, the row goes to running, the printer ignores the command
  3856. # and the run silently cancels itself after the grace window.
  3857. printer = printers_by_id.get(row.printer_id)
  3858. unsupported = drying_preflight.check_drying_supported(
  3859. printer.model if printer else None, state.firmware_version
  3860. )
  3861. if unsupported:
  3862. row.status = "failed"
  3863. row.error_message = unsupported
  3864. row.completed_at = now
  3865. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  3866. continue
  3867. if self._drying_in_progress.get(row.printer_id) or row.printer_id in running_printer_ids:
  3868. row.waiting_reason = "already_drying"
  3869. continue
  3870. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  3871. row.waiting_reason = "printer_busy"
  3872. continue
  3873. target = drying_preflight.find_ams_unit(state, row.ams_id)
  3874. if target is None:
  3875. row.waiting_reason = "ams_not_found"
  3876. continue
  3877. blocking = drying_preflight.blocking_reason_codes(target)
  3878. if blocking:
  3879. # Keep the power case distinct; it needs the user to act, so the
  3880. # card can say so instead of waiting silently.
  3881. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  3882. continue
  3883. filament = drying_preflight.resolve_filament(target, row.filament)
  3884. logger.info(
  3885. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  3886. row.id,
  3887. row.printer_id,
  3888. row.ams_id,
  3889. row.temp,
  3890. row.duration_hours,
  3891. )
  3892. success = printer_manager.send_drying_command(
  3893. row.printer_id,
  3894. row.ams_id,
  3895. row.temp,
  3896. row.duration_hours,
  3897. mode=1,
  3898. filament=filament,
  3899. rotate_tray=row.rotate_tray,
  3900. )
  3901. if success:
  3902. row.status = "running"
  3903. row.started_at = now
  3904. row.waiting_reason = None
  3905. row.filament = filament
  3906. self._drying_in_progress[row.printer_id] = time.monotonic()
  3907. self._scheduled_drying_printer_ids.add(row.printer_id)
  3908. running_printer_ids.add(row.printer_id)
  3909. else:
  3910. row.waiting_reason = "printer_offline"
  3911. # Release the printers whose run has ended. `_drying_in_progress` is
  3912. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  3913. # but that call sits behind the auto-drying enabled check, and this
  3914. # method is the one writer that runs whether auto-drying is on or not.
  3915. # With it off, nothing would ever drop the entry short of a print being
  3916. # dispatched to the same printer, so the next scheduled run would wait
  3917. # on "already_drying" forever and `queue_drying_block` would hold the
  3918. # printer's prints too. Covers a run that ended during this pass and one
  3919. # cancelled through the route between passes.
  3920. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  3921. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  3922. self._drying_in_progress.pop(printer_id, None)
  3923. await db.commit()
  3924. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  3925. """Detect completion or interruption of a running scheduled drying.
  3926. The firmware reports remaining minutes in ams.dry_time; 0 means not
  3927. drying. Within the grace window after start we ignore dry_time==0
  3928. (the status lags the command). After that, dry_time==0 near the end
  3929. of the configured duration means completed. Much earlier means the
  3930. run was stopped: re-queue it if a print preempted the dryer, but a
  3931. stop while the printer is idle was deliberate, so cancel the row
  3932. rather than restart drying the user just stopped.
  3933. """
  3934. if row.started_at is None:
  3935. row.started_at = now
  3936. return
  3937. elapsed = (now - row.started_at).total_seconds()
  3938. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  3939. return
  3940. state = printer_manager.get_status(row.printer_id)
  3941. if not state:
  3942. return # offline mid-dry; resolve when it reconnects
  3943. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  3944. # throw on a malformed id would cost the whole pass including print
  3945. # dispatch, every tick.
  3946. target = drying_preflight.find_ams_unit(state, row.ams_id)
  3947. try:
  3948. dry_time = int(target.get("dry_time") or 0) if target else 0
  3949. except (TypeError, ValueError):
  3950. dry_time = 0
  3951. if dry_time > 0:
  3952. return
  3953. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  3954. row.status = "completed"
  3955. row.completed_at = now
  3956. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  3957. row.status = "pending"
  3958. row.started_at = None
  3959. row.waiting_reason = "interrupted"
  3960. else:
  3961. row.status = "cancelled"
  3962. row.completed_at = now
  3963. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  3964. """Get all smart plugs associated with a printer."""
  3965. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3966. return list(result.scalars().all())
  3967. @staticmethod
  3968. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  3969. """Pick the plug to power-cycle a printer back online with (#2629).
  3970. Only a plug flagged ``controls_printer_power`` can actually bring the
  3971. printer back; waiting for a boot on an accessory (filter fan, lights)
  3972. just burns the power-on timeout and fails the dispatch. Falls back to
  3973. the first plug when none is flagged, which is the pre-#2629 behaviour.
  3974. Callers must pass a non-empty list.
  3975. """
  3976. for plug in auto_on_plugs:
  3977. if plug.controls_printer_power:
  3978. return plug
  3979. return auto_on_plugs[0]
  3980. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  3981. # chamber-temperature recommendations BambuStudio ships for the matching
  3982. # filament profile; users can override via Settings → Workflow → Preheat
  3983. # card. "default" applies when a loaded tray's normalised type isn't in
  3984. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  3985. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  3986. "PLA": 0,
  3987. "PETG": 0,
  3988. "PETG-CF": 40,
  3989. "ABS": 45,
  3990. "ASA": 45,
  3991. "PA": 50,
  3992. "PA-CF": 55,
  3993. "PC": 50,
  3994. "PC-FR": 50,
  3995. "TPU": 0,
  3996. "PVA": 0,
  3997. "default": 0,
  3998. }
  3999. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  4000. """Parse the user-configured filament→chamber-target map, falling back
  4001. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  4002. are uppercased and the 'default' fallback is always present in the
  4003. returned dict so the resolution loop can index it unconditionally."""
  4004. raw = await self._get_setting(db, "preheat_filament_targets")
  4005. if not raw:
  4006. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  4007. try:
  4008. parsed = json.loads(raw)
  4009. if not isinstance(parsed, dict):
  4010. raise ValueError("not an object")
  4011. except (json.JSONDecodeError, ValueError) as exc:
  4012. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  4013. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  4014. # Coerce values to int; drop unparseable rows so a stray string
  4015. # doesn't crash the loop.
  4016. out: dict[str, int] = {}
  4017. for key, value in parsed.items():
  4018. try:
  4019. out[str(key).upper()] = int(value)
  4020. except (TypeError, ValueError):
  4021. continue
  4022. if "DEFAULT" not in out:
  4023. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  4024. return out
  4025. @staticmethod
  4026. def _normalize_filament_type(tray_type: str) -> str:
  4027. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  4028. existing drying-preset normalisation (split-at-space, upper-case) so
  4029. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  4030. "PA-CF" (no space to split on)."""
  4031. return tray_type.split()[0].upper() if tray_type else ""
  4032. def _derive_chamber_target(
  4033. self,
  4034. printer: Printer,
  4035. targets: dict[str, int],
  4036. ) -> int:
  4037. """Look up the chamber target for each loaded AMS tray and return the
  4038. max. Returns 0 when no AMS data is available (e.g. external-spool
  4039. prints) or when every loaded slot maps to 0 — the chamber phase then
  4040. short-circuits in the main loop.
  4041. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  4042. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  4043. less slots have empty `tray_type` and contribute nothing."""
  4044. state = printer_manager.get_status(printer.id)
  4045. if state is None:
  4046. return 0
  4047. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  4048. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  4049. if isinstance(ams_list, dict):
  4050. ams_list = ams_list.get("ams") or []
  4051. if not isinstance(ams_list, list):
  4052. return 0
  4053. best = 0
  4054. for ams in ams_list:
  4055. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  4056. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  4057. if not normalised:
  4058. continue
  4059. target = targets.get(normalised, targets.get("DEFAULT", 0))
  4060. if target > best:
  4061. best = target
  4062. return best
  4063. def _release_keep_warm(self, pid: int) -> None:
  4064. """Release keep-warm on a printer that left the candidate set.
  4065. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  4066. reports the target we set (``entry.held_target``), so a user or
  4067. subsequent print that changed the bed target since is not clobbered.
  4068. Best-effort, never raises.
  4069. The entry is kept, not dropped, when the printer cannot be reached
  4070. right now: a printer that is briefly offline still has a hot bed, and
  4071. holding the entry is what keeps the max-duration timeout applying and
  4072. lets a later tick retry the release. Only a printer that has left the
  4073. manager entirely gives up on that, in ``_sample_chamber_temps``.
  4074. """
  4075. entry = self._keep_warm.get(pid)
  4076. if entry is None:
  4077. return
  4078. state = printer_manager.get_status(pid)
  4079. client = printer_manager.get_client(pid)
  4080. if state is None or client is None:
  4081. logger.debug(
  4082. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  4083. pid,
  4084. )
  4085. return
  4086. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  4087. if int(cur_bed_target) != entry.held_target:
  4088. # Someone else owns the bed now, so there is nothing of ours to
  4089. # undo and nothing left to track.
  4090. logger.info(
  4091. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  4092. pid,
  4093. int(cur_bed_target),
  4094. entry.held_target,
  4095. )
  4096. self._keep_warm.pop(pid, None)
  4097. return
  4098. try:
  4099. client.set_bed_temperature(0)
  4100. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  4101. self._keep_warm.pop(pid, None)
  4102. except Exception as exc:
  4103. # Keep the entry so the next tick tries again rather than leaving
  4104. # the bed hot with nothing tracking it.
  4105. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  4106. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  4107. """Release printers that dropped out of the keep-warm candidate set.
  4108. Called from ``_apply_keep_warm`` on every tick (with the current
  4109. candidate set), and from ``check_queue``'s no-pending-items early
  4110. return (with an empty candidate set) so orphaned holds still get
  4111. released when the queue empties. Also called with an empty candidate
  4112. set when any of the three gate settings toggles off, so a printer
  4113. whose feature was disabled mid-hold gets its bed released.
  4114. Printers being dispatched this tick are excluded from the bed-off
  4115. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  4116. transient 0 in between would just churn against preheat. Ownership of
  4117. the hot bed transfers to the preheat rollback pin instead — if the
  4118. dispatch aborts before the print starts (failed upload, cancelled
  4119. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  4120. skips (e.g. the item has no bed_temperature metadata) the pin entry
  4121. is the ONLY thing standing between an aborted dispatch and a bed
  4122. left hot with no owner. A successful print start clears the pin and
  4123. the print's own gcode takes over, as usual.
  4124. """
  4125. for _pid in list(self._keep_warm):
  4126. if _pid in active_candidates:
  4127. continue
  4128. if _pid in dispatched:
  4129. handed_over = self._keep_warm.pop(_pid, None)
  4130. self._preheat_pin.setdefault(_pid, set()).add("bed")
  4131. if handed_over is not None:
  4132. self._preheat_pin_bed[_pid] = handed_over.held_target
  4133. continue
  4134. self._release_keep_warm(_pid)
  4135. async def _apply_keep_warm(
  4136. self,
  4137. db: AsyncSession,
  4138. items: list[PrintQueueItem],
  4139. dispatch_ids: list[int] | set[int],
  4140. busy_printers: set[int],
  4141. require_plate_clear: bool,
  4142. ) -> None:
  4143. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  4144. When a printer just finished a job (FINISH state) and the next queued
  4145. item needs chamber heating, hold the bed hot so the chamber stays warm
  4146. during the bed-clearing window. The bed is the chamber's heating
  4147. element here, not a print surface — nothing is printing during the
  4148. hold and the dispatched print's own preheat/gcode re-targets the bed —
  4149. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  4150. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  4151. aftermarket chamber heaters), raised to the item's own parsed
  4152. bed_temperature when that is higher. Items whose archive metadata has
  4153. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  4154. get a hold — chamber need is what gates the feature, not metadata.
  4155. Skips entirely for filaments that map to a 0°C chamber target
  4156. (PLA, PETG, etc.). Printers being dispatched this cycle are excluded:
  4157. ``_preheat_and_soak`` already handles their bed temperature.
  4158. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  4159. released to 0 and the entry is latched ``expired=True`` so
  4160. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  4161. MQTT: publish is skipped when firmware already has the target.
  4162. The release sweep runs BEFORE the engagement gate so a printer that
  4163. was owned by keep-warm still gets its bed released when any of the
  4164. three gate settings is toggled off mid-hold. The
  4165. ``check_queue`` early-return-when-no-items path also calls
  4166. ``_sweep_keep_warm`` directly to release orphaned holds.
  4167. """
  4168. dispatch_set = set(dispatch_ids)
  4169. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  4170. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  4171. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  4172. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  4173. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  4174. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  4175. # Release sweep first — must run even when gate_open is False so a
  4176. # printer owned by keep-warm when a gate toggles off gets released.
  4177. self._sweep_keep_warm(
  4178. active_candidates=warm_candidates if gate_open else set(),
  4179. dispatched=dispatched_printers,
  4180. )
  4181. if not gate_open:
  4182. return
  4183. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  4184. max_hold_seconds = (
  4185. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  4186. )
  4187. now_mono = time.monotonic()
  4188. filament_targets: dict[str, int] | None = None
  4189. for pid in warm_candidates:
  4190. entry = self._keep_warm.get(pid)
  4191. # Latched-expired: max-duration timeout already fired for this
  4192. # printer. Skip until the release sweep drops the entry (i.e.
  4193. # until the printer leaves the candidate set).
  4194. if entry is not None and entry.expired:
  4195. continue
  4196. # These two guards sit ahead of the max-duration check below, so an
  4197. # engaged hold only ages out while its printer is still reachable
  4198. # and still in FINISH. That is deliberate rather than a hole: with
  4199. # no status or no client there is no M140 to send anyway, and the
  4200. # elapsed check runs off `entry.started` so it fires on the first
  4201. # tick after the printer comes back. Leaving FINISH means the plate
  4202. # was cleared, which drops the printer out of `warm_candidates` and
  4203. # hands it to `_release_keep_warm` instead. The invariant worth
  4204. # preserving if this is ever reordered: every path out of an
  4205. # engaged hold ends in a bed-off, whether by timeout or release.
  4206. state = printer_manager.get_status(pid)
  4207. if state is None or state.state != "FINISH":
  4208. continue
  4209. client = printer_manager.get_client(pid)
  4210. if client is None:
  4211. continue
  4212. next_item = next((it for it in items if it.printer_id == pid), None)
  4213. if next_item is None:
  4214. continue
  4215. # Hold temperature: the configured keep-warm temp, raised to the
  4216. # item's own bed temp when the metadata reports a higher one. A
  4217. # missing bed_temperature (Orca gcode.3mf exports parse without
  4218. # one) does NOT skip the hold — chamber need gates the feature.
  4219. archive = next_item.archive
  4220. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  4221. bed_target = max(item_bed, hold_temp)
  4222. if bed_target <= 0:
  4223. continue
  4224. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  4225. if explicit is not None:
  4226. chamber_needed = int(explicit) > 0
  4227. else:
  4228. if filament_targets is None:
  4229. filament_targets = await self._get_preheat_filament_targets(db)
  4230. printer_obj = await self._get_printer(db, pid)
  4231. chamber_needed = (
  4232. printer_obj is not None and self._derive_chamber_target(printer_obj, filament_targets) > 0
  4233. )
  4234. if not chamber_needed:
  4235. continue
  4236. # Seed the timer on first engagement; keep it on subsequent ticks
  4237. # (never re-seed — that would defeat the max-duration cap).
  4238. if entry is None:
  4239. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  4240. self._keep_warm[pid] = entry
  4241. elapsed = now_mono - entry.started
  4242. if elapsed > max_hold_seconds:
  4243. # Timeout: publish bed → 0 once (if firmware still holds our
  4244. # target) and latch expired. The entry stays until the release
  4245. # sweep drops it, preventing the next tick from re-seeding.
  4246. logger.warning(
  4247. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  4248. pid,
  4249. elapsed,
  4250. )
  4251. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  4252. if int(cur_bed_target) == entry.held_target:
  4253. try:
  4254. client.set_bed_temperature(0)
  4255. except Exception as exc:
  4256. logger.warning(
  4257. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  4258. pid,
  4259. exc,
  4260. )
  4261. else:
  4262. logger.info(
  4263. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  4264. pid,
  4265. int(cur_bed_target),
  4266. entry.held_target,
  4267. )
  4268. entry.expired = True
  4269. continue
  4270. # Idempotence: skip publish when firmware already has our target.
  4271. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  4272. if int(cur_bed_target) == bed_target:
  4273. entry.held_target = bed_target
  4274. continue
  4275. try:
  4276. client.set_bed_temperature(bed_target)
  4277. entry.held_target = bed_target
  4278. logger.info(
  4279. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  4280. bed_target,
  4281. pid,
  4282. )
  4283. except Exception as exc:
  4284. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  4285. def _sample_chamber_temps(self) -> None:
  4286. """Record a chamber temperature sample for every connected printer.
  4287. Called once per scheduler tick (every 3–30 s). Entries older than
  4288. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  4289. Also evicts per-printer state whose printer_id is no longer registered
  4290. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  4291. """
  4292. now = time.monotonic()
  4293. cutoff = now - self._chamber_history_ttl
  4294. statuses = printer_manager.get_all_statuses()
  4295. known_pids = set(statuses.keys())
  4296. for pid, status in statuses.items():
  4297. if status is None or not status.connected:
  4298. continue
  4299. temps = status.temperatures or {}
  4300. chamber = temps.get("chamber")
  4301. if chamber is None:
  4302. continue
  4303. hist = self._chamber_history.setdefault(pid, deque())
  4304. hist.append((now, float(chamber)))
  4305. while hist and hist[0][0] < cutoff:
  4306. hist.popleft()
  4307. # Evict state for printers that are no longer registered with the manager.
  4308. # This is the one place a keep-warm entry is dropped without releasing
  4309. # the bed: the printer is gone from the manager, so there is no client
  4310. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  4311. # for printers that are merely unreachable, which is what makes this
  4312. # the terminal case rather than a silent leak.
  4313. for pid in list(self._chamber_history):
  4314. if pid not in known_pids:
  4315. self._chamber_history.pop(pid, None)
  4316. for pid in list(self._keep_warm):
  4317. if pid not in known_pids:
  4318. logger.info(
  4319. "Queue: dropping keep-warm state for printer %d — no longer registered",
  4320. pid,
  4321. )
  4322. self._keep_warm.pop(pid, None)
  4323. for pid in list(self._preheat_pin):
  4324. if pid not in known_pids:
  4325. self._preheat_pin.pop(pid, None)
  4326. self._preheat_pin_bed.pop(pid, None)
  4327. def _chamber_soak_remaining(
  4328. self,
  4329. printer_id: int,
  4330. chamber_target: float,
  4331. soak_seconds: int,
  4332. tolerance: float = 2.0,
  4333. ) -> int:
  4334. """Return how many seconds of soak time are still needed.
  4335. Credits the time the chamber has already spent at temperature against
  4336. the configured soak. The credit may not start earlier than any of:
  4337. * **The newest sample.** Nothing recent means the printer stopped
  4338. reporting mid-observation and the chamber may have cooled unseen, so
  4339. the full soak is required. (A 2 h history whose last reading is half
  4340. an hour old is not evidence of anything — the measured cooling rate
  4341. is fast enough to cross the threshold in that time.)
  4342. * **The most recent contiguous run of samples.** A gap wider than
  4343. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  4344. far side is not evidence of temperature.
  4345. * **The end of the most recent real dip below the threshold.**
  4346. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  4347. — see that constant for the thermal reasoning. A stray low reading is
  4348. an artifact, and treating it as cooling would discard a soak that
  4349. actually happened.
  4350. Returns ``soak_seconds`` when nothing can be credited (no history,
  4351. stale history, or the chamber is below the threshold right now) and 0
  4352. once the credited time covers the whole soak.
  4353. """
  4354. hist = self._chamber_history.get(printer_id)
  4355. if not hist:
  4356. return soak_seconds
  4357. now = time.monotonic()
  4358. newest_ts, newest_temp = hist[-1]
  4359. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  4360. return soak_seconds # stale — no fresh evidence to credit
  4361. threshold = chamber_target - tolerance
  4362. if newest_temp < threshold:
  4363. return soak_seconds # below target right now; nothing is soaked
  4364. samples = list(hist)
  4365. # Earliest point we have unbroken observations for.
  4366. credit_from = samples[-1][0]
  4367. for i in range(len(samples) - 1, 0, -1):
  4368. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  4369. break
  4370. credit_from = samples[i - 1][0]
  4371. # Pull the credit forward to the end of the last significant dip. Each
  4372. # excursion is measured between the in-range readings that bracket it,
  4373. # so a lone stray sample is charged one sampling interval rather than
  4374. # zero, and the comparison errs towards calling a dip real.
  4375. i = 0
  4376. while i < len(samples):
  4377. if samples[i][1] >= threshold:
  4378. i += 1
  4379. continue
  4380. j = i
  4381. while j < len(samples) and samples[j][1] < threshold:
  4382. j += 1
  4383. # `newest_temp >= threshold` was checked above, so j is in range.
  4384. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  4385. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  4386. # Credit resumes at the last below-threshold sample rather than
  4387. # the first good one after it, so a recovered dip over-credits
  4388. # by up to one sampling interval — the opposite lean to the
  4389. # bracketing above. Both are bounded by the sample cadence and
  4390. # dwarfed by the grace period, so neither is worth the extra
  4391. # arithmetic to remove.
  4392. credit_from = max(credit_from, samples[j - 1][0])
  4393. i = j
  4394. return max(0, soak_seconds - int(now - credit_from))
  4395. def notify_dispatch_cancelled(self, item_id: int) -> None:
  4396. """Tell an in-flight dispatch that its item no longer wants to print.
  4397. Called by the queue's cancel and delete routes. Those only write to the
  4398. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  4399. observe — so preheat would keep heating for the rest of max_wait + soak
  4400. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  4401. blocking every other queued item behind a print that is not happening.
  4402. Signalling in memory rather than re-reading the row keeps this off the
  4403. database entirely: no second session, no transaction held across a long
  4404. sleep, and no snapshot staleness deciding whether a print goes ahead.
  4405. Bambuddy serves from a single uvicorn process with one scheduler task,
  4406. so the route and the dispatch always share this object. The flag is
  4407. advisory — dropping it (e.g. after a restart) only costs a wasted
  4408. preheat, never a wrongly-abandoned print.
  4409. Only ids with a dispatch actually in flight are recorded, so the set
  4410. stays bounded by the upload pool rather than growing once per cancelled
  4411. item for the life of the process. Skipping the rest loses nothing: an
  4412. item that is not in flight cannot start heating later either, because
  4413. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  4414. the caller has already committed a terminal status (or deleted the row)
  4415. before calling this.
  4416. """
  4417. if item_id in self._inflight:
  4418. self._cancelled_dispatches.add(item_id)
  4419. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  4420. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  4421. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  4422. while it is parked, so the wait is chopped into
  4423. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  4424. """
  4425. remaining = float(seconds)
  4426. while remaining > 0:
  4427. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  4428. await asyncio.sleep(slice_secs)
  4429. remaining -= slice_secs
  4430. if item_id in self._cancelled_dispatches:
  4431. return False
  4432. return True
  4433. async def _preheat_and_soak(
  4434. self,
  4435. db: AsyncSession,
  4436. item: PrintQueueItem,
  4437. printer: Printer,
  4438. archive: PrintArchive | None,
  4439. ) -> bool:
  4440. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  4441. Returns True when the dispatch should carry on to the upload — including
  4442. every case where preheat is skipped, since a skipped preheat is not a
  4443. reason to abandon the print. Returns False only when the item stopped
  4444. wanting to be printed while the stage was waiting (cancelled or
  4445. deleted); the caller must then abandon the dispatch, and
  4446. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  4447. Resolution order:
  4448. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  4449. to the global `preheat_enabled` setting; 'on' forces the stage on
  4450. even if the global is off.
  4451. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  4452. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  4453. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  4454. phase + soak timer).
  4455. 3. Three hardware tiers branch the wait loop:
  4456. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  4457. send M141 to the resolved target, then wait for the chamber sensor
  4458. to reach it (or the max-wait timeout to elapse).
  4459. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  4460. no M141; the bed is the only heat source, so we wait for the chamber
  4461. sensor to rise via bed radiation OR fall through on timeout.
  4462. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  4463. temperature; the function just heats the bed and holds for the
  4464. configured soak duration.
  4465. The bed target comes from the archive's parsed metadata
  4466. (`bed_temperature`); if missing the preheat stage logs and returns
  4467. without dispatching anything, rather than guessing at a default that
  4468. might wreck filament setup.
  4469. Failures are logged but never re-raised — preheat is best-effort. A
  4470. printer that goes offline mid-soak, a refused gcode command, or a
  4471. missing temperature reading must not turn into a failed queue item; the
  4472. normal upload + start path runs immediately after this method returns.
  4473. """
  4474. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  4475. if override == "off":
  4476. return True
  4477. if override == "inherit":
  4478. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  4479. if not enabled:
  4480. return True
  4481. # override == "on" forces the stage on regardless of the global setting.
  4482. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  4483. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  4484. # Chamber target resolution:
  4485. # 1. Explicit per-item override beats everything (user knows best).
  4486. # 2. Otherwise derive from loaded AMS filament types via the per-
  4487. # filament target map. PLA-only print derives 0 → chamber phase
  4488. # auto-skips without the user touching anything.
  4489. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  4490. if explicit_target is not None and explicit_target > 0:
  4491. chamber_target = int(explicit_target)
  4492. chamber_source = "item-override"
  4493. elif explicit_target == 0:
  4494. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  4495. chamber_source = "item-override-zero"
  4496. else:
  4497. targets = await self._get_preheat_filament_targets(db)
  4498. chamber_target = self._derive_chamber_target(printer, targets)
  4499. chamber_source = "filament-map"
  4500. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  4501. if bed_target <= 0:
  4502. # No bed temperature in the slicer metadata. When the print needs a
  4503. # hot chamber the bed is simply how we heat it, so fall back to the
  4504. # configured chamber-heating bed temperature rather than skipping
  4505. # the whole stage — otherwise the print starts with a cold chamber,
  4506. # which is exactly what preheat exists to prevent. Without a chamber
  4507. # requirement there is nothing to preheat *for*, so skip as before
  4508. # rather than guess a bed temperature for the print itself.
  4509. if chamber_target <= 0:
  4510. logger.info(
  4511. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  4512. item.id,
  4513. )
  4514. return True
  4515. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  4516. logger.info(
  4517. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  4518. "%d°C to drive the chamber to %d°C",
  4519. item.id,
  4520. bed_target,
  4521. chamber_target,
  4522. )
  4523. client = printer_manager.get_client(printer.id)
  4524. if client is None:
  4525. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  4526. return True
  4527. model = printer.model or ""
  4528. has_heater = supports_chamber_heater(model)
  4529. has_sensor = supports_chamber_temp(model)
  4530. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  4531. # Fast path: if the chamber has been continuously above target for at
  4532. # least soak_seconds and the bed is already at temperature, skip the
  4533. # entire preheat stage. Typical case: keep-warm held the bed between
  4534. # consecutive same-material prints and the chamber never dropped.
  4535. if do_chamber and has_sensor and soak_seconds > 0:
  4536. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  4537. if remaining == 0:
  4538. cur = printer_manager.get_status(printer.id)
  4539. if cur:
  4540. cur_temps = cur.temperatures or {}
  4541. if (
  4542. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  4543. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  4544. ):
  4545. logger.info(
  4546. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  4547. "and bed is already at temperature (chamber history fast-path)",
  4548. item.id,
  4549. chamber_target,
  4550. soak_seconds,
  4551. )
  4552. # Still set targets to prevent cooling during the 3MF upload window.
  4553. # Register each successful set in the preheat pin so `_dispatch_one`
  4554. # unwinds them on any non-success exit.
  4555. pin = self._preheat_pin.setdefault(printer.id, set())
  4556. try:
  4557. client.set_bed_temperature(bed_target)
  4558. pin.add("bed")
  4559. self._preheat_pin_bed[printer.id] = bed_target
  4560. except Exception as exc:
  4561. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  4562. if supports_airduct(model):
  4563. cur_airduct = getattr(cur, "airduct_mode", None)
  4564. if cur_airduct != _AIRDUCT_MODE_HEATING:
  4565. try:
  4566. client.set_airduct_mode("heating")
  4567. # Only undo what we can see we replaced. `None`
  4568. # means no mode has been observed yet, and
  4569. # rolling that back to cooling would assert a
  4570. # state the printer never reported.
  4571. if cur_airduct == _AIRDUCT_MODE_COOLING:
  4572. pin.add("airduct")
  4573. except Exception as exc:
  4574. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  4575. if has_heater:
  4576. try:
  4577. client.set_chamber_temperature(chamber_target)
  4578. pin.add("chamber")
  4579. except Exception as exc:
  4580. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  4581. return True
  4582. logger.info(
  4583. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  4584. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  4585. item.id,
  4586. bed_target,
  4587. chamber_target if do_chamber else 0,
  4588. chamber_source,
  4589. override,
  4590. model,
  4591. has_heater,
  4592. has_sensor,
  4593. max_wait,
  4594. soak_seconds,
  4595. )
  4596. # Preheat rollback registry: everything we set below is recorded here so
  4597. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  4598. # (bed off, chamber off, airduct back to cooling) on any non-success
  4599. # exit. Populated as each command succeeds; consumed and cleared by
  4600. # `_dispatch_one`.
  4601. pin = self._preheat_pin.setdefault(printer.id, set())
  4602. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  4603. # cache the target locally so the polling reads below see consistent
  4604. # state (firmware MQTT echoes lag by ~1s).
  4605. try:
  4606. client.set_bed_temperature(bed_target)
  4607. pin.add("bed")
  4608. self._preheat_pin_bed[printer.id] = bed_target
  4609. except Exception as exc:
  4610. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  4611. return True
  4612. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  4613. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  4614. # left it on, regardless of M141. Default cooling actively vents the
  4615. # chamber, so a `chamber_target > 0` print with the flap stuck in
  4616. # cooling never converges — the heater fights the open exhaust. We
  4617. # flip the flap BEFORE M141 to "heating" when the preheat wants
  4618. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  4619. # on an H2D that was previously running ABS would otherwise stay in
  4620. # heating mode and overheat PLA). The current-state read keeps the
  4621. # command idempotent — no MQTT chatter when the flap is already where
  4622. # we want it.
  4623. if supports_airduct(model):
  4624. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  4625. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  4626. current_state = printer_manager.get_status(printer.id)
  4627. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  4628. if current_airduct != desired_id:
  4629. try:
  4630. client.set_airduct_mode(desired_airduct)
  4631. # As in the fast path: only pin a rollback for a flap we
  4632. # saw in cooling. `current_airduct` of None means no mode
  4633. # has been observed, so there is nothing to restore to.
  4634. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  4635. pin.add("airduct")
  4636. except Exception as exc:
  4637. logger.warning(
  4638. "Queue item %s: preheat airduct %s mode failed: %s",
  4639. item.id,
  4640. desired_airduct,
  4641. exc,
  4642. )
  4643. if do_chamber and has_heater:
  4644. try:
  4645. client.set_chamber_temperature(chamber_target)
  4646. pin.add("chamber")
  4647. except Exception as exc:
  4648. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  4649. # Release the pooled DB connection before the (potentially many-minute)
  4650. # heat-soak wait below (#2572). Every setting this method needs is read
  4651. # above; the wait/soak loop only polls printer_manager state and sleeps —
  4652. # it never touches the DB. Without this the caller's transaction sat
  4653. # "idle in transaction" for the whole soak, pinning one pooled connection
  4654. # per preheating printer. expire_on_commit=False keeps item/printer
  4655. # readable afterwards; there are no pending writes to lose here.
  4656. await db.commit()
  4657. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  4658. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  4659. # Poll every 3s — frequent enough for responsive logging without
  4660. # spamming the MQTT state stream. The "converged" predicate is:
  4661. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  4662. # AND
  4663. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  4664. BED_TOLERANCE = 2.0
  4665. CHAMBER_TOLERANCE = 2.0
  4666. POLL_INTERVAL = 3.0
  4667. deadline = asyncio.get_event_loop().time() + max_wait
  4668. while True:
  4669. state = printer_manager.get_status(printer.id)
  4670. if state is None:
  4671. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  4672. break
  4673. temps = state.temperatures or {}
  4674. bed_now = float(temps.get("bed", 0) or 0)
  4675. chamber_now = float(temps.get("chamber", 0) or 0)
  4676. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  4677. if not do_chamber:
  4678. chamber_ok = True # phase disabled or model has neither sensor nor heater
  4679. elif not has_sensor:
  4680. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  4681. else:
  4682. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  4683. if bed_ok and chamber_ok:
  4684. logger.info(
  4685. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  4686. item.id,
  4687. bed_now,
  4688. chamber_now,
  4689. )
  4690. break
  4691. if asyncio.get_event_loop().time() >= deadline:
  4692. logger.info(
  4693. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  4694. item.id,
  4695. bed_now,
  4696. bed_target,
  4697. chamber_now,
  4698. chamber_target if do_chamber else 0,
  4699. )
  4700. break
  4701. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  4702. logger.info(
  4703. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  4704. item.id,
  4705. )
  4706. return False
  4707. if soak_seconds > 0:
  4708. if do_chamber and has_sensor:
  4709. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  4710. else:
  4711. remaining = soak_seconds # no sensor — can't verify history, run full soak
  4712. if remaining > 0:
  4713. logger.info(
  4714. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  4715. "has been above target for ~%ds already)",
  4716. item.id,
  4717. remaining,
  4718. soak_seconds,
  4719. soak_seconds - remaining,
  4720. )
  4721. if not await self._preheat_sleep(item.id, remaining):
  4722. logger.info(
  4723. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  4724. item.id,
  4725. )
  4726. return False
  4727. else:
  4728. logger.info(
  4729. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  4730. item.id,
  4731. chamber_target,
  4732. soak_seconds,
  4733. )
  4734. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  4735. return True
  4736. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  4737. """Turn on smart plug and wait for printer to connect.
  4738. Returns True if printer connected successfully within timeout.
  4739. """
  4740. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  4741. service = await smart_plug_manager.get_service_for_plug(plug, db)
  4742. # Check current plug state
  4743. status = await service.get_status(plug)
  4744. if not status.get("reachable"):
  4745. logger.warning("Smart plug '%s' is not reachable", plug.name)
  4746. return False
  4747. # Turn on if not already on
  4748. if status.get("state") != "ON":
  4749. success = await service.turn_on(plug)
  4750. if not success:
  4751. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  4752. return False
  4753. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  4754. # Get printer from database for connection
  4755. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4756. printer = result.scalar_one_or_none()
  4757. if not printer:
  4758. logger.error("Printer %s not found in database", printer_id)
  4759. return False
  4760. # Wait for printer to boot (give it some time before trying to connect)
  4761. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  4762. await asyncio.sleep(30)
  4763. # Try to connect to the printer periodically
  4764. elapsed = 30 # Already waited 30s
  4765. while elapsed < self._power_on_wait_time:
  4766. # Try to connect
  4767. logger.info("Attempting to connect to printer %s...", printer_id)
  4768. try:
  4769. connected = await printer_manager.connect_printer(printer)
  4770. if connected:
  4771. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  4772. # Give it a moment to stabilize and get status
  4773. await asyncio.sleep(5)
  4774. return True
  4775. except Exception as e:
  4776. logger.debug("Connection attempt failed: %s", e)
  4777. await asyncio.sleep(self._power_on_check_interval)
  4778. elapsed += self._power_on_check_interval
  4779. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  4780. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  4781. return False
  4782. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  4783. """Check if the previous print on this printer succeeded.
  4784. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  4785. deliberate action, not a failure, so subsequent items should still
  4786. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  4787. a skip isn't an actual print attempt, so it must not gate downstream
  4788. items — counting it as a failed predecessor was the cascade bug that
  4789. let a single cancellation block 18 items over 3 days for the reporter.
  4790. Only `failed` and `aborted` — real print-attempt failures — block.
  4791. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  4792. action — #1818) are also excluded from the lookback so the user can
  4793. clear the gate after fixing the physical issue without having to
  4794. re-queue every downstream job.
  4795. """
  4796. result = await db.execute(
  4797. select(PrintQueueItem)
  4798. .where(PrintQueueItem.printer_id == item.printer_id)
  4799. .where(PrintQueueItem.id != item.id)
  4800. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  4801. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  4802. .order_by(PrintQueueItem.completed_at.desc())
  4803. .limit(1)
  4804. )
  4805. prev_item = result.scalar_one_or_none()
  4806. # If no previous item, assume success (first in queue)
  4807. if not prev_item:
  4808. return True
  4809. return prev_item.status in ("completed", "cancelled")
  4810. async def _repoint_siblings_at_archive(
  4811. self,
  4812. db: AsyncSession,
  4813. *,
  4814. consumed_library_file_id: int,
  4815. archive_id: int,
  4816. dispatched_item_id: int,
  4817. ) -> int:
  4818. """Move the other queue items off a library row that is about to be deleted (#2819).
  4819. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  4820. upload-and-print flow uploads a transient file, prints it, and deletes it.
  4821. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  4822. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  4823. clones, so the first dispatch could pull the file out from under rows that
  4824. had not run yet. What those rows did next depended on the database, and
  4825. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  4826. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  4827. they were left pointing at a row that no longer existed, failing with
  4828. "Library file not found" whenever someone started them -- or sitting
  4829. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  4830. constraint, so there the rows were deleted outright and the queued copies
  4831. simply vanished, with no error and no history.
  4832. The archive holds its own copy of the 3MF, so the remaining copies can print
  4833. from it instead. Two things happen here, and both must happen *before* the
  4834. delete -- afterwards there is nothing left to repair on PostgreSQL:
  4835. * every row still naming the file has ``library_file_id`` cleared, which is
  4836. what takes it out of the cascade's reach. That covers rows this cannot
  4837. re-point as well -- a copy already printing from its own archive, and the
  4838. finished ones, which are not spare parts but the record a batch order
  4839. counts its progress from.
  4840. * the rows that still need something to print are pointed at the archive.
  4841. Returns how many items were re-pointed.
  4842. """
  4843. variant_item_ids = (
  4844. (
  4845. await db.execute(
  4846. select(PrintQueueVariant.queue_item_id).where(
  4847. PrintQueueVariant.library_file_id == consumed_library_file_id
  4848. )
  4849. )
  4850. )
  4851. .scalars()
  4852. .all()
  4853. )
  4854. # Candidate rows naming the consumed file have to go rather than be
  4855. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  4856. # one out of the cascade. This is what PostgreSQL already does, and
  4857. # _candidates_for skips such a variant on SQLite anyway, so no selection
  4858. # outcome changes -- the two backends simply stop disagreeing about
  4859. # whether the row is still there.
  4860. #
  4861. # It also has to happen before the re-point below: a cross-model item
  4862. # (#671) picks a variant every pass and folds it onto the row, and
  4863. # _resolve_variant clears archive_id as it does so, which would undo the
  4864. # re-point on the very next lap.
  4865. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  4866. # An item left with other candidates still has somewhere to go, and those
  4867. # carry their own target model -- pointing it at this archive would print a
  4868. # file the matcher never chose. It is excluded from the re-point and simply
  4869. # re-resolves against what is left.
  4870. surviving_variant_item_ids = set(
  4871. (
  4872. await db.execute(
  4873. select(PrintQueueVariant.queue_item_id).where(
  4874. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  4875. )
  4876. )
  4877. )
  4878. .scalars()
  4879. .all()
  4880. )
  4881. repoint_ids = set(
  4882. (
  4883. await db.execute(
  4884. select(PrintQueueItem.id)
  4885. .where(PrintQueueItem.id != dispatched_item_id)
  4886. .where(PrintQueueItem.archive_id.is_(None))
  4887. # "skipped" belongs here with the two live states: it is not
  4888. # terminal. Clearing a printer's previous-success gate puts
  4889. # every item skipped by it back to "pending"
  4890. # (resume_after_failure), and one restored onto a deleted
  4891. # file is the same orphan by a slower route. "failed",
  4892. # "cancelled", "aborted" and "completed" never return.
  4893. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  4894. .where(
  4895. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  4896. )
  4897. .where(
  4898. or_(
  4899. PrintQueueItem.library_file_id == consumed_library_file_id,
  4900. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  4901. )
  4902. )
  4903. )
  4904. )
  4905. .scalars()
  4906. .all()
  4907. )
  4908. if repoint_ids:
  4909. await db.execute(
  4910. update(PrintQueueItem)
  4911. .where(PrintQueueItem.id.in_(repoint_ids))
  4912. .values(
  4913. archive_id=archive_id,
  4914. library_file_id=None,
  4915. # The file this flag named is already consumed. Leaving it set
  4916. # would arm every re-pointed copy to delete whatever library
  4917. # row it is next given.
  4918. cleanup_library_after_dispatch=False,
  4919. )
  4920. )
  4921. logger.info(
  4922. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  4923. sorted(repoint_ids),
  4924. archive_id,
  4925. consumed_library_file_id,
  4926. dispatched_item_id,
  4927. )
  4928. # Everything else that still names the file: taken out of the cascade's
  4929. # reach without touching what it prints. The file is gone either way; what
  4930. # this preserves is the row.
  4931. await db.execute(
  4932. update(PrintQueueItem)
  4933. .where(PrintQueueItem.id != dispatched_item_id)
  4934. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  4935. .values(library_file_id=None)
  4936. )
  4937. return len(repoint_ids)
  4938. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  4939. """Schedule power-off if the queue item enabled auto_off_after.
  4940. Delegates to the smart-plug manager so the off honours each plug's
  4941. configured strategy (time delay or temperature threshold), is cancelled
  4942. if the printer starts printing again, and never cuts power on a loaded
  4943. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  4944. powered off on the timeout regardless of print state.
  4945. """
  4946. if not item.auto_off_after:
  4947. return
  4948. try:
  4949. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  4950. except Exception as e:
  4951. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  4952. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  4953. """Get a human-readable name for a queue item."""
  4954. if item.archive_id:
  4955. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  4956. archive = result.scalar_one_or_none()
  4957. if archive:
  4958. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  4959. if item.library_file_id:
  4960. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  4961. library_file = result.scalar_one_or_none()
  4962. if library_file:
  4963. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  4964. # A cross-model item (#671) holds no file of its own until a printer is
  4965. # picked, so name it after its first candidate — otherwise every waiting
  4966. # notification for one reads "Job #12". Queried rather than read off
  4967. # item.variants because callers outside the selection loop have not
  4968. # eager-loaded them, and a lazy load raises in async.
  4969. first_variant_name = (
  4970. await db.execute(
  4971. select(LibraryFile.filename)
  4972. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  4973. .where(PrintQueueVariant.queue_item_id == item.id)
  4974. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  4975. .limit(1)
  4976. )
  4977. ).scalar_one_or_none()
  4978. if first_variant_name:
  4979. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  4980. return f"Job #{item.id}"
  4981. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  4982. """Get printer by ID."""
  4983. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4984. return result.scalar_one_or_none()
  4985. async def _notify_dispatch_gave_up(
  4986. self,
  4987. queue_item_id: int,
  4988. printer_id: int,
  4989. created_by_id: int | None,
  4990. reason: str = "Printer accepted the file but never started printing",
  4991. ) -> None:
  4992. """Tell the user the queue item was failed after exhausting its dispatch retries.
  4993. Called from the watchdog, which is a background task with no session of
  4994. its own — hence the fresh one here. Best-effort throughout: the row is
  4995. already marked failed and that is the load-bearing part; a notification
  4996. provider being down must not resurrect the retry loop we just stopped.
  4997. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  4998. path passes its own, because "accepted the file but never started" is the
  4999. opposite of what happened there — the printer refused it outright (#2732).
  5000. """
  5001. try:
  5002. async with async_session() as db:
  5003. item = await db.get(PrintQueueItem, queue_item_id)
  5004. if not item:
  5005. return
  5006. job_name = await self._get_job_name(db, item)
  5007. printer = await self._get_printer(db, printer_id)
  5008. await notification_service.on_queue_job_failed(
  5009. job_name=job_name,
  5010. printer_id=printer_id,
  5011. printer_name=printer.name if printer else "Unknown",
  5012. reason=reason,
  5013. db=db,
  5014. )
  5015. except Exception as e:
  5016. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  5017. try:
  5018. await ws_manager.send_queue_item_failed(
  5019. user_id=created_by_id,
  5020. queue_item_id=queue_item_id,
  5021. printer_id=printer_id,
  5022. reason="never_started",
  5023. )
  5024. except Exception:
  5025. pass # toast is best-effort
  5026. async def _block_on_filament_deficit(
  5027. self,
  5028. db: AsyncSession,
  5029. item: PrintQueueItem,
  5030. ) -> bool:
  5031. """Promote the item to manual_start when the assigned spool is short (#1496).
  5032. Returns True when this dispatch attempt was blocked, False when the
  5033. item is clear to start. A previously-flagged item whose spool has
  5034. since been swapped to one with enough material clears the flag here
  5035. so the next scheduler tick dispatches it.
  5036. """
  5037. # User has explicitly acknowledged the deficit ("Print Anyway") —
  5038. # don't re-flag, don't even compute. Without this short-circuit the
  5039. # scheduler bounces between "user said anyway" (route clears
  5040. # manual_start) and "scheduler re-blocked" (this method re-flags it
  5041. # on identical spool state) (#1698-followup).
  5042. if item.skip_filament_check:
  5043. # #1762 diagnostic: surface the short-circuit at INFO so a
  5044. # future "Print Anyway didn't work" report (e.g. issue #1762
  5045. # comment 3) has actionable evidence in the support bundle
  5046. # without needing DEBUG enabled.
  5047. logger.info(
  5048. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  5049. item.id,
  5050. )
  5051. return False
  5052. try:
  5053. deficit = await compute_deficit_for_queue_item(db, item)
  5054. except Exception as e:
  5055. # Never let a flaky deficit check wedge the queue — log and let
  5056. # dispatch proceed. The PrintModal-side check still runs on the
  5057. # manual paths.
  5058. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  5059. return False
  5060. if deficit:
  5061. item.filament_short = True
  5062. item.manual_start = True
  5063. await db.commit()
  5064. job_name = await self._get_job_name(db, item)
  5065. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  5066. logger.info(
  5067. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  5068. item.id,
  5069. len(deficit),
  5070. )
  5071. try:
  5072. await notification_service.on_queue_job_waiting(
  5073. job_name=job_name,
  5074. target_model=(printer.model if printer else "") or "",
  5075. waiting_reason="filament_short",
  5076. db=db,
  5077. )
  5078. except Exception as e:
  5079. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  5080. return True
  5081. # No deficit — clear any stale flag from a previous tick.
  5082. if item.filament_short:
  5083. item.filament_short = False
  5084. await db.commit()
  5085. return False
  5086. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  5087. """Hand the queue item's owner to printer_manager so the
  5088. print-complete callback can credit the user in PrintLogEntry (#1670).
  5089. No-ops when the item has no `created_by_id` or the referenced user
  5090. row is missing (e.g. user deleted between queue-add and dispatch —
  5091. in that case the print log row falls back to the existing un-credited
  5092. behaviour rather than crashing the dispatch).
  5093. """
  5094. if not item.created_by_id:
  5095. return
  5096. from backend.app.models.user import User
  5097. owner = await db.get(User, item.created_by_id)
  5098. if owner:
  5099. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  5100. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  5101. """Upload file and start print for a queue item.
  5102. Supports two sources:
  5103. - archive_id: Print from an existing archive
  5104. - library_file_id: Print from a library file (file manager)
  5105. """
  5106. logger.info("Starting queue item %s", item.id)
  5107. # Also covers a reservation left active by a process interruption
  5108. # during an earlier attempt. `_dispatch_one` releases this marker on
  5109. # every exit unless start_print() confirms that the command was sent.
  5110. self._unconfirmed_budget_reservations.add(item.id)
  5111. try:
  5112. from backend.app.models.user import User
  5113. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  5114. # Recompute at the final authorization boundary as well as enqueue
  5115. # time. This covers rows created before the server-side estimate
  5116. # migration and prevents any alternate write path from weakening
  5117. # the budget reservation.
  5118. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  5119. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  5120. item.estimated_cost = await estimate_queue_source_cost(
  5121. db,
  5122. archive=archive,
  5123. library_file=library_file,
  5124. plate_id=item.plate_id,
  5125. ams_mapping=item.ams_mapping,
  5126. printer_id=item.printer_id,
  5127. )
  5128. await validate_print_budget(
  5129. db,
  5130. cost_center_id=item.cost_center_id,
  5131. estimated_cost=item.estimated_cost,
  5132. current_user=queue_user,
  5133. exclude_queue_item_id=item.id,
  5134. exclude_reservation_source_type="print_queue",
  5135. exclude_reservation_source_id=item.id,
  5136. )
  5137. budget_reservation = await create_budget_reservation(
  5138. db,
  5139. cost_center_id=item.cost_center_id,
  5140. estimated_cost=item.estimated_cost,
  5141. current_user=queue_user,
  5142. source_type="print_queue",
  5143. source_id=item.id,
  5144. print_archive_id=item.archive_id,
  5145. exclude_queue_item_id=item.id,
  5146. )
  5147. await db.commit()
  5148. except HTTPException as exc:
  5149. item.status = "failed"
  5150. item.error_message = str(exc.detail)
  5151. item.completed_at = datetime.now(timezone.utc)
  5152. await db.commit()
  5153. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  5154. await self._power_off_if_needed(db, item)
  5155. return
  5156. # Get printer first (needed for both paths)
  5157. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  5158. printer = result.scalar_one_or_none()
  5159. if not printer:
  5160. item.status = "failed"
  5161. item.error_message = "Printer not found"
  5162. item.completed_at = datetime.now(timezone.utc)
  5163. await db.commit()
  5164. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  5165. await self._power_off_if_needed(db, item)
  5166. return
  5167. # Check printer is connected
  5168. if not printer_manager.is_connected(item.printer_id):
  5169. item.status = "failed"
  5170. item.error_message = "Printer not connected"
  5171. item.completed_at = datetime.now(timezone.utc)
  5172. await db.commit()
  5173. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  5174. await self._power_off_if_needed(db, item)
  5175. return
  5176. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  5177. # `items` was taken at the top of check_queue, but the user can /cancel
  5178. # any pending row in the gap before we reach this point. Re-read the
  5179. # row and bail out cleanly instead of starting an FTP upload for a row
  5180. # that's already cancelled. The atomic CAS at the pending→printing
  5181. # transition (below, before start_print) is the load-bearing guard;
  5182. # this is the early-exit optimisation that avoids wasted FTP I/O.
  5183. await db.refresh(item)
  5184. if item.status != "pending":
  5185. logger.info(
  5186. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  5187. item.id,
  5188. item.status,
  5189. )
  5190. return
  5191. # Busy-printer guard (#2598). check_queue gates dispatch on
  5192. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  5193. # keep reporting FINISH for tens of seconds *after* it accepted a
  5194. # project_file (see the watchdog's phase-B note). A watchdog revert
  5195. # (#2555) also releases the dispatch hold, so a re-selected item can
  5196. # reach here while its printer has actually started printing. Uploading
  5197. # and dispatching then collides with the live job — the firmware answers
  5198. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  5199. # live state right before the expensive FTP upload: if the printer is
  5200. # busy, leave the item pending and let a later tick dispatch it once the
  5201. # printer is genuinely idle. No wasted upload, no collision.
  5202. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  5203. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  5204. logger.info(
  5205. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  5206. "leaving item pending for a later tick (#2598)",
  5207. item.id,
  5208. item.printer_id,
  5209. pre_dispatch_state,
  5210. )
  5211. return
  5212. # Determine source: archive or library file
  5213. archive = None
  5214. library_file = None
  5215. file_path = None
  5216. filename = None
  5217. cleanup_disk_paths: list[Path] = []
  5218. if item.archive_id:
  5219. # Print from archive
  5220. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  5221. archive = result.scalar_one_or_none()
  5222. if not archive:
  5223. item.status = "failed"
  5224. item.error_message = "Archive not found"
  5225. item.completed_at = datetime.now(timezone.utc)
  5226. await db.commit()
  5227. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  5228. await self._power_off_if_needed(db, item)
  5229. return
  5230. # Persist the queue item's selected plate onto the archive so Print
  5231. # History can show the actual plate after cancel/fail/complete (#2603).
  5232. # Only when the archive doesn't already carry one, so a reprint of a
  5233. # plate-specific archive isn't relabelled by a differently-plated
  5234. # queue row.
  5235. if archive.plate_id is None and item.plate_id is not None:
  5236. archive.plate_id = item.plate_id
  5237. file_path = settings.base_dir / archive.file_path
  5238. filename = archive.filename
  5239. elif item.library_file_id:
  5240. # Print from library file (file manager)
  5241. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  5242. library_file = result.scalar_one_or_none()
  5243. if not library_file:
  5244. # "Not found" covers two different situations and only one of
  5245. # them is recoverable, so say which. A trashed file is still
  5246. # there and restoring it makes a re-queued job work; a file that
  5247. # is really gone needs a different one. Neither is knowable from
  5248. # the queue, which is the whole complaint about this message.
  5249. trashed = (
  5250. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  5251. ).scalar_one_or_none()
  5252. item.status = "failed"
  5253. item.error_message = (
  5254. f"'{trashed}' is in the library trash — restore it and queue the print again"
  5255. if trashed
  5256. else "Library file not found — it was deleted after this job was queued"
  5257. )
  5258. item.completed_at = datetime.now(timezone.utc)
  5259. await db.commit()
  5260. logger.error(
  5261. "Queue item %s: library file %s is %s",
  5262. item.id,
  5263. item.library_file_id,
  5264. "in the trash" if trashed else "gone",
  5265. )
  5266. await self._power_off_if_needed(db, item)
  5267. return
  5268. # Library files store absolute paths
  5269. lib_path = Path(library_file.file_path)
  5270. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  5271. filename = library_file.filename
  5272. # Create archive from library file so usage tracking has access to the 3MF
  5273. queue_item_id = item.id
  5274. # Held separately: a cleanup dispatch clears item.library_file_id
  5275. # below, and the log line at the end of this block reported that
  5276. # cleared field -- so every consumed print logged "from library
  5277. # file None", which is the one case worth being able to trace.
  5278. source_library_file_id = item.library_file_id
  5279. try:
  5280. from backend.app.services.archive import ArchiveService
  5281. archive_service = ArchiveService(db)
  5282. archive = await archive_service.archive_print(
  5283. printer_id=item.printer_id,
  5284. source_file=file_path,
  5285. original_filename=filename,
  5286. created_by_id=item.created_by_id,
  5287. project_id=item.project_id,
  5288. cost_center_id=item.cost_center_id,
  5289. library_file_id=item.library_file_id, # per-file project progress (#1897)
  5290. plate_id=item.plate_id, # selected plate → Print History (#2603)
  5291. )
  5292. if archive:
  5293. item.archive_id = archive.id
  5294. if budget_reservation is not None:
  5295. budget_reservation.print_archive_id = archive.id
  5296. if item.cleanup_library_after_dispatch and not library_file.is_external:
  5297. consumed_library_file_id = library_file.id
  5298. item.library_file_id = None
  5299. cleanup_disk_paths.append(file_path)
  5300. if library_file.thumbnail_path:
  5301. thumb_path = Path(library_file.thumbnail_path)
  5302. if not thumb_path.is_absolute():
  5303. thumb_path = settings.base_dir / library_file.thumbnail_path
  5304. cleanup_disk_paths.append(thumb_path)
  5305. # Before the delete, not after: on PostgreSQL the FK
  5306. # cascade would already have taken these rows (#2819).
  5307. await self._repoint_siblings_at_archive(
  5308. db,
  5309. consumed_library_file_id=consumed_library_file_id,
  5310. archive_id=archive.id,
  5311. dispatched_item_id=item.id,
  5312. )
  5313. await db.delete(library_file)
  5314. file_path = settings.base_dir / archive.file_path
  5315. filename = archive.filename
  5316. # Commit, not flush — flush opens the SQLite write
  5317. # transaction (item.archive_id update + library_file
  5318. # delete) and would hold the WAL writer lock through the
  5319. # FTP upload below, causing "database is locked" cascades
  5320. # for sensor history + concurrent cancels (#1853).
  5321. await db.commit()
  5322. logger.info(
  5323. "Queue item %s: Created archive %s from library file %s",
  5324. item.id,
  5325. archive.id,
  5326. source_library_file_id,
  5327. )
  5328. except Exception as e:
  5329. logger.warning(
  5330. "Queue item %s: Failed to create archive from library file: %s",
  5331. queue_item_id,
  5332. e,
  5333. exc_info=True,
  5334. )
  5335. await db.rollback()
  5336. item = await db.get(PrintQueueItem, queue_item_id)
  5337. if item:
  5338. item.status = "failed"
  5339. item.error_message = "Failed to create archive from library file"
  5340. item.completed_at = datetime.now(timezone.utc)
  5341. await db.commit()
  5342. await self._power_off_if_needed(db, item)
  5343. return
  5344. if not archive:
  5345. item.status = "failed"
  5346. item.error_message = "Failed to create archive from library file"
  5347. item.completed_at = datetime.now(timezone.utc)
  5348. await db.commit()
  5349. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  5350. await self._power_off_if_needed(db, item)
  5351. return
  5352. else:
  5353. # Neither archive nor library file specified
  5354. item.status = "failed"
  5355. item.error_message = "No source file specified"
  5356. item.completed_at = datetime.now(timezone.utc)
  5357. await db.commit()
  5358. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  5359. await self._power_off_if_needed(db, item)
  5360. return
  5361. # Check file exists on disk
  5362. if not file_path.exists():
  5363. item.status = "failed"
  5364. item.error_message = "Source file not found on disk"
  5365. item.completed_at = datetime.now(timezone.utc)
  5366. await db.commit()
  5367. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  5368. await self._power_off_if_needed(db, item)
  5369. return
  5370. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  5371. # size dispatched to a printer with a different nozzle installed is
  5372. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  5373. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  5374. # gives the user no idea what went wrong. Catch it here, before we spend
  5375. # time preheating and uploading, and fail with an actionable message.
  5376. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  5377. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  5378. # the printer hasn't reported its nozzles yet, we fall through and let the
  5379. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  5380. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  5381. # as one of the two hotends is a 0.6.
  5382. #
  5383. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  5384. # (#2885): the printer fetches one as part of starting the print, so the
  5385. # set to test against is "reachable", not "currently mounted". This runs
  5386. # well before the rack picker at the bottom of this method, so without
  5387. # the rack in scope here that picker never got the chance to run.
  5388. sliced_nozzle = archive.nozzle_diameter if archive else None
  5389. if sliced_nozzle:
  5390. nozzle_status = printer_manager.get_status(item.printer_id)
  5391. installed = _installed_nozzle_diameters(nozzle_status)
  5392. rack = _rack_nozzle_diameters(nozzle_status)
  5393. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  5394. if mismatch_msg:
  5395. item.status = "failed"
  5396. item.error_message = mismatch_msg
  5397. item.completed_at = datetime.now(timezone.utc)
  5398. await db.commit()
  5399. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  5400. await notification_service.on_queue_job_failed(
  5401. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  5402. printer_id=printer.id,
  5403. printer_name=printer.name,
  5404. reason=mismatch_msg,
  5405. db=db,
  5406. )
  5407. try:
  5408. await ws_manager.send_queue_item_failed(
  5409. user_id=item.created_by_id,
  5410. queue_item_id=item.id,
  5411. printer_id=item.printer_id,
  5412. reason="nozzle_mismatch",
  5413. )
  5414. except Exception:
  5415. pass
  5416. await self._power_off_if_needed(db, item)
  5417. return
  5418. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  5419. # bed (and chamber, if applicable) is at temperature when the firmware
  5420. # starts the actual print routine. Best-effort: any failure logs and
  5421. # falls through to the normal upload+start path rather than turning a
  5422. # configuration issue into a failed queue item.
  5423. # Returns False only when the item was cancelled or deleted while the
  5424. # stage was holding at temperature. Uploading and starting it anyway
  5425. # would print a job the user has already called off, so abandon the
  5426. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  5427. if not await self._preheat_and_soak(db, item, printer, archive):
  5428. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  5429. return
  5430. # G-code injection for auto-print systems (#422)
  5431. injected_path = None
  5432. # #2547: tracked separately from `injected_path`, which is also set when
  5433. # only a START snippet was injected. Only an END snippet changes what the
  5434. # camera sees at print completion.
  5435. end_gcode_injected = False
  5436. if item.gcode_injection:
  5437. try:
  5438. snippets_raw = await self._get_setting(db, "gcode_snippets")
  5439. if snippets_raw:
  5440. snippets = json.loads(snippets_raw)
  5441. model_snippets = snippets.get(printer.model, {})
  5442. start_gc = (model_snippets.get("start_gcode") or "").strip()
  5443. end_gc = (model_snippets.get("end_gcode") or "").strip()
  5444. if start_gc or end_gc:
  5445. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  5446. injected_path = inject_gcode_into_3mf(
  5447. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  5448. )
  5449. if injected_path:
  5450. file_path = injected_path
  5451. end_gcode_injected = bool(end_gc)
  5452. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  5453. else:
  5454. logger.warning(
  5455. "Queue item %s: G-code injection returned no result, using original", item.id
  5456. )
  5457. except Exception as e:
  5458. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  5459. # #2547: the finish-photo path can't learn from telemetry that this print
  5460. # ends with user End G-code — which means the plate may be gone by the
  5461. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  5462. # the print once the printer confirms it running.
  5463. if end_gcode_injected:
  5464. print_dispatch_context.mark_pending(printer.id)
  5465. # Upload to root directory (not /cache/) - the start_print command references
  5466. # files by name only (ftp://{filename}), so they must be in the root
  5467. remote_filename = derive_remote_filename(filename)
  5468. remote_path = f"/{remote_filename}"
  5469. # Get FTP retry settings
  5470. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5471. logger.info(
  5472. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  5473. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  5474. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  5475. )
  5476. # Release the pooled DB connection before the FTP delete/upload (#2572).
  5477. # Every read this method needs (printer, archive/library, preheat) is
  5478. # done, and the library-file branch already committed its archive
  5479. # creation. Without this the transaction opened by the first SELECT above
  5480. # stays "idle in transaction" for the entire upload — multiple seconds
  5481. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  5482. # a farm dispatching many jobs at once then exhausts the pool. This was
  5483. # correlated to an exact idle-in-transaction session on a 93-printer farm
  5484. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  5485. # readable; the status writes below (upload-failure path and the
  5486. # pending->printing CAS) transparently open a fresh transaction.
  5487. await db.commit()
  5488. # Where this printer's handshake cool-off stood before we touched it.
  5489. # The delete and upload below ignore the cool-off, so finding one armed
  5490. # afterwards proves nothing on its own -- a background timelapse or 3MF
  5491. # fetch for an earlier print could have armed it minutes ago. A deadline
  5492. # that MOVED, though, can only mean a handshake failed during this
  5493. # dispatch, which is what the failure message needs to know (#2898).
  5494. cooloff_before = ftps_handshake_cooloff_deadline(printer.ip_address)
  5495. # Delete existing file if present (avoids 553 error on overwrite)
  5496. try:
  5497. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  5498. delete_result = await delete_file_async(
  5499. printer.ip_address,
  5500. printer.access_code,
  5501. remote_path,
  5502. socket_timeout=ftp_timeout,
  5503. printer_model=printer.model,
  5504. # This delete and the upload below are one bounded, user-initiated
  5505. # unit -- at most nine connections -- so neither skips on the
  5506. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  5507. # trace this delete took the TLS failure and armed the cool-off,
  5508. # and the upload's four attempts were then spent against it
  5509. # without a socket being opened.
  5510. respect_handshake_cooloff=False,
  5511. )
  5512. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  5513. except Exception as e:
  5514. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  5515. # Dispatch toast — announce the upload start with the total byte
  5516. # count so the frontend can render an honest progress bar.
  5517. toast_uid = item.created_by_id
  5518. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  5519. try:
  5520. total_bytes = file_path.stat().st_size
  5521. except OSError:
  5522. total_bytes = 0
  5523. try:
  5524. await ws_manager.send_queue_item_uploading(
  5525. user_id=toast_uid,
  5526. queue_item_id=item.id,
  5527. printer_id=item.printer_id,
  5528. printer_name=printer.name,
  5529. file_name=toast_file_name,
  5530. total_bytes=total_bytes,
  5531. )
  5532. except Exception:
  5533. pass # toast is best-effort
  5534. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  5535. # A deadline expiry gets its own message: "check your SD card" is the
  5536. # wrong advice for a link that was simply too slow to finish (#2529).
  5537. upload_error: str | None = None
  5538. try:
  5539. if ftp_retry_enabled:
  5540. uploaded = await with_ftp_retry(
  5541. upload_file_async,
  5542. printer.ip_address,
  5543. printer.access_code,
  5544. file_path,
  5545. remote_path,
  5546. socket_timeout=ftp_timeout,
  5547. printer_model=printer.model,
  5548. progress_callback=progress_bridge,
  5549. respect_handshake_cooloff=False,
  5550. max_retries=ftp_retry_count,
  5551. retry_delay=ftp_retry_delay,
  5552. operation_name=f"Upload print to {printer.name}",
  5553. )
  5554. else:
  5555. uploaded = await upload_file_async(
  5556. printer.ip_address,
  5557. printer.access_code,
  5558. file_path,
  5559. remote_path,
  5560. socket_timeout=ftp_timeout,
  5561. printer_model=printer.model,
  5562. progress_callback=progress_bridge,
  5563. respect_handshake_cooloff=False,
  5564. )
  5565. except UploadCancelled as e:
  5566. uploaded = False
  5567. upload_error = (
  5568. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  5569. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  5570. )
  5571. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  5572. except Exception as e:
  5573. uploaded = False
  5574. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  5575. # Clean up injected temp file after upload attempt
  5576. if injected_path and injected_path.exists():
  5577. injected_path.unlink(missing_ok=True)
  5578. if not uploaded:
  5579. # A cool-off armed during this dispatch is proof the printer
  5580. # answered port 990 with something that was not TLS, so the SD card
  5581. # is the wrong thing to go and look at -- and it is what three of
  5582. # #2898's queue items were sent to check. "During this dispatch" is
  5583. # load-bearing: an unrelated background fetch can leave a cool-off
  5584. # armed for minutes, and blaming TLS for an upload that actually hit
  5585. # a full disk would repeat the mistake in the other direction.
  5586. cooloff_after = ftps_handshake_cooloff_deadline(printer.ip_address)
  5587. if not upload_error and cooloff_after is not None and cooloff_after != cooloff_before:
  5588. upload_error = (
  5589. "The printer's file service did not answer over TLS, so the file could not be sent to it. "
  5590. "Its SD card is not involved. Bambuddy will leave this printer alone for a few minutes "
  5591. "before trying again."
  5592. )
  5593. error_msg = upload_error or (
  5594. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  5595. "See server logs for detailed diagnostics."
  5596. )
  5597. item.status = "failed"
  5598. item.error_message = error_msg
  5599. item.completed_at = datetime.now(timezone.utc)
  5600. await db.commit()
  5601. logger.error(
  5602. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  5603. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  5604. )
  5605. # Send failure notification
  5606. await notification_service.on_queue_job_failed(
  5607. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  5608. printer_id=printer.id,
  5609. printer_name=printer.name,
  5610. reason="Failed to upload file to printer",
  5611. db=db,
  5612. )
  5613. try:
  5614. await ws_manager.send_queue_item_failed(
  5615. user_id=toast_uid,
  5616. queue_item_id=item.id,
  5617. printer_id=item.printer_id,
  5618. reason="upload_failed",
  5619. )
  5620. except Exception:
  5621. pass
  5622. await self._power_off_if_needed(db, item)
  5623. return
  5624. # Parse AMS mapping if stored
  5625. ams_mapping = None
  5626. if item.ams_mapping:
  5627. try:
  5628. ams_mapping = json.loads(item.ams_mapping)
  5629. except json.JSONDecodeError:
  5630. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  5631. # Register as expected print so we don't create a duplicate archive
  5632. # Only applicable for archive-based prints
  5633. if archive:
  5634. from backend.app.main import register_expected_print
  5635. register_expected_print(
  5636. item.printer_id,
  5637. remote_filename,
  5638. archive.id,
  5639. ams_mapping=ams_mapping,
  5640. created_by_id=item.created_by_id,
  5641. cost_center_id=item.cost_center_id,
  5642. plate_id=item.plate_id,
  5643. )
  5644. # Registration happens before the print command by necessity (the
  5645. # printer can report the print before the send returns), so record
  5646. # what to undo if we never get as far as sending. `_dispatch_one`
  5647. # rolls back anything still pending here on every exit — exception,
  5648. # early return, or cancel winning the CAS below.
  5649. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  5650. # Propagate the queue item's owner into printer_manager so the
  5651. # print-complete callback can credit the user in the PrintLogEntry
  5652. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  5653. # items) or when the user clicks the manual-start button.
  5654. await self._propagate_owner_to_printer_manager(db, item)
  5655. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  5656. # This prevents phantom reprints if the backend crashes/restarts after the
  5657. # print command is sent but before the status update is committed.
  5658. # If we crash after this commit but before start_print(), the item will be
  5659. # in "printing" status without actually printing - but that's safer than
  5660. # accidentally reprinting the same file hours later.
  5661. #
  5662. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  5663. # initial pending read at the top of check_queue and this point) flips
  5664. # the row to "cancelled" in a separate session. Without the WHERE
  5665. # status='pending' clause, the unconditional update here would silently
  5666. # overwrite that cancellation and we'd ship the MQTT start_print below
  5667. # — printer obeys, user sees "I pressed cancel and the print started".
  5668. # rowcount==0 means the user won the race; bail out, best-effort delete
  5669. # the file we just uploaded, do NOT send start_print.
  5670. now_utc = datetime.now(timezone.utc)
  5671. billing_run_id = str(uuid.uuid4())
  5672. cas = await db.execute(
  5673. update(PrintQueueItem)
  5674. .where(PrintQueueItem.id == item.id)
  5675. .where(PrintQueueItem.status == "pending")
  5676. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  5677. )
  5678. await db.commit()
  5679. if cas.rowcount == 0:
  5680. logger.info(
  5681. "Queue item %s no longer pending at print-command time "
  5682. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  5683. item.id,
  5684. )
  5685. try:
  5686. await delete_file_async(
  5687. printer.ip_address,
  5688. printer.access_code,
  5689. remote_path,
  5690. socket_timeout=ftp_timeout,
  5691. printer_model=printer.model,
  5692. )
  5693. except Exception as cleanup_err:
  5694. logger.debug(
  5695. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  5696. item.id,
  5697. cleanup_err,
  5698. )
  5699. try:
  5700. await ws_manager.send_queue_item_failed(
  5701. user_id=toast_uid,
  5702. queue_item_id=item.id,
  5703. printer_id=item.printer_id,
  5704. reason="cancelled_mid_dispatch",
  5705. )
  5706. except Exception:
  5707. pass
  5708. return
  5709. # Sync the in-memory item so subsequent code that reads item.status /
  5710. # item.started_at sees the values we just persisted.
  5711. item.status = "printing"
  5712. item.started_at = now_utc
  5713. item.billing_run_id = billing_run_id
  5714. if archive is not None:
  5715. archive.billing_run_id = billing_run_id
  5716. # Legacy transaction deletion used an archive-wide skip flag.
  5717. # A newly dispatched run has its own UUID/tombstone, so it must be
  5718. # billable independently of any older deleted run on this archive.
  5719. archive.wallet_charge_skipped = False
  5720. # Persist before MQTT send so completion and restart recovery can
  5721. # always recover the internal billing identity.
  5722. await db.commit()
  5723. for cleanup_path in cleanup_disk_paths:
  5724. try:
  5725. if cleanup_path.exists():
  5726. cleanup_path.unlink()
  5727. except OSError as cleanup_err:
  5728. logger.warning(
  5729. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  5730. json.dumps(
  5731. {
  5732. "queue_item_id": item.id,
  5733. "path": str(cleanup_path),
  5734. "error": str(cleanup_err),
  5735. },
  5736. sort_keys=True,
  5737. ),
  5738. )
  5739. # Clear the awaiting-plate-clear flag now that we're starting a new print
  5740. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  5741. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  5742. # Capture state before dispatch so the watchdog can detect whether the
  5743. # printer actually transitioned (#967). Also capture subtask_id so the
  5744. # watchdog can recognise "command landed but state hasn't flipped yet"
  5745. # on slow H2D transitions (#1078).
  5746. pre_status = printer_manager.get_status(item.printer_id)
  5747. pre_state = getattr(pre_status, "state", None) if pre_status else None
  5748. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  5749. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  5750. # #1721: respect the user's explicit timelapse choice. The #1397
  5751. # force-on at dispatch was removed because it caused per-layer nozzle
  5752. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  5753. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  5754. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  5755. # FINISH-state fallback — no need to force a video.
  5756. effective_timelapse = bool(item.timelapse)
  5757. # Nozzle-rack fallback (#2800). A job that never passed through the
  5758. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  5759. # dispatches with no nozzle field at all and chooses for itself — which
  5760. # is how a print levelled on one hotend and then printed on another,
  5761. # millimetres above the plate. Derive the per-slot extruder assignment
  5762. # from the file being dispatched.
  5763. #
  5764. # Done here rather than at queue time because this is the first point
  5765. # that knows both the actual printer and the actual file: an item can
  5766. # be created without a printer (model-based assignment), reassigned
  5767. # afterwards, or have its file swapped for a G-code-injected copy just
  5768. # above. Every queue-creation path — the print dialog, a bulk library
  5769. # add, the webhook, a pipeline run — is covered by the one call.
  5770. # Skipped when the item already carries a Bambu Studio capture: that
  5771. # one wins downstream anyway, so reading the 3MF again would be work
  5772. # thrown away on every dispatch.
  5773. # Rack position resolution (#1784), tried before the #2800 fallback
  5774. # below because it can express what that one cannot: a plate wanting a
  5775. # *different* hotend off the rack per filament group. The position per
  5776. # group is the operator's pick — the 3MF states it nowhere, proven by
  5777. # sending one plate twice with different picks and finding the two
  5778. # files identical bar float noise — so it is resolved here against the
  5779. # rack as it stands right now, after the upload, not at queue time.
  5780. resolved_nozzle_mapping = None
  5781. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  5782. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=item.plate_id or 1)
  5783. if rack_plan is not None:
  5784. try:
  5785. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  5786. except (json.JSONDecodeError, TypeError):
  5787. stored_choice = {}
  5788. logger.warning(
  5789. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  5790. item.id,
  5791. item.nozzle_rack_choice,
  5792. )
  5793. # JSON object keys are strings; the groups are ints.
  5794. choice: dict[int, int] = {}
  5795. for key, value in (stored_choice or {}).items():
  5796. try:
  5797. choice[int(key)] = int(value)
  5798. except (TypeError, ValueError):
  5799. continue
  5800. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  5801. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  5802. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  5803. )
  5804. if resolved_nozzle_mapping is None and choice:
  5805. # An explicit pick that no longer holds stops the print. The
  5806. # operator named a hotend; printing from a different one is
  5807. # how a plate gets levelled on one nozzle and drawn with
  5808. # another, millimetres above the bed. Nothing has been sent
  5809. # to the printer yet, so failing here costs only the upload.
  5810. item.status = "failed"
  5811. item.error_message = (
  5812. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  5813. "Edit the item to choose another position."
  5814. )
  5815. item.completed_at = datetime.now(timezone.utc)
  5816. await db.commit()
  5817. logger.warning(
  5818. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  5819. item.id,
  5820. printer.name,
  5821. rack_error,
  5822. choice,
  5823. [slot.get("id") for slot in live_rack],
  5824. )
  5825. await notification_service.on_queue_job_failed(
  5826. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  5827. printer_id=printer.id,
  5828. printer_name=printer.name,
  5829. reason=item.error_message,
  5830. db=db,
  5831. )
  5832. try:
  5833. await ws_manager.send_queue_item_failed(
  5834. user_id=toast_uid,
  5835. queue_item_id=item.id,
  5836. printer_id=item.printer_id,
  5837. reason="nozzle_rack_pick_stale",
  5838. )
  5839. except Exception:
  5840. pass # Best-effort — don't fail the error handler
  5841. # The file is already on the SD card by this point, and a
  5842. # 3MF left there is a phantom print waiting to be started
  5843. # from the touchscreen. Same cleanup the start_print
  5844. # failure path below does, for the same reason.
  5845. try:
  5846. await delete_file_async(
  5847. printer.ip_address,
  5848. printer.access_code,
  5849. remote_path,
  5850. printer_model=printer.model,
  5851. )
  5852. except Exception:
  5853. pass # Best-effort — don't fail the error handler
  5854. return
  5855. if resolved_nozzle_mapping is None:
  5856. # Nothing was picked and nothing could be assigned. Falls
  5857. # through to the #2800 path, which is what ran before this
  5858. # existed — strictly not worse than today.
  5859. logger.info(
  5860. "Queue item %s: no rack positions assignable (%s); falling back",
  5861. item.id,
  5862. rack_error,
  5863. )
  5864. else:
  5865. logger.info(
  5866. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  5867. item.id,
  5868. resolved_nozzle_mapping,
  5869. rack_plan.slot_groups,
  5870. choice or "auto",
  5871. )
  5872. nozzle_slot_extruders = None
  5873. if (
  5874. not item.nozzle_mapping
  5875. and resolved_nozzle_mapping is None
  5876. and file_path is not None
  5877. and is_nozzle_rack_model(printer.model)
  5878. ):
  5879. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=item.plate_id or 1)
  5880. if slot_extruders:
  5881. nozzle_slot_extruders = json.dumps(slot_extruders)
  5882. # Start the print with AMS mapping, plate_id and print options.
  5883. # nozzle_mapping rides through verbatim — JSON string captured from
  5884. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  5885. # parses + injects it only for dual-nozzle models so a null on every
  5886. # other model is a transparent pass-through. The rack fallback is
  5887. # resolved down there too, where the live rack position is known.
  5888. started = printer_manager.start_print(
  5889. item.printer_id,
  5890. remote_filename,
  5891. plate_id=item.plate_id or 1,
  5892. ams_mapping=ams_mapping,
  5893. bed_levelling=item.bed_levelling,
  5894. flow_cali=item.flow_cali,
  5895. vibration_cali=item.vibration_cali,
  5896. layer_inspect=item.layer_inspect,
  5897. timelapse=effective_timelapse,
  5898. use_ams=item.use_ams,
  5899. nozzle_offset_cali=item.nozzle_offset_cali,
  5900. nozzle_mapping=item.nozzle_mapping
  5901. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  5902. nozzle_slot_extruders=nozzle_slot_extruders,
  5903. )
  5904. if started:
  5905. # The command is away, so the expectation is now legitimate and must
  5906. # survive. Anything still in this dict when _dispatch_one exits gets
  5907. # rolled back.
  5908. self._unconfirmed_expected_print.pop(item.id, None)
  5909. self._unconfirmed_budget_reservations.discard(item.id)
  5910. # Handoff to the print's own gcode: keep whatever preheat set (bed
  5911. # target, chamber target, airduct heating) — the gcode owns
  5912. # heater/flap control from here. Clearing the pin prevents
  5913. # `_dispatch_one`'s finally from unwinding a live print.
  5914. self._preheat_pin.pop(item.printer_id, None)
  5915. self._preheat_pin_bed.pop(item.printer_id, None)
  5916. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  5917. # No dispatch-toast event here: the legacy bg-dispatch path kept
  5918. # status='processing' from upload start until the printer acked
  5919. # (or timed out). The frontend derives "Awaiting printer…" purely
  5920. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  5921. # event would push the status chip out of 'PROCESSING' prematurely
  5922. # — which is exactly what the screenshot at #1625-followup
  5923. # complained about.
  5924. # Register the local 3MF in the cover-cache so /cover skips FTP
  5925. # (#1166 follow-up). file_path was resolved earlier from either the
  5926. # archive or the library file row.
  5927. if file_path is not None:
  5928. cache_3mf_download(item.printer_id, remote_filename, file_path)
  5929. # Hold the printer against further dispatches until the watchdog
  5930. # confirms the printer transitioned (or until the hard timeout).
  5931. # Prevents multi-plate batches from triple-dispatching onto the
  5932. # same H2D Pro while it digests the first project_file (#1157).
  5933. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  5934. # Watchdog: if the printer never transitions out of pre_state AND
  5935. # never advances subtask_id, the MQTT publish was accepted locally but
  5936. # didn't reach the printer (half-broken session — same shape as
  5937. # #887/#936). Revert the queue item so the next dispatch can pick it
  5938. # up instead of leaving it stuck in "printing" (#967). subtask_id
  5939. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  5940. # that would otherwise cause the item to re-dispatch as a reprint
  5941. # of the just-finished job (#1078).
  5942. if pre_state:
  5943. spawn_background_task(
  5944. self._watchdog_print_start(
  5945. item.id,
  5946. item.printer_id,
  5947. pre_state,
  5948. pre_subtask_id,
  5949. pre_gcode_file,
  5950. created_by_id=toast_uid,
  5951. ),
  5952. name=f"watchdog-print-start-{item.id}",
  5953. )
  5954. # Get estimated time for notification.
  5955. #
  5956. # This used to fall back to `library_file.print_time_seconds`, a column
  5957. # LibraryFile does not have — the print time it knows about lives in
  5958. # `file_metadata`. So a library print whose archive carried no parseable
  5959. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  5960. # AttributeError right here, *after* the printer had already been sent
  5961. # the job: the started-notification never fired, and the exception
  5962. # unwound the whole queue pass, so every other printer still waiting to
  5963. # be dispatched on that tick silently missed its turn.
  5964. #
  5965. # The queue item caches the print time at creation ("Cached from
  5966. # archive/library"), which is the value this was reaching for.
  5967. estimated_time = None
  5968. if archive and archive.print_time_seconds:
  5969. estimated_time = archive.print_time_seconds
  5970. elif item.print_time_seconds:
  5971. estimated_time = item.print_time_seconds
  5972. # Send job started notification
  5973. await notification_service.on_queue_job_started(
  5974. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  5975. printer_id=printer.id,
  5976. printer_name=printer.name,
  5977. db=db,
  5978. estimated_time=estimated_time,
  5979. )
  5980. # MQTT relay - publish queue job started
  5981. try:
  5982. from backend.app.services.mqtt_relay import mqtt_relay
  5983. await mqtt_relay.on_queue_job_started(
  5984. job_id=item.id,
  5985. filename=filename,
  5986. printer_id=printer.id,
  5987. printer_name=printer.name,
  5988. printer_serial=printer.serial_number,
  5989. )
  5990. except Exception:
  5991. pass # Don't fail if MQTT fails
  5992. else:
  5993. # Clean up uploaded file from SD card to prevent phantom prints
  5994. try:
  5995. await delete_file_async(
  5996. printer.ip_address,
  5997. printer.access_code,
  5998. remote_path,
  5999. printer_model=printer.model,
  6000. )
  6001. except Exception:
  6002. pass # Best-effort — don't fail the error handler
  6003. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  6004. # state can flip from idle to active in the window between the
  6005. # pre-dispatch check above and this publish (the FTP upload takes
  6006. # seconds); start_print() then refuses to send project_file to the
  6007. # now-busy printer and returns False. Failing the item here would be
  6008. # wrong — the printer is fine, it is simply busy — so revert to
  6009. # pending and let a later tick dispatch it once the printer is idle,
  6010. # exactly like the pre-dispatch guard. Only a start_print() False on
  6011. # an idle/unknown printer is a genuine command failure.
  6012. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  6013. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  6014. logger.info(
  6015. "Queue item %s: printer %s became busy (state=%s) before the start "
  6016. "command was sent — deferring, reverting item to pending (#2598)",
  6017. item.id,
  6018. item.printer_id,
  6019. post_dispatch_state,
  6020. )
  6021. item.status = "pending"
  6022. item.started_at = None
  6023. await db.commit()
  6024. return
  6025. # Print command failed - revert status
  6026. item.status = "failed"
  6027. item.error_message = "Failed to send print command to printer"
  6028. item.completed_at = datetime.now(timezone.utc)
  6029. await db.commit()
  6030. logger.error(
  6031. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  6032. f"printer_manager.start_print() returned False. "
  6033. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  6034. f"Check printer status and backend logs for details."
  6035. )
  6036. # Send failure notification
  6037. await notification_service.on_queue_job_failed(
  6038. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  6039. printer_id=printer.id,
  6040. printer_name=printer.name,
  6041. reason="Failed to send print command to printer - check printer connection and status",
  6042. db=db,
  6043. )
  6044. try:
  6045. await ws_manager.send_queue_item_failed(
  6046. user_id=toast_uid,
  6047. queue_item_id=item.id,
  6048. printer_id=item.printer_id,
  6049. reason="start_command_failed",
  6050. )
  6051. except Exception:
  6052. pass
  6053. await self._power_off_if_needed(db, item)
  6054. @staticmethod
  6055. async def _watchdog_print_start(
  6056. queue_item_id: int,
  6057. printer_id: int,
  6058. pre_state: str,
  6059. pre_subtask_id: str | None = None,
  6060. pre_gcode_file: str | None = None,
  6061. timeout: float = 90.0,
  6062. phase_b_timeout: float = 180.0,
  6063. poll_interval: float = 3.0,
  6064. created_by_id: int | None = None,
  6065. ) -> None:
  6066. """Revert a queue item if the printer never acknowledges the start command.
  6067. Bambuddy optimistically marks the queue item as "printing" right after the
  6068. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  6069. Phase A (up to ``timeout``): wait for either an active-state transition
  6070. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  6071. primary signal; subtask_id advance handles the H2D case where state can
  6072. sit at FINISH for ~50 s after the printer accepted ``project_file``
  6073. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  6074. was lost on a half-broken session (#887/#936) — revert and force
  6075. reconnect (the #967 recovery path).
  6076. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  6077. alone): keep watching for the active-state transition. subtask_id alone
  6078. proves the file landed but not that the printer started — and a printer
  6079. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  6080. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  6081. used to leave the queue item stuck in 'printing' forever because the
  6082. old watchdog returned success as soon as subtask_id advanced. If Phase
  6083. B times out, revert the queue item so the user can retry without
  6084. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  6085. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  6086. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  6087. transitions that also don't emit an early subtask_id tick.
  6088. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  6089. refuses to verify our commands will never start this job or any other,
  6090. so waiting out the full 270 s and re-uploading the 3MF twice more only
  6091. burns an upload slot the rest of the farm is queued behind — that path
  6092. is for a printer that might still come good, which this one cannot
  6093. (#2732). It fails the item on the spot with the actual reason instead.
  6094. """
  6095. last_status = None
  6096. landed_on_subtask = False
  6097. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  6098. # every push carrying an `hms` key, so the fault can come and go between
  6099. # 3-second polls. Seeing it once inside the dispatch window is enough.
  6100. command_rejected = False
  6101. # Latched for the same reason as command_rejected: drying can finish, or
  6102. # be stopped by the user, part-way through the dispatch window. Seeing it
  6103. # once is what matters — it is the state the printer was in when it
  6104. # declined to start (#2758).
  6105. drying_ams_ids: list[int] = []
  6106. deadline = time.monotonic() + timeout
  6107. while time.monotonic() < deadline:
  6108. await asyncio.sleep(poll_interval)
  6109. status = printer_manager.get_status(printer_id)
  6110. if not status:
  6111. # Printer disconnected — don't mess with the DB. Drop the
  6112. # in-memory dispatch hold too so a fresh dispatch can retry
  6113. # once the printer comes back; the hard timeout would
  6114. # otherwise hold the printer unnecessarily.
  6115. scheduler._release_dispatch_hold(printer_id)
  6116. return
  6117. last_status = status
  6118. if status.state in _ACTIVE_PRINT_STATES:
  6119. # Printer is actively processing the job — release the
  6120. # post-dispatch hold so the next pending item for this printer
  6121. # can be evaluated normally. We do NOT accept arbitrary state
  6122. # transitions: a printer going FINISH -> IDLE (user dismissed
  6123. # the post-print prompt without accepting our project_file)
  6124. # would otherwise look like "command landed" and leave the
  6125. # queue item stuck in 'printing' forever (#1370).
  6126. scheduler._release_dispatch_hold(printer_id)
  6127. try:
  6128. await ws_manager.send_queue_item_acked(
  6129. user_id=created_by_id,
  6130. queue_item_id=queue_item_id,
  6131. printer_id=printer_id,
  6132. )
  6133. except Exception:
  6134. pass
  6135. return
  6136. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  6137. # Checked only after the active-state exit above: a stale HMS left
  6138. # over from an earlier job must never abort a print that is visibly
  6139. # running. An actually-refused command leaves the printer idle, so
  6140. # this ordering costs the detection nothing.
  6141. if _mqtt_commands_rejected(status):
  6142. command_rejected = True
  6143. break
  6144. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  6145. # Phase A exit — printer accepted the file (subtask_id flipped
  6146. # to our submission id). Don't return yet: the printer may
  6147. # have accepted the command but never actually start (e.g.
  6148. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  6149. # B watches for the active-state transition.
  6150. landed_on_subtask = True
  6151. break
  6152. if landed_on_subtask and not command_rejected:
  6153. phase_b_deadline = time.monotonic() + phase_b_timeout
  6154. while time.monotonic() < phase_b_deadline:
  6155. await asyncio.sleep(poll_interval)
  6156. status = printer_manager.get_status(printer_id)
  6157. if not status:
  6158. scheduler._release_dispatch_hold(printer_id)
  6159. return
  6160. last_status = status
  6161. if status.state in _ACTIVE_PRINT_STATES:
  6162. scheduler._release_dispatch_hold(printer_id)
  6163. try:
  6164. await ws_manager.send_queue_item_acked(
  6165. user_id=created_by_id,
  6166. queue_item_id=queue_item_id,
  6167. printer_id=printer_id,
  6168. )
  6169. except Exception:
  6170. pass
  6171. return
  6172. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  6173. # Same ordering rule as Phase A: a running print wins over a
  6174. # lingering HMS.
  6175. if _mqtt_commands_rejected(status):
  6176. command_rejected = True
  6177. break
  6178. # No active-state transition. Revert the item so the scheduler can retry.
  6179. # Drop the in-memory hold so the retry isn't blocked by it.
  6180. scheduler._release_dispatch_hold(printer_id)
  6181. # Logged on every failed dispatch window, not just the last one, so a
  6182. # support bundle shows the correlation from the first attempt rather than
  6183. # only after the retry budget is spent (#2758).
  6184. if drying_ams_ids:
  6185. logger.info(
  6186. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  6187. queue_item_id,
  6188. printer_id,
  6189. ", ".join(str(i) for i in drying_ams_ids),
  6190. )
  6191. # Four outcomes from the revert attempt, each routed differently:
  6192. # "reverted": row flipped from printing -> pending, run recovery
  6193. # "gave_up": same, but the retry budget is spent — row failed
  6194. # rather than pending, so it stops going round again
  6195. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  6196. # on_print_complete or user). Skip recovery entirely
  6197. # — the print clearly landed somewhere even if the
  6198. # watchdog didn't see the active-state transition.
  6199. # "revert_failed": SQLite contention exhausted retries. Still run
  6200. # recovery so the MQTT session gets a fresh client_id
  6201. # on the half-broken-session path.
  6202. #
  6203. # The retry budget (#2555): reverting to 'pending' hands the item straight
  6204. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  6205. # the watchdog again. For a printer that is genuinely wedged that loop never
  6206. # ends — the reporter had one printer "since this morning still not launch"
  6207. # — and each lap also consumes an upload slot that the other printers in the
  6208. # farm are waiting on. Retrying is right; retrying forever is not.
  6209. async def _do_revert(db):
  6210. item = await db.get(PrintQueueItem, queue_item_id)
  6211. if not item or item.status != "printing":
  6212. return "already_moved_on"
  6213. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  6214. item.started_at = None
  6215. # Charge the attempt to the candidate that was actually dispatched, so
  6216. # a cross-model item (#671) reaches for its other file next lap instead
  6217. # of retrying the printer that just failed to start. Matched by file
  6218. # because that is what the resolver copied onto the row.
  6219. if item.library_file_id is not None:
  6220. await db.execute(
  6221. update(PrintQueueVariant)
  6222. .where(PrintQueueVariant.queue_item_id == item.id)
  6223. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  6224. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  6225. )
  6226. if command_rejected:
  6227. # No retry budget for this one: the printer refused to verify the
  6228. # command, and re-uploading the same 3MF to the same printer will
  6229. # be refused the same way. Fail now with the fix rather than after
  6230. # three laps of a message about SD cards (#2732).
  6231. item.status = "failed"
  6232. item.error_message = (
  6233. "The printer rejected the print command: MQTT command verification failed "
  6234. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  6235. "then start the job again."
  6236. )
  6237. item.completed_at = datetime.now(timezone.utc)
  6238. await db.commit()
  6239. return "command_rejected"
  6240. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  6241. item.status = "failed"
  6242. if drying_ams_ids:
  6243. # #2758: the generic message below sent the reporter looking
  6244. # at the SD card while the actual obstacle — AMS units in a
  6245. # drying cycle — was on screen the whole time. Name what we
  6246. # observed and let the user judge it; Bambuddy does not stop
  6247. # the cycle itself, because on this hardware drying can run
  6248. # alongside a print and stopping it may not be the fix.
  6249. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  6250. item.error_message = (
  6251. f"The printer accepted the file but never started printing, after "
  6252. f"{item.dispatch_attempts} attempts. {units} "
  6253. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  6254. f"some printers refuse to begin a print while an AMS is in a drying "
  6255. f"cycle, and an AMS drying without its external power supply can also "
  6256. f"leave too little power for the start-of-print calibration. Stop the "
  6257. f"drying, or connect the AMS power supply, and start the job again."
  6258. )
  6259. else:
  6260. item.error_message = (
  6261. f"The printer accepted the file but never started printing, after "
  6262. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  6263. f"prompt or error, confirm its SD card is readable, and start the job again."
  6264. )
  6265. item.completed_at = datetime.now(timezone.utc)
  6266. await release_budget_reservation(
  6267. db,
  6268. source_type="print_queue",
  6269. source_id=item.id,
  6270. status="released",
  6271. )
  6272. await db.commit()
  6273. return "gave_up"
  6274. item.status = "pending"
  6275. await db.commit()
  6276. return "reverted"
  6277. try:
  6278. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  6279. except Exception as e:
  6280. logger.warning(
  6281. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  6282. "scheduler may keep treating this item as in-flight",
  6283. queue_item_id,
  6284. printer_id,
  6285. e,
  6286. )
  6287. revert_outcome = "revert_failed"
  6288. if revert_outcome == "already_moved_on":
  6289. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  6290. # other path) already moved the item past 'printing', don't run the
  6291. # MQTT session-recovery logic below — a forced reconnect on a healthy
  6292. # session breaks ongoing prints on the same printer.
  6293. return
  6294. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  6295. if revert_outcome == "command_rejected":
  6296. logger.error(
  6297. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  6298. "failed) — the print command was rejected, not lost. Failing the item "
  6299. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  6300. queue_item_id,
  6301. printer_id,
  6302. HMS_MQTT_VERIFY_FAILED,
  6303. )
  6304. await scheduler._notify_dispatch_gave_up(
  6305. queue_item_id,
  6306. printer_id,
  6307. created_by_id,
  6308. reason="Printer rejected the print command (MQTT command verification failed)",
  6309. )
  6310. # Same reasoning as the landed_on_subtask path below: the file is on
  6311. # the printer and a forced reconnect would only add 0500_4003 to a
  6312. # problem that has nothing to do with the MQTT session (#1150).
  6313. return
  6314. if revert_outcome == "gave_up":
  6315. logger.error(
  6316. "Queue item %s: printer %d never started the print after %d dispatch "
  6317. "attempts (last one waited %.0fs) — marking the item failed instead of "
  6318. "re-uploading it again (#2555)",
  6319. queue_item_id,
  6320. printer_id,
  6321. DISPATCH_MAX_ATTEMPTS,
  6322. total_timeout,
  6323. )
  6324. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  6325. elif revert_outcome == "reverted":
  6326. if landed_on_subtask:
  6327. logger.warning(
  6328. "Queue item %s: printer %d accepted project_file (subtask_id "
  6329. "advanced) but never transitioned to an active state within "
  6330. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  6331. "for retry (#1678)",
  6332. queue_item_id,
  6333. printer_id,
  6334. total_timeout,
  6335. )
  6336. else:
  6337. logger.warning(
  6338. "Queue item %s: printer %d did not respond to print command within "
  6339. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  6340. "for retry (#967)",
  6341. queue_item_id,
  6342. printer_id,
  6343. timeout,
  6344. pre_state,
  6345. pre_subtask_id,
  6346. )
  6347. # Phase B was entered iff subtask_id advanced, which means the
  6348. # project_file landed on the printer. A forced reconnect at this point
  6349. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  6350. # skip the recovery entirely.
  6351. if landed_on_subtask:
  6352. return
  6353. # Phase A timeout path: if the printer's gcode_file changed since
  6354. # pre-dispatch, the project_file command landed and the printer is
  6355. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  6356. # If gcode_file is unchanged, the publish was silently swallowed
  6357. # (#887/#936) and force_reconnect recovery is what we want.
  6358. client = printer_manager.get_client(printer_id)
  6359. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  6360. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  6361. if publish_landed:
  6362. logger.warning(
  6363. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  6364. "received the command and is parsing slowly. Skipping forced "
  6365. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  6366. queue_item_id,
  6367. current_gcode_file,
  6368. pre_gcode_file,
  6369. )
  6370. elif client and hasattr(client, "force_reconnect_stale_session"):
  6371. client.force_reconnect_stale_session(
  6372. f"queue print command unacknowledged after {timeout:.0f}s "
  6373. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  6374. )
  6375. # Global scheduler instance
  6376. scheduler = PrintScheduler()