print_scheduler.py 464 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. import zipfile
  8. from collections import deque
  9. from collections.abc import Mapping
  10. from dataclasses import dataclass
  11. from datetime import datetime, timedelta, timezone
  12. from pathlib import Path
  13. from fastapi import HTTPException
  14. from sqlalchemy import delete, false, func, or_, select, true, update
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from sqlalchemy.orm import selectinload
  17. from backend.app.core.config import settings
  18. from backend.app.core.database import async_session, run_with_retry
  19. from backend.app.core.tasks import spawn_background_task
  20. from backend.app.core.websocket import ws_manager
  21. from backend.app.models.archive import PrintArchive
  22. from backend.app.models.library import LibraryFile
  23. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  24. from backend.app.models.printer import Printer
  25. from backend.app.models.scheduled_drying import ScheduledDrying
  26. from backend.app.models.settings import Settings
  27. from backend.app.models.smart_plug import SmartPlug
  28. from backend.app.models.spool_assignment import SpoolAssignment
  29. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  30. from backend.app.services import drying_preflight, kprofile_drift, print_dispatch_context, stock_forecast
  31. from backend.app.services.bambu_ftp import (
  32. FtpFailureKind,
  33. FtpFailureReport,
  34. UploadCancelled,
  35. cache_3mf_download,
  36. delete_file_async,
  37. describe_upload_failure,
  38. get_ftp_retry_settings,
  39. upload_file_async,
  40. with_ftp_retry,
  41. )
  42. from backend.app.services.bambu_mqtt import _RACK_NOZZLE_IDS, HMS_MQTT_VERIFY_FAILED, resolve_rack_plan_mapping
  43. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  44. from backend.app.services.finance_budget import (
  45. create_budget_reservation,
  46. release_budget_reservation,
  47. validate_print_budget,
  48. )
  49. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  50. from backend.app.services.notification_service import notification_service
  51. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  52. from backend.app.services.printer_manager import (
  53. printer_manager,
  54. supports_airduct,
  55. supports_chamber_heater,
  56. supports_chamber_temp,
  57. supports_drying,
  58. supports_drying_while_printing,
  59. )
  60. from backend.app.services.smart_plug_manager import smart_plug_manager
  61. from backend.app.services.spool_assignment_notifications import (
  62. _global_tray_from_assignment,
  63. _slot_label_from_global_tray,
  64. )
  65. from backend.app.utils.ams_drying import is_countdown_parked
  66. from backend.app.utils.ams_humidity import ams_humidity_percent
  67. from backend.app.utils.archive_paths import archive_photos_dir
  68. from backend.app.utils.color_utils import perceptual_color_distance
  69. from backend.app.utils.filament_types import canonical_filament_type
  70. from backend.app.utils.filename import derive_remote_filename
  71. from backend.app.utils.library_paths import move_library_photos
  72. from backend.app.utils.local_time import utcnow_naive
  73. from backend.app.utils.printer_models import (
  74. is_dual_nozzle_model,
  75. is_gcode_compatible,
  76. is_nozzle_rack_model,
  77. normalize_printer_model,
  78. )
  79. from backend.app.utils.threemf_tools import (
  80. default_plate_number,
  81. extract_rack_plan_from_3mf,
  82. extract_slot_extruders_from_3mf,
  83. select_plate_gcode_name,
  84. )
  85. logger = logging.getLogger(__name__)
  86. def _ams_slot_label(ams_id: int, tray_id: int) -> str:
  87. """Human slot name for an assignment tuple, in the spelling already in use.
  88. Composed from the notification side's own pair rather than spelled out again
  89. here. The hand-rolled version this replaces got three real slot kinds wrong:
  90. ams_id 254 fell into its ``>= 128`` branch and came out as ``HT-`` plus
  91. ``chr(191)``; both externals collapsed to one label, because an external
  92. assignment stores ams_id 255 with tray_id picking left or right
  93. (inventory.py:1771, ``ext_id = data.tray_id + 254``); and an A2L AMS-Lite,
  94. normalised to unit 6, read as ``AMS-G`` instead of ``Lite-``.
  95. Naming the same slot two ways is its own defect once an alert and the
  96. Inventory page are meant to be talking about the same tray, so this defers
  97. rather than adding a fifth spelling.
  98. """
  99. return _slot_label_from_global_tray(_global_tray_from_assignment(ams_id, tray_id))
  100. # Minimum seconds between low-filament checks. Matches the scheduler's idle
  101. # interval: the fast path runs every 3 s while an upload is in flight, and a
  102. # low spool does not need answering at that resolution (#2913).
  103. _FILAMENT_LOW_MIN_INTERVAL = 30.0
  104. # Minimum seconds between stock forecast checks (#2955). The forecast is in whole
  105. # days, so a finer check would only repeat the same answer.
  106. _STOCK_FORECAST_MIN_INTERVAL = 3600.0
  107. # The settings row that holds which stock alerts have already been sent (#2955).
  108. _STOCK_ALERTS_SETTING_KEY = "stock_alerts_notified"
  109. # The Inventory page asks for this many usage records and the forecast panel
  110. # builds its rates from them; the alert reads the same window so the two agree.
  111. _STOCK_FORECAST_HISTORY_LIMIT = 5000
  112. def _remaining_percent(label_weight: int | float | None, weight_used: float | None) -> float | None:
  113. """Remaining filament as a percentage of the label weight.
  114. The same arithmetic the Inventory page's Low Stock count uses, and it works
  115. unchanged in both inventory modes: internal spools store ``weight_used``
  116. directly, and ``_map_spoolman_spool`` derives it from Spoolman's
  117. ``remaining_weight`` so the shape matches. Returns None when there is no
  118. label weight to be a percentage of -- a spool that cannot say how full it
  119. started cannot say how empty it is.
  120. """
  121. if not label_weight or label_weight <= 0:
  122. return None
  123. remaining = max(0.0, float(label_weight) - float(weight_used or 0.0))
  124. return remaining / float(label_weight) * 100.0
  125. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  126. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  127. # byte gate) from before the scheduler unification. Time gate keeps small
  128. # files from going silent (a single 8 KB chunk fires once and that's it);
  129. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  130. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  131. # sub-200 ms files.
  132. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  133. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  134. # How far back chamber temperature samples are retained. 2h comfortably spans
  135. # any soak a user can configure (capped at 30 min) plus the plate-clearing gap
  136. # before the next print.
  137. _CHAMBER_HISTORY_TTL_SECONDS = 7200
  138. # Fallback for `queue_keep_warm_max_minutes` — how long the bed may be held
  139. # warm on a printer sitting in FINISH before the heaters are shut off. Users
  140. # who clear plates promptly will want far less than this; it is deliberately
  141. # the cautious end, since the cost of it being too short is only a re-soak.
  142. _KEEP_WARM_MAX_MINUTES_DEFAULT = 120
  143. # Max acceptable gap between two consecutive chamber samples before we treat
  144. # the older one as belonging to a separate observation run (printer went
  145. # offline and came back). Above ~30s cadence with a safety margin.
  146. _CHAMBER_SAMPLE_MAX_GAP_SECONDS = 60.0
  147. # How long the chamber must read below target before we accept that it really
  148. # cooled. An enclosed chamber's thermal mass cannot lose and regain several
  149. # degrees quickly: measured on an X1C, falling from ~55°C to below 48°C took
  150. # 23-73 minutes (~0.2 C/min), while the fastest drop ever recorded was
  151. # 27 C/min — impossible for that mass, i.e. a sensor artifact. Brief
  152. # sub-target readings are therefore a door opening or noise, not lost soak,
  153. # and a plate swap (exactly when keep-warm is running) produces one. Six
  154. # minutes clears the longest such artifact observed (~5 min once bracketed by
  155. # its neighbouring samples) and still sits far below the 23-minute floor for
  156. # real cooling.
  157. _CHAMBER_DIP_GRACE_SECONDS = 360.0
  158. # How often the preheat stage re-checks that the item it is heating for still
  159. # wants to be printed. Cancelling only writes `status` to the database — it
  160. # cannot interrupt a coroutine parked in `asyncio.sleep` — so without this the
  161. # heaters run for the rest of max_wait + soak (45 min at the default settings)
  162. # and the printer stays in `busy_printers`, blocking every other queued item
  163. # behind a print that is not happening.
  164. _PREHEAT_CANCEL_CHECK_SECONDS = 10.0
  165. # set_airduct_mode modeId values (bambu_mqtt.py:5937 — 0 cooling, 1 heating).
  166. _AIRDUCT_MODE_COOLING = 0
  167. _AIRDUCT_MODE_HEATING = 1
  168. # How long a queue row may stay 'printing' while its printer sits in a terminal
  169. # state before the scheduler closes it itself (#2829).
  170. #
  171. # A real completion arrives within seconds of the printer going terminal, so
  172. # five minutes is far outside the normal path — this only ever sees a row whose
  173. # completion was refused or never delivered. It is the whole cost of the
  174. # failure to the user, though: a stranded row blocks every later job for that
  175. # printer, so it should not be raised without reason.
  176. _STRANDED_PRINTING_GRACE_SECONDS = 300.0
  177. # gcode_state values that mean the print is over, mapped to the queue status
  178. # they imply. Mirrors the mapping in bambu_mqtt's completion detection
  179. # (FINISH -> completed, FAILED -> failed, anything else terminal -> aborted,
  180. # which the queue calls cancelled) so a recovered row cannot disagree with one
  181. # closed by the normal path.
  182. _TERMINAL_STATE_QUEUE_STATUS = {
  183. "FINISH": "completed",
  184. "FAILED": "failed",
  185. "IDLE": "cancelled",
  186. }
  187. def _terminal_queue_status(state) -> str | None:
  188. """Queue status implied by *state*, or None if the print is not over.
  189. None for a disconnected printer as well as a busy one: a printer we are not
  190. talking to has a stale ``state`` field that proves nothing about what it is
  191. doing now.
  192. """
  193. if state is None or not getattr(state, "connected", False):
  194. return None
  195. return _TERMINAL_STATE_QUEUE_STATUS.get(getattr(state, "state", None))
  196. @dataclass
  197. class _KeepWarmEntry:
  198. """Per-printer keep-warm state.
  199. - ``started``: monotonic time when keep-warm first fired for this printer.
  200. Used by the max-duration timeout.
  201. - ``held_target``: last bed target we successfully published. On release
  202. we only send bed-off when firmware still reports this value, so a user
  203. or subsequent print that changed the target isn't clobbered.
  204. - ``expired``: latched True when the max-duration timeout fires. Prevents
  205. re-engagement (and re-seeding of ``started``) on subsequent ticks. The
  206. release sweep drops the entry entirely once the printer leaves the
  207. candidate set.
  208. """
  209. started: float
  210. held_target: int
  211. expired: bool = False
  212. # Auto-drying re-arm guards (#2770).
  213. #
  214. # An AMS reports HIGHER relative humidity while it is warm than once it has
  215. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  216. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  217. # threshold set inside that band therefore cannot be satisfied while the box is
  218. # hot, and the firmware is free to end a cycle whenever it decides the filament
  219. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  220. # the threshold and arms another cycle. The reporter's log has five 12-hour
  221. # cycles armed inside four hours, one of them six seconds after the previous
  222. # ended.
  223. #
  224. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  225. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  226. # manual or firmware-run dry is untouched.
  227. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  228. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  229. # Sustained-humidity wait (#2518): an above-threshold streak is only
  230. # "continuous" if some pass observed it within the gap ceiling. A unit that
  231. # goes unobserved longer (print running, printer disconnected, sensor silent)
  232. # restarts its streak rather than inheriting a stale one. The ceiling is
  233. # derived from the scheduler cadence — four missed passes — with this floor so
  234. # a fast-polling configuration does not void streaks on a single hiccup.
  235. AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS = 120
  236. # How long a finished scheduled drying row is kept before it is pruned.
  237. SCHEDULED_DRYING_RETENTION_DAYS = 7
  238. # How often that prune actually runs. The check itself is called on every queue
  239. # pass — every 3s while dispatching — and issuing the DELETE is what begins a
  240. # write transaction, which SQLite serialises against every other writer. Rows
  241. # only become prunable a week after they finish, so anything short of hourly is
  242. # paying that cost for nothing.
  243. SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS = 60 * 60
  244. class _UploadProgressBridge:
  245. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  246. ``upload_file_async`` runs the FTP transfer in an executor thread and
  247. invokes its ``progress_callback`` from that thread, so the callback
  248. body cannot ``await`` directly. This bridge captures the asyncio loop
  249. at construction (on the scheduler thread) and uses
  250. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  251. matches the legacy background_dispatch.py path 1:1 so the toast feels
  252. identical to the pre-#1625 experience.
  253. Failures inside the emit are swallowed — progress is a UX nicety, the
  254. upload itself must not fail because of a WS hiccup.
  255. """
  256. def __init__(self, user_id: int | None, queue_item_id: int):
  257. self._user_id = user_id
  258. self._queue_item_id = queue_item_id
  259. try:
  260. self._loop = asyncio.get_running_loop()
  261. except RuntimeError:
  262. self._loop = None
  263. self._last_emit_bytes = 0
  264. self._last_emit_monotonic = 0.0
  265. self._has_emitted = False
  266. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  267. if self._loop is None or total_bytes <= 0:
  268. return
  269. now = time.monotonic()
  270. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  271. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  272. # the four matter most: first-call so the user sees something even
  273. # for sub-chunk-size files; uploaded >= total so the bar locks at
  274. # 100% even when the throttle would otherwise eat it.
  275. should_emit = (
  276. not self._has_emitted
  277. or bytes_transferred >= total_bytes
  278. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  279. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  280. )
  281. if not should_emit:
  282. return
  283. self._has_emitted = True
  284. self._last_emit_bytes = bytes_transferred
  285. self._last_emit_monotonic = now
  286. try:
  287. asyncio.run_coroutine_threadsafe(
  288. ws_manager.send_queue_item_upload_progress(
  289. user_id=self._user_id,
  290. queue_item_id=self._queue_item_id,
  291. bytes_transferred=bytes_transferred,
  292. total_bytes=total_bytes,
  293. ),
  294. self._loop,
  295. )
  296. except Exception:
  297. pass # progress is best-effort, never block the upload
  298. # Bambu firmware states that mean the project_file has actually been accepted
  299. # and the printer is now processing / running / paused mid-print. Used by the
  300. # dispatch watchdog (#1370): a transition into one of these states means the
  301. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  302. # a post-print prompt) is NOT a valid "command landed" signal even though the
  303. # state value did change. SLICING is included because some firmwares park
  304. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  305. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  306. # How many times the start-watchdog may revert an item to 'pending' before it
  307. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  308. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  309. # both never recovers and starves the other printers of dispatch slots. Three
  310. # is chosen to clear the transient causes the watchdog already recovers from —
  311. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  312. # force-reconnect on the very next attempt — while still bounding the loop.
  313. DISPATCH_MAX_ATTEMPTS = 3
  314. # Upload failures that mean the file never reached the printer's storage: the
  315. # file service refused or never answered (#3210). These put the item back in
  316. # the queue instead of failing it, because nothing about the job is wrong --
  317. # and failing it left the printer idle, so the next pass handed it the next
  318. # item, which failed the same way. One P2S whose file service was out of
  319. # connection slots ate 43 queued jobs in ten minutes that way.
  320. #
  321. # Not here: AUTH (a wrong access code needs the user), STORAGE (a full or
  322. # missing card does too), NOT_FOUND (a Bambuddy-side path problem), UNKNOWN,
  323. # and an upload that overran its deadline -- each of those would fail the same
  324. # way on every retry.
  325. _UPLOAD_REQUEUE_KINDS: frozenset[FtpFailureKind] = frozenset(
  326. {FtpFailureKind.HANDSHAKE, FtpFailureKind.COOLOFF, FtpFailureKind.TIMEOUT, FtpFailureKind.NETWORK}
  327. )
  328. # How long a printer whose upload was put back stays out of dispatch (#3210).
  329. # The first window matches the FTP client's own handshake cool-off, so the
  330. # retry lands after the client would talk to the printer again anyway. Each
  331. # further refusal in a row doubles it, up to the cap: #3210's printer refused
  332. # for some 40 hours, and every retry costs a preheat cycle where preheat is on,
  333. # five connection attempts and a page of log. A successful upload resets it.
  334. UPLOAD_FAILURE_BACKOFF_SECONDS = 300
  335. UPLOAD_FAILURE_BACKOFF_MAX_SECONDS = 3600
  336. def _upload_backoff_seconds(refusals: int) -> int:
  337. """Backoff after the *refusals*-th refused upload in a row (1-based)."""
  338. return min(UPLOAD_FAILURE_BACKOFF_SECONDS * 2 ** max(refusals - 1, 0), UPLOAD_FAILURE_BACKOFF_MAX_SECONDS)
  339. @dataclass(slots=True)
  340. class _ModelCandidate:
  341. """One (file, printer model) pair the model-based matcher may try.
  342. Model-based assignment used to have exactly one of these per item, held
  343. directly in the item's own columns. Cross-model queue items (#671) have
  344. several, held in ``print_queue_variants``. Both shapes are normalised into
  345. this so the matching, the cross-model gate and the waiting-reason handling
  346. are written once and an item without variants provably takes the same path
  347. it took before variants existed.
  348. ``variant`` is None for the item's own columns and set for a real variant
  349. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  350. item once that candidate wins.
  351. """
  352. target_model: str | None
  353. sliced_for: str | None
  354. required_filament_types: str | None
  355. filament_overrides: str | None
  356. variant: "PrintQueueVariant | None" = None
  357. def _sliced_for_model(archive, library_file) -> str | None:
  358. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  359. if archive is not None:
  360. return archive.sliced_for_model
  361. if library_file is not None and library_file.file_metadata:
  362. return library_file.file_metadata.get("sliced_for_model")
  363. return None
  364. def _filament_constraints(candidate: _ModelCandidate) -> tuple[list[str] | None, list[dict] | None]:
  365. """The filament a candidate needs, as ``(types, overrides)``.
  366. Both columns are JSON text written by the slicer step. Malformed content is
  367. treated as no constraint rather than as an error: a job whose overrides
  368. cannot be parsed still prints, it just gets no filament-based narrowing.
  369. Overrides carry their own types, so the returned type list is the union of
  370. the two — an override on one slot must not drop the requirements of the
  371. slots it says nothing about.
  372. Shared by the matcher and by the smart-plug wake step so both ask a printer
  373. for the same filament (#2876). Waking a printer the matcher would then
  374. reject on colour is the bug this exists to prevent.
  375. """
  376. required_types = None
  377. if candidate.required_filament_types:
  378. try:
  379. required_types = json.loads(candidate.required_filament_types)
  380. except json.JSONDecodeError:
  381. pass
  382. filament_overrides = None
  383. if candidate.filament_overrides:
  384. try:
  385. filament_overrides = json.loads(candidate.filament_overrides)
  386. except json.JSONDecodeError:
  387. pass
  388. effective_types = required_types
  389. if filament_overrides:
  390. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  391. if override_types:
  392. effective_types = sorted(set(required_types or []) | set(override_types))
  393. return effective_types, filament_overrides
  394. def _could_take_printer(item: PrintQueueItem, printer_id: int, printer_model: str | None) -> bool:
  395. """Whether ``item`` was competing for the printer another item just took.
  396. The SJF starvation guard marks a job as jumped when a shorter one lower in
  397. the queue takes a printer it wanted. A pinned job and an "Any <model>" job
  398. compete for the same printer, so the guard has to look across both lanes
  399. (#3200); looking only inside the dispatched item's own lane let a stream of
  400. short model-based jobs hold a longer pinned job back indefinitely.
  401. Location filters are not checked: over-marking only lifts an item that was
  402. going to wait anyway, while under-marking is the starvation this prevents.
  403. """
  404. if item.printer_id is not None:
  405. return item.printer_id == printer_id
  406. if not printer_model:
  407. return False
  408. wanted = (normalize_printer_model(printer_model) or printer_model).lower()
  409. models = [v.target_model for v in item.variants] if item.variants else [item.target_model]
  410. return any(m and (normalize_printer_model(m) or m).lower() == wanted for m in models)
  411. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  412. """Candidate files for ``item``, best first.
  413. An item with no variant rows yields exactly one candidate built from its own
  414. columns — the pre-#671 behaviour, unchanged.
  415. Variants come back least-attempted first, ties broken by the user's
  416. ``position``. On the first pass every count is zero, so this is purely the
  417. user's priority order. After a start-watchdog bounce the printer that failed
  418. drops behind, so the next lap tries the other machine rather than spending the
  419. item's whole retry budget on the one that is wedged. Once every candidate has
  420. been tried equally often they cycle again, which keeps the item-level
  421. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  422. still gives up, it just does not give up without trying them.
  423. """
  424. if not item.variants:
  425. if not item.archive_id and not item.library_file_id:
  426. # Nothing to print at all. Dispatching would fail deep in the upload
  427. # on "No archive_id or library_file_id"; the caller holds the item
  428. # with an explanation instead.
  429. return []
  430. return [
  431. _ModelCandidate(
  432. target_model=item.target_model,
  433. sliced_for=_sliced_for_model(item.archive, item.library_file),
  434. required_filament_types=item.required_filament_types,
  435. filament_overrides=item.filament_overrides,
  436. )
  437. ]
  438. # Drop candidates whose file is gone or in the trash. Both are reachable and
  439. # neither is covered by the schema: library deletes are soft (the row lives
  440. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  441. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  442. # fires there and a hard delete leaves the variant row pointing at nothing.
  443. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  444. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  445. return [
  446. _ModelCandidate(
  447. target_model=v.target_model,
  448. sliced_for=_sliced_for_model(None, v.library_file),
  449. required_filament_types=v.required_filament_types,
  450. filament_overrides=v.filament_overrides,
  451. variant=v,
  452. )
  453. for v in ordered
  454. ]
  455. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  456. """Fold one waiting reason per candidate into a single line for the item.
  457. A cross-model item produces a reason per candidate, and pasting them
  458. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  459. — on which machine?). Each reason is prefixed with its model, except in the
  460. single-candidate case where the item already displays its target model and
  461. the prefix would be noise.
  462. Identical reasons collapse rather than repeat, so three idle-less models
  463. read as one clause.
  464. When *every* candidate is merely busy the parts are joined with the ``" | "``
  465. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  466. unprefixed. That case must keep testing busy-only: a fleet that is simply
  467. printing needs no user action, and labelling the clauses would turn each pass
  468. over a two-model item into a "job waiting" notification.
  469. """
  470. reasons = [(model, reason) for model, reason in per_model if reason]
  471. if not reasons:
  472. return None
  473. if len(reasons) == 1:
  474. return reasons[0][1]
  475. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  476. if len(distinct) == 1:
  477. return distinct[0]
  478. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  479. return " | ".join(distinct)
  480. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  481. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  482. """Human label for the models an item is waiting on ("H2S or H2C").
  483. Notifications take a single target model. For a cross-model item the item's
  484. own ``target_model`` is whichever variant happens to be first, which reads as
  485. a lie once it is the H2C that actually runs — so name all of them.
  486. """
  487. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  488. if not models:
  489. return None
  490. return " or ".join(models)
  491. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  492. """True if ``mapping`` is a non-empty list whose every entry is the
  493. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  494. Such a mapping is a bug artifact: a frontend status-load race can serialize
  495. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  496. recomputed from live status at dispatch rather than trusted, otherwise it
  497. reaches the print command and is silently downgraded to external-spool mode.
  498. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  499. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  500. explicit external selection (``>= 254``) is NOT unresolved either — those
  501. keep their meaning.
  502. """
  503. if not isinstance(mapping, list) or not mapping:
  504. return False
  505. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  506. def _is_tray_id(value: object) -> bool:
  507. """True when ``value`` can be read as a global tray ID.
  508. ``bool`` is a subclass of ``int``, so a hand-written API payload carrying
  509. ``true`` would otherwise be read as tray 1 and judged — or dispatched —
  510. against whatever happens to be loaded there.
  511. """
  512. return isinstance(value, int) and not isinstance(value, bool)
  513. # Prefix of the waiting_reason `_block_on_unmatched_filament` writes when it
  514. # stages an item (#2799). The manual_start branch clears every other reason on
  515. # a staged item (#3074); this one is the reason it was staged, so it stays.
  516. _UNMATCHED_HOLD_PREFIX = "Needs "
  517. def _is_unmatched_hold_reason(reason: str | None) -> bool:
  518. """True for the reason the unmatched-filament hold wrote when it staged the item."""
  519. return bool(reason) and reason.startswith(_UNMATCHED_HOLD_PREFIX)
  520. def _unresolved_required(required: list[dict], mapping: list) -> list[dict]:
  521. """The requirements in ``required`` that ``mapping`` gives no tray (#2799).
  522. Only slots the plate prints are judged: a ``-1`` anywhere else is padding
  523. for a filament this plate does not use. A slot past the end of the mapping
  524. is unresolved too.
  525. """
  526. unresolved = []
  527. for req in required:
  528. slot_id = req.get("slot_id") or 0
  529. if slot_id <= 0:
  530. continue
  531. tray = mapping[slot_id - 1] if slot_id <= len(mapping) else None
  532. if not _is_tray_id(tray) or tray < 0:
  533. unresolved.append(req)
  534. return unresolved
  535. # Global tray ids at or above this are the external spool(s), not an AMS slot:
  536. # 254 is the deputy feed and 255 the main one. Mirrors the sentinel documented
  537. # on `_mapping_is_all_unresolved`.
  538. _EXTERNAL_TRAY_ID_MIN = 254
  539. def _consumed_mapping_entries(mapping: list | None, required: list[dict] | None) -> list | None:
  540. """The ``mapping`` entries for the slots this plate actually prints.
  541. ``required`` comes from ``extract_filament_requirements``, which drops any
  542. filament with ``used_g <= 0`` — so a slot_id present there is one the plate
  543. consumes, and one absent from it is padding. That distinction is why this
  544. decision lives here and not in the MQTT command builder: a ``-1`` in the
  545. mapping means either "this plate does not print filament N" or "we never
  546. worked out which tray", and only the plate's own filament list separates
  547. them. The builder sees both as the same byte, which is how a plate whose one
  548. printed filament sat on the external spool went out as `use_ams=true` with a
  549. mapping of nothing but -1 and stalled at preheat until the firmware gave up
  550. with 07FF_8012 (#3087).
  551. Returns None whenever the two cannot be lined up — no mapping, no parsed
  552. requirements, or a requirement the mapping is too short to cover — so every
  553. caller falls back to existing behaviour rather than acting on a guess.
  554. """
  555. if not isinstance(mapping, list) or not mapping or not required:
  556. return None
  557. entries = []
  558. for filament in required:
  559. slot_id = filament.get("slot_id")
  560. if not isinstance(slot_id, int) or not 1 <= slot_id <= len(mapping):
  561. # The mapping and the requirements disagree about how many filaments
  562. # the file has. They came from different reads, so judge nothing.
  563. return None
  564. entries.append(mapping[slot_id - 1])
  565. return entries or None
  566. def _is_external_tray(tray_id) -> bool:
  567. """True for an explicit external-spool selection (254/255), not for an
  568. unresolved slot and not for an AMS tray."""
  569. if tray_id is None:
  570. return False
  571. try:
  572. return int(tray_id) >= _EXTERNAL_TRAY_ID_MIN
  573. except (TypeError, ValueError):
  574. return False
  575. def _might_be_dual_nozzle(printer_model: str | None, status) -> bool:
  576. """Whether this printer could have two extruders, judged generously.
  577. On a dual-nozzle printer ``use_ams`` is nozzle routing rather than an
  578. AMS on/off flag — H2D Pro firmware reads it as an extruder index — which is
  579. why the MQTT command builder skips its own use_ams reconcile there. Anything
  580. that might be dual-nozzle therefore keeps whatever ``use_ams`` it arrived
  581. with, external spools or not.
  582. Deliberately over-eager: a wrong "yes" only means this printer keeps the
  583. behaviour it has always had, while a wrong "no" would rewrite a field that
  584. steers which nozzle prints. The model name is the first answer (it is what
  585. the command builder falls back to as well), then the same live evidence the
  586. dispatcher's extruder annotation uses — a second nozzle reporting a
  587. diameter, a populated ``ams_extruder_map``, or more than one external feed,
  588. since a single-nozzle printer has exactly one.
  589. """
  590. if is_dual_nozzle_model(printer_model):
  591. return True
  592. nozzles = getattr(status, "nozzles", None) or []
  593. if len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""):
  594. return True
  595. raw = getattr(status, "raw_data", None) or {}
  596. if raw.get("ams_extruder_map"):
  597. return True
  598. vt_trays = raw.get("vt_tray") or []
  599. return isinstance(vt_trays, list) and len(vt_trays) > 1
  600. def _int_or(value, default: int) -> int:
  601. """``int(value)``, or ``default`` when the field is missing or junk.
  602. AMS telemetry types its ids inconsistently — `"0"` in one firmware, `0` in
  603. the next — and a tray id that fails to parse must not take the whole
  604. derivation down with it.
  605. """
  606. try:
  607. return int(value)
  608. except (TypeError, ValueError):
  609. return default
  610. def _global_tray_id(ams_id: int, tray_id: int) -> int:
  611. """Bambu's flat tray addressing: ``ams_id * 4 + tray_id`` for a four-slot
  612. unit, and the bare unit id for an AMS-HT (ids from 128, one tray each).
  613. Mirrors the calculation in ``_build_loaded_filaments``, which is what
  614. produces the ids stored in ``PrintQueueItem.ams_mapping`` — the two must
  615. agree or a mapping cannot be read back against live tray telemetry.
  616. """
  617. return ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  618. def _used_global_tray_ids(item: PrintQueueItem | None) -> set[int] | None:
  619. """The global tray ids ``item`` actually prints from, or None if unknown.
  620. ``ams_mapping`` is the array the print command carries: position = filament
  621. slot, value = global tray id, ``-1`` / ``None`` for a slot this plate does
  622. not use. None means "no usable statement" — no mapping, unparseable JSON,
  623. an all-unresolved mapping (the artifact ``_mapping_is_all_unresolved``
  624. documents), or one that resolves to no tray at all. Callers must treat None
  625. as "consider every loaded tray" rather than "consider none": narrowing on
  626. an absent mapping would silently drop requirements the print really has.
  627. """
  628. raw = getattr(item, "ams_mapping", None)
  629. if not raw:
  630. return None
  631. if isinstance(raw, str):
  632. try:
  633. mapping = json.loads(raw)
  634. except (json.JSONDecodeError, TypeError):
  635. return None
  636. else:
  637. mapping = raw
  638. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  639. return None
  640. used = {t for t in mapping if isinstance(t, int) and not isinstance(t, bool) and t >= 0}
  641. return used or None
  642. def _mqtt_commands_rejected(status) -> bool:
  643. """True when the printer is currently reporting that it refused a command.
  644. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  645. a control command it could not verify. Queries still answer, so the printer
  646. looks connected and idle while project_file, gcode_line and
  647. ams_change_filament are all dropped — no amount of waiting or re-uploading
  648. changes that (#2732).
  649. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  650. ``print_error`` path builds HMSError differently), so this is safe to call on
  651. every watchdog poll.
  652. """
  653. for err in getattr(status, "hms_errors", None) or []:
  654. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  655. return True
  656. return False
  657. def _drying_ams_ids(status) -> list[int]:
  658. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  659. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  660. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  661. started (#2758) — it is a diagnostic, not a gate.
  662. Deliberately not used to block or stop drying before dispatch. This printer
  663. class supports drying concurrently with an active print
  664. (``supports_drying_while_printing``), so drying is not incompatible with
  665. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  666. while two AMS units were drying, one of them without its external PSU. Until
  667. it is known whether the blocker is drying itself or the power budget
  668. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  669. hardware is perfectly happy to continue.
  670. """
  671. ids: list[int] = []
  672. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  673. if not isinstance(unit, dict):
  674. continue
  675. try:
  676. if int(unit.get("dry_time") or 0) > 0:
  677. ids.append(int(unit.get("id", 0)))
  678. except (TypeError, ValueError):
  679. continue
  680. return ids
  681. def _parse_diameter(raw) -> float | None:
  682. """``"0.4"`` → ``0.4``; anything unparseable or non-positive → None."""
  683. try:
  684. value = float(raw)
  685. except (TypeError, ValueError):
  686. return None
  687. return value if value > 0 else None
  688. def _nozzle_info_by_id(status) -> dict[int, dict]:
  689. """Index ``PrinterState.nozzle_rack`` by nozzle id.
  690. The field name is historical: on the H2 series ``nozzle_info`` carries an
  691. entry for *every* nozzle the printer knows about — the L/R hotends under
  692. ids 0/1 and, on a rack model, the dock positions under ids 16-21. Only the
  693. latter are the rack proper; :func:`_rack_nozzle_diameters` and
  694. :func:`_installed_nozzle_diameters` each take the half they need.
  695. """
  696. by_id: dict[int, dict] = {}
  697. for entry in getattr(status, "nozzle_rack", None) or []:
  698. if not isinstance(entry, dict):
  699. continue
  700. try:
  701. by_id[int(entry.get("id"))] = entry
  702. except (TypeError, ValueError):
  703. continue
  704. return by_id
  705. # What the firmware puts in a nozzle's serial number when the carriage or dock
  706. # is empty. Measured on an H2C at idle, where the rack-side hotend had parked
  707. # its nozzle back in the rack (#2885).
  708. _EMPTY_NOZZLE_SERIAL = "N/A"
  709. def _nozzle_is_mounted(entry: dict | None) -> bool:
  710. """Whether a ``nozzle_info`` entry describes hardware that is actually there.
  711. A hotend entry is reported whether or not a nozzle is mounted, and an empty
  712. carriage keeps the *last* nozzle's diameter — measured on an H2C at idle,
  713. where id 1 read ``diameter "0.4"`` with ``max_temp 0``, ``serial_number
  714. "N/A"`` and ``wear 0`` because that hotend had parked its nozzle back in
  715. the dock. So the diameter is not a presence signal (#2885).
  716. Emptiness has to be stated, not merely unstated. The serial must be the
  717. firmware's explicit ``"N/A"`` marker *and* the temperature rating must be
  718. absent — an empty serial only means the printer didn't say, and a firmware
  719. that reports neither field normalises to exactly that. Treating "didn't
  720. say" as "empty" would silently switch the #1899 guard off on any such
  721. machine, so everything we cannot positively call empty counts as mounted.
  722. """
  723. if entry is None:
  724. return True
  725. serial = str(entry.get("serial_number") or "").strip().upper()
  726. if serial != _EMPTY_NOZZLE_SERIAL:
  727. return True
  728. try:
  729. max_temp = float(entry.get("max_temp") or 0)
  730. except (TypeError, ValueError):
  731. return True
  732. return max_temp > 0
  733. def _installed_nozzle_diameters(status) -> list[float]:
  734. """Parse the mounted nozzle diameters from a PrinterState (#1899).
  735. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  736. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  737. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  738. told us its nozzle hardware" — callers must treat that as unknown, not as a
  739. mismatch, so we never block a print on missing data.
  740. A hotend whose ``nozzle_info`` entry says nothing is mounted is skipped even
  741. though ``nozzles`` still carries a diameter for it: that value is stale, and
  742. counting it would let a slice match a nozzle the machine does not have
  743. (#2885). Printers that report no ``nozzle_info`` at all are unaffected.
  744. """
  745. info = _nozzle_info_by_id(status)
  746. diameters: list[float] = []
  747. for index, nozzle in enumerate(getattr(status, "nozzles", None) or []):
  748. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  749. try:
  750. value = float(raw)
  751. except (TypeError, ValueError):
  752. continue
  753. if value > 0 and _nozzle_is_mounted(info.get(index)):
  754. diameters.append(value)
  755. return diameters
  756. def _rack_nozzle_diameters(status) -> list[float]:
  757. """Diameters sitting in the tool-changer rack, nearest dock first (#2885).
  758. Keyed off the nozzle ids themselves rather than the printer model: only a
  759. rack machine ever reports ids 16-21, so there is no model registry to keep
  760. in sync. An empty dock is simply absent from the payload — measured on an
  761. H2C whose R2 (id 17) was empty and unlisted while R1/R3/R4/R5/R6 were all
  762. present — so appearing here already means "a nozzle is in that dock".
  763. ``stat`` is deliberately not interpreted: its values aren't known, and
  764. reading it wrongly could hide a nozzle the printer would happily fetch.
  765. """
  766. diameters: list[float] = []
  767. for nozzle_id, entry in sorted(_nozzle_info_by_id(status).items()):
  768. if nozzle_id not in _RACK_NOZZLE_IDS:
  769. continue
  770. # PrinterState spells it "diameter"; the REST schema renames it to
  771. # "nozzle_diameter". Accept either so a caller holding the serialised
  772. # shape gets the same answer.
  773. value = _parse_diameter(entry.get("diameter") or entry.get("nozzle_diameter"))
  774. if value is not None:
  775. diameters.append(value)
  776. return diameters
  777. def _format_diameters(diameters: list[float]) -> str:
  778. """``[0.4, 0.4, 0.6]`` → ``"0.4mm / 0.6mm"``, in first-seen order.
  779. Deduplicated because a loaded rack holds several nozzles of the same size,
  780. and "0.4mm / 0.4mm / 0.4mm / 0.6mm / 0.2mm" tells the reader nothing the
  781. short form doesn't. Matching still runs over the full list.
  782. """
  783. return " / ".join(f"{d:g}mm" for d in dict.fromkeys(diameters))
  784. def _nozzle_mismatch_message(
  785. sliced_nozzle: float | None,
  786. installed: list[float],
  787. rack: list[float] | None = None,
  788. ) -> str | None:
  789. """Return an actionable error message when the sliced nozzle can't be
  790. printed on any nozzle the machine can reach, else None (#1899).
  791. Fail-safe: returns None whenever we lack the data to judge — no sliced
  792. diameter, or the printer reported no nozzles — so a print is only ever
  793. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  794. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  795. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  796. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  797. *rack* holds the diameters parked in a tool-changer dock (H2C). Those count
  798. as reachable: the printer fetches one as part of starting the print, so a
  799. slice that matches a docked nozzle is not a mismatch. Without this the
  800. guard blocked every job whose nozzle happened not to be on a hotend at
  801. dispatch time — on a rack loaded with 0.2/0.4/0.6 that meant only the
  802. diameter already mounted could ever print, and the user had to fetch the
  803. nozzle by hand on the printer's own UI first (#2885).
  804. """
  805. reachable = [*installed, *(rack or [])]
  806. if not sliced_nozzle or not reachable:
  807. return None
  808. if any(abs(d - sliced_nozzle) < 0.05 for d in reachable):
  809. return None
  810. where = f"{_format_diameters(installed)} installed" if installed else "no nozzle mounted"
  811. if rack:
  812. where += f" and {_format_diameters(rack)} in the nozzle rack"
  813. return (
  814. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  815. f"{where}. Re-slice for an available nozzle, or fit the matching "
  816. f"nozzle before printing."
  817. )
  818. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  819. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  820. Shared by the required and loaded sides, which name their extruder
  821. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  822. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  823. 1 the left/deputy — and both are absent on single-nozzle printers, where
  824. naming a nozzle would be noise.
  825. """
  826. parts = [(entry.get("type") or "filament").upper()]
  827. if entry.get("color"):
  828. parts.append(str(entry["color"]))
  829. nozzle = entry.get(nozzle_key)
  830. if nozzle == 0:
  831. parts.append("(right nozzle)")
  832. elif nozzle == 1:
  833. parts.append("(left nozzle)")
  834. return " ".join(parts)
  835. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  836. """Explain that nothing loaded matches what the file needs (#2771).
  837. Only ever built for a printer with no AMS, where the loaded list is short
  838. enough to quote in full and there is no "load another spool and hit Resume"
  839. recovery — the external spool holder is all there is, so the user needs to
  840. be told which filament to put on it.
  841. """
  842. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  843. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  844. return (
  845. f"No filament loaded on this printer matches the file. It needs {want}; "
  846. f"the printer has {have} and no AMS. Load the required filament on the "
  847. f"external spool holder, or send this job to a printer that has it."
  848. )
  849. def _effective_plate_id(explicit_plate_id: int | None, file_path: Path) -> int:
  850. """The plate to dispatch, resolved once in ``_start_print`` and reused at
  851. every call site below it: G-code injection, usage registration, rack-plan
  852. lookup, slot-extruder lookup, the external-spool check, and the actual
  853. print command.
  854. A positive explicit ``plate_id`` on the queue item always wins. A
  855. non-positive one is treated as "not set" and resolved from the archive,
  856. the way the rest of the queue code already reads it (``if item.plate_id:``
  857. in ``api/routes/print_queue.py``): the schemas put no lower bound on the
  858. field, and passing a 0 straight through would build a print command for
  859. ``Metadata/plate_0.gcode``, which is the same wedge this function exists
  860. to prevent. The ``item.plate_id or 1`` this replaced mapped 0 to 1.
  861. Falling back to a bare ``1`` instead of reading the archive assumes a
  862. single-plate file's one G-code is numbered 1, which only holds for a
  863. plate exported on its own: one cut out of a larger project keeps its
  864. ORIGINAL plate number, so a printer asked to print "plate 1" of a file
  865. whose only G-code is ``plate_2.gcode`` accepts the command, can't find
  866. the file, throws an HMS error, and sits wedged in IDLE until
  867. power-cycled (#2947).
  868. The call sites agreed on a fallback only by accident before this:
  869. with G-code injection on, ``inject_gcode_into_3mf`` already falls back to
  870. the archive's own default plate internally whenever the plate id it's
  871. handed isn't in the file, so it could silently inject into a different
  872. plate than the one the print command itself asked for.
  873. Falls back to 1 when the archive can't be read, holds no G-code member at
  874. all, or its default member doesn't follow the ``plate_N`` naming
  875. convention (a slicer that doesn't use it has no number to dispatch).
  876. An explicit plate the archive doesn't hold is logged and then sent
  877. anyway. It wedges the printer exactly like #2947 did, but redirecting it
  878. to a plate that is in the file would print a model nobody asked for,
  879. which is the worse of the two.
  880. """
  881. try:
  882. with zipfile.ZipFile(file_path, "r") as zf:
  883. names = zf.namelist()
  884. except (OSError, zipfile.BadZipFile) as exc:
  885. logger.warning(
  886. "Dispatch plate: cannot read %s (%s), so the archive's own plate numbering "
  887. "is unavailable; dispatching plate %s",
  888. file_path,
  889. exc,
  890. explicit_plate_id if explicit_plate_id is not None and explicit_plate_id > 0 else 1,
  891. )
  892. names = None
  893. if explicit_plate_id is not None and explicit_plate_id > 0:
  894. if (
  895. names is not None
  896. and default_plate_number(names) is not None
  897. and select_plate_gcode_name(names, explicit_plate_id) is None
  898. ):
  899. logger.warning(
  900. "Dispatch plate: %s was queued for plate %s but holds no G-code for it "
  901. "(it has %s). Sending plate %s as asked; expect the printer to reject the "
  902. "file, since printing a different plate would print the wrong model (#2947)",
  903. file_path,
  904. explicit_plate_id,
  905. ", ".join(sorted(n for n in names if n.endswith(".gcode"))),
  906. explicit_plate_id,
  907. )
  908. return explicit_plate_id
  909. resolved = default_plate_number(names) if names is not None else None
  910. return resolved if resolved is not None else 1
  911. class PrintScheduler:
  912. """Background scheduler that processes the print queue."""
  913. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  914. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  915. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  916. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  917. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  918. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  919. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  920. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  921. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  922. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  923. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  924. }
  925. def __init__(self):
  926. self._running = False
  927. self._check_interval = 30 # seconds
  928. # After a pass that actually dispatched something, loop again almost
  929. # immediately instead of sleeping the full interval (#2555). A dispatch
  930. # changes printer state — a batch launch fans out over several passes as
  931. # printers free up, a wedged head-of-line job reverts to pending, an
  932. # upload slot opens — and the next batch of ready work should not have to
  933. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  934. # pending items are behind printers that are genuinely busy printing),
  935. # there is nothing to react to, so we fall back to the normal interval;
  936. # that also means this can never tight-loop, since fast ticks only
  937. # continue while dispatches keep happening and the queue is draining.
  938. self._fast_check_interval = 3 # seconds
  939. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  940. self._power_on_check_interval = 10 # seconds between connection checks
  941. # Printers whose class-target power-on failed, mapped to the monotonic
  942. # time their cool-off expires (#2786).
  943. #
  944. # Without this, one printer with an unreachable plug starves every
  945. # sibling of its model forever: the wake step walks candidates in id
  946. # order, spends the pass's single attempt on the same broken printer
  947. # every time, and the healthy one two slots down is never reached. It
  948. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  949. # which delays the whole queue, not just this job.
  950. #
  951. # Entries expire on read rather than being cleared on success: a printer
  952. # inside its cool-off is skipped before the power-on is reached, so a
  953. # live entry can never be overwritten by a success anyway. A printer
  954. # that comes back by any other route stops being a wake candidate the
  955. # moment it connects.
  956. self._wake_failures: dict[int, float] = {}
  957. self._wake_failure_cooloff = 600 # seconds
  958. # Printers whose last upload never reached them, mapped to the monotonic
  959. # time they may be dispatched to again (#3210). Same expire-on-read shape
  960. # as `_wake_failures`. Without it, a printer that cannot take files is
  961. # idle on every pass, so it is picked on every pass.
  962. self._upload_backoff: dict[int, float] = {}
  963. # Refused uploads in a row per printer, which sets the next backoff
  964. # window. Cleared by a successful upload to that printer.
  965. self._upload_refusals: dict[int, int] = {}
  966. # Printers whose current run of refusals has already sent its one
  967. # "job waiting" notification. Each retry clears the item's waiting
  968. # reason and the next refusal sets it again, which `hold_item` reads as
  969. # a new reason; without this, every retry would notify. Cleared with
  970. # `_upload_refusals`.
  971. self._upload_refusal_notified: set[int] = set()
  972. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  973. self._drying_in_progress: dict[int, float] = {}
  974. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  975. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  976. # cycle and the humidity finally coming down, so the normal steady
  977. # state is an empty dict. Fields:
  978. # running — a cycle we armed is (or should be) on the firmware
  979. # ended_at — monotonic when we observed that cycle end
  980. # unproductive — consecutive armed cycles that ended with the reading
  981. # still above the threshold
  982. # suspended — we have stopped arming this unit and said so
  983. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  984. # Sustained-humidity streaks for the ambient-drying wait (#2518). Keyed
  985. # like _auto_dry_units but deliberately a SEPARATE dict: membership in
  986. # _auto_dry_units means "Bambuddy armed a cycle on this unit", and the
  987. # print-takes-priority stop, the manual-cycle adoption guard, and the
  988. # arming setdefault all act on that meaning -- a unit that is merely
  989. # waiting out its streak must not become stoppable or judgeable.
  990. # since -- monotonic stamp when the current continuous above-threshold
  991. # streak began
  992. # last -- monotonic stamp of the last pass that observed the streak
  993. self._auto_dry_above: dict[tuple[int, int], dict[str, float]] = {}
  994. # Slots already notified as low on filament:
  995. # {(printer_id, ams_id, tray_id, spool_id)}.
  996. # Cleared when the slot goes back above its threshold rather than on a
  997. # timer, mirroring _notified_hms_errors — a spool hovering at the
  998. # boundary must not produce an alert on every pass, and a slot that has
  999. # been refilled has to be able to alert again. See #2913.
  1000. #
  1001. # The spool id is part of the key because the slot alone cannot clear
  1002. # itself. Pull a low spool and put a different part-used one in the same
  1003. # slot: the key survives the pass where the slot resolves to nothing --
  1004. # deliberately, so a brief Spoolman outage does not re-alert everything
  1005. # when it returns -- and the replacement never goes above the threshold,
  1006. # so it can never re-arm. Keyed with the spool, the new spool is simply a
  1007. # different key and the stale one is inert.
  1008. self._notified_filament_low: set[tuple[int, int, int, int]] = set()
  1009. # Earliest monotonic time the next low-filament check may run (#2913).
  1010. self._filament_low_next_check: float = 0.0
  1011. # SKU key -> (condition, events told) for a SKU that is alerting (#2955): the
  1012. # condition is "reorder" or "break", the events are those that had a
  1013. # subscriber when it was sent. Absent means not alerting. Cleared when the
  1014. # condition clears, so it can alert again, and when nobody wants either
  1015. # event. Mirrored to one settings row (_STOCK_ALERTS_SETTING_KEY), because the
  1016. # first check runs as soon as Bambuddy starts and a restart would otherwise
  1017. # re-send one message per SKU that is still low.
  1018. self._notified_stock_alerts: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  1019. # The JSON last read from or written to that row; None until it has been read.
  1020. self._stock_alerts_persisted: str | None = None
  1021. # Earliest monotonic time the next stock forecast check may run (#2955).
  1022. self._stock_forecast_next_check: float = 0.0
  1023. # Printers with a "running" scheduled drying row (#2638). Rebuilt from the
  1024. # DB on every _check_scheduled_dryings call so route-side cancels show up.
  1025. # Auto-drying's stop-all branches must not stop or untrack these printers;
  1026. # both features share _drying_in_progress.
  1027. self._scheduled_drying_printer_ids: set[int] = set()
  1028. # Monotonic stamp of the last scheduled-drying prune. None = never, so
  1029. # the first pass after a restart reaps anything left behind.
  1030. self._last_scheduled_drying_prune: float | None = None
  1031. # Defensive in-memory dispatch hold (#1157): a printer that just received
  1032. # a project_file command must not get a second dispatch until either it
  1033. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  1034. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  1035. # during that window the DB busy_printers seed is empirically unreliable
  1036. # (multi-plate batches double-/triple-dispatched onto the same printer
  1037. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  1038. # or revert.
  1039. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  1040. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  1041. # Minimum cooldown between dispatches to the same printer (covers the
  1042. # H2D's project_file digestion window).
  1043. self._dispatch_min_cooldown = 60.0
  1044. # Hard timeout — drop the hold even if we never observed a transition,
  1045. # so a lost MQTT session can't lock a printer out of the queue forever.
  1046. # Matches the watchdog timeout (90 s) plus a safety margin so the
  1047. # watchdog runs first on the unhappy path.
  1048. self._dispatch_max_hold = 180.0
  1049. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  1050. # an earlier pass and is still running. `_start_print` flips the row
  1051. # pending -> printing only *after* the upload completes, so until then
  1052. # the row stays `pending`: each tick, check_queue excludes these
  1053. # item_ids from re-selection and their printers from new dispatch /
  1054. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  1055. # freed slots refill on the next fast tick. check_queue is the sole,
  1056. # sequential caller and the prune done-callbacks run in the same
  1057. # event-loop thread, so this dict needs no lock.
  1058. # item_id -> (task, printer_id)
  1059. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  1060. # Expected prints registered by `_start_print` that have not yet had a
  1061. # print command sent. Populated at registration, dropped once
  1062. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  1063. # other exit. Same threading argument as `_inflight` above: one
  1064. # sequential caller, callbacks on the same loop, so no lock.
  1065. # item_id -> (printer_id, remote_filename, archive_id)
  1066. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  1067. # Budget reservations created for a dispatch whose print command has
  1068. # not been confirmed yet. `_dispatch_one` releases these on every
  1069. # unsuccessful exit; a successful start removes the item id and leaves
  1070. # the reservation for finance_billing to consume with the archive.
  1071. self._unconfirmed_budget_reservations: set[int] = set()
  1072. # Chamber temperature history for smart soak-time reduction.
  1073. # printer_id -> deque of (monotonic_timestamp, celsius) sampled each scheduler tick.
  1074. # Entries older than _chamber_history_ttl are pruned on write.
  1075. self._chamber_history: dict[int, deque[tuple[float, float]]] = {}
  1076. self._chamber_history_ttl = _CHAMBER_HISTORY_TTL_SECONDS
  1077. # Per-printer keep-warm state (see `_KeepWarmEntry` at module top).
  1078. # Populated on engagement in `_apply_keep_warm`, cleared by
  1079. # `_sweep_keep_warm` when the printer leaves the candidate set (or
  1080. # when a gate setting toggles off mid-hold — the release publishes
  1081. # bed → 0 first).
  1082. self._keep_warm: dict[int, _KeepWarmEntry] = {}
  1083. # Preheat rollback registry: printer_id -> subset of
  1084. # {"bed", "chamber", "airduct"} listing which preheat commands
  1085. # actually fired for the in-flight dispatch. `_dispatch_one` unwinds
  1086. # every entry still present at exit unless the print successfully
  1087. # started, so a failed upload / cancel / exception never leaves the
  1088. # printer heating for a job that isn't happening.
  1089. self._preheat_pin: dict[int, set[str]] = {}
  1090. # Bed target (°C) that the pinned "bed" entry above actually set, so the
  1091. # rollback can tell its own target from one someone else has since
  1092. # chosen — the same guard `_release_keep_warm` applies to a keep-warm
  1093. # hold. Written wherever `"bed"` joins the pin, evicted alongside it.
  1094. self._preheat_pin_bed: dict[int, int] = {}
  1095. # Item ids whose in-flight dispatch has been cancelled or deleted while
  1096. # its preheat was still holding at temperature. Set by
  1097. # `notify_dispatch_cancelled` from the queue routes, consumed by
  1098. # `_preheat_sleep`, and cleared when the dispatch exits.
  1099. self._cancelled_dispatches: set[int] = set()
  1100. # printer_id -> monotonic time it was first seen terminal while one of
  1101. # its queue rows was still 'printing'. Reset by any non-terminal
  1102. # observation, so it measures an unbroken run rather than a total.
  1103. # In-memory on purpose: a restart re-arms the grace period, which only
  1104. # delays a recovery that is already the exceptional path (#2829).
  1105. self._terminal_since: dict[int, float] = {}
  1106. # Per-pass memo for `_get_filament_requirements` (#2799 review). Two
  1107. # gates parse the same 3MF per dispatch attempt, and a one-file fan-out
  1108. # across idle printers repeats that for every one of them in a single
  1109. # pass. Cleared at the top of each pass so a re-sliced file is never
  1110. # served from a previous tick.
  1111. self._filament_req_memo: dict[tuple, list[dict] | None] = {}
  1112. async def run(self):
  1113. """Main loop - check queue every interval."""
  1114. self._running = True
  1115. logger.info("Print scheduler started")
  1116. await self._clear_stale_dispatch_claims(at_startup=True)
  1117. while self._running:
  1118. dispatched = False
  1119. try:
  1120. self._sample_chamber_temps()
  1121. # No-op while any upload is in flight; on a quiet tick it releases
  1122. # a claim whose best-effort clear failed (e.g. the database was
  1123. # briefly unreachable), instead of leaving the row wedged until
  1124. # the next restart.
  1125. await self._clear_stale_dispatch_claims()
  1126. await self._close_stranded_printing_items()
  1127. dispatched = await self.check_queue()
  1128. except Exception as e:
  1129. logger.error("Scheduler error: %s", e)
  1130. # Re-check quickly after a productive pass so a draining batch does
  1131. # not stall behind the idle interval; otherwise sleep normally (#2555).
  1132. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  1133. async def _close_stranded_printing_items(self) -> None:
  1134. """Close a ``printing`` row the completion event never closed (#2829).
  1135. ``on_print_complete`` refuses to close a row when the completion's
  1136. subtask name disagrees with the file the row was dispatched with, so a
  1137. completion meant for something else (the printer's own
  1138. ``auto_pa_line_calib_mode`` run, say) cannot end someone's job early.
  1139. The refusal has no way back, though: nothing else ever closes the row,
  1140. and ``check_queue`` treats every ``printing`` row as a busy printer, so
  1141. one bad comparison wedges that printer's queue until a human presses
  1142. cancel. That is what #2829's reporters hit, and the guard's own
  1143. docstring already called stranding the worse of the two failures.
  1144. This is the way back. When a row has been ``printing`` while its
  1145. printer sat in a terminal state for the whole grace period, the print
  1146. is over however the event was read, and the row is closed with the
  1147. status the printer's own state implies.
  1148. Deliberately conservative:
  1149. * Only a connected printer counts. A disconnected one has a stale
  1150. ``state`` and proves nothing.
  1151. * The clock is reset by any non-terminal observation, so this cannot
  1152. fire on a printer that is merely between stages.
  1153. * The grace period is far longer than the gap between a printer
  1154. finishing and its completion arriving, so the normal path always
  1155. wins the race and this only ever sees genuine strandings.
  1156. What it does *not* do is replay the completion's side effects --
  1157. notifications, billing, auto-off. It restores the queue, which is the
  1158. harm being undone; the archive was updated by the normal path
  1159. regardless, since only the queue block refuses. A recovery that
  1160. silently re-fired notifications minutes late would be its own bug.
  1161. """
  1162. try:
  1163. async with async_session() as db:
  1164. result = await db.execute(
  1165. select(PrintQueueItem)
  1166. .where(PrintQueueItem.status == "printing")
  1167. .where(PrintQueueItem.printer_id.is_not(None))
  1168. )
  1169. items = list(result.scalars().all())
  1170. if not items:
  1171. self._terminal_since.clear()
  1172. return
  1173. now = time.monotonic()
  1174. seen_printers: set[int] = set()
  1175. closed = False
  1176. for item in items:
  1177. printer_id = item.printer_id
  1178. seen_printers.add(printer_id)
  1179. state = printer_manager.get_status(printer_id)
  1180. status = _terminal_queue_status(state)
  1181. if status is None:
  1182. self._terminal_since.pop(printer_id, None)
  1183. continue
  1184. since = self._terminal_since.setdefault(printer_id, now)
  1185. if now - since < _STRANDED_PRINTING_GRACE_SECONDS:
  1186. continue
  1187. item.status = status
  1188. item.completed_at = datetime.now(timezone.utc)
  1189. closed = True
  1190. logger.warning(
  1191. "Queue item %s was still 'printing' after printer %s reported %s for %.0fs — "
  1192. "closing it as %s. Its completion event was never matched to it, which blocks "
  1193. "every later job for this printer (#2829).",
  1194. item.id,
  1195. printer_id,
  1196. getattr(state, "state", None),
  1197. now - since,
  1198. status,
  1199. )
  1200. if closed:
  1201. await db.commit()
  1202. for printer_id in list(self._terminal_since):
  1203. if printer_id not in seen_printers:
  1204. del self._terminal_since[printer_id]
  1205. except Exception as e:
  1206. # Best-effort, same as the claim sweep beside it: a recovery path
  1207. # that can itself break the scheduler loop is worse than the strand.
  1208. logger.error("Stranded-item sweep failed: %s", e)
  1209. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  1210. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  1211. A claim is only ever held by a live dispatch coroutine, so when this
  1212. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  1213. is stale. At startup that is trivially true — no coroutine survives a
  1214. restart. It is equally true on any later tick where no upload is running,
  1215. which is what makes this safe to repeat rather than only run once.
  1216. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  1217. the database is briefly unreachable at exactly the moment dispatch ends,
  1218. the claim survives and the row is wedged out of the selection query. That
  1219. used to last until the next restart (#2702 follow-up, seen when
  1220. PostgreSQL refused a connection mid-dispatch).
  1221. ``_inflight`` is populated when the task is spawned, before the coroutine
  1222. claims its row, and pruned by a done-callback that cannot run before the
  1223. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  1224. race window and needs no age threshold. A size-derived upload deadline
  1225. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  1226. """
  1227. if self._inflight:
  1228. return
  1229. try:
  1230. async with async_session() as db:
  1231. res = await db.execute(
  1232. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  1233. )
  1234. await db.commit()
  1235. if res.rowcount:
  1236. logger.info(
  1237. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  1238. res.rowcount,
  1239. " at startup" if at_startup else "",
  1240. )
  1241. except Exception as exc:
  1242. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  1243. def stop(self):
  1244. """Stop the scheduler."""
  1245. self._running = False
  1246. logger.info("Print scheduler stopped")
  1247. async def check_queue(self) -> bool:
  1248. """Check for prints ready to start.
  1249. Returns True if this pass dispatched at least one item, so the caller
  1250. can loop again quickly instead of sleeping the full interval (#2555).
  1251. """
  1252. # Scoped to one pass: a file re-sliced between ticks must be re-read.
  1253. self._filament_req_memo.clear()
  1254. async with async_session() as db:
  1255. # Check if shortest-job-first scheduling is enabled
  1256. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  1257. # Get all pending items in the one order the queue page shows them
  1258. # in (#3200). The first eligible item takes a printer, so this order
  1259. # decides who wins a printer that a pinned job and an "Any <model>"
  1260. # job both want. It used to start with ``printer_id``, which made the
  1261. # lane outrank the position: SQLite sorts NULL first, so model-based
  1262. # jobs always won; PostgreSQL sorts it last, so pinned jobs did.
  1263. # Neither is what the user dragged into place.
  1264. if sjf_enabled:
  1265. # SJF: items already jumped get top priority (starvation guard),
  1266. # then sort by print_time ascending. Items with no print time go
  1267. # last, and position breaks ties.
  1268. result = await db.execute(
  1269. select(PrintQueueItem)
  1270. .where(PrintQueueItem.status == "pending")
  1271. # Never re-select a row a dispatch worker has already claimed
  1272. # (#2615) — belt-and-suspenders with the _inflight exclusion
  1273. # below, and the guard that lets an orphaned claim be ignored
  1274. # until startup reconciliation clears it.
  1275. .where(PrintQueueItem.dispatching_at.is_(None))
  1276. # archive/library_file are read by the cross-model gate
  1277. # (#2578); eager-load once per pass instead of a lazy-load
  1278. # (which would raise in async) per item.
  1279. .options(
  1280. selectinload(PrintQueueItem.archive),
  1281. selectinload(PrintQueueItem.library_file),
  1282. # Cross-model candidates (#671), plus each candidate's file
  1283. # for the same cross-model gate. Lazy-loading either would
  1284. # raise in async.
  1285. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1286. )
  1287. .order_by(
  1288. PrintQueueItem.been_jumped.desc(),
  1289. PrintQueueItem.print_time_seconds.asc().nullslast(),
  1290. PrintQueueItem.position,
  1291. PrintQueueItem.id,
  1292. )
  1293. )
  1294. else:
  1295. result = await db.execute(
  1296. select(PrintQueueItem)
  1297. .where(PrintQueueItem.status == "pending")
  1298. # Skip rows already claimed by a dispatch worker (#2615).
  1299. .where(PrintQueueItem.dispatching_at.is_(None))
  1300. .options(
  1301. selectinload(PrintQueueItem.archive),
  1302. selectinload(PrintQueueItem.library_file),
  1303. # Cross-model candidates (#671), plus each candidate's file
  1304. # for the same cross-model gate. Lazy-loading either would
  1305. # raise in async.
  1306. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1307. )
  1308. .order_by(PrintQueueItem.position, PrintQueueItem.id)
  1309. )
  1310. items = list(result.scalars().all())
  1311. # Drop rows whose upload is still in flight from an earlier pass
  1312. # (#2602). They stay `pending` until the upload finishes, so without
  1313. # this a fast tick would re-select and re-dispatch the same row.
  1314. # Belt-and-suspenders with the printer exclusion below.
  1315. if self._inflight:
  1316. inflight_ids = set(self._inflight)
  1317. items = [it for it in items if it.id not in inflight_ids]
  1318. # Read plate-clear setting once per queue check. Default MUST be
  1319. # False to match the schema (SettingsSchema.require_plate_clear
  1320. # defaults False) and the frontend (toggle + card badge both treat a
  1321. # missing value as off). When no settings row exists, a True default
  1322. # here re-enabled the plate-clear gate the UI showed as disabled,
  1323. # blocking dispatch to FINISH-state printers forever with no UI path
  1324. # to clear it (#1865).
  1325. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  1326. # Dispatch and track scheduled drying runs (#2638)
  1327. await self._check_scheduled_dryings(db)
  1328. if not items:
  1329. # No dispatchable pending items — still check auto-drying on idle
  1330. # printers, but keep any printer with an upload still in flight
  1331. # from an earlier pass out of it (#2602): its print is imminent,
  1332. # so it must not be auto-dried in the gap before the row flips to
  1333. # printing. Report the pass as productive while uploads run so the
  1334. # loop stays on the fast interval.
  1335. #
  1336. # Also release any keep-warm holds that got orphaned by the queue
  1337. # emptying — the normal sweep in `_apply_keep_warm` is skipped by
  1338. # this early return, so call it directly with an empty candidate
  1339. # set. Without this, a printer whose queued item was cancelled or
  1340. # deleted would keep its bed at target until the max-duration
  1341. # timeout expired.
  1342. self._sweep_keep_warm(active_candidates=set(), dispatched=set())
  1343. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  1344. await self._check_auto_drying(db, [], inflight_printers)
  1345. await self._check_filament_low(db)
  1346. await self._check_stock_forecast(db)
  1347. return bool(self._inflight)
  1348. logger.info(
  1349. "Queue check: found %d pending items: %s",
  1350. len(items),
  1351. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  1352. )
  1353. # Seed busy_printers with printers that already have an item in 'printing'
  1354. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  1355. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  1356. # lag several seconds behind the print command, so the next check_queue
  1357. # tick still sees IDLE and would double-dispatch onto the same printer.
  1358. # Without this guard, two pending items targeting the same printer
  1359. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  1360. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  1361. busy_result = await db.execute(
  1362. select(PrintQueueItem.printer_id)
  1363. .where(PrintQueueItem.status == "printing")
  1364. .where(PrintQueueItem.printer_id.is_not(None))
  1365. )
  1366. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  1367. # Why each printer left this pass, recorded where the decision is
  1368. # made rather than re-derived when the summary is logged. #3018's
  1369. # bundle shows what the old summary produced: "printer 1 not
  1370. # available -- connected=True, state=IDLE" immediately followed by a
  1371. # dispatch to printer 1. Two things went wrong at once. The line read
  1372. # live state at log time, which by then no longer matched the state
  1373. # the decision was made on; and `busy_printers` holds both printers
  1374. # that cannot take work and printers this pass has claimed for it,
  1375. # which are opposite facts. It is the first line anyone greps for
  1376. # "why did my item not go out", so it has to say which.
  1377. busy_reasons: dict[int, str] = dict.fromkeys(busy_printers, "an item is already printing on it")
  1378. # Printers this pass is dispatching to. They are in busy_printers so
  1379. # nothing else in the pass targets them -- that is a reservation, not
  1380. # an obstruction, and the summary says so.
  1381. claimed_printers: set[int] = set()
  1382. def mark_busy(printer_id: int, reason: str) -> None:
  1383. """Take ``printer_id`` out of this pass, recording why.
  1384. First reason wins: a printer already excluded by a stronger fact
  1385. -- a print running on it -- must not be relabelled by a weaker
  1386. check that ran later and would have excluded it anyway.
  1387. """
  1388. busy_printers.add(printer_id)
  1389. busy_reasons.setdefault(printer_id, reason)
  1390. def claim_printer(printer_id: int) -> None:
  1391. """Reserve ``printer_id`` for an item this pass is dispatching."""
  1392. claimed_printers.add(printer_id)
  1393. mark_busy(printer_id, "selected for dispatch in this pass")
  1394. # The user-facing half of `busy_reasons` (#3074). The same decisions
  1395. # worded for a different audience: the log wants "still inside its
  1396. # post-dispatch hold window", the queue row wants to know the printer
  1397. # is taken and nothing is broken. Only the cases that would read wrong
  1398. # as a plain "Busy" are recorded here; the rest fall back to it.
  1399. item_hold_reasons: dict[int, str] = {}
  1400. # Names and models for the printers this pass may have to write a
  1401. # waiting reason about, read once rather than per skip per tick. The
  1402. # model-based branch already has its names from `_printers_for_model`.
  1403. pinned_printer_ids = {i.printer_id for i in items if i.printer_id}
  1404. pinned_printers: dict[int, tuple[str, str]] = {}
  1405. if pinned_printer_ids:
  1406. pinned_rows = await db.execute(
  1407. select(Printer.id, Printer.name, Printer.model).where(Printer.id.in_(pinned_printer_ids))
  1408. )
  1409. pinned_printers = {pid: (name or "", model or "") for pid, name, model in pinned_rows.all()}
  1410. def printer_label(printer_id: int) -> str:
  1411. """What to call this printer in a queue row."""
  1412. entry = pinned_printers.get(printer_id)
  1413. return (entry[0] if entry else "") or f"printer {printer_id}"
  1414. async def hold_item(item: PrintQueueItem, reason: str | None, *, notify: bool = True) -> None:
  1415. """Record why *item* is not going out, in the words the queue row shows.
  1416. The fixed-printer branch's single writer for ``waiting_reason``
  1417. (#3074). Before this, the sensor interlock was the only thing that
  1418. wrote the field there, so an item pinned to a printer that was
  1419. merely printing sat at `pending` with nothing to show for it —
  1420. indistinguishable from a queue that had stopped working — while
  1421. the same job queued as "Any <model>" explained itself.
  1422. Every exit from that branch now calls this, which is also what
  1423. replaced the interlock's old habit of clearing the field up front:
  1424. a lifted hold cannot leave "Waiting on Enclosure Door" standing,
  1425. because whichever exit runs next overwrites it and the dispatch
  1426. path clears it.
  1427. A notification goes out when this item starts asking for
  1428. something, and only then: the new reason needs the user, and what
  1429. it replaced did not. "What it replaced did not" has to include a
  1430. busy-only reason, not just an empty one. The sequence this branch
  1431. actually produces is a print running (``Busy: X1C-01``) and then
  1432. the plate it left behind (``Waiting for plate confirmation``), and
  1433. testing "was the field empty" would call that no transition at all
  1434. and stay quiet through the one case worth saying out loud.
  1435. The cost is that a printer dropping offline, coming back busy and
  1436. dropping again asks twice rather than once. That is the honest
  1437. reading — it went wrong twice — and the alternative was a rule
  1438. that never fired for the case this was built for.
  1439. *notify* is how a caller opts out. The sensor interlock does: it
  1440. has never sent this notification, and a change about what the
  1441. queue *displays* is not the place to start (#1148).
  1442. """
  1443. if item.waiting_reason == reason:
  1444. return
  1445. # Busy-only and empty are the same thing here: neither is the
  1446. # queue asking the user for anything.
  1447. was_asking = bool(item.waiting_reason) and not self._is_busy_only(item.waiting_reason)
  1448. item.waiting_reason = reason
  1449. await db.commit()
  1450. if not notify or not reason or was_asking or self._is_busy_only(reason):
  1451. return
  1452. try:
  1453. job_name = await self._get_job_name(db, item)
  1454. entry = pinned_printers.get(item.printer_id) if item.printer_id else None
  1455. await notification_service.on_queue_job_waiting(
  1456. job_name=job_name,
  1457. target_model=(entry[1] if entry else "") or "",
  1458. waiting_reason=reason,
  1459. db=db,
  1460. )
  1461. except Exception as e:
  1462. # A queue that cannot say why it is waiting is the bug being
  1463. # fixed here; a queue that stops dispatching because a
  1464. # notification provider is down would be a worse one.
  1465. logger.debug("Waiting notification failed for item %s: %s", item.id, e)
  1466. async def hold_for_printer(
  1467. item: PrintQueueItem, printer_id: int, log_reason: str, item_reason: str
  1468. ) -> None:
  1469. """Take *printer_id* out of this pass and tell the item's owner why."""
  1470. mark_busy(printer_id, log_reason)
  1471. item_hold_reasons.setdefault(printer_id, item_reason)
  1472. await hold_item(item, item_reason)
  1473. # Defense-in-depth (#1157): augment busy_printers with any printer
  1474. # still in its post-dispatch hold window. Empirically, the DB seed
  1475. # above can miss in-flight items in a multi-plate batch — same-file
  1476. # plates were being dispatched 30 s apart while the H2D was still
  1477. # digesting the first project_file. The hold is keyed in-memory and
  1478. # released by the watchdog on the success path, so it adds a layer
  1479. # that doesn't depend on DB row visibility or completion-callback
  1480. # timing.
  1481. for held_printer_id in list(self._dispatch_holds.keys()):
  1482. if self._printer_in_dispatch_hold(held_printer_id):
  1483. mark_busy(held_printer_id, "still inside its post-dispatch hold window")
  1484. # Exclude printers whose upload is still in flight from an earlier
  1485. # pass (#2602). The row is `pending` until the upload finishes and
  1486. # the printing-state seed / dispatch hold above only arm once the
  1487. # upload completes, so this is what holds the printer (and, via
  1488. # busy_printers, its auto-drying) out of the pass during the upload.
  1489. for _task, inflight_pid in self._inflight.values():
  1490. if inflight_pid is not None:
  1491. mark_busy(inflight_pid, "an upload to it is still in flight")
  1492. # Snapshot taken here, before the item loop adds anything (#2801).
  1493. #
  1494. # The three sources above all mean the same thing: a print on this
  1495. # printer is running or imminent. Everything the loop adds below
  1496. # means only "the queue could not dispatch to it this pass", which
  1497. # is a different statement -- a printer waiting on a plate-clear
  1498. # acknowledgment, an offline printer, one with no matching file.
  1499. #
  1500. # Auto-drying must only see the first kind. Reading the whole set
  1501. # as "is currently printing" is what put a plate-held printer down
  1502. # the mid-print path: it capped the drying temperature, logged the
  1503. # cycle as (mid-print), and skipped the very gate that was supposed
  1504. # to hold it. The interlock block below already documents the same
  1505. # hazard and works around it by staying out of busy_printers; this
  1506. # generalises that workaround instead of repeating it per case.
  1507. dispatching_printers: set[int] = set(busy_printers)
  1508. # Printers whose last upload never reached them (#3210). After the
  1509. # snapshot above on purpose: such a printer is idle, not about to
  1510. # print, and auto-drying must keep treating it as idle.
  1511. now_mono = time.monotonic()
  1512. # In backoff this pass. Kept apart from busy_printers so keep-warm
  1513. # can leave them out: there is no print to keep a bed warm for.
  1514. backoff_printers: set[int] = set()
  1515. # In backoff, and the "job waiting" notification for this run of
  1516. # refusals has gone out already. Their holds are written silently.
  1517. silent_hold_printers: set[int] = set()
  1518. for backoff_pid, retry_at in list(self._upload_backoff.items()):
  1519. if now_mono >= retry_at:
  1520. del self._upload_backoff[backoff_pid]
  1521. continue
  1522. backoff_printers.add(backoff_pid)
  1523. if backoff_pid in self._upload_refusal_notified:
  1524. silent_hold_printers.add(backoff_pid)
  1525. else:
  1526. self._upload_refusal_notified.add(backoff_pid)
  1527. mark_busy(
  1528. backoff_pid,
  1529. f"its file service refused the last upload; retrying in {retry_at - now_mono:.0f}s",
  1530. )
  1531. item_hold_reasons.setdefault(
  1532. backoff_pid,
  1533. f"{printer_label(backoff_pid)} is not accepting files — Bambuddy will retry automatically",
  1534. )
  1535. # Printers held by a Home Assistant sensor interlock (#1148) — an
  1536. # enclosure door left open, say. The fixed-printer branch turns
  1537. # this into a waiting_reason the user can act on; the model-based
  1538. # branch hides these printers from the matcher so an "Any <model>"
  1539. # job runs on a sibling instead of queueing behind the held one.
  1540. #
  1541. # Deliberately NOT merged into busy_printers, even though that set
  1542. # already means "unavailable this pass". _check_auto_drying reads
  1543. # it as "is currently printing" and would put an idle-but-held
  1544. # printer down the mid-print drying path, which caps the drying
  1545. # temperature and skips the queue-only gating. A held printer is
  1546. # idle; it should dry exactly as it did before.
  1547. #
  1548. # Only sensors we actually read and found alerting appear here; see
  1549. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  1550. # holds nothing.
  1551. interlocked: dict[int, str] = {}
  1552. try:
  1553. interlocked = await ha_sensor_manager.blocked_printers(db)
  1554. except Exception as e:
  1555. # Never let the interlock stop the queue running. A broken
  1556. # lookup means no holds, not no dispatches.
  1557. logger.warning("Home Assistant interlock check failed: %s", e)
  1558. interlocked = {}
  1559. # Printers a smart plug can bring back, read once for the whole pass
  1560. # (#2786). Used by the model-based branch both to word "Offline" in
  1561. # the waiting reason and to decide what the wake step may switch on.
  1562. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  1563. # At most one power-on per queue check. Each one blocks this loop
  1564. # for the boot wait, so a queue of ten class-targeted jobs must not
  1565. # switch on ten printers inside a single pass — the next pass wakes
  1566. # the next one (#2786).
  1567. power_on_attempted = False
  1568. # Log skip reasons once per queue check (not per item)
  1569. skip_reasons: dict[str, int] = {}
  1570. # Items selected for dispatch in this pass, one per printer. The
  1571. # loop below only *decides* — the uploads happen afterwards, in
  1572. # parallel (#2555). See _dispatch_selected().
  1573. dispatch_ids: list[int] = []
  1574. # Library rows queued with `cleanup_library_after_dispatch` (the
  1575. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  1576. # that prints them: the row is deleted and the 3MF is unlinked from
  1577. # disk. That was safe only because dispatch was serial. Run two of
  1578. # them against the same row at once and the second DELETE matches no
  1579. # row (StaleDataError), and the winner's unlink can pull the file out
  1580. # from under the loser's in-flight upload.
  1581. #
  1582. # Only the cleanup flag mutates the row. An ordinary library print
  1583. # just reads it, so the common fan-out — one file, many printers,
  1584. # which is exactly the reporter's workload — still goes out fully in
  1585. # parallel. Narrow the guard to the mutating case; do not serialise
  1586. # the case the whole fix exists for.
  1587. dispatch_libs: set[int] = set()
  1588. consumed_libs: set[int] = set()
  1589. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  1590. """True if dispatching `candidate` now would race another item's cleanup."""
  1591. lib_id = candidate.library_file_id
  1592. if lib_id is None:
  1593. return False
  1594. if candidate.cleanup_library_after_dispatch:
  1595. # We would delete a row someone else in this pass is reading.
  1596. return lib_id in dispatch_libs
  1597. # Someone else in this pass will delete the row out from under us.
  1598. return lib_id in consumed_libs
  1599. def _claim_library_row(candidate: PrintQueueItem) -> None:
  1600. lib_id = candidate.library_file_id
  1601. if lib_id is None:
  1602. return
  1603. dispatch_libs.add(lib_id)
  1604. if candidate.cleanup_library_after_dispatch:
  1605. consumed_libs.add(lib_id)
  1606. for item in items:
  1607. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  1608. if item.scheduled_time:
  1609. sched = item.scheduled_time
  1610. if sched.tzinfo is None:
  1611. sched = sched.replace(tzinfo=timezone.utc)
  1612. if sched > datetime.now(timezone.utc):
  1613. # Waiting on the clock, not on a printer.
  1614. await hold_item(item, None)
  1615. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  1616. continue
  1617. # Skip items that require manual start
  1618. if item.manual_start:
  1619. # Waiting on the user, not on a printer. Cleared here because
  1620. # this is the last pass that will look at the row: a staged
  1621. # item never reaches the branches below again, so a reason
  1622. # left from before it was staged would stand forever (#3074).
  1623. # The one exception is the unmatched-filament hold, whose
  1624. # reason was written at staging and is why the item waits:
  1625. # it names the filament to load (#2799). Pressing start
  1626. # clears manual_start, and the branches below overwrite it.
  1627. keep = item.waiting_reason if _is_unmatched_hold_reason(item.waiting_reason) else None
  1628. await hold_item(item, keep)
  1629. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  1630. continue
  1631. if item.printer_id:
  1632. # Held by a sensor interlock (#1148). Checked before the
  1633. # busy_printers test that would otherwise swallow it
  1634. # silently — "waiting for a printer" and "waiting for you
  1635. # to shut the enclosure" need to read differently, and only
  1636. # one of them is something the user can fix.
  1637. #
  1638. # It used to be the only thing that wrote a waiting_reason on
  1639. # this branch, and it cleared the field up front so a lifted
  1640. # hold could not leave a shut door reading "Waiting on
  1641. # Enclosure Door". `hold_item` carries that guarantee now —
  1642. # every exit below writes — so the clear is gone and the
  1643. # interlock is an ordinary hold like the rest (#3074).
  1644. interlock_reason = interlocked.get(item.printer_id)
  1645. if interlock_reason:
  1646. # Silent, exactly as it has always been. #1148 built this
  1647. # as a hold that shows on the row, never as an alert, and
  1648. # routing it through the shared writer must not quietly
  1649. # turn every open door into a notification.
  1650. await hold_item(item, f"Waiting on {interlock_reason}", notify=False)
  1651. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  1652. continue
  1653. # Specific printer assignment (existing behavior)
  1654. if item.printer_id in busy_printers:
  1655. # Whatever took the printer out of this pass — a print
  1656. # already running on it, a post-dispatch hold, an upload
  1657. # still in flight, an item ahead of this one in the same
  1658. # pass — reads the same way from the queue: the printer is
  1659. # taken and this item is in line for it. The exceptions
  1660. # that do not (an offline printer, say) recorded their own
  1661. # wording in `item_hold_reasons` when they held it.
  1662. await hold_item(
  1663. item,
  1664. item_hold_reasons.get(item.printer_id) or f"Busy: {printer_label(item.printer_id)}",
  1665. notify=item.printer_id not in silent_hold_printers,
  1666. )
  1667. continue
  1668. # Check if printer is idle
  1669. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1670. printer_connected = printer_manager.is_connected(item.printer_id)
  1671. # If printer not connected, try to power on via smart plug
  1672. if not printer_connected:
  1673. plugs = await self._get_smart_plugs(db, item.printer_id)
  1674. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1675. if auto_on_plugs:
  1676. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  1677. # Power on using the plug that actually feeds the printer, and
  1678. # wait for it to boot on that one only (#2629).
  1679. primary_plug = self._pick_power_plug(auto_on_plugs)
  1680. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  1681. if powered_on:
  1682. # Also turn on any remaining auto_on plugs (e.g., filter)
  1683. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1684. try:
  1685. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1686. await service.turn_on(extra_plug)
  1687. logger.info(
  1688. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  1689. )
  1690. except Exception as e:
  1691. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1692. printer_connected = True
  1693. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  1694. else:
  1695. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  1696. await hold_for_printer(
  1697. item,
  1698. item.printer_id,
  1699. "smart-plug power-on failed",
  1700. f"Offline: {printer_label(item.printer_id)} — the smart plug could not power it on",
  1701. )
  1702. continue
  1703. else:
  1704. # No plug or auto_on disabled. Worded exactly as the
  1705. # model-based branch words it (#2786): this is the one
  1706. # entry on that list the user has to act on, because
  1707. # Bambuddy will never switch this printer on itself.
  1708. await hold_for_printer(
  1709. item,
  1710. item.printer_id,
  1711. "offline, with no smart plug to power it on",
  1712. f"Offline, no Auto On smart plug: {printer_label(item.printer_id)}",
  1713. )
  1714. continue
  1715. # Check if printer is idle (busy with another print)
  1716. if not printer_idle:
  1717. await hold_for_printer(
  1718. item,
  1719. item.printer_id,
  1720. "not idle",
  1721. self._pinned_hold_reason(
  1722. item.printer_id, printer_label(item.printer_id), require_plate_clear
  1723. ),
  1724. )
  1725. continue
  1726. # Drying blocks the queue, if the user asked it to. A hold
  1727. # is a skip like any other, so it belongs here with the
  1728. # rest of the availability checks.
  1729. # A parked timer (#2896) never ends, so it must not hold the
  1730. # queue; it stays tracked so the stop paths still reach it.
  1731. if (
  1732. self._drying_in_progress.get(item.printer_id)
  1733. and not self._drying_is_only_parked(item.printer_id)
  1734. and await self._get_bool_setting(db, "queue_drying_block")
  1735. ):
  1736. # Busy-shaped on purpose: the cycle ends on its own and
  1737. # the job goes out, so there is nothing to alert about.
  1738. await hold_for_printer(
  1739. item,
  1740. item.printer_id,
  1741. "drying, and drying is set to block the queue",
  1742. f"Busy: {printer_label(item.printer_id)} (drying)",
  1743. )
  1744. continue
  1745. # Check condition (previous print success)
  1746. if item.require_previous_success:
  1747. if not await self._check_previous_success(db, item):
  1748. item.status = "skipped"
  1749. item.error_message = "Previous print failed or was aborted"
  1750. item.completed_at = datetime.now(timezone.utc)
  1751. # Not pending any more, so not waiting for anything.
  1752. item.waiting_reason = None
  1753. await db.commit()
  1754. logger.info("Skipped queue item %s - previous print failed", item.id)
  1755. # Send notification
  1756. job_name = await self._get_job_name(db, item)
  1757. printer = await self._get_printer(db, item.printer_id)
  1758. await notification_service.on_queue_job_skipped(
  1759. job_name=job_name,
  1760. printer_id=item.printer_id,
  1761. printer_name=printer.name if printer else "Unknown",
  1762. reason="Previous print failed or was aborted",
  1763. db=db,
  1764. )
  1765. continue
  1766. # Resolve the AMS mapping when it's missing OR unresolved
  1767. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  1768. # frontend status-load race can persist [-1] (#2589) — and
  1769. # must be recomputed from live trays rather than trusted.
  1770. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  1771. if unmappable:
  1772. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  1773. continue
  1774. # Filament-deficit pre-dispatch check (#1496). If the
  1775. # assigned spool can't satisfy any required slot grams,
  1776. # promote the item to manual_start so the user must
  1777. # acknowledge via the ▶ button (which re-checks live).
  1778. if await self._block_on_filament_deficit(db, item):
  1779. # Now staged for the user to start by hand, and the row
  1780. # shows the filament-short badge instead. Cleared because
  1781. # a staged item never reaches this branch again.
  1782. await hold_item(item, None)
  1783. continue
  1784. # Unmatched-filament pre-dispatch check (#2799). Hold rather
  1785. # than let the printer pick a substitute for a slot the
  1786. # matcher could not resolve on this printer.
  1787. if await self._block_on_unmatched_filament(db, item):
  1788. continue
  1789. # Hold this item back for the next pass rather than racing
  1790. # another dispatch over the same transient library row. The
  1791. # printer is still marked busy so a later item does not jump
  1792. # its place in this printer's queue.
  1793. if _library_row_conflict(item):
  1794. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1795. await hold_for_printer(
  1796. item,
  1797. item.printer_id,
  1798. "holding its place while another item releases a library row",
  1799. f"Busy: {printer_label(item.printer_id)}",
  1800. )
  1801. continue
  1802. # Print takes priority: stop a cycle Bambuddy armed, now
  1803. # that this item is definitely going out.
  1804. #
  1805. # Placement is the whole point (#2801). This used to sit up
  1806. # with the availability checks, inside the not-idle branch
  1807. # -- so it fired only on the passes where the print was NOT
  1808. # going to start, and never on the ones where it was.
  1809. # Drying is not one of the things `_is_printer_idle` looks
  1810. # at, so a stop could never have unblocked that printer
  1811. # anyway; the cycle was spent for nothing, auto-drying
  1812. # re-armed on the next tick, and a plate left
  1813. # unacknowledged turned that into a loop on the scheduler
  1814. # interval. Every skip between there and here -- a failed
  1815. # previous print, an unmappable item, a filament deficit, a
  1816. # contested library row -- is another way to lose a cycle
  1817. # for a print that never happens, which is why this waits
  1818. # until the decision is actually made.
  1819. if self._drying_in_progress.get(
  1820. item.printer_id
  1821. ) and not await self._drying_may_continue_through_print(db, item.printer_id):
  1822. await self._stop_drying(item.printer_id)
  1823. # Queue the dispatch instead of running it here — see
  1824. # _dispatch_selected(). busy_printers still gets the printer
  1825. # immediately, so nothing else in this pass can target it.
  1826. #
  1827. # The reason goes first: this item is not waiting for anything
  1828. # any more, and the model-based branch clears its own at the
  1829. # equivalent moment (#3074).
  1830. await hold_item(item, None)
  1831. _claim_library_row(item)
  1832. dispatch_ids.append(item.id)
  1833. claim_printer(item.printer_id)
  1834. # SJF starvation guard: mark items that were jumped
  1835. if sjf_enabled and item.print_time_seconds is not None:
  1836. pinned_model = pinned_printers.get(item.printer_id, ("", ""))[1]
  1837. for other in items:
  1838. if (
  1839. other.id != item.id
  1840. and other.id not in dispatch_ids
  1841. and other.status == "pending"
  1842. and _could_take_printer(other, item.printer_id, pinned_model)
  1843. and not other.been_jumped
  1844. and other.position < item.position
  1845. and (
  1846. other.print_time_seconds is None
  1847. or other.print_time_seconds > item.print_time_seconds
  1848. )
  1849. ):
  1850. other.been_jumped = True
  1851. await db.commit()
  1852. elif item.target_model or item.variants:
  1853. # Model-based assignment - find any idle printer of matching model.
  1854. # A plain model-based item has exactly one candidate, built from
  1855. # its own columns. A cross-model item (#671) has one per sliced
  1856. # variant and takes the first that matches, walking them in the
  1857. # user's priority order so the pick is reproducible when more
  1858. # than one printer is free in the same pass.
  1859. candidates = _candidates_for(item)
  1860. printer_id = None
  1861. chosen: _ModelCandidate | None = None
  1862. per_model_reasons: list[tuple[str | None, str]] = []
  1863. # Candidates that cleared the cross-model gate below. The
  1864. # smart-plug wake step may only consider these — waking a
  1865. # printer for a file that can never legally run on it is
  1866. # worse than not waking at all (#2786).
  1867. wakeable_candidates: list[_ModelCandidate] = []
  1868. if not candidates:
  1869. # Every candidate file has been deleted or trashed out from
  1870. # under this item. Hold it with something the user can act
  1871. # on rather than letting it look dispatchable forever.
  1872. per_model_reasons.append(
  1873. (
  1874. item.target_model,
  1875. "Every file for this job has been deleted — add a file back or remove the item",
  1876. )
  1877. )
  1878. for candidate in candidates:
  1879. effective_types, filament_overrides = _filament_constraints(candidate)
  1880. # Cross-model safety gate (#2578): never hand a 3MF sliced
  1881. # for an incompatible model to a printer, no matter how the
  1882. # row got into the DB (old rows, direct API writes). Held
  1883. # as pending with an actionable waiting_reason — the user
  1884. # fixes it by editing the item's target model.
  1885. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  1886. per_model_reasons.append(
  1887. (
  1888. candidate.target_model,
  1889. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  1890. f"{candidate.target_model} — edit the item and fix its target model",
  1891. )
  1892. )
  1893. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  1894. continue
  1895. wakeable_candidates.append(candidate)
  1896. match_id, match_reason = await self._find_idle_printer_for_model(
  1897. db,
  1898. candidate.target_model,
  1899. # Sensor-held printers are unavailable to the
  1900. # matcher but stay out of busy_printers itself
  1901. # (#1148) — see where `interlocked` is built.
  1902. busy_printers | interlocked.keys(),
  1903. effective_types,
  1904. item.target_location,
  1905. filament_overrides=filament_overrides,
  1906. require_plate_clear=require_plate_clear,
  1907. wakeable_ids=wakeable_printer_ids,
  1908. )
  1909. if match_id:
  1910. printer_id = match_id
  1911. chosen = candidate
  1912. break
  1913. per_model_reasons.append((candidate.target_model, match_reason or ""))
  1914. # Nothing is available and nothing has been woken this pass:
  1915. # switch one matching printer on. Assignment is left to the
  1916. # next pass, which sees the booted printer's live state
  1917. # instead of guessing at it seconds after connect (#2786).
  1918. if printer_id is None and not power_on_attempted and wakeable_candidates:
  1919. woken_id, attempted_id = await self._wake_printer_for_model(
  1920. db,
  1921. wakeable_candidates,
  1922. item.target_location,
  1923. busy_printers | interlocked.keys(),
  1924. wakeable_printer_ids,
  1925. require_plate_clear,
  1926. )
  1927. # An attempt spends the pass's one wake whether or not
  1928. # it worked: it has already blocked the queue loop for
  1929. # the boot wait. A failed printer is held out of later
  1930. # passes by its own cool-off, deliberately NOT by
  1931. # busy_printers — it is off, not busy, and labelling it
  1932. # busy would both misdescribe it in every later item's
  1933. # waiting reason and suppress the notification, since
  1934. # an all-busy reason is treated as needing no action.
  1935. power_on_attempted = attempted_id is not None
  1936. if woken_id is not None:
  1937. # Hold this item back rather than dispatching onto a
  1938. # printer whose AMS has not reported yet.
  1939. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  1940. continue
  1941. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  1942. # Fold the winning variant's file and settings onto the item
  1943. # before anything else looks at them — the guards below and
  1944. # every step of the dispatch read the item's own columns.
  1945. if chosen is not None:
  1946. self._resolve_variant(item, chosen)
  1947. # Update waiting_reason if changed and send notification when first waiting
  1948. if item.waiting_reason != waiting_reason:
  1949. was_waiting = item.waiting_reason is not None
  1950. item.waiting_reason = waiting_reason
  1951. await db.commit()
  1952. # Send waiting notification only when transitioning to waiting state
  1953. # and the reason requires user action (not just "all printers busy")
  1954. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  1955. job_name = await self._get_job_name(db, item)
  1956. await notification_service.on_queue_job_waiting(
  1957. job_name=job_name,
  1958. target_model=_candidate_model_label(candidates) or item.target_model,
  1959. waiting_reason=waiting_reason,
  1960. db=db,
  1961. )
  1962. if printer_id:
  1963. # Before claiming the printer: hold back rather than race
  1964. # another dispatch over the same transient library row.
  1965. # Checked here so a held item does not get a printer
  1966. # assigned and then sit on it. See _library_row_conflict().
  1967. #
  1968. # No busy_printers.add() here, unlike the fixed-printer
  1969. # branch above: that one protects its printer's own queue
  1970. # ordering, but this item was never assigned to `printer_id`
  1971. # — the matcher merely offered it. Marking it busy would
  1972. # strand an idle printer for the rest of the pass.
  1973. if _library_row_conflict(item):
  1974. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1975. continue
  1976. # Check condition (previous print success) before assigning
  1977. if item.require_previous_success:
  1978. if not await self._check_previous_success(db, item):
  1979. item.status = "skipped"
  1980. item.error_message = "Previous print failed or was aborted"
  1981. item.completed_at = datetime.now(timezone.utc)
  1982. await db.commit()
  1983. logger.info("Skipped queue item %s - previous print failed", item.id)
  1984. # Send notification
  1985. job_name = await self._get_job_name(db, item)
  1986. printer = await self._get_printer(db, printer_id)
  1987. await notification_service.on_queue_job_skipped(
  1988. job_name=job_name,
  1989. printer_id=printer_id,
  1990. printer_name=printer.name if printer else "Unknown",
  1991. reason="Previous print failed or was aborted",
  1992. db=db,
  1993. )
  1994. continue
  1995. # Assign printer and start - clear waiting reason
  1996. item.printer_id = printer_id
  1997. item.waiting_reason = None
  1998. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  1999. # Send assignment notification
  2000. job_name = await self._get_job_name(db, item)
  2001. printer = await self._get_printer(db, printer_id)
  2002. await notification_service.on_queue_job_assigned(
  2003. job_name=job_name,
  2004. printer_id=printer_id,
  2005. printer_name=printer.name if printer else "Unknown",
  2006. target_model=item.target_model,
  2007. db=db,
  2008. )
  2009. # Resolve the AMS mapping for the assigned printer when it's
  2010. # missing OR unresolved (all -1). Critical for model-based
  2011. # jobs where mapping wasn't computed upfront, and it also
  2012. # self-heals a bogus stored [-1] (#2589).
  2013. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  2014. if unmappable:
  2015. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  2016. continue
  2017. # Filament-deficit pre-dispatch check (#1496).
  2018. if await self._block_on_filament_deficit(db, item):
  2019. continue
  2020. # Unmatched-filament pre-dispatch check (#2799). Model-based
  2021. # selection already filters on filament type, so this is a
  2022. # backstop for an AMS that changed between assignment and
  2023. # dispatch, and for a type loaded on the wrong nozzle.
  2024. # The assignment made above is released with the hold —
  2025. # this item asked for a model, not this printer.
  2026. if await self._block_on_unmatched_filament(db, item, release_assignment=True):
  2027. continue
  2028. _claim_library_row(item)
  2029. dispatch_ids.append(item.id)
  2030. claim_printer(printer_id)
  2031. # SJF starvation guard: mark items that were jumped
  2032. if sjf_enabled and item.print_time_seconds is not None:
  2033. for other in items:
  2034. if (
  2035. other.id != item.id
  2036. and other.id not in dispatch_ids
  2037. and other.status == "pending"
  2038. and _could_take_printer(other, printer_id, item.target_model)
  2039. and not other.been_jumped
  2040. and other.position < item.position
  2041. and (
  2042. other.print_time_seconds is None
  2043. or other.print_time_seconds > item.print_time_seconds
  2044. )
  2045. ):
  2046. other.been_jumped = True
  2047. await db.commit()
  2048. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  2049. # as long as the slowest upload takes (minutes on a big 3MF), and a
  2050. # skip summary that only lands after the transfers have finished is
  2051. # useless for working out why an item did not go out.
  2052. if skip_reasons:
  2053. logger.info("Queue skip summary: %s", skip_reasons)
  2054. for pid in sorted(busy_printers):
  2055. reason = busy_reasons.get(pid, "no reason recorded")
  2056. if pid in claimed_printers:
  2057. logger.info("Queue: printer %d reserved — %s", pid, reason)
  2058. continue
  2059. # The three live fields stay, because they are what someone
  2060. # reading a bundle wants next -- but they are labelled as read
  2061. # now, not as the state the decision was made on, which is what
  2062. # made the old line contradict itself.
  2063. state = printer_manager.get_status(pid)
  2064. logger.info(
  2065. "Queue: printer %d unavailable — %s (now: connected=%s, state=%s, awaiting_plate_clear=%s)",
  2066. pid,
  2067. reason,
  2068. printer_manager.is_connected(pid),
  2069. state.state if state else "NO_STATUS",
  2070. printer_manager.is_awaiting_plate_clear(pid),
  2071. )
  2072. # Keep-warm is a comfort feature; dispatch is not. It sits between
  2073. # selection and `_launch_uploads`, so anything raising here would
  2074. # discard this tick's selections — computed AMS mappings and all —
  2075. # and, on a persistent fault, stop the queue dispatching entirely.
  2076. # Same reasoning as the deficit check's guard below: never let an
  2077. # auxiliary check wedge the queue. The bed simply stays wherever it
  2078. # was, and the next tick tries again.
  2079. try:
  2080. await self._apply_keep_warm(
  2081. db, items, dispatch_ids, busy_printers - backoff_printers, require_plate_clear
  2082. )
  2083. except Exception as e:
  2084. logger.warning("Keep-warm pass failed, continuing with dispatch: %s", e, exc_info=True)
  2085. # Read the concurrency limit BEFORE the commit below, not inside
  2086. # _dispatch_selected(). A SELECT on this session after the commit
  2087. # implicitly opens a fresh transaction that nothing then closes, and
  2088. # it would stay open for the whole dispatch — minutes of "idle in
  2089. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  2090. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  2091. # checkpointed while every dispatch is writing to it.
  2092. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  2093. # Selection is done; every decision above is recorded on `db`
  2094. # (model-based printer assignment, computed ams_mapping). Flush it
  2095. # before the dispatch tasks open their own sessions, or they will
  2096. # read a row that still says printer_id=None. This also releases the
  2097. # connection back to the pool for the duration of the dispatch.
  2098. await db.commit()
  2099. if dispatch_ids:
  2100. item_printers = {it.id: it.printer_id for it in items}
  2101. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  2102. # Auto-drying: start drying on idle printers that have no pending queue items
  2103. await self._check_auto_drying(db, items, dispatching_printers)
  2104. # Low filament: alert on assigned spools that have crossed their
  2105. # low-stock threshold (#2913). Runs on both paths out of this method
  2106. # for the same reason auto-drying does — an empty queue does not mean
  2107. # the spools in the printers stopped mattering.
  2108. await self._check_filament_low(db)
  2109. # Stock forecast: alert when a filament SKU reaches its reorder point or
  2110. # is about to run out before a replenishment could arrive (#2955).
  2111. await self._check_stock_forecast(db)
  2112. # Keep the loop on the fast interval while any upload is in flight so
  2113. # a slot freed mid-tick refills within seconds rather than after the
  2114. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  2115. # deferred because the pool was full) also counts as productive.
  2116. return bool(dispatch_ids) or bool(self._inflight)
  2117. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  2118. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  2119. Dispatch used to happen inline in the selection loop: ``await
  2120. _start_print(db, item)`` per item in turn. Since ``_start_print``
  2121. performs the FTP upload, that serialized every printer behind every
  2122. other printer's transfer even though the printers are independent
  2123. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  2124. gather was awaited before ``check_queue`` returned, so the run loop
  2125. stayed blocked until the *slowest* upload in the batch finished — a
  2126. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  2127. 93-printer farm even as other printers came free (#2602).
  2128. Each upload now runs as an independent background task tracked in
  2129. ``self._inflight``. check_queue excludes in-flight item_ids (still
  2130. `pending` until their upload completes) and their printers from the
  2131. next pass's selection, and this method launches at most
  2132. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  2133. the next fast tick instead of waiting out the whole batch. The bound
  2134. exists because the printers are independent but the host is not: each
  2135. in-flight upload holds a thread in the FTP pool, a TLS session and a
  2136. file handle.
  2137. The no-overlapping-dispatch invariant the batch-await used to provide
  2138. is now carried by the in-flight exclusion in check_queue. Everything
  2139. else — the pending->printing CAS, the busy-printer guard (#2598), the
  2140. per-printer hold, and each item's independent failure handling — still
  2141. lives in ``_start_print`` and runs per task exactly as before.
  2142. Synchronous on purpose: it registers every launched task into
  2143. ``self._inflight`` before returning, so the next (sequential) tick sees
  2144. an accurate in-flight count with no interleaving await.
  2145. """
  2146. free = limit - len(self._inflight)
  2147. if free <= 0:
  2148. logger.info(
  2149. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  2150. len(self._inflight),
  2151. limit,
  2152. len(item_ids),
  2153. item_ids,
  2154. )
  2155. return
  2156. to_launch = item_ids[:free]
  2157. deferred = item_ids[free:]
  2158. logger.info(
  2159. "Launching %d upload(s) (pool %d/%d in flight)%s",
  2160. len(to_launch),
  2161. len(self._inflight),
  2162. limit,
  2163. f" — deferring {deferred} to a later tick" if deferred else "",
  2164. )
  2165. for item_id in to_launch:
  2166. task = spawn_background_task(
  2167. self._dispatch_one(item_id, item_printers.get(item_id)),
  2168. name=f"queue-upload-{item_id}",
  2169. )
  2170. self._inflight[item_id] = (task, item_printers.get(item_id))
  2171. # Prune on completion so the freed slot is refillable next tick.
  2172. # spawn_background_task already logs any uncaught exception; this
  2173. # only reclaims the pool slot (fires on success, failure, or cancel).
  2174. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  2175. async def _dispatch_one(self, item_id: int, selected_printer_id: int | None = None) -> None:
  2176. """Upload + start one queue item in its own session (pool worker, #2602).
  2177. Its own session: pool workers run concurrently and an AsyncSession is
  2178. not safe to share across tasks; it also keeps a slow upload from pinning
  2179. the scheduler's session (and, on SQLite, its transaction) open for the
  2180. transfer's duration.
  2181. ``selected_printer_id`` is the printer this item was selected for, taken
  2182. from the same snapshot the caller used. It exists so the preheat pin can
  2183. be unwound on the paths that never reach the ``finally`` below — see the
  2184. claim failure a few lines down. Optional so the direct-call tests keep
  2185. working; when it is absent those paths simply behave as they did before.
  2186. """
  2187. async with async_session() as item_db:
  2188. # Claim the row for dispatch BEFORE reading the printer snapshot or
  2189. # touching any slow I/O (#2615). The claim is an atomic CAS on
  2190. # (status='pending', dispatching_at IS NULL); while it's held the edit
  2191. # routes reject reassignment (409), so printer_id can't change out from
  2192. # under the in-flight upload and split the queue row from the
  2193. # archive/expected-print/physical command.
  2194. if not await self._claim_for_dispatch(item_db, item_id):
  2195. logger.info(
  2196. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  2197. item_id,
  2198. )
  2199. # This return is outside the try/finally below, so the rollback
  2200. # has to happen here. Selecting this item already handed any
  2201. # keep-warm hold on its printer over to the preheat pin
  2202. # (`_sweep_keep_warm`), on the promise that this dispatch would
  2203. # unwind it. Bailing without doing so leaves the bed hot with
  2204. # nothing tracking it: the keep-warm entry is gone, so the
  2205. # max-duration cap no longer applies, and if this was the
  2206. # printer's last pending item nothing else will ever turn it
  2207. # off. Reachable whenever a cancel or delete lands between
  2208. # selection and the claim.
  2209. if selected_printer_id is not None:
  2210. self._rollback_preheat_pin(item_id, selected_printer_id)
  2211. return
  2212. # Seeded from the caller's snapshot so the `item vanished` return
  2213. # below still unwinds the pin; overwritten with the row's own
  2214. # printer_id as soon as we have it.
  2215. item_printer_id: int | None = selected_printer_id
  2216. try:
  2217. item = await item_db.get(PrintQueueItem, item_id)
  2218. if not item:
  2219. logger.info("Queue item %s vanished after claim — skipping", item_id)
  2220. return
  2221. item_printer_id = item.printer_id
  2222. await self._start_print(item_db, item)
  2223. finally:
  2224. # Undo an expected-print registration whose print command never
  2225. # went out. One choke point covers every way `_start_print` can
  2226. # end without sending: a raised exception (a DB failure mid-
  2227. # dispatch is the reported case), an early return, a cancel
  2228. # winning the #1853 CAS, or `start_print()` returning False.
  2229. # A confirmed send removes the entry itself, so this is a no-op
  2230. # on the happy path.
  2231. self._rollback_unconfirmed_expected_print(item_id)
  2232. # Mirror the pre-#1625 background-dispatch lifecycle: a
  2233. # reservation survives only after start_print() accepted the
  2234. # command. Failure, cancellation, deferral, and exceptions all
  2235. # release it here.
  2236. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  2237. # Unwind preheat state (bed/chamber/airduct) if the
  2238. # dispatch aborted before the print's own gcode took over.
  2239. # `_start_print` clears the pin on successful `start_print()`;
  2240. # anything still present here is by definition an aborted
  2241. # dispatch and gets rolled back so the printer isn't left
  2242. # heating for a job that isn't happening.
  2243. if item_printer_id is not None:
  2244. self._rollback_preheat_pin(item_id, item_printer_id)
  2245. # The cancellation flag only has meaning while this dispatch is
  2246. # running; drop it so the set cannot grow without bound and a
  2247. # re-queued item never inherits a stale cancellation.
  2248. self._cancelled_dispatches.discard(item_id)
  2249. # Release the claim on every exit. Once dispatch has finished the
  2250. # row's status carries the lock (printing/failed/cancelled are all
  2251. # != pending), so the token is only needed for the duration of the
  2252. # upload. A row left pending (e.g. busy-printer deferral) becomes
  2253. # dispatchable again on the next tick.
  2254. await self._clear_dispatch_claim(item_db, item_id)
  2255. async def _requeue_after_upload_refused(
  2256. self,
  2257. db: AsyncSession,
  2258. item: PrintQueueItem,
  2259. printer: Printer,
  2260. error_msg: str,
  2261. toast_uid: int | None,
  2262. ) -> None:
  2263. """Put an item back in the queue after its file never reached the printer (#3210).
  2264. The item keeps its printer. Its AMS mapping was computed against that
  2265. printer's trays, and nothing on the row says whether a mapping was
  2266. computed or set by the user, so moving it to a sibling could print from
  2267. the wrong slots. The printer goes into `_upload_backoff` instead, which
  2268. keeps every other item away from it; this one waits there and is the
  2269. only thing that knocks again, once per backoff window. The window
  2270. grows with each refusal in a row; see ``_upload_backoff_seconds``.
  2271. `dispatch_attempts` is not charged: that budget bounds a printer that
  2272. takes the file and then never starts, which this is not.
  2273. """
  2274. refusals = self._upload_refusals.get(printer.id, 0) + 1
  2275. self._upload_refusals[printer.id] = refusals
  2276. backoff = _upload_backoff_seconds(refusals)
  2277. self._upload_backoff[printer.id] = time.monotonic() + backoff
  2278. # The row is still `pending` -- it only moves to `printing` after a
  2279. # successful upload -- so there is no status to write back. Writing one
  2280. # anyway would undo a cancel that landed during the upload.
  2281. if item.error_message:
  2282. item.error_message = None
  2283. await db.commit()
  2284. logger.warning(
  2285. "Queue item %s: upload to printer %s (%s) never reached it — %s Kept in the queue; "
  2286. "refusal %d in a row, so the printer is out of dispatch for %ds.",
  2287. item.id,
  2288. printer.id,
  2289. printer.name,
  2290. error_msg,
  2291. refusals,
  2292. backoff,
  2293. )
  2294. try:
  2295. # Closes the dispatch toast for this attempt. Without it the toast
  2296. # keeps spinning on an upload that has ended.
  2297. await ws_manager.send_queue_item_failed(
  2298. user_id=toast_uid,
  2299. queue_item_id=item.id,
  2300. printer_id=item.printer_id,
  2301. reason="upload_failed",
  2302. )
  2303. except Exception:
  2304. pass # toast is best-effort
  2305. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  2306. """Drop an expectation for a print command that was never sent.
  2307. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  2308. where the interesting exception is usually the one already propagating.
  2309. """
  2310. pending = self._unconfirmed_expected_print.pop(item_id, None)
  2311. if pending is None:
  2312. return
  2313. printer_id, remote_filename, archive_id = pending
  2314. try:
  2315. from backend.app.main import unregister_expected_print
  2316. unregister_expected_print(printer_id, remote_filename, archive_id)
  2317. except Exception:
  2318. logger.warning(
  2319. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  2320. item_id,
  2321. printer_id,
  2322. remote_filename,
  2323. archive_id,
  2324. exc_info=True,
  2325. )
  2326. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  2327. """Release a queue reservation without touching the dispatch session."""
  2328. if item_id not in self._unconfirmed_budget_reservations:
  2329. return
  2330. for attempt in range(1, 4):
  2331. async with async_session() as cleanup_db:
  2332. try:
  2333. await release_budget_reservation(
  2334. cleanup_db,
  2335. source_type="print_queue",
  2336. source_id=item_id,
  2337. status="released",
  2338. )
  2339. await cleanup_db.commit()
  2340. self._unconfirmed_budget_reservations.discard(item_id)
  2341. return
  2342. except Exception as exc:
  2343. try:
  2344. await cleanup_db.rollback()
  2345. except Exception:
  2346. pass
  2347. if attempt == 3:
  2348. logger.error(
  2349. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  2350. item_id,
  2351. attempt,
  2352. exc,
  2353. )
  2354. return
  2355. await asyncio.sleep(0.5 * attempt)
  2356. @staticmethod
  2357. def _reported_bed_target(printer_id: int) -> int | None:
  2358. """The bed target firmware currently reports, or None if it can't be read.
  2359. None means "no evidence", not "zero" — callers must not treat it as a
  2360. temperature. Deliberately total: this feeds cleanup paths that run in a
  2361. ``finally``, where a malformed status must not become the exception the
  2362. caller sees.
  2363. """
  2364. try:
  2365. state = printer_manager.get_status(printer_id)
  2366. if state is None:
  2367. return None
  2368. temps = state.temperatures
  2369. if not isinstance(temps, dict):
  2370. return None
  2371. return int(float(temps.get("bed_target", 0) or 0))
  2372. except (TypeError, ValueError, AttributeError):
  2373. return None
  2374. def _rollback_preheat_pin(self, item_id: int, printer_id: int) -> None:
  2375. """Unwind everything preheat set when dispatch did NOT hand off to a running print.
  2376. Turns the bed heater off, the chamber heater off, and opens the
  2377. airduct flap back to cooling — for whichever of those preheat
  2378. actually applied. `_start_print` clears the pin on successful
  2379. `start_print()`; anything still present when `_dispatch_one` exits
  2380. is by definition an aborted dispatch and gets rolled back here.
  2381. The bed is the one action that can be declined: if firmware has since
  2382. been given a target other than the one we pinned, it belongs to someone
  2383. else and is left alone. See the comment at that branch.
  2384. Also called directly from `_dispatch_one`'s claim-failure return, which
  2385. never reaches the ``finally``.
  2386. Best-effort and never raises — this runs in the ``finally`` of dispatch.
  2387. """
  2388. pin = self._preheat_pin.pop(printer_id, set())
  2389. pinned_bed = self._preheat_pin_bed.pop(printer_id, None)
  2390. if not pin:
  2391. return
  2392. client = printer_manager.get_client(printer_id)
  2393. if client is None:
  2394. logger.info(
  2395. "Dispatch item %s (printer %d): preheat rollback skipped — no client",
  2396. item_id,
  2397. printer_id,
  2398. )
  2399. return
  2400. if "bed" in pin:
  2401. # Only undo our own target. If firmware reports something else, the
  2402. # user or another writer owns the bed now and zeroing it would
  2403. # clobber their choice -- the same guard `_release_keep_warm`
  2404. # applies to a keep-warm hold.
  2405. #
  2406. # Every uncertain case switches the bed off rather than leaving it:
  2407. # no recorded target (a pin written before this bookkeeping, or a
  2408. # setter that raised after pinning) and an unreadable status both
  2409. # fall through. A bed left hot with no owner is the worse failure,
  2410. # and this runs in a `finally` where raising would mask the real
  2411. # exception.
  2412. cur_bed_target = self._reported_bed_target(printer_id) if pinned_bed is not None else None
  2413. if cur_bed_target is not None and cur_bed_target != pinned_bed:
  2414. logger.info(
  2415. "Dispatch item %s (printer %d): rollback skipped bed → 0 (firmware target %d != pinned %d)",
  2416. item_id,
  2417. printer_id,
  2418. cur_bed_target,
  2419. pinned_bed,
  2420. )
  2421. else:
  2422. try:
  2423. client.set_bed_temperature(0)
  2424. except Exception as exc:
  2425. logger.warning("Dispatch item %s: rollback bed → 0 failed: %s", item_id, exc)
  2426. if "chamber" in pin:
  2427. try:
  2428. client.set_chamber_temperature(0)
  2429. except Exception as exc:
  2430. logger.warning("Dispatch item %s: rollback chamber → 0 failed: %s", item_id, exc)
  2431. if "airduct" in pin:
  2432. try:
  2433. client.set_airduct_mode("cooling")
  2434. except Exception as exc:
  2435. logger.warning("Dispatch item %s: rollback airduct → cooling failed: %s", item_id, exc)
  2436. logger.info(
  2437. "Dispatch item %s (printer %d): preheat rollback → %s",
  2438. item_id,
  2439. printer_id,
  2440. sorted(pin),
  2441. )
  2442. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  2443. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  2444. Returns True if this call won the claim, False if the row was already
  2445. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  2446. the load-bearing guard against reassign-during-dispatch (#2615)."""
  2447. res = await db.execute(
  2448. update(PrintQueueItem)
  2449. .where(PrintQueueItem.id == item_id)
  2450. .where(PrintQueueItem.status == "pending")
  2451. .where(PrintQueueItem.dispatching_at.is_(None))
  2452. .values(dispatching_at=datetime.now(timezone.utc))
  2453. )
  2454. await db.commit()
  2455. return res.rowcount > 0
  2456. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  2457. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  2458. mask the dispatch outcome.
  2459. Retried, because the failure mode in practice is transient and narrow: a
  2460. database that is momentarily unreachable — PostgreSQL out of connection
  2461. slots is the observed case — refuses this write for a second or two while
  2462. the dispatch that just ended is still holding the row out of the selection
  2463. query. One attempt was enough to wedge the item; a couple of spaced
  2464. attempts clear it. Each attempt rolls back first, since a failed write
  2465. leaves the session needing it before it can be reused.
  2466. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  2467. on the next quiet tick.
  2468. """
  2469. for attempt in range(1, 4):
  2470. try:
  2471. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  2472. await db.commit()
  2473. return
  2474. except Exception as exc:
  2475. try:
  2476. await db.rollback()
  2477. except Exception:
  2478. pass
  2479. if attempt == 3:
  2480. logger.warning(
  2481. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  2482. "— a later quiet tick will release it",
  2483. item_id,
  2484. attempt,
  2485. exc,
  2486. )
  2487. return
  2488. await asyncio.sleep(0.5 * attempt)
  2489. async def _printers_for_model(
  2490. self,
  2491. db: AsyncSession,
  2492. model: str,
  2493. target_location: str | None = None,
  2494. ) -> list[Printer]:
  2495. """Active printers of *model*, optionally narrowed to one location.
  2496. Shared by the matcher and by the smart-plug wake step (#2786) so both
  2497. answer "which printers can this job run on" from one query — a job can
  2498. only be woken onto a printer the matcher would also have considered.
  2499. """
  2500. normalized_model = normalize_printer_model(model) or model
  2501. query = (
  2502. select(Printer)
  2503. .where(func.lower(Printer.model) == normalized_model.lower())
  2504. .where(Printer.is_active == True) # noqa: E712
  2505. )
  2506. if target_location:
  2507. query = query.where(Printer.location == target_location)
  2508. result = await db.execute(query)
  2509. return list(result.scalars().all())
  2510. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  2511. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  2512. Read once per queue check rather than per printer: it decides both
  2513. whether the wake step has anything to do and how an offline printer is
  2514. worded in the waiting reason — "Offline" and "offline with no Auto On
  2515. plug" are different problems, and the second is the one the user has to
  2516. fix themselves (#2786).
  2517. """
  2518. result = await db.execute(
  2519. select(SmartPlug.printer_id)
  2520. .where(SmartPlug.printer_id.is_not(None))
  2521. .where(SmartPlug.enabled == True) # noqa: E712
  2522. .where(SmartPlug.auto_on == True) # noqa: E712
  2523. )
  2524. return {pid for (pid,) in result.all() if pid is not None}
  2525. def _wake_recently_failed(self, printer_id: int) -> bool:
  2526. """True while this printer's failed power-on is still cooling off (#2786)."""
  2527. deadline = self._wake_failures.get(printer_id)
  2528. if deadline is None:
  2529. return False
  2530. if time.monotonic() >= deadline:
  2531. del self._wake_failures[printer_id]
  2532. return False
  2533. return True
  2534. async def _wake_printer_for_model(
  2535. self,
  2536. db: AsyncSession,
  2537. candidates: list[_ModelCandidate],
  2538. target_location: str | None,
  2539. exclude_ids: set[int],
  2540. wakeable_ids: set[int],
  2541. require_plate_clear: bool,
  2542. ) -> tuple[int | None, int | None]:
  2543. """Power on one offline printer a model-based item could run on (#2786).
  2544. The fixed-printer branch has powered a printer on since smart plugs
  2545. existed. The model-based branch never could: its matcher drops an
  2546. offline printer into the "Offline:" waiting reason and nothing looks at
  2547. its plugs, so a class-targeted job with every matching printer switched
  2548. off sat pending forever. The reporter's log is the controlled
  2549. experiment — the same item, same plug, same Auto On setting, dispatched
  2550. the moment they edited it onto a specific printer.
  2551. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  2552. power-on was actually tried, so the caller can tell "nothing here was
  2553. wakeable" (both None — cheap, other items may still find something)
  2554. from "we tried and it did not come up" (only ``attempted_id`` — the
  2555. boot timeout has already been spent).
  2556. A printer whose last known trays cannot satisfy the job is passed over
  2557. rather than woken (#2876): the colours are readable while it is off, so
  2558. switching a farm on one machine at a time to discover them wakes
  2559. printers that could never have taken the job.
  2560. Deliberately does NOT go on to match the job once a printer is up: AMS
  2561. trays arrive with the first status push after connect, so a filament
  2562. check against a printer that booted seconds ago can reject the printer
  2563. we just woke. The next queue pass matches it with live state.
  2564. At most one printer per pass. Each wake blocks the queue loop for the
  2565. boot wait, and a queue of ten class-targeted jobs must not switch on
  2566. ten printers inside one check.
  2567. """
  2568. for candidate in candidates:
  2569. if not candidate.target_model:
  2570. continue
  2571. required_types, filament_overrides = _filament_constraints(candidate)
  2572. printers = await self._printers_for_model(db, candidate.target_model, target_location)
  2573. for printer in sorted(printers, key=lambda p: p.id):
  2574. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  2575. continue
  2576. if printer_manager.is_connected(printer.id):
  2577. continue
  2578. if self._wake_recently_failed(printer.id):
  2579. # Its plug did not bring it back a moment ago. Move on to a
  2580. # sibling instead of spending this pass — and every pass —
  2581. # on the same printer.
  2582. continue
  2583. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  2584. # Waking this one buys nothing: it would boot into IDLE and
  2585. # then be held by the plate-clear gate, which is exactly
  2586. # what the reporter's log shows happening for 80 minutes
  2587. # after a fixed-printer wake. The flag is Bambuddy-side and
  2588. # persisted, so it is readable while the printer is off.
  2589. logger.info(
  2590. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  2591. printer.id,
  2592. candidate.target_model,
  2593. )
  2594. continue
  2595. shortfall = self._cached_filament_shortfall(printer.id, required_types, filament_overrides)
  2596. if shortfall:
  2597. logger.info(
  2598. "Not powering on printer %s for a %s job: last known filament cannot satisfy it (needs %s)",
  2599. printer.id,
  2600. candidate.target_model,
  2601. ", ".join(shortfall),
  2602. )
  2603. continue
  2604. plugs = await self._get_smart_plugs(db, printer.id)
  2605. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  2606. if not auto_on_plugs:
  2607. # wakeable_ids said otherwise — the plug changed under us
  2608. # mid-pass. Nothing to do but move on.
  2609. continue
  2610. logger.info(
  2611. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  2612. candidate.target_model,
  2613. printer.id,
  2614. )
  2615. primary_plug = self._pick_power_plug(auto_on_plugs)
  2616. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  2617. logger.warning(
  2618. "Could not power on printer %s via smart plug; not trying it again for %ss",
  2619. printer.id,
  2620. self._wake_failure_cooloff,
  2621. )
  2622. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  2623. return None, printer.id
  2624. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  2625. try:
  2626. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  2627. await service.turn_on(extra_plug)
  2628. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  2629. except Exception as e:
  2630. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  2631. return printer.id, printer.id
  2632. return None, None
  2633. async def _find_idle_printer_for_model(
  2634. self,
  2635. db: AsyncSession,
  2636. model: str,
  2637. exclude_ids: set[int],
  2638. required_filament_types: list[str] | None = None,
  2639. target_location: str | None = None,
  2640. filament_overrides: list[dict] | None = None,
  2641. require_plate_clear: bool = True,
  2642. wakeable_ids: set[int] | None = None,
  2643. ) -> tuple[int | None, str | None]:
  2644. """Find an idle, connected printer matching the model with compatible filaments.
  2645. Args:
  2646. db: Database session
  2647. model: Printer model to match (e.g., "X1C", "P1S")
  2648. exclude_ids: Printer IDs to exclude (already busy)
  2649. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  2650. If provided, only printers with all required types loaded will match.
  2651. target_location: Optional location filter. If provided, only printers in this location are considered.
  2652. filament_overrides: Optional list of override dicts. Each entry may include
  2653. ``force_color_match: true`` to require an exact type+color match
  2654. on the printer for that slot. Without the flag the existing
  2655. colour-preference logic applies.
  2656. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  2657. offline printer is worded: one Bambuddy will switch on reads
  2658. differently from one the user has to go and switch on themselves.
  2659. Returns:
  2660. Tuple of (printer_id, waiting_reason):
  2661. - (printer_id, None) if a matching printer was found
  2662. - (None, reason) if no printer is available, with explanation
  2663. """
  2664. normalized_model = normalize_printer_model(model) or model
  2665. printers = await self._printers_for_model(db, model, target_location)
  2666. location_suffix = f" in {target_location}" if target_location else ""
  2667. if not printers:
  2668. return None, f"No active {normalized_model} printers{location_suffix} configured"
  2669. # Separate force-matched overrides from preference-only overrides
  2670. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2671. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2672. # Track reasons for skipping printers
  2673. printers_busy = []
  2674. printers_offline = []
  2675. printers_offline_no_plug = []
  2676. printers_missing_filament: list[tuple[str, list[str]]] = []
  2677. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  2678. for printer in printers:
  2679. if printer.id in exclude_ids:
  2680. # Printer is already claimed by another job in this scheduling run.
  2681. # For force-color jobs, still check if the color would match — if not,
  2682. # report it as a color mismatch rather than plain "Busy" so the user
  2683. # knows the job needs a filament change, not just to wait for availability.
  2684. if force_overrides and not pref_overrides:
  2685. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2686. if missing_colors:
  2687. printers_missing_filament.append((printer.name, missing_colors))
  2688. continue
  2689. printers_busy.append(printer.name)
  2690. continue
  2691. is_connected = printer_manager.is_connected(printer.id)
  2692. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  2693. if not is_connected:
  2694. # An offline printer whose last known filament cannot run this
  2695. # job is reported as needing filament rather than as offline
  2696. # (#2876). It is also the printer the smart-plug step will now
  2697. # decline to switch on, and "Offline:" on its own would leave
  2698. # that decision looking like nothing happening at all.
  2699. shortfall = self._cached_filament_shortfall(printer.id, required_filament_types, filament_overrides)
  2700. if shortfall:
  2701. printers_missing_filament.append((printer.name, shortfall))
  2702. elif wakeable_ids is not None and printer.id not in wakeable_ids:
  2703. printers_offline_no_plug.append(printer.name)
  2704. else:
  2705. printers_offline.append(printer.name)
  2706. continue
  2707. if not is_idle:
  2708. # Printer is currently printing. For force-color jobs, check whether the
  2709. # loaded color would satisfy the requirement — if not, surface it as a
  2710. # color-mismatch reason rather than plain "Busy" so the user understands
  2711. # that the job is waiting for a filament change, not just printer availability.
  2712. if force_overrides and not pref_overrides:
  2713. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2714. if missing_colors:
  2715. printers_missing_filament.append((printer.name, missing_colors))
  2716. logger.debug(
  2717. "Printer %s (%s) is busy but also has wrong force-color: %s",
  2718. printer.id,
  2719. printer.name,
  2720. missing_colors,
  2721. )
  2722. continue
  2723. printers_busy.append(printer.name)
  2724. continue
  2725. # Validate filament compatibility if required types are specified
  2726. if required_filament_types:
  2727. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  2728. if missing:
  2729. # When force_overrides are present, enrich missing entries with color info
  2730. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  2731. if force_overrides:
  2732. force_color_map = {
  2733. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  2734. for o in force_overrides
  2735. }
  2736. missing_enriched = [
  2737. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2738. for t in missing
  2739. ]
  2740. printers_missing_filament.append((printer.name, missing_enriched))
  2741. else:
  2742. printers_missing_filament.append((printer.name, missing))
  2743. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  2744. continue
  2745. # Force color match: ALL flagged slots must have an exact type+color match
  2746. if force_overrides:
  2747. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  2748. if missing_colors:
  2749. printers_missing_filament.append((printer.name, missing_colors))
  2750. logger.debug(
  2751. "Skipping printer %s (%s) - missing force-matched colors: %s",
  2752. printer.id,
  2753. printer.name,
  2754. missing_colors,
  2755. )
  2756. continue
  2757. # If preference-only overrides exist, rank by color matches (existing behaviour)
  2758. if pref_overrides:
  2759. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  2760. if color_matches > 0:
  2761. candidates.append((printer.id, color_matches))
  2762. else:
  2763. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  2764. printers_missing_filament.append((printer.name, override_colors))
  2765. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  2766. continue
  2767. elif force_overrides:
  2768. # Passed all force checks — immediately eligible (no preference ordering needed)
  2769. return printer.id, None
  2770. else:
  2771. # No overrides at all - take first available (existing behavior)
  2772. return printer.id, None
  2773. # If we have candidates from preference override matching, pick the one with most color matches
  2774. if candidates:
  2775. candidates.sort(key=lambda c: c[1], reverse=True)
  2776. return candidates[0][0], None
  2777. # Build waiting reason from what we found
  2778. reasons = []
  2779. if printers_missing_filament:
  2780. # Filament/color mismatch is most actionable - show first
  2781. if force_overrides and not pref_overrides:
  2782. # All mismatches are force-color failures — use descriptive message only;
  2783. # but only if there are no busy printers that DO have the matching color.
  2784. # If a printer has the right color but is busy, surface "Busy" instead so
  2785. # the user knows the job will start automatically once that printer is free.
  2786. # Same for a printer that is merely offline: Bambuddy switches that one on
  2787. # by itself, so the job is not actually waiting on anybody to change a
  2788. # spool (#2876 — offline printers reach this list now that a switched-off
  2789. # printer's own filament is read).
  2790. if not printers_busy and not printers_offline:
  2791. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  2792. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  2793. # else: fall through — the self-resolving entries are appended below
  2794. else:
  2795. names_and_missing = [
  2796. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  2797. ]
  2798. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  2799. if printers_busy:
  2800. reasons.append(f"Busy: {', '.join(printers_busy)}")
  2801. if printers_offline:
  2802. reasons.append(f"Offline: {', '.join(printers_offline)}")
  2803. if printers_offline_no_plug:
  2804. # Named separately because it is the one entry on this list the
  2805. # user has to act on: no enabled Auto On plug means Bambuddy will
  2806. # never power this printer on for the queue (#2786).
  2807. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  2808. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  2809. @staticmethod
  2810. def _is_busy_only(waiting_reason: str) -> bool:
  2811. """Check if the waiting reason only contains 'Busy' entries.
  2812. When all matching printers are simply busy printing, the queued job
  2813. will start automatically once a printer finishes — no user action
  2814. is required, so we skip the notification.
  2815. """
  2816. parts = [p.strip() for p in waiting_reason.split(" | ")]
  2817. return all(p.startswith("Busy:") for p in parts)
  2818. def _get_missing_force_color_slots(
  2819. self, printer_id: int, force_overrides: list[dict], raw_data: dict | None = None
  2820. ) -> list[str]:
  2821. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  2822. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  2823. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  2824. with an exact type+color match.
  2825. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  2826. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  2827. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  2828. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  2829. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  2830. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  2831. setups are unaffected.
  2832. Returns:
  2833. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  2834. """
  2835. if raw_data is None:
  2836. status = printer_manager.get_status(printer_id)
  2837. if not status:
  2838. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  2839. raw_data = status.raw_data
  2840. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  2841. loaded: list[tuple[str, str, str]] = []
  2842. for ams_unit in raw_data.get("ams", []):
  2843. for tray in ams_unit.get("tray", []):
  2844. tray_type = tray.get("tray_type")
  2845. if tray_type:
  2846. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2847. loaded.append((canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or ""))
  2848. for vt in raw_data.get("vt_tray") or []:
  2849. vt_type = vt.get("tray_type")
  2850. if vt_type:
  2851. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2852. loaded.append((canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  2853. missing = []
  2854. for o in force_overrides:
  2855. o_type = canonical_filament_type(o.get("type") or "")
  2856. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2857. o_idx = o.get("tray_info_idx") or ""
  2858. satisfied = any(
  2859. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  2860. for t_type, t_color, t_idx in loaded
  2861. )
  2862. if not satisfied:
  2863. color_label = o.get("color_name") or o.get("color", "?")
  2864. missing.append(f"{o_type} ({color_label})")
  2865. return missing
  2866. def _get_missing_filament_types(
  2867. self, printer_id: int, required_types: list[str], raw_data: dict | None = None
  2868. ) -> list[str]:
  2869. """Get the list of required filament types that are not loaded on the printer.
  2870. Args:
  2871. printer_id: The printer ID
  2872. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  2873. Returns:
  2874. List of missing filament types (empty if all are loaded)
  2875. """
  2876. if raw_data is None:
  2877. status = printer_manager.get_status(printer_id)
  2878. if not status:
  2879. return required_types # Can't determine, assume all missing
  2880. raw_data = status.raw_data
  2881. # Collect all filament types loaded on this printer (AMS units + external spool)
  2882. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  2883. loaded_types: set[str] = set()
  2884. # Check AMS units (stored in raw_data["ams"])
  2885. ams_data = raw_data.get("ams", [])
  2886. if ams_data:
  2887. for ams_unit in ams_data:
  2888. for tray in ams_unit.get("tray", []):
  2889. tray_type = tray.get("tray_type")
  2890. if tray_type:
  2891. loaded_types.add(canonical_filament_type(tray_type))
  2892. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  2893. for vt in raw_data.get("vt_tray") or []:
  2894. vt_type = vt.get("tray_type")
  2895. if vt_type:
  2896. loaded_types.add(canonical_filament_type(vt_type))
  2897. # Find which required types are missing (using canonical type for equivalence)
  2898. missing = []
  2899. for req_type in required_types:
  2900. if canonical_filament_type(req_type) not in loaded_types:
  2901. missing.append(req_type)
  2902. return missing
  2903. def _count_override_color_matches(
  2904. self, printer_id: int, overrides: list[dict], raw_data: dict | None = None
  2905. ) -> int:
  2906. """Count how many filament overrides have an exact color match on the printer.
  2907. Used to prefer printers that already have the desired override colors loaded.
  2908. """
  2909. if raw_data is None:
  2910. status = printer_manager.get_status(printer_id)
  2911. if not status:
  2912. return 0
  2913. raw_data = status.raw_data
  2914. # Collect loaded filaments' type+color pairs
  2915. loaded: set[tuple[str, str]] = set()
  2916. for ams_unit in raw_data.get("ams", []):
  2917. for tray in ams_unit.get("tray", []):
  2918. tray_type = tray.get("tray_type")
  2919. # `or ""`, not a dict default: a slot can carry the key with a
  2920. # null value, and this now runs against switched-off printers
  2921. # too, where nobody is watching for the AttributeError.
  2922. tray_color = tray.get("tray_color") or ""
  2923. if tray_type:
  2924. color_norm = tray_color.replace("#", "").lower()[:6]
  2925. loaded.add((tray_type.upper(), color_norm))
  2926. for vt in raw_data.get("vt_tray") or []:
  2927. vt_type = vt.get("tray_type")
  2928. if vt_type:
  2929. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  2930. loaded.add((vt_type.upper(), color_norm))
  2931. matches = 0
  2932. for o in overrides:
  2933. o_type = (o.get("type") or "").upper()
  2934. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  2935. if (o_type, o_color) in loaded:
  2936. matches += 1
  2937. return matches
  2938. @staticmethod
  2939. def _tray_reading(printer_id: int) -> dict:
  2940. """The best tray reading available for a printer that is not printing.
  2941. Live status first: a printer keeps its last status after the power
  2942. goes, because ``mark_power_off`` blanks ``connected`` and ``state`` and
  2943. leaves ``raw_data`` alone. The manager's own record is the fallback,
  2944. for when the client itself has been dropped and taken its status with
  2945. it — which is what every power-on attempt does.
  2946. An empty result means "we have never heard", not "nothing is loaded":
  2947. the two are indistinguishable from here, and only the second would be
  2948. safe to act on.
  2949. """
  2950. status = printer_manager.get_status(printer_id)
  2951. raw = (status.raw_data if status else None) or {}
  2952. for ams_unit in raw.get("ams") or []:
  2953. if any(tray.get("tray_type") for tray in ams_unit.get("tray", [])):
  2954. return raw
  2955. if any(vt.get("tray_type") for vt in raw.get("vt_tray") or []):
  2956. return raw
  2957. return printer_manager.last_known_trays(printer_id)
  2958. def _cached_filament_shortfall(
  2959. self,
  2960. printer_id: int,
  2961. required_types: list[str] | None,
  2962. filament_overrides: list[dict] | None,
  2963. ) -> list[str]:
  2964. """What a switched-off printer's last known filament cannot provide (#2876).
  2965. The smart-plug wake step used to consider only the model, so a job for a
  2966. colour loaded on the last printer in ID order switched on every earlier
  2967. one in turn, evaluated it, rejected it on colour and left it running.
  2968. Bambuddy knew those colours the whole time. This asks the same three
  2969. questions the matcher asks a live printer — required types, forced
  2970. colours, preferred colours — of the trays it last reported, and returns
  2971. the answers in the same shape the "Waiting for filament" reason uses.
  2972. Empty means the printer may still be able to take the job.
  2973. Fails open, and deliberately: with no tray reading (never connected
  2974. since Bambuddy started, or the cache dropped by a reconnect) this
  2975. returns nothing to report and the printer is treated as it was before.
  2976. A farm restarted while its printers were off must not conclude that
  2977. none of them can print.
  2978. """
  2979. if not required_types and not filament_overrides:
  2980. return []
  2981. raw_data = self._tray_reading(printer_id)
  2982. if not raw_data:
  2983. return []
  2984. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  2985. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  2986. if required_types:
  2987. missing = self._get_missing_filament_types(printer_id, required_types, raw_data)
  2988. if missing:
  2989. # Same enrichment the live path applies: a bare "PLA" is not
  2990. # much help when what is missing is a particular PLA.
  2991. force_color_map = {
  2992. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?") for o in force_overrides
  2993. }
  2994. return [
  2995. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  2996. for t in missing
  2997. ]
  2998. if force_overrides:
  2999. missing_colors = self._get_missing_force_color_slots(printer_id, force_overrides, raw_data)
  3000. if missing_colors:
  3001. return missing_colors
  3002. # Preference overrides read as a preference but the matcher treats zero
  3003. # matches as a skip, so a printer with none of the wanted colours is
  3004. # rejected there too. Waking it would only produce that same rejection.
  3005. if pref_overrides and self._count_override_color_matches(printer_id, pref_overrides, raw_data) == 0:
  3006. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in pref_overrides]
  3007. return []
  3008. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  3009. """Fold the winning candidate's file and settings onto the queue row (#671).
  3010. This is the whole trick that keeps cross-model items cheap: the many-to-many
  3011. never escapes the selection loop. By the time the pass commits, the row
  3012. looks exactly like an ordinary single-file model-based item, so the upload,
  3013. archive creation, expected-print registration, print history and reprint
  3014. paths need no knowledge that variants exist.
  3015. No-ops for a non-variant candidate, which is already the item's own columns.
  3016. Safe to run and re-run: the item's file columns are only ever *read* when it
  3017. has no variants, so an item that gets resolved and then skipped (library-row
  3018. conflict, previous-print gate) is simply resolved again on the next pass.
  3019. """
  3020. variant = candidate.variant
  3021. if variant is None:
  3022. return
  3023. item.library_file_id = variant.library_file_id
  3024. item.library_file = variant.library_file
  3025. # The dispatcher checks archive_id first and would print that instead of
  3026. # the file we just picked. Creation refuses to combine the two, so this
  3027. # only ever fires on a hand-written row — clear it rather than silently
  3028. # dispatch something the matcher never considered.
  3029. item.archive_id = None
  3030. item.archive = None
  3031. item.target_model = variant.target_model
  3032. item.plate_id = variant.plate_id
  3033. item.ams_mapping = variant.ams_mapping
  3034. item.nozzle_mapping = variant.nozzle_mapping
  3035. item.nozzle_rack_choice = variant.nozzle_rack_choice
  3036. item.filament_overrides = variant.filament_overrides
  3037. item.required_filament_types = variant.required_filament_types
  3038. if variant.print_time_seconds is not None:
  3039. # The row carried the shortest candidate's estimate so SJF could order
  3040. # it before a printer was known; now that one is chosen, record what is
  3041. # actually going to run so history and the ETA agree with reality.
  3042. item.print_time_seconds = variant.print_time_seconds
  3043. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  3044. """Ensure the queue item carries a usable AMS mapping before dispatch.
  3045. Recomputes from live printer status when the stored mapping is missing OR
  3046. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  3047. frontend status-load race can serialize [-1] before the printer's AMS
  3048. trays are known (#2589) — and must not be trusted: downstream it would be
  3049. silently downgraded to external-spool mode and print against an empty
  3050. feed. A resolved mapping is re-checked against the target printer's
  3051. live trays before it is trusted (#2799) and recomputed when it does not
  3052. fit. When it does fit, its resolved slots are kept as they are and only
  3053. the slots the plate prints that are still unresolved are matched again;
  3054. all of it is left alone when the user has acknowledged it with "Print
  3055. Anyway".
  3056. When recompute cannot resolve it either (no compatible tray loaded), the
  3057. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  3058. external selection. On a printer that reported loaded trays,
  3059. ``_block_on_unmatched_filament`` holds the item rather than let it go out
  3060. mapping-less; where it cannot judge, the print command keeps use_ams=True
  3061. and the firmware surfaces a clear AMS-mapping error instead of silently
  3062. printing to the empty external feed.
  3063. Returns an actionable message when that firmware error is the only
  3064. possible outcome — the matcher ran, matched nothing, and the printer has
  3065. no AMS to load a different spool into (#2771). The caller fails the item
  3066. on it instead of spending an upload on a print that cannot start.
  3067. Returns None everywhere else, including every case where we simply lack
  3068. the data to judge, so dispatch is only ever blocked on a positive
  3069. finding.
  3070. """
  3071. stored_mapping: list | None = None
  3072. if item.ams_mapping:
  3073. try:
  3074. stored_mapping = json.loads(item.ams_mapping)
  3075. except (json.JSONDecodeError, TypeError):
  3076. stored_mapping = None
  3077. # Present and resolved. Global tray IDs only mean something relative to
  3078. # the printer they were resolved against, so "resolved" is not the same
  3079. # as "resolved *here*" — check the mapping still fits the printer that
  3080. # is about to run this item before trusting it (#2799). "Print anyway"
  3081. # is the user overriding exactly this judgement, so it short-circuits.
  3082. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  3083. if item.skip_filament_check:
  3084. return None
  3085. conflict = await self._stored_mapping_conflict(db, printer_id, item, stored_mapping)
  3086. if conflict is None:
  3087. # It fits, but a slot the plate prints may still be empty: the
  3088. # spool was missing when it was mapped, and has perhaps been
  3089. # loaded since. Nothing else would ever look at that slot again,
  3090. # so a job held for it would be held again on every Start.
  3091. filled = await self._fill_unresolved_slots(db, printer_id, item, stored_mapping)
  3092. if filled is not None:
  3093. item.ams_mapping = json.dumps(filled)
  3094. logger.info(
  3095. "Queue item %s: filled unresolved slots of %s on printer %s: %s",
  3096. item.id,
  3097. stored_mapping,
  3098. printer_id,
  3099. filled,
  3100. )
  3101. await db.commit()
  3102. return None
  3103. logger.warning(
  3104. "Queue item %s: stored ams_mapping %s does not fit printer %s (%s) — recomputing",
  3105. item.id,
  3106. stored_mapping,
  3107. printer_id,
  3108. conflict,
  3109. )
  3110. # Drop it before recomputing so a failed recompute cannot fall back
  3111. # to the mapping we just rejected.
  3112. item.ams_mapping = None
  3113. stored_mapping = None
  3114. await db.commit()
  3115. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  3116. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  3117. item.ams_mapping = json.dumps(computed_mapping)
  3118. logger.info(
  3119. "Queue item %s: Computed AMS mapping for printer %s: %s",
  3120. item.id,
  3121. printer_id,
  3122. computed_mapping,
  3123. )
  3124. await db.commit()
  3125. return None
  3126. if _mapping_is_all_unresolved(stored_mapping):
  3127. logger.warning(
  3128. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  3129. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  3130. item.id,
  3131. stored_mapping,
  3132. printer_id,
  3133. )
  3134. item.ams_mapping = None
  3135. await db.commit()
  3136. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  3137. async def _fill_unresolved_slots(
  3138. self,
  3139. db: AsyncSession,
  3140. printer_id: int,
  3141. item: PrintQueueItem,
  3142. stored_mapping: list | None,
  3143. ) -> list | None:
  3144. """``stored_mapping`` with its unresolved required slots matched on live trays (#2799).
  3145. Every resolved entry is kept, so a tray the user picked by hand stays
  3146. picked. Only the plate's unresolved slots are matched, and only against
  3147. trays the mapping does not already use: the matcher never gives two
  3148. slots one tray, and filling a gap with a tray the user assigned to
  3149. another slot would print that slot's filament twice.
  3150. Returns None when there is nothing to fill or nothing could be filled.
  3151. """
  3152. if not isinstance(stored_mapping, list) or not stored_mapping:
  3153. return None
  3154. required = await self._get_filament_requirements(db, item)
  3155. if not required:
  3156. return None
  3157. self._apply_filament_overrides(item, required)
  3158. gaps = {req["slot_id"] for req in _unresolved_required(required, stored_mapping)}
  3159. if not gaps:
  3160. return None
  3161. reserved = {t for t in stored_mapping if _is_tray_id(t) and t >= 0}
  3162. computed = await self._compute_ams_mapping_for_printer(
  3163. db, printer_id, item, only_slots=gaps, reserved_trays=reserved
  3164. )
  3165. if not computed:
  3166. return None
  3167. merged = list(stored_mapping) + [-1] * max(0, len(computed) - len(stored_mapping))
  3168. filled = False
  3169. for slot_id in gaps:
  3170. tray = computed[slot_id - 1] if slot_id <= len(computed) else None
  3171. if _is_tray_id(tray) and tray >= 0:
  3172. merged[slot_id - 1] = tray
  3173. filled = True
  3174. return merged if filled else None
  3175. async def missing_filament_for_start(self, db: AsyncSession, item: PrintQueueItem) -> list[str] | None:
  3176. """What a staged item would be held for if it were started now (#2799).
  3177. The Start button asks this before releasing an item, so that a job whose
  3178. filament is still not loaded offers "Print Anyway" instead of being
  3179. released, held again by the scheduler and leaving no way past the hold.
  3180. It reaches the same answer the dispatch path would: a stored mapping
  3181. that fits is kept and only its gaps are matched again, and one that
  3182. does not fit (or is missing) is replaced by a fresh match.
  3183. Returns the missing filaments, described the way the queue row
  3184. describes them, or None when nothing is missing or there is not enough
  3185. evidence to say: no printer yet (a model-based item picks one at
  3186. dispatch), no status, no trays reported, or no readable 3MF.
  3187. """
  3188. if item.skip_filament_check or not item.printer_id:
  3189. return None
  3190. status = printer_manager.get_status(item.printer_id)
  3191. if status is None or not self._build_loaded_filaments(status):
  3192. return None
  3193. # Called from a request, not from a pass: drop whatever the last pass
  3194. # memoised so this reads the file as it is now. A pass running at the
  3195. # same time only loses its cache.
  3196. self._filament_req_memo.clear()
  3197. mapping: list | None = None
  3198. if item.ams_mapping:
  3199. try:
  3200. mapping = json.loads(item.ams_mapping)
  3201. except (json.JSONDecodeError, TypeError):
  3202. mapping = None
  3203. if not isinstance(mapping, list) or _mapping_is_all_unresolved(mapping):
  3204. mapping = None
  3205. if mapping is not None:
  3206. if await self._stored_mapping_conflict(db, item.printer_id, item, mapping) is None:
  3207. mapping = await self._fill_unresolved_slots(db, item.printer_id, item, mapping) or mapping
  3208. else:
  3209. mapping = None
  3210. if mapping is None:
  3211. mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item) or []
  3212. required = await self._get_filament_requirements(db, item)
  3213. if not required:
  3214. return None
  3215. self._apply_filament_overrides(item, required)
  3216. missing = _unresolved_required(required, mapping)
  3217. return [_describe_filament(req, "nozzle_id") for req in missing] or None
  3218. async def _stored_mapping_conflict(
  3219. self,
  3220. db: AsyncSession,
  3221. printer_id: int,
  3222. item: PrintQueueItem,
  3223. stored_mapping: list | None,
  3224. ) -> str | None:
  3225. """Describe why ``stored_mapping`` cannot be trusted on ``printer_id`` (#2799).
  3226. A mapping is a list of global tray IDs, and those are only meaningful
  3227. relative to the printer they were resolved against — the same rule
  3228. ``print_queue`` documents for tray identity. Two ways a stored mapping
  3229. arrives at a printer it was not resolved for:
  3230. * the print dialog stamps one mapping onto every selected printer, so a
  3231. mapping computed against the first printer is dispatched verbatim to
  3232. the rest, whose AMS slot order differs;
  3233. * a spool is moved between queueing and dispatch.
  3234. Both end the same way: the slot index still resolves, so nothing looks
  3235. wrong, and the printer obeys it — an explicit ``ams_mapping`` bypasses
  3236. the firmware's own type check, so a PETG slot happily prints in ASA.
  3237. Returns a short reason when the mapping names a tray this printer does
  3238. not have loaded, or points a slot at a tray holding a different filament
  3239. type. Returns None when the mapping fits, and — deliberately — whenever
  3240. we lack the evidence to judge, so a recompute only ever follows a
  3241. positive finding.
  3242. An unresolved (``-1``) required slot is NOT a conflict: it says the
  3243. matcher had nothing, not that the mapping belongs to another printer,
  3244. and destroying a partially hand-resolved mapping over it would lose the
  3245. slots the user did resolve. ``_fill_unresolved_slots`` matches those
  3246. slots again on their own, and ``_block_on_unmatched_filament`` holds the
  3247. item when that finds nothing.
  3248. """
  3249. if not isinstance(stored_mapping, list) or not stored_mapping:
  3250. return None
  3251. status = printer_manager.get_status(printer_id)
  3252. if status is None:
  3253. return None
  3254. loaded = self._build_loaded_filaments(status)
  3255. if not loaded:
  3256. # Nothing reported yet (reconnect, first push pending). Saying
  3257. # "tray not loaded" here would recompute against an AMS we cannot
  3258. # see, which is how #2589 produced a bogus all-[-1] in the first
  3259. # place.
  3260. return None
  3261. by_tray = {f["global_tray_id"]: f for f in loaded}
  3262. # Cheap pass first, on live status alone: every tray the mapping names
  3263. # has to exist here. This catches a foreign mapping without opening the
  3264. # 3MF, which is worth doing because the parse below is neither cached
  3265. # nor free.
  3266. for index, tray in enumerate(stored_mapping):
  3267. if not _is_tray_id(tray) or tray < 0:
  3268. continue
  3269. if tray in by_tray:
  3270. continue
  3271. if tray >= 254:
  3272. # An external feed we have not heard about is absence of
  3273. # evidence about *that slot* — the rest of the mapping is still
  3274. # worth judging, so skip it rather than abandoning the pass.
  3275. continue
  3276. return f"slot {index + 1} points at tray {tray}, which this printer does not have loaded"
  3277. # Only now is the 3MF worth opening: the type check needs to know what
  3278. # each slot actually asked for. The external spool is checked the same
  3279. # way as an AMS tray — `_build_loaded_filaments` reports its type, and
  3280. # two printers with different filament in the external feed is the same
  3281. # failure this method exists to catch.
  3282. required = await self._get_filament_requirements(db, item)
  3283. if not required:
  3284. return None
  3285. self._apply_filament_overrides(item, required)
  3286. for req in required:
  3287. slot_id = req.get("slot_id") or 0
  3288. if slot_id <= 0:
  3289. continue
  3290. if slot_id > len(stored_mapping):
  3291. return f"slot {slot_id} is not covered by the mapping"
  3292. tray = stored_mapping[slot_id - 1]
  3293. if not _is_tray_id(tray) or tray < 0:
  3294. continue
  3295. loaded_tray = by_tray.get(tray)
  3296. if loaded_tray is None:
  3297. continue
  3298. want = canonical_filament_type(req.get("type"))
  3299. have = canonical_filament_type(loaded_tray.get("type"))
  3300. if want and have and want != have:
  3301. return f"slot {slot_id} needs {req.get('type')} but tray {tray} holds {loaded_tray.get('type')}"
  3302. return None
  3303. async def _unmappable_without_ams_message(
  3304. self,
  3305. db: AsyncSession,
  3306. printer_id: int,
  3307. item: PrintQueueItem,
  3308. computed_mapping: list[int] | None,
  3309. ) -> str | None:
  3310. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  3311. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  3312. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  3313. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  3314. uploaded several megabytes and burned its dispatch retries. This method
  3315. speaks only for the AMS-less case: there is nothing to resume into — the
  3316. external spool holder is the whole inventory — so the useful answer is to
  3317. say which filament is missing and stop. With an AMS attached it returns
  3318. None: where live status reported loaded trays,
  3319. ``_block_on_unmatched_filament`` holds the item instead, and where it
  3320. reported none the print goes out and the firmware error is the answer —
  3321. the user can load the right spool and press Resume.
  3322. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  3323. every branch that lacks the evidence to be sure returns None.
  3324. """
  3325. # None means the matcher never ran (no requirements parsed from the 3MF,
  3326. # or nothing loaded at all) rather than "ran and matched nothing". Those
  3327. # dispatch as they always have.
  3328. if not _mapping_is_all_unresolved(computed_mapping):
  3329. return None
  3330. status = printer_manager.get_status(printer_id)
  3331. if status is None:
  3332. return None
  3333. # "No AMS" has to be a fact the printer stated, not the absence of a
  3334. # statement. `raw_data["ams"]` is written only once an AMS push has been
  3335. # handled and is preserved across partial pushes thereafter, so a missing
  3336. # key means we have not heard yet — most likely a reconnect, where the
  3337. # trays of a fully loaded AMS would be invisible for a few seconds. An
  3338. # empty list is the positive report of a printer with no AMS.
  3339. ams_units = status.raw_data.get("ams")
  3340. if not isinstance(ams_units, list) or ams_units:
  3341. return None
  3342. required = await self._get_filament_requirements(db, item)
  3343. loaded = self._build_loaded_filaments(status)
  3344. if not required or not loaded:
  3345. # Both were non-empty moments ago or the matcher could not have run.
  3346. # If the picture changed under us, say nothing rather than fail an
  3347. # item on stale evidence.
  3348. return None
  3349. self._apply_filament_overrides(item, required)
  3350. return _unmatched_filament_message(required, loaded)
  3351. async def _fail_unmappable_item(
  3352. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  3353. ) -> None:
  3354. """Fail a queue item whose filament mapping cannot resolve (#2771).
  3355. This replaces a failure, not a success: without it the item is uploaded,
  3356. rejected by the firmware with 0700_8012, retried twice more and failed
  3357. anyway with "never started the print after N dispatch attempts". So this
  3358. applies on the model-based path too, even though it means an "Any <model>"
  3359. job stops at the first printer offered rather than trying its siblings —
  3360. deferring instead would need the check to move inside
  3361. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  3362. re-assigns the same printer on the next tick.
  3363. """
  3364. item.status = "failed"
  3365. item.error_message = message
  3366. item.completed_at = datetime.now(timezone.utc)
  3367. item.waiting_reason = None
  3368. await db.commit()
  3369. logger.warning(
  3370. "Queue item %s: no usable AMS mapping on printer %s — %s",
  3371. item.id,
  3372. printer_id,
  3373. message,
  3374. )
  3375. job_name = await self._get_job_name(db, item)
  3376. printer = await self._get_printer(db, printer_id)
  3377. await notification_service.on_queue_job_failed(
  3378. job_name=job_name,
  3379. printer_id=printer_id,
  3380. printer_name=printer.name if printer else "Unknown",
  3381. reason=message,
  3382. db=db,
  3383. )
  3384. try:
  3385. await ws_manager.send_queue_item_failed(
  3386. user_id=item.created_by_id,
  3387. queue_item_id=item.id,
  3388. printer_id=printer_id,
  3389. reason="filament_unmappable",
  3390. )
  3391. except Exception:
  3392. pass
  3393. async def _compute_ams_mapping_for_printer(
  3394. self,
  3395. db: AsyncSession,
  3396. printer_id: int,
  3397. item: PrintQueueItem,
  3398. *,
  3399. only_slots: set[int] | None = None,
  3400. reserved_trays: set[int] | None = None,
  3401. ) -> list[int] | None:
  3402. """Compute AMS mapping for a printer based on filament requirements.
  3403. Called when a queue item has no ams_mapping set — either for model-based
  3404. items after printer assignment, or printer-specific items (e.g. from VP).
  3405. Args:
  3406. db: Database session
  3407. printer_id: The assigned printer ID
  3408. item: The queue item (contains archive_id or library_file_id)
  3409. only_slots: Match only these filament slots; every other slot comes
  3410. back unresolved (-1). Used to fill the gaps of a stored mapping.
  3411. reserved_trays: Global tray IDs to leave out of the match, because
  3412. the stored mapping already gives them to another slot.
  3413. Returns:
  3414. AMS mapping array or None if no mapping needed/possible
  3415. """
  3416. # Get printer status
  3417. status = printer_manager.get_status(printer_id)
  3418. if not status:
  3419. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  3420. return None
  3421. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  3422. # either extruder, so the per-nozzle hard filter below must NOT apply.
  3423. # Otherwise a print on one nozzle can't use a spool physically loaded in
  3424. # an AMS on the *other* nozzle, and the matcher falls through to a
  3425. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  3426. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  3427. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  3428. # Get filament requirements from source file
  3429. filament_reqs = await self._get_filament_requirements(db, item)
  3430. if not filament_reqs:
  3431. # When the 3MF can't be read but force-color overrides are present, build a
  3432. # direct mapping from the overrides so the printer uses the correct AMS slot.
  3433. if item.filament_overrides:
  3434. try:
  3435. overrides = json.loads(item.filament_overrides)
  3436. force_overrides = [o for o in overrides if o.get("force_color_match")]
  3437. if force_overrides:
  3438. logger.info(
  3439. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  3440. "force-color override(s)",
  3441. item.id,
  3442. len(force_overrides),
  3443. )
  3444. return self._build_override_direct_mapping(force_overrides, status)
  3445. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3446. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  3447. logger.debug("No filament requirements found for queue item %s", item.id)
  3448. return None
  3449. self._apply_filament_overrides(item, filament_reqs)
  3450. if only_slots is not None:
  3451. filament_reqs = [req for req in filament_reqs if req.get("slot_id") in only_slots]
  3452. if not filament_reqs:
  3453. return None
  3454. # Build loaded filaments from printer status
  3455. loaded_filaments = self._build_loaded_filaments(status)
  3456. if reserved_trays:
  3457. loaded_filaments = [f for f in loaded_filaments if f["global_tray_id"] not in reserved_trays]
  3458. if not loaded_filaments:
  3459. logger.debug("No filaments loaded on printer %s", printer_id)
  3460. return None
  3461. # Check if user prefers lowest remaining filament when multiple spools match
  3462. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  3463. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  3464. # Without backup, the printer will not switch to a second spool when the
  3465. # picked one runs out — so sorting toward the lowest leaves the print
  3466. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  3467. # today's behaviour intentionally.
  3468. if prefer_lowest and status.ams_filament_backup is False:
  3469. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  3470. prefer_lowest = False
  3471. # When the preference is on, surface Bambuddy's inventory-side
  3472. # remaining for each slot that's bound to a tracked spool, so the
  3473. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  3474. # entirely when the preference is off — no behaviour change for
  3475. # users who haven't opted in.
  3476. inventory_remain_overrides: dict[int, float] | None = None
  3477. if prefer_lowest:
  3478. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  3479. # Compute mapping: match required filaments to available slots
  3480. return self._match_filaments_to_slots(
  3481. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  3482. )
  3483. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  3484. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  3485. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  3486. diagnosis (#2771) describes the filament the matcher actually looked
  3487. for, not the one the 3MF was sliced with — naming the pre-override
  3488. filament in a user-facing error would send the user to load the wrong
  3489. spool.
  3490. """
  3491. if not item.filament_overrides:
  3492. return
  3493. try:
  3494. overrides = json.loads(item.filament_overrides)
  3495. override_map = {o["slot_id"]: o for o in overrides}
  3496. for req in filament_reqs:
  3497. if req["slot_id"] in override_map:
  3498. override = override_map[req["slot_id"]]
  3499. req["type"] = override["type"]
  3500. req["color"] = override["color"]
  3501. # A manual/preference override SWAPS the slot's filament, so the
  3502. # 3MF's original tray_info_idx now points at the old spool and must
  3503. # be cleared — matching then falls back to type+colour. A
  3504. # force_color_match override is not a swap: it carries the 3MF's
  3505. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  3506. # it here too, letting the matcher pin the correct variant slot on a
  3507. # printer holding two same-colour spools of different variants (#2650).
  3508. # If that variant isn't loaded the matcher falls back to type+colour,
  3509. # so an eligible printer never fails to map.
  3510. req["tray_info_idx"] = (
  3511. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  3512. )
  3513. logger.debug(
  3514. "Queue item %s: Override slot %d -> %s %s",
  3515. item.id,
  3516. req["slot_id"],
  3517. override["type"],
  3518. override["color"],
  3519. )
  3520. except (json.JSONDecodeError, KeyError, TypeError) as e:
  3521. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  3522. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  3523. """Build an AMS mapping directly from force-color overrides without a 3MF.
  3524. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  3525. slice_info is missing or unreadable) but ``force_color_match`` overrides
  3526. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  3527. treated as the filament requirement for that slot and matched against the
  3528. current AMS state of the printer.
  3529. Returns the same format as ``_match_filaments_to_slots``, or None when
  3530. the AMS has no loaded filaments.
  3531. """
  3532. loaded = self._build_loaded_filaments(status)
  3533. if not loaded:
  3534. return None
  3535. reqs = [
  3536. {
  3537. "slot_id": o["slot_id"],
  3538. "type": o.get("type", ""),
  3539. "color": o.get("color", ""),
  3540. # These are all force_color_match overrides, so the idx (when the
  3541. # 3MF carried one) is the intended variant, not a stale swap —
  3542. # keep it so the matcher pins the right variant slot, falling back
  3543. # to type+colour when it isn't loaded (#2650).
  3544. "tray_info_idx": o.get("tray_info_idx", ""),
  3545. }
  3546. for o in force_overrides
  3547. ]
  3548. return self._match_filaments_to_slots(reqs, loaded)
  3549. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  3550. """Resolve the queue item's source 3MF and parse the per-slot
  3551. filament requirements out of it. Thin DB-resolver wrapper around
  3552. ``filament_requirements.extract_filament_requirements`` so the VP
  3553. queue-mode write path (#1188) can reuse the same parser at upload
  3554. time.
  3555. """
  3556. from backend.app.services.filament_requirements import extract_filament_requirements
  3557. # Callers rewrite these dicts in place via `_apply_filament_overrides`,
  3558. # so every caller gets its own copy — a shared list would leak one
  3559. # item's overrides into the next item that happens to print the same
  3560. # plate.
  3561. memo_key = (item.archive_id, item.library_file_id, item.plate_id)
  3562. if memo_key in self._filament_req_memo:
  3563. cached = self._filament_req_memo[memo_key]
  3564. return [dict(r) for r in cached] if cached else None
  3565. file_path: Path | None = None
  3566. if item.archive_id:
  3567. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3568. archive = result.scalar_one_or_none()
  3569. if archive:
  3570. file_path = settings.base_dir / archive.file_path
  3571. elif item.library_file_id:
  3572. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3573. library_file = result.scalar_one_or_none()
  3574. if library_file:
  3575. lib_path = Path(library_file.file_path)
  3576. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3577. if not file_path or not file_path.exists():
  3578. self._filament_req_memo[memo_key] = None
  3579. return None
  3580. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  3581. self._filament_req_memo[memo_key] = filaments or None
  3582. return [dict(r) for r in filaments] if filaments else None
  3583. def _build_loaded_filaments(self, status) -> list[dict]:
  3584. """Build list of loaded filaments from printer status.
  3585. Args:
  3586. status: PrinterState from printer_manager
  3587. Returns:
  3588. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  3589. """
  3590. filaments = []
  3591. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  3592. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  3593. # Dual-nozzle detection, used below to route external spools to an
  3594. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  3595. # which was corrected for #1257 while this copy kept the old signal.
  3596. #
  3597. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  3598. # printer with zero AMS units reports an empty map — and every external
  3599. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  3600. # `_match_filaments_to_slots` rejects outright because `None` equals
  3601. # neither 0 nor 1. On an X2D feeding from external spools only that left
  3602. # nothing to match, the mapping came back all -1, and the print went out
  3603. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  3604. # "Failed to get AMS mapping table".
  3605. #
  3606. # `nozzles` is always a two-entry list (the state seeds it with two empty
  3607. # NozzleInfo stubs), so its length proves nothing; only a populated
  3608. # diameter on the second entry means real hardware. The other two signals
  3609. # are fallbacks for firmware revisions that surface one but not the
  3610. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  3611. # and so is more than one `vt_tray` entry, since single-nozzle printers
  3612. # expose exactly one external feed.
  3613. nozzles = getattr(status, "nozzles", None) or []
  3614. vt_trays = status.raw_data.get("vt_tray") or []
  3615. is_dual_nozzle = bool(
  3616. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  3617. or ams_extruder_map
  3618. # isinstance, because a dict here would count its ~30 keys as trays.
  3619. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  3620. # so this is unreachable — but the loop below would raise on a dict
  3621. # and that is the pre-existing behaviour to keep, not to paper over.
  3622. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  3623. )
  3624. # Parse AMS units from raw_data
  3625. ams_data = status.raw_data.get("ams", [])
  3626. for ams_unit in ams_data:
  3627. ams_id = int(ams_unit.get("id", 0))
  3628. trays = ams_unit.get("tray", [])
  3629. is_ht = len(trays) == 1 # AMS-HT has single tray
  3630. for tray in trays:
  3631. tray_type = tray.get("tray_type")
  3632. if tray_type:
  3633. tray_id = int(tray.get("id", 0))
  3634. tray_color = tray.get("tray_color", "")
  3635. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  3636. tray_info_idx = tray.get("tray_info_idx", "")
  3637. # Normalize color: remove alpha, add hash
  3638. color = self._normalize_color(tray_color)
  3639. # Calculate global tray ID
  3640. # AMS-HT units have IDs starting at 128 with a single tray
  3641. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  3642. filaments.append(
  3643. {
  3644. "type": tray_type,
  3645. "color": color,
  3646. "tray_info_idx": tray_info_idx,
  3647. "ams_id": ams_id,
  3648. "tray_id": tray_id,
  3649. "is_ht": is_ht,
  3650. "is_external": False,
  3651. "global_tray_id": global_tray_id,
  3652. "extruder_id": ams_extruder_map.get(str(ams_id)),
  3653. "remain": tray.get("remain", -1),
  3654. }
  3655. )
  3656. # Check external spool(s) (vt_tray is a list)
  3657. for idx, vt in enumerate(vt_trays):
  3658. if vt.get("tray_type"):
  3659. color = self._normalize_color(vt.get("tray_color", ""))
  3660. tray_id = int(vt.get("id", 254))
  3661. filaments.append(
  3662. {
  3663. "type": vt["tray_type"],
  3664. "color": color,
  3665. "tray_info_idx": vt.get("tray_info_idx", ""),
  3666. "ams_id": -1,
  3667. "tray_id": idx,
  3668. "is_ht": False,
  3669. "is_external": True,
  3670. "global_tray_id": tray_id,
  3671. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  3672. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  3673. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  3674. "remain": vt.get("remain", -1),
  3675. }
  3676. )
  3677. return filaments
  3678. def _normalize_color(self, color: str | None) -> str:
  3679. """Normalize color to #RRGGBB format."""
  3680. if not color:
  3681. return "#808080"
  3682. hex_color = color.replace("#", "")[:6]
  3683. return f"#{hex_color}"
  3684. def _normalize_color_for_compare(self, color: str | None) -> str:
  3685. """Normalize color for comparison (lowercase, no hash)."""
  3686. if not color:
  3687. return ""
  3688. return color.replace("#", "").lower()[:6]
  3689. def _color_distance(self, color1: str | None, color2: str | None) -> float | None:
  3690. """Perceptual (CIEDE2000) distance, or None when either colour is unusable.
  3691. Ranks the candidates ``_colors_are_similar`` admits (#2804). Eligibility
  3692. stays the per-channel box that shipped — this only decides which of
  3693. several eligible spools is closest, so nothing becomes usable or
  3694. unusable because of it.
  3695. It ranks by how far apart the colours *look*, not how far apart their
  3696. numbers are. RGB distance overweights blue badly enough to invert the
  3697. answer: against a required ``#1E4821`` green, a purple ``#38202F`` is
  3698. the nearer of two eligible spools by RGB and the further by a factor of
  3699. four once measured perceptually.
  3700. Alpha is ignored, deliberately: the alpha a slicer writes for a
  3701. transparent filament is not a colour the user chose, and counting it
  3702. would stop a transparent filament matching itself.
  3703. """
  3704. return perceptual_color_distance(color1, color2)
  3705. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  3706. """Check if two colors are visually similar within a threshold."""
  3707. hex1 = self._normalize_color_for_compare(color1)
  3708. hex2 = self._normalize_color_for_compare(color2)
  3709. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  3710. return False
  3711. try:
  3712. r1 = int(hex1[0:2], 16)
  3713. g1 = int(hex1[2:4], 16)
  3714. b1 = int(hex1[4:6], 16)
  3715. r2 = int(hex2[0:2], 16)
  3716. g2 = int(hex2[2:4], 16)
  3717. b2 = int(hex2[4:6], 16)
  3718. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  3719. except ValueError:
  3720. return False
  3721. async def _build_inventory_remain_overrides(
  3722. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  3723. ) -> dict[int, float]:
  3724. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  3725. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  3726. The MQTT ``remain`` field on a tray is the printer firmware's
  3727. RFID-decremented value, which has two limitations the "Prefer Lowest
  3728. Remaining Filament" feature has been ignoring (#1508):
  3729. - it's only meaningful for Bambu RFID spools; everything else reports
  3730. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  3731. compare equal and the sort collapses to AMS-slot order — the user
  3732. who's curating inventory weights gets the lower-slot pick instead
  3733. of the lower-remaining pick;
  3734. - even when set, it's the *printer's* counter, not Bambuddy's
  3735. ``label_weight - weight_used`` (internal mode) or Spoolman's
  3736. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  3737. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  3738. When the user has bound a spool to a slot, their own inventory
  3739. tracking is authoritative; this helper surfaces that value so the
  3740. sort can prefer it. Slots without a binding are absent from the
  3741. returned map — the caller then falls back to MQTT ``remain`` for
  3742. those, preserving the pre-#1508 behaviour for un-tracked spools.
  3743. Returns an empty map on any failure (no inventory bindings, DB
  3744. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  3745. is a preference, not a guarantee.
  3746. """
  3747. if not loaded:
  3748. return {}
  3749. # External / virtual-tray slots are tracked separately from AMS — skip
  3750. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  3751. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  3752. # match is fiddly and out of scope for this fix).
  3753. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  3754. if not tracked_slots:
  3755. return {}
  3756. is_spoolman = await self._is_spoolman_mode(db)
  3757. overrides: dict[int, float] = {}
  3758. if is_spoolman:
  3759. result = await db.execute(
  3760. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3761. )
  3762. assignments = list(result.scalars().all())
  3763. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  3764. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  3765. for ams_id, tray_id, gtid in tracked_slots:
  3766. spoolman_id = by_slot.get((ams_id, tray_id))
  3767. if spoolman_id is None:
  3768. continue
  3769. grams = await _spoolman_remaining_grams(spoolman_id)
  3770. if grams is not None:
  3771. overrides[gtid] = grams
  3772. return overrides
  3773. # Internal inventory mode (default). selectinload matches the pattern
  3774. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  3775. # plus an eager-loaded relationship rather than an explicit join, so
  3776. # the row-attribute shape is exactly what those routes already rely on.
  3777. result = await db.execute(
  3778. select(SpoolAssignment)
  3779. .options(selectinload(SpoolAssignment.spool))
  3780. .where(SpoolAssignment.printer_id == printer_id)
  3781. )
  3782. assignments = list(result.scalars().all())
  3783. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  3784. for ams_id, tray_id, gtid in tracked_slots:
  3785. spool = by_slot.get((ams_id, tray_id))
  3786. if spool is None:
  3787. continue
  3788. label = float(spool.label_weight or 0)
  3789. used = float(spool.weight_used or 0)
  3790. overrides[gtid] = max(0.0, label - used)
  3791. return overrides
  3792. @staticmethod
  3793. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  3794. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  3795. here to avoid making this module import-dependent on that private
  3796. helper's signature."""
  3797. try:
  3798. from backend.app.api.routes.settings import get_setting
  3799. v = await get_setting(db, "spoolman_enabled")
  3800. return bool(v) and v.lower() == "true"
  3801. except Exception:
  3802. return False
  3803. @staticmethod
  3804. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  3805. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  3806. Three bands, matched to the emission order in ``_build_loaded_filaments``
  3807. so a tied sort produces the same physical-position order the pre-#1508
  3808. stable sort did (preserves the regression-free baseline):
  3809. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  3810. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  3811. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  3812. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  3813. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  3814. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  3815. """
  3816. if ams_id is None or ams_id < 0:
  3817. return 10_000
  3818. if ams_id >= 128:
  3819. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  3820. return ams_id * 4 + (tray_id or 0)
  3821. @staticmethod
  3822. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  3823. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  3824. Two-tier ordering: inventory-tracked spools always sort BEFORE
  3825. non-tracked spools (the user has told us they care about these
  3826. specifically), then ascending by remaining within each tier, then
  3827. ascending by AMS slot position as the deterministic tie-breaker.
  3828. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  3829. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  3830. because the tier flag dominates — which is what lets us mix grams
  3831. (inventory) and percent (MQTT) without a unit conversion.
  3832. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  3833. spools the printer DOES know something about sort ahead of those
  3834. it knows nothing about — preserves pre-#1508 behaviour for the
  3835. no-inventory-binding case.
  3836. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  3837. external on ties, matching the legacy emission-order stable sort.
  3838. """
  3839. gtid = f.get("global_tray_id")
  3840. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  3841. if overrides and gtid in overrides:
  3842. return (0, overrides[gtid], slot_order)
  3843. remain = f.get("remain", -1)
  3844. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  3845. def _match_filaments_to_slots(
  3846. self,
  3847. required: list[dict],
  3848. loaded: list[dict],
  3849. prefer_lowest: bool = False,
  3850. inventory_remain_overrides: dict[int, float] | None = None,
  3851. fts_installed: bool = False,
  3852. ) -> list[int] | None:
  3853. """Match required filaments to loaded filaments and build AMS mapping.
  3854. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  3855. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  3856. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  3857. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  3858. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  3859. matching among those trays.
  3860. Args:
  3861. required: List of required filaments with slot_id, type, color, tray_info_idx
  3862. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  3863. Returns:
  3864. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  3865. """
  3866. if not required:
  3867. return None
  3868. # Track used trays to avoid duplicate assignment
  3869. used_tray_ids: set[int] = set()
  3870. comparisons = []
  3871. for req in required:
  3872. req_type = (req.get("type") or "").upper()
  3873. req_color = req.get("color", "")
  3874. req_tray_info_idx = req.get("tray_info_idx", "")
  3875. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  3876. idx_match = None
  3877. exact_match = None
  3878. similar_match = None
  3879. similar_distance = float("inf")
  3880. type_only_match = None
  3881. # Get available trays (not already used)
  3882. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  3883. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  3884. # Hard filter — cross-nozzle assignment causes print failures
  3885. # ("position of left hotend is abnormal"), so never fall back.
  3886. # Skipped when an FTS is installed: it routes any AMS slot to either
  3887. # extruder, so restricting to one nozzle would wrongly exclude the
  3888. # correct spool sitting in the other nozzle's AMS (#2186).
  3889. req_nozzle_id = req.get("nozzle_id")
  3890. if req_nozzle_id is not None and not fts_installed:
  3891. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  3892. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  3893. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  3894. # _prefer_lowest_sort_key for the full rationale.
  3895. if prefer_lowest:
  3896. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  3897. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  3898. # One line per filament req so a bug report can be diagnosed
  3899. # without enabling debug logging: shows what the matcher saw
  3900. # (req shape + sorted candidate trays with their remain values
  3901. # and any inventory override that was applied). Mirrored by
  3902. # the picked-match log at the bottom of the loop.
  3903. logger.info(
  3904. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  3905. req.get("slot_id"),
  3906. req_type,
  3907. req_color,
  3908. req_tray_info_idx,
  3909. req_nozzle_id,
  3910. [
  3911. {
  3912. "gtid": f.get("global_tray_id"),
  3913. "type": f.get("type"),
  3914. "color": f.get("color"),
  3915. "tii": f.get("tray_info_idx"),
  3916. "remain": f.get("remain"),
  3917. "inv_g": (
  3918. inventory_remain_overrides.get(f.get("global_tray_id"))
  3919. if inventory_remain_overrides
  3920. else None
  3921. ),
  3922. }
  3923. for f in available
  3924. ],
  3925. )
  3926. # Check if tray_info_idx is unique among available trays
  3927. if req_tray_info_idx:
  3928. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  3929. if len(idx_matches) == 1:
  3930. # Unique tray_info_idx - use it as definitive match
  3931. idx_match = idx_matches[0]
  3932. logger.debug(
  3933. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  3934. f"-> tray {idx_match['global_tray_id']}"
  3935. )
  3936. elif len(idx_matches) > 1:
  3937. # Multiple trays with same tray_info_idx - use color matching among them
  3938. logger.debug(
  3939. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  3940. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  3941. )
  3942. if prefer_lowest:
  3943. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  3944. # Use color matching within this subset
  3945. for f in idx_matches:
  3946. f_color = f.get("color", "")
  3947. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  3948. if not exact_match:
  3949. exact_match = f
  3950. elif self._colors_are_similar(f_color, req_color):
  3951. distance = self._color_distance(f_color, req_color)
  3952. if distance is not None and distance < similar_distance:
  3953. similar_match = f
  3954. similar_distance = distance
  3955. elif not type_only_match:
  3956. type_only_match = f
  3957. # If no idx_match yet, do standard type/color matching on all available trays
  3958. if not idx_match and not exact_match and not similar_match and not type_only_match:
  3959. for f in available:
  3960. f_type = (f.get("type") or "").upper()
  3961. if canonical_filament_type(f_type) != canonical_filament_type(req_type):
  3962. continue
  3963. # Type matches - check color
  3964. f_color = f.get("color", "")
  3965. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  3966. if not exact_match:
  3967. exact_match = f
  3968. elif self._colors_are_similar(f_color, req_color):
  3969. # Nearest wins, not first-in-tray-order. `available` is
  3970. # already in the caller's order (slot order, or the
  3971. # prefer-lowest sort), and `<` keeps the earliest of
  3972. # equally close spools — so that order survives as the
  3973. # tie-break (#2804).
  3974. distance = self._color_distance(f_color, req_color)
  3975. if distance is not None and distance < similar_distance:
  3976. similar_match = f
  3977. similar_distance = distance
  3978. elif not type_only_match:
  3979. type_only_match = f
  3980. match = idx_match or exact_match or similar_match or type_only_match
  3981. if match:
  3982. used_tray_ids.add(match["global_tray_id"])
  3983. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  3984. else:
  3985. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  3986. # Which bucket won, always — not only under Prefer Lowest (#2804).
  3987. # "Why did it pick that spool" is the question every wrong-filament
  3988. # report starts with, and a `similar_color` win is now a ranked
  3989. # choice among several eligible spools rather than whichever tray
  3990. # came first, so it is worth being able to see after the fact.
  3991. # Pairs with the "available (sorted)" log above when Prefer Lowest
  3992. # is on (#1766).
  3993. if match:
  3994. bucket = (
  3995. "idx"
  3996. if idx_match is not None
  3997. else "exact_color"
  3998. if exact_match is not None
  3999. else "similar_color"
  4000. if similar_match is not None
  4001. else "type_only"
  4002. )
  4003. logger.info(
  4004. "[ams-match] picked gtid=%s via %s for req slot=%s%s",
  4005. match["global_tray_id"],
  4006. bucket,
  4007. req.get("slot_id"),
  4008. f" (deltaE {similar_distance:.2f})" if bucket == "similar_color" else "",
  4009. )
  4010. else:
  4011. logger.info(
  4012. "[ams-match] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  4013. req.get("slot_id"),
  4014. req_type,
  4015. req_color,
  4016. req_tray_info_idx,
  4017. )
  4018. # Build mapping array
  4019. if not comparisons:
  4020. return None
  4021. max_slot_id = max(c["slot_id"] for c in comparisons)
  4022. if max_slot_id <= 0:
  4023. return None
  4024. mapping = [-1] * max_slot_id
  4025. for c in comparisons:
  4026. slot_id = c["slot_id"]
  4027. if slot_id and slot_id > 0:
  4028. mapping[slot_id - 1] = c["global_tray_id"]
  4029. return mapping
  4030. def _mark_printer_dispatched(
  4031. self,
  4032. printer_id: int,
  4033. pre_state: str | None,
  4034. pre_subtask_id: str | None,
  4035. ) -> None:
  4036. """Record that a print command was just sent to ``printer_id``.
  4037. Held until either the watchdog observes a state/subtask transition
  4038. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  4039. """
  4040. if not pre_state:
  4041. # No pre_state means we can't detect a transition — fall back to a
  4042. # pure time-based hold using empty string as a sentinel that won't
  4043. # match any real printer state.
  4044. pre_state = ""
  4045. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  4046. def _release_dispatch_hold(self, printer_id: int) -> None:
  4047. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  4048. self._dispatch_holds.pop(printer_id, None)
  4049. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  4050. """True if ``printer_id`` is still inside its post-dispatch hold window.
  4051. Returns False (and clears the hold) once any of these are true:
  4052. - hard timeout (``_dispatch_max_hold``) has elapsed
  4053. - the printer has transitioned out of pre_state and we're past the
  4054. minimum cooldown
  4055. - the printer's subtask_id has advanced past pre_subtask_id and we're
  4056. past the minimum cooldown
  4057. Otherwise the printer is held — caller should treat it as busy.
  4058. """
  4059. entry = self._dispatch_holds.get(printer_id)
  4060. if not entry:
  4061. return False
  4062. started_at, pre_state, pre_subtask_id = entry
  4063. elapsed = time.monotonic() - started_at
  4064. if elapsed >= self._dispatch_max_hold:
  4065. self._dispatch_holds.pop(printer_id, None)
  4066. return False
  4067. # Without a pre_state we can't detect a transition — fall back to the
  4068. # min cooldown alone, then drop the hold.
  4069. if not pre_state:
  4070. if elapsed >= self._dispatch_min_cooldown:
  4071. self._dispatch_holds.pop(printer_id, None)
  4072. return False
  4073. return True
  4074. status = printer_manager.get_status(printer_id)
  4075. current_state = getattr(status, "state", None) if status else None
  4076. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  4077. transitioned = (current_state is not None and current_state != pre_state) or (
  4078. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  4079. )
  4080. if transitioned and elapsed >= self._dispatch_min_cooldown:
  4081. self._dispatch_holds.pop(printer_id, None)
  4082. return False
  4083. return True
  4084. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  4085. """Check if a printer is connected and idle."""
  4086. if not printer_manager.is_connected(printer_id):
  4087. logger.debug("Printer %d: not connected", printer_id)
  4088. return False
  4089. state = printer_manager.get_status(printer_id)
  4090. if not state:
  4091. logger.debug("Printer %d: no status available", printer_id)
  4092. return False
  4093. # Plate-clear gate: if the printer finished/failed a previous print and the user
  4094. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  4095. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  4096. # printer, it boots back into IDLE with no memory of the previous finish; without
  4097. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  4098. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4099. logger.debug(
  4100. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  4101. printer_id,
  4102. state.state,
  4103. )
  4104. return False
  4105. idle = state.state in ("IDLE", "FINISH", "FAILED")
  4106. if not idle:
  4107. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  4108. return idle
  4109. @staticmethod
  4110. def _pinned_hold_reason(printer_id: int, printer_name: str, require_plate_clear: bool) -> str:
  4111. """Why a connected, non-idle printer cannot take this job, for the queue row (#3074).
  4112. Only ever asked about a printer :meth:`_is_printer_idle` has just refused
  4113. and that the fixed-printer branch has already found connected, so the two
  4114. offline cases answer at their own exits and never arrive here.
  4115. The default is the model-based branch's ``Busy:`` wording, which
  4116. :meth:`_is_busy_only` reads as "resolves itself, stay quiet". That is also
  4117. the right answer for the connected-but-no-telemetry second or two after a
  4118. reconnect: the model-based branch has always reported it that way, and it
  4119. is not something to wake anybody up for.
  4120. A plate nobody has confirmed is the one case here that does not resolve
  4121. itself — somebody has to walk over to the printer — so it is worded as
  4122. itself and allowed to notify.
  4123. """
  4124. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  4125. return f"Waiting for plate confirmation: {printer_name}"
  4126. return f"Busy: {printer_name}"
  4127. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  4128. """Read a setting value from the database."""
  4129. result = await db.execute(select(Settings).where(Settings.key == key))
  4130. setting = result.scalar_one_or_none()
  4131. return setting.value if setting else None
  4132. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  4133. """Read a boolean setting from the database."""
  4134. result = await db.execute(select(Settings).where(Settings.key == key))
  4135. setting = result.scalar_one_or_none()
  4136. if setting:
  4137. return setting.value.lower() == "true"
  4138. return default
  4139. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  4140. """Read an int setting; falls back to default on missing/unparseable rows."""
  4141. result = await db.execute(select(Settings).where(Settings.key == key))
  4142. setting = result.scalar_one_or_none()
  4143. if setting and setting.value:
  4144. try:
  4145. return int(setting.value)
  4146. except ValueError:
  4147. pass
  4148. return default
  4149. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  4150. """Get drying presets (user-configured or built-in defaults)."""
  4151. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  4152. setting = result.scalar_one_or_none()
  4153. if setting and setting.value:
  4154. try:
  4155. presets = json.loads(setting.value)
  4156. if isinstance(presets, dict) and presets:
  4157. return presets
  4158. except json.JSONDecodeError:
  4159. pass
  4160. return self.DEFAULT_DRYING_PRESETS
  4161. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  4162. """Per-filament humidity thresholds (#1605).
  4163. Returns the user-configured overrides map keyed by normalized filament
  4164. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  4165. unknown / unmapped types. Empty / unset → empty dict, in which case
  4166. callers fall back to ``ams_humidity_fair``.
  4167. """
  4168. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4169. setting = result.scalar_one_or_none()
  4170. if not setting or not setting.value:
  4171. return {}
  4172. try:
  4173. data = json.loads(setting.value)
  4174. except json.JSONDecodeError:
  4175. return {}
  4176. if not isinstance(data, dict):
  4177. return {}
  4178. out: dict[str, int] = {}
  4179. for key, value in data.items():
  4180. try:
  4181. out[str(key).upper() if key != "default" else "default"] = int(value)
  4182. except (TypeError, ValueError):
  4183. continue
  4184. return out
  4185. # Materials whose AMS spelling differs from the key the tables above use.
  4186. # Bambu labels nylon "PA" while its own composites spell the family out, so
  4187. # PA6, PA11, PA12 and PAHT would otherwise miss a table with a perfectly
  4188. # good PA row (#3067).
  4189. #
  4190. # Mirrors DRYING_MATERIAL_ALIASES in frontend/src/utils/dryingPresets.ts.
  4191. # The drying popover has resolved these correctly since #2774 and the
  4192. # scheduler never did, which is exactly why #3067's reporter could dry a
  4193. # PA6-CF spool by hand while auto-drying skipped it every pass.
  4194. #
  4195. # PPA is here too. Polyphthalamide is a distinct polymer rather than a grade
  4196. # of nylon, so it is the one entry that is a judgement rather than a
  4197. # spelling -- but it is an aromatic polyamide, it absorbs moisture the same
  4198. # way, and PA's row is the hottest the table has. Drying it there is closer
  4199. # to right than not drying it at all, which is what it got before.
  4200. FILAMENT_KEY_ALIASES: dict[str, str] = {
  4201. "NYLON": "PA",
  4202. "PA6": "PA",
  4203. "PA11": "PA",
  4204. "PA12": "PA",
  4205. "PAHT": "PA",
  4206. "PPA": "PA",
  4207. }
  4208. @classmethod
  4209. def _resolve_filament_key(cls, tray_type: str | None, table: Mapping[str, object]) -> str | None:
  4210. """The key in *table* that answers for this tray's material, or None.
  4211. The printer reports the material in ``tray_type``, and it spells filled
  4212. and foamed variants out: PLA-CF, PETG-CF, ABS-GF, PLA-AERO, PA6-CF. The
  4213. tables here are keyed by base material, so matching the raw string alone
  4214. found a row for 8 of the 41 types a printer can report and skipped the
  4215. rest -- silently, because every caller reads "no row" as "nothing to do
  4216. for this tray". Auto-drying therefore ignored every composite spool on
  4217. the install (#3067).
  4218. Exact match first, so a table the user has extended with a row of its
  4219. own -- ``PA6-CF`` at a temperature they picked -- still wins over the
  4220. base material's. Then the suffix is dropped, then the alias map above
  4221. answers for the polyamide spellings.
  4222. Returns None rather than a default: what to do with an unrecognised
  4223. material differs per caller, and only the caller knows whether "no row"
  4224. means skip the tray or fall back to a catch-all. Nothing here invents a
  4225. temperature for a material the table does not list.
  4226. """
  4227. raw = cls._normalize_filament_type(tray_type or "")
  4228. if not raw:
  4229. return None
  4230. for candidate in (raw, raw.split("-")[0]):
  4231. key = cls.FILAMENT_KEY_ALIASES.get(candidate, candidate)
  4232. if key in table:
  4233. return key
  4234. return None
  4235. @staticmethod
  4236. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  4237. """Resolve the effective humidity threshold for an AMS unit (#1605).
  4238. For mixed filament types loaded into one AMS, returns the most
  4239. restrictive (lowest) threshold across all loaded tray types — matches
  4240. the conservative-params strategy already used for drying temp/hours.
  4241. Empty / unloaded trays contribute no constraint. Unknown types use the
  4242. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  4243. when no per-type map is configured at all.
  4244. """
  4245. default = thresholds.get("default", fallback)
  4246. if not thresholds:
  4247. return fallback
  4248. candidates: list[int] = []
  4249. for tray in trays:
  4250. tray_type = str(tray.get("tray_type") or "").strip()
  4251. if not tray_type:
  4252. continue
  4253. # A composite carries its base material's threshold when it has no
  4254. # row of its own, the same way it takes its drying preset (#3067).
  4255. key = PrintScheduler._resolve_filament_key(tray_type, thresholds)
  4256. candidates.append(thresholds[key] if key is not None else default)
  4257. if not candidates:
  4258. return default
  4259. return min(candidates)
  4260. def _get_conservative_drying_params(
  4261. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  4262. ) -> tuple[int, int, str] | None:
  4263. """Get the most conservative drying params for mixed filament types in an AMS unit.
  4264. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  4265. """
  4266. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  4267. hours_key = f"{temp_key}_hours"
  4268. min_temp = None
  4269. max_hours = None
  4270. filament_type = ""
  4271. for tray in trays:
  4272. tray_type = tray.get("tray_type", "")
  4273. if not tray_type:
  4274. continue
  4275. # "PLA Basic" -> PLA, and "PA6-CF" -> PA rather than nothing at all,
  4276. # which is what stopped auto-drying on every composite spool (#3067).
  4277. base_type = self._resolve_filament_key(tray_type, presets)
  4278. if base_type is None:
  4279. continue
  4280. # The table is user-editable JSON with no per-row validation, so a
  4281. # row can be present and empty. That has always meant "skip this
  4282. # material", and it has to keep meaning it: the reads below fall
  4283. # back to 55C/12h per missing field, which is a temperature nobody
  4284. # chose and would deform a PLA spool.
  4285. preset = presets[base_type]
  4286. if not preset:
  4287. continue
  4288. temp = preset.get(temp_key, 55)
  4289. hours = preset.get(hours_key, 12)
  4290. # Conservative: lowest temp, longest duration
  4291. if min_temp is None or temp < min_temp:
  4292. min_temp = temp
  4293. if max_hours is None or hours > max_hours:
  4294. max_hours = hours
  4295. if not filament_type:
  4296. filament_type = base_type
  4297. if min_temp is None:
  4298. return None
  4299. return (min_temp, max_hours or 12, filament_type)
  4300. async def _check_filament_low(self, db: AsyncSession) -> None:
  4301. """Alert on AMS slots whose assigned spool has crossed its low-stock threshold (#2913).
  4302. ``on_filament_low`` has had a column, a schema field, a route, a template
  4303. and a UI toggle since the notification system was built, and no caller --
  4304. so the toggle could be switched on and could never fire. This is the
  4305. producer.
  4306. No new setting. ``low_stock_threshold`` (default 20%) with the per-spool
  4307. ``low_stock_threshold_pct`` override is already exactly this decision:
  4308. already configurable, already surfaced, already driving the Inventory
  4309. page's Low Stock count. The AMS ``remain`` percentage is deliberately not
  4310. consulted -- it has been measured up to 56 points out against a scale,
  4311. which is not a number to page someone on.
  4312. Only slots with an assigned spool produce an event. A slot Bambuddy
  4313. cannot resolve to a spool has no remaining weight it can stand behind,
  4314. and guessing one is how the remain percentage would have got in.
  4315. """
  4316. from backend.app.models.spool import Spool
  4317. # Time-gated rather than run on every pass. run() sleeps
  4318. # _fast_check_interval -- 3 seconds -- on any productive pass, and the
  4319. # early-return path counts as productive while an upload is in flight
  4320. # (#2602), so an unthrottled check would re-read the whole spool
  4321. # collection every 3 seconds for the length of a batch drain. In
  4322. # Spoolman mode that is a request storm against a third-party service,
  4323. # which is the thing this producer's design note argues against; and
  4324. # when Spoolman is down, _get_with_retry burns ~16 s inside
  4325. # check_queue holding the scheduler's session, so the outage would
  4326. # throttle the print queue itself. A low spool is not a 3-second
  4327. # concern -- the idle interval is the natural resolution.
  4328. now = time.monotonic()
  4329. if now < self._filament_low_next_check:
  4330. return
  4331. self._filament_low_next_check = now + _FILAMENT_LOW_MIN_INTERVAL
  4332. try:
  4333. # on_filament_low defaults to off on every provider, so on most
  4334. # installs nobody wants this alert. Without this the check would
  4335. # still read every assigned spool each interval -- the whole
  4336. # collection over HTTP in Spoolman mode -- for an event that is
  4337. # switched off. One query against the provider table settles it
  4338. # before any spool work, the same guard the bed-cooled waiter uses.
  4339. # No printer_id: this asks whether any provider wants the event at
  4340. # all; per-printer scoping is applied when the event is sent.
  4341. #
  4342. # While nobody wants it, no pass sees a slot go back above its
  4343. # threshold, so nothing can re-arm; a spool refilled under the same
  4344. # id in that time would stay silenced until a restart. Forgetting
  4345. # what was sent is right anyway: whoever switches the event back on
  4346. # is told about the spools that are low now.
  4347. if not await notification_service._get_providers_for_event(db, "on_filament_low"):
  4348. self._notified_filament_low.clear()
  4349. return
  4350. global_threshold = await self._get_low_stock_threshold(db)
  4351. spoolman_on = await self._get_bool_setting(db, "spoolman_enabled")
  4352. # (printer_id, ams_id, tray_id, spool_id) -> (remaining_pct, threshold, colour name)
  4353. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4354. if spoolman_on:
  4355. slots = await self._filament_low_slots_spoolman(db, global_threshold)
  4356. else:
  4357. rows = (
  4358. await db.execute(
  4359. select(SpoolAssignment, Spool)
  4360. .join(Spool, SpoolAssignment.spool_id == Spool.id)
  4361. # An archived spool is not stock. The Inventory page's
  4362. # Low Stock count skips them (InventoryPage.tsx:1089)
  4363. # and get_all_spools without allow_archived already
  4364. # excludes them in Spoolman mode, so without this the
  4365. # internal path is the only one that alerts on them.
  4366. .where(Spool.archived_at.is_(None))
  4367. )
  4368. ).all()
  4369. for assignment, spool in rows:
  4370. pct = _remaining_percent(spool.label_weight, spool.weight_used)
  4371. if pct is None:
  4372. continue
  4373. threshold = float(spool.low_stock_threshold_pct or global_threshold)
  4374. slots[(assignment.printer_id, assignment.ams_id, assignment.tray_id, spool.id)] = (
  4375. pct,
  4376. threshold,
  4377. spool.color_name,
  4378. )
  4379. if not slots:
  4380. # Nothing resolvable this pass. Deliberately not clearing the
  4381. # notified set: a Spoolman that is briefly unreachable would
  4382. # otherwise re-alert on every spool as soon as it came back.
  4383. return
  4384. await self._emit_filament_low(db, slots)
  4385. except Exception as e:
  4386. logger.warning("Low-filament check failed: %s", e, exc_info=True)
  4387. async def _get_low_stock_threshold(self, db: AsyncSession) -> float:
  4388. """The global low-stock percentage, defaulting to the schema's 20.0."""
  4389. raw = (await db.execute(select(Settings).where(Settings.key == "low_stock_threshold"))).scalar_one_or_none()
  4390. if raw is None or raw.value is None:
  4391. return 20.0
  4392. try:
  4393. value = float(raw.value)
  4394. except (TypeError, ValueError):
  4395. return 20.0
  4396. return value if 0 < value <= 100 else 20.0
  4397. async def _filament_low_slots_spoolman(
  4398. self, db: AsyncSession, global_threshold: float
  4399. ) -> dict[tuple[int, int, int, int], tuple[float, float, str | None]]:
  4400. """Resolve Spoolman-mode slots to (remaining %, threshold, colour name).
  4401. Spoolman spools carry no per-spool override -- ``low_stock_threshold_pct``
  4402. is a column on Bambuddy's own spool table and has no Spoolman equivalent,
  4403. so the global threshold is the only one that applies here. That matches
  4404. what the Inventory page already does in this mode.
  4405. One ``get_all_spools`` call covers every slot rather than a request per
  4406. spool. Archived spools do not appear -- ``get_all_spools`` excludes them
  4407. without ``allow_archived`` -- which is the behaviour the internal path
  4408. has to ask for explicitly.
  4409. An unreachable Spoolman returns no slots rather than raising. It is an
  4410. ordinary state for a third-party service, not an error in this pass: the
  4411. caller's "nothing resolvable" branch already leaves the notified set
  4412. alone, which is exactly right here, whereas letting it reach the broad
  4413. ``except`` would write a full traceback every time the check runs.
  4414. """
  4415. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4416. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4417. assignments = (await db.execute(select(SpoolmanSlotAssignment))).scalars().all()
  4418. if not assignments:
  4419. return {}
  4420. client = await get_spoolman_client()
  4421. if client is None:
  4422. return {}
  4423. try:
  4424. all_spools = await client.get_all_spools()
  4425. except SpoolmanUnavailableError as e:
  4426. logger.debug("Low-filament check skipped, Spoolman unreachable: %s", e)
  4427. return {}
  4428. by_id: dict[int, dict] = {}
  4429. for raw in all_spools:
  4430. raw_id = raw.get("id")
  4431. if isinstance(raw_id, int):
  4432. by_id[raw_id] = raw
  4433. slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]] = {}
  4434. for assignment in assignments:
  4435. raw = by_id.get(assignment.spoolman_spool_id)
  4436. if raw is None:
  4437. continue
  4438. try:
  4439. mapped = _map_spoolman_spool(raw)
  4440. except ValueError:
  4441. continue
  4442. pct = _remaining_percent(mapped.get("label_weight"), mapped.get("weight_used"))
  4443. if pct is None:
  4444. continue
  4445. key = (assignment.printer_id, assignment.ams_id, assignment.tray_id, assignment.spoolman_spool_id)
  4446. slots[key] = (pct, global_threshold, mapped.get("color_name"))
  4447. return slots
  4448. async def _emit_filament_low(
  4449. self, db: AsyncSession, slots: dict[tuple[int, int, int, int], tuple[float, float, str | None]]
  4450. ) -> None:
  4451. """Send one notification per slot that has newly crossed its threshold."""
  4452. printer_names: dict[int, str] = {}
  4453. for key, (pct, threshold, color) in slots.items():
  4454. printer_id, ams_id, tray_id, _spool_id = key
  4455. if pct >= threshold:
  4456. # Back above the line: re-arm rather than expire on a timer, so a
  4457. # refilled slot can alert again and a spool sitting just under the
  4458. # threshold stays quiet.
  4459. self._notified_filament_low.discard(key)
  4460. continue
  4461. if key in self._notified_filament_low:
  4462. continue
  4463. # Marked before sending, which is a choice rather than the only
  4464. # option, and it is the opposite failure mode from the one the
  4465. # debounce argues against: one transient provider failure loses this
  4466. # alert until the spool goes back above the threshold and crosses it
  4467. # again. Marking after a successful send would trade that for
  4468. # re-alerting on every pass while a provider is down -- which is the
  4469. # repetition the whole debounce exists to prevent, and the louder of
  4470. # the two failures. A spool that is low stays low, so the next real
  4471. # signal is not far away; a provider stuck retrying is a signal that
  4472. # never stops.
  4473. self._notified_filament_low.add(key)
  4474. if printer_id not in printer_names:
  4475. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4476. if printer is None:
  4477. continue
  4478. printer_names[printer_id] = printer.name
  4479. try:
  4480. await notification_service.on_filament_low(
  4481. printer_id,
  4482. printer_names[printer_id],
  4483. _ams_slot_label(ams_id, tray_id),
  4484. int(pct),
  4485. db,
  4486. color=color,
  4487. )
  4488. except Exception as e:
  4489. logger.warning("Low-filament notification failed for slot %s: %s", key, e)
  4490. async def _check_stock_forecast(self, db: AsyncSession) -> None:
  4491. """Alert when a filament SKU reaches its reorder point or is about to break (#2955).
  4492. ``on_stock_reorder_alert`` and ``on_stock_break_alert`` have had a column,
  4493. a schema field, a template and a UI toggle, and nothing that computes the
  4494. condition -- the Forecast panel does it in the browser, so with no page
  4495. open nothing could ever alert. This runs the same arithmetic
  4496. (``stock_forecast``) from the scheduler loop.
  4497. An alert is sent when a SKU *moves into* a condition, once, and again
  4498. after the condition has cleared. A SKU that worsens from reorder to break
  4499. alerts again as a break, because the panel treats the two as exclusive; one
  4500. that eases from break back to reorder does not alert again.
  4501. A SKU with alerts snoozed is treated as not alerting, so un-snoozing it
  4502. while it is still low tells you.
  4503. Time-gated to hourly for the reasons ``_check_filament_low`` is gated: the
  4504. loop runs every 3 s while an upload is in flight, and the whole spool
  4505. collection is read over HTTP in Spoolman mode. Both events default to off
  4506. on every provider, so nothing is read unless a provider wants one.
  4507. """
  4508. now = time.monotonic()
  4509. if now < self._stock_forecast_next_check:
  4510. return
  4511. self._stock_forecast_next_check = now + _STOCK_FORECAST_MIN_INTERVAL
  4512. try:
  4513. if self._stock_alerts_persisted is None:
  4514. await self._load_stock_alerts(db)
  4515. wanted = {
  4516. "reorder": bool(await notification_service._get_providers_for_event(db, "on_stock_reorder_alert")),
  4517. "break": bool(await notification_service._get_providers_for_event(db, "on_stock_break_alert")),
  4518. }
  4519. if not any(wanted.values()):
  4520. # Nobody wants either event. Forget what was sent, so whoever
  4521. # switches one on is told about the SKUs that are low now.
  4522. self._notified_stock_alerts.clear()
  4523. await self._save_stock_alerts(db)
  4524. return
  4525. forecasts = await self._stock_forecasts(db)
  4526. if forecasts is None:
  4527. # Spoolman unreachable. Deliberately not clearing the notified
  4528. # set: a brief outage would otherwise re-alert every SKU when it
  4529. # came back.
  4530. return
  4531. await self._emit_stock_alerts(db, forecasts, wanted)
  4532. await self._save_stock_alerts(db)
  4533. except Exception as e:
  4534. logger.warning("Stock forecast check failed: %s", e, exc_info=True)
  4535. def _serialize_stock_alerts(self) -> str:
  4536. """The notified set as JSON, in a fixed order so an unchanged set compares equal."""
  4537. rows = sorted([list(key), kind, sorted(events)] for key, (kind, events) in self._notified_stock_alerts.items())
  4538. return json.dumps(rows)
  4539. async def _load_stock_alerts(self, db: AsyncSession) -> None:
  4540. """Read the notified set saved by the last run, once per process.
  4541. A missing or unreadable row is an empty set: the worst that does is one
  4542. repeat of what a restart used to cause every time.
  4543. """
  4544. raw = (await db.execute(select(Settings).where(Settings.key == _STOCK_ALERTS_SETTING_KEY))).scalar_one_or_none()
  4545. loaded: dict[stock_forecast.SkuKey, tuple[str, frozenset[str]]] = {}
  4546. if raw and raw.value:
  4547. try:
  4548. for key, kind, events in json.loads(raw.value):
  4549. if len(key) == 4 and kind in ("reorder", "break"):
  4550. loaded[tuple(str(part) for part in key)] = (kind, frozenset(str(e) for e in events))
  4551. except (ValueError, TypeError):
  4552. logger.warning("Ignoring unreadable %s setting", _STOCK_ALERTS_SETTING_KEY)
  4553. loaded = {}
  4554. self._notified_stock_alerts = loaded
  4555. self._stock_alerts_persisted = self._serialize_stock_alerts()
  4556. async def _save_stock_alerts(self, db: AsyncSession) -> None:
  4557. """Write the notified set to its settings row if it changed since it was last read or written."""
  4558. serialized = self._serialize_stock_alerts()
  4559. if serialized == self._stock_alerts_persisted:
  4560. return
  4561. from backend.app.core.db_dialect import upsert_setting
  4562. await upsert_setting(db, Settings, _STOCK_ALERTS_SETTING_KEY, serialized)
  4563. await db.commit()
  4564. self._stock_alerts_persisted = serialized
  4565. async def _stock_forecasts(self, db: AsyncSession) -> stock_forecast.ForecastMap | None:
  4566. """Forecast every active SKU in whichever inventory mode is on. None if it cannot be read."""
  4567. from backend.app.models.filament_sku_settings import FilamentSkuSettings
  4568. global_lead_time = max(0, await self._get_int_setting(db, "forecast_global_lead_time_days", default=0))
  4569. sku_rows = (await db.execute(select(FilamentSkuSettings))).scalars().all()
  4570. sku_settings = {
  4571. stock_forecast.sku_key(row.material, row.subtype, row.brand, row.color_name): stock_forecast.SkuSettings(
  4572. lead_time_days=row.lead_time_days,
  4573. safety_margin_value=row.safety_margin_value,
  4574. safety_margin_unit=row.safety_margin_unit,
  4575. alerts_snoozed=bool(row.alerts_snoozed),
  4576. )
  4577. for row in sku_rows
  4578. }
  4579. if await self._get_bool_setting(db, "spoolman_enabled"):
  4580. spools = await self._stock_spools_spoolman()
  4581. if spools is None:
  4582. return None
  4583. # Spoolman owns the usage in this mode and Bambuddy's own history
  4584. # table holds nothing for those spools, so the rate is always the
  4585. # delta rate. Bambuddy's table is deliberately not consulted: its ids
  4586. # are local spool ids, and a Spoolman id that happens to match one
  4587. # (left over from before Spoolman was switched on) would borrow an
  4588. # unrelated spool's history.
  4589. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4590. else:
  4591. spools = await self._stock_spools_internal(db)
  4592. history = await self._stock_usage_history(db)
  4593. return stock_forecast.forecast_all(spools, history, sku_settings, global_lead_time, utcnow_naive())
  4594. async def _stock_spools_internal(self, db: AsyncSession) -> list[stock_forecast.StockSpool]:
  4595. from backend.app.models.spool import Spool
  4596. rows = (await db.execute(select(Spool).where(Spool.archived_at.is_(None)))).scalars().all()
  4597. return [
  4598. stock_forecast.StockSpool(
  4599. id=spool.id,
  4600. material=spool.material,
  4601. subtype=spool.subtype,
  4602. brand=spool.brand,
  4603. color_name=spool.color_name,
  4604. label_weight=float(spool.label_weight or 0),
  4605. weight_used=float(spool.weight_used or 0),
  4606. weight_used_baseline=float(spool.weight_used_baseline or 0),
  4607. created_at=spool.created_at,
  4608. )
  4609. for spool in rows
  4610. ]
  4611. async def _stock_usage_history(self, db: AsyncSession) -> dict[int, list[stock_forecast.UsageRecord]]:
  4612. from backend.app.models.spool_usage_history import SpoolUsageHistory
  4613. rows = (
  4614. await db.execute(
  4615. select(SpoolUsageHistory.spool_id, SpoolUsageHistory.created_at, SpoolUsageHistory.weight_used)
  4616. .order_by(SpoolUsageHistory.created_at.desc())
  4617. .limit(_STOCK_FORECAST_HISTORY_LIMIT)
  4618. )
  4619. ).all()
  4620. history: dict[int, list[stock_forecast.UsageRecord]] = {}
  4621. for spool_id, created_at, weight_used in rows:
  4622. if created_at is None:
  4623. continue
  4624. history.setdefault(spool_id, []).append(stock_forecast.UsageRecord(created_at, float(weight_used or 0)))
  4625. return history
  4626. async def _stock_spools_spoolman(self) -> list[stock_forecast.StockSpool] | None:
  4627. """Spoolman's spools in the forecast's shape, or None when Spoolman cannot be reached.
  4628. ``get_all_spools`` leaves archived spools out unless asked, which is the
  4629. exclusion the internal query applies explicitly. ``_map_spoolman_spool``
  4630. is the same mapping the Inventory page (and so the panel) reads.
  4631. """
  4632. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  4633. from backend.app.services.spoolman import SpoolmanUnavailableError, get_spoolman_client
  4634. client = await get_spoolman_client()
  4635. if client is None:
  4636. logger.debug("Stock forecast skipped, no Spoolman client (spoolman_enabled without a URL?)")
  4637. return None
  4638. try:
  4639. raw_spools = await client.get_all_spools()
  4640. except SpoolmanUnavailableError as e:
  4641. logger.debug("Stock forecast skipped, Spoolman unreachable: %s", e)
  4642. return None
  4643. spools: list[stock_forecast.StockSpool] = []
  4644. for raw in raw_spools:
  4645. try:
  4646. mapped = _map_spoolman_spool(raw)
  4647. except ValueError:
  4648. continue
  4649. created_at = None
  4650. if mapped.get("created_at"):
  4651. try:
  4652. created_at = datetime.fromisoformat(str(mapped["created_at"]).replace("Z", "+00:00"))
  4653. except ValueError:
  4654. created_at = None
  4655. spools.append(
  4656. stock_forecast.StockSpool(
  4657. id=mapped["id"],
  4658. material=mapped["material"],
  4659. subtype=mapped.get("subtype"),
  4660. brand=mapped.get("brand"),
  4661. color_name=mapped.get("color_name"),
  4662. label_weight=float(mapped.get("label_weight") or 0),
  4663. weight_used=float(mapped.get("weight_used") or 0),
  4664. weight_used_baseline=float(mapped.get("weight_used_baseline") or 0),
  4665. created_at=created_at,
  4666. color_name_is_synthesized=bool(mapped.get("color_name_is_synthesized")),
  4667. )
  4668. )
  4669. return spools
  4670. async def _emit_stock_alerts(
  4671. self,
  4672. db: AsyncSession,
  4673. forecasts: stock_forecast.ForecastMap,
  4674. wanted: dict[str, bool],
  4675. ) -> None:
  4676. """Send the notifications for each SKU that has moved into a stock alert condition.
  4677. A SKU in break has also reached its reorder point, so both events apply to
  4678. it: the break event goes to providers that have it on, and the reorder event
  4679. to the providers that have only that one on. A provider with both on gets the
  4680. break and no second message.
  4681. What is remembered per SKU is the condition and which events had a
  4682. subscriber when it was sent. An event with no subscriber is forgotten, so
  4683. switching it on later reports the SKUs already in that condition.
  4684. """
  4685. active_events = {event for event, on in wanted.items() if on}
  4686. for key, (forecast, spool) in forecasts.items():
  4687. kind: str | None = None
  4688. if not forecast.snoozed:
  4689. if forecast.stock_break_alert:
  4690. kind = "break"
  4691. elif forecast.reorder_alert:
  4692. kind = "reorder"
  4693. applicable = {"break": {"break", "reorder"}, "reorder": {"reorder"}}.get(kind or "", set())
  4694. events = applicable & active_events
  4695. if not events:
  4696. self._notified_stock_alerts.pop(key, None)
  4697. continue
  4698. previous = self._notified_stock_alerts.get(key)
  4699. told = (previous[1] & active_events) if previous else frozenset()
  4700. # Trimmed to the events this condition can send. That is what makes easing from
  4701. # break back to reorder silent (the reorder event was told with the break) and
  4702. # worsening again news again (the break event is no longer remembered).
  4703. self._notified_stock_alerts[key] = (kind, frozenset((told | events) & applicable))
  4704. # Recorded before sending, for the reason _emit_filament_low gives: a
  4705. # provider that is down should lose this alert, not repeat it every hour.
  4706. to_send = events - told
  4707. # Both flags imply a positive rate and so a day count.
  4708. days_left = forecast.days_remaining if forecast.days_remaining is not None else 0
  4709. rate = forecast.daily_rate_g if forecast.daily_rate_g is not None else 0.0
  4710. color = None if spool.color_name_is_synthesized else spool.color_name
  4711. try:
  4712. if "break" in to_send:
  4713. await notification_service.on_stock_break_alert(
  4714. spool.material,
  4715. spool.brand,
  4716. forecast.remaining_g,
  4717. rate,
  4718. days_left,
  4719. forecast.effective_lead_time_days,
  4720. db,
  4721. subtype=spool.subtype,
  4722. color=color,
  4723. )
  4724. if "reorder" in to_send:
  4725. await notification_service.on_stock_reorder_alert(
  4726. spool.material,
  4727. spool.brand,
  4728. forecast.remaining_g,
  4729. rate,
  4730. days_left,
  4731. db,
  4732. subtype=spool.subtype,
  4733. color=color,
  4734. skip_break_subscribers=kind == "break",
  4735. )
  4736. except Exception as e:
  4737. logger.warning("Stock %s notification failed for %s: %s", kind, key, e)
  4738. # A SKU with no spools left is no longer alerting.
  4739. for key in [k for k in self._notified_stock_alerts if k not in forecasts]:
  4740. del self._notified_stock_alerts[key]
  4741. async def _check_auto_drying(
  4742. self,
  4743. db: AsyncSession,
  4744. queue_items: list[PrintQueueItem],
  4745. dispatching_printers: set[int],
  4746. ):
  4747. """Start drying on idle printers based on humidity.
  4748. Three modes (can all be enabled independently):
  4749. - queue_drying_enabled: Dry between scheduled queue prints
  4750. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  4751. - print_drying_enabled: Also evaluate printers that are currently printing,
  4752. when model+firmware supports "Print While Drying" (gated by
  4753. supports_drying_while_printing). Drying temperature is capped at
  4754. max(40, preset_temp - 5) to protect spools mid-print.
  4755. """
  4756. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  4757. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  4758. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  4759. sustained_minutes = await self._get_int_setting(db, "ambient_drying_sustained_minutes", default=0)
  4760. # The wait belongs to ambient drying: the settings UI only shows it while
  4761. # ambient drying is on, so a value left behind when ambient is turned off
  4762. # must not keep delaying the one path that still reaches the wait gate
  4763. # without it (a mid-print start under print_drying).
  4764. sustained_wait_active = sustained_minutes > 0 and ambient_drying_enabled
  4765. # Clear every streak as soon as the wait is inactive. An early return (or
  4766. # an already-drying unit) may otherwise skip the per-unit cleanup and let
  4767. # a quick toggle-on inherit an old streak.
  4768. if not sustained_wait_active:
  4769. self._auto_dry_above.clear()
  4770. if not queue_drying_enabled and not ambient_drying_enabled:
  4771. # Stop active drying on all printers if both features disabled
  4772. if self._drying_in_progress:
  4773. for pid in list(self._drying_in_progress):
  4774. if pid in self._scheduled_drying_printer_ids:
  4775. continue
  4776. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  4777. await self._stop_drying(pid)
  4778. return
  4779. # Update drying state from printer status (handles backend restart)
  4780. self._sync_drying_state()
  4781. # Find printers with scheduled items (for queue drying mode)
  4782. printers_with_scheduled: set[int] = set()
  4783. printers_with_items: set[int] = set()
  4784. for item in queue_items:
  4785. if item.printer_id:
  4786. printers_with_items.add(item.printer_id)
  4787. if item.scheduled_time and not item.manual_start:
  4788. printers_with_scheduled.add(item.printer_id)
  4789. # If only queue mode is on and no printers have scheduled items, stop drying
  4790. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  4791. # may still be eligible for mid-print drying regardless of queue state).
  4792. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  4793. for pid in list(self._drying_in_progress):
  4794. if pid in self._scheduled_drying_printer_ids:
  4795. continue
  4796. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  4797. await self._stop_drying(pid)
  4798. return
  4799. # Get humidity threshold (global fallback)
  4800. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  4801. setting = result.scalar_one_or_none()
  4802. global_humidity_threshold = int(setting.value) if setting else 60
  4803. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  4804. # to the global threshold for every AMS unit.
  4805. per_type_thresholds = await self._get_humidity_thresholds(db)
  4806. # Get drying presets
  4807. presets = await self._get_drying_presets(db)
  4808. # Determine if drying should be skipped for printers with pending items
  4809. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  4810. # Get all active printers
  4811. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  4812. for printer in all_printers.scalars():
  4813. pid = printer.id
  4814. # Resolve model+firmware up front — needed to decide whether this printer
  4815. # qualifies for mid-print drying (busy printer on capable hardware).
  4816. state = printer_manager.get_status(pid)
  4817. if not state:
  4818. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  4819. continue
  4820. model = printer_manager.get_model(pid)
  4821. firmware = state.firmware_version
  4822. # "Mid-print" has to mean the printer is actually printing (#2801).
  4823. # It used to be inferred from the dispatch set, which also holds
  4824. # printers that merely could not be dispatched to -- so a printer
  4825. # sitting in FINISH behind an unacknowledged plate was treated as
  4826. # printing, had its drying temperature capped by the mid-print
  4827. # spool protection, and was logged as (mid-print) while idle.
  4828. is_printing = state.state in _ACTIVE_PRINT_STATES
  4829. mid_print = is_printing and print_drying_enabled and supports_drying_while_printing(model, firmware)
  4830. # A printer whose print is running or imminent is left alone unless
  4831. # it can dry through it. `dispatching_printers` is deliberately the
  4832. # narrow set: running, held post-dispatch, or mid-upload.
  4833. if (is_printing or pid in dispatching_printers) and not mid_print:
  4834. logger.debug("Auto-drying: printer %d skipped — printing or about to", pid)
  4835. continue
  4836. if not mid_print:
  4837. # In queue-only mode, only dry printers that have scheduled prints
  4838. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  4839. if self._drying_in_progress.get(pid) and pid not in self._scheduled_drying_printer_ids:
  4840. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  4841. await self._stop_drying(pid)
  4842. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  4843. continue
  4844. # When block mode is on, don't START new drying on printers with pending items.
  4845. # But allow already-drying printers through so humidity auto-stop logic still runs.
  4846. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  4847. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  4848. continue
  4849. if not printer_manager.is_connected(pid):
  4850. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  4851. continue
  4852. # Plate-clear is deliberately ignored here (#2801). It answers
  4853. # "is the bed ready for the next job", which says nothing about
  4854. # whether the AMS may heat -- and the gap between a finished print
  4855. # and the acknowledgment is exactly when drying is most useful,
  4856. # because the printer is free and nobody is waiting on it. Leaving
  4857. # the plate unacknowledged is also how people hold the queue by
  4858. # hand, and that hold should not cost them their drying.
  4859. if not mid_print and not self._is_printer_idle(pid, require_plate_clear=False):
  4860. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  4861. continue
  4862. # Check drying capability. For mid-print path, supports_drying_while_printing
  4863. # was already verified when computing mid_print above.
  4864. if not mid_print and not supports_drying(model, firmware):
  4865. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  4866. continue
  4867. # Check each AMS unit from raw_data
  4868. ams_list = state.raw_data.get("ams", [])
  4869. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  4870. for ams_data in ams_list:
  4871. module_type = str(ams_data.get("module_type") or "")
  4872. ams_id = int(ams_data.get("id", 0))
  4873. # Only n3f/n3s support drying
  4874. if module_type not in ("n3f", "n3s"):
  4875. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  4876. continue
  4877. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  4878. # Most-restrictive of all loaded tray types; falls back to the
  4879. # global threshold when no overrides are configured.
  4880. trays = ams_data.get("tray", []) or []
  4881. humidity_threshold = self.resolve_humidity_threshold(
  4882. trays, per_type_thresholds, global_humidity_threshold
  4883. )
  4884. dry_time = int(ams_data.get("dry_time") or 0)
  4885. # Read humidity as a percentage. The 1-5 index is never
  4886. # substituted: it is inverted, and being unable to exceed any
  4887. # threshold it would read as "dry" forever (#3140). ``None``
  4888. # already means "skip this unit" everywhere below.
  4889. humidity_pct = ams_humidity_percent(ams_data)
  4890. humidity = int(round(humidity_pct)) if humidity_pct is not None else None
  4891. unit_key = (pid, ams_id)
  4892. unit_state = self._auto_dry_units.get(unit_key)
  4893. # Already drying — let it run to its configured duration (#1892).
  4894. #
  4895. # We deliberately do NOT stop drying from a humidity re-check here.
  4896. # Relative humidity drops steeply in heated air, so the AMS sensor
  4897. # reads ~15-20% within minutes of the dryer starting even while the
  4898. # filament is still saturated. A humidity-based early-stop therefore
  4899. # always fires at the minimum-time floor, truncating both user-started
  4900. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  4901. # The firmware stops when the configured duration elapses; scheduling
  4902. # stops (print takes priority, queue no longer needs drying) are
  4903. # handled separately via _stop_drying().
  4904. if dry_time > 0:
  4905. if pid not in self._drying_in_progress:
  4906. # Drying we didn't start (manual or from before restart) —
  4907. # track it so scheduling stops still apply; never auto-stop it.
  4908. self._drying_in_progress[pid] = time.monotonic()
  4909. if unit_state is not None:
  4910. unit_state["running"] = True
  4911. logger.debug(
  4912. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  4913. pid,
  4914. ams_id,
  4915. dry_time,
  4916. humidity,
  4917. )
  4918. continue
  4919. # Nothing is drying. Close out a cycle we armed ourselves and
  4920. # judge whether it achieved anything (#2770).
  4921. #
  4922. # "Achieved anything" is measured against the LOWEST reading any
  4923. # cycle on this unit has ended at, not against the threshold and
  4924. # not against the previous cycle. A spool that is genuinely wet
  4925. # in a humid room comes down slowly — 40, 37, 35 — and must be
  4926. # allowed to keep going for as long as it is still coming down,
  4927. # however far it still is from the threshold. What must not
  4928. # continue is a cycle that ends exactly where the last one did,
  4929. # which is the reporter's signature: 15, 15, 16, 15, forever.
  4930. # Comparing against the running minimum rather than the previous
  4931. # end is what stops a sensor oscillating by one point between two
  4932. # values from reading as progress every other cycle.
  4933. if unit_state is not None and unit_state.pop("running", False):
  4934. unit_state["ended_at"] = time.monotonic()
  4935. # The streak that armed this cycle is spent; the next one
  4936. # starts fresh (and accumulates through the re-arm cooldown
  4937. # below, so the wait overlaps the cooldown, never stacks on
  4938. # top of it).
  4939. self._auto_dry_above.pop(unit_key, None)
  4940. if humidity is not None and humidity > humidity_threshold:
  4941. best = unit_state.get("best_end_humidity")
  4942. if isinstance(best, int) and humidity < best:
  4943. # Still coming down. Keep going, however far the
  4944. # threshold still is.
  4945. unproductive = 0
  4946. else:
  4947. unproductive = int(unit_state.get("unproductive", 0)) + 1
  4948. if not isinstance(best, int) or humidity < best:
  4949. unit_state["best_end_humidity"] = humidity
  4950. unit_state["unproductive"] = unproductive
  4951. logger.info(
  4952. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  4953. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  4954. pid,
  4955. ams_id,
  4956. humidity,
  4957. humidity_threshold,
  4958. unit_state.get("best_end_humidity"),
  4959. unproductive,
  4960. )
  4961. # A cycle that ended at or below the threshold needs no
  4962. # counter reset here: the branch below drops the whole entry.
  4963. # Humidity below threshold — no need to start drying. This is
  4964. # also the only thing that lifts a suspension: the reading we
  4965. # gave up on has come down, so auto-drying works again and the
  4966. # unit goes back to having no history at all.
  4967. if humidity is None or humidity <= humidity_threshold:
  4968. if unit_state is not None and unit_state.get("suspended"):
  4969. logger.info(
  4970. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  4971. "threshold, resuming automatic drying",
  4972. pid,
  4973. ams_id,
  4974. humidity,
  4975. humidity_threshold,
  4976. )
  4977. # Clear the judgement, keep the clock (#2801). Dropping the
  4978. # whole entry also dropped `ended_at`, and with it the
  4979. # 30-minute cooldown -- so a reading that dips to the
  4980. # threshold as the AMS cools and comes back above it once
  4981. # warm wiped its own history and re-armed immediately. That
  4982. # oscillation is the very thing #2770's cooldown exists to
  4983. # ride out, and it is worst at exactly the margin that makes
  4984. # a unit dry repeatedly: a point or two above the threshold.
  4985. if unit_state is not None:
  4986. unit_state.pop("suspended", None)
  4987. unit_state.pop("unproductive", None)
  4988. unit_state.pop("best_end_humidity", None)
  4989. # A real below-threshold reading ends any sustained-wait
  4990. # streak (#2518) -- "continuously above" means exactly that.
  4991. # An absent reading (humidity is None) is no-information and
  4992. # leaves the streak alone; the observation-gap guard handles
  4993. # a prolonged sensor silence.
  4994. if humidity is not None:
  4995. _above = self._auto_dry_above.pop(unit_key, None)
  4996. if _above is not None and sustained_wait_active:
  4997. logger.info(
  4998. "Auto-drying: printer %d AMS %d — humidity fell back to %s%% after "
  4999. "%.0fs of the required %dm above the %d%% threshold; not drying",
  5000. pid,
  5001. ams_id,
  5002. humidity,
  5003. time.monotonic() - _above["since"],
  5004. sustained_minutes,
  5005. humidity_threshold,
  5006. )
  5007. logger.debug(
  5008. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  5009. pid,
  5010. ams_id,
  5011. humidity,
  5012. humidity_threshold,
  5013. )
  5014. continue
  5015. # Sustained-humidity streak (#2518): updated on every pass that
  5016. # observes the reading above the threshold, BEFORE the
  5017. # suspension/cooldown gates below -- a suspended or cooling-down
  5018. # unit still accumulates streak time, so the wait overlaps those
  5019. # gates instead of stacking after them. Inert when the feature
  5020. # is off: no entries are written, and an entry left over from a
  5021. # toggle-off is dropped so it cannot seed a stale streak later.
  5022. if sustained_wait_active:
  5023. _now = time.monotonic()
  5024. # Four missed scheduler passes, floored: a single slow pass
  5025. # must not void a streak, but the ceiling has to scale with
  5026. # the cadence or a slow loop silently restarts every streak.
  5027. _gap_ceiling = max(4 * self._check_interval, AUTO_DRY_SUSTAINED_GAP_FLOOR_SECONDS)
  5028. _above = self._auto_dry_above.get(unit_key)
  5029. if _above is None:
  5030. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5031. elif _now - _above["last"] > _gap_ceiling:
  5032. # Restart, and say so at the same level as the dip
  5033. # reset: a silent restart voids the streak invisibly,
  5034. # and a user who set a long wait and never gets a dry
  5035. # has no way to see why.
  5036. logger.info(
  5037. "Auto-drying: printer %d AMS %d — sustained-humidity streak restarted after a "
  5038. "%.0fs observation gap (ceiling %ds); the %dm wait starts over",
  5039. pid,
  5040. ams_id,
  5041. _now - _above["last"],
  5042. _gap_ceiling,
  5043. sustained_minutes,
  5044. )
  5045. self._auto_dry_above[unit_key] = {"since": _now, "last": _now}
  5046. else:
  5047. _above["last"] = _now
  5048. else:
  5049. self._auto_dry_above.pop(unit_key, None)
  5050. if unit_state is not None:
  5051. if unit_state.get("suspended"):
  5052. logger.debug(
  5053. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  5054. "above the %d%% threshold",
  5055. pid,
  5056. ams_id,
  5057. int(unit_state.get("unproductive", 0)),
  5058. humidity_threshold,
  5059. )
  5060. continue
  5061. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  5062. unit_state["suspended"] = True
  5063. logger.warning(
  5064. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  5065. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  5066. "higher while it is warm, so a threshold in that range can never be reached and "
  5067. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  5068. pid,
  5069. ams_id,
  5070. int(unit_state.get("unproductive", 0)),
  5071. humidity,
  5072. humidity_threshold,
  5073. )
  5074. await self._notify_auto_drying_suspended(
  5075. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  5076. )
  5077. continue
  5078. ended_at = unit_state.get("ended_at")
  5079. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  5080. logger.debug(
  5081. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  5082. "cycle before the humidity reading is worth acting on",
  5083. pid,
  5084. ams_id,
  5085. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  5086. )
  5087. continue
  5088. # Check cannot-dry reasons (power constraints etc.). Sits
  5089. # ahead of the sustained wait so a unit the firmware refuses
  5090. # to dry never logs a wait it was never going to cash in.
  5091. sf_reasons = ams_data.get("dry_sf_reason", [])
  5092. if sf_reasons:
  5093. logger.debug(
  5094. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  5095. pid,
  5096. ams_id,
  5097. sf_reasons,
  5098. )
  5099. continue
  5100. # Sustained-humidity wait (#2518): ambient-triggered starts
  5101. # wait; only a printer with a scheduled queue item pending
  5102. # keeps the instant behavior, because that drying has a real
  5103. # deadline. Mid-print is deliberately NOT exempt while ambient
  5104. # drying is on: a humidity start on a printer that happens to be
  5105. # printing is as vulnerable to a lid-open spike as one on an idle
  5106. # printer (proven live: a 2-point threshold crossing mid-print
  5107. # bought a parked 12h command). Inactive when ambient drying is
  5108. # off: print_drying then still starts mid-print cycles on its own
  5109. # (#1816, "regardless of queue state"), and those stay instant.
  5110. if sustained_wait_active and pid not in printers_with_scheduled:
  5111. _above = self._auto_dry_above.get(unit_key)
  5112. _waited = time.monotonic() - _above["since"] if _above else 0.0
  5113. if _waited < sustained_minutes * 60:
  5114. logger.debug(
  5115. "Auto-drying: printer %d AMS %d waiting — humidity %s%% above the %d%% "
  5116. "threshold for %.0fs of the required %dm",
  5117. pid,
  5118. ams_id,
  5119. humidity,
  5120. humidity_threshold,
  5121. _waited,
  5122. sustained_minutes,
  5123. )
  5124. continue
  5125. # Get conservative drying params for mixed filaments
  5126. params = self._get_conservative_drying_params(trays, module_type, presets)
  5127. if not params:
  5128. logger.debug(
  5129. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  5130. )
  5131. continue
  5132. temp, duration_hours, filament_type = params
  5133. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  5134. # "drying temperature must not exceed the filament's softening temperature"
  5135. # for Print While Drying). Floor at 40 degC — below that the dryer is
  5136. # ineffective and firmware will reject anyway.
  5137. if mid_print:
  5138. temp = max(40, temp - 5)
  5139. # Start drying
  5140. logger.info(
  5141. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  5142. "starting %s drying at %d°C for %dh%s",
  5143. pid,
  5144. ams_id,
  5145. humidity,
  5146. humidity_threshold,
  5147. filament_type,
  5148. temp,
  5149. duration_hours,
  5150. " (mid-print)" if mid_print else "",
  5151. )
  5152. success = printer_manager.send_drying_command(
  5153. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  5154. )
  5155. if success:
  5156. self._drying_in_progress[pid] = time.monotonic()
  5157. armed = self._auto_dry_units.setdefault(
  5158. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  5159. )
  5160. armed["running"] = True
  5161. async def _notify_auto_drying_suspended(
  5162. self,
  5163. db: AsyncSession,
  5164. printer: Printer,
  5165. ams_id: int,
  5166. humidity: int,
  5167. threshold: int,
  5168. cycles: int,
  5169. ) -> None:
  5170. """Tell the user auto-drying has given up on one AMS unit (#2770).
  5171. Fires once per suspension — the caller sets ``suspended`` before calling
  5172. and every later pass short-circuits on it — because the whole point is
  5173. that Bambuddy has stopped acting. Somebody whose printer sits in another
  5174. building needs that to reach them, and the hourly humidity alarm they
  5175. are already getting says the opposite of what happened here.
  5176. Never raises: a notification provider being down must not stop the
  5177. suspension itself from taking effect.
  5178. """
  5179. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  5180. try:
  5181. await notification_service.on_ams_drying_suspended(
  5182. printer.id,
  5183. printer.name,
  5184. ams_label,
  5185. float(humidity),
  5186. float(threshold),
  5187. cycles,
  5188. db,
  5189. )
  5190. except Exception as e:
  5191. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  5192. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  5193. """Stop judging the drying cycle currently on this AMS unit (#2770).
  5194. The unproductive-cycle counter exists to notice that *drying* is not
  5195. moving the humidity reading. A cycle that ended because somebody sent a
  5196. stop says nothing about that — it was cut short before it had a chance —
  5197. so counting it would suspend auto-drying for a reason that has nothing to
  5198. do with the loop the counter is there to break.
  5199. Two callers, both of them a stop Bambuddy is responsible for: the
  5200. print-takes-priority stop below, and the manual Stop button. Left
  5201. uncalled, an install that dries between queue jobs would suspend its own
  5202. auto-drying after two prints interrupted a dry — exactly the install
  5203. queue-drying exists for.
  5204. The rest of the unit's history is kept: the cooldown before re-arming
  5205. still applies, and an earlier count still stands.
  5206. """
  5207. state = self._auto_dry_units.get((printer_id, ams_id))
  5208. if state is not None:
  5209. state.pop("running", None)
  5210. state["ended_at"] = time.monotonic()
  5211. # A stopped cycle spends the streak that armed it, same as a completed
  5212. # one (#2518).
  5213. self._auto_dry_above.pop((printer_id, ams_id), None)
  5214. def _sync_drying_state(self):
  5215. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  5216. One direction only: it prunes, it never adds. A printer drying without an
  5217. entry here — because the user started the cycle from Studio, the printer's
  5218. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  5219. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  5220. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  5221. That is deliberate for now rather than an oversight: populating this from
  5222. telemetry would hand the scheduler authority to stop drying a user started
  5223. by hand. It also means the backend-restart case this used to claim to
  5224. handle is not handled.
  5225. """
  5226. to_remove = []
  5227. for pid in self._drying_in_progress:
  5228. state = printer_manager.get_status(pid)
  5229. if not state:
  5230. to_remove.append(pid)
  5231. continue
  5232. # Check if any AMS unit is still drying
  5233. ams_list = state.raw_data.get("ams", [])
  5234. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  5235. if not any_drying:
  5236. to_remove.append(pid)
  5237. for pid in to_remove:
  5238. self._drying_in_progress.pop(pid, None)
  5239. # A printer that has gone away entirely takes its per-AMS auto-drying
  5240. # history with it (#2770), so a printer deleted and re-added does not
  5241. # inherit a suspension it never earned.
  5242. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  5243. self._auto_dry_units.pop(key, None)
  5244. # Same for sustained-wait streaks (#2518): a deleted-and-re-added
  5245. # printer starts a fresh wait, and vanished printers do not leak
  5246. # entries.
  5247. for key in [k for k in self._auto_dry_above if printer_manager.get_status(k[0]) is None]:
  5248. self._auto_dry_above.pop(key, None)
  5249. @staticmethod
  5250. def _drying_is_only_parked(printer_id: int) -> bool:
  5251. """True when every AMS unit with a drying timer on this printer is parked.
  5252. A parked timer (#2896: the command was taken but the countdown never
  5253. runs) does not end on its own, so nothing may wait on it. False when no
  5254. unit reports a timer yet -- a command just sent that the firmware has not
  5255. reported back is real drying about to begin.
  5256. """
  5257. state = printer_manager.get_status(printer_id)
  5258. units = [a for a in ((state.raw_data or {}).get("ams") or [] if state else []) if isinstance(a, dict)]
  5259. timed = []
  5260. for unit in units:
  5261. try:
  5262. if int(unit.get("dry_time") or 0) > 0:
  5263. timed.append(unit)
  5264. except (TypeError, ValueError):
  5265. continue
  5266. return bool(timed) and all(is_countdown_parked(unit) for unit in timed)
  5267. async def _drying_may_continue_through_print(self, db: AsyncSession, printer_id: int) -> bool:
  5268. """True when a running cycle can be left alone while the next print runs.
  5269. Some hardware dries happily through a print and #2758 settled that we
  5270. should not tear those cycles down: the X2D there was refusing to
  5271. *start* a job, which is a different problem, and stopping drying before
  5272. every dispatch would throw away cycles the printer was content to run.
  5273. Where the model cannot do it, or the user has not enabled it, the print
  5274. takes priority and the cycle stops -- which is what the queue_drying_block
  5275. setting has always promised in its off position.
  5276. """
  5277. if not await self._get_bool_setting(db, "print_drying_enabled"):
  5278. return False
  5279. status = printer_manager.get_status(printer_id)
  5280. return supports_drying_while_printing(
  5281. printer_manager.get_model(printer_id),
  5282. status.firmware_version if status else None,
  5283. )
  5284. async def _stop_drying(self, printer_id: int):
  5285. """Stop drying cycles Bambuddy armed on a printer (print takes priority).
  5286. Scoped to units in ``_auto_dry_units``. It used to send a stop to every
  5287. AMS reporting ``dry_time > 0``, which meant one auto-dried unit was
  5288. enough to kill a cycle the user had started by hand on a *different*
  5289. unit of the same printer (#2801). That contradicted the contract
  5290. ``_sync_drying_state`` already documents -- the entry gate deliberately
  5291. only knows about cycles Bambuddy began, so the action must not reach
  5292. past them either.
  5293. """
  5294. state = printer_manager.get_status(printer_id)
  5295. if not state:
  5296. self._drying_in_progress.pop(printer_id, None)
  5297. return
  5298. ams_list = state.raw_data.get("ams", [])
  5299. for ams_data in ams_list:
  5300. dry_time = int(ams_data.get("dry_time") or 0)
  5301. if dry_time > 0:
  5302. ams_id = int(ams_data.get("id", 0))
  5303. if (printer_id, ams_id) not in self._auto_dry_units:
  5304. logger.debug(
  5305. "Auto-drying: leaving printer %d AMS %d alone — not a cycle Bambuddy started",
  5306. printer_id,
  5307. ams_id,
  5308. )
  5309. continue
  5310. logger.info(
  5311. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  5312. printer_id,
  5313. ams_id,
  5314. )
  5315. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  5316. self.forget_auto_dry_cycle(printer_id, ams_id)
  5317. self._drying_in_progress.pop(printer_id, None)
  5318. # Scheduled manual drying (#2638) -----------------------------------
  5319. SCHEDULED_DRYING_GRACE_SECONDS = 120 # firmware needs time to report dry_time
  5320. SCHEDULED_DRYING_COMPLETE_FRACTION = 0.9 # dry_time==0 earlier than this = interrupted
  5321. async def _check_scheduled_dryings(self, db: AsyncSession):
  5322. """Dispatch due scheduled drying runs and track running ones."""
  5323. now = utcnow_naive()
  5324. # Hourly, not every pass: see SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS.
  5325. # Monotonic, so a clock adjustment cannot park the prune for hours.
  5326. since_prune = time.monotonic()
  5327. if (
  5328. self._last_scheduled_drying_prune is None
  5329. or since_prune - self._last_scheduled_drying_prune >= SCHEDULED_DRYING_PRUNE_INTERVAL_SECONDS
  5330. ):
  5331. self._last_scheduled_drying_prune = since_prune
  5332. await db.execute(
  5333. delete(ScheduledDrying).where(
  5334. ScheduledDrying.status.in_(("completed", "cancelled", "failed")),
  5335. ScheduledDrying.completed_at.is_not(None),
  5336. ScheduledDrying.completed_at < now - timedelta(days=SCHEDULED_DRYING_RETENTION_DAYS),
  5337. )
  5338. )
  5339. # Same order as the list route: with two rows due on one printer the
  5340. # earliest scheduled wins rather than whatever the DB hands back first.
  5341. result = await db.execute(
  5342. select(ScheduledDrying)
  5343. .where(ScheduledDrying.status.in_(("pending", "running")))
  5344. .order_by(ScheduledDrying.start_after.asc().nullsfirst(), ScheduledDrying.id.asc())
  5345. )
  5346. rows = list(result.scalars().all())
  5347. # Rebuild from the DB every tick so route-side cancels and completions
  5348. # show up. Auto-drying's stop-all branches check this set before
  5349. # stopping anything (#2638).
  5350. # Kept from the previous pass so a run that ended between passes — a
  5351. # cancel through the route, say — can still be released below.
  5352. previously_running = self._scheduled_drying_printer_ids
  5353. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5354. running_printer_ids = set(self._scheduled_drying_printer_ids)
  5355. # Model and firmware come from the printer row, not the live state.
  5356. printer_ids = {row.printer_id for row in rows}
  5357. printers_by_id: dict[int, Printer] = {}
  5358. if printer_ids:
  5359. printer_rows = await db.execute(select(Printer).where(Printer.id.in_(printer_ids)))
  5360. printers_by_id = {p.id: p for p in printer_rows.scalars()}
  5361. for row in rows:
  5362. if row.status == "running":
  5363. self._update_running_scheduled_drying(row, now)
  5364. continue
  5365. if row.start_after is not None and row.start_after > now:
  5366. continue
  5367. state = printer_manager.get_status(row.printer_id)
  5368. if not state:
  5369. row.waiting_reason = "printer_offline"
  5370. continue
  5371. # Same preflight the immediate endpoint runs. Without it the publish
  5372. # succeeds, the row goes to running, the printer ignores the command
  5373. # and the run silently cancels itself after the grace window.
  5374. printer = printers_by_id.get(row.printer_id)
  5375. unsupported = drying_preflight.check_drying_supported(
  5376. printer.model if printer else None, state.firmware_version
  5377. )
  5378. if unsupported:
  5379. row.status = "failed"
  5380. row.error_message = unsupported
  5381. row.error_code = drying_preflight.DETAIL_CODES.get(unsupported)
  5382. row.completed_at = now
  5383. logger.warning("Scheduled drying %d: %s", row.id, unsupported)
  5384. continue
  5385. if (
  5386. self._drying_in_progress.get(row.printer_id) and not self._drying_is_only_parked(row.printer_id)
  5387. ) or row.printer_id in running_printer_ids:
  5388. row.waiting_reason = "already_drying"
  5389. continue
  5390. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5391. row.waiting_reason = "printer_busy"
  5392. continue
  5393. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5394. if target is None:
  5395. row.waiting_reason = "ams_not_found"
  5396. continue
  5397. blocking = drying_preflight.blocking_reason_codes(target)
  5398. if blocking:
  5399. # Keep the power case distinct; it needs the user to act, so the
  5400. # card can say so instead of waiting silently.
  5401. row.waiting_reason = drying_preflight.waiting_reason_for_codes(blocking)
  5402. continue
  5403. filament = drying_preflight.resolve_filament(target, row.filament)
  5404. logger.info(
  5405. "Scheduled drying %d: starting on printer %d AMS %d at %d°C for %dh",
  5406. row.id,
  5407. row.printer_id,
  5408. row.ams_id,
  5409. row.temp,
  5410. row.duration_hours,
  5411. )
  5412. success = printer_manager.send_drying_command(
  5413. row.printer_id,
  5414. row.ams_id,
  5415. row.temp,
  5416. row.duration_hours,
  5417. mode=1,
  5418. filament=filament,
  5419. rotate_tray=row.rotate_tray,
  5420. )
  5421. if success:
  5422. row.status = "running"
  5423. row.started_at = now
  5424. row.waiting_reason = None
  5425. row.filament = filament
  5426. self._drying_in_progress[row.printer_id] = time.monotonic()
  5427. self._scheduled_drying_printer_ids.add(row.printer_id)
  5428. running_printer_ids.add(row.printer_id)
  5429. else:
  5430. row.waiting_reason = "printer_offline"
  5431. # Release the printers whose run has ended. `_drying_in_progress` is
  5432. # shared with auto-drying, which prunes it in `_sync_drying_state()` —
  5433. # but that call sits behind the auto-drying enabled check, and this
  5434. # method is the one writer that runs whether auto-drying is on or not.
  5435. # With it off, nothing would ever drop the entry short of a print being
  5436. # dispatched to the same printer, so the next scheduled run would wait
  5437. # on "already_drying" forever and `queue_drying_block` would hold the
  5438. # printer's prints too. Covers a run that ended during this pass and one
  5439. # cancelled through the route between passes.
  5440. self._scheduled_drying_printer_ids = {row.printer_id for row in rows if row.status == "running"}
  5441. for printer_id in (previously_running | running_printer_ids) - self._scheduled_drying_printer_ids:
  5442. self._drying_in_progress.pop(printer_id, None)
  5443. await db.commit()
  5444. def _update_running_scheduled_drying(self, row: ScheduledDrying, now: datetime):
  5445. """Detect completion or interruption of a running scheduled drying.
  5446. The firmware reports remaining minutes in ams.dry_time; 0 means not
  5447. drying. Within the grace window after start we ignore dry_time==0
  5448. (the status lags the command). After that, dry_time==0 near the end
  5449. of the configured duration means completed. Much earlier means the
  5450. run was stopped: re-queue it if a print preempted the dryer, but a
  5451. stop while the printer is idle was deliberate, so cancel the row
  5452. rather than restart drying the user just stopped.
  5453. """
  5454. if row.started_at is None:
  5455. row.started_at = now
  5456. return
  5457. elapsed = (now - row.started_at).total_seconds()
  5458. if elapsed < self.SCHEDULED_DRYING_GRACE_SECONDS:
  5459. return
  5460. state = printer_manager.get_status(row.printer_id)
  5461. if not state:
  5462. return # offline mid-dry; resolve when it reconnects
  5463. # find_ams_unit, not a local lookup: this runs inside check_queue, so a
  5464. # throw on a malformed id would cost the whole pass including print
  5465. # dispatch, every tick.
  5466. target = drying_preflight.find_ams_unit(state, row.ams_id)
  5467. try:
  5468. dry_time = int(target.get("dry_time") or 0) if target else 0
  5469. except (TypeError, ValueError):
  5470. dry_time = 0
  5471. if dry_time > 0 and is_countdown_parked(target):
  5472. # The printer took the command but the countdown is not running
  5473. # (#2896) and will never reach 0, so the run would stay "running"
  5474. # forever. A print in progress is the likely cause (the power budget
  5475. # is spent), so re-queue it like any interruption; the next start
  5476. # waits for the printer to be idle. Parked on an idle printer is a
  5477. # refusal, not something a retry fixes. The timer itself is left on
  5478. # the printer: it may yet start once power frees up.
  5479. if not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5480. logger.info(
  5481. "Scheduled drying %d: AMS %d countdown is not running during a print; re-queued",
  5482. row.id,
  5483. row.ams_id,
  5484. )
  5485. row.status = "pending"
  5486. row.started_at = None
  5487. row.waiting_reason = "interrupted"
  5488. else:
  5489. logger.warning(
  5490. "Scheduled drying %d: printer accepted the command but AMS %d never started drying",
  5491. row.id,
  5492. row.ams_id,
  5493. )
  5494. row.status = "failed"
  5495. row.error_message = drying_preflight.DID_NOT_START_DETAIL
  5496. row.error_code = drying_preflight.DETAIL_CODES[drying_preflight.DID_NOT_START_DETAIL]
  5497. row.completed_at = now
  5498. return
  5499. if dry_time > 0:
  5500. return
  5501. if elapsed >= row.duration_hours * 3600 * self.SCHEDULED_DRYING_COMPLETE_FRACTION:
  5502. row.status = "completed"
  5503. row.completed_at = now
  5504. elif not self._is_printer_idle(row.printer_id, require_plate_clear=False):
  5505. row.status = "pending"
  5506. row.started_at = None
  5507. row.waiting_reason = "interrupted"
  5508. else:
  5509. row.status = "cancelled"
  5510. row.completed_at = now
  5511. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  5512. """Get all smart plugs associated with a printer."""
  5513. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  5514. return list(result.scalars().all())
  5515. @staticmethod
  5516. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  5517. """Pick the plug to power-cycle a printer back online with (#2629).
  5518. Only a plug flagged ``controls_printer_power`` can actually bring the
  5519. printer back; waiting for a boot on an accessory (filter fan, lights)
  5520. just burns the power-on timeout and fails the dispatch. Falls back to
  5521. the first plug when none is flagged, which is the pre-#2629 behaviour.
  5522. Callers must pass a non-empty list.
  5523. """
  5524. for plug in auto_on_plugs:
  5525. if plug.controls_printer_power:
  5526. return plug
  5527. return auto_on_plugs[0]
  5528. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  5529. # chamber-temperature recommendations BambuStudio ships for the matching
  5530. # filament profile; users can override via Settings → Workflow → Preheat
  5531. # card. "default" applies when a loaded tray's normalised type isn't in
  5532. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  5533. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  5534. "PLA": 0,
  5535. "PETG": 0,
  5536. "PETG-CF": 40,
  5537. "ABS": 45,
  5538. "ASA": 45,
  5539. "PA": 50,
  5540. "PA-CF": 55,
  5541. "PC": 50,
  5542. "PC-FR": 50,
  5543. "TPU": 0,
  5544. "PVA": 0,
  5545. "default": 0,
  5546. }
  5547. @classmethod
  5548. def _bundled_preheat_targets(cls) -> dict[str, int]:
  5549. """The bundled map under the same key casing a parsed one gets.
  5550. The constant is declared with a lowercase ``default`` because that is
  5551. the key the Settings editor writes and displays. Every read of the map
  5552. happens after ``str(key).upper()``, so handing the constant back as
  5553. declared broke the contract the parser documents: an install that had
  5554. never touched the setting returned a dict with no ``DEFAULT`` in it,
  5555. and the resolution loop's fallback silently found nothing. It read the
  5556. right number only because the bundled default happens to be 0 -- change
  5557. that constant and every unconfigured install would keep preheating to
  5558. zero with no way to tell why.
  5559. """
  5560. return {key.upper(): value for key, value in cls.DEFAULT_PREHEAT_FILAMENT_TARGETS.items()}
  5561. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  5562. """Parse the user-configured filament→chamber-target map, falling back
  5563. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  5564. are uppercased and the 'default' fallback is always present in the
  5565. returned dict so the resolution loop can index it unconditionally."""
  5566. raw = await self._get_setting(db, "preheat_filament_targets")
  5567. if not raw:
  5568. return self._bundled_preheat_targets()
  5569. try:
  5570. parsed = json.loads(raw)
  5571. if not isinstance(parsed, dict):
  5572. raise ValueError("not an object")
  5573. except (json.JSONDecodeError, ValueError) as exc:
  5574. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  5575. return self._bundled_preheat_targets()
  5576. # Coerce values to int; drop unparseable rows so a stray string
  5577. # doesn't crash the loop.
  5578. out: dict[str, int] = {}
  5579. for key, value in parsed.items():
  5580. try:
  5581. out[str(key).upper()] = int(value)
  5582. except (TypeError, ValueError):
  5583. continue
  5584. if "DEFAULT" not in out:
  5585. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  5586. return out
  5587. @staticmethod
  5588. def _normalize_filament_type(tray_type: str) -> str:
  5589. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  5590. existing drying-preset normalisation (split-at-space, upper-case) so
  5591. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  5592. "PA-CF" (no space to split on).
  5593. This is the first stage of ``_resolve_filament_key``, which goes on to
  5594. drop the suffix and consult the alias map; on its own it only decides
  5595. what the tray is called, not which row answers for it.
  5596. Indexing the split rather than testing the input: a tray_type of spaces
  5597. is truthy and splits to nothing, so the old ``if tray_type`` guard let
  5598. it through to an IndexError.
  5599. """
  5600. words = (tray_type or "").split()
  5601. return words[0].upper() if words else ""
  5602. def _target_for_tray_type(self, tray_type: str | None, targets: dict[str, int]) -> int:
  5603. """Per-filament chamber target for one tray's reported type, or 0 when
  5604. the tray is empty / RFID-less and reports no type at all.
  5605. A filled or foamed variant wants its base material's chamber when the
  5606. map has no row of its own: ASA-GF is ASA and needs ASA's 45 degrees,
  5607. not the 0 an unknown type falls to. The specific type is still tried
  5608. first, so PETG-CF and PA-CF keep the hotter rows they are listed with
  5609. (#2902).
  5610. That lookup is now the shared one, which adds the polyamide aliases on
  5611. top of the suffix it already dropped -- so PA6-CF reaches PA's row here
  5612. too, rather than the catch-all it was landing on (#3067).
  5613. """
  5614. if not self._normalize_filament_type(tray_type or ""):
  5615. return 0
  5616. key = self._resolve_filament_key(tray_type, targets)
  5617. if key is not None:
  5618. return targets[key]
  5619. # A type the map does not list at all, which is not the same as a tray
  5620. # with nothing in it -- that already returned 0 above.
  5621. return targets.get("DEFAULT", 0)
  5622. def _derive_chamber_target(
  5623. self,
  5624. printer: Printer,
  5625. targets: dict[str, int],
  5626. item: PrintQueueItem | None = None,
  5627. ) -> int:
  5628. """Chamber target for the trays this print actually loads: the max of
  5629. their per-filament targets. Returns 0 when there is nothing to read (no
  5630. status, no AMS telemetry — e.g. external-spool prints) or when every
  5631. tray considered maps to 0, and the chamber phase then short-circuits in
  5632. the main loop.
  5633. ``item`` narrows the scan to the trays named in its ``ams_mapping``.
  5634. Scanning the whole unit instead meant one ASA spool parked in the AMS
  5635. forced a 45°C chamber onto every PLA job sharing it — the full max-wait
  5636. plus soak burned ahead of each upload, on a printer whose chamber never
  5637. reaches the target anyway (#2886). An item with no usable mapping falls
  5638. back to scanning every loaded tray: that is the only signal left, and
  5639. narrowing to nothing would skip preheat on prints that genuinely need
  5640. it.
  5641. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  5642. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  5643. less slots have empty `tray_type` and contribute nothing. The external
  5644. spool is consulted only when the mapping names it (>= 254); it stays
  5645. out of the unnarrowed scan, so an item without a mapping derives from
  5646. the AMS alone exactly as before.
  5647. """
  5648. state = printer_manager.get_status(printer.id)
  5649. if state is None:
  5650. return 0
  5651. raw_data = state.raw_data or {}
  5652. used = _used_global_tray_ids(item)
  5653. ams_list = raw_data.get("ams")
  5654. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  5655. if isinstance(ams_list, dict):
  5656. ams_list = ams_list.get("ams") or []
  5657. if not isinstance(ams_list, list):
  5658. ams_list = []
  5659. best = 0
  5660. for ams in ams_list:
  5661. if not isinstance(ams, dict):
  5662. continue
  5663. ams_id = _int_or(ams.get("id"), 0)
  5664. for tray in ams.get("tray") or []:
  5665. # A non-dict entry has never been seen from real firmware, but
  5666. # `.get` on one raises, and nothing between here and
  5667. # `_dispatch_one`'s try/finally catches it — the item would be
  5668. # left holding its dispatch claim. Preheat is best-effort by
  5669. # contract, so step over it instead.
  5670. if not isinstance(tray, dict):
  5671. continue
  5672. if used is not None and _global_tray_id(ams_id, _int_or(tray.get("id"), 0)) not in used:
  5673. continue
  5674. best = max(best, self._target_for_tray_type(tray.get("tray_type"), targets))
  5675. if used is not None and any(t >= _EXTERNAL_TRAY_ID_MIN for t in used):
  5676. for vt in raw_data.get("vt_tray") or []:
  5677. if not isinstance(vt, dict):
  5678. continue
  5679. # `_build_loaded_filaments` addresses external feeds by the id
  5680. # the firmware reports — 255 main, 254 deputy — defaulting to
  5681. # 254 when the field is absent. Same expression here so the two
  5682. # agree on which entry a mapping's 254/255 refers to.
  5683. if _int_or(vt.get("id"), _EXTERNAL_TRAY_ID_MIN) not in used:
  5684. continue
  5685. best = max(best, self._target_for_tray_type(vt.get("tray_type"), targets))
  5686. return best
  5687. def _release_keep_warm(self, pid: int) -> None:
  5688. """Release keep-warm on a printer that left the candidate set.
  5689. Publishes ``set_bed_temperature(0)`` once — but only if firmware still
  5690. reports the target we set (``entry.held_target``), so a user or
  5691. subsequent print that changed the bed target since is not clobbered.
  5692. Best-effort, never raises.
  5693. The entry is kept, not dropped, when the printer cannot be reached
  5694. right now: a printer that is briefly offline still has a hot bed, and
  5695. holding the entry is what keeps the max-duration timeout applying and
  5696. lets a later tick retry the release. Only a printer that has left the
  5697. manager entirely gives up on that, in ``_sample_chamber_temps``.
  5698. """
  5699. entry = self._keep_warm.get(pid)
  5700. if entry is None:
  5701. return
  5702. state = printer_manager.get_status(pid)
  5703. client = printer_manager.get_client(pid)
  5704. if state is None or client is None:
  5705. logger.debug(
  5706. "Queue: keep-warm release for printer %d deferred — printer unreachable, entry kept",
  5707. pid,
  5708. )
  5709. return
  5710. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  5711. if int(cur_bed_target) != entry.held_target:
  5712. # Someone else owns the bed now, so there is nothing of ours to
  5713. # undo and nothing left to track.
  5714. logger.info(
  5715. "Queue: keep-warm release for printer %d skipped bed-off (firmware target %d != held %d)",
  5716. pid,
  5717. int(cur_bed_target),
  5718. entry.held_target,
  5719. )
  5720. self._keep_warm.pop(pid, None)
  5721. return
  5722. try:
  5723. client.set_bed_temperature(0)
  5724. logger.info("Queue: keep-warm released for printer %d (bed → 0)", pid)
  5725. self._keep_warm.pop(pid, None)
  5726. except Exception as exc:
  5727. # Keep the entry so the next tick tries again rather than leaving
  5728. # the bed hot with nothing tracking it.
  5729. logger.warning("Queue: keep-warm release for printer %d failed: %s", pid, exc)
  5730. def _sweep_keep_warm(self, active_candidates: set[int], dispatched: set[int]) -> None:
  5731. """Release printers that dropped out of the keep-warm candidate set.
  5732. Called from ``_apply_keep_warm`` on every tick (with the current
  5733. candidate set), and from ``check_queue``'s no-pending-items early
  5734. return (with an empty candidate set) so orphaned holds still get
  5735. released when the queue empties. Also called with an empty candidate
  5736. set when any of the three gate settings toggles off, so a printer
  5737. whose feature was disabled mid-hold gets its bed released.
  5738. Printers being dispatched this tick are excluded from the bed-off
  5739. publish: ``_preheat_and_soak`` owns the bed from that tick on, so a
  5740. transient 0 in between would just churn against preheat. Ownership of
  5741. the hot bed transfers to the preheat rollback pin instead — if the
  5742. dispatch aborts before the print starts (failed upload, cancelled
  5743. item), `_rollback_preheat_pin` turns the bed off; if preheat itself
  5744. skips (e.g. the item has no bed_temperature metadata) the pin entry
  5745. is the ONLY thing standing between an aborted dispatch and a bed
  5746. left hot with no owner. A successful print start clears the pin and
  5747. the print's own gcode takes over, as usual.
  5748. """
  5749. for _pid in list(self._keep_warm):
  5750. if _pid in active_candidates:
  5751. continue
  5752. if _pid in dispatched:
  5753. handed_over = self._keep_warm.pop(_pid, None)
  5754. self._preheat_pin.setdefault(_pid, set()).add("bed")
  5755. if handed_over is not None:
  5756. self._preheat_pin_bed[_pid] = handed_over.held_target
  5757. continue
  5758. self._release_keep_warm(_pid)
  5759. async def _apply_keep_warm(
  5760. self,
  5761. db: AsyncSession,
  5762. items: list[PrintQueueItem],
  5763. dispatch_ids: list[int] | set[int],
  5764. busy_printers: set[int],
  5765. require_plate_clear: bool,
  5766. ) -> None:
  5767. """Hold the bed warm on FINISH printers whose next queued item needs chamber heat.
  5768. When a printer just finished a job (FINISH state) and the next queued
  5769. item needs chamber heating, hold the bed hot so the chamber stays warm
  5770. during the bed-clearing window. The bed is the chamber's heating
  5771. element here, not a print surface — nothing is printing during the
  5772. hold and the dispatched print's own preheat/gcode re-targets the bed —
  5773. so the hold temperature is ``queue_keep_warm_bed_temp`` (default 90°C,
  5774. chosen to sustain chamber warmth and to satisfy bed-threshold-linked
  5775. aftermarket chamber heaters), raised to the item's own parsed
  5776. bed_temperature when that is higher. Items whose archive metadata has
  5777. no bed temperature (e.g. OrcaSlicer gcode.3mf exports) therefore still
  5778. get a hold — chamber need is what gates the feature, not metadata.
  5779. Skips entirely for filaments that map to a 0°C chamber target
  5780. (PLA, PETG, etc.) — read off the trays the next item's ``ams_mapping``
  5781. names, so a hot-chamber spool it never touches does not hold the bed of
  5782. a PLA job (#2886). An item still awaiting its mapping is judged on the
  5783. whole unit, as every item was before. Printers being dispatched this
  5784. cycle are excluded:
  5785. ``_preheat_and_soak`` already handles their bed temperature.
  5786. Bounded by ``queue_keep_warm_max_minutes`` — on timeout the bed is
  5787. released to 0 and the entry is latched ``expired=True`` so
  5788. subsequent ticks neither re-engage nor re-seed the clock. Idempotent
  5789. MQTT: publish is skipped when firmware already has the target.
  5790. The release sweep runs BEFORE the engagement gate so a printer that
  5791. was owned by keep-warm still gets its bed released when any of the
  5792. three gate settings is toggled off mid-hold. The
  5793. ``check_queue`` early-return-when-no-items path also calls
  5794. ``_sweep_keep_warm`` directly to release orphaned holds.
  5795. """
  5796. dispatch_set = set(dispatch_ids)
  5797. dispatched_printers = {it.printer_id for it in items if it.id in dispatch_set and it.printer_id}
  5798. pending_printer_ids = {it.printer_id for it in items if it.printer_id}
  5799. warm_candidates = (pending_printer_ids & busy_printers) - dispatched_printers
  5800. keep_warm_enabled = await self._get_bool_setting(db, "queue_keep_bed_warm", default=False)
  5801. preheat_on = await self._get_bool_setting(db, "preheat_enabled", default=False)
  5802. gate_open = keep_warm_enabled and require_plate_clear and preheat_on
  5803. # Release sweep first — must run even when gate_open is False so a
  5804. # printer owned by keep-warm when a gate toggles off gets released.
  5805. self._sweep_keep_warm(
  5806. active_candidates=warm_candidates if gate_open else set(),
  5807. dispatched=dispatched_printers,
  5808. )
  5809. if not gate_open:
  5810. return
  5811. hold_temp = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  5812. max_hold_seconds = (
  5813. await self._get_int_setting(db, "queue_keep_warm_max_minutes", default=_KEEP_WARM_MAX_MINUTES_DEFAULT) * 60
  5814. )
  5815. now_mono = time.monotonic()
  5816. filament_targets: dict[str, int] | None = None
  5817. for pid in warm_candidates:
  5818. entry = self._keep_warm.get(pid)
  5819. # Latched-expired: max-duration timeout already fired for this
  5820. # printer. Skip until the release sweep drops the entry (i.e.
  5821. # until the printer leaves the candidate set).
  5822. if entry is not None and entry.expired:
  5823. continue
  5824. # These two guards sit ahead of the max-duration check below, so an
  5825. # engaged hold only ages out while its printer is still reachable
  5826. # and still in FINISH. That is deliberate rather than a hole: with
  5827. # no status or no client there is no M140 to send anyway, and the
  5828. # elapsed check runs off `entry.started` so it fires on the first
  5829. # tick after the printer comes back. Leaving FINISH means the plate
  5830. # was cleared, which drops the printer out of `warm_candidates` and
  5831. # hands it to `_release_keep_warm` instead. The invariant worth
  5832. # preserving if this is ever reordered: every path out of an
  5833. # engaged hold ends in a bed-off, whether by timeout or release.
  5834. state = printer_manager.get_status(pid)
  5835. if state is None or state.state != "FINISH":
  5836. continue
  5837. client = printer_manager.get_client(pid)
  5838. if client is None:
  5839. continue
  5840. next_item = next((it for it in items if it.printer_id == pid), None)
  5841. if next_item is None:
  5842. continue
  5843. # Hold temperature: the configured keep-warm temp, raised to the
  5844. # item's own bed temp when the metadata reports a higher one. A
  5845. # missing bed_temperature (Orca gcode.3mf exports parse without
  5846. # one) does NOT skip the hold — chamber need gates the feature.
  5847. archive = next_item.archive
  5848. item_bed = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  5849. bed_target = max(item_bed, hold_temp)
  5850. if bed_target <= 0:
  5851. continue
  5852. explicit = getattr(next_item, "preheat_chamber_target_override", None)
  5853. if explicit is not None:
  5854. chamber_needed = int(explicit) > 0
  5855. else:
  5856. if filament_targets is None:
  5857. filament_targets = await self._get_preheat_filament_targets(db)
  5858. printer_obj = await self._get_printer(db, pid)
  5859. chamber_needed = (
  5860. printer_obj is not None
  5861. and self._derive_chamber_target(printer_obj, filament_targets, next_item) > 0
  5862. )
  5863. if not chamber_needed:
  5864. continue
  5865. # Seed the timer on first engagement; keep it on subsequent ticks
  5866. # (never re-seed — that would defeat the max-duration cap).
  5867. if entry is None:
  5868. entry = _KeepWarmEntry(started=now_mono, held_target=bed_target)
  5869. self._keep_warm[pid] = entry
  5870. elapsed = now_mono - entry.started
  5871. if elapsed > max_hold_seconds:
  5872. # Timeout: publish bed → 0 once (if firmware still holds our
  5873. # target) and latch expired. The entry stays until the release
  5874. # sweep drops it, preventing the next tick from re-seeding.
  5875. logger.warning(
  5876. "Queue: keep-warm timeout for printer %d (held for %.0fs) — publishing bed → 0",
  5877. pid,
  5878. elapsed,
  5879. )
  5880. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  5881. if int(cur_bed_target) == entry.held_target:
  5882. try:
  5883. client.set_bed_temperature(0)
  5884. except Exception as exc:
  5885. logger.warning(
  5886. "Queue: keep-warm timeout bed-off failed for printer %d: %s",
  5887. pid,
  5888. exc,
  5889. )
  5890. else:
  5891. logger.info(
  5892. "Queue: keep-warm timeout for printer %d skipped bed-off (firmware target %d != held %d)",
  5893. pid,
  5894. int(cur_bed_target),
  5895. entry.held_target,
  5896. )
  5897. entry.expired = True
  5898. continue
  5899. # Idempotence: skip publish when firmware already has our target.
  5900. cur_bed_target = float((state.temperatures or {}).get("bed_target", 0) or 0)
  5901. if int(cur_bed_target) == bed_target:
  5902. entry.held_target = bed_target
  5903. continue
  5904. try:
  5905. client.set_bed_temperature(bed_target)
  5906. entry.held_target = bed_target
  5907. logger.info(
  5908. "Queue: keeping bed warm at %d°C for printer %d (FINISH, next item needs chamber heat)",
  5909. bed_target,
  5910. pid,
  5911. )
  5912. except Exception as exc:
  5913. logger.warning("Queue: keep-warm bed command failed for printer %d: %s", pid, exc)
  5914. def _sample_chamber_temps(self) -> None:
  5915. """Record a chamber temperature sample for every connected printer.
  5916. Called once per scheduler tick (every 3–30 s). Entries older than
  5917. _chamber_history_ttl are pruned on each write so the deques stay bounded.
  5918. Also evicts per-printer state whose printer_id is no longer registered
  5919. (e.g. deleted from the DB), so nothing accumulates for gone printers.
  5920. """
  5921. now = time.monotonic()
  5922. cutoff = now - self._chamber_history_ttl
  5923. statuses = printer_manager.get_all_statuses()
  5924. known_pids = set(statuses.keys())
  5925. for pid, status in statuses.items():
  5926. if status is None or not status.connected:
  5927. continue
  5928. temps = status.temperatures or {}
  5929. chamber = temps.get("chamber")
  5930. if chamber is None:
  5931. continue
  5932. hist = self._chamber_history.setdefault(pid, deque())
  5933. hist.append((now, float(chamber)))
  5934. while hist and hist[0][0] < cutoff:
  5935. hist.popleft()
  5936. # Evict state for printers that are no longer registered with the manager.
  5937. # This is the one place a keep-warm entry is dropped without releasing
  5938. # the bed: the printer is gone from the manager, so there is no client
  5939. # left to send M140 to. `_release_keep_warm` deliberately keeps entries
  5940. # for printers that are merely unreachable, which is what makes this
  5941. # the terminal case rather than a silent leak.
  5942. for pid in list(self._chamber_history):
  5943. if pid not in known_pids:
  5944. self._chamber_history.pop(pid, None)
  5945. for pid in list(self._keep_warm):
  5946. if pid not in known_pids:
  5947. logger.info(
  5948. "Queue: dropping keep-warm state for printer %d — no longer registered",
  5949. pid,
  5950. )
  5951. self._keep_warm.pop(pid, None)
  5952. for pid in list(self._preheat_pin):
  5953. if pid not in known_pids:
  5954. self._preheat_pin.pop(pid, None)
  5955. self._preheat_pin_bed.pop(pid, None)
  5956. def _chamber_soak_remaining(
  5957. self,
  5958. printer_id: int,
  5959. chamber_target: float,
  5960. soak_seconds: int,
  5961. tolerance: float = 2.0,
  5962. ) -> int:
  5963. """Return how many seconds of soak time are still needed.
  5964. Credits the time the chamber has already spent at temperature against
  5965. the configured soak. The credit may not start earlier than any of:
  5966. * **The newest sample.** Nothing recent means the printer stopped
  5967. reporting mid-observation and the chamber may have cooled unseen, so
  5968. the full soak is required. (A 2 h history whose last reading is half
  5969. an hour old is not evidence of anything — the measured cooling rate
  5970. is fast enough to cross the threshold in that time.)
  5971. * **The most recent contiguous run of samples.** A gap wider than
  5972. ``_CHAMBER_SAMPLE_MAX_GAP_SECONDS`` is a disconnect, and time on its
  5973. far side is not evidence of temperature.
  5974. * **The end of the most recent real dip below the threshold.**
  5975. A dip only counts as real once it lasts ``_CHAMBER_DIP_GRACE_SECONDS``
  5976. — see that constant for the thermal reasoning. A stray low reading is
  5977. an artifact, and treating it as cooling would discard a soak that
  5978. actually happened.
  5979. Returns ``soak_seconds`` when nothing can be credited (no history,
  5980. stale history, or the chamber is below the threshold right now) and 0
  5981. once the credited time covers the whole soak.
  5982. """
  5983. hist = self._chamber_history.get(printer_id)
  5984. if not hist:
  5985. return soak_seconds
  5986. now = time.monotonic()
  5987. newest_ts, newest_temp = hist[-1]
  5988. if now - newest_ts > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  5989. return soak_seconds # stale — no fresh evidence to credit
  5990. threshold = chamber_target - tolerance
  5991. if newest_temp < threshold:
  5992. return soak_seconds # below target right now; nothing is soaked
  5993. samples = list(hist)
  5994. # Earliest point we have unbroken observations for.
  5995. credit_from = samples[-1][0]
  5996. for i in range(len(samples) - 1, 0, -1):
  5997. if samples[i][0] - samples[i - 1][0] > _CHAMBER_SAMPLE_MAX_GAP_SECONDS:
  5998. break
  5999. credit_from = samples[i - 1][0]
  6000. # Pull the credit forward to the end of the last significant dip. Each
  6001. # excursion is measured between the in-range readings that bracket it,
  6002. # so a lone stray sample is charged one sampling interval rather than
  6003. # zero, and the comparison errs towards calling a dip real.
  6004. i = 0
  6005. while i < len(samples):
  6006. if samples[i][1] >= threshold:
  6007. i += 1
  6008. continue
  6009. j = i
  6010. while j < len(samples) and samples[j][1] < threshold:
  6011. j += 1
  6012. # `newest_temp >= threshold` was checked above, so j is in range.
  6013. opened_at = samples[i - 1][0] if i > 0 else samples[i][0]
  6014. if samples[j][0] - opened_at >= _CHAMBER_DIP_GRACE_SECONDS:
  6015. # Credit resumes at the last below-threshold sample rather than
  6016. # the first good one after it, so a recovered dip over-credits
  6017. # by up to one sampling interval — the opposite lean to the
  6018. # bracketing above. Both are bounded by the sample cadence and
  6019. # dwarfed by the grace period, so neither is worth the extra
  6020. # arithmetic to remove.
  6021. credit_from = max(credit_from, samples[j - 1][0])
  6022. i = j
  6023. return max(0, soak_seconds - int(now - credit_from))
  6024. def notify_dispatch_cancelled(self, item_id: int) -> None:
  6025. """Tell an in-flight dispatch that its item no longer wants to print.
  6026. Called by the queue's cancel and delete routes. Those only write to the
  6027. database, which a dispatch coroutine parked in ``asyncio.sleep`` cannot
  6028. observe — so preheat would keep heating for the rest of max_wait + soak
  6029. (45 minutes at the defaults) and keep the printer in ``busy_printers``,
  6030. blocking every other queued item behind a print that is not happening.
  6031. Signalling in memory rather than re-reading the row keeps this off the
  6032. database entirely: no second session, no transaction held across a long
  6033. sleep, and no snapshot staleness deciding whether a print goes ahead.
  6034. Bambuddy serves from a single uvicorn process with one scheduler task,
  6035. so the route and the dispatch always share this object. The flag is
  6036. advisory — dropping it (e.g. after a restart) only costs a wasted
  6037. preheat, never a wrongly-abandoned print.
  6038. Only ids with a dispatch actually in flight are recorded, so the set
  6039. stays bounded by the upload pool rather than growing once per cancelled
  6040. item for the life of the process. Skipping the rest loses nothing: an
  6041. item that is not in flight cannot start heating later either, because
  6042. ``_claim_for_dispatch`` only claims rows that are still ``pending`` and
  6043. the caller has already committed a terminal status (or deleted the row)
  6044. before calling this.
  6045. """
  6046. if item_id in self._inflight:
  6047. self._cancelled_dispatches.add(item_id)
  6048. async def _preheat_sleep(self, item_id: int, seconds: float) -> bool:
  6049. """Sleep in slices, returning False as soon as the item stops wanting preheat.
  6050. A single long ``asyncio.sleep`` cannot notice a cancellation that lands
  6051. while it is parked, so the wait is chopped into
  6052. ``_PREHEAT_CANCEL_CHECK_SECONDS`` slices with a check after each.
  6053. """
  6054. remaining = float(seconds)
  6055. while remaining > 0:
  6056. slice_secs = min(_PREHEAT_CANCEL_CHECK_SECONDS, remaining)
  6057. await asyncio.sleep(slice_secs)
  6058. remaining -= slice_secs
  6059. if item_id in self._cancelled_dispatches:
  6060. return False
  6061. return True
  6062. def _preheat_flap_to_cooling(self, item_id: int, printer: Printer) -> None:
  6063. """Put the airduct flap back to cooling for a print that wants no chamber heat.
  6064. The full preheat stage does this as part of its own dispatch: an H2D
  6065. left in heating mode by the ABS job before it would otherwise cook the
  6066. PLA that follows. The skip path never reaches that code, so it calls
  6067. this instead -- one idempotent MQTT command, no waiting, and nothing to
  6068. add to the rollback pin, because a flap set to cooling for a print that
  6069. needs no heat is where it should have been either way.
  6070. Best-effort like everything else in the stage: a refused command logs
  6071. and the dispatch carries on.
  6072. """
  6073. model = printer.model or ""
  6074. if not supports_airduct(model):
  6075. return
  6076. state = printer_manager.get_status(printer.id)
  6077. current = getattr(state, "airduct_mode", None) if state else None
  6078. if current == _AIRDUCT_MODE_COOLING:
  6079. return
  6080. client = printer_manager.get_client(printer.id)
  6081. if client is None:
  6082. return
  6083. try:
  6084. client.set_airduct_mode("cooling")
  6085. except Exception as exc:
  6086. logger.warning("Queue item %s: preheat-skip airduct cooling failed: %s", item_id, exc)
  6087. async def _preheat_and_soak(
  6088. self,
  6089. db: AsyncSession,
  6090. item: PrintQueueItem,
  6091. printer: Printer,
  6092. archive: PrintArchive | None,
  6093. ) -> bool:
  6094. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  6095. Returns True when the dispatch should carry on to the upload — including
  6096. every case where preheat is skipped, since a skipped preheat is not a
  6097. reason to abandon the print. Returns False only when the item stopped
  6098. wanting to be printed while the stage was waiting (cancelled or
  6099. deleted); the caller must then abandon the dispatch, and
  6100. ``_dispatch_one``'s rollback shuts the heaters off on the way out.
  6101. Resolution order:
  6102. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  6103. to the global `preheat_enabled` setting; 'on' forces the stage on
  6104. even if the global is off.
  6105. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  6106. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  6107. across the trays `item.ams_mapping` names (every loaded slot when
  6108. it names none).
  6109. 3. A target of 0 off the filament map skips the whole stage: the
  6110. materials this print loads want no chamber, so there is nothing to
  6111. soak for and the bed phase would only delay the upload (#3041).
  6112. An explicit 0 typed into the per-item override, or a per-item
  6113. 'on', still runs the bed phase and the soak — both are the user
  6114. asking for a warm bed in so many words.
  6115. 4. Three hardware tiers branch the wait loop:
  6116. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  6117. send M141 to the resolved target, then wait for the chamber sensor
  6118. to reach it (or the max-wait timeout to elapse).
  6119. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  6120. no M141; the bed is the only heat source, so we wait for the chamber
  6121. sensor to rise via bed radiation OR fall through on timeout.
  6122. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  6123. temperature; the function just heats the bed and holds for the
  6124. configured soak duration.
  6125. The bed target comes from the archive's parsed metadata
  6126. (`bed_temperature`); if missing the preheat stage logs and returns
  6127. without dispatching anything, rather than guessing at a default that
  6128. might wreck filament setup.
  6129. Failures are logged but never re-raised — preheat is best-effort. A
  6130. printer that goes offline mid-soak, a refused gcode command, or a
  6131. missing temperature reading must not turn into a failed queue item; the
  6132. normal upload + start path runs immediately after this method returns.
  6133. """
  6134. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  6135. if override == "off":
  6136. return True
  6137. if override == "inherit":
  6138. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  6139. if not enabled:
  6140. return True
  6141. # override == "on" forces the stage on regardless of the global setting.
  6142. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  6143. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  6144. # Chamber target resolution:
  6145. # 1. Explicit per-item override beats everything (user knows best).
  6146. # 2. Otherwise derive from the filament types this print loads, via
  6147. # the per-filament target map. A PLA-only print derives 0 and the
  6148. # block below skips the stage without the user touching anything,
  6149. # even when an ASA spool is sitting in another slot of the same
  6150. # AMS (#2886).
  6151. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  6152. if explicit_target is not None and explicit_target > 0:
  6153. chamber_target = int(explicit_target)
  6154. chamber_source = "item-override"
  6155. elif explicit_target == 0:
  6156. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  6157. chamber_source = "item-override-zero"
  6158. else:
  6159. targets = await self._get_preheat_filament_targets(db)
  6160. chamber_target = self._derive_chamber_target(printer, targets, item)
  6161. chamber_source = "filament-map"
  6162. # Nothing to preheat *for*. A zero that came out of the filament map is
  6163. # the map saying this print's materials want no chamber conditioning --
  6164. # PLA, PETG, TPU and PVA all sit at 0 by default. Running the stage
  6165. # anyway heated the bed and then held it for the full soak, which
  6166. # delayed every PLA dispatch by minutes and bought nothing: the print's
  6167. # own G-code sets the bed the moment it starts, so preheating it here
  6168. # only moves that heating ahead of the upload instead of overlapping
  6169. # with it, and the soak has no chamber to condition (#3041).
  6170. #
  6171. # An explicit statement from the user still runs the stage. Forcing the
  6172. # per-item override to 'on', or typing a chamber target of exactly 0,
  6173. # both mean "preheat the bed for this print" -- the second is
  6174. # documented as doing precisely that. Only the automatic path, the
  6175. # global toggle plus the filament map, short-circuits here.
  6176. if chamber_target <= 0 and chamber_source == "filament-map" and override != "on":
  6177. logger.info(
  6178. "Queue item %s: preheat skipped -- the loaded filaments derive no chamber "
  6179. "target, so there is nothing to soak for (override=%s model=%s)",
  6180. item.id,
  6181. override,
  6182. printer.model or "",
  6183. )
  6184. self._preheat_flap_to_cooling(item.id, printer)
  6185. return True
  6186. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  6187. if bed_target <= 0:
  6188. # No bed temperature in the slicer metadata. When the print needs a
  6189. # hot chamber the bed is simply how we heat it, so fall back to the
  6190. # configured chamber-heating bed temperature rather than skipping
  6191. # the whole stage — otherwise the print starts with a cold chamber,
  6192. # which is exactly what preheat exists to prevent. Without a chamber
  6193. # requirement there is nothing to preheat *for*, so skip as before
  6194. # rather than guess a bed temperature for the print itself.
  6195. if chamber_target <= 0:
  6196. logger.info(
  6197. "Queue item %s: preheat skipped — archive has no bed_temperature metadata and no chamber target",
  6198. item.id,
  6199. )
  6200. return True
  6201. bed_target = await self._get_int_setting(db, "queue_keep_warm_bed_temp", default=90)
  6202. logger.info(
  6203. "Queue item %s: archive has no bed_temperature metadata — heating the bed to "
  6204. "%d°C to drive the chamber to %d°C",
  6205. item.id,
  6206. bed_target,
  6207. chamber_target,
  6208. )
  6209. client = printer_manager.get_client(printer.id)
  6210. if client is None:
  6211. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  6212. return True
  6213. model = printer.model or ""
  6214. has_heater = supports_chamber_heater(model)
  6215. has_sensor = supports_chamber_temp(model)
  6216. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  6217. # Fast path: if the chamber has been continuously above target for at
  6218. # least soak_seconds and the bed is already at temperature, skip the
  6219. # entire preheat stage. Typical case: keep-warm held the bed between
  6220. # consecutive same-material prints and the chamber never dropped.
  6221. if do_chamber and has_sensor and soak_seconds > 0:
  6222. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6223. if remaining == 0:
  6224. cur = printer_manager.get_status(printer.id)
  6225. if cur:
  6226. cur_temps = cur.temperatures or {}
  6227. if (
  6228. float(cur_temps.get("bed", 0) or 0) >= bed_target - 2.0
  6229. and float(cur_temps.get("chamber", 0) or 0) >= chamber_target - 2.0
  6230. ):
  6231. logger.info(
  6232. "Queue item %s: preheat skipped — chamber has been above %d°C for ≥%ds "
  6233. "and bed is already at temperature (chamber history fast-path)",
  6234. item.id,
  6235. chamber_target,
  6236. soak_seconds,
  6237. )
  6238. # Still set targets to prevent cooling during the 3MF upload window.
  6239. # Register each successful set in the preheat pin so `_dispatch_one`
  6240. # unwinds them on any non-success exit.
  6241. pin = self._preheat_pin.setdefault(printer.id, set())
  6242. try:
  6243. client.set_bed_temperature(bed_target)
  6244. pin.add("bed")
  6245. self._preheat_pin_bed[printer.id] = bed_target
  6246. except Exception as exc:
  6247. logger.warning("Queue item %s: fast-path bed M140 failed: %s", item.id, exc)
  6248. if supports_airduct(model):
  6249. cur_airduct = getattr(cur, "airduct_mode", None)
  6250. if cur_airduct != _AIRDUCT_MODE_HEATING:
  6251. try:
  6252. client.set_airduct_mode("heating")
  6253. # Only undo what we can see we replaced. `None`
  6254. # means no mode has been observed yet, and
  6255. # rolling that back to cooling would assert a
  6256. # state the printer never reported.
  6257. if cur_airduct == _AIRDUCT_MODE_COOLING:
  6258. pin.add("airduct")
  6259. except Exception as exc:
  6260. logger.warning("Queue item %s: fast-path airduct failed: %s", item.id, exc)
  6261. if has_heater:
  6262. try:
  6263. client.set_chamber_temperature(chamber_target)
  6264. pin.add("chamber")
  6265. except Exception as exc:
  6266. logger.warning("Queue item %s: fast-path chamber M141 failed: %s", item.id, exc)
  6267. return True
  6268. logger.info(
  6269. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  6270. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  6271. item.id,
  6272. bed_target,
  6273. chamber_target if do_chamber else 0,
  6274. chamber_source,
  6275. override,
  6276. model,
  6277. has_heater,
  6278. has_sensor,
  6279. max_wait,
  6280. soak_seconds,
  6281. )
  6282. # Preheat rollback registry: everything we set below is recorded here so
  6283. # `_dispatch_one`'s finally clause can unwind the whole heating regime
  6284. # (bed off, chamber off, airduct back to cooling) on any non-success
  6285. # exit. Populated as each command succeeds; consumed and cleared by
  6286. # `_dispatch_one`.
  6287. pin = self._preheat_pin.setdefault(printer.id, set())
  6288. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  6289. # cache the target locally so the polling reads below see consistent
  6290. # state (firmware MQTT echoes lag by ~1s).
  6291. try:
  6292. client.set_bed_temperature(bed_target)
  6293. pin.add("bed")
  6294. self._preheat_pin_bed[printer.id] = bed_target
  6295. except Exception as exc:
  6296. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  6297. return True
  6298. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  6299. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  6300. # left it on, regardless of M141. Default cooling actively vents the
  6301. # chamber, so a `chamber_target > 0` print with the flap stuck in
  6302. # cooling never converges — the heater fights the open exhaust. We
  6303. # flip the flap BEFORE M141 to "heating" when the preheat wants
  6304. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  6305. # on an H2D that was previously running ABS would otherwise stay in
  6306. # heating mode and overheat PLA). The current-state read keeps the
  6307. # command idempotent — no MQTT chatter when the flap is already where
  6308. # we want it.
  6309. if supports_airduct(model):
  6310. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  6311. desired_id = _AIRDUCT_MODE_HEATING if desired_airduct == "heating" else _AIRDUCT_MODE_COOLING
  6312. current_state = printer_manager.get_status(printer.id)
  6313. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  6314. if current_airduct != desired_id:
  6315. try:
  6316. client.set_airduct_mode(desired_airduct)
  6317. # As in the fast path: only pin a rollback for a flap we
  6318. # saw in cooling. `current_airduct` of None means no mode
  6319. # has been observed, so there is nothing to restore to.
  6320. if desired_airduct == "heating" and current_airduct == _AIRDUCT_MODE_COOLING:
  6321. pin.add("airduct")
  6322. except Exception as exc:
  6323. logger.warning(
  6324. "Queue item %s: preheat airduct %s mode failed: %s",
  6325. item.id,
  6326. desired_airduct,
  6327. exc,
  6328. )
  6329. if do_chamber and has_heater:
  6330. try:
  6331. client.set_chamber_temperature(chamber_target)
  6332. pin.add("chamber")
  6333. except Exception as exc:
  6334. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  6335. # Release the pooled DB connection before the (potentially many-minute)
  6336. # heat-soak wait below (#2572). Every setting this method needs is read
  6337. # above; the wait/soak loop only polls printer_manager state and sleeps —
  6338. # it never touches the DB. Without this the caller's transaction sat
  6339. # "idle in transaction" for the whole soak, pinning one pooled connection
  6340. # per preheating printer. expire_on_commit=False keeps item/printer
  6341. # readable afterwards; there are no pending writes to lose here.
  6342. await db.commit()
  6343. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  6344. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  6345. # Poll every 3s — frequent enough for responsive logging without
  6346. # spamming the MQTT state stream. The "converged" predicate is:
  6347. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  6348. # AND
  6349. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  6350. BED_TOLERANCE = 2.0
  6351. CHAMBER_TOLERANCE = 2.0
  6352. POLL_INTERVAL = 3.0
  6353. deadline = asyncio.get_event_loop().time() + max_wait
  6354. while True:
  6355. state = printer_manager.get_status(printer.id)
  6356. if state is None:
  6357. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  6358. break
  6359. temps = state.temperatures or {}
  6360. bed_now = float(temps.get("bed", 0) or 0)
  6361. chamber_now = float(temps.get("chamber", 0) or 0)
  6362. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  6363. if not do_chamber:
  6364. chamber_ok = True # phase disabled or model has neither sensor nor heater
  6365. elif not has_sensor:
  6366. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  6367. else:
  6368. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  6369. if bed_ok and chamber_ok:
  6370. logger.info(
  6371. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  6372. item.id,
  6373. bed_now,
  6374. chamber_now,
  6375. )
  6376. break
  6377. if asyncio.get_event_loop().time() >= deadline:
  6378. logger.info(
  6379. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  6380. item.id,
  6381. bed_now,
  6382. bed_target,
  6383. chamber_now,
  6384. chamber_target if do_chamber else 0,
  6385. )
  6386. break
  6387. if not await self._preheat_sleep(item.id, POLL_INTERVAL):
  6388. logger.info(
  6389. "Queue item %s: preheat aborted — item cancelled or deleted while waiting for temperature",
  6390. item.id,
  6391. )
  6392. return False
  6393. if soak_seconds > 0:
  6394. if do_chamber and has_sensor:
  6395. remaining = self._chamber_soak_remaining(printer.id, float(chamber_target), soak_seconds)
  6396. else:
  6397. remaining = soak_seconds # no sensor — can't verify history, run full soak
  6398. if remaining > 0:
  6399. logger.info(
  6400. "Queue item %s: preheat soak — holding for %ds (of %ds configured; chamber "
  6401. "has been above target for ~%ds already)",
  6402. item.id,
  6403. remaining,
  6404. soak_seconds,
  6405. soak_seconds - remaining,
  6406. )
  6407. if not await self._preheat_sleep(item.id, remaining):
  6408. logger.info(
  6409. "Queue item %s: preheat aborted — item cancelled or deleted during soak",
  6410. item.id,
  6411. )
  6412. return False
  6413. else:
  6414. logger.info(
  6415. "Queue item %s: preheat soak skipped — chamber has been above %d°C for ≥%ds",
  6416. item.id,
  6417. chamber_target,
  6418. soak_seconds,
  6419. )
  6420. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  6421. return True
  6422. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  6423. """Turn on smart plug and wait for printer to connect.
  6424. Returns True if printer connected successfully within timeout.
  6425. """
  6426. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  6427. service = await smart_plug_manager.get_service_for_plug(plug, db)
  6428. # Check current plug state
  6429. status = await service.get_status(plug)
  6430. if not status.get("reachable"):
  6431. logger.warning("Smart plug '%s' is not reachable", plug.name)
  6432. return False
  6433. # Turn on if not already on
  6434. if status.get("state") != "ON":
  6435. success = await service.turn_on(plug)
  6436. if not success:
  6437. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  6438. return False
  6439. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  6440. # Get printer from database for connection
  6441. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6442. printer = result.scalar_one_or_none()
  6443. if not printer:
  6444. logger.error("Printer %s not found in database", printer_id)
  6445. return False
  6446. # Wait for printer to boot (give it some time before trying to connect)
  6447. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  6448. await asyncio.sleep(30)
  6449. # Try to connect to the printer periodically
  6450. elapsed = 30 # Already waited 30s
  6451. while elapsed < self._power_on_wait_time:
  6452. # Try to connect
  6453. logger.info("Attempting to connect to printer %s...", printer_id)
  6454. try:
  6455. connected = await printer_manager.connect_printer(printer)
  6456. if connected:
  6457. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  6458. # Give it a moment to stabilize and get status
  6459. await asyncio.sleep(5)
  6460. return True
  6461. except Exception as e:
  6462. logger.debug("Connection attempt failed: %s", e)
  6463. await asyncio.sleep(self._power_on_check_interval)
  6464. elapsed += self._power_on_check_interval
  6465. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  6466. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  6467. return False
  6468. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  6469. """Check if the previous print on this printer succeeded.
  6470. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  6471. deliberate action, not a failure, so subsequent items should still
  6472. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  6473. a skip isn't an actual print attempt, so it must not gate downstream
  6474. items — counting it as a failed predecessor was the cascade bug that
  6475. let a single cancellation block 18 items over 3 days for the reporter.
  6476. Only `failed` and `aborted` — real print-attempt failures — block.
  6477. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  6478. action — #1818) are also excluded from the lookback so the user can
  6479. clear the gate after fixing the physical issue without having to
  6480. re-queue every downstream job.
  6481. """
  6482. result = await db.execute(
  6483. select(PrintQueueItem)
  6484. .where(PrintQueueItem.printer_id == item.printer_id)
  6485. .where(PrintQueueItem.id != item.id)
  6486. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  6487. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  6488. .order_by(PrintQueueItem.completed_at.desc())
  6489. .limit(1)
  6490. )
  6491. prev_item = result.scalar_one_or_none()
  6492. # If no previous item, assume success (first in queue)
  6493. if not prev_item:
  6494. return True
  6495. return prev_item.status in ("completed", "cancelled")
  6496. async def _repoint_siblings_at_archive(
  6497. self,
  6498. db: AsyncSession,
  6499. *,
  6500. consumed_library_file_id: int,
  6501. archive_id: int,
  6502. dispatched_item_id: int,
  6503. ) -> int:
  6504. """Move the other queue items off a library row that is about to be deleted (#2819).
  6505. ``cleanup_library_after_dispatch`` consumes the library row: the printer-card
  6506. upload-and-print flow uploads a transient file, prints it, and deletes it.
  6507. Queue creation happily puts that flag on every copy of a ``quantity > 1``
  6508. request, and ``_clone_queue_item`` copies ``library_file_id`` onto batch
  6509. clones, so the first dispatch could pull the file out from under rows that
  6510. had not run yet. What those rows did next depended on the database, and
  6511. neither answer was right: SQLite ships with ``PRAGMA foreign_keys`` off, so
  6512. the ``ON DELETE CASCADE`` on ``print_queue.library_file_id`` never fired and
  6513. they were left pointing at a row that no longer existed, failing with
  6514. "Library file not found" whenever someone started them -- or sitting
  6515. ``pending`` forever under ``manual_start``. PostgreSQL enforces the same
  6516. constraint, so there the rows were deleted outright and the queued copies
  6517. simply vanished, with no error and no history.
  6518. The archive holds its own copy of the 3MF, so the remaining copies can print
  6519. from it instead. Two things happen here, and both must happen *before* the
  6520. delete -- afterwards there is nothing left to repair on PostgreSQL:
  6521. * every row still naming the file has ``library_file_id`` cleared, which is
  6522. what takes it out of the cascade's reach. That covers rows this cannot
  6523. re-point as well -- a copy already printing from its own archive, and the
  6524. finished ones, which are not spare parts but the record a batch order
  6525. counts its progress from.
  6526. * the rows that still need something to print are pointed at the archive.
  6527. Returns how many items were re-pointed.
  6528. """
  6529. variant_item_ids = (
  6530. (
  6531. await db.execute(
  6532. select(PrintQueueVariant.queue_item_id).where(
  6533. PrintQueueVariant.library_file_id == consumed_library_file_id
  6534. )
  6535. )
  6536. )
  6537. .scalars()
  6538. .all()
  6539. )
  6540. # Candidate rows naming the consumed file have to go rather than be
  6541. # cleared: `library_file_id` is NOT NULL there, so there is no way to keep
  6542. # one out of the cascade. This is what PostgreSQL already does, and
  6543. # _candidates_for skips such a variant on SQLite anyway, so no selection
  6544. # outcome changes -- the two backends simply stop disagreeing about
  6545. # whether the row is still there.
  6546. #
  6547. # It also has to happen before the re-point below: a cross-model item
  6548. # (#671) picks a variant every pass and folds it onto the row, and
  6549. # _resolve_variant clears archive_id as it does so, which would undo the
  6550. # re-point on the very next lap.
  6551. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id == consumed_library_file_id))
  6552. # An item left with other candidates still has somewhere to go, and those
  6553. # carry their own target model -- pointing it at this archive would print a
  6554. # file the matcher never chose. It is excluded from the re-point and simply
  6555. # re-resolves against what is left.
  6556. surviving_variant_item_ids = set(
  6557. (
  6558. await db.execute(
  6559. select(PrintQueueVariant.queue_item_id).where(
  6560. PrintQueueVariant.queue_item_id.in_(variant_item_ids) if variant_item_ids else false()
  6561. )
  6562. )
  6563. )
  6564. .scalars()
  6565. .all()
  6566. )
  6567. repoint_ids = set(
  6568. (
  6569. await db.execute(
  6570. select(PrintQueueItem.id)
  6571. .where(PrintQueueItem.id != dispatched_item_id)
  6572. .where(PrintQueueItem.archive_id.is_(None))
  6573. # "skipped" belongs here with the two live states: it is not
  6574. # terminal. Clearing a printer's previous-success gate puts
  6575. # every item skipped by it back to "pending"
  6576. # (resume_after_failure), and one restored onto a deleted
  6577. # file is the same orphan by a slower route. "failed",
  6578. # "cancelled", "aborted" and "completed" never return.
  6579. .where(PrintQueueItem.status.in_(("pending", "printing", "skipped")))
  6580. .where(
  6581. PrintQueueItem.id.notin_(surviving_variant_item_ids) if surviving_variant_item_ids else true()
  6582. )
  6583. .where(
  6584. or_(
  6585. PrintQueueItem.library_file_id == consumed_library_file_id,
  6586. PrintQueueItem.id.in_(variant_item_ids) if variant_item_ids else false(),
  6587. )
  6588. )
  6589. )
  6590. )
  6591. .scalars()
  6592. .all()
  6593. )
  6594. if repoint_ids:
  6595. await db.execute(
  6596. update(PrintQueueItem)
  6597. .where(PrintQueueItem.id.in_(repoint_ids))
  6598. .values(
  6599. archive_id=archive_id,
  6600. library_file_id=None,
  6601. # The file this flag named is already consumed. Leaving it set
  6602. # would arm every re-pointed copy to delete whatever library
  6603. # row it is next given.
  6604. cleanup_library_after_dispatch=False,
  6605. )
  6606. )
  6607. logger.info(
  6608. "Queue items %s: re-pointed at archive %s -- library file %s was consumed by item %s",
  6609. sorted(repoint_ids),
  6610. archive_id,
  6611. consumed_library_file_id,
  6612. dispatched_item_id,
  6613. )
  6614. # Everything else that still names the file: taken out of the cascade's
  6615. # reach without touching what it prints. The file is gone either way; what
  6616. # this preserves is the row.
  6617. await db.execute(
  6618. update(PrintQueueItem)
  6619. .where(PrintQueueItem.id != dispatched_item_id)
  6620. .where(PrintQueueItem.library_file_id == consumed_library_file_id)
  6621. .values(library_file_id=None)
  6622. )
  6623. return len(repoint_ids)
  6624. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  6625. """Schedule power-off if the queue item enabled auto_off_after.
  6626. Delegates to the smart-plug manager so the off honours each plug's
  6627. configured strategy (time delay or temperature threshold), is cancelled
  6628. if the printer starts printing again, and never cuts power on a loaded
  6629. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  6630. powered off on the timeout regardless of print state.
  6631. """
  6632. if not item.auto_off_after:
  6633. return
  6634. try:
  6635. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  6636. except Exception as e:
  6637. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  6638. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  6639. """Get a human-readable name for a queue item."""
  6640. if item.archive_id:
  6641. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  6642. archive = result.scalar_one_or_none()
  6643. if archive:
  6644. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6645. if item.library_file_id:
  6646. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  6647. library_file = result.scalar_one_or_none()
  6648. if library_file:
  6649. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  6650. # A cross-model item (#671) holds no file of its own until a printer is
  6651. # picked, so name it after its first candidate — otherwise every waiting
  6652. # notification for one reads "Job #12". Queried rather than read off
  6653. # item.variants because callers outside the selection loop have not
  6654. # eager-loaded them, and a lazy load raises in async.
  6655. first_variant_name = (
  6656. await db.execute(
  6657. select(LibraryFile.filename)
  6658. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  6659. .where(PrintQueueVariant.queue_item_id == item.id)
  6660. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  6661. .limit(1)
  6662. )
  6663. ).scalar_one_or_none()
  6664. if first_variant_name:
  6665. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  6666. return f"Job #{item.id}"
  6667. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  6668. """Get printer by ID."""
  6669. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6670. return result.scalar_one_or_none()
  6671. async def _notify_dispatch_gave_up(
  6672. self,
  6673. queue_item_id: int,
  6674. printer_id: int,
  6675. created_by_id: int | None,
  6676. reason: str = "Printer accepted the file but never started printing",
  6677. ) -> None:
  6678. """Tell the user the queue item was failed after exhausting its dispatch retries.
  6679. Called from the watchdog, which is a background task with no session of
  6680. its own — hence the fresh one here. Best-effort throughout: the row is
  6681. already marked failed and that is the load-bearing part; a notification
  6682. provider being down must not resurrect the retry loop we just stopped.
  6683. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  6684. path passes its own, because "accepted the file but never started" is the
  6685. opposite of what happened there — the printer refused it outright (#2732).
  6686. """
  6687. try:
  6688. async with async_session() as db:
  6689. item = await db.get(PrintQueueItem, queue_item_id)
  6690. if not item:
  6691. return
  6692. job_name = await self._get_job_name(db, item)
  6693. printer = await self._get_printer(db, printer_id)
  6694. await notification_service.on_queue_job_failed(
  6695. job_name=job_name,
  6696. printer_id=printer_id,
  6697. printer_name=printer.name if printer else "Unknown",
  6698. reason=reason,
  6699. db=db,
  6700. )
  6701. except Exception as e:
  6702. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  6703. try:
  6704. await ws_manager.send_queue_item_failed(
  6705. user_id=created_by_id,
  6706. queue_item_id=queue_item_id,
  6707. printer_id=printer_id,
  6708. reason="never_started",
  6709. )
  6710. except Exception:
  6711. pass # toast is best-effort
  6712. async def _block_on_filament_deficit(
  6713. self,
  6714. db: AsyncSession,
  6715. item: PrintQueueItem,
  6716. ) -> bool:
  6717. """Promote the item to manual_start when the assigned spool is short (#1496).
  6718. Returns True when this dispatch attempt was blocked, False when the
  6719. item is clear to start. A previously-flagged item whose spool has
  6720. since been swapped to one with enough material clears the flag here
  6721. so the next scheduler tick dispatches it.
  6722. """
  6723. # User has explicitly acknowledged the deficit ("Print Anyway") —
  6724. # don't re-flag, don't even compute. Without this short-circuit the
  6725. # scheduler bounces between "user said anyway" (route clears
  6726. # manual_start) and "scheduler re-blocked" (this method re-flags it
  6727. # on identical spool state) (#1698-followup).
  6728. if item.skip_filament_check:
  6729. # #1762 diagnostic: surface the short-circuit at INFO so a
  6730. # future "Print Anyway didn't work" report (e.g. issue #1762
  6731. # comment 3) has actionable evidence in the support bundle
  6732. # without needing DEBUG enabled.
  6733. logger.info(
  6734. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  6735. item.id,
  6736. )
  6737. return False
  6738. try:
  6739. deficit = await compute_deficit_for_queue_item(db, item)
  6740. except Exception as e:
  6741. # Never let a flaky deficit check wedge the queue — log and let
  6742. # dispatch proceed. The PrintModal-side check still runs on the
  6743. # manual paths.
  6744. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  6745. return False
  6746. if deficit:
  6747. item.filament_short = True
  6748. item.manual_start = True
  6749. await db.commit()
  6750. job_name = await self._get_job_name(db, item)
  6751. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  6752. logger.info(
  6753. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  6754. item.id,
  6755. len(deficit),
  6756. )
  6757. try:
  6758. await notification_service.on_queue_job_waiting(
  6759. job_name=job_name,
  6760. target_model=(printer.model if printer else "") or "",
  6761. waiting_reason="filament_short",
  6762. db=db,
  6763. )
  6764. except Exception as e:
  6765. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  6766. return True
  6767. # No deficit — clear any stale flag from a previous tick.
  6768. if item.filament_short:
  6769. item.filament_short = False
  6770. await db.commit()
  6771. return False
  6772. async def _block_on_unmatched_filament(
  6773. self,
  6774. db: AsyncSession,
  6775. item: PrintQueueItem,
  6776. release_assignment: bool = False,
  6777. ) -> bool:
  6778. """Promote to manual_start when a slot the plate prints has no tray (#2799).
  6779. The matcher leaves a requirement it cannot satisfy at ``-1`` and dispatch
  6780. goes ahead, letting the printer choose — which is how a job prints in the
  6781. wrong material without anyone being asked. Holding is the same answer the
  6782. deficit gate already gives for "the spool is too light", so it reuses the
  6783. same promote-and-notify machinery.
  6784. Keyed off unresolved slots in the *computed* mapping intersected with the
  6785. plate's own requirement list. Intersecting is what makes ``-1`` safe to
  6786. read: on its own it also pads slots this plate does not print, so the
  6787. array alone would hold perfectly good jobs. Reading the mapping rather
  6788. than the printer's loaded filament types also inherits the matcher's
  6789. per-nozzle restriction for free — a dual-nozzle printer carrying the
  6790. filament on the other nozzle's AMS has it "loaded" but unusable, and a
  6791. type-only scan would wave that through.
  6792. A mapping that resolved *nothing* is the same finding arriving as an
  6793. absence. ``_ensure_ams_mapping`` clears a rejected mapping its recompute
  6794. could not replace, and dispatch then goes out as ``use_ams`` with no
  6795. table at all — several megabytes uploaded for an 0700_8012 rejection.
  6796. That is held too, but only once live status positively reports loaded
  6797. trays: #2589's mapping is bogus precisely because the AMS was not known
  6798. yet, and its empty loaded list is that ignorance rather than a miss.
  6799. ``release_assignment`` is for the model-based path, which commits its
  6800. printer choice before the gates run. Holding an "any P2S" job would
  6801. otherwise pin it to the one P2S that could not run it.
  6802. Returns True when this dispatch attempt was blocked.
  6803. """
  6804. if item.skip_filament_check or not item.printer_id:
  6805. return False
  6806. if item.ams_mapping:
  6807. try:
  6808. mapping = json.loads(item.ams_mapping)
  6809. except (json.JSONDecodeError, TypeError):
  6810. return False
  6811. if not isinstance(mapping, list):
  6812. return False
  6813. else:
  6814. # Nothing resolved, or nothing survived revalidation. Only a printer
  6815. # that reported loaded trays makes that a finding — see the
  6816. # docstring on why an empty list is not one.
  6817. status = printer_manager.get_status(item.printer_id)
  6818. if status is None or not self._build_loaded_filaments(status):
  6819. return False
  6820. # Every required slot reads unresolved against an empty mapping.
  6821. mapping = []
  6822. required = await self._get_filament_requirements(db, item)
  6823. if not required:
  6824. return False
  6825. self._apply_filament_overrides(item, required)
  6826. unmatched = _unresolved_required(required, mapping)
  6827. if not unmatched:
  6828. # No cleanup needed here: once start is pressed the item is no
  6829. # longer staged, and whichever exit runs next overwrites the reason
  6830. # (`hold_item` on the fixed-printer branch, the assignment on the
  6831. # model-based one), as does dispatch.
  6832. return False
  6833. wanted = ", ".join(_describe_filament(r, "nozzle_id") for r in unmatched)
  6834. held_by = item.printer_id
  6835. item.manual_start = True
  6836. # Human-readable: this renders on the queue row.
  6837. item.waiting_reason = f"{_UNMATCHED_HOLD_PREFIX}{wanted}"
  6838. if release_assignment:
  6839. # "Any P2S" means any, so the job returns to the pool rather than
  6840. # waiting on the printer that could not take it. The mapping goes
  6841. # with the assignment: its tray IDs were resolved against the
  6842. # printer being released and mean nothing on the next one (#2799),
  6843. # and keeping them would hold the job again even on a printer that
  6844. # has the filament, since an unresolved slot is deliberately not a
  6845. # conflict worth recomputing over.
  6846. item.printer_id = None
  6847. item.ams_mapping = None
  6848. await db.commit()
  6849. job_name = await self._get_job_name(db, item)
  6850. printer = await self._get_printer(db, held_by)
  6851. logger.info(
  6852. "Queue item %s blocked — printer %s has nothing loaded for %s; promoted to manual_start",
  6853. item.id,
  6854. held_by,
  6855. wanted,
  6856. )
  6857. try:
  6858. await notification_service.on_queue_job_waiting(
  6859. job_name=job_name,
  6860. target_model=(printer.model if printer else "") or "",
  6861. waiting_reason=f"needs {wanted}",
  6862. db=db,
  6863. )
  6864. except Exception as e:
  6865. logger.debug("filament_missing notification failed for item %s: %s", item.id, e)
  6866. return True
  6867. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  6868. """Hand the queue item's owner to printer_manager so the
  6869. print-complete callback can credit the user in PrintLogEntry (#1670).
  6870. No-ops when the item has no `created_by_id` or the referenced user
  6871. row is missing (e.g. user deleted between queue-add and dispatch —
  6872. in that case the print log row falls back to the existing un-credited
  6873. behaviour rather than crashing the dispatch).
  6874. """
  6875. if not item.created_by_id:
  6876. return
  6877. from backend.app.models.user import User
  6878. owner = await db.get(User, item.created_by_id)
  6879. if owner:
  6880. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  6881. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  6882. """Upload file and start print for a queue item.
  6883. Supports two sources:
  6884. - archive_id: Print from an existing archive
  6885. - library_file_id: Print from a library file (file manager)
  6886. """
  6887. logger.info("Starting queue item %s", item.id)
  6888. # Also covers a reservation left active by a process interruption
  6889. # during an earlier attempt. `_dispatch_one` releases this marker on
  6890. # every exit unless start_print() confirms that the command was sent.
  6891. self._unconfirmed_budget_reservations.add(item.id)
  6892. try:
  6893. from backend.app.models.user import User
  6894. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  6895. # Recompute at the final authorization boundary as well as enqueue
  6896. # time. This covers rows created before the server-side estimate
  6897. # migration and prevents any alternate write path from weakening
  6898. # the budget reservation.
  6899. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  6900. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  6901. item.estimated_cost = await estimate_queue_source_cost(
  6902. db,
  6903. archive=archive,
  6904. library_file=library_file,
  6905. plate_id=item.plate_id,
  6906. ams_mapping=item.ams_mapping,
  6907. printer_id=item.printer_id,
  6908. )
  6909. await validate_print_budget(
  6910. db,
  6911. cost_center_id=item.cost_center_id,
  6912. estimated_cost=item.estimated_cost,
  6913. current_user=queue_user,
  6914. exclude_queue_item_id=item.id,
  6915. exclude_reservation_source_type="print_queue",
  6916. exclude_reservation_source_id=item.id,
  6917. )
  6918. budget_reservation = await create_budget_reservation(
  6919. db,
  6920. cost_center_id=item.cost_center_id,
  6921. estimated_cost=item.estimated_cost,
  6922. current_user=queue_user,
  6923. source_type="print_queue",
  6924. source_id=item.id,
  6925. print_archive_id=item.archive_id,
  6926. exclude_queue_item_id=item.id,
  6927. )
  6928. await db.commit()
  6929. except HTTPException as exc:
  6930. item.status = "failed"
  6931. item.error_message = str(exc.detail)
  6932. item.completed_at = datetime.now(timezone.utc)
  6933. await db.commit()
  6934. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  6935. await self._power_off_if_needed(db, item)
  6936. return
  6937. # Get printer first (needed for both paths)
  6938. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  6939. printer = result.scalar_one_or_none()
  6940. if not printer:
  6941. item.status = "failed"
  6942. item.error_message = "Printer not found"
  6943. item.completed_at = datetime.now(timezone.utc)
  6944. await db.commit()
  6945. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  6946. await self._power_off_if_needed(db, item)
  6947. return
  6948. # Check printer is connected
  6949. if not printer_manager.is_connected(item.printer_id):
  6950. item.status = "failed"
  6951. item.error_message = "Printer not connected"
  6952. item.completed_at = datetime.now(timezone.utc)
  6953. await db.commit()
  6954. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  6955. await self._power_off_if_needed(db, item)
  6956. return
  6957. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  6958. # `items` was taken at the top of check_queue, but the user can /cancel
  6959. # any pending row in the gap before we reach this point. Re-read the
  6960. # row and bail out cleanly instead of starting an FTP upload for a row
  6961. # that's already cancelled. The atomic CAS at the pending→printing
  6962. # transition (below, before start_print) is the load-bearing guard;
  6963. # this is the early-exit optimisation that avoids wasted FTP I/O.
  6964. await db.refresh(item)
  6965. if item.status != "pending":
  6966. logger.info(
  6967. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  6968. item.id,
  6969. item.status,
  6970. )
  6971. return
  6972. # Busy-printer guard (#2598). check_queue gates dispatch on
  6973. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  6974. # keep reporting FINISH for tens of seconds *after* it accepted a
  6975. # project_file (see the watchdog's phase-B note). A watchdog revert
  6976. # (#2555) also releases the dispatch hold, so a re-selected item can
  6977. # reach here while its printer has actually started printing. Uploading
  6978. # and dispatching then collides with the live job — the firmware answers
  6979. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  6980. # live state right before the expensive FTP upload: if the printer is
  6981. # busy, leave the item pending and let a later tick dispatch it once the
  6982. # printer is genuinely idle. No wasted upload, no collision.
  6983. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  6984. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  6985. logger.info(
  6986. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  6987. "leaving item pending for a later tick (#2598)",
  6988. item.id,
  6989. item.printer_id,
  6990. pre_dispatch_state,
  6991. )
  6992. return
  6993. # Determine source: archive or library file
  6994. archive = None
  6995. library_file = None
  6996. file_path = None
  6997. filename = None
  6998. cleanup_disk_paths: list[Path] = []
  6999. # Set when a dispatch consumes its library file, so the photos can be
  7000. # carried over after the commit that removes the row (#3077).
  7001. consumed_library_file_id: int | None = None
  7002. consumed_photos: list[str] = []
  7003. if item.archive_id:
  7004. # Print from archive
  7005. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  7006. archive = result.scalar_one_or_none()
  7007. if not archive:
  7008. item.status = "failed"
  7009. item.error_message = "Archive not found"
  7010. item.completed_at = datetime.now(timezone.utc)
  7011. await db.commit()
  7012. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  7013. await self._power_off_if_needed(db, item)
  7014. return
  7015. # Persist the queue item's selected plate onto the archive so Print
  7016. # History can show the actual plate after cancel/fail/complete (#2603).
  7017. # Only when the archive doesn't already carry one, so a reprint of a
  7018. # plate-specific archive isn't relabelled by a differently-plated
  7019. # queue row.
  7020. if archive.plate_id is None and item.plate_id is not None:
  7021. archive.plate_id = item.plate_id
  7022. # Ask-for-outcome opt-in rides from the queue item to the archive
  7023. # the same way (#1898); never cleared here so a reprint of an
  7024. # archive that already asked keeps asking.
  7025. if item.confirm_outcome:
  7026. archive.confirm_requested = True
  7027. file_path = settings.base_dir / archive.file_path
  7028. filename = archive.filename
  7029. elif item.library_file_id:
  7030. # Print from library file (file manager)
  7031. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  7032. library_file = result.scalar_one_or_none()
  7033. if not library_file:
  7034. # "Not found" covers two different situations and only one of
  7035. # them is recoverable, so say which. A trashed file is still
  7036. # there and restoring it makes a re-queued job work; a file that
  7037. # is really gone needs a different one. Neither is knowable from
  7038. # the queue, which is the whole complaint about this message.
  7039. trashed = (
  7040. await db.execute(select(LibraryFile.filename).where(LibraryFile.id == item.library_file_id))
  7041. ).scalar_one_or_none()
  7042. item.status = "failed"
  7043. item.error_message = (
  7044. f"'{trashed}' is in the library trash — restore it and queue the print again"
  7045. if trashed
  7046. else "Library file not found — it was deleted after this job was queued"
  7047. )
  7048. item.completed_at = datetime.now(timezone.utc)
  7049. await db.commit()
  7050. logger.error(
  7051. "Queue item %s: library file %s is %s",
  7052. item.id,
  7053. item.library_file_id,
  7054. "in the trash" if trashed else "gone",
  7055. )
  7056. await self._power_off_if_needed(db, item)
  7057. return
  7058. # Library files store absolute paths
  7059. lib_path = Path(library_file.file_path)
  7060. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  7061. filename = library_file.filename
  7062. # Create archive from library file so usage tracking has access to the 3MF
  7063. queue_item_id = item.id
  7064. # Held separately: a cleanup dispatch clears item.library_file_id
  7065. # below, and the log line at the end of this block reported that
  7066. # cleared field -- so every consumed print logged "from library
  7067. # file None", which is the one case worth being able to trace.
  7068. source_library_file_id = item.library_file_id
  7069. try:
  7070. from backend.app.services.archive import ArchiveService
  7071. archive_service = ArchiveService(db)
  7072. archive = await archive_service.archive_print(
  7073. printer_id=item.printer_id,
  7074. source_file=file_path,
  7075. original_filename=filename,
  7076. created_by_id=item.created_by_id,
  7077. project_id=item.project_id,
  7078. cost_center_id=item.cost_center_id,
  7079. library_file_id=item.library_file_id, # per-file project progress (#1897)
  7080. plate_id=item.plate_id, # selected plate → Print History (#2603)
  7081. )
  7082. if archive:
  7083. item.archive_id = archive.id
  7084. if item.confirm_outcome:
  7085. archive.confirm_requested = True # ask-for-outcome opt-in (#1898)
  7086. if budget_reservation is not None:
  7087. budget_reservation.print_archive_id = archive.id
  7088. if item.cleanup_library_after_dispatch and not library_file.is_external:
  7089. consumed_library_file_id = library_file.id
  7090. item.library_file_id = None
  7091. cleanup_disk_paths.append(file_path)
  7092. if library_file.thumbnail_path:
  7093. thumb_path = Path(library_file.thumbnail_path)
  7094. if not thumb_path.is_absolute():
  7095. thumb_path = settings.base_dir / library_file.thumbnail_path
  7096. cleanup_disk_paths.append(thumb_path)
  7097. # Before the delete, not after: on PostgreSQL the FK
  7098. # cascade would already have taken these rows (#2819).
  7099. await self._repoint_siblings_at_archive(
  7100. db,
  7101. consumed_library_file_id=consumed_library_file_id,
  7102. archive_id=archive.id,
  7103. dispatched_item_id=item.id,
  7104. )
  7105. # Read while the row is still here; the photos move
  7106. # below, once the delete has actually committed.
  7107. consumed_photos = list(library_file.photos or [])
  7108. await db.delete(library_file)
  7109. file_path = settings.base_dir / archive.file_path
  7110. filename = archive.filename
  7111. # Commit, not flush — flush opens the SQLite write
  7112. # transaction (item.archive_id update + library_file
  7113. # delete) and would hold the WAL writer lock through the
  7114. # FTP upload below, causing "database is locked" cascades
  7115. # for sensor history + concurrent cancels (#1853).
  7116. await db.commit()
  7117. logger.info(
  7118. "Queue item %s: Created archive %s from library file %s",
  7119. item.id,
  7120. archive.id,
  7121. source_library_file_id,
  7122. )
  7123. except Exception as e:
  7124. logger.warning(
  7125. "Queue item %s: Failed to create archive from library file: %s",
  7126. queue_item_id,
  7127. e,
  7128. exc_info=True,
  7129. )
  7130. await db.rollback()
  7131. item = await db.get(PrintQueueItem, queue_item_id)
  7132. if item:
  7133. item.status = "failed"
  7134. item.error_message = "Failed to create archive from library file"
  7135. item.completed_at = datetime.now(timezone.utc)
  7136. await db.commit()
  7137. await self._power_off_if_needed(db, item)
  7138. return
  7139. if not archive:
  7140. item.status = "failed"
  7141. item.error_message = "Failed to create archive from library file"
  7142. item.completed_at = datetime.now(timezone.utc)
  7143. await db.commit()
  7144. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  7145. await self._power_off_if_needed(db, item)
  7146. return
  7147. # The photos follow the file into the archive that replaces it, for
  7148. # the same reason the siblings do (#3077). After the commit above,
  7149. # never before it: that commit can fail ("database is locked",
  7150. # #1853) and roll the library row back, and photos already moved
  7151. # would leave it naming a directory that no longer exists. The
  7152. # file and thumbnail unlinks are deferred for the same reason.
  7153. if consumed_library_file_id is not None and consumed_photos:
  7154. # Held as a plain int, read here while the session is still
  7155. # healthy, because the handler below may not touch an ORM
  7156. # instance at all. The commit it exists for fails inside the
  7157. # FLUSH, not at COMMIT: SQLite takes the write lock at the
  7158. # first DML statement, so a busy writer surfaces as "database
  7159. # is locked" on the UPDATE (#1853). SQLAlchemy rolls that back
  7160. # internally through safe_reraise before re-raising, which
  7161. # expires every loaded instance and leaves the session in
  7162. # pending-rollback state -- so `archive.id` inside the except
  7163. # would itself raise PendingRollbackError and the rollback
  7164. # below would never be reached.
  7165. archive_id = archive.id
  7166. try:
  7167. carried_photos = move_library_photos(
  7168. consumed_library_file_id,
  7169. consumed_photos,
  7170. archive_photos_dir(archive),
  7171. )
  7172. if carried_photos:
  7173. archive.photos = list(archive.photos or []) + carried_photos
  7174. await db.commit()
  7175. except Exception as e:
  7176. # The archive and the delete are already committed; the
  7177. # print goes ahead either way. Worst case the pictures sit
  7178. # unnamed in the archive's own directory.
  7179. #
  7180. # Ints only until the rollback has run, per the note above,
  7181. # which is why this logs queue_item_id and not item.id --
  7182. # the sibling handler forty lines up does the same.
  7183. logger.warning(
  7184. "Queue item %s: failed to carry library photos into archive %s: %s",
  7185. queue_item_id,
  7186. archive_id,
  7187. e,
  7188. )
  7189. await db.rollback()
  7190. # rollback() expires every loaded instance, and in async
  7191. # SQLAlchemy the next plain attribute read is lazy IO
  7192. # outside the greenlet -- MissingGreenlet, which would turn
  7193. # this cosmetic failure into a dispatch crash in exactly the
  7194. # "database is locked" case the block exists for (#1853).
  7195. # The nozzle guard, the upload and the start all keep
  7196. # reading item, archive and printer, so all three go back
  7197. # into the session before falling through.
  7198. item = await db.get(PrintQueueItem, queue_item_id)
  7199. archive = await db.get(PrintArchive, archive_id)
  7200. printer = await db.get(Printer, item.printer_id) if item else None
  7201. if not item or not archive or not printer:
  7202. logger.error(
  7203. "Queue item %s: item, archive %s or printer gone after the photo rollback",
  7204. queue_item_id,
  7205. archive_id,
  7206. )
  7207. return
  7208. else:
  7209. # Neither archive nor library file specified
  7210. item.status = "failed"
  7211. item.error_message = "No source file specified"
  7212. item.completed_at = datetime.now(timezone.utc)
  7213. await db.commit()
  7214. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  7215. await self._power_off_if_needed(db, item)
  7216. return
  7217. # Check file exists on disk
  7218. if not file_path.exists():
  7219. item.status = "failed"
  7220. item.error_message = "Source file not found on disk"
  7221. item.completed_at = datetime.now(timezone.utc)
  7222. await db.commit()
  7223. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  7224. await self._power_off_if_needed(db, item)
  7225. return
  7226. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  7227. # size dispatched to a printer with a different nozzle installed is
  7228. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  7229. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  7230. # gives the user no idea what went wrong. Catch it here, before we spend
  7231. # time preheating and uploading, and fail with an actionable message.
  7232. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  7233. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  7234. # the printer hasn't reported its nozzles yet, we fall through and let the
  7235. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  7236. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  7237. # as one of the two hotends is a 0.6.
  7238. #
  7239. # On a tool-changer model (H2C) the nozzles parked in the rack count too
  7240. # (#2885): the printer fetches one as part of starting the print, so the
  7241. # set to test against is "reachable", not "currently mounted". This runs
  7242. # well before the rack picker at the bottom of this method, so without
  7243. # the rack in scope here that picker never got the chance to run.
  7244. sliced_nozzle = archive.nozzle_diameter if archive else None
  7245. if sliced_nozzle:
  7246. nozzle_status = printer_manager.get_status(item.printer_id)
  7247. installed = _installed_nozzle_diameters(nozzle_status)
  7248. rack = _rack_nozzle_diameters(nozzle_status)
  7249. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed, rack)
  7250. if mismatch_msg:
  7251. item.status = "failed"
  7252. item.error_message = mismatch_msg
  7253. item.completed_at = datetime.now(timezone.utc)
  7254. await db.commit()
  7255. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  7256. await notification_service.on_queue_job_failed(
  7257. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7258. printer_id=printer.id,
  7259. printer_name=printer.name,
  7260. reason=mismatch_msg,
  7261. db=db,
  7262. )
  7263. try:
  7264. await ws_manager.send_queue_item_failed(
  7265. user_id=item.created_by_id,
  7266. queue_item_id=item.id,
  7267. printer_id=item.printer_id,
  7268. reason="nozzle_mismatch",
  7269. )
  7270. except Exception:
  7271. pass
  7272. await self._power_off_if_needed(db, item)
  7273. return
  7274. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  7275. # bed (and chamber, if applicable) is at temperature when the firmware
  7276. # starts the actual print routine. Best-effort: any failure logs and
  7277. # falls through to the normal upload+start path rather than turning a
  7278. # configuration issue into a failed queue item.
  7279. # Returns False only when the item was cancelled or deleted while the
  7280. # stage was holding at temperature. Uploading and starting it anyway
  7281. # would print a job the user has already called off, so abandon the
  7282. # dispatch here; `_dispatch_one`'s finally clause unwinds the heaters.
  7283. if not await self._preheat_and_soak(db, item, printer, archive):
  7284. logger.info("Queue item %s: dispatch abandoned — cancelled during preheat", item.id)
  7285. return
  7286. # See `_effective_plate_id` for why this is resolved once here rather
  7287. # than each site below repeating `item.plate_id or 1`.
  7288. effective_plate_id = _effective_plate_id(item.plate_id, file_path)
  7289. # G-code injection for auto-print systems (#422)
  7290. injected_path = None
  7291. # #2547: tracked separately from `injected_path`, which is also set when
  7292. # only a START snippet was injected. Only an END snippet changes what the
  7293. # camera sees at print completion.
  7294. end_gcode_injected = False
  7295. if item.gcode_injection:
  7296. try:
  7297. snippets_raw = await self._get_setting(db, "gcode_snippets")
  7298. if snippets_raw:
  7299. snippets = json.loads(snippets_raw)
  7300. model_snippets = snippets.get(printer.model, {})
  7301. start_gc = (model_snippets.get("start_gcode") or "").strip()
  7302. end_gc = (model_snippets.get("end_gcode") or "").strip()
  7303. if start_gc or end_gc:
  7304. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  7305. injected_path = inject_gcode_into_3mf(
  7306. file_path, effective_plate_id, start_gc or None, end_gc or None
  7307. )
  7308. if injected_path:
  7309. file_path = injected_path
  7310. end_gcode_injected = bool(end_gc)
  7311. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  7312. else:
  7313. logger.warning(
  7314. "Queue item %s: G-code injection returned no result, using original", item.id
  7315. )
  7316. except Exception as e:
  7317. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  7318. # #2547: the finish-photo path can't learn from telemetry that this print
  7319. # ends with user End G-code — which means the plate may be gone by the
  7320. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  7321. # the print once the printer confirms it running.
  7322. if end_gcode_injected:
  7323. print_dispatch_context.mark_pending(printer.id)
  7324. # Upload to root directory (not /cache/) - the start_print command references
  7325. # files by name only (ftp://{filename}), so they must be in the root
  7326. remote_filename = derive_remote_filename(filename)
  7327. remote_path = f"/{remote_filename}"
  7328. # Get FTP retry settings
  7329. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  7330. logger.info(
  7331. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  7332. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  7333. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  7334. )
  7335. # Release the pooled DB connection before the FTP delete/upload (#2572).
  7336. # Every read this method needs (printer, archive/library, preheat) is
  7337. # done, and the library-file branch already committed its archive
  7338. # creation. Without this the transaction opened by the first SELECT above
  7339. # stays "idle in transaction" for the entire upload — multiple seconds
  7340. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  7341. # a farm dispatching many jobs at once then exhausts the pool. This was
  7342. # correlated to an exact idle-in-transaction session on a 93-printer farm
  7343. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  7344. # readable; the status writes below (upload-failure path and the
  7345. # pending->printing CAS) transparently open a fresh transaction.
  7346. await db.commit()
  7347. # Delete existing file if present (avoids 553 error on overwrite)
  7348. try:
  7349. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  7350. delete_result = await delete_file_async(
  7351. printer.ip_address,
  7352. printer.access_code,
  7353. remote_path,
  7354. socket_timeout=ftp_timeout,
  7355. printer_model=printer.model,
  7356. # This delete and the upload below are one bounded, user-initiated
  7357. # unit -- at most nine connections -- so neither skips on the
  7358. # handshake cool-off the opportunistic sweeps rely on. In #2898's
  7359. # trace this delete took the TLS failure and armed the cool-off,
  7360. # and the upload's four attempts were then spent against it
  7361. # without a socket being opened.
  7362. respect_handshake_cooloff=False,
  7363. )
  7364. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  7365. except Exception as e:
  7366. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  7367. # Dispatch toast — announce the upload start with the total byte
  7368. # count so the frontend can render an honest progress bar.
  7369. toast_uid = item.created_by_id
  7370. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  7371. try:
  7372. total_bytes = file_path.stat().st_size
  7373. except OSError:
  7374. total_bytes = 0
  7375. try:
  7376. await ws_manager.send_queue_item_uploading(
  7377. user_id=toast_uid,
  7378. queue_item_id=item.id,
  7379. printer_id=item.printer_id,
  7380. printer_name=printer.name,
  7381. file_name=toast_file_name,
  7382. total_bytes=total_bytes,
  7383. )
  7384. except Exception:
  7385. pass # toast is best-effort
  7386. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  7387. # A deadline expiry gets its own message: "check your SD card" is the
  7388. # wrong advice for a link that was simply too slow to finish (#2529).
  7389. upload_error: str | None = None
  7390. # Why the upload failed, straight from the client rather than inferred.
  7391. # Owned here, so a background fetch for another print cannot overwrite
  7392. # it between the failure and the sentence built from it (#2899).
  7393. upload_failure = FtpFailureReport()
  7394. try:
  7395. if ftp_retry_enabled:
  7396. uploaded = await with_ftp_retry(
  7397. upload_file_async,
  7398. printer.ip_address,
  7399. printer.access_code,
  7400. file_path,
  7401. remote_path,
  7402. socket_timeout=ftp_timeout,
  7403. printer_model=printer.model,
  7404. progress_callback=progress_bridge,
  7405. respect_handshake_cooloff=False,
  7406. failure=upload_failure,
  7407. max_retries=ftp_retry_count,
  7408. retry_delay=ftp_retry_delay,
  7409. operation_name=f"Upload print to {printer.name}",
  7410. )
  7411. else:
  7412. uploaded = await upload_file_async(
  7413. printer.ip_address,
  7414. printer.access_code,
  7415. file_path,
  7416. remote_path,
  7417. socket_timeout=ftp_timeout,
  7418. printer_model=printer.model,
  7419. progress_callback=progress_bridge,
  7420. respect_handshake_cooloff=False,
  7421. failure=upload_failure,
  7422. )
  7423. except UploadCancelled as e:
  7424. uploaded = False
  7425. upload_error = (
  7426. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  7427. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  7428. )
  7429. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  7430. except Exception as e:
  7431. uploaded = False
  7432. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  7433. # Clean up injected temp file after upload attempt
  7434. if injected_path and injected_path.exists():
  7435. injected_path.unlink(missing_ok=True)
  7436. if not uploaded:
  7437. # This used to be one string for every upload failure, telling
  7438. # everyone to check the SD card. The client knows which of seven
  7439. # things went wrong and logs each one differently; it just had no
  7440. # way to say so here, so the card got named even for a TLS
  7441. # handshake that never reached the printer's filesystem (#2899).
  7442. error_msg = upload_error or describe_upload_failure(upload_failure.failure)
  7443. failure = upload_failure.failure
  7444. if upload_error is None and failure is not None and failure.kind in _UPLOAD_REQUEUE_KINDS:
  7445. await self._requeue_after_upload_refused(db, item, printer, error_msg, toast_uid)
  7446. return
  7447. item.status = "failed"
  7448. item.error_message = error_msg
  7449. item.completed_at = datetime.now(timezone.utc)
  7450. await db.commit()
  7451. logger.error(
  7452. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  7453. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  7454. )
  7455. # Send failure notification
  7456. await notification_service.on_queue_job_failed(
  7457. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7458. printer_id=printer.id,
  7459. printer_name=printer.name,
  7460. # The same sentence the queue shows. A push notification saying
  7461. # something different from the UI is its own small bug (#2899).
  7462. reason=error_msg,
  7463. db=db,
  7464. )
  7465. try:
  7466. await ws_manager.send_queue_item_failed(
  7467. user_id=toast_uid,
  7468. queue_item_id=item.id,
  7469. printer_id=item.printer_id,
  7470. reason="upload_failed",
  7471. )
  7472. except Exception:
  7473. pass
  7474. await self._power_off_if_needed(db, item)
  7475. return
  7476. # The printer took a file, so any run of refused uploads is over: the
  7477. # next refusal starts again at the shortest backoff, and notifies (#3210).
  7478. self._upload_refusals.pop(printer.id, None)
  7479. self._upload_refusal_notified.discard(printer.id)
  7480. # Parse AMS mapping if stored
  7481. ams_mapping = None
  7482. if item.ams_mapping:
  7483. try:
  7484. ams_mapping = json.loads(item.ams_mapping)
  7485. except json.JSONDecodeError:
  7486. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  7487. # Register as expected print so we don't create a duplicate archive
  7488. # Only applicable for archive-based prints
  7489. if archive:
  7490. from backend.app.main import register_expected_print
  7491. register_expected_print(
  7492. item.printer_id,
  7493. remote_filename,
  7494. archive.id,
  7495. ams_mapping=ams_mapping,
  7496. created_by_id=item.created_by_id,
  7497. cost_center_id=item.cost_center_id,
  7498. # The plate actually dispatched, not the queue item's raw
  7499. # column: on None, `register_expected_print` stores nothing,
  7500. # and `extract_filament_usage_from_3mf` then books every
  7501. # filament in the file rather than the one plate that printed.
  7502. plate_id=effective_plate_id,
  7503. )
  7504. # Registration happens before the print command by necessity (the
  7505. # printer can report the print before the send returns), so record
  7506. # what to undo if we never get as far as sending. `_dispatch_one`
  7507. # rolls back anything still pending here on every exit — exception,
  7508. # early return, or cancel winning the CAS below.
  7509. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  7510. # Propagate the queue item's owner into printer_manager so the
  7511. # print-complete callback can credit the user in the PrintLogEntry
  7512. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  7513. # items) or when the user clicks the manual-start button.
  7514. await self._propagate_owner_to_printer_manager(db, item)
  7515. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  7516. # This prevents phantom reprints if the backend crashes/restarts after the
  7517. # print command is sent but before the status update is committed.
  7518. # If we crash after this commit but before start_print(), the item will be
  7519. # in "printing" status without actually printing - but that's safer than
  7520. # accidentally reprinting the same file hours later.
  7521. #
  7522. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  7523. # initial pending read at the top of check_queue and this point) flips
  7524. # the row to "cancelled" in a separate session. Without the WHERE
  7525. # status='pending' clause, the unconditional update here would silently
  7526. # overwrite that cancellation and we'd ship the MQTT start_print below
  7527. # — printer obeys, user sees "I pressed cancel and the print started".
  7528. # rowcount==0 means the user won the race; bail out, best-effort delete
  7529. # the file we just uploaded, do NOT send start_print.
  7530. now_utc = datetime.now(timezone.utc)
  7531. billing_run_id = str(uuid.uuid4())
  7532. cas = await db.execute(
  7533. update(PrintQueueItem)
  7534. .where(PrintQueueItem.id == item.id)
  7535. .where(PrintQueueItem.status == "pending")
  7536. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  7537. )
  7538. await db.commit()
  7539. if cas.rowcount == 0:
  7540. logger.info(
  7541. "Queue item %s no longer pending at print-command time "
  7542. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  7543. item.id,
  7544. )
  7545. try:
  7546. await delete_file_async(
  7547. printer.ip_address,
  7548. printer.access_code,
  7549. remote_path,
  7550. socket_timeout=ftp_timeout,
  7551. printer_model=printer.model,
  7552. )
  7553. except Exception as cleanup_err:
  7554. logger.debug(
  7555. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  7556. item.id,
  7557. cleanup_err,
  7558. )
  7559. try:
  7560. await ws_manager.send_queue_item_failed(
  7561. user_id=toast_uid,
  7562. queue_item_id=item.id,
  7563. printer_id=item.printer_id,
  7564. reason="cancelled_mid_dispatch",
  7565. )
  7566. except Exception:
  7567. pass
  7568. return
  7569. # Sync the in-memory item so subsequent code that reads item.status /
  7570. # item.started_at sees the values we just persisted.
  7571. item.status = "printing"
  7572. item.started_at = now_utc
  7573. item.billing_run_id = billing_run_id
  7574. if archive is not None:
  7575. archive.billing_run_id = billing_run_id
  7576. # Legacy transaction deletion used an archive-wide skip flag.
  7577. # A newly dispatched run has its own UUID/tombstone, so it must be
  7578. # billable independently of any older deleted run on this archive.
  7579. archive.wallet_charge_skipped = False
  7580. # Persist before MQTT send so completion and restart recovery can
  7581. # always recover the internal billing identity.
  7582. await db.commit()
  7583. for cleanup_path in cleanup_disk_paths:
  7584. try:
  7585. if cleanup_path.exists():
  7586. cleanup_path.unlink()
  7587. except OSError as cleanup_err:
  7588. logger.warning(
  7589. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  7590. json.dumps(
  7591. {
  7592. "queue_item_id": item.id,
  7593. "path": str(cleanup_path),
  7594. "error": str(cleanup_err),
  7595. },
  7596. sort_keys=True,
  7597. ),
  7598. )
  7599. # Clear the awaiting-plate-clear flag now that we're starting a new print
  7600. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  7601. # #1898: with the opt-in default-good setting, moving on to the next
  7602. # print resolves the previous print's unanswered outcome prompt as
  7603. # "good" — this path also covers the camera-based plate detection,
  7604. # which releases the gate by allowing dispatch rather than by an
  7605. # explicit acknowledgment. Rides on the dispatch transaction.
  7606. if await self._get_bool_setting(db, "confirm_default_good_on_plate_clear", default=False):
  7607. from backend.app.services.print_confirmation import resolve_pending_confirmation_as_good
  7608. await resolve_pending_confirmation_as_good(db, item.printer_id)
  7609. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  7610. # Capture state before dispatch so the watchdog can detect whether the
  7611. # printer actually transitioned (#967). Also capture subtask_id so the
  7612. # watchdog can recognise "command landed but state hasn't flipped yet"
  7613. # on slow H2D transitions (#1078).
  7614. pre_status = printer_manager.get_status(item.printer_id)
  7615. pre_state = getattr(pre_status, "state", None) if pre_status else None
  7616. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  7617. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  7618. # #1721: respect the user's explicit timelapse choice. The #1397
  7619. # force-on at dispatch was removed because it caused per-layer nozzle
  7620. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  7621. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  7622. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  7623. # FINISH-state fallback — no need to force a video.
  7624. effective_timelapse = bool(item.timelapse)
  7625. # Nozzle-rack fallback (#2800). A job that never passed through the
  7626. # Virtual Printer carries no Bambu Studio nozzle pick, and an H2C then
  7627. # dispatches with no nozzle field at all and chooses for itself — which
  7628. # is how a print levelled on one hotend and then printed on another,
  7629. # millimetres above the plate. Derive the per-slot extruder assignment
  7630. # from the file being dispatched.
  7631. #
  7632. # Done here rather than at queue time because this is the first point
  7633. # that knows both the actual printer and the actual file: an item can
  7634. # be created without a printer (model-based assignment), reassigned
  7635. # afterwards, or have its file swapped for a G-code-injected copy just
  7636. # above. Every queue-creation path — the print dialog, a bulk library
  7637. # add, the webhook, a pipeline run — is covered by the one call.
  7638. # Skipped when the item already carries a Bambu Studio capture: that
  7639. # one wins downstream anyway, so reading the 3MF again would be work
  7640. # thrown away on every dispatch.
  7641. # Rack position resolution (#1784), tried before the #2800 fallback
  7642. # below because it can express what that one cannot: a plate wanting a
  7643. # *different* hotend off the rack per filament group. The position per
  7644. # group is the operator's pick — the 3MF states it nowhere, proven by
  7645. # sending one plate twice with different picks and finding the two
  7646. # files identical bar float noise — so it is resolved here against the
  7647. # rack as it stands right now, after the upload, not at queue time.
  7648. resolved_nozzle_mapping = None
  7649. if not item.nozzle_mapping and file_path is not None and is_nozzle_rack_model(printer.model):
  7650. rack_plan = extract_rack_plan_from_3mf(file_path, plate_id=effective_plate_id)
  7651. if rack_plan is not None:
  7652. try:
  7653. stored_choice = json.loads(item.nozzle_rack_choice) if item.nozzle_rack_choice else {}
  7654. except (json.JSONDecodeError, TypeError):
  7655. stored_choice = {}
  7656. logger.warning(
  7657. "Queue item %s: unreadable nozzle_rack_choice %r, assigning rack positions instead",
  7658. item.id,
  7659. item.nozzle_rack_choice,
  7660. )
  7661. # JSON object keys are strings; the groups are ints.
  7662. choice: dict[int, int] = {}
  7663. for key, value in (stored_choice or {}).items():
  7664. try:
  7665. choice[int(key)] = int(value)
  7666. except (TypeError, ValueError):
  7667. continue
  7668. live_rack = getattr(printer_manager.get_status(item.printer_id), "nozzle_rack", None) or []
  7669. resolved_nozzle_mapping, rack_error = resolve_rack_plan_mapping(
  7670. rack_plan.slot_groups, rack_plan.group_dicts(), choice, live_rack
  7671. )
  7672. if resolved_nozzle_mapping is None and choice:
  7673. # An explicit pick that no longer holds stops the print. The
  7674. # operator named a hotend; printing from a different one is
  7675. # how a plate gets levelled on one nozzle and drawn with
  7676. # another, millimetres above the bed. Nothing has been sent
  7677. # to the printer yet, so failing here costs only the upload.
  7678. item.status = "failed"
  7679. item.error_message = (
  7680. f"Nozzle rack pick no longer fits the printer: {rack_error}. "
  7681. "Edit the item to choose another position."
  7682. )
  7683. item.completed_at = datetime.now(timezone.utc)
  7684. await db.commit()
  7685. logger.warning(
  7686. "Queue item %s: refusing to dispatch to %s — %s (chose %s, rack %s)",
  7687. item.id,
  7688. printer.name,
  7689. rack_error,
  7690. choice,
  7691. [slot.get("id") for slot in live_rack],
  7692. )
  7693. await notification_service.on_queue_job_failed(
  7694. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7695. printer_id=printer.id,
  7696. printer_name=printer.name,
  7697. reason=item.error_message,
  7698. db=db,
  7699. )
  7700. try:
  7701. await ws_manager.send_queue_item_failed(
  7702. user_id=toast_uid,
  7703. queue_item_id=item.id,
  7704. printer_id=item.printer_id,
  7705. reason="nozzle_rack_pick_stale",
  7706. )
  7707. except Exception:
  7708. pass # Best-effort — don't fail the error handler
  7709. # The file is already on the SD card by this point, and a
  7710. # 3MF left there is a phantom print waiting to be started
  7711. # from the touchscreen. Same cleanup the start_print
  7712. # failure path below does, for the same reason.
  7713. try:
  7714. await delete_file_async(
  7715. printer.ip_address,
  7716. printer.access_code,
  7717. remote_path,
  7718. printer_model=printer.model,
  7719. )
  7720. except Exception:
  7721. pass # Best-effort — don't fail the error handler
  7722. return
  7723. if resolved_nozzle_mapping is None:
  7724. # Nothing was picked and nothing could be assigned. Falls
  7725. # through to the #2800 path, which is what ran before this
  7726. # existed — strictly not worse than today.
  7727. logger.info(
  7728. "Queue item %s: no rack positions assignable (%s); falling back",
  7729. item.id,
  7730. rack_error,
  7731. )
  7732. else:
  7733. logger.info(
  7734. "Queue item %s: rack mapping %s (groups %s, chosen %s)",
  7735. item.id,
  7736. resolved_nozzle_mapping,
  7737. rack_plan.slot_groups,
  7738. choice or "auto",
  7739. )
  7740. nozzle_slot_extruders = None
  7741. if (
  7742. not item.nozzle_mapping
  7743. and resolved_nozzle_mapping is None
  7744. and file_path is not None
  7745. and is_nozzle_rack_model(printer.model)
  7746. ):
  7747. slot_extruders = extract_slot_extruders_from_3mf(file_path, plate_id=effective_plate_id)
  7748. if slot_extruders:
  7749. nozzle_slot_extruders = json.dumps(slot_extruders)
  7750. # Every filament this plate prints is on the external spool -> the print
  7751. # must go out with use_ams=False. The firmware answers use_ams=true plus
  7752. # a mapping it cannot resolve with 07FF_8012 "Failed to get AMS mapping
  7753. # table", which is what held the reporter's P1S at Heatbed preheating
  7754. # for ten minutes before it gave up (#3087). The MQTT command builder
  7755. # already downgrades a mapping that is *only* external ([254]), but a
  7756. # multi-filament project pads the slots this plate does not print with
  7757. # -1 — BambuStudio's own convention — and down there a -1 is
  7758. # indistinguishable from a slot that never resolved, which must never be
  7759. # sent to the spool holder (#2589). Here the plate's filament list says
  7760. # which is which, so the answer is exact rather than a guess.
  7761. #
  7762. # Deliberately narrow: this fires only when every consumed slot is an
  7763. # explicit 254/255. A consumed slot that did not resolve leaves use_ams
  7764. # alone and the firmware still rejects the print, exactly as today. And
  7765. # only for single-nozzle printers, mirroring the builder's own reconcile
  7766. # — on a dual-nozzle machine use_ams is which extruder to feed, not
  7767. # whether to use the AMS, so it is not ours to rewrite.
  7768. effective_use_ams = item.use_ams
  7769. if (
  7770. effective_use_ams
  7771. and ams_mapping
  7772. and file_path is not None
  7773. # Cheap gate before opening the file: with nothing on the spool
  7774. # holder anywhere in the mapping, no subset of it can be all
  7775. # external, so most dispatches never pay for the parse. The
  7776. # isinstance also keeps a malformed stored mapping (a bare number
  7777. # from a hand-edited row) failing where it always failed, in the
  7778. # command builder, rather than here.
  7779. and isinstance(ams_mapping, list)
  7780. and any(_is_external_tray(t) for t in ams_mapping)
  7781. and not _might_be_dual_nozzle(printer.model, pre_status)
  7782. ):
  7783. from backend.app.services.filament_requirements import extract_filament_requirements
  7784. consumed = _consumed_mapping_entries(
  7785. ams_mapping, extract_filament_requirements(file_path, plate_id=effective_plate_id)
  7786. )
  7787. if consumed and all(_is_external_tray(t) for t in consumed):
  7788. effective_use_ams = False
  7789. logger.info(
  7790. "Queue item %s: every filament plate %s prints is on the external spool "
  7791. "(mapping %s) — dispatching with use_ams=False (#3087)",
  7792. item.id,
  7793. effective_plate_id,
  7794. ams_mapping,
  7795. )
  7796. # A slot that lost its K-profile selection (a power cycle resets every
  7797. # slot to the default K) would print on the default. The idle check in
  7798. # the status handler normally restores it first, but nothing guarantees
  7799. # it ran before this dispatch (#3219). Unthrottled: once per job.
  7800. # Never allowed to stop the print it is protecting.
  7801. try:
  7802. await kprofile_drift.reapply_lost_kprofiles(item.printer_id, _used_global_tray_ids(item), throttle=False)
  7803. except Exception:
  7804. logger.exception("Queue item %s: K-profile check before dispatch failed", item.id)
  7805. # Start the print with AMS mapping, plate_id and print options.
  7806. # nozzle_mapping rides through verbatim — JSON string captured from
  7807. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  7808. # parses + injects it only for dual-nozzle models so a null on every
  7809. # other model is a transparent pass-through. The rack fallback is
  7810. # resolved down there too, where the live rack position is known.
  7811. started = printer_manager.start_print(
  7812. item.printer_id,
  7813. remote_filename,
  7814. plate_id=effective_plate_id,
  7815. ams_mapping=ams_mapping,
  7816. bed_levelling=item.bed_levelling,
  7817. flow_cali=item.flow_cali,
  7818. vibration_cali=item.vibration_cali,
  7819. layer_inspect=item.layer_inspect,
  7820. timelapse=effective_timelapse,
  7821. use_ams=effective_use_ams,
  7822. nozzle_offset_cali=item.nozzle_offset_cali,
  7823. nozzle_mapping=item.nozzle_mapping
  7824. or (json.dumps(resolved_nozzle_mapping) if resolved_nozzle_mapping else None),
  7825. nozzle_slot_extruders=nozzle_slot_extruders,
  7826. )
  7827. if started:
  7828. # The command is away, so the expectation is now legitimate and must
  7829. # survive. Anything still in this dict when _dispatch_one exits gets
  7830. # rolled back.
  7831. self._unconfirmed_expected_print.pop(item.id, None)
  7832. self._unconfirmed_budget_reservations.discard(item.id)
  7833. # Handoff to the print's own gcode: keep whatever preheat set (bed
  7834. # target, chamber target, airduct heating) — the gcode owns
  7835. # heater/flap control from here. Clearing the pin prevents
  7836. # `_dispatch_one`'s finally from unwinding a live print.
  7837. self._preheat_pin.pop(item.printer_id, None)
  7838. self._preheat_pin_bed.pop(item.printer_id, None)
  7839. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  7840. # No dispatch-toast event here: the legacy bg-dispatch path kept
  7841. # status='processing' from upload start until the printer acked
  7842. # (or timed out). The frontend derives "Awaiting printer…" purely
  7843. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  7844. # event would push the status chip out of 'PROCESSING' prematurely
  7845. # — which is exactly what the screenshot at #1625-followup
  7846. # complained about.
  7847. # Register the local 3MF in the cover-cache so /cover skips FTP
  7848. # (#1166 follow-up). file_path was resolved earlier from either the
  7849. # archive or the library file row.
  7850. if file_path is not None:
  7851. cache_3mf_download(item.printer_id, remote_filename, file_path)
  7852. # Hold the printer against further dispatches until the watchdog
  7853. # confirms the printer transitioned (or until the hard timeout).
  7854. # Prevents multi-plate batches from triple-dispatching onto the
  7855. # same H2D Pro while it digests the first project_file (#1157).
  7856. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  7857. # Watchdog: if the printer never transitions out of pre_state AND
  7858. # never advances subtask_id, the MQTT publish was accepted locally but
  7859. # didn't reach the printer (half-broken session — same shape as
  7860. # #887/#936). Revert the queue item so the next dispatch can pick it
  7861. # up instead of leaving it stuck in "printing" (#967). subtask_id
  7862. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  7863. # that would otherwise cause the item to re-dispatch as a reprint
  7864. # of the just-finished job (#1078).
  7865. if pre_state:
  7866. spawn_background_task(
  7867. self._watchdog_print_start(
  7868. item.id,
  7869. item.printer_id,
  7870. pre_state,
  7871. pre_subtask_id,
  7872. pre_gcode_file,
  7873. created_by_id=toast_uid,
  7874. ),
  7875. name=f"watchdog-print-start-{item.id}",
  7876. )
  7877. # Get estimated time for notification.
  7878. #
  7879. # This used to fall back to `library_file.print_time_seconds`, a column
  7880. # LibraryFile does not have — the print time it knows about lives in
  7881. # `file_metadata`. So a library print whose archive carried no parseable
  7882. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  7883. # AttributeError right here, *after* the printer had already been sent
  7884. # the job: the started-notification never fired, and the exception
  7885. # unwound the whole queue pass, so every other printer still waiting to
  7886. # be dispatched on that tick silently missed its turn.
  7887. #
  7888. # The queue item caches the print time at creation ("Cached from
  7889. # archive/library"), which is the value this was reaching for.
  7890. estimated_time = None
  7891. if archive and archive.print_time_seconds:
  7892. estimated_time = archive.print_time_seconds
  7893. elif item.print_time_seconds:
  7894. estimated_time = item.print_time_seconds
  7895. # Send job started notification
  7896. await notification_service.on_queue_job_started(
  7897. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7898. printer_id=printer.id,
  7899. printer_name=printer.name,
  7900. db=db,
  7901. estimated_time=estimated_time,
  7902. )
  7903. # MQTT relay - publish queue job started
  7904. try:
  7905. from backend.app.services.mqtt_relay import mqtt_relay
  7906. await mqtt_relay.on_queue_job_started(
  7907. job_id=item.id,
  7908. filename=filename,
  7909. printer_id=printer.id,
  7910. printer_name=printer.name,
  7911. printer_serial=printer.serial_number,
  7912. )
  7913. except Exception:
  7914. pass # Don't fail if MQTT fails
  7915. else:
  7916. # Clean up uploaded file from SD card to prevent phantom prints
  7917. try:
  7918. await delete_file_async(
  7919. printer.ip_address,
  7920. printer.access_code,
  7921. remote_path,
  7922. printer_model=printer.model,
  7923. )
  7924. except Exception:
  7925. pass # Best-effort — don't fail the error handler
  7926. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  7927. # state can flip from idle to active in the window between the
  7928. # pre-dispatch check above and this publish (the FTP upload takes
  7929. # seconds); start_print() then refuses to send project_file to the
  7930. # now-busy printer and returns False. Failing the item here would be
  7931. # wrong — the printer is fine, it is simply busy — so revert to
  7932. # pending and let a later tick dispatch it once the printer is idle,
  7933. # exactly like the pre-dispatch guard. Only a start_print() False on
  7934. # an idle/unknown printer is a genuine command failure.
  7935. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  7936. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  7937. logger.info(
  7938. "Queue item %s: printer %s became busy (state=%s) before the start "
  7939. "command was sent — deferring, reverting item to pending (#2598)",
  7940. item.id,
  7941. item.printer_id,
  7942. post_dispatch_state,
  7943. )
  7944. item.status = "pending"
  7945. item.started_at = None
  7946. await db.commit()
  7947. return
  7948. # Print command failed - revert status
  7949. item.status = "failed"
  7950. item.error_message = "Failed to send print command to printer"
  7951. item.completed_at = datetime.now(timezone.utc)
  7952. await db.commit()
  7953. logger.error(
  7954. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  7955. f"printer_manager.start_print() returned False. "
  7956. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  7957. f"Check printer status and backend logs for details."
  7958. )
  7959. # Send failure notification
  7960. await notification_service.on_queue_job_failed(
  7961. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  7962. printer_id=printer.id,
  7963. printer_name=printer.name,
  7964. reason="Failed to send print command to printer - check printer connection and status",
  7965. db=db,
  7966. )
  7967. try:
  7968. await ws_manager.send_queue_item_failed(
  7969. user_id=toast_uid,
  7970. queue_item_id=item.id,
  7971. printer_id=item.printer_id,
  7972. reason="start_command_failed",
  7973. )
  7974. except Exception:
  7975. pass
  7976. await self._power_off_if_needed(db, item)
  7977. @staticmethod
  7978. async def _watchdog_print_start(
  7979. queue_item_id: int,
  7980. printer_id: int,
  7981. pre_state: str,
  7982. pre_subtask_id: str | None = None,
  7983. pre_gcode_file: str | None = None,
  7984. timeout: float = 90.0,
  7985. phase_b_timeout: float = 180.0,
  7986. poll_interval: float = 3.0,
  7987. created_by_id: int | None = None,
  7988. ) -> None:
  7989. """Revert a queue item if the printer never acknowledges the start command.
  7990. Bambuddy optimistically marks the queue item as "printing" right after the
  7991. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  7992. Phase A (up to ``timeout``): wait for either an active-state transition
  7993. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  7994. primary signal; subtask_id advance handles the H2D case where state can
  7995. sit at FINISH for ~50 s after the printer accepted ``project_file``
  7996. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  7997. was lost on a half-broken session (#887/#936) — revert and force
  7998. reconnect (the #967 recovery path).
  7999. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  8000. alone): keep watching for the active-state transition. subtask_id alone
  8001. proves the file landed but not that the printer started — and a printer
  8002. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  8003. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  8004. used to leave the queue item stuck in 'printing' forever because the
  8005. old watchdog returned success as soon as subtask_id advanced. If Phase
  8006. B times out, revert the queue item so the user can retry without
  8007. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  8008. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8009. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  8010. transitions that also don't emit an early subtask_id tick.
  8011. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  8012. refuses to verify our commands will never start this job or any other,
  8013. so waiting out the full 270 s and re-uploading the 3MF twice more only
  8014. burns an upload slot the rest of the farm is queued behind — that path
  8015. is for a printer that might still come good, which this one cannot
  8016. (#2732). It fails the item on the spot with the actual reason instead.
  8017. """
  8018. last_status = None
  8019. landed_on_subtask = False
  8020. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  8021. # every push carrying an `hms` key, so the fault can come and go between
  8022. # 3-second polls. Seeing it once inside the dispatch window is enough.
  8023. command_rejected = False
  8024. # Latched for the same reason as command_rejected: drying can finish, or
  8025. # be stopped by the user, part-way through the dispatch window. Seeing it
  8026. # once is what matters — it is the state the printer was in when it
  8027. # declined to start (#2758).
  8028. drying_ams_ids: list[int] = []
  8029. deadline = time.monotonic() + timeout
  8030. while time.monotonic() < deadline:
  8031. await asyncio.sleep(poll_interval)
  8032. status = printer_manager.get_status(printer_id)
  8033. if not status:
  8034. # Printer disconnected — don't mess with the DB. Drop the
  8035. # in-memory dispatch hold too so a fresh dispatch can retry
  8036. # once the printer comes back; the hard timeout would
  8037. # otherwise hold the printer unnecessarily.
  8038. scheduler._release_dispatch_hold(printer_id)
  8039. return
  8040. last_status = status
  8041. if status.state in _ACTIVE_PRINT_STATES:
  8042. # Printer is actively processing the job — release the
  8043. # post-dispatch hold so the next pending item for this printer
  8044. # can be evaluated normally. We do NOT accept arbitrary state
  8045. # transitions: a printer going FINISH -> IDLE (user dismissed
  8046. # the post-print prompt without accepting our project_file)
  8047. # would otherwise look like "command landed" and leave the
  8048. # queue item stuck in 'printing' forever (#1370).
  8049. scheduler._release_dispatch_hold(printer_id)
  8050. try:
  8051. await ws_manager.send_queue_item_acked(
  8052. user_id=created_by_id,
  8053. queue_item_id=queue_item_id,
  8054. printer_id=printer_id,
  8055. )
  8056. except Exception:
  8057. pass
  8058. return
  8059. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8060. # Checked only after the active-state exit above: a stale HMS left
  8061. # over from an earlier job must never abort a print that is visibly
  8062. # running. An actually-refused command leaves the printer idle, so
  8063. # this ordering costs the detection nothing.
  8064. if _mqtt_commands_rejected(status):
  8065. command_rejected = True
  8066. break
  8067. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  8068. # Phase A exit — printer accepted the file (subtask_id flipped
  8069. # to our submission id). Don't return yet: the printer may
  8070. # have accepted the command but never actually start (e.g.
  8071. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  8072. # B watches for the active-state transition.
  8073. landed_on_subtask = True
  8074. break
  8075. if landed_on_subtask and not command_rejected:
  8076. phase_b_deadline = time.monotonic() + phase_b_timeout
  8077. while time.monotonic() < phase_b_deadline:
  8078. await asyncio.sleep(poll_interval)
  8079. status = printer_manager.get_status(printer_id)
  8080. if not status:
  8081. scheduler._release_dispatch_hold(printer_id)
  8082. return
  8083. last_status = status
  8084. if status.state in _ACTIVE_PRINT_STATES:
  8085. scheduler._release_dispatch_hold(printer_id)
  8086. try:
  8087. await ws_manager.send_queue_item_acked(
  8088. user_id=created_by_id,
  8089. queue_item_id=queue_item_id,
  8090. printer_id=printer_id,
  8091. )
  8092. except Exception:
  8093. pass
  8094. return
  8095. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  8096. # Same ordering rule as Phase A: a running print wins over a
  8097. # lingering HMS.
  8098. if _mqtt_commands_rejected(status):
  8099. command_rejected = True
  8100. break
  8101. # No active-state transition. Revert the item so the scheduler can retry.
  8102. # Drop the in-memory hold so the retry isn't blocked by it.
  8103. scheduler._release_dispatch_hold(printer_id)
  8104. # Logged on every failed dispatch window, not just the last one, so a
  8105. # support bundle shows the correlation from the first attempt rather than
  8106. # only after the retry budget is spent (#2758).
  8107. if drying_ams_ids:
  8108. logger.info(
  8109. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  8110. queue_item_id,
  8111. printer_id,
  8112. ", ".join(str(i) for i in drying_ams_ids),
  8113. )
  8114. # Four outcomes from the revert attempt, each routed differently:
  8115. # "reverted": row flipped from printing -> pending, run recovery
  8116. # "gave_up": same, but the retry budget is spent — row failed
  8117. # rather than pending, so it stops going round again
  8118. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  8119. # on_print_complete or user). Skip recovery entirely
  8120. # — the print clearly landed somewhere even if the
  8121. # watchdog didn't see the active-state transition.
  8122. # "revert_failed": SQLite contention exhausted retries. Still run
  8123. # recovery so the MQTT session gets a fresh client_id
  8124. # on the half-broken-session path.
  8125. #
  8126. # The retry budget (#2555): reverting to 'pending' hands the item straight
  8127. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  8128. # the watchdog again. For a printer that is genuinely wedged that loop never
  8129. # ends — the reporter had one printer "since this morning still not launch"
  8130. # — and each lap also consumes an upload slot that the other printers in the
  8131. # farm are waiting on. Retrying is right; retrying forever is not.
  8132. async def _do_revert(db):
  8133. item = await db.get(PrintQueueItem, queue_item_id)
  8134. if not item or item.status != "printing":
  8135. return "already_moved_on"
  8136. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  8137. item.started_at = None
  8138. # Charge the attempt to the candidate that was actually dispatched, so
  8139. # a cross-model item (#671) reaches for its other file next lap instead
  8140. # of retrying the printer that just failed to start. Matched by file
  8141. # because that is what the resolver copied onto the row.
  8142. if item.library_file_id is not None:
  8143. await db.execute(
  8144. update(PrintQueueVariant)
  8145. .where(PrintQueueVariant.queue_item_id == item.id)
  8146. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  8147. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  8148. )
  8149. if command_rejected:
  8150. # No retry budget for this one: the printer refused to verify the
  8151. # command, and re-uploading the same 3MF to the same printer will
  8152. # be refused the same way. Fail now with the fix rather than after
  8153. # three laps of a message about SD cards (#2732).
  8154. item.status = "failed"
  8155. item.error_message = (
  8156. "The printer rejected the print command: MQTT command verification failed "
  8157. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  8158. "then start the job again."
  8159. )
  8160. item.completed_at = datetime.now(timezone.utc)
  8161. await db.commit()
  8162. return "command_rejected"
  8163. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  8164. item.status = "failed"
  8165. if drying_ams_ids:
  8166. # #2758: the generic message below sent the reporter looking
  8167. # at the SD card while the actual obstacle — AMS units in a
  8168. # drying cycle — was on screen the whole time. Name what we
  8169. # observed and let the user judge it; Bambuddy does not stop
  8170. # the cycle itself, because on this hardware drying can run
  8171. # alongside a print and stopping it may not be the fix.
  8172. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  8173. item.error_message = (
  8174. f"The printer accepted the file but never started printing, after "
  8175. f"{item.dispatch_attempts} attempts. {units} "
  8176. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  8177. f"some printers refuse to begin a print while an AMS is in a drying "
  8178. f"cycle, and an AMS drying without its external power supply can also "
  8179. f"leave too little power for the start-of-print calibration. Stop the "
  8180. f"drying, or connect the AMS power supply, and start the job again."
  8181. )
  8182. else:
  8183. item.error_message = (
  8184. f"The printer accepted the file but never started printing, after "
  8185. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  8186. f"prompt or error, confirm its SD card is readable, and start the job again."
  8187. )
  8188. item.completed_at = datetime.now(timezone.utc)
  8189. await release_budget_reservation(
  8190. db,
  8191. source_type="print_queue",
  8192. source_id=item.id,
  8193. status="released",
  8194. )
  8195. await db.commit()
  8196. return "gave_up"
  8197. item.status = "pending"
  8198. await db.commit()
  8199. return "reverted"
  8200. try:
  8201. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  8202. except Exception as e:
  8203. logger.warning(
  8204. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  8205. "scheduler may keep treating this item as in-flight",
  8206. queue_item_id,
  8207. printer_id,
  8208. e,
  8209. )
  8210. revert_outcome = "revert_failed"
  8211. if revert_outcome == "already_moved_on":
  8212. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  8213. # other path) already moved the item past 'printing', don't run the
  8214. # MQTT session-recovery logic below — a forced reconnect on a healthy
  8215. # session breaks ongoing prints on the same printer.
  8216. return
  8217. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  8218. if revert_outcome == "command_rejected":
  8219. logger.error(
  8220. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  8221. "failed) — the print command was rejected, not lost. Failing the item "
  8222. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  8223. queue_item_id,
  8224. printer_id,
  8225. HMS_MQTT_VERIFY_FAILED,
  8226. )
  8227. await scheduler._notify_dispatch_gave_up(
  8228. queue_item_id,
  8229. printer_id,
  8230. created_by_id,
  8231. reason="Printer rejected the print command (MQTT command verification failed)",
  8232. )
  8233. # Same reasoning as the landed_on_subtask path below: the file is on
  8234. # the printer and a forced reconnect would only add 0500_4003 to a
  8235. # problem that has nothing to do with the MQTT session (#1150).
  8236. return
  8237. if revert_outcome == "gave_up":
  8238. logger.error(
  8239. "Queue item %s: printer %d never started the print after %d dispatch "
  8240. "attempts (last one waited %.0fs) — marking the item failed instead of "
  8241. "re-uploading it again (#2555)",
  8242. queue_item_id,
  8243. printer_id,
  8244. DISPATCH_MAX_ATTEMPTS,
  8245. total_timeout,
  8246. )
  8247. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  8248. elif revert_outcome == "reverted":
  8249. if landed_on_subtask:
  8250. logger.warning(
  8251. "Queue item %s: printer %d accepted project_file (subtask_id "
  8252. "advanced) but never transitioned to an active state within "
  8253. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  8254. "for retry (#1678)",
  8255. queue_item_id,
  8256. printer_id,
  8257. total_timeout,
  8258. )
  8259. else:
  8260. logger.warning(
  8261. "Queue item %s: printer %d did not respond to print command within "
  8262. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  8263. "for retry (#967)",
  8264. queue_item_id,
  8265. printer_id,
  8266. timeout,
  8267. pre_state,
  8268. pre_subtask_id,
  8269. )
  8270. # Phase B was entered iff subtask_id advanced, which means the
  8271. # project_file landed on the printer. A forced reconnect at this point
  8272. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  8273. # skip the recovery entirely.
  8274. if landed_on_subtask:
  8275. return
  8276. # Phase A timeout path: if the printer's gcode_file changed since
  8277. # pre-dispatch, the project_file command landed and the printer is
  8278. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  8279. # If gcode_file is unchanged, the publish was silently swallowed
  8280. # (#887/#936) and force_reconnect recovery is what we want.
  8281. client = printer_manager.get_client(printer_id)
  8282. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  8283. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  8284. if publish_landed:
  8285. logger.warning(
  8286. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  8287. "received the command and is parsing slowly. Skipping forced "
  8288. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  8289. queue_item_id,
  8290. current_gcode_file,
  8291. pre_gcode_file,
  8292. )
  8293. elif client and hasattr(client, "force_reconnect_stale_session"):
  8294. client.force_reconnect_stale_session(
  8295. f"queue print command unacknowledged after {timeout:.0f}s "
  8296. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  8297. )
  8298. # Global scheduler instance
  8299. scheduler = PrintScheduler()