print_scheduler.py 368 KB

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