print_scheduler.py 419 KB

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