print_scheduler.py 405 KB

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