print_scheduler.py 420 KB

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