print_scheduler.py 339 KB

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