print_scheduler.py 323 KB

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