print_scheduler.py 389 KB

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