print_scheduler.py 364 KB

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