print_scheduler.py 385 KB

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