print_scheduler.py 400 KB

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