print_scheduler.py 329 KB

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